content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
senseiraw = {
"name": "SteelSeries Sensei RAW (Experimental)",
"vendor_id": 0x1038,
"product_id": 0x1369,
"interface_number": 0,
"commands": {
"set_logo_light_effect": {
"description": "Set the logo light effect",
"cli": ["-e", "--logo-light-effect"],
"command": [0x07, 0x01],
"value_type": "choice",
"choices": {
"steady": 0x01,
"breath": 0x03,
"off": 0x05,
0: 0x00,
1: 0x01,
2: 0x02,
3: 0x03,
4: 0x04,
5: 0x05,
},
"default": "steady",
},
},
}
|
senseiraw = {'name': 'SteelSeries Sensei RAW (Experimental)', 'vendor_id': 4152, 'product_id': 4969, 'interface_number': 0, 'commands': {'set_logo_light_effect': {'description': 'Set the logo light effect', 'cli': ['-e', '--logo-light-effect'], 'command': [7, 1], 'value_type': 'choice', 'choices': {'steady': 1, 'breath': 3, 'off': 5, 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5}, 'default': 'steady'}}}
|
def ordering_fries():
print("Can I have some fried potatoes please?")
def countries_papagias_preferes():
print("Albania-Bulgaria-Romania...!")
|
def ordering_fries():
print('Can I have some fried potatoes please?')
def countries_papagias_preferes():
print('Albania-Bulgaria-Romania...!')
|
'''
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
4. get_next and set_function is again similar to the data function ; it would be to get and set the next node value respectively.
5. has_next fucntion returns a Boolean whether the node has a next pointer or not
2. Linked List class with operations:
1. init function to initilise the nodes
2. get_size to return the size of the Linked List
3. add function to add a node
4. remove function to remove a node
5. print_list to print the linked list
6. sort to sort the linked list
7. find function to find a item in a linked list
'''
class Node(object):
def __init__(self, data, nextNode=None):
self.data = data
self.nextNode = nextNode
def get_next(self):
''' get the next node value'''
return self.nextNode
def set_next(self, nextNode):
''' point the node to next node'''
self.nextNode = nextNode
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def has_next(self):
if self.nextNode == None:
return False
else:
return True
class LinkedList(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size(self):
return f"Size of the Linked List is : {self.size}"
def add(self, data):
newNode = Node(data, self.root)
self.root = newNode
self.size += 1
def remove(self, data):
r_node = self.root
prev_node = None
while r_node:
if r_node.get_data() == data:
if prev_node:
prev_node.set_next(r_node.get_next())
else:
self.root = r_node.get_next()
self.size -= 1
return True
else:
prev_node = r_node
r_node = r_node.get_next()
return False # item not found
def find(self, data):
find_data = self.root
while find_data:
if find_data.get_data() == data:
return f"Data found {data}"
elif find_data.get_next() == None:
return False # item not in list
else:
find_data = find_data.get_next()
return None
def print_list(self):
pass
def sort_list():
pass
linked = LinkedList()
linked.add(4)
linked.add(5)
linked.add(7)
linked.add(1)
print(linked.get_size())
print(str(linked.find(5)))
linked.add(9)
linked.add(0)
print(linked.get_size())
print(linked.find(0))
print(linked.remove(4))
print(linked.get_size())
print(linked.find(4))
|
"""
Linked List has 2 parts : A node that stores the data and a pointer to the next Node.
So it is handled in 2 classes:
1. Node class with operations:
1. init function to get the data and next node value
2. get_data function to get the data of the node
3. set_data function to set the data of the node
4. get_next and set_function is again similar to the data function ; it would be to get and set the next node value respectively.
5. has_next fucntion returns a Boolean whether the node has a next pointer or not
2. Linked List class with operations:
1. init function to initilise the nodes
2. get_size to return the size of the Linked List
3. add function to add a node
4. remove function to remove a node
5. print_list to print the linked list
6. sort to sort the linked list
7. find function to find a item in a linked list
"""
class Node(object):
def __init__(self, data, nextNode=None):
self.data = data
self.nextNode = nextNode
def get_next(self):
""" get the next node value"""
return self.nextNode
def set_next(self, nextNode):
""" point the node to next node"""
self.nextNode = nextNode
def get_data(self):
return self.data
def set_data(self, data):
self.data = data
def has_next(self):
if self.nextNode == None:
return False
else:
return True
class Linkedlist(object):
def __init__(self, r=None):
self.root = r
self.size = 0
def get_size(self):
return f'Size of the Linked List is : {self.size}'
def add(self, data):
new_node = node(data, self.root)
self.root = newNode
self.size += 1
def remove(self, data):
r_node = self.root
prev_node = None
while r_node:
if r_node.get_data() == data:
if prev_node:
prev_node.set_next(r_node.get_next())
else:
self.root = r_node.get_next()
self.size -= 1
return True
else:
prev_node = r_node
r_node = r_node.get_next()
return False
def find(self, data):
find_data = self.root
while find_data:
if find_data.get_data() == data:
return f'Data found {data}'
elif find_data.get_next() == None:
return False
else:
find_data = find_data.get_next()
return None
def print_list(self):
pass
def sort_list():
pass
linked = linked_list()
linked.add(4)
linked.add(5)
linked.add(7)
linked.add(1)
print(linked.get_size())
print(str(linked.find(5)))
linked.add(9)
linked.add(0)
print(linked.get_size())
print(linked.find(0))
print(linked.remove(4))
print(linked.get_size())
print(linked.find(4))
|
# This file was generated by wxPython's wscript.
VERSION_STRING = '4.0.7.post2'
MAJOR_VERSION = 4
MINOR_VERSION = 0
RELEASE_NUMBER = 7
BUILD_TYPE = 'release'
VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2')
|
version_string = '4.0.7.post2'
major_version = 4
minor_version = 0
release_number = 7
build_type = 'release'
version = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '.post2')
|
## TASK 1 - here are the expected letter frequencies in the english language - convert them to a byte frequency table
expected_letter_frequencies = {'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.702, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, 'o': 7.507, 'p': 1.929, 'q': 0.095, 'r': 5.987, 's': 6.327, 't': 9.056, 'u': 2.758, 'v': 0.978, 'w': 2.361, 'x': 0.150, 'y': 1.974, 'z': 0.074}
expected_byte_frequencies = {}
for letter, frequency in expected_letter_frequencies.items():
byte = letter.encode('latin1')[0]
expected_byte_frequencies[byte] = frequency
|
expected_letter_frequencies = {'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.702, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, 'o': 7.507, 'p': 1.929, 'q': 0.095, 'r': 5.987, 's': 6.327, 't': 9.056, 'u': 2.758, 'v': 0.978, 'w': 2.361, 'x': 0.15, 'y': 1.974, 'z': 0.074}
expected_byte_frequencies = {}
for (letter, frequency) in expected_letter_frequencies.items():
byte = letter.encode('latin1')[0]
expected_byte_frequencies[byte] = frequency
|
def bracket_check(brackets):
'''function for checking a string of brackets'''
o = [ '{', '[', '(' ]
c = [ '}', ']', ')' ]
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else:
print('nah')
bracket_check('8x8y[E(x,y) ! [(P(x) ! P(y)) ! (P(y) ! P(a)]]')
|
def bracket_check(brackets):
"""function for checking a string of brackets"""
o = ['{', '[', '(']
c = ['}', ']', ')']
l = []
check = 0
for i in brackets:
if i in o:
check += 1
if i in c:
check -= 1
if check == 0:
print('yep')
else:
print('nah')
bracket_check('8x8y[E(x,y) ! [(P(x) ! P(y)) ! (P(y) ! P(a)]]')
|
class Utils:
@staticmethod
def fastModuloPow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = (num ** 2) % modulo
pow = pow // 2
else:
result = (num * result) % modulo
pow -= 1
return result
|
class Utils:
@staticmethod
def fast_modulo_pow(num: int, pow: int, modulo: int) -> int:
result = 1
while pow:
if pow % 2 == 0:
num = num ** 2 % modulo
pow = pow // 2
else:
result = num * result % modulo
pow -= 1
return result
|
# https://leetcode.com/problems/satisfiability-of-equality-equations
class UnionFind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
return par
def unite(self, x, y):
x, y = self.find_par(x), self.find_par(y)
if x == y:
return
if x < y:
self.node2par[y] = x
else:
self.node2par[x] = y
class Solution:
def equationsPossible(self, equations):
uf = UnionFind()
neqs = []
for eq in equations:
if eq[1] == "=":
uf.unite(eq[0], eq[-1])
else:
neqs.append(eq)
for neq in neqs:
if uf.find_par(neq[0]) == uf.find_par(neq[-1]):
return False
return True
|
class Unionfind:
def __init__(self):
self.node2par = {chr(i + 97): chr(i + 97) for i in range(26)}
def find_par(self, x):
if self.node2par[x] == x:
return x
par = self.find_par(self.node2par[x])
return par
def unite(self, x, y):
(x, y) = (self.find_par(x), self.find_par(y))
if x == y:
return
if x < y:
self.node2par[y] = x
else:
self.node2par[x] = y
class Solution:
def equations_possible(self, equations):
uf = union_find()
neqs = []
for eq in equations:
if eq[1] == '=':
uf.unite(eq[0], eq[-1])
else:
neqs.append(eq)
for neq in neqs:
if uf.find_par(neq[0]) == uf.find_par(neq[-1]):
return False
return True
|
#
# PySNMP MIB module A3COM-HUAWEI-DHCPSNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-DHCPSNOOP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:04:11 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)
#
hwdot1qVlanIndex, = mibBuilder.importSymbols("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex")
h3cCommon, = mibBuilder.importSymbols("A3COM-HUAWEI-OID-MIB", "h3cCommon")
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Counter64, ModuleIdentity, Unsigned32, ObjectIdentity, Counter32, iso, Bits, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Counter64", "ModuleIdentity", "Unsigned32", "ObjectIdentity", "Counter32", "iso", "Bits", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "IpAddress", "TimeTicks", "Integer32")
TextualConvention, MacAddress, RowStatus, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "RowStatus", "DisplayString", "TruthValue")
h3cDhcpSnoop = ModuleIdentity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36))
if mibBuilder.loadTexts: h3cDhcpSnoop.setLastUpdated('200501140000Z')
if mibBuilder.loadTexts: h3cDhcpSnoop.setOrganization('Huawei-3com Technologies Co.,Ltd.')
if mibBuilder.loadTexts: h3cDhcpSnoop.setContactInfo('Platform Team Beijing Institute Huawei-3com Tech, Inc. Http:\\\\www.huawei-3com.com E-mail:[email protected]')
if mibBuilder.loadTexts: h3cDhcpSnoop.setDescription('The private mib file includes the DHCP Snooping profile.')
h3cDhcpSnoopMibObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1))
h3cDhcpSnoopEnable = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEnable.setDescription('DHCP Snooping status (enable or disable).')
h3cDhcpSnoopTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2), )
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTable.setDescription("The table containing information of DHCP clients listened by DHCP snooping and it's enabled or disabled by setting h3cDhcpSnoopEnable node.")
h3cDhcpSnoopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddressType"), (0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopClientIpAddress"))
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopEntry.setDescription('An entry containing information of DHCP clients.')
h3cDhcpSnoopClientIpAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 1), InetAddressType().clone('ipv4'))
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddressType.setDescription("DHCP clients' IP addresses type (IPv4 or IPv6).")
h3cDhcpSnoopClientIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 2), InetAddress())
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientIpAddress.setDescription("DHCP clients' IP addresses collected by DHCP snooping.")
h3cDhcpSnoopClientMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 3), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientMacAddress.setDescription("DHCP clients' MAC addresses collected by DHCP snooping.")
h3cDhcpSnoopClientProperty = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("static", 1), ("dynamic", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientProperty.setDescription('Method of getting IP addresses collected by DHCP snooping.')
h3cDhcpSnoopClientUnitNum = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopClientUnitNum.setDescription('IRF (Intelligent Resilient Fabric) unit number via whom the clients get their IP addresses. The value 0 means this device does not support IRF.')
h3cDhcpSnoopTrustTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3), )
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustTable.setDescription('A table is used to configure and monitor port trusted status.')
h3cDhcpSnoopTrustEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustEntry.setDescription('An entry containing information about trusted status of ports.')
h3cDhcpSnoopTrustStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("untrusted", 0), ("trusted", 1))).clone('untrusted')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopTrustStatus.setDescription('Trusted status of current port which supports both get and set operation.')
h3cDhcpSnoopVlanTable = MibTable((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4), )
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanTable.setDescription('A table is used to configure and monitor DHCP Snooping status of VLANs.')
h3cDhcpSnoopVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1), ).setIndexNames((0, "A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopVlanIndex"))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEntry.setDescription('The entry information about h3cDhcpSnoopVlanTable.')
h3cDhcpSnoopVlanIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)))
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanIndex.setDescription('Current VLAN index.')
h3cDhcpSnoopVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopVlanEnable.setDescription('DHCP Snooping status of current VLAN.')
h3cDhcpSnoopTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2))
h3cDhcpSnoopTrapsPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0))
h3cDhcpSnoopTrapsObject = MibIdentifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1))
h3cDhcpSnoopSpoofServerMac = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 1), MacAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerMac.setDescription('MAC address of the spoofing server and it is derived from link-layer header of offer packet. If the offer packet is relayed by dhcp relay entity, it may be the MAC address of relay entity. ')
h3cDhcpSnoopSpoofServerIP = MibScalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 2), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerIP.setDescription("IP address of the spoofing server and it is derived from IP header of offer packet. A tricksy host may send offer packet use other host's address, so this address can not always be trust. ")
h3cDhcpSnoopSpoofServerDetected = NotificationType((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0, 1)).setObjects(("IF-MIB", "ifIndex"), ("A3COM-HUAWEI-LswVLAN-MIB", "hwdot1qVlanIndex"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerMac"), ("A3COM-HUAWEI-DHCPSNOOP-MIB", "h3cDhcpSnoopSpoofServerIP"))
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setStatus('current')
if mibBuilder.loadTexts: h3cDhcpSnoopSpoofServerDetected.setDescription('To detect unauthorized DHCP servers on a network, the DHCP snooping device sends DHCP-DISCOVER messages through its downstream port (which is connected to the DHCP clients). If any response (DHCP-OFFER message) is received from the downstream port, an unauthorized DHCP server is considered present, and then the device sends a trap. With unauthorized DHCP server detection enabled, the interface sends a DHCP-DISCOVER message to detect unauthorized DHCP servers on the network. If this interface receives a DHCP-OFFER message, the DHCP server which sent it is considered unauthorized. ')
mibBuilder.exportSymbols("A3COM-HUAWEI-DHCPSNOOP-MIB", h3cDhcpSnoopClientProperty=h3cDhcpSnoopClientProperty, h3cDhcpSnoopTraps=h3cDhcpSnoopTraps, h3cDhcpSnoopTrapsObject=h3cDhcpSnoopTrapsObject, h3cDhcpSnoopVlanEnable=h3cDhcpSnoopVlanEnable, h3cDhcpSnoopEnable=h3cDhcpSnoopEnable, h3cDhcpSnoopClientIpAddress=h3cDhcpSnoopClientIpAddress, h3cDhcpSnoopVlanEntry=h3cDhcpSnoopVlanEntry, h3cDhcpSnoopEntry=h3cDhcpSnoopEntry, PYSNMP_MODULE_ID=h3cDhcpSnoop, h3cDhcpSnoopTrapsPrefix=h3cDhcpSnoopTrapsPrefix, h3cDhcpSnoopClientIpAddressType=h3cDhcpSnoopClientIpAddressType, h3cDhcpSnoopSpoofServerMac=h3cDhcpSnoopSpoofServerMac, h3cDhcpSnoopTrustEntry=h3cDhcpSnoopTrustEntry, h3cDhcpSnoopSpoofServerIP=h3cDhcpSnoopSpoofServerIP, h3cDhcpSnoop=h3cDhcpSnoop, h3cDhcpSnoopTrustStatus=h3cDhcpSnoopTrustStatus, h3cDhcpSnoopClientUnitNum=h3cDhcpSnoopClientUnitNum, h3cDhcpSnoopTable=h3cDhcpSnoopTable, h3cDhcpSnoopTrustTable=h3cDhcpSnoopTrustTable, h3cDhcpSnoopSpoofServerDetected=h3cDhcpSnoopSpoofServerDetected, h3cDhcpSnoopVlanIndex=h3cDhcpSnoopVlanIndex, h3cDhcpSnoopClientMacAddress=h3cDhcpSnoopClientMacAddress, h3cDhcpSnoopMibObject=h3cDhcpSnoopMibObject, h3cDhcpSnoopVlanTable=h3cDhcpSnoopVlanTable)
|
(hwdot1q_vlan_index,) = mibBuilder.importSymbols('A3COM-HUAWEI-LswVLAN-MIB', 'hwdot1qVlanIndex')
(h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddress', 'InetAddressType')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(gauge32, counter64, module_identity, unsigned32, object_identity, counter32, iso, bits, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, ip_address, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Counter64', 'ModuleIdentity', 'Unsigned32', 'ObjectIdentity', 'Counter32', 'iso', 'Bits', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'IpAddress', 'TimeTicks', 'Integer32')
(textual_convention, mac_address, row_status, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'MacAddress', 'RowStatus', 'DisplayString', 'TruthValue')
h3c_dhcp_snoop = module_identity((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36))
if mibBuilder.loadTexts:
h3cDhcpSnoop.setLastUpdated('200501140000Z')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setOrganization('Huawei-3com Technologies Co.,Ltd.')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setContactInfo('Platform Team Beijing Institute Huawei-3com Tech, Inc. Http:\\\\www.huawei-3com.com E-mail:[email protected]')
if mibBuilder.loadTexts:
h3cDhcpSnoop.setDescription('The private mib file includes the DHCP Snooping profile.')
h3c_dhcp_snoop_mib_object = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1))
h3c_dhcp_snoop_enable = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopEnable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopEnable.setDescription('DHCP Snooping status (enable or disable).')
h3c_dhcp_snoop_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2))
if mibBuilder.loadTexts:
h3cDhcpSnoopTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTable.setDescription("The table containing information of DHCP clients listened by DHCP snooping and it's enabled or disabled by setting h3cDhcpSnoopEnable node.")
h3c_dhcp_snoop_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1)).setIndexNames((0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopClientIpAddressType'), (0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopClientIpAddress'))
if mibBuilder.loadTexts:
h3cDhcpSnoopEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopEntry.setDescription('An entry containing information of DHCP clients.')
h3c_dhcp_snoop_client_ip_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 1), inet_address_type().clone('ipv4'))
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddressType.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddressType.setDescription("DHCP clients' IP addresses type (IPv4 or IPv6).")
h3c_dhcp_snoop_client_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 2), inet_address())
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddress.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientIpAddress.setDescription("DHCP clients' IP addresses collected by DHCP snooping.")
h3c_dhcp_snoop_client_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 3), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientMacAddress.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientMacAddress.setDescription("DHCP clients' MAC addresses collected by DHCP snooping.")
h3c_dhcp_snoop_client_property = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('static', 1), ('dynamic', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientProperty.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientProperty.setDescription('Method of getting IP addresses collected by DHCP snooping.')
h3c_dhcp_snoop_client_unit_num = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 2, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientUnitNum.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopClientUnitNum.setDescription('IRF (Intelligent Resilient Fabric) unit number via whom the clients get their IP addresses. The value 0 means this device does not support IRF.')
h3c_dhcp_snoop_trust_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3))
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustTable.setDescription('A table is used to configure and monitor port trusted status.')
h3c_dhcp_snoop_trust_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustEntry.setDescription('An entry containing information about trusted status of ports.')
h3c_dhcp_snoop_trust_status = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 3, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('untrusted', 0), ('trusted', 1))).clone('untrusted')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustStatus.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopTrustStatus.setDescription('Trusted status of current port which supports both get and set operation.')
h3c_dhcp_snoop_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanTable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanTable.setDescription('A table is used to configure and monitor DHCP Snooping status of VLANs.')
h3c_dhcp_snoop_vlan_entry = mib_table_row((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1)).setIndexNames((0, 'A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopVlanIndex'))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEntry.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEntry.setDescription('The entry information about h3cDhcpSnoopVlanTable.')
h3c_dhcp_snoop_vlan_index = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647)))
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanIndex.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanIndex.setDescription('Current VLAN index.')
h3c_dhcp_snoop_vlan_enable = mib_table_column((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 1, 4, 1, 2), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEnable.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopVlanEnable.setDescription('DHCP Snooping status of current VLAN.')
h3c_dhcp_snoop_traps = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2))
h3c_dhcp_snoop_traps_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0))
h3c_dhcp_snoop_traps_object = mib_identifier((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1))
h3c_dhcp_snoop_spoof_server_mac = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 1), mac_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerMac.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerMac.setDescription('MAC address of the spoofing server and it is derived from link-layer header of offer packet. If the offer packet is relayed by dhcp relay entity, it may be the MAC address of relay entity. ')
h3c_dhcp_snoop_spoof_server_ip = mib_scalar((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 1, 2), ip_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerIP.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerIP.setDescription("IP address of the spoofing server and it is derived from IP header of offer packet. A tricksy host may send offer packet use other host's address, so this address can not always be trust. ")
h3c_dhcp_snoop_spoof_server_detected = notification_type((1, 3, 6, 1, 4, 1, 43, 45, 1, 10, 2, 36, 2, 0, 1)).setObjects(('IF-MIB', 'ifIndex'), ('A3COM-HUAWEI-LswVLAN-MIB', 'hwdot1qVlanIndex'), ('A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopSpoofServerMac'), ('A3COM-HUAWEI-DHCPSNOOP-MIB', 'h3cDhcpSnoopSpoofServerIP'))
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerDetected.setStatus('current')
if mibBuilder.loadTexts:
h3cDhcpSnoopSpoofServerDetected.setDescription('To detect unauthorized DHCP servers on a network, the DHCP snooping device sends DHCP-DISCOVER messages through its downstream port (which is connected to the DHCP clients). If any response (DHCP-OFFER message) is received from the downstream port, an unauthorized DHCP server is considered present, and then the device sends a trap. With unauthorized DHCP server detection enabled, the interface sends a DHCP-DISCOVER message to detect unauthorized DHCP servers on the network. If this interface receives a DHCP-OFFER message, the DHCP server which sent it is considered unauthorized. ')
mibBuilder.exportSymbols('A3COM-HUAWEI-DHCPSNOOP-MIB', h3cDhcpSnoopClientProperty=h3cDhcpSnoopClientProperty, h3cDhcpSnoopTraps=h3cDhcpSnoopTraps, h3cDhcpSnoopTrapsObject=h3cDhcpSnoopTrapsObject, h3cDhcpSnoopVlanEnable=h3cDhcpSnoopVlanEnable, h3cDhcpSnoopEnable=h3cDhcpSnoopEnable, h3cDhcpSnoopClientIpAddress=h3cDhcpSnoopClientIpAddress, h3cDhcpSnoopVlanEntry=h3cDhcpSnoopVlanEntry, h3cDhcpSnoopEntry=h3cDhcpSnoopEntry, PYSNMP_MODULE_ID=h3cDhcpSnoop, h3cDhcpSnoopTrapsPrefix=h3cDhcpSnoopTrapsPrefix, h3cDhcpSnoopClientIpAddressType=h3cDhcpSnoopClientIpAddressType, h3cDhcpSnoopSpoofServerMac=h3cDhcpSnoopSpoofServerMac, h3cDhcpSnoopTrustEntry=h3cDhcpSnoopTrustEntry, h3cDhcpSnoopSpoofServerIP=h3cDhcpSnoopSpoofServerIP, h3cDhcpSnoop=h3cDhcpSnoop, h3cDhcpSnoopTrustStatus=h3cDhcpSnoopTrustStatus, h3cDhcpSnoopClientUnitNum=h3cDhcpSnoopClientUnitNum, h3cDhcpSnoopTable=h3cDhcpSnoopTable, h3cDhcpSnoopTrustTable=h3cDhcpSnoopTrustTable, h3cDhcpSnoopSpoofServerDetected=h3cDhcpSnoopSpoofServerDetected, h3cDhcpSnoopVlanIndex=h3cDhcpSnoopVlanIndex, h3cDhcpSnoopClientMacAddress=h3cDhcpSnoopClientMacAddress, h3cDhcpSnoopMibObject=h3cDhcpSnoopMibObject, h3cDhcpSnoopVlanTable=h3cDhcpSnoopVlanTable)
|
#Copyright (c) 2020 Jan Kiefer
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
class ChatUsr:
def __init__(self, utfmsg):
self.wob_id = utfmsg.get_int_arg(1)
self.message = utfmsg.get_string_arg(2)
self.type = utfmsg.get_int_list_arg(0)[2]
self.mode = 0 if utfmsg.get_arg_count() <= 3 else utfmsg.get_int_arg(3)
self.overheard = False if utfmsg.get_arg_count() <= 4 else utfmsg.get_boolean_arg(4)
class ChatSrv:
def __init__(self, utfmsg):
self.message = utfmsg.get_string_arg(1)
|
class Chatusr:
def __init__(self, utfmsg):
self.wob_id = utfmsg.get_int_arg(1)
self.message = utfmsg.get_string_arg(2)
self.type = utfmsg.get_int_list_arg(0)[2]
self.mode = 0 if utfmsg.get_arg_count() <= 3 else utfmsg.get_int_arg(3)
self.overheard = False if utfmsg.get_arg_count() <= 4 else utfmsg.get_boolean_arg(4)
class Chatsrv:
def __init__(self, utfmsg):
self.message = utfmsg.get_string_arg(1)
|
ast = int(input("Ingrese numero de asteroides"))
nom =input("Ingrese nombre de asteroides")
print("Los",ast,"asteroides",nom,"caen del cielo")
|
ast = int(input('Ingrese numero de asteroides'))
nom = input('Ingrese nombre de asteroides')
print('Los', ast, 'asteroides', nom, 'caen del cielo')
|
#!/usr/bin/env python
compsys={
'Artisan':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
'Central Office user':{
'db':'file-store',
'objects':['Artisan','Product','Order','Customer'],
},
}
|
compsys = {'Artisan': {'db': 'file-store', 'objects': ['Artisan', 'Product', 'Order', 'Customer']}, 'Central Office user': {'db': 'file-store', 'objects': ['Artisan', 'Product', 'Order', 'Customer']}}
|
def main():
my_integ_loop.getIntegrator( trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == "__main__":
main()
|
def main():
my_integ_loop.getIntegrator(trick.Runge_Kutta_2, 4)
trick.stop(300.0)
if __name__ == '__main__':
main()
|
S_ASK_DOWNLOAD = 0
C_ANSWER_YES = 1
C_ANSWER_NO = 2
S_ASK_UPLOAD = 3
S_ASK_WAIT = 4
S_BEGIN = 5
|
s_ask_download = 0
c_answer_yes = 1
c_answer_no = 2
s_ask_upload = 3
s_ask_wait = 4
s_begin = 5
|
#!/usr/bin/env python3
n = 4
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
b = [0, 1, 2, 3]
# Gauss elim
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
# External stability
print("External stability")
A = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2],
[2, 0.00001, 1, 0.4]]
db = 0.3
da = 0.3
dA = [[da for j in range(n)] for i in range(n)]
b = [db for i in range(n)]
for i in range(n):
for j in range(n):
b[i] -= dA[i][j] * x[j]
print("new b:", b)
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print("A:", A)
print("b:", b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print("x:", x)
|
n = 4
a = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2], [2, 1e-05, 1, 0.4]]
b = [0, 1, 2, 3]
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print('A:', A)
print('b:', b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print('x:', x)
print('External stability')
a = [[0.1, 0.5, 3, 0.25], [1.2, 0.2, 0.25, 0.2], [-1, 0.25, 0.3, 2], [2, 1e-05, 1, 0.4]]
db = 0.3
da = 0.3
d_a = [[da for j in range(n)] for i in range(n)]
b = [db for i in range(n)]
for i in range(n):
for j in range(n):
b[i] -= dA[i][j] * x[j]
print('new b:', b)
for i in range(n):
pivot = A[i][i]
b[i] /= pivot
for j in range(n):
A[i][j] /= pivot
for j in range(i + 1, n):
times = A[j][i]
b[j] -= times * b[i]
for k in range(n):
A[j][k] -= times * A[i][k]
print('A:', A)
print('b:', b)
x = b.copy()
for k in range(n - 1, -1, -1):
s = 0
for j in range(k + 1, n):
s = s + A[k][j] * x[j]
x[k] = (b[k] - s) / A[k][k]
print('x:', x)
|
#Pat McDonald - 8/2/2018
#Exercise 3: Collatz conjecture
#Week 3 of Programming and Scripting
#Inspired by Reddit!: https://www.reddit.com/r/Python/comments/57r6bf/collatz_conjecture_program/?st=jdhil1j5&sh=ba8fd995
n = int(input("Type an integer: "))
print(n)
while n != 1:
if (n % 2 == 0):
#(n / 2) outputs a float , so I tried //
n = n // 2
print(n)
else:
n = (3 * n) + 1
print(n)
|
n = int(input('Type an integer: '))
print(n)
while n != 1:
if n % 2 == 0:
n = n // 2
print(n)
else:
n = 3 * n + 1
print(n)
|
n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0,qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0,n):
menor = 100000
for j in range(0,len(indice)):
temp = abs(i - indice[j])
if(temp < menor):
menor = temp
if menor >= 9:
print("9",end=" ")
else:
print(menor,end=" ")
|
n = int(input())
lista = [int(x) for x in input().split()]
qtde = lista.count(0)
indice = []
for i in range(0, qtde):
indice.append(lista.index(0))
lista[indice[i]] = 2
for i in range(0, n):
menor = 100000
for j in range(0, len(indice)):
temp = abs(i - indice[j])
if temp < menor:
menor = temp
if menor >= 9:
print('9', end=' ')
else:
print(menor, end=' ')
|
N = int(input())
S = str(input())
flag = False
half = (N+1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print("Yes")
else:
print("No")
|
n = int(input())
s = str(input())
flag = False
half = (N + 1) // 2
if S[:half] == S[half:N]:
flag = True
if flag:
print('Yes')
else:
print('No')
|
#!/usr/bin/env python
weight = input("your weight is? ")
height = input("your height is? ")
bmi = float(weight) / ( float(height) ** 2 )
print(f"your bmi: {bmi:.2f}")
if bmi <= 18.5:
print("you are so thin!")
elif bmi <= 25 and bmi > 18.5:
print("well, you are fit.")
elif bmi <= 28 and bmi > 25:
print("it looks you are a little heavy.")
elif bmi <= 32 and bmi > 28:
print("you are fat, what about doing exercise?")
else:
print("i dont want to tell the truth, but could you active? otherwise you may die of you fat")
|
weight = input('your weight is? ')
height = input('your height is? ')
bmi = float(weight) / float(height) ** 2
print(f'your bmi: {bmi:.2f}')
if bmi <= 18.5:
print('you are so thin!')
elif bmi <= 25 and bmi > 18.5:
print('well, you are fit.')
elif bmi <= 28 and bmi > 25:
print('it looks you are a little heavy.')
elif bmi <= 32 and bmi > 28:
print('you are fat, what about doing exercise?')
else:
print('i dont want to tell the truth, but could you active? otherwise you may die of you fat')
|
#!/usr/bin/env conda-execute
# conda execute
# env:
# - python ==3.5
# - conda-build
# - pygithub >=1.29
# - pyyaml
# - requests
# - setuptools
# - tqdm
# channels:
# - conda-forge
# run_with: python
# TODO take package or list of packages
# TODO take github url or github urls
# TODO If user doesn't have a fork of conda-forge create one
# TODO if user doesn't have a branch for this package, create one
# TODO run conda smithy pypi package
# TODO If successful, parse generated meta.yaml
# TODO Drop any meta.yaml build reqs
# TODO Drop any test reqs
# TODO Add sections to bring in line with the standard template
# TODO Add variable to bring in line with the standard template
# TODO change the setup script based on whether or not setuptools is required
# TODO deal with license file
# TODO commit the modified meta.yaml to user/staged-recipes:branch
# TODO submit pull request to conda-forge/staged-recipes:master as a new recipe.
def main():
return
if __init__ == "__main__":
main()
|
def main():
return
if __init__ == '__main__':
main()
|
#! env\bin\python
# Ryan Simmons
# Coffee Machine Project
class CoffeeMachine:
# the values in supplies refers to 1-1 with this
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink):
# Money is represented as the value taken (negative) there always less than and should not cause an error
for i in range(len(drink)):
if drink[i] > self.supplies[i]:
print(f'Sorry not enough {self.supply_str[i]} !')
break
else:
for i in range(len(drink)):
self.supplies[i] -= drink[i] # Completes the transaction for the drink
print('I have enough resources, making you a coffee!')
def drink_maker(self):
drink = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ")
# Inputs the value for particular drinks into supply_checker()
if drink == '1':
espresso = [250, 0, 16, 1, -4]
self.supply_checker(espresso)
elif drink == '2':
latte = [350, 75, 20, 1, -7]
self.supply_checker(latte)
elif drink == '3':
cappuccino = [200, 100, 12, 1, -6]
self.supply_checker(cappuccino)
else:
return
def filler(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
self.supplies[0] += int(input(f'Write how many ml of {self.supply_str[0]} do you want to add: '))
self.supplies[1] += int(input(f'Write how many ml of {self.supply_str[1]} do you want to add: '))
self.supplies[2] += int(input(f'Write how many grams of {self.supply_str[2]} do you want to add: '))
self.supplies[3] += int(input(f'Write how many {self.supply_str[3]} of coffee do you want to add: '))
def remaining(self):
# supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
print('The coffee machine has:')
for i in range(len(self.supplies)):
print(f'{self.supplies[i]} of {self.supply_str[i]}')
# Only method that user should have to interact with, Like a real cafe!
def barista(self):
while True:
action = input('Write action (buy, fill, take, remaining, exit): ')
if action == 'buy':
self.drink_maker()
elif action == 'fill':
self.filler()
elif action == 'take':
print(f'I gave you ${self.supplies[4]}')
self.supplies[4] = 0
elif action == 'remaining':
self.remaining()
elif action == 'exit':
break
print()
# Debugging
my_supplies = [400, 540, 120, 9, 550]
my_coffee = CoffeeMachine(my_supplies)
my_coffee.barista()
|
class Coffeemachine:
supply_str = ['water', 'milk', 'coffee beans', 'disposable cups', 'money']
def __init__(self, supplies):
self.supplies = supplies
def supply_checker(self, drink):
for i in range(len(drink)):
if drink[i] > self.supplies[i]:
print(f'Sorry not enough {self.supply_str[i]} !')
break
else:
for i in range(len(drink)):
self.supplies[i] -= drink[i]
print('I have enough resources, making you a coffee!')
def drink_maker(self):
drink = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ')
if drink == '1':
espresso = [250, 0, 16, 1, -4]
self.supply_checker(espresso)
elif drink == '2':
latte = [350, 75, 20, 1, -7]
self.supply_checker(latte)
elif drink == '3':
cappuccino = [200, 100, 12, 1, -6]
self.supply_checker(cappuccino)
else:
return
def filler(self):
self.supplies[0] += int(input(f'Write how many ml of {self.supply_str[0]} do you want to add: '))
self.supplies[1] += int(input(f'Write how many ml of {self.supply_str[1]} do you want to add: '))
self.supplies[2] += int(input(f'Write how many grams of {self.supply_str[2]} do you want to add: '))
self.supplies[3] += int(input(f'Write how many {self.supply_str[3]} of coffee do you want to add: '))
def remaining(self):
print('The coffee machine has:')
for i in range(len(self.supplies)):
print(f'{self.supplies[i]} of {self.supply_str[i]}')
def barista(self):
while True:
action = input('Write action (buy, fill, take, remaining, exit): ')
if action == 'buy':
self.drink_maker()
elif action == 'fill':
self.filler()
elif action == 'take':
print(f'I gave you ${self.supplies[4]}')
self.supplies[4] = 0
elif action == 'remaining':
self.remaining()
elif action == 'exit':
break
print()
my_supplies = [400, 540, 120, 9, 550]
my_coffee = coffee_machine(my_supplies)
my_coffee.barista()
|
# Write a program to print the pattern
def pattern(a):
print("Output :")
for i in range(1, a+1):
c = 1
for k in range(a, i, -1):
print(" ", end="")
for j in range(1, 2*i):
if j < i:
print(c, end="")
c += 1
else:
print(c, end="")
c -= 1
print()
a = int(input("Input : "))
pattern(a)
|
def pattern(a):
print('Output :')
for i in range(1, a + 1):
c = 1
for k in range(a, i, -1):
print(' ', end='')
for j in range(1, 2 * i):
if j < i:
print(c, end='')
c += 1
else:
print(c, end='')
c -= 1
print()
a = int(input('Input : '))
pattern(a)
|
# O(n ^ 4)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# ans = 0
# for a in range(n - 3):
# for b in range(a + 1, n - 2):
# for c in range(b + 1, n -1):
# for d in range(c + 1, n):
# if nums[a] + nums[b] + nums[c] == nums[d]:
# ans += 1
# return ans
# O(n ^ 3)
# class Solution:
# def countQuadruplets(self, nums: List[int]) -> int:
# n = len(nums)
# cnt = defaultdict(int)
# ans = 0
# for c in range(n - 2, 1, -1):
# cnt[nums[c + 1]] += 1
# for a in range(c - 1):
# for b in range(a + 1, c):
# ans += cnt[nums[a] + nums[b] + nums[c]]
# return ans
# O(n ^ 2)
class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
ans = 0
for b in range(n - 3, 0, -1):
for d in range(b + 2, n):
cnt[nums[d] - nums[b + 1]] += 1
for a in range(b):
ans += cnt[nums[a] + nums[b]]
return ans
|
class Solution:
def count_quadruplets(self, nums: List[int]) -> int:
n = len(nums)
cnt = defaultdict(int)
ans = 0
for b in range(n - 3, 0, -1):
for d in range(b + 2, n):
cnt[nums[d] - nums[b + 1]] += 1
for a in range(b):
ans += cnt[nums[a] + nums[b]]
return ans
|
# Constants
#
# Device Variables
VAR_BILLINGPERIODDURATION = 'zigbee:BillingPeriodDuration'
VAR_BILLINGPERIODSTART = 'zigbee:BillingPeriodStart'
VAR_BLOCK1PRICE = 'zigbee:Block1Price'
VAR_BLOCK1THRESHOLD = 'zigbee:Block1Threshold'
VAR_BLOCK2PRICE = 'zigbee:Block2Price'
VAR_BLOCK2THRESHOLD = 'zigbee:Block2Threshold'
VAR_BLOCK3PRICE = 'zigbee:Block3Price'
VAR_BLOCK3THRESHOLD = 'zigbee:Block3Threshold'
VAR_BLOCK4PRICE = 'zigbee:Block4Price'
VAR_BLOCK4THRESHOLD = 'zigbee:Block4Threshold'
VAR_BLOCK5PRICE = 'zigbee:Block5Price'
VAR_BLOCK5THRESHOLD = 'zigbee:Block5Threshold'
VAR_BLOCK6PRICE = 'zigbee:Block6Price'
VAR_BLOCK6THRESHOLD = 'zigbee:Block6Threshold'
VAR_BLOCK7PRICE = 'zigbee:Block7Price'
VAR_BLOCK7THRESHOLD = 'zigbee:Block7Threshold'
VAR_BLOCK8PRICE = 'zigbee:Block8Price'
VAR_BLOCK8THRESHOLD = 'zigbee:Block8Threshold'
VAR_BLOCKNPRICE = 'zigbee:Block{}Price'
VAR_BLOCKNTHRESHOLD = 'zigbee:Block{}Threshold'
VAR_BLOCKPERIODCONSUMPTION = 'zigbee:BlockPeriodConsumption'
VAR_BLOCKPERIODDURATION = 'zigbee:BlockPeriodDuration'
VAR_BLOCKPERIODNUMBEROFBLOCKS = 'zigbee:BlockPeriodNumberOfBlocks'
VAR_BLOCKPERIODSTART = 'zigbee:BlockPeriodStart'
VAR_BLOCKTHRESHOLDDIVISOR = 'zigbee:BlockThresholdDivisor'
VAR_BLOCKTHRESHOLDMULTIPLIER = 'zigbee:BlockThresholdMultiplier'
VAR_CURRENCY = 'zigbee:Currency'
VAR_CURRENTSUMMATIONDELIVERED = 'zigbee:CurrentSummationDelivered'
VAR_CURRENTSUMMATIONRECEIVED = 'zigbee:CurrentSummationReceived'
VAR_DIVISOR = 'zigbee:Divisor'
VAR_INSTANTANEOUSDEMAND = 'zigbee:InstantaneousDemand'
VAR_MESSAGE = 'zigbee:Message'
VAR_MESSAGECONFIRMATIONREQUIRED = 'zigbee:MessageConfirmationRequired'
VAR_MESSAGECONFIRMED = 'zigbee:MessageConfirmed'
VAR_MESSAGEDURATIONINMINUTES = 'zigbee:MessageDurationInMinutes'
VAR_MESSAGEID = 'zigbee:MessageId'
VAR_MESSAGEPRIORITY = 'zigbee:MessagePriority'
VAR_MESSAGESTARTTIME = 'zigbee:MessageStartTime'
VAR_MULTIPLIER = 'zigbee:Multiplier'
VAR_PRICE = 'zigbee:Price'
VAR_PRICEDURATION = 'zigbee:PriceDuration'
VAR_PRICESTARTTIME = 'zigbee:PriceStartTime'
VAR_PRICETIER = 'zigbee:PriceTier'
VAR_RATELABEL = 'zigbee:RateLabel'
VAR_TRAILINGDIGITS = 'zigbee:TrailingDigits'
|
var_billingperiodduration = 'zigbee:BillingPeriodDuration'
var_billingperiodstart = 'zigbee:BillingPeriodStart'
var_block1_price = 'zigbee:Block1Price'
var_block1_threshold = 'zigbee:Block1Threshold'
var_block2_price = 'zigbee:Block2Price'
var_block2_threshold = 'zigbee:Block2Threshold'
var_block3_price = 'zigbee:Block3Price'
var_block3_threshold = 'zigbee:Block3Threshold'
var_block4_price = 'zigbee:Block4Price'
var_block4_threshold = 'zigbee:Block4Threshold'
var_block5_price = 'zigbee:Block5Price'
var_block5_threshold = 'zigbee:Block5Threshold'
var_block6_price = 'zigbee:Block6Price'
var_block6_threshold = 'zigbee:Block6Threshold'
var_block7_price = 'zigbee:Block7Price'
var_block7_threshold = 'zigbee:Block7Threshold'
var_block8_price = 'zigbee:Block8Price'
var_block8_threshold = 'zigbee:Block8Threshold'
var_blocknprice = 'zigbee:Block{}Price'
var_blocknthreshold = 'zigbee:Block{}Threshold'
var_blockperiodconsumption = 'zigbee:BlockPeriodConsumption'
var_blockperiodduration = 'zigbee:BlockPeriodDuration'
var_blockperiodnumberofblocks = 'zigbee:BlockPeriodNumberOfBlocks'
var_blockperiodstart = 'zigbee:BlockPeriodStart'
var_blockthresholddivisor = 'zigbee:BlockThresholdDivisor'
var_blockthresholdmultiplier = 'zigbee:BlockThresholdMultiplier'
var_currency = 'zigbee:Currency'
var_currentsummationdelivered = 'zigbee:CurrentSummationDelivered'
var_currentsummationreceived = 'zigbee:CurrentSummationReceived'
var_divisor = 'zigbee:Divisor'
var_instantaneousdemand = 'zigbee:InstantaneousDemand'
var_message = 'zigbee:Message'
var_messageconfirmationrequired = 'zigbee:MessageConfirmationRequired'
var_messageconfirmed = 'zigbee:MessageConfirmed'
var_messagedurationinminutes = 'zigbee:MessageDurationInMinutes'
var_messageid = 'zigbee:MessageId'
var_messagepriority = 'zigbee:MessagePriority'
var_messagestarttime = 'zigbee:MessageStartTime'
var_multiplier = 'zigbee:Multiplier'
var_price = 'zigbee:Price'
var_priceduration = 'zigbee:PriceDuration'
var_pricestarttime = 'zigbee:PriceStartTime'
var_pricetier = 'zigbee:PriceTier'
var_ratelabel = 'zigbee:RateLabel'
var_trailingdigits = 'zigbee:TrailingDigits'
|
def load_file_list(f_list):
lines=[]
for fp in f_list:
with open(fp,'r',encoding='utf-8') as f:
for line in f:
strs=line.strip().split('\t')
lines.append([float(strs[0]),len(lines),strs[1]])
return lines
def build_id_dict(list):
dic={}
for l in list:
dic[len(dic)]=l
return dic
def select_data_by_lm_score(inf_path,fm_path,top_rate=0.1,bottom_rate=0.1,suffix='.filtered_by_lm'):
inf_ori=load_file_list([inf_path])
fm_ori=load_file_list([fm_path])
inf_dic=build_id_dict(inf_ori)
fm_dic=build_id_dict(fm_ori)
inf_sorted=sorted(inf_ori,key=lambda x:x[0],reverse=True)
fm_sorted = sorted(fm_ori, key=lambda x: x[0], reverse=True)
data_num=len(inf_ori)
start_id=int(top_rate*data_num)
end_id=int((1-bottom_rate)*data_num)
fm_top_score=fm_sorted[start_id][0]
fm_bottom_score=fm_sorted[end_id-1][0]
selected_inf=inf_sorted[start_id:end_id]
fw_inf=open(inf_path+suffix,'w',encoding='utf-8')
fw_fm=open(fm_path+suffix,'w',encoding='utf-8')
for item in selected_inf:
fm_item=fm_dic[item[1]]
if fm_item[0]>=fm_bottom_score and fm_item[0]<=fm_top_score:
fw_inf.write(item[2]+'\n')
fw_fm.write(fm_item[2]+'\n')
fw_inf.close()
fw_fm.close()
if __name__=='__main__':
select_data_by_lm_score('../new_exp_fr/add_data/informal.add.rule.bpe.bpe_len_filtered.score',
'../new_exp_fr/add_data/formal.add.rule.bpe.bpe_len_filtered.score')
print('all work has finished')
|
def load_file_list(f_list):
lines = []
for fp in f_list:
with open(fp, 'r', encoding='utf-8') as f:
for line in f:
strs = line.strip().split('\t')
lines.append([float(strs[0]), len(lines), strs[1]])
return lines
def build_id_dict(list):
dic = {}
for l in list:
dic[len(dic)] = l
return dic
def select_data_by_lm_score(inf_path, fm_path, top_rate=0.1, bottom_rate=0.1, suffix='.filtered_by_lm'):
inf_ori = load_file_list([inf_path])
fm_ori = load_file_list([fm_path])
inf_dic = build_id_dict(inf_ori)
fm_dic = build_id_dict(fm_ori)
inf_sorted = sorted(inf_ori, key=lambda x: x[0], reverse=True)
fm_sorted = sorted(fm_ori, key=lambda x: x[0], reverse=True)
data_num = len(inf_ori)
start_id = int(top_rate * data_num)
end_id = int((1 - bottom_rate) * data_num)
fm_top_score = fm_sorted[start_id][0]
fm_bottom_score = fm_sorted[end_id - 1][0]
selected_inf = inf_sorted[start_id:end_id]
fw_inf = open(inf_path + suffix, 'w', encoding='utf-8')
fw_fm = open(fm_path + suffix, 'w', encoding='utf-8')
for item in selected_inf:
fm_item = fm_dic[item[1]]
if fm_item[0] >= fm_bottom_score and fm_item[0] <= fm_top_score:
fw_inf.write(item[2] + '\n')
fw_fm.write(fm_item[2] + '\n')
fw_inf.close()
fw_fm.close()
if __name__ == '__main__':
select_data_by_lm_score('../new_exp_fr/add_data/informal.add.rule.bpe.bpe_len_filtered.score', '../new_exp_fr/add_data/formal.add.rule.bpe.bpe_len_filtered.score')
print('all work has finished')
|
# -------------
# netrecon info
# --------------
__name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: [email protected]'
|
__name__ = 'netrecon'
__version__ = 0.19
__author__ = 'Avery Rozar: [email protected]'
|
def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.aim = self.aim + y
def up(self, y):
self.aim = self.aim - y
def get_multiplied(self):
return self.horizontal * self.depth
if __name__ == "__main__":
submarine = Submarine()
content = read_puzzle("puzzle_input.txt")
for line in content:
commands = line.split(" ")
if commands[0] == "forward":
submarine.forward(int(commands[1]))
elif commands[0] == "down":
submarine.down(int(commands[1]))
elif commands[0] == "up":
submarine.up(int(commands[1]))
print("Final location of the submarine: Horizontal: " + str(submarine.horizontal) + ", Depth: " + str(submarine.depth) +
", Multiplied: " + str(submarine.get_multiplied()))
|
def read_puzzle(path):
with open(path, 'r+') as file:
return file.read().split('\n')
class Submarine:
horizontal = 0
depth = 0
aim = 0
def forward(self, x):
self.horizontal = self.horizontal + x
self.depth = self.depth + self.aim * x
def down(self, y):
self.aim = self.aim + y
def up(self, y):
self.aim = self.aim - y
def get_multiplied(self):
return self.horizontal * self.depth
if __name__ == '__main__':
submarine = submarine()
content = read_puzzle('puzzle_input.txt')
for line in content:
commands = line.split(' ')
if commands[0] == 'forward':
submarine.forward(int(commands[1]))
elif commands[0] == 'down':
submarine.down(int(commands[1]))
elif commands[0] == 'up':
submarine.up(int(commands[1]))
print('Final location of the submarine: Horizontal: ' + str(submarine.horizontal) + ', Depth: ' + str(submarine.depth) + ', Multiplied: ' + str(submarine.get_multiplied()))
|
for t in range(int(input())):
N = int(input())
A = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and not flag:
counter = 1
flag = True
elif i == 1 and counter < 6 :
result = False
break
elif i == 1 and counter >= 6:
counter = 1
else:
counter += 1
if result:
print("YES")
else:
print("NO")
|
for t in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
counter = 0
flag = False
result = True
for i in A:
if i == 1 and (not flag):
counter = 1
flag = True
elif i == 1 and counter < 6:
result = False
break
elif i == 1 and counter >= 6:
counter = 1
else:
counter += 1
if result:
print('YES')
else:
print('NO')
|
# https://leetcode.com/problems/longest-substring-of-all-vowels-in-order/
class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
if 0 <= dic[word[i]] - dic[word[i - 1]] <= 1 and dp[i - 1] > 0:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1 if word[i] == 'a' else 0
res = [v for i, v in enumerate(dp) if word[i] == 'u']
return max([v for i, v in enumerate(dp) if word[i] == 'u'], default=0)
s = Solution()
print(s.longestBeautifulSubstring('uuuuu')) # 0
print(s.longestBeautifulSubstring('aeiaaioaaaaeiiiiouuuooaauuaeiu')) # 13
print(s.longestBeautifulSubstring('aeeeiiiioooauuuaeiou')) # 5
|
class Solution:
def longest_beautiful_substring(self, word: str) -> int:
dp = [0] * len(word)
dic = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
dp[0] = 1 if word[0] == 'a' else 0
for i in range(1, len(word)):
if 0 <= dic[word[i]] - dic[word[i - 1]] <= 1 and dp[i - 1] > 0:
dp[i] = dp[i - 1] + 1
else:
dp[i] = 1 if word[i] == 'a' else 0
res = [v for (i, v) in enumerate(dp) if word[i] == 'u']
return max([v for (i, v) in enumerate(dp) if word[i] == 'u'], default=0)
s = solution()
print(s.longestBeautifulSubstring('uuuuu'))
print(s.longestBeautifulSubstring('aeiaaioaaaaeiiiiouuuooaauuaeiu'))
print(s.longestBeautifulSubstring('aeeeiiiioooauuuaeiou'))
|
# flake8: noqa
def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source()
|
def foo():
def inner():
x = __test_source()
__test_sink(x)
def inner_with_model():
return __test_source()
|
with open("3.txt") as f:
nums = [x for x in f.read().split("\n")]
totals = [0] * len(nums[0])
for n in nums:
for i, c in enumerate(n):
totals[i] += 1 if c == "1" else -1
gamma = int("".join(map(lambda x: "1" if x > 0 else "0", totals)), 2)
epsilon = int("".join(map(lambda x: "1" if x <= 0 else "0", totals)), 2)
print("part 1: {}".format(gamma * epsilon))
nums = sorted(nums)
def process(nums, flip):
for i in range(len(nums[0])):
index = next((j for j, n in enumerate(nums) if n[i] == "1"), len(nums))
cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2
nums = nums[index:] if cmp else nums[:index]
if len(nums) == 1:
return int(nums[0], 2)
print("part 2: {}".format(process(nums, True) * process(nums, False)))
|
with open('3.txt') as f:
nums = [x for x in f.read().split('\n')]
totals = [0] * len(nums[0])
for n in nums:
for (i, c) in enumerate(n):
totals[i] += 1 if c == '1' else -1
gamma = int(''.join(map(lambda x: '1' if x > 0 else '0', totals)), 2)
epsilon = int(''.join(map(lambda x: '1' if x <= 0 else '0', totals)), 2)
print('part 1: {}'.format(gamma * epsilon))
nums = sorted(nums)
def process(nums, flip):
for i in range(len(nums[0])):
index = next((j for (j, n) in enumerate(nums) if n[i] == '1'), len(nums))
cmp = index > len(nums) / 2 if flip else index <= len(nums) / 2
nums = nums[index:] if cmp else nums[:index]
if len(nums) == 1:
return int(nums[0], 2)
print('part 2: {}'.format(process(nums, True) * process(nums, False)))
|
count = 0
count2 = 0
while True:
questions = set()
# 2nd part
everyone = set()
fst = True
try:
person = input()
while person != "":
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(x)
else:
this = set()
for x in person:
this.add(x)
everyone = everyone.intersection(this)
person = input()
fst = False
count += len(questions)
count2 += len(everyone)
except:
break
#print(questions)
count += len(questions)
count2 += len(everyone)
print(count)
print(count2)
|
count = 0
count2 = 0
while True:
questions = set()
everyone = set()
fst = True
try:
person = input()
while person != '':
for x in person:
questions.add(x)
if fst:
for x in person:
everyone.add(x)
else:
this = set()
for x in person:
this.add(x)
everyone = everyone.intersection(this)
person = input()
fst = False
count += len(questions)
count2 += len(everyone)
except:
break
count += len(questions)
count2 += len(everyone)
print(count)
print(count2)
|
class SerializerError(Exception):
def __init__(self, message):
self._message = message
class ValidationError(SerializerError):
pass
class InvalidSerializer(SerializerError):
pass
|
class Serializererror(Exception):
def __init__(self, message):
self._message = message
class Validationerror(SerializerError):
pass
class Invalidserializer(SerializerError):
pass
|
n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row))
# For the record, I feel dumb because it could be
# done with a single line of code
# a = [[abs(i - j) for j in range(n)] for i in range(n)]
|
n = int(input())
a = [['' for j in range(n)] for i in range(n)]
for i in range(n):
f = 0
for j in range(i, n):
a[i][j] = str(f)
f += 1
f = i
for j in range(i):
a[i][j] = str(f)
f -= 1
for row in a:
print(' '.join(row))
|
#!/usr/bin/env python3
# https://abc102.contest.atcoder.jp/tasks/abc102_b
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
|
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
print(a[-1] - a[0])
|
# Spiegelmann (9071005) | In Monster Park Maps
response = sm.sendAskYesNo("Do you want to leave?")
if response:
sm.warpInstanceOut(951000000)
|
response = sm.sendAskYesNo('Do you want to leave?')
if response:
sm.warpInstanceOut(951000000)
|
#!/usr/local/bin/python3
def main():
# Test suite
tests = [
[None, None], # Should throw a TypeError
[-1, None], # Should throw a ValueError
[0, 0],
[9, 9],
[138, 3],
[65536, 7]
]
print('Testing add_digits')
for item in tests:
try:
temp_result = add_digits(item[0])
if temp_result == item[1]:
print('PASSED: add_digits({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
print('\nTesting add_digits_digital_root')
for item in tests:
try:
temp_result = add_digits_digital_root(item[0])
if temp_result == item[1]:
print('PASSED: add_digits_digital_root({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits_digital_root({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
return 0
def add_digits(val):
'''
Sums the digits of an integer until it reduces to one digit
Input: val is non-negative integer
Output: single digit integer
Assumes no other data structure can be used
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
digit_sum = val
while digit_sum > 9:
# Sum the digits in integer
temp_sum = 0
while digit_sum > 0:
temp_sum += digit_sum % 10
digit_sum = digit_sum // 10
digit_sum = temp_sum
return digit_sum
def add_digits_digital_root(val):
'''
This is a digital root, can be solved taking % 9
Time: O(1)
Complexity: O(1)
'''
# Check inputs
if type(val) is not int:
raise TypeError('Input must be an integer')
if val < 0:
raise ValueError('Input must be non-negative')
if val == 0:
return 0
elif val % 9 == 0:
return 9
else:
return val % 9
if __name__ == '__main__':
main()
|
def main():
tests = [[None, None], [-1, None], [0, 0], [9, 9], [138, 3], [65536, 7]]
print('Testing add_digits')
for item in tests:
try:
temp_result = add_digits(item[0])
if temp_result == item[1]:
print('PASSED: add_digits({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
print('\nTesting add_digits_digital_root')
for item in tests:
try:
temp_result = add_digits_digital_root(item[0])
if temp_result == item[1]:
print('PASSED: add_digits_digital_root({}) returned {}'.format(item[0], temp_result))
else:
print('FAILED: add_digits_digital_root({}) returned {}, should have returned {}'.format(item[0], temp_result, item[1]))
except TypeError:
print('PASSED TypeError test')
except ValueError:
print('PASSED ValueError test')
return 0
def add_digits(val):
"""
Sums the digits of an integer until it reduces to one digit
Input: val is non-negative integer
Output: single digit integer
Assumes no other data structure can be used
"""
if type(val) is not int:
raise type_error('Input must be an integer')
if val < 0:
raise value_error('Input must be non-negative')
digit_sum = val
while digit_sum > 9:
temp_sum = 0
while digit_sum > 0:
temp_sum += digit_sum % 10
digit_sum = digit_sum // 10
digit_sum = temp_sum
return digit_sum
def add_digits_digital_root(val):
"""
This is a digital root, can be solved taking % 9
Time: O(1)
Complexity: O(1)
"""
if type(val) is not int:
raise type_error('Input must be an integer')
if val < 0:
raise value_error('Input must be non-negative')
if val == 0:
return 0
elif val % 9 == 0:
return 9
else:
return val % 9
if __name__ == '__main__':
main()
|
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Most digits
#Problem level: 7 kyu
def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))]
|
def find_longest(arr):
return arr[[len(str(x)) for x in arr].index(max([len(str(x)) for x in arr]))]
|
#!/usr/bin/env python3
def main():
# initialize round counter to 0 and answer to blank
round = 0
answer = " "
# set up loop
while round < 3 and (answer.lower() != "brian" and answer.lower() != "shrubbery"):
# increment round
round += 1
answer = input("Finish the movie title, \"Monty Python\'s The Life of ______: ")
# correct answer given
if answer.lower() == 'brian':
print('Correct')
elif answer.lower() == "shrubbery":
print("You gave the super secret answer")
# reached end of game with no correct answer
elif round==3:
print("Sorry, the answer was Brian.")
# loop back to beginning of while loop
else:
print("Sorry! Try again!")
main()
|
def main():
round = 0
answer = ' '
while round < 3 and (answer.lower() != 'brian' and answer.lower() != 'shrubbery'):
round += 1
answer = input('Finish the movie title, "Monty Python\'s The Life of ______: ')
if answer.lower() == 'brian':
print('Correct')
elif answer.lower() == 'shrubbery':
print('You gave the super secret answer')
elif round == 3:
print('Sorry, the answer was Brian.')
else:
print('Sorry! Try again!')
main()
|
def sentence_maker(phrase):
interrogatives = ("why","how","what")
capitalized = phrase.capitalize()
#startswith function checks whether the string starts with the given values
if phrase.startswith(interrogatives):
return f"{capitalized}?"
else:
return f"{capitalized}."
conversation = []
while True:
userInput = input("Say something: ")
if userInput == "\end":
if conversation.__len__() >= 0:
break
else:
conversation.append(sentence_maker(userInput))
print(" ".join(conversation))
|
def sentence_maker(phrase):
interrogatives = ('why', 'how', 'what')
capitalized = phrase.capitalize()
if phrase.startswith(interrogatives):
return f'{capitalized}?'
else:
return f'{capitalized}.'
conversation = []
while True:
user_input = input('Say something: ')
if userInput == '\\end':
if conversation.__len__() >= 0:
break
else:
conversation.append(sentence_maker(userInput))
print(' '.join(conversation))
|
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
# O(n + m) time | O(1) space
# where 'n' is the length of row and 'm' is the length on column
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < row:
row += 1
else:
return [row, col]
return [-1, -1]
|
def search_in_sorted_matrix(matrix, target):
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] > target:
col -= 1
elif matrix[row][col] < row:
row += 1
else:
return [row, col]
return [-1, -1]
|
def get_variables():
return {
'SPECIAL_FUNC': {'hoge': 'fuga'}
}
|
def get_variables():
return {'SPECIAL_FUNC': {'hoge': 'fuga'}}
|
n=int(input())
numSwaps=0
a=list(map(int, input().strip().split()))
for i in range(n-1):
for j in range(n-i-1):
if (a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
numSwaps+=1
print(f"Array is Sorted in {numSwaps} swaps")
print(f"First Element: {a[j]}")
print(f"Last Element: {a[j-1]}")
|
n = int(input())
num_swaps = 0
a = list(map(int, input().strip().split()))
for i in range(n - 1):
for j in range(n - i - 1):
if a[j] > a[j + 1]:
(a[j], a[j + 1]) = (a[j + 1], a[j])
num_swaps += 1
print(f'Array is Sorted in {numSwaps} swaps')
print(f'First Element: {a[j]}')
print(f'Last Element: {a[j - 1]}')
|
# Has the same id
a = [1, 2, 3]
c = a
print(id(a), id(c))
# Has a different id
b = 42
print(id(b))
b = '42'
print(id(b))
|
a = [1, 2, 3]
c = a
print(id(a), id(c))
b = 42
print(id(b))
b = '42'
print(id(b))
|
class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0. if higher else 1. for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self.scores
def update(self, scores, epoch):
self.present = scores
self.epoch = epoch
self.best = [max(best, score) if self.highers[idx] else min(best, score) for idx, (best, score) in enumerate(zip(self.best, scores))]
self.best_epoch = [epoch if present == best else best_epoch for present, best, best_epoch in zip(self.present, self.best, self.best_epoch)]
saves = [epoch == best_epoch for best_epoch in self.best_epoch]
return saves
def print_present(self):
m_str = '{} : {:.4f}, {} : {:.4f} on ' + self.name
m_list = []
for metric, present in zip(self.metrics, self.present):
m_list.append(metric)
m_list.append(present)
print(m_str.format(*m_list))
def print_best(self):
m_str = 'Best score: {}_{} : {:.4f}, {}_{} : {:.4f} on ' + self.name
m_list = []
for metric, best, best_epoch in zip(self.metrics, self.best, self.best_epoch):
m_list.append(metric)
m_list.append(best_epoch)
m_list.append(best)
print(m_str.format(*m_list))
|
class Score:
def __init__(self, name, loader):
self.name = name
self.metrics = ['F', 'M']
self.highers = [1, 0]
self.scores = [0.0 if higher else 1.0 for higher in self.highers]
self.best = self.scores
self.best_epoch = [0] * len(self.scores)
self.present = self.scores
def update(self, scores, epoch):
self.present = scores
self.epoch = epoch
self.best = [max(best, score) if self.highers[idx] else min(best, score) for (idx, (best, score)) in enumerate(zip(self.best, scores))]
self.best_epoch = [epoch if present == best else best_epoch for (present, best, best_epoch) in zip(self.present, self.best, self.best_epoch)]
saves = [epoch == best_epoch for best_epoch in self.best_epoch]
return saves
def print_present(self):
m_str = '{} : {:.4f}, {} : {:.4f} on ' + self.name
m_list = []
for (metric, present) in zip(self.metrics, self.present):
m_list.append(metric)
m_list.append(present)
print(m_str.format(*m_list))
def print_best(self):
m_str = 'Best score: {}_{} : {:.4f}, {}_{} : {:.4f} on ' + self.name
m_list = []
for (metric, best, best_epoch) in zip(self.metrics, self.best, self.best_epoch):
m_list.append(metric)
m_list.append(best_epoch)
m_list.append(best)
print(m_str.format(*m_list))
|
mysql = {
'user': 'scott',
'password': 'password',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True,
}
|
mysql = {'user': 'scott', 'password': 'password', 'host': '127.0.0.1', 'database': 'employees', 'raise_on_warnings': True}
|
# Author: allannozomu
# Runtime: 544 ms
# Memory: 19.8 MB
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if (A[0] < A[-1]):
ordered = sorted(A)
else:
ordered = sorted(A, reverse = True)
return ordered == A
|
class Solution:
def is_monotonic(self, A: List[int]) -> bool:
if A[0] < A[-1]:
ordered = sorted(A)
else:
ordered = sorted(A, reverse=True)
return ordered == A
|
def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[" " for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1,2,2,2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) / 2)
i = 0
x = pivot
y = pivot
while len(slowo):
elem = slowo[:kon[i]]
for j in range(len(elem)):
ukl[y][x] = elem[j]
ii = i
if j == len(elem) - 1 and i != 0:
ii += 1
if ii % 4 == 0:
y += 1
elif ii % 4 == 1:
x += 1
elif ii % 4 == 2:
y -= 1
elif ii % 4 == 3:
x -= 1
slowo = slowo[kon[i]:]
i += 1
wynik = ""
for line in ukl[::-1]:
for l in line:
if l != ' ':
wynik += l
return wynik
|
def szyfr(slowa):
wynik = []
for slowo in slowa:
wynik.append(slimak(slowo))
return wynik
def slimak(slowo):
ukl = [[' ' for _ in range(len(slowo))] for _ in range(len(slowo))]
kon = [1, 2, 2, 2] + [j for j in range(3, 20)] + [j for j in range(3, 20)]
kon.sort()
pivot = int(len(slowo) / 2)
i = 0
x = pivot
y = pivot
while len(slowo):
elem = slowo[:kon[i]]
for j in range(len(elem)):
ukl[y][x] = elem[j]
ii = i
if j == len(elem) - 1 and i != 0:
ii += 1
if ii % 4 == 0:
y += 1
elif ii % 4 == 1:
x += 1
elif ii % 4 == 2:
y -= 1
elif ii % 4 == 3:
x -= 1
slowo = slowo[kon[i]:]
i += 1
wynik = ''
for line in ukl[::-1]:
for l in line:
if l != ' ':
wynik += l
return wynik
|
class Error(Exception):
pass
class InvalidTypeError(Error):
pass
class InvalidArgumentError(Error):
pass
|
class Error(Exception):
pass
class Invalidtypeerror(Error):
pass
class Invalidargumenterror(Error):
pass
|
#********************************************************************
# Filename: FibonacciSearch.py
# Author: Javier Montenegro (https://javiermontenegro.github.io/)
# Copyright:
# Details: This code is the implementation of the fibonacci search algorithm.
#*********************************************************************
def fibonacci_search(arr, val):
fib_N_2 = 0
fib_N_1 = 1
fibNext = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_N_2 = fib_N_1
fib_N_1 = fibNext
fibNext = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
i = min(index + fib_N_2, (length - 1))
if arr[i] < val:
fibNext = fib_N_1
fib_N_1 = fib_N_2
fib_N_2 = fibNext - fib_N_1
index = i
elif arr[i] > val:
fibNext = fib_N_2
fib_N_1 = fib_N_1 - fib_N_2
fib_N_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index + 1
return -1
if __name__ == "__main__":
collection = [1, 6, 7, 0, 0, 0]
print("List numbers: %s\n" % repr(collection))
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = fibonacci_search(collection, target)
if result > 0:
print("%s found at positions: %s" % (target, result))
else:
print("Number not found in list")
|
def fibonacci_search(arr, val):
fib_n_2 = 0
fib_n_1 = 1
fib_next = fib_N_1 + fib_N_2
length = len(arr)
if length == 0:
return 0
while fibNext < len(arr):
fib_n_2 = fib_N_1
fib_n_1 = fibNext
fib_next = fib_N_1 + fib_N_2
index = -1
while fibNext > 1:
i = min(index + fib_N_2, length - 1)
if arr[i] < val:
fib_next = fib_N_1
fib_n_1 = fib_N_2
fib_n_2 = fibNext - fib_N_1
index = i
elif arr[i] > val:
fib_next = fib_N_2
fib_n_1 = fib_N_1 - fib_N_2
fib_n_2 = fibNext - fib_N_1
else:
return i
if (fib_N_1 and index < length - 1) and arr[index + 1] == val:
return index + 1
return -1
if __name__ == '__main__':
collection = [1, 6, 7, 0, 0, 0]
print('List numbers: %s\n' % repr(collection))
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = fibonacci_search(collection, target)
if result > 0:
print('%s found at positions: %s' % (target, result))
else:
print('Number not found in list')
|
class HostAssignedStorageVolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class HostAssignedStorageVolumesColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
|
class Hostassignedstoragevolumes(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_host_assigned_volumes(idx_name)
class Hostassignedstoragevolumescolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_hosts()
|
def checkBingo(c):
for x in range(5):
if c[(x * 5) + 0] == c[(x * 5) + 1] == c[(x * 5) + 2] == c[(x * 5) + 3] == c[(x * 5) + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
with open(path) as input:
for l in input:
p_input.append(l)
drawing = [int(x) for x in p_input[0].split(",")]
p_input = p_input[2:]
card = 0
cards = [[]]
ticked = [[]]
for l in p_input:
if l == "\n":
card += 1
cards.append([])
ticked.append([])
else:
# print(l[0:2])
cards[card].append(int(l[0:2]))
ticked[card].append(False)
# print(l[3:5])
cards[card].append(int(l[3:5]))
ticked[card].append(False)
# print(l[6:8])
cards[card].append(int(l[6:8]))
ticked[card].append(False)
# print(l[9:11])
cards[card].append(int(l[9:11]))
ticked[card].append(False)
# print(l[12:15])
cards[card].append(int(l[12:15]))
ticked[card].append(False)
cards_won = 0
won_cards = set()
for n in drawing:
for i, x in enumerate(cards):
for j, y in enumerate(x):
if y == n:
ticked[i][j] = True
for i in range(len(cards)):
if i not in won_cards and checkBingo(ticked[i]):
# print(i)
cards_won += 1
won_cards.add(i)
if cards_won == len(cards):
sum_unmarked = 0
for x in range(25):
if not ticked[i][x]:
sum_unmarked += cards[i][x]
# print(n)
return sum_unmarked * n
|
def check_bingo(c):
for x in range(5):
if c[x * 5 + 0] == c[x * 5 + 1] == c[x * 5 + 2] == c[x * 5 + 3] == c[x * 5 + 4] == True:
return True
if c[x + 0] == c[x + 5] == c[x + 10] == c[x + 15] == c[x + 20] == True:
return True
return False
def part2(path):
p_input = []
with open(path) as input:
for l in input:
p_input.append(l)
drawing = [int(x) for x in p_input[0].split(',')]
p_input = p_input[2:]
card = 0
cards = [[]]
ticked = [[]]
for l in p_input:
if l == '\n':
card += 1
cards.append([])
ticked.append([])
else:
cards[card].append(int(l[0:2]))
ticked[card].append(False)
cards[card].append(int(l[3:5]))
ticked[card].append(False)
cards[card].append(int(l[6:8]))
ticked[card].append(False)
cards[card].append(int(l[9:11]))
ticked[card].append(False)
cards[card].append(int(l[12:15]))
ticked[card].append(False)
cards_won = 0
won_cards = set()
for n in drawing:
for (i, x) in enumerate(cards):
for (j, y) in enumerate(x):
if y == n:
ticked[i][j] = True
for i in range(len(cards)):
if i not in won_cards and check_bingo(ticked[i]):
cards_won += 1
won_cards.add(i)
if cards_won == len(cards):
sum_unmarked = 0
for x in range(25):
if not ticked[i][x]:
sum_unmarked += cards[i][x]
return sum_unmarked * n
|
# 207-course-schedule.py
#
# Copyright (C) 2019 Sang-Kil Park <[email protected]>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# Make skeleton vertex graph.
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set() # Visited vertex set for permanent storage
traced = set() # Traced vertex set for temporary storage.
def visit(vertex):
if vertex in visited:
return False
traced.add(vertex)
visited.add(vertex)
if vertex in graph:
for neighbour in graph[vertex]:
if neighbour in traced or visit(neighbour):
return True # cyclic!
traced.remove(vertex)
return False
for v in graph:
if visit(v):
return False
return True
|
class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
graph = {k[1]: [] for k in prerequisites}
for pr in prerequisites:
graph[pr[1]].append(pr[0])
visited = set()
traced = set()
def visit(vertex):
if vertex in visited:
return False
traced.add(vertex)
visited.add(vertex)
if vertex in graph:
for neighbour in graph[vertex]:
if neighbour in traced or visit(neighbour):
return True
traced.remove(vertex)
return False
for v in graph:
if visit(v):
return False
return True
|
def main():
n = int(input("Enter a number: "))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime: print(f"{i} ", end="")
print()
if __name__ == '__main__':
main()
|
def main():
n = int(input('Enter a number: '))
for i in range(3, n + 1):
is_prime = True
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
print(f'{i} ', end='')
print()
if __name__ == '__main__':
main()
|
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, key):
return self._module_dict[key]
def register_module(self, module=None):
if module is None:
raise TypeError('fail to register None in Registry {}'.format(self.name))
module_name = module.__name__
if module_name in self._module_dict:
raise KeyError('{} is already registry in Registry {}'.format(module_name, self.name))
self._module_dict[module_name] = module
return module
DATASETS = Registry('dataset')
BACKBONES = Registry('backbone')
NETS = Registry('nets')
|
class Registry(object):
def __init__(self, name):
super(Registry, self).__init__()
self._name = name
self._module_dict = dict()
@property
def name(self):
return self._name
@property
def module_dict(self):
return self._module_dict
def __len__(self):
return len(self.module_dict)
def get(self, key):
return self._module_dict[key]
def register_module(self, module=None):
if module is None:
raise type_error('fail to register None in Registry {}'.format(self.name))
module_name = module.__name__
if module_name in self._module_dict:
raise key_error('{} is already registry in Registry {}'.format(module_name, self.name))
self._module_dict[module_name] = module
return module
datasets = registry('dataset')
backbones = registry('backbone')
nets = registry('nets')
|
'''
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid
move.
For example, given s = "++++", after one move, it may become one of the
following states:
[
"--++",
"+--+",
"++--"
]
If there is no valid move, return an empty list [].
'''
class Solution(object):
# https://github.com/shiyanhui/Algorithm/blob/master/LeetCode/Python/293%20Flip%20Game.py
def generatePossibleNextMoves(self, s):
res = []
for i in range(len(s)-1):
if s[i] == s[i+1] == '+':
res.append(s[:i] + '--' + s[i+2:])
return res
s = Solution()
print(s.generatePossibleNextMoves('++++'))
|
"""
293. Flip Game
=========
You are playing the following Flip Game with your friend: Given a string that
contains only these two characters: + and -, you and your friend take turns to
flip two consecutive "++" into "--". The game ends when a person can no longer
make a move and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid
move.
For example, given s = "++++", after one move, it may become one of the
following states:
[
"--++",
"+--+",
"++--"
]
If there is no valid move, return an empty list [].
"""
class Solution(object):
def generate_possible_next_moves(self, s):
res = []
for i in range(len(s) - 1):
if s[i] == s[i + 1] == '+':
res.append(s[:i] + '--' + s[i + 2:])
return res
s = solution()
print(s.generatePossibleNextMoves('++++'))
|
test_patterns = '''
Given source text and a list of pattens,
look for matches for each patterns within the
text and print them to stdout'''
# Look for each pattern in the text and print the results.
|
test_patterns = '\nGiven source text and a list of pattens,\nlook for matches for each patterns within the\ntext and print them to stdout'
|
# Source : https://leetcode.com/problems/range-sum-of-bst/
# Author : foxfromworld
# Date : 27/04/2021
# Second attempt (recursive)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_rangeSumBST(root):
if root:
if low <= root.val <= high:
self.retV += root.val
if low < root.val:
sub_rangeSumBST(root.left)
if root.val < high:
sub_rangeSumBST(root.right)
sub_rangeSumBST(root)
return self.retV
# Date : 26/04/2021
# First attempt (iterative)
class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
returnV = 0
stack = [root]
while stack:
current = stack.pop()
if current:
if low <= current.val <= high:
returnV += current.val
if low < current.val:
stack.append(current.left)
if current.val < high:
stack.append(current.right)
return returnV
|
class Solution:
def range_sum_bst(self, root: TreeNode, low: int, high: int) -> int:
self.retV = 0
def sub_range_sum_bst(root):
if root:
if low <= root.val <= high:
self.retV += root.val
if low < root.val:
sub_range_sum_bst(root.left)
if root.val < high:
sub_range_sum_bst(root.right)
sub_range_sum_bst(root)
return self.retV
class Solution:
def range_sum_bst(self, root: TreeNode, low: int, high: int) -> int:
return_v = 0
stack = [root]
while stack:
current = stack.pop()
if current:
if low <= current.val <= high:
return_v += current.val
if low < current.val:
stack.append(current.left)
if current.val < high:
stack.append(current.right)
return returnV
|
class IntegerString:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(self):
my_digits = []
other_digits = []
class SquareTenTree:
def __init__(self):
pass
def get_level_length(self, level: int) -> int:
if 0 == level:
return 10
return 10 ** (2 ** (level - 1))
def is_ten_factor(self, num: int) -> bool:
return num % 10 == 0
def find_level(self, num:int) -> int:
level_num = 0
while num >= 10:
num = num // 10
level_num += 1
return level_num
def find_partitions(self, l, r, dest, subset_count=-1, level=0, num_levels=0):
num_levels += 1
level_finished_flag = 0
while l <= r:
k = 1
size = 10
while (r % size == 0) and (r - size + 1) >= l:
k += 1
size = 10 ** (2 ** (k - 1))
k -= 1
if r == dest:
level = k
if k == 0:
size = 1
else:
size = 10 ** (2 ** (k - 1))
r -= size
print(r)
if k == level:
subset_count += 1
else:
level_finished_flag = 1
break
if l > r:
if level_finished_flag == 1:
num_levels += 1
subset_count += 1
print(num_levels)
print(k, " ", 1)
print(level, " ", subset_count)
else:
subset_count += 1
print(num_levels)
print(k, " ", subset_count)
return
if level_finished_flag == 1:
if subset_count >= 0:
subset_count += 1
self.find_partitions(l, r, dest, 0, k, num_levels)
print(level, " ", subset_count)
else:
self.find_partitions(l, r, dest, 0, k, num_levels-1)
if __name__ == '__main__':
st = SquareTenTree()
l = int(input())
r = int(input())
dest = r
st.find_partitions(l, r, dest)
|
class Integerstring:
def __init__(self) -> None:
self.digits = bytearray([0])
self._length = 0
def __init__(self, digits: bytearray) -> None:
self.digits = digits
self._length = len(self.digits)
@property
def length(self):
return self._length
def add(self):
my_digits = []
other_digits = []
class Squaretentree:
def __init__(self):
pass
def get_level_length(self, level: int) -> int:
if 0 == level:
return 10
return 10 ** 2 ** (level - 1)
def is_ten_factor(self, num: int) -> bool:
return num % 10 == 0
def find_level(self, num: int) -> int:
level_num = 0
while num >= 10:
num = num // 10
level_num += 1
return level_num
def find_partitions(self, l, r, dest, subset_count=-1, level=0, num_levels=0):
num_levels += 1
level_finished_flag = 0
while l <= r:
k = 1
size = 10
while r % size == 0 and r - size + 1 >= l:
k += 1
size = 10 ** 2 ** (k - 1)
k -= 1
if r == dest:
level = k
if k == 0:
size = 1
else:
size = 10 ** 2 ** (k - 1)
r -= size
print(r)
if k == level:
subset_count += 1
else:
level_finished_flag = 1
break
if l > r:
if level_finished_flag == 1:
num_levels += 1
subset_count += 1
print(num_levels)
print(k, ' ', 1)
print(level, ' ', subset_count)
else:
subset_count += 1
print(num_levels)
print(k, ' ', subset_count)
return
if level_finished_flag == 1:
if subset_count >= 0:
subset_count += 1
self.find_partitions(l, r, dest, 0, k, num_levels)
print(level, ' ', subset_count)
else:
self.find_partitions(l, r, dest, 0, k, num_levels - 1)
if __name__ == '__main__':
st = square_ten_tree()
l = int(input())
r = int(input())
dest = r
st.find_partitions(l, r, dest)
|
# format the date in January 1, 2022 form
def format_date(date):
return date.strftime('%B %d, %Y')
# format plural word
def format_plural(total, word):
if total != 1:
return word + 's'
return word
|
def format_date(date):
return date.strftime('%B %d, %Y')
def format_plural(total, word):
if total != 1:
return word + 's'
return word
|
# -*- coding: utf-8 -*-
class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pass
def end_chapter(self, chapter):
pass
def begin_section(self, section, chapter):
pass
def end_section(self, section, chapter):
pass
def visit_talk(self, talk, section, chapter):
pass
|
class Visitor:
def visit(self, manager):
self.begin_visit(manager)
manager.visit(self)
return self.end_visit(manager)
def begin_visit(self, manager):
pass
def end_visit(self, manager):
pass
def begin_chapter(self, chapter):
pass
def end_chapter(self, chapter):
pass
def begin_section(self, section, chapter):
pass
def end_section(self, section, chapter):
pass
def visit_talk(self, talk, section, chapter):
pass
|
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
output=[]
stack=[(root,0)]
prev_depth=0
while(stack):
node, depth = stack.pop(0)
if depth!=prev_depth:
output.append(prev_node.val)
if node.left:
stack.append((node.left, depth+1))
if node.right:
stack.append((node.right, depth+1))
prev_depth=depth
prev_node=node
output.append(prev_node.val)
return output
|
class Solution:
def right_side_view(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
output = []
stack = [(root, 0)]
prev_depth = 0
while stack:
(node, depth) = stack.pop(0)
if depth != prev_depth:
output.append(prev_node.val)
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
prev_depth = depth
prev_node = node
output.append(prev_node.val)
return output
|
_base_ = ["./common_base.py", "./renderer_base.py"]
# -----------------------------------------------------------------------------
# base model cfg for self6d-v2
# -----------------------------------------------------------------------------
refiner_cfg_path = "configs/_base_/self6dpp_refiner_base.py"
MODEL = dict(
DEVICE="cuda",
WEIGHTS="",
REFINER_WEIGHTS="",
PIXEL_MEAN=[0, 0, 0], # to [0,1]
PIXEL_STD=[255.0, 255.0, 255.0],
SELF_TRAIN=False, # whether to do self-supervised training
FREEZE_BN=False, # use frozen_bn for self-supervised training
WITH_REFINER=False, # whether to use refiner
# -----------
LOAD_DETS_TRAIN=False, # NOTE: load detections for self-train
LOAD_DETS_TRAIN_WITH_POSE=False, # load detections with pose_refine as pseudo pose
PSEUDO_POSE_TYPE="pose_refine", # pose_est | pose_refine | pose_init (online inferred by teacher)
LOAD_DETS_TEST=False,
BBOX_CROP_REAL=False, # whether to use bbox_128, for cropped lm
BBOX_CROP_SYN=False,
# -----------
# Model Exponential Moving Average https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
# NOTE: momentum-based mean teacher
EMA=dict(
ENABLED=False,
INIT_CFG=dict(decay=0.999, updates=0), # epoch-based
UPDATE_FREQ=10, # update the mean teacher every n epochs
),
POSE_NET=dict(
NAME="GDRN", # used module file name
# NOTE: for self-supervised training phase, use offline labels should be more accurate
XYZ_ONLINE=False, # rendering xyz online
XYZ_BP=True, # calculate xyz from depth by backprojection
NUM_CLASSES=13,
USE_MTL=False, # uncertainty multi-task weighting, TODO: implement for self loss
INPUT_RES=256,
OUTPUT_RES=64,
## backbone
BACKBONE=dict(
FREEZE=False,
PRETRAINED="timm",
INIT_CFG=dict(
type="timm/resnet34",
pretrained=True,
in_chans=3,
features_only=True,
out_indices=(4,),
),
),
NECK=dict(
ENABLED=False,
FREEZE=False,
LR_MULT=1.0,
INIT_CFG=dict(
type="FPN",
in_channels=[256, 512, 1024, 2048],
out_channels=256,
num_outs=4,
),
),
## geo head: Mask, XYZ, Region
GEO_HEAD=dict(
FREEZE=False,
LR_MULT=1.0,
INIT_CFG=dict(
type="TopDownMaskXyzRegionHead",
in_dim=512, # this is num out channels of backbone conv feature
up_types=("deconv", "bilinear", "bilinear"), # stride 32 to 4
deconv_kernel_size=3,
num_conv_per_block=2,
feat_dim=256,
feat_kernel_size=3,
norm="GN",
num_gn_groups=32,
act="GELU", # relu | lrelu | silu (swish) | gelu | mish
out_kernel_size=1,
out_layer_shared=True,
),
XYZ_BIN=64, # for classification xyz, the last one is bg
XYZ_CLASS_AWARE=False,
MASK_CLASS_AWARE=False,
REGION_CLASS_AWARE=False,
MASK_THR_TEST=0.5,
# for region classification, 0 is bg, [1, num_regions]
# num_regions <= 1: no region classification
NUM_REGIONS=64,
),
## for direct regression
PNP_NET=dict(
FREEZE=False,
TRAIN_R_ONLY=False, # only train fc_r (only valid when FREEZE=False)
LR_MULT=1.0,
# ConvPnPNet | SimplePointPnPNet | PointPnPNet | ResPointPnPNet
INIT_CFG=dict(
type="ConvPnPNet",
norm="GN",
act="relu",
num_gn_groups=32,
drop_prob=0.0, # 0.25
denormalize_by_extent=True,
),
WITH_2D_COORD=False, # using 2D XY coords
COORD_2D_TYPE="abs", # rel | abs
REGION_ATTENTION=False, # region attention
MASK_ATTENTION="none", # none | concat | mul
ROT_TYPE="ego_rot6d", # {allo/ego}_{quat/rot6d/log_quat/lie_vec}
TRANS_TYPE="centroid_z", # trans | centroid_z (SITE) | centroid_z_abs
Z_TYPE="REL", # REL | ABS | LOG | NEG_LOG (only valid for centroid_z)
),
LOSS_CFG=dict(
# xyz loss ----------------------------
XYZ_LOSS_TYPE="L1", # L1 | CE_coor
XYZ_LOSS_MASK_GT="visib", # trunc | visib | obj
XYZ_LW=1.0,
# full mask loss ---------------------------
FULL_MASK_LOSS_TYPE="BCE", # L1 | BCE | CE
FULL_MASK_LW=0.0,
# mask loss ---------------------------
MASK_LOSS_TYPE="L1", # L1 | BCE | CE | RW_BCE | dice
MASK_LOSS_GT="trunc", # trunc | visib | gt
MASK_LW=1.0,
# region loss -------------------------
REGION_LOSS_TYPE="CE", # CE
REGION_LOSS_MASK_GT="visib", # trunc | visib | obj
REGION_LW=1.0,
# point matching loss -----------------
NUM_PM_POINTS=3000,
PM_LOSS_TYPE="L1", # L1 | Smooth_L1
PM_SMOOTH_L1_BETA=1.0,
PM_LOSS_SYM=False, # use symmetric PM loss
PM_NORM_BY_EXTENT=False, # 10. / extent.max(1, keepdim=True)[0]
# if False, the trans loss is in point matching loss
PM_R_ONLY=True, # only do R loss in PM
PM_DISENTANGLE_T=False, # disentangle R/T
PM_DISENTANGLE_Z=False, # disentangle R/xy/z
PM_T_USE_POINTS=True,
PM_LW=1.0,
# rot loss ----------------------------
ROT_LOSS_TYPE="angular", # angular | L2
ROT_LW=0.0,
# centroid loss -----------------------
CENTROID_LOSS_TYPE="L1",
CENTROID_LW=1.0,
# z loss ------------------------------
Z_LOSS_TYPE="L1",
Z_LW=1.0,
# trans loss --------------------------
TRANS_LOSS_TYPE="L1",
TRANS_LOSS_DISENTANGLE=True,
TRANS_LW=0.0,
# bind term loss: R^T@t ---------------
BIND_LOSS_TYPE="L1",
BIND_LW=0.0,
),
SELF_LOSS_CFG=dict(
# LAB space loss ------------------
LAB_NO_L=True,
LAB_LW=0.0,
# MS-SSIM loss --------------------
MS_SSIM_LW=0.0,
# perceptual loss -----------------
# PERCEPT_CFG=
PERCEPT_LW=0.0,
# mask loss (init, ren) -----------------------
MASK_WEIGHT_TYPE="edge_lower", # none | edge_lower | edge_higher
MASK_INIT_REN_LOSS_TYPE="RW_BCE", # L1 | RW_BCE (re-weighted BCE) | dice
MASK_INIT_REN_LW=1.0,
# depth-based geometric loss ------
GEOM_LOSS_TYPE="chamfer", # L1, chamfer
GEOM_LW=0.0, # 100
CHAMFER_CENTER_LW=0.0,
CHAMFER_DIST_THR=0.5,
# refiner-based loss --------------
REFINE_LW=0.0,
# xyz loss (init, ren)
XYZ_INIT_REN_LOSS_TYPE="L1", # L1 | CE_coor (for cls)
XYZ_INIT_REN_LW=0.0,
# xyz loss (init, pred)
XYZ_INIT_PRED_LOSS_TYPE="L1", # L1 | smoothL1
XYZ_INIT_PRED_LW=0.0,
# region loss
REGION_INIT_PRED_LW=0.0,
# losses between init and pred ==========================
# mask loss (init, pred) -----------------------
MASK_TYPE="vis", # vis | full
MASK_INIT_PRED_LOSS_TYPE="RW_BCE", # L1 | RW_BCE (re-weighted BCE)
MASK_INIT_PRED_LW=0.0,
MASK_INIT_PRED_TYPE=("vis",), # ("vis","full",)
# point matching loss using pseudo pose ---------------------------
SELF_PM_CFG=dict(
loss_type="L1",
beta=1.0,
reduction="mean",
loss_weight=0.0, # NOTE: >0 to enable this loss
norm_by_extent=False,
symmetric=True,
disentangle_t=True,
disentangle_z=True,
t_loss_use_points=True,
r_only=False,
),
),
),
# some d2 keys but not used
KEYPOINT_ON=False,
LOAD_PROPOSALS=False,
)
TRAIN = dict(PRINT_FREQ=20, DEBUG_SINGLE_IM=False)
TEST = dict(
EVAL_PERIOD=0,
VIS=False,
TEST_BBOX_TYPE="est", # gt | est
USE_PNP=False, # use pnp or direct prediction
SAVE_RESULTS_ONLY=False, # turn this on to only save the predicted results
# ransac_pnp | net_iter_pnp (learned pnp init + iter pnp) | net_ransac_pnp (net init + ransac pnp)
# net_ransac_pnp_rot (net_init + ransanc pnp --> net t + pnp R)
PNP_TYPE="ransac_pnp",
PRECISE_BN=dict(ENABLED=False, NUM_ITER=200),
)
|
_base_ = ['./common_base.py', './renderer_base.py']
refiner_cfg_path = 'configs/_base_/self6dpp_refiner_base.py'
model = dict(DEVICE='cuda', WEIGHTS='', REFINER_WEIGHTS='', PIXEL_MEAN=[0, 0, 0], PIXEL_STD=[255.0, 255.0, 255.0], SELF_TRAIN=False, FREEZE_BN=False, WITH_REFINER=False, LOAD_DETS_TRAIN=False, LOAD_DETS_TRAIN_WITH_POSE=False, PSEUDO_POSE_TYPE='pose_refine', LOAD_DETS_TEST=False, BBOX_CROP_REAL=False, BBOX_CROP_SYN=False, EMA=dict(ENABLED=False, INIT_CFG=dict(decay=0.999, updates=0), UPDATE_FREQ=10), POSE_NET=dict(NAME='GDRN', XYZ_ONLINE=False, XYZ_BP=True, NUM_CLASSES=13, USE_MTL=False, INPUT_RES=256, OUTPUT_RES=64, BACKBONE=dict(FREEZE=False, PRETRAINED='timm', INIT_CFG=dict(type='timm/resnet34', pretrained=True, in_chans=3, features_only=True, out_indices=(4,))), NECK=dict(ENABLED=False, FREEZE=False, LR_MULT=1.0, INIT_CFG=dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=4)), GEO_HEAD=dict(FREEZE=False, LR_MULT=1.0, INIT_CFG=dict(type='TopDownMaskXyzRegionHead', in_dim=512, up_types=('deconv', 'bilinear', 'bilinear'), deconv_kernel_size=3, num_conv_per_block=2, feat_dim=256, feat_kernel_size=3, norm='GN', num_gn_groups=32, act='GELU', out_kernel_size=1, out_layer_shared=True), XYZ_BIN=64, XYZ_CLASS_AWARE=False, MASK_CLASS_AWARE=False, REGION_CLASS_AWARE=False, MASK_THR_TEST=0.5, NUM_REGIONS=64), PNP_NET=dict(FREEZE=False, TRAIN_R_ONLY=False, LR_MULT=1.0, INIT_CFG=dict(type='ConvPnPNet', norm='GN', act='relu', num_gn_groups=32, drop_prob=0.0, denormalize_by_extent=True), WITH_2D_COORD=False, COORD_2D_TYPE='abs', REGION_ATTENTION=False, MASK_ATTENTION='none', ROT_TYPE='ego_rot6d', TRANS_TYPE='centroid_z', Z_TYPE='REL'), LOSS_CFG=dict(XYZ_LOSS_TYPE='L1', XYZ_LOSS_MASK_GT='visib', XYZ_LW=1.0, FULL_MASK_LOSS_TYPE='BCE', FULL_MASK_LW=0.0, MASK_LOSS_TYPE='L1', MASK_LOSS_GT='trunc', MASK_LW=1.0, REGION_LOSS_TYPE='CE', REGION_LOSS_MASK_GT='visib', REGION_LW=1.0, NUM_PM_POINTS=3000, PM_LOSS_TYPE='L1', PM_SMOOTH_L1_BETA=1.0, PM_LOSS_SYM=False, PM_NORM_BY_EXTENT=False, PM_R_ONLY=True, PM_DISENTANGLE_T=False, PM_DISENTANGLE_Z=False, PM_T_USE_POINTS=True, PM_LW=1.0, ROT_LOSS_TYPE='angular', ROT_LW=0.0, CENTROID_LOSS_TYPE='L1', CENTROID_LW=1.0, Z_LOSS_TYPE='L1', Z_LW=1.0, TRANS_LOSS_TYPE='L1', TRANS_LOSS_DISENTANGLE=True, TRANS_LW=0.0, BIND_LOSS_TYPE='L1', BIND_LW=0.0), SELF_LOSS_CFG=dict(LAB_NO_L=True, LAB_LW=0.0, MS_SSIM_LW=0.0, PERCEPT_LW=0.0, MASK_WEIGHT_TYPE='edge_lower', MASK_INIT_REN_LOSS_TYPE='RW_BCE', MASK_INIT_REN_LW=1.0, GEOM_LOSS_TYPE='chamfer', GEOM_LW=0.0, CHAMFER_CENTER_LW=0.0, CHAMFER_DIST_THR=0.5, REFINE_LW=0.0, XYZ_INIT_REN_LOSS_TYPE='L1', XYZ_INIT_REN_LW=0.0, XYZ_INIT_PRED_LOSS_TYPE='L1', XYZ_INIT_PRED_LW=0.0, REGION_INIT_PRED_LW=0.0, MASK_TYPE='vis', MASK_INIT_PRED_LOSS_TYPE='RW_BCE', MASK_INIT_PRED_LW=0.0, MASK_INIT_PRED_TYPE=('vis',), SELF_PM_CFG=dict(loss_type='L1', beta=1.0, reduction='mean', loss_weight=0.0, norm_by_extent=False, symmetric=True, disentangle_t=True, disentangle_z=True, t_loss_use_points=True, r_only=False))), KEYPOINT_ON=False, LOAD_PROPOSALS=False)
train = dict(PRINT_FREQ=20, DEBUG_SINGLE_IM=False)
test = dict(EVAL_PERIOD=0, VIS=False, TEST_BBOX_TYPE='est', USE_PNP=False, SAVE_RESULTS_ONLY=False, PNP_TYPE='ransac_pnp', PRECISE_BN=dict(ENABLED=False, NUM_ITER=200))
|
#
# PySNMP MIB module RADLAN-SOCKET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-SOCKET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:49:20 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
rnd, = mibBuilder.importSymbols("RADLAN-MIB", "rnd")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, NotificationType, TimeTicks, ObjectIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, ModuleIdentity, Gauge32, Counter64, Unsigned32, IpAddress, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "NotificationType", "TimeTicks", "ObjectIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "ModuleIdentity", "Gauge32", "Counter64", "Unsigned32", "IpAddress", "iso", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
rlSocket = ModuleIdentity((1, 3, 6, 1, 4, 1, 89, 85))
rlSocket.setRevisions(('2007-01-02 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rlSocket.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts: rlSocket.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts: rlSocket.setOrganization('Radlan - a MARVELL company. Marvell Semiconductor, Inc.')
if mibBuilder.loadTexts: rlSocket.setContactInfo('www.marvell.com')
if mibBuilder.loadTexts: rlSocket.setDescription('This private MIB module defines socket private MIBs.')
rlSocketMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 89, 85, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketMibVersion.setStatus('current')
if mibBuilder.loadTexts: rlSocketMibVersion.setDescription("MIB's version, the current version is 1.")
rlSocketTable = MibTable((1, 3, 6, 1, 4, 1, 89, 85, 2), )
if mibBuilder.loadTexts: rlSocketTable.setStatus('current')
if mibBuilder.loadTexts: rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.')
rlSocketEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 85, 2, 1), ).setIndexNames((0, "RADLAN-SOCKET-MIB", "rlSocketId"))
if mibBuilder.loadTexts: rlSocketEntry.setStatus('current')
if mibBuilder.loadTexts: rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.')
rlSocketId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketId.setStatus('current')
if mibBuilder.loadTexts: rlSocketId.setDescription('The value of the id of the socket. ')
rlSocketType = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("stream", 1), ("dgram", 2), ("raw", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketType.setStatus('current')
if mibBuilder.loadTexts: rlSocketType.setDescription('Specifies the type of the socket. ')
rlSocketState = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("connected", 1), ("notConnected", 2), ("recvClosed", 3), ("sendClosed", 4), ("closed", 5), ("peerClosed", 6), ("sendRecvClosed", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketState.setStatus('current')
if mibBuilder.loadTexts: rlSocketState.setDescription('Specifies the state in which the socket is in. ')
rlSocketBlockMode = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("blocking", 1), ("nonBlocking", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketBlockMode.setStatus('current')
if mibBuilder.loadTexts: rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ')
rlSocketUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 5), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSocketUpTime.setStatus('current')
if mibBuilder.loadTexts: rlSocketUpTime.setDescription('The time elapsed since this socket was created.')
mibBuilder.exportSymbols("RADLAN-SOCKET-MIB", rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, PYSNMP_MODULE_ID=rlSocket, rlSocketId=rlSocketId, rlSocketType=rlSocketType, rlSocket=rlSocket, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketBlockMode=rlSocketBlockMode, rlSocketMibVersion=rlSocketMibVersion)
|
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint')
(rnd,) = mibBuilder.importSymbols('RADLAN-MIB', 'rnd')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, notification_type, time_ticks, object_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, module_identity, gauge32, counter64, unsigned32, ip_address, iso, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'NotificationType', 'TimeTicks', 'ObjectIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'ModuleIdentity', 'Gauge32', 'Counter64', 'Unsigned32', 'IpAddress', 'iso', 'Counter32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
rl_socket = module_identity((1, 3, 6, 1, 4, 1, 89, 85))
rlSocket.setRevisions(('2007-01-02 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
rlSocket.setRevisionsDescriptions(('Initial revision.',))
if mibBuilder.loadTexts:
rlSocket.setLastUpdated('200701020000Z')
if mibBuilder.loadTexts:
rlSocket.setOrganization('Radlan - a MARVELL company. Marvell Semiconductor, Inc.')
if mibBuilder.loadTexts:
rlSocket.setContactInfo('www.marvell.com')
if mibBuilder.loadTexts:
rlSocket.setDescription('This private MIB module defines socket private MIBs.')
rl_socket_mib_version = mib_scalar((1, 3, 6, 1, 4, 1, 89, 85, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketMibVersion.setStatus('current')
if mibBuilder.loadTexts:
rlSocketMibVersion.setDescription("MIB's version, the current version is 1.")
rl_socket_table = mib_table((1, 3, 6, 1, 4, 1, 89, 85, 2))
if mibBuilder.loadTexts:
rlSocketTable.setStatus('current')
if mibBuilder.loadTexts:
rlSocketTable.setDescription('The (conceptual) table listing the sockets which are currently open in the system.')
rl_socket_entry = mib_table_row((1, 3, 6, 1, 4, 1, 89, 85, 2, 1)).setIndexNames((0, 'RADLAN-SOCKET-MIB', 'rlSocketId'))
if mibBuilder.loadTexts:
rlSocketEntry.setStatus('current')
if mibBuilder.loadTexts:
rlSocketEntry.setDescription('An entry (conceptual row) in the SocketTable.')
rl_socket_id = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketId.setStatus('current')
if mibBuilder.loadTexts:
rlSocketId.setDescription('The value of the id of the socket. ')
rl_socket_type = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('stream', 1), ('dgram', 2), ('raw', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketType.setStatus('current')
if mibBuilder.loadTexts:
rlSocketType.setDescription('Specifies the type of the socket. ')
rl_socket_state = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('connected', 1), ('notConnected', 2), ('recvClosed', 3), ('sendClosed', 4), ('closed', 5), ('peerClosed', 6), ('sendRecvClosed', 7)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketState.setStatus('current')
if mibBuilder.loadTexts:
rlSocketState.setDescription('Specifies the state in which the socket is in. ')
rl_socket_block_mode = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('blocking', 1), ('nonBlocking', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketBlockMode.setStatus('current')
if mibBuilder.loadTexts:
rlSocketBlockMode.setDescription('Specifies the blocking mode of the socket. ')
rl_socket_up_time = mib_table_column((1, 3, 6, 1, 4, 1, 89, 85, 2, 1, 5), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlSocketUpTime.setStatus('current')
if mibBuilder.loadTexts:
rlSocketUpTime.setDescription('The time elapsed since this socket was created.')
mibBuilder.exportSymbols('RADLAN-SOCKET-MIB', rlSocketUpTime=rlSocketUpTime, rlSocketTable=rlSocketTable, PYSNMP_MODULE_ID=rlSocket, rlSocketId=rlSocketId, rlSocketType=rlSocketType, rlSocket=rlSocket, rlSocketState=rlSocketState, rlSocketEntry=rlSocketEntry, rlSocketBlockMode=rlSocketBlockMode, rlSocketMibVersion=rlSocketMibVersion)
|
RATING_DATE = 'rating_date'
ANALYSTS_MIN_MEAN_SUCCESS_RATE = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
DAYS_SINCE_ANALYSTS_ALERT = 'DAYS_SINCE_ANALYSTS_ALERT'
QUESTIONABLE_SOURCES = []
EMISSIONS = 'emissions'
|
rating_date = 'rating_date'
analysts_min_mean_success_rate = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE'
days_since_analysts_alert = 'DAYS_SINCE_ANALYSTS_ALERT'
questionable_sources = []
emissions = 'emissions'
|
# Source and destination file names.
test_source = "cyrillic.txt"
test_destination = "xetex-cyrillic.tex"
# Keyword parameters passed to publish_file.
writer_name = "xetex"
# Settings
settings_overrides['language_code'] = 'ru'
# use "smartquotes" transition:
settings_overrides['smart_quotes'] = True
|
test_source = 'cyrillic.txt'
test_destination = 'xetex-cyrillic.tex'
writer_name = 'xetex'
settings_overrides['language_code'] = 'ru'
settings_overrides['smart_quotes'] = True
|
# Leetcode 101. Symmetric Tree
#
# Link: https://leetcode.com/problems/symmetric-tree/
# Difficulty: Easy
# Complexity:
# O(N) time | where N represent the number of nodes in the tree
# O(N) space | where N represent the number of nodes in the tree
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def isMirror(root1, root2):
if not root1 and not root2:
return True
if root1 and root2:
if root1.val == root2.val:
return (isMirror(root1.left, root2.right) and isMirror(root1.right, root2.left))
return False
return isMirror(root, root)
|
class Solution:
def is_symmetric(self, root: Optional[TreeNode]) -> bool:
def is_mirror(root1, root2):
if not root1 and (not root2):
return True
if root1 and root2:
if root1.val == root2.val:
return is_mirror(root1.left, root2.right) and is_mirror(root1.right, root2.left)
return False
return is_mirror(root, root)
|
# !/usr/bin/env python3
# Author: C.K
# Email: [email protected]
# DateTime:2021-07-09 19:40:06
# Description:
class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}','').replace('()','').replace('[]','')
if s == '':
return True
else:
return False
if __name__ == "__main__":
pass
|
class Solution:
def is_valid(self, s: str) -> bool:
n = len(s)
if n == 0:
return True
if n % 2 != 0:
return False
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('{}', '').replace('()', '').replace('[]', '')
if s == '':
return True
else:
return False
if __name__ == '__main__':
pass
|
'''
Numerical validations.
All functions are boolean.
'''
def is_int(string: str) -> bool:
'''
Returns True if the string argument represents a valid integer.
'''
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
'''
Returns True if the string parameter represents a valid float number.
'''
try:
float(string)
except ValueError:
return False
else:
return True
|
"""
Numerical validations.
All functions are boolean.
"""
def is_int(string: str) -> bool:
"""
Returns True if the string argument represents a valid integer.
"""
try:
int(string)
except ValueError:
return False
else:
return True
def is_float(string: str) -> bool:
"""
Returns True if the string parameter represents a valid float number.
"""
try:
float(string)
except ValueError:
return False
else:
return True
|
class DumbCRC32(object):
def __init__(self):
self._remainder = 0xffffffff
self._reversed_polynomial = 0xedb88320
self._final_xor = 0xffffffff
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & (1 << (bit_n & 7))
self._remainder ^= 1 if bit_in != 0 else 0
bit_out = (self._remainder & 1)
self._remainder >>= 1;
if bit_out != 0:
self._remainder ^= self._reversed_polynomial;
def digest(self):
return self._remainder ^ self._final_xor
def hexdigest(self):
return '%08x' % self.digest()
|
class Dumbcrc32(object):
def __init__(self):
self._remainder = 4294967295
self._reversed_polynomial = 3988292384
self._final_xor = 4294967295
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & 1 << (bit_n & 7)
self._remainder ^= 1 if bit_in != 0 else 0
bit_out = self._remainder & 1
self._remainder >>= 1
if bit_out != 0:
self._remainder ^= self._reversed_polynomial
def digest(self):
return self._remainder ^ self._final_xor
def hexdigest(self):
return '%08x' % self.digest()
|
# Leetcode 36. Valid Sudoku
#
# Link: https://leetcode.com/problems/valid-sudoku/
# Difficulty: Medium
# Complexity:
# O(9^2) time
# O(9^2) space
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
width, height = len(board[0]), len(board)
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxs = collections.defaultdict(set)
for row in range(height):
for col in range(width):
if board[row][col] == '.':
continue
if (board[row][col] in rows[row] or
board[row][col] in cols[col] or
board[row][col] in boxs[(col // 3, row // 3)]):
return False
rows[row].add(board[row][col])
cols[col].add(board[row][col])
boxs[(col // 3, row // 3)].add(board[row][col])
return True
|
class Solution:
def is_valid_sudoku(self, board: List[List[str]]) -> bool:
(width, height) = (len(board[0]), len(board))
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxs = collections.defaultdict(set)
for row in range(height):
for col in range(width):
if board[row][col] == '.':
continue
if board[row][col] in rows[row] or board[row][col] in cols[col] or board[row][col] in boxs[col // 3, row // 3]:
return False
rows[row].add(board[row][col])
cols[col].add(board[row][col])
boxs[col // 3, row // 3].add(board[row][col])
return True
|
filename="data2.txt"
file=open(filename, "r")
rs=file.read()
fs=rs.split(",")
il=[]
for i in fs:
il.append(int(i))
i=0
while i<len(il):
moved=False
if il[i]==1:
il[il[i+3]]=il[il[i+1]]+il[il[i+2]]
moved=True
elif il[i]==2:
il[il[i+3]]=il[il[i+1]]*il[il[i+2]]
moved=True
elif il[i]==99:
break
if moved==True:
i+=4
else:
i+=1
print(il)
|
filename = 'data2.txt'
file = open(filename, 'r')
rs = file.read()
fs = rs.split(',')
il = []
for i in fs:
il.append(int(i))
i = 0
while i < len(il):
moved = False
if il[i] == 1:
il[il[i + 3]] = il[il[i + 1]] + il[il[i + 2]]
moved = True
elif il[i] == 2:
il[il[i + 3]] = il[il[i + 1]] * il[il[i + 2]]
moved = True
elif il[i] == 99:
break
if moved == True:
i += 4
else:
i += 1
print(il)
|
class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body
|
class Post:
def __init__(self, index, title, subtitle, body):
self.id = index
self.title = title
self.subtitle = subtitle
self.body = body
|
# Rwapple -
#Lesson 1: saying hello
# Chapter one of the book.
Print ('Hello, World!')
|
print('Hello, World!')
|
# Write your solution here
word = input("Please type in a word: ")
char = input("Please type in a character: ")
index = word.find(char)
if (char in word and index < len(word)-2):
print(word[index:index+3])
|
word = input('Please type in a word: ')
char = input('Please type in a character: ')
index = word.find(char)
if char in word and index < len(word) - 2:
print(word[index:index + 3])
|
def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != queue.pop():
return "False"
if not queue:
return "True"
else:
return "False"
string = ""
print(string, "-", multi_bracket_validation(string))
|
def multi_bracket_validation(str):
open_brackets = tuple('({[')
close_brackets = tuple(')}]')
map = dict(zip(open_brackets, close_brackets))
queue = []
for i in str:
if i in open_brackets:
queue.append(map[i])
elif i in close_brackets:
if not queue or i != queue.pop():
return 'False'
if not queue:
return 'True'
else:
return 'False'
string = ''
print(string, '-', multi_bracket_validation(string))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_simulation_1.py
# Create Date: 2015-03-02 23:19:56
# Usage: AC_simulation_1.py
# Descripton:
class Solution:
# @return an integer
def romanToInt(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
for i in range(len(s)):
if i > 0 and val[s[i]] > val[s[i - 1]]:
ret += val[s[i]] - 2 * val[s[i - 1]]
else:
ret += val[s[i]]
return ret
|
class Solution:
def roman_to_int(self, s):
val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
for i in range(len(s)):
if i > 0 and val[s[i]] > val[s[i - 1]]:
ret += val[s[i]] - 2 * val[s[i - 1]]
else:
ret += val[s[i]]
return ret
|
__version__ = "0.7.1"
def version():
return __version__
|
__version__ = '0.7.1'
def version():
return __version__
|
lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1])
|
lista = [1, 3, 5, 7]
lista_animal = ['cachorro', 'gato', 'elefante']
print(lista)
print(type(lista))
print(lista_animal[1])
|
# The version number is stored here here so that:
# 1) we don't load dependencies by storing it in the actual project
# 2) we can import it in setup.py for the same reason as 1)
# 3) we can import it into all other modules
__version__ = '0.0.1'
|
__version__ = '0.0.1'
|
class Solution:
def isConvex(self, points):
def direction(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
d, n = 0, len(points)
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if not d: d = a
elif a * d < 0: return False
return True
|
class Solution:
def is_convex(self, points):
def direction(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
(d, n) = (0, len(points))
for i in range(n):
a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n])
if not d:
d = a
elif a * d < 0:
return False
return True
|
#! -*- coding: utf-8 -*-
SIGBITS = 5
RSHIFT = 8 - SIGBITS
MAX_ITERATION = 1000
FRACT_BY_POPULATIONS = 0.75
|
sigbits = 5
rshift = 8 - SIGBITS
max_iteration = 1000
fract_by_populations = 0.75
|
def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) ** 2 + (signal[m + 3] - signal[m + 5]) ** 2)
if a + b + c == 0:
r = 0
else:
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c))
area = sqrt(area)
r.append((2 * area) / (a + b + c))
return r[::lag]
|
def in_radius(signal, lag=6):
n = len(signal) - 6
r = []
for m in range(n):
a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2)
b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2)
c = sqrt((signal[m + 2] - signal[m + 4]) ** 2 + (signal[m + 3] - signal[m + 5]) ** 2)
if a + b + c == 0:
r = 0
else:
s = (a + b + c) / 2
area = s * (s - a) * (s - b) * (s - c)
area = sqrt(area)
r.append(2 * area / (a + b + c))
return r[::lag]
|
# Determine the sign of number
n = float(input("Enter a number: "))
if n > 0:
print("Positive.")
elif n < 0:
print("Negative.")
else:
print("STRAIGHT AWAY ZERROOO.")
|
n = float(input('Enter a number: '))
if n > 0:
print('Positive.')
elif n < 0:
print('Negative.')
else:
print('STRAIGHT AWAY ZERROOO.')
|
# https://codeforces.com/problemset/problem/520/A
n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print("YES") if flag == 0 else print("NO")
else:
print("NO")
|
n = int(input())
s = sorted(set(list(input().upper())))
flag = 0
if len(s) == 26:
for i in range(len(s)):
if chr(65 + i) != s[i]:
flag = 1
break
print('YES') if flag == 0 else print('NO')
else:
print('NO')
|
{
'targets':[
{
'target_name': 'native_module',
'sources': [
'src/native_module.cc',
'src/native.cc'
],
'conditions': [
['OS=="linux"', {
'cflags_cc': [ '-std=c++0x' ]
}]
]
}
]
}
|
{'targets': [{'target_name': 'native_module', 'sources': ['src/native_module.cc', 'src/native.cc'], 'conditions': [['OS=="linux"', {'cflags_cc': ['-std=c++0x']}]]}]}
|
level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94
|
level = 3
name = 'Pacet'
capital = 'Cikitu'
area = 91.94
|
# Function to calculate the mask of a number.
def split(n):
b = []
# Iterating the number by digits.
while n > 0:
# If the digit is lucky digit it is appended to the list.
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
# Return the mask.
return b
# Input the two input values.
x, y = [int(x) for x in input().split()]
# Calculate the mask of 'y'.
a = split(y)
# Iterate for value greater than 'x'.
for i in range(x + 1, 1000000):
# If mask equals output the integer and break the loop.
if split(i) == a:
print(i)
break
|
def split(n):
b = []
while n > 0:
if n % 10 == 4 or n % 10 == 7:
b.append(n % 10)
n //= 10
return b
(x, y) = [int(x) for x in input().split()]
a = split(y)
for i in range(x + 1, 1000000):
if split(i) == a:
print(i)
break
|
## Model parameters
model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
## Training parameters
learning_rate_init = 1e-4
#speakers_per_batch = 64
speakers_per_batch = 128
utterances_per_speaker = 10
|
model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3
learning_rate_init = 0.0001
speakers_per_batch = 128
utterances_per_speaker = 10
|
fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number)
|
fyrst_number = int(input())
second_number = int(input())
third_number = int(input())
if fyrst_number > second_number and fyrst_number > third_number:
print(fyrst_number)
elif second_number > fyrst_number and second_number > third_number:
print(second_number)
else:
print(third_number)
|
s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2))
|
s1 = input().upper()
s2 = input().upper()
def sol(s1, s2):
i = 0
while i < len(s1):
if ord(s1[i]) < ord(s2[i]):
return -1
elif ord(s1[i]) > ord(s2[i]):
return 1
i += 1
return 0
print(sol(s1, s2))
|
lexy_copts = select({
"@bazel_tools//src/conditions:windows": ["/std:c++latest"],
"@bazel_tools//src/conditions:windows_msvc": ["/std:c++latest"],
"//conditions:default": ["-std=c++20"],
})
|
lexy_copts = select({'@bazel_tools//src/conditions:windows': ['/std:c++latest'], '@bazel_tools//src/conditions:windows_msvc': ['/std:c++latest'], '//conditions:default': ['-std=c++20']})
|
class URLInfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ""
result += f"domain: {self.domain}\n"
result += f"subject: {self.subject}\n"
return result
|
class Urlinfo:
def __init__(self, domain, subject):
self.domain = domain
self.subject = subject
def __str__(self):
result = ''
result += f'domain: {self.domain}\n'
result += f'subject: {self.subject}\n'
return result
|
def insertion_sorting(input_array):
for i in range(len(input_array)):
value, position = input_array[i], i
while position > 0 and input_array[position-1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = value
return input_array
if __name__ == '__main__':
user_input = int(input("Enter number of elements in your array: "))
input_array = list(map(int, input("\nEnter the array elements separated by spaces: ").strip().split()))[:user_input]
sorted_array = insertion_sorting(input_array)
print('Here is your sorted array: ' + ','.join(str(number) for number in sorted_array))
|
def insertion_sorting(input_array):
for i in range(len(input_array)):
(value, position) = (input_array[i], i)
while position > 0 and input_array[position - 1] > value:
input_array[position] = input_array[position - 1]
position = position - 1
input_array[position] = value
return input_array
if __name__ == '__main__':
user_input = int(input('Enter number of elements in your array: '))
input_array = list(map(int, input('\nEnter the array elements separated by spaces: ').strip().split()))[:user_input]
sorted_array = insertion_sorting(input_array)
print('Here is your sorted array: ' + ','.join((str(number) for number in sorted_array)))
|
A=[3,5,7]
B=[1,8]
C=[]
counter=0
while len(A)>0 and len(B)>0:
if A[0] <= B[0]:
C[counter]=A[0]
A=A[1:]
counter=counter+1
else:
C[counter]=B[0]
B=B[1:]
counter=counter+1
print(C)
|
a = [3, 5, 7]
b = [1, 8]
c = []
counter = 0
while len(A) > 0 and len(B) > 0:
if A[0] <= B[0]:
C[counter] = A[0]
a = A[1:]
counter = counter + 1
else:
C[counter] = B[0]
b = B[1:]
counter = counter + 1
print(C)
|
name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}')
|
name = str(input('digite seu name: ')).upper()
if name == 'LUZIA':
print(f'{name} good night')
else:
print(f'hello {name}')
|
# All participants who ranked A-th or higher get a T-shirt.
# Additionally, from the participants who ranked between
# (A+1)-th and B-th (inclusive), C participants chosen uniformly at random get a T-shirt.
A, B, C, X = map(int, input().split())
if(X <= A):
print(1.000000000000)
elif(X > A and X <= B):
print(C/(B-A))
else:
print(0.000000000000)
|
(a, b, c, x) = map(int, input().split())
if X <= A:
print(1.0)
elif X > A and X <= B:
print(C / (B - A))
else:
print(0.0)
|
cifar10_config = {
'num_clients': 100,
'model_name': 'Cifar10Net', # Model type
'round': 1000,
'save_period': 200,
'weight_decay': 1e-3,
'batch_size': 50,
'test_batch_size': 256, # no this param in official code
'lr_decay_per_round': 1,
'epochs': 5,
'lr': 0.1,
'print_freq': 5,
'alpha_coef': 1e-2,
'max_norm': 10,
'sample_ratio': 1,
'partition': 'iid',
'dataset': 'cifar10',
}
debug_config = {
'num_clients': 30,
'model_name': 'Cifar10Net', # Model type
'round': 5,
'save_period': 2,
'weight_decay': 1e-3,
'batch_size': 50,
'test_batch_size': 50,
'act_prob': 1,
'lr_decay_per_round': 1,
'epochs': 5,
'lr': 0.1,
'print_freq': 1,
'alpha_coef': 1e-2,
'max_norm': 10,
'sample_ratio': 1,
'partition': 'iid',
'dataset': 'cifar10'
}
# usage: local_params_file_pattern.format(cid=cid)
local_grad_vector_file_pattern = "client_{cid:03d}_local_grad_vector.pt" # accumulated model gradient
clnt_params_file_pattern = "client_{cid:03d}_clnt_params.pt" # latest model param
local_grad_vector_list_file_pattern = "client_rank_{rank:02d}_local_grad_vector_list.pt" # accumulated model gradient for clients in one client process
clnt_params_list_file_pattern = "client_rank_{rank:02d}_clnt_params_list.pt" # latest model param for clients in one client process
|
cifar10_config = {'num_clients': 100, 'model_name': 'Cifar10Net', 'round': 1000, 'save_period': 200, 'weight_decay': 0.001, 'batch_size': 50, 'test_batch_size': 256, 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq': 5, 'alpha_coef': 0.01, 'max_norm': 10, 'sample_ratio': 1, 'partition': 'iid', 'dataset': 'cifar10'}
debug_config = {'num_clients': 30, 'model_name': 'Cifar10Net', 'round': 5, 'save_period': 2, 'weight_decay': 0.001, 'batch_size': 50, 'test_batch_size': 50, 'act_prob': 1, 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq': 1, 'alpha_coef': 0.01, 'max_norm': 10, 'sample_ratio': 1, 'partition': 'iid', 'dataset': 'cifar10'}
local_grad_vector_file_pattern = 'client_{cid:03d}_local_grad_vector.pt'
clnt_params_file_pattern = 'client_{cid:03d}_clnt_params.pt'
local_grad_vector_list_file_pattern = 'client_rank_{rank:02d}_local_grad_vector_list.pt'
clnt_params_list_file_pattern = 'client_rank_{rank:02d}_clnt_params_list.pt'
|
# OpenWeatherMap API Key
weather_api_key = "9cfaeb3dbd4832137f0fb5f0e12ca0f4"
# Google API Key
g_key = "AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A"
|
weather_api_key = '9cfaeb3dbd4832137f0fb5f0e12ca0f4'
g_key = 'AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A'
|
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = Square(88)
print(unittest.area())
unittest2 = Shape()
print((unittest2.area()))
|
class Shape:
def __init__(self):
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
unittest = square(88)
print(unittest.area())
unittest2 = shape()
print(unittest2.area())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.