content
stringlengths 7
1.05M
|
---|
# Time: O(nlogn)
# Space: O(n)
class Solution(object):
def relativeSortArray(self, arr1, arr2):
"""
:type arr1: List[int]
:type arr2: List[int]
:rtype: List[int]
"""
lookup = {v: i for i, v in enumerate(arr2)}
return sorted(arr1, key=lambda i: lookup.get(i, len(arr2)+i))
|
# Objetivo do algorítimo:
# Desenvolver uma lógica que leia a altura e o peso de uma pessoa
# calcule seu imc e mostre seu status de acordo com a tabela:
# Abaixo de 18.5: Abaixo do peso.
# Entre 18.5 e 25: Peso ideal.
# 25 até 30: Sobrepeso.
# 30 até 40: Obesidade
# Acima de 40 obesidade mórbida
# Exercicio pensado por: Gustavo Guanabara / Curso em vídeo
def imc(peso, altura):
imc = peso / (altura*altura)
print(f'O seu imc é: {round(imc, 4)}')
if imc < 18.5:
print("Você está no peso ideal!")
elif imc >= 18.5 and imc < 25:
print("Você está no seu peso ideal")
elif imc >= 25 and imc < 30:
print("Você está com sobrepeso")
elif imc >=30 and imc < 40:
print('Você está com obesidade')
elif imc > 40:
print('Você está com obesidade mórbida')
if __name__ == '__main__':
peso = float(input("Qual é seu peso? (Kg) "))
altura = float(input("QUal é sua altura? (m) "))
imc(peso, altura) |
"""
https://parzibyte.me/blog
"""
print("Hola. Elimina esto y haz que diga 'Mi nombre es Luis'")
print("Hola. Me llamo cambia esto para que diga tu nombre, sin borrar el final. Tengo 23 años")
# Eleva el 2 a la potencia 3, no a la 50
pow(2, 50) |
"""
Criando sua própria versão de loop
"""
for num in range(1, 6):
print(num, end=', ')
print()
def meu_for(iteravel):
it = iter(iteravel)
while True:
try:
print(next(it))
except StopIteration:
break
numeros = range(1, 6)
meu_for(numeros)
|
"""
17263. Sort 마스터 배지훈
작성자: xCrypt0r
언어: Python 3
사용 메모리: 70,552 KB
소요 시간: 204 ms
해결 날짜: 2020년 9월 16일
"""
def main():
input()
print(max(map(int, input().split())))
if __name__ == '__main__':
main()
|
#Horas-minutos e Segundos
valor = int(input())
horas = 0
minutos = 0
segundos = 0
valorA = valor
contador = segundos
while(contador <= valorA):
if contador > 0:
segundos += 1
if segundos >= 60:
minutos += 1
segundos = 0
if minutos >= 60:
horas += 1
minutos = 0
contador+=1
print("{}:{}:{}".format(horas,minutos,segundos))
|
#!/usr/bin/env python
# Author: Omid Mashayekhi <[email protected]>
# ssh -i ~/.ssh/omidm-sing-key-pair-us-west-2.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@<ip>
# US West (Northern California) Region
# EC2_LOCATION = 'us-west-1'
# NIMBUS_AMI = 'ami-50201815'
# UBUNTU_AMI = 'ami-660c3023'
# KEY_NAME = 'omidm-sing-key-pair-us-west-1'
# SECURITY_GROUP = 'nimbus_sg_uswest1'
# EC2 configurations
# US West (Oregon) Region
EC2_LOCATION = 'us-west-2'
UBUNTU_AMI = 'ami-fa9cf1ca'
NIMBUS_AMI = 'ami-4f5c392f'
CONTROLLER_INSTANCE_TYPE = 'c3.4xlarge'
WORKER_INSTANCE_TYPE = 'c3.2xlarge'
PLACEMENT = 'us-west-2a' # None
PLACEMENT_GROUP = 'nimbus-cluster' # None / '*'
SECURITY_GROUP = 'nimbus_sg_uswest2'
KEY_NAME = 'sing-key-pair-us-west-2'
PRIVATE_KEY = '/home/omidm/.ssh/' + KEY_NAME + '.pem'
CONTROLLER_NUM = 1
WORKER_NUM = 100
#Environment variables
DBG_MODE = 'warn' # 'error'
TTIMER_LEVEL = 'l1' # 'l0'
# Controller configurations
ASSIGNER_THREAD_NUM = 8
BATCH_ASSIGN_NUM = 200
COMMAND_BATCH_SIZE = 10000
DEACTIVATE_CONTROLLER_TEMPLATE = False
DEACTIVATE_COMPLEX_MEMOIZATION = False
DEACTIVATE_BINDING_MEMOIZATION = False
DEACTIVATE_WORKER_TEMPLATE = False
DEACTIVATE_MEGA_RCR_JOB = False
DEACTIVATE_CASCADED_BINDING = False
ACTIVATE_LB = False
ACTIVATE_FT = False
LB_PERIOD = 60
FT_PERIOD = 600
FIRST_PORT = 5800
SPLIT_ARGS = str(WORKER_NUM) + ' 1 1' # '2 2 2' '4 4 4'
# Worker configurations
OTHREAD_NUM = 8
APPLICATION = 'lr' # 'lr' 'k-means' 'water' 'heat'
DEACTIVATE_EXECUTION_TEMPLATE = False
DEACTIVATE_CACHE_MANAGER = False
DEACTIVATE_VDATA_MANAGER = False
DISABLE_HYPERTHREADING = False
RUN_WITH_TASKSET = False
WORKER_TASKSET = '0-1,4-5' # '0-3,8-11'
# Application configurations
# lr and k-means
DIMENSION = 10
CLUSTER_NUM = 2
ITERATION_NUM = 30
PARTITION_PER_CORE = 10
PARTITION_NUM = WORKER_NUM * OTHREAD_NUM * PARTITION_PER_CORE # 8000
REDUCTION_PARTITION_NUM = WORKER_NUM
SAMPLE_NUM_M = 544 # PARTITION_NUM / 1000000.0
SPIN_WAIT_US = 0 # 4000 # 4000 * (100 / WORKER_NUM)
DEACTIVATE_AUTOMATIC_REDUCTION = True
DEACTIVATE_REDUCTION_COMBINER = False
# water
SIMULATION_SCALE = 512
PART_X = 4
PART_Y = 4
PART_Z = 4
PROJ_PART_X = 4
PROJ_PART_Y = 4
PROJ_PART_Z = 4
FRAME_NUMBER = 1
ITERATION_BATCH = 1
MAX_ITERATION = 100
WATER_LEVEL = 0.35
PROJECTION_SMART_LEVEL = 0
NO_PROJ_BOTTLENECK = False
GLOBAL_WRITE = False
# heat
ITER_NUM = 30
NX = 800
NY = 800
NZ = 800
PNX = 2
PNY = 2
PNZ = 2
BW = 1
SW_US = 0
|
# SPDX-FileCopyrightText: Aresys S.r.l. <[email protected]>
# SPDX-License-Identifier: MIT
"""
Constants module
----------------
Example of usage:
.. code-block:: python
import arepytools.constants as cst
print(cst.LIGHT_SPEED)
"""
# Speed of light
LIGHT_SPEED = 299792458.0
"""
Speed of light in vacuum (m/s).
"""
# Units of measure
SECOND_STR = 's'
"""
Second symbol.
"""
HERTZ_STR = 'Hz'
"""
Hertz symbol.
"""
JOULE_STR = 'j'
"""
Joule symbol.
"""
DEGREE_STR = 'deg'
"""
Degree symbol.
"""
RAD_STR = 'rad'
"""
Radian symbol.
"""
UTC_STR = 'Utc'
"""
Coordinated Universal Time abbreviation.
"""
METER_STR = 'm'
"""
Meter symbol.
"""
# Metric prefixes
KILO = 1e3
"""
Number of units in one kilounit (kilounits-to-units conversion factor).
"""
MEGA = KILO**2
"""
Number of units in one megaunit (megaunits-to-units conversion factor).
"""
GIGA = KILO**3
"""
Number of units in one gigaunit (gigaunits-to-units conversion factor).
"""
MILLI = KILO**-1
"""
Number of units in one milliunit (milliunits-to-units conversion factor).
"""
MICRO = KILO**-2
"""
Number of units in one microunit (microunits-to-units conversion factor).
"""
NANO = KILO**-3
"""
Number of units in one nanounit (nanounits-to-units conversion factor).
"""
PICO = KILO**-4
"""
Number of units in one picounit (picounits-to-units conversion factor).
"""
|
a = float(input('Primeiro segmento: '))
b = float(input('Segundo segmento: '))
c = float(input('Terceiro segmento: '))
# print(a, b, c)
if (a < b + c) and (b < a + c) and (c < a + b):
triangulo = True
parte1 = 'Os segmentos acima PODEM FORMAR um triângulo '
else:
triangulo = False
parte1 = 'Os segmentos acima NÃO PODEM FORMAR triângulo'
if triangulo:
if a == b and b == c:
parte2 = 'EQUILÁTERO!'
elif a == b or b == c or a == c:
parte2 = 'ISÓSCELES!'
else:
parte2 = 'ESCALENO!'
else:
parte2 = '!'
msg = parte1 + parte2
print(msg)
|
# Copyright: 2006 Marien Zwart <[email protected]>
# License: BSD/GPL2
#base class
__all__ = ("PackageError", "InvalidPackageName", "MetadataException", "InvalidDependency",
"ChksumBase", "MissingChksum", "ParseChksumError")
class PackageError(ValueError):
pass
class InvalidPackageName(PackageError):
pass
class MetadataException(PackageError):
def __init__(self, pkg, attr, error):
Exception.__init__(self,
"Metadata Exception: pkg %s, attr %s\nerror: %s" %
(pkg, attr, error))
self.pkg, self.attr, self.error = pkg, attr, error
class InvalidDependency(PackageError):
pass
class ChksumBase(Exception):
pass
class MissingChksum(ChksumBase):
def __init__(self, filename):
ChksumBase.__init__(self, "Missing chksum data for %r" % filename)
self.file = filename
class ParseChksumError(ChksumBase):
def __init__(self, filename, error, missing=False):
if missing:
ChksumBase.__init__(self, "Failed parsing %r chksum; data isn't available: %s" %
(filename, error))
else:
ChksumBase.__init__(self, "Failed parsing %r chksum due to %s" %
(filename, error))
self.file = filename
self.error = error
self.missing = missing
|
#
# PySNMP MIB module CISCO-ENTITY-ASSET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-ASSET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:50 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
ModuleIdentity, IpAddress, iso, MibIdentifier, NotificationType, Counter64, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ObjectIdentity, TimeTicks, Counter32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "IpAddress", "iso", "MibIdentifier", "NotificationType", "Counter64", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ObjectIdentity", "TimeTicks", "Counter32", "Integer32")
TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "DisplayString")
ciscoEntityAssetMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 92))
ciscoEntityAssetMIB.setRevisions(('2003-09-18 00:00', '2002-07-23 16:00', '1999-06-02 16:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoEntityAssetMIB.setRevisionsDescriptions(('Some of the Objects have been deprecated since these are available in ENTITY-MIB(RFC 2737). 1. Following Objects have been deprecated. ceAssetOEMString : superceded by entPhysicalMfgName ceAssetSerialNumber : superceded by entPhysicalSerialNum ceAssetOrderablePartNumber: superceded by entPhysicalModelName ceAssetHardwareRevision : superceded by entPhysicalHardwareRev ceAssetFirmwareID : superceded by entPhysicalFirmwareRev ceAssetFirmwareRevision : superceded by entPhysicalFirmwareRev ceAssetSoftwareID : superceded by entPhysicalSoftwareRev ceAssetSoftwareRevision : superceded by entPhysicalSoftwareRev ceAssetAlias : superceded by entPhysicalAlias ceAssetTag : superceded by entPhysicalAssetID ceAssetIsFRU : superceded by entPhysicalIsFRU. 2. ceAssetEntityGroup has been deprecated.', 'Split the MIB objects of this MIB into two object groups.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoEntityAssetMIB.setLastUpdated('200309180000Z')
if mibBuilder.loadTexts: ciscoEntityAssetMIB.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoEntityAssetMIB.setContactInfo('Cisco Systems Customer Service Postal: Cisco Systems, Inc. 170 West Tasman Drive San Jose, CA 95134-1706 USA Tel: +1 408 526 4000 E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoEntityAssetMIB.setDescription('Monitor the asset information of items in the ENTITY-MIB (RFC 2037) entPhysical table.')
ciscoEntityAssetMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 1))
ceAssetTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1), )
if mibBuilder.loadTexts: ceAssetTable.setStatus('current')
if mibBuilder.loadTexts: ceAssetTable.setDescription('This table lists the orderable part number, serial number, hardware revision, manufacturing assembly number and revision, firmwareID and revision if any, and softwareID and revision if any, of relevant entities listed in the ENTITY-MIB entPhysicalTable. Entities for which none of this data is available are not listed in this table. This is a sparse table so some of these variables may not exist for a particular entity at a particular time. For example, a powered-off module does not have softwareID and revision; a power-supply would probably never have firmware or software information. Although the data may have other items encoded in it (for example manufacturing-date in the serial number) please treat all data items as monolithic. Do not decompose them or parse them. Use only string equals and unequals operations on them.')
ceAssetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"))
if mibBuilder.loadTexts: ceAssetEntry.setStatus('current')
if mibBuilder.loadTexts: ceAssetEntry.setDescription('An entAssetEntry entry describes the asset-tracking related data for an entity.')
ceAssetOEMString = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 1), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetOEMString.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetOEMString.setDescription('This variable indicates the Original Equipment Manufacturer of the entity.')
ceAssetSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 2), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetSerialNumber.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetSerialNumber.setDescription('This variable indicates the serial number of the entity.')
ceAssetOrderablePartNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetOrderablePartNumber.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetOrderablePartNumber.setDescription('This variable indicates the part number you can use to order the entity.')
ceAssetHardwareRevision = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 4), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetHardwareRevision.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetHardwareRevision.setDescription('This variable indicates the engineering design revision of the hardware of the entity.')
ceAssetMfgAssyNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 5), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetMfgAssyNumber.setStatus('current')
if mibBuilder.loadTexts: ceAssetMfgAssyNumber.setDescription("This variable indicates the manufacturing assembly number, which is the 'hardware' identification.")
ceAssetMfgAssyRevision = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetMfgAssyRevision.setStatus('current')
if mibBuilder.loadTexts: ceAssetMfgAssyRevision.setDescription('This variable indicates the revision of the entity, within the ceAssetMfgAssyNumber.')
ceAssetFirmwareID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 7), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetFirmwareID.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetFirmwareID.setDescription("This variable indicates the firmware installed on this entity. For IOS devices, this variable's value is in the IOS Image Naming Convention format. IOS Image Naming Convention Software images are named according to a scheme that identifies what's in the image and what platform it runs on. The names have three parts, separated by dashes: e.g. xxxx-yyyy-ww. xxxx = Platform yyyy = Features ww = Where it executes from and if compressed ")
ceAssetFirmwareRevision = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 8), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetFirmwareRevision.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetFirmwareRevision.setDescription("This variable indicates the revision of firmware installed on this entity. For IOS devices, this variable's value is in the NGRP external customer-visible format. NGRP external customer-visible revision strings have this format: 'x.y (z [p] ) [A] [ [ u ( v [ p ] ) ] ] [ q ]', where: - x.y Combination of two 1-2 digit numerics separated by a '.' that identify the Software major release - z 1-3 digit numeric that identifies the maintenance release of x.y - A 1-3 alpha letters, designator of the release train. - u 1-2 digit numeric that identifies the version of the ED-specific code - v 1-2 digit numeric that identifies the maintenance release of the ED-specific code - v 1-2 digit numeric that identifies the maintenance release of the ED-specific code - p 1 alpha letter that identifies the unusual special case SW Line Stop Fast Re-build by the Release Ops team to replace the posted/shipping release in CCO and Mfg with a version containing a critical catastrophic defect fix that cannot wait until the next maintenance release - q 3 alphanumeric optional suffix used as an indicator in the image banner by the SW Line Stop Re-build process used unusual special case situation when the renumber build has occurred but the images have not been released (value always blank unless these special circumstances require its use). ")
ceAssetSoftwareID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 9), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetSoftwareID.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetSoftwareID.setDescription("This variable indicates the software installed on this entity. For IOS devices, this variable's value is in the IOS Image Naming Convention format. IOS Image Naming Convention --------------------------- Software images are named according to a scheme that identifies what's in the image and what platform it runs on. The names have three parts, separated by dashes: e.g. xxxx-yyyy-ww. xxxx = Platform yyyy = Features ww = Where it executes from and if compressed ")
ceAssetSoftwareRevision = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 10), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetSoftwareRevision.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetSoftwareRevision.setDescription("This variable indicates the revision of software installed on this entity. For IOS devices, this variable's value is in the NGRP external customer-visible format. NGRP external customer-visible revision strings have this format: 'x.y (z [p] ) [A] [ [ u ( v [ p ] ) ] ] [ q ]', where: - x.y Combination of two 1-2 digit numerics separated by a '.' that identify the Software major release - z 1-3 digit numeric that identifies the maintenance release of x.y - A 1-3 alpha letters, designator of the release train. - u 1-2 digit numeric that identifies the version of the ED-specific code - v 1-2 digit numeric that identifies the maintenance release of the ED-specific code - p 1 alpha letter that identifies the unusual special case SW Line Stop Fast Re-build by the Release Ops team to replace the posted/shipping release in CCO and Mfg with a version containing a critical catastrophic defect fix that cannot wait until the next maintenance release - q 3 alphanumeric optional suffix used as an indicator in the image banner by the SW Line Stop Re-build process used unusual special case situation when the renumber build has occurred but the images have not been released (value always blank unless these special circumstances require its use). ")
ceAssetCLEI = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 11), SnmpAdminString().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(10, 10), ))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetCLEI.setReference('Bellcore Technical reference GR-485-CORE, COMMON LANGUAGE Equipment Processes and Guidelines, Issue 2, October, 1995.')
if mibBuilder.loadTexts: ceAssetCLEI.setStatus('current')
if mibBuilder.loadTexts: ceAssetCLEI.setDescription('This object represents the CLEI (Common Language Equipment Identifier) code for the physical entity. If the physical entity is not present in the system, or does not have an associated CLEI code, then the value of this object will be a zero-length string.')
ceAssetAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 12), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceAssetAlias.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetAlias.setDescription("This object is an 'alias' name for the physical entity as specified by a network manager, and provides a non-volatile 'handle' for the physical entity. On the first instantiation of an physical entity, the value of entPhysicalAlias associated with that entity is set to the zero-length string. However, agent may set the value to a locally unique default value, instead of a zero-length string. If write access is implemented for an instance of entPhysicalAlias, and a value is written into the instance, the agent must retain the supplied value in the entPhysicalAlias instance associated with the same physical entity for as long as that entity remains instantiated. This includes instantiations across all re-initializations/reboots of the network management system, including those which result in a change of the physical entity's entPhysicalIndex value.")
ceAssetTag = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 13), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ceAssetTag.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetTag.setDescription("This object is a user-assigned asset tracking identifier for the physical entity as specified by a network manager, and provides non-volatile storage of this information. On the first instantiation of an physical entity, the value of ceasAssetID associated with that entity is set to the zero-length string. Not every physical component will have a asset tracking identifier, or even need one. Physical entities for which the associated value of the ceAssetIsFRU object is equal to 'false' (e.g., the repeater ports within a repeater module), do not need their own unique asset tracking identifier. An agent does not have to provide write access for such entities, and may instead return a zero-length string. If write access is implemented for an instance of ceasAssetID, and a value is written into the instance, the agent must retain the supplied value in the ceasAssetID instance associated with the same physical entity for as long as that entity remains instantiated. This includes instantiations across all re-initializations/reboots of the network management system, including those which result in a change of the physical entity's entPhysicalIndex value. If no asset tracking information is associated with the physical component, then this object will contain a zero- length string.")
ceAssetIsFRU = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 92, 1, 1, 1, 14), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ceAssetIsFRU.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetIsFRU.setDescription("This object indicates whether or not this physical entity is considered a 'field replaceable unit' by the vendor. If this object contains the value 'true' then the corresponding entPhysicalEntry identifies a field replaceable unit. For all entPhysicalEntries which represent components that are permanently contained within a field replaceable unit, the value 'false' should be returned for this object.")
ciscoEntityAssetMIBNotificationsPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 2))
ciscoEntityAssetMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 2, 0))
ciscoEntityAssetMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 3))
ciscoEntityAssetMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 1))
ciscoEntityAssetMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 2))
ciscoEntityAssetMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 1, 1)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityAssetMIBCompliance = ciscoEntityAssetMIBCompliance.setStatus('deprecated')
if mibBuilder.loadTexts: ciscoEntityAssetMIBCompliance.setDescription('An ENTITY-MIB implementation that lists entities with asset information in its entPhysicalTable must implement this group.')
ciscoEntityAssetMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 1, 2)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetGroupRev1"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetEntityGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityAssetMIBComplianceRev1 = ciscoEntityAssetMIBComplianceRev1.setStatus('deprecated')
if mibBuilder.loadTexts: ciscoEntityAssetMIBComplianceRev1.setDescription('An ENTITY-MIB implementation that lists entities with asset information in its entPhysicalTable must implement this group.')
ciscoEntityAssetMIBComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 1, 3)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetGroupRev2"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoEntityAssetMIBComplianceRev2 = ciscoEntityAssetMIBComplianceRev2.setStatus('current')
if mibBuilder.loadTexts: ciscoEntityAssetMIBComplianceRev2.setDescription('An ENTITY-MIB implementation that lists entities with asset information in its entPhysicalTable must implement this group.')
ceAssetGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 2, 1)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetOEMString"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSerialNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetOrderablePartNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetHardwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetFirmwareID"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetFirmwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSoftwareID"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSoftwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetCLEI"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetAlias"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetTag"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetIsFRU"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceAssetGroup = ceAssetGroup.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetGroup.setDescription('The collection of objects which are used to describe and monitor asset-related data of ENTITY-MIB entPhysicalTable items.')
ceAssetGroupRev1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 2, 2)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetOEMString"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetFirmwareID"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSoftwareID"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetCLEI"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceAssetGroupRev1 = ceAssetGroupRev1.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetGroupRev1.setDescription('The collection of objects which are used to describe and monitor asset-related extension data of ENTITY-MIB (RFC 2737) entPhysicalTable items.')
ceAssetEntityGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 2, 3)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetOrderablePartNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSerialNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetHardwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetFirmwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetSoftwareRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetAlias"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetTag"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetIsFRU"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceAssetEntityGroup = ceAssetEntityGroup.setStatus('deprecated')
if mibBuilder.loadTexts: ceAssetEntityGroup.setDescription('The collection of objects which are duplicated from the objects in the entPhysicalTable of ENTITY-MIB (RFC 2737).')
ceAssetGroupRev2 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 92, 3, 2, 4)).setObjects(("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyNumber"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetMfgAssyRevision"), ("CISCO-ENTITY-ASSET-MIB", "ceAssetCLEI"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ceAssetGroupRev2 = ceAssetGroupRev2.setStatus('current')
if mibBuilder.loadTexts: ceAssetGroupRev2.setDescription('The collection of objects which are used to describe and monitor asset-related extension data of ENTITY-MIB (RFC 2737) entPhysicalTable items.')
mibBuilder.exportSymbols("CISCO-ENTITY-ASSET-MIB", ciscoEntityAssetMIBComplianceRev1=ciscoEntityAssetMIBComplianceRev1, ciscoEntityAssetMIB=ciscoEntityAssetMIB, ceAssetTag=ceAssetTag, ciscoEntityAssetMIBGroups=ciscoEntityAssetMIBGroups, ceAssetFirmwareRevision=ceAssetFirmwareRevision, ceAssetAlias=ceAssetAlias, ciscoEntityAssetMIBNotifications=ciscoEntityAssetMIBNotifications, ceAssetGroup=ceAssetGroup, PYSNMP_MODULE_ID=ciscoEntityAssetMIB, ceAssetCLEI=ceAssetCLEI, ceAssetMfgAssyNumber=ceAssetMfgAssyNumber, ceAssetSerialNumber=ceAssetSerialNumber, ceAssetHardwareRevision=ceAssetHardwareRevision, ceAssetGroupRev2=ceAssetGroupRev2, ciscoEntityAssetMIBComplianceRev2=ciscoEntityAssetMIBComplianceRev2, ciscoEntityAssetMIBObjects=ciscoEntityAssetMIBObjects, ceAssetEntry=ceAssetEntry, ciscoEntityAssetMIBCompliances=ciscoEntityAssetMIBCompliances, ciscoEntityAssetMIBCompliance=ciscoEntityAssetMIBCompliance, ceAssetSoftwareRevision=ceAssetSoftwareRevision, ceAssetIsFRU=ceAssetIsFRU, ciscoEntityAssetMIBConformance=ciscoEntityAssetMIBConformance, ceAssetOEMString=ceAssetOEMString, ceAssetFirmwareID=ceAssetFirmwareID, ceAssetTable=ceAssetTable, ceAssetEntityGroup=ceAssetEntityGroup, ciscoEntityAssetMIBNotificationsPrefix=ciscoEntityAssetMIBNotificationsPrefix, ceAssetSoftwareID=ceAssetSoftwareID, ceAssetGroupRev1=ceAssetGroupRev1, ceAssetOrderablePartNumber=ceAssetOrderablePartNumber, ceAssetMfgAssyRevision=ceAssetMfgAssyRevision)
|
def egcd(a, b):
if a==0:
return b, 0, 1
else:
gcd, x, y = egcd(b%a, a)
return gcd, y-(b//a)*x, x
if __name__ == '__main__':
a = int(input('Enter a: '))
b = int(input('Enter b: '))
gcd, x, y = egcd(a, b)
print(egcd(a,b))
if gcd!=1:
print("M.I. doesn't exist")
else:
print('M.I. of b under modulo a is: ', (x%b + b)%b)
|
class Engine(object):
"""Engine"""
def __init__(self, rest):
self.rest = rest
def list(self, params=None):
return self.rest.get('engines', params)
def create(self, data=None):
return self.rest.post('engines', data)
def get(self, name):
return self.rest.get('engines/' + name)
def update(self, name, data=None):
return self.rest.put('engines/' + name, data=data)
def delete(self, name):
return self.rest.delete('engines/' + name)
|
def app(environ, start_response):
s = ""
for i in environ['QUERY_STRING'].split("&"):
s = s + i + "\r\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(s)))
])
return [bytes(s, 'utf-8')]
|
# -*- coding: utf-8 -*-
'''
File name: code\integer_angled_quadrilaterals\sol_177.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #177 :: Integer angled Quadrilaterals
#
# For more information see:
# https://projecteuler.net/problem=177
# Problem Statement
'''
Let ABCD be a convex quadrilateral, with diagonals AC and BD. At each vertex the diagonal makes an angle with each of the two sides, creating eight corner angles.
For example, at vertex A, the two angles are CAD, CAB.
We call such a quadrilateral for which all eight corner angles have integer values when measured in degrees an "integer angled quadrilateral". An example of an integer angled quadrilateral is a square, where all eight corner angles are 45°. Another example is given by DAC = 20°, BAC = 60°, ABD = 50°, CBD = 30°, BCA = 40°, DCA = 30°, CDB = 80°, ADB = 50°.
What is the total number of non-similar integer angled quadrilaterals?
Note: In your calculations you may assume that a calculated angle is integral if it is within a tolerance of 10-9 of an integer value.
'''
# Solution
# Solution Approach
'''
'''
|
deck_test = {
"kategori 1": ["kartuA", "kartuB", "kartuC", "kartuD"],
"kategori 2": ["kartuE", "kartuF", "kartuG", "kartuH"],
"kategori 3": ["kartuI", "kartuJ", "kartuK", "kartuL"],
# "kategori 4": ["kartuM", "kartuN", "kartuO", "kartuP"],
# "kategori 5": ["kartuQ", "kartuR", "kartuS", "kartuT"],
}
deck_used = {
"nasi": ["nasi goreng", "nasi uduk", "nasi kuning", "nasi kucing"],
"air": ["air putih", "air santan", "air susu", "air tajin"],
"benda lengkung": ["busur", "karet", "tampah", "jembatan"],
"minuman": ["kopi", "teh", "cincau", "boba"],
"sumber tenaga": ["listrik", "bensin", "matahari", "karbohidrat"],
"manisan": ["permen", "coklat", "gula", "tebu"],
"tempat tinggal": ["hotel", "apartemen", "rumah", "emperan"]
}
|
data = [int(input()), input()]
if 10 <= data[0] <= 15 and data[1] == "f":
print("YES")
else:
print("NO")
|
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res = cnt = 0
for i in nums:
if i:
cnt += 1
else:
if cnt:
res = max(res, cnt)
cnt = 0
return max(res, cnt) |
n = int(input())
while True:
s,z =0,n
while z>0:
s+=z%10
z//=10
if n%s==0:
print(n)
break
n+=1 |
n = int(input())
k = n >> 1
ans = 1
for i in range(n-k+1,n+1):
ans *= i
for i in range(1,k+1):
ans //= i
print (ans)
|
#
# PySNMP MIB module DVMRP-STD-MIB-UNI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB-UNI
# Produced by pysmi-0.3.4 at Mon Apr 29 18:40:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
Integer32, TimeTicks, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, MibIdentifier, Unsigned32, ModuleIdentity, iso, IpAddress, Bits, ObjectIdentity, Gauge32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "TimeTicks", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "MibIdentifier", "Unsigned32", "ModuleIdentity", "iso", "IpAddress", "Bits", "ObjectIdentity", "Gauge32", "Counter32")
TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus")
usdDvmrpExperiment, = mibBuilder.importSymbols("Unisphere-Data-Experiment", "usdDvmrpExperiment")
dvmrpStdMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1))
dvmrpStdMIB.setRevisions(('1999-10-19 12:00',))
if mibBuilder.loadTexts: dvmrpStdMIB.setLastUpdated('9910191200Z')
if mibBuilder.loadTexts: dvmrpStdMIB.setOrganization('IETF IDMR Working Group.')
dvmrpMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1))
dvmrp = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1))
dvmrpScalar = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 1))
dvmrpVersionString = MibScalar((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpVersionString.setStatus('current')
dvmrpGenerationId = MibScalar((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpGenerationId.setStatus('current')
dvmrpNumRoutes = MibScalar((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNumRoutes.setStatus('current')
dvmrpReachableRoutes = MibScalar((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpReachableRoutes.setStatus('current')
dvmrpInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2), )
if mibBuilder.loadTexts: dvmrpInterfaceTable.setStatus('current')
dvmrpInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1), ).setIndexNames((0, "DVMRP-STD-MIB-UNI", "dvmrpInterfaceIfIndex"))
if mibBuilder.loadTexts: dvmrpInterfaceEntry.setStatus('current')
dvmrpInterfaceIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpInterfaceIfIndex.setStatus('current')
dvmrpInterfaceLocalAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 2), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceLocalAddress.setStatus('current')
dvmrpInterfaceMetric = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceMetric.setStatus('current')
dvmrpInterfaceStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceStatus.setStatus('current')
dvmrpInterfaceRcvBadPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadPkts.setStatus('current')
dvmrpInterfaceRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadRoutes.setStatus('current')
dvmrpInterfaceSentRoutes = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceSentRoutes.setStatus('current')
dvmrpInterfaceInterfaceKey = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 8), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceInterfaceKey.setStatus('current')
dvmrpInterfaceInterfaceKeyVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 2, 1, 9), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceInterfaceKeyVersion.setStatus('current')
dvmrpNeighborTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3), )
if mibBuilder.loadTexts: dvmrpNeighborTable.setStatus('current')
dvmrpNeighborEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1), ).setIndexNames((0, "DVMRP-STD-MIB-UNI", "dvmrpNeighborIfIndex"), (0, "DVMRP-STD-MIB-UNI", "dvmrpNeighborAddress"))
if mibBuilder.loadTexts: dvmrpNeighborEntry.setStatus('current')
dvmrpNeighborIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpNeighborIfIndex.setStatus('current')
dvmrpNeighborAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpNeighborAddress.setStatus('current')
dvmrpNeighborUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborUpTime.setStatus('current')
dvmrpNeighborExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborExpiryTime.setStatus('current')
dvmrpNeighborGenerationId = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborGenerationId.setStatus('current')
dvmrpNeighborMajorVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborMajorVersion.setStatus('current')
dvmrpNeighborMinorVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborMinorVersion.setStatus('current')
dvmrpNeighborCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 8), Bits().clone(namedValues=NamedValues(("leaf", 0), ("prune", 1), ("generationID", 2), ("mtrace", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborCapabilities.setStatus('current')
dvmrpNeighborRcvRoutes = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvRoutes.setStatus('current')
dvmrpNeighborRcvBadPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvBadPkts.setStatus('current')
dvmrpNeighborRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvBadRoutes.setStatus('current')
dvmrpNeighborState = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("oneway", 1), ("active", 2), ("ignoring", 3), ("down", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborState.setStatus('current')
dvmrpRouteTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4), )
if mibBuilder.loadTexts: dvmrpRouteTable.setStatus('current')
dvmrpRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1), ).setIndexNames((0, "DVMRP-STD-MIB-UNI", "dvmrpRouteSource"), (0, "DVMRP-STD-MIB-UNI", "dvmrpRouteSourceMask"))
if mibBuilder.loadTexts: dvmrpRouteEntry.setStatus('current')
dvmrpRouteSource = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteSource.setStatus('current')
dvmrpRouteSourceMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteSourceMask.setStatus('current')
dvmrpRouteUpstreamNeighbor = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteUpstreamNeighbor.setStatus('current')
dvmrpRouteIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 4), InterfaceIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteIfIndex.setStatus('current')
dvmrpRouteMetric = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteMetric.setStatus('current')
dvmrpRouteExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 6), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteExpiryTime.setStatus('current')
dvmrpRouteUpTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 4, 1, 7), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteUpTime.setStatus('current')
dvmrpRouteNextHopTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5), )
if mibBuilder.loadTexts: dvmrpRouteNextHopTable.setStatus('current')
dvmrpRouteNextHopEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5, 1), ).setIndexNames((0, "DVMRP-STD-MIB-UNI", "dvmrpRouteNextHopSource"), (0, "DVMRP-STD-MIB-UNI", "dvmrpRouteNextHopSourceMask"), (0, "DVMRP-STD-MIB-UNI", "dvmrpRouteNextHopIfIndex"))
if mibBuilder.loadTexts: dvmrpRouteNextHopEntry.setStatus('current')
dvmrpRouteNextHopSource = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteNextHopSource.setStatus('current')
dvmrpRouteNextHopSourceMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteNextHopSourceMask.setStatus('current')
dvmrpRouteNextHopIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5, 1, 3), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpRouteNextHopIfIndex.setStatus('current')
dvmrpRouteNextHopType = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("leaf", 1), ("branch", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteNextHopType.setStatus('current')
dvmrpPruneTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6), )
if mibBuilder.loadTexts: dvmrpPruneTable.setStatus('current')
dvmrpPruneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6, 1), ).setIndexNames((0, "DVMRP-STD-MIB-UNI", "dvmrpPruneGroup"), (0, "DVMRP-STD-MIB-UNI", "dvmrpPruneSource"), (0, "DVMRP-STD-MIB-UNI", "dvmrpPruneSourceMask"))
if mibBuilder.loadTexts: dvmrpPruneEntry.setStatus('current')
dvmrpPruneGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneGroup.setStatus('current')
dvmrpPruneSource = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneSource.setStatus('current')
dvmrpPruneSourceMask = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6, 1, 3), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneSourceMask.setStatus('current')
dvmrpPruneExpiryTime = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 6, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpPruneExpiryTime.setStatus('current')
dvmrpTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 0))
dvmrpNeighborLoss = NotificationType((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 0, 1)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborState"))
if mibBuilder.loadTexts: dvmrpNeighborLoss.setStatus('current')
dvmrpNeighborNotPruning = NotificationType((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 1, 1, 0, 2)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborCapabilities"))
if mibBuilder.loadTexts: dvmrpNeighborNotPruning.setStatus('current')
dvmrpMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2))
dvmrpMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 1))
dvmrpMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2))
dvmrpMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 1, 1)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpGeneralGroup"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceGroup"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborGroup"), ("DVMRP-STD-MIB-UNI", "dvmrpRoutingGroup"), ("DVMRP-STD-MIB-UNI", "dvmrpTreeGroup"), ("DVMRP-STD-MIB-UNI", "dvmrpSecurityGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpMIBCompliance = dvmrpMIBCompliance.setStatus('current')
dvmrpGeneralGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 2)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpVersionString"), ("DVMRP-STD-MIB-UNI", "dvmrpGenerationId"), ("DVMRP-STD-MIB-UNI", "dvmrpNumRoutes"), ("DVMRP-STD-MIB-UNI", "dvmrpReachableRoutes"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpGeneralGroup = dvmrpGeneralGroup.setStatus('current')
dvmrpInterfaceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 3)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceMetric"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceStatus"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceRcvBadPkts"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceRcvBadRoutes"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceSentRoutes"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpInterfaceGroup = dvmrpInterfaceGroup.setStatus('current')
dvmrpNeighborGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 4)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpNeighborUpTime"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborExpiryTime"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborGenerationId"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborMajorVersion"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborMinorVersion"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborCapabilities"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborRcvRoutes"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborRcvBadPkts"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborRcvBadRoutes"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpNeighborGroup = dvmrpNeighborGroup.setStatus('current')
dvmrpRoutingGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 5)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpRouteUpstreamNeighbor"), ("DVMRP-STD-MIB-UNI", "dvmrpRouteIfIndex"), ("DVMRP-STD-MIB-UNI", "dvmrpRouteMetric"), ("DVMRP-STD-MIB-UNI", "dvmrpRouteExpiryTime"), ("DVMRP-STD-MIB-UNI", "dvmrpRouteUpTime"), ("DVMRP-STD-MIB-UNI", "dvmrpRouteNextHopType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpRoutingGroup = dvmrpRoutingGroup.setStatus('current')
dvmrpSecurityGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 6)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpInterfaceInterfaceKey"), ("DVMRP-STD-MIB-UNI", "dvmrpInterfaceInterfaceKeyVersion"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpSecurityGroup = dvmrpSecurityGroup.setStatus('current')
dvmrpTreeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 7)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpPruneExpiryTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpTreeGroup = dvmrpTreeGroup.setStatus('current')
dvmrpNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 4874, 3, 2, 1, 1, 2, 2, 8)).setObjects(("DVMRP-STD-MIB-UNI", "dvmrpNeighborLoss"), ("DVMRP-STD-MIB-UNI", "dvmrpNeighborNotPruning"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpNotificationGroup = dvmrpNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("DVMRP-STD-MIB-UNI", dvmrpInterfaceRcvBadRoutes=dvmrpInterfaceRcvBadRoutes, dvmrpNeighborMinorVersion=dvmrpNeighborMinorVersion, dvmrpNeighborUpTime=dvmrpNeighborUpTime, dvmrpNeighborEntry=dvmrpNeighborEntry, dvmrpReachableRoutes=dvmrpReachableRoutes, dvmrpInterfaceIfIndex=dvmrpInterfaceIfIndex, dvmrpNeighborAddress=dvmrpNeighborAddress, dvmrpPruneGroup=dvmrpPruneGroup, dvmrpPruneExpiryTime=dvmrpPruneExpiryTime, dvmrpMIBCompliances=dvmrpMIBCompliances, dvmrpRouteUpTime=dvmrpRouteUpTime, dvmrpInterfaceInterfaceKey=dvmrpInterfaceInterfaceKey, dvmrp=dvmrp, dvmrpNeighborExpiryTime=dvmrpNeighborExpiryTime, dvmrpNeighborRcvBadRoutes=dvmrpNeighborRcvBadRoutes, dvmrpInterfaceSentRoutes=dvmrpInterfaceSentRoutes, dvmrpRouteSource=dvmrpRouteSource, dvmrpRouteNextHopTable=dvmrpRouteNextHopTable, dvmrpRouteNextHopSourceMask=dvmrpRouteNextHopSourceMask, dvmrpRouteNextHopIfIndex=dvmrpRouteNextHopIfIndex, dvmrpTraps=dvmrpTraps, dvmrpNeighborNotPruning=dvmrpNeighborNotPruning, dvmrpNeighborState=dvmrpNeighborState, dvmrpRouteTable=dvmrpRouteTable, dvmrpNeighborRcvRoutes=dvmrpNeighborRcvRoutes, dvmrpScalar=dvmrpScalar, dvmrpMIBGroups=dvmrpMIBGroups, dvmrpRouteIfIndex=dvmrpRouteIfIndex, dvmrpInterfaceLocalAddress=dvmrpInterfaceLocalAddress, dvmrpNeighborCapabilities=dvmrpNeighborCapabilities, dvmrpRouteNextHopSource=dvmrpRouteNextHopSource, dvmrpRouteNextHopType=dvmrpRouteNextHopType, dvmrpInterfaceRcvBadPkts=dvmrpInterfaceRcvBadPkts, dvmrpRouteSourceMask=dvmrpRouteSourceMask, dvmrpNotificationGroup=dvmrpNotificationGroup, dvmrpInterfaceInterfaceKeyVersion=dvmrpInterfaceInterfaceKeyVersion, dvmrpSecurityGroup=dvmrpSecurityGroup, PYSNMP_MODULE_ID=dvmrpStdMIB, dvmrpRouteEntry=dvmrpRouteEntry, dvmrpNeighborTable=dvmrpNeighborTable, dvmrpRouteUpstreamNeighbor=dvmrpRouteUpstreamNeighbor, dvmrpPruneSource=dvmrpPruneSource, dvmrpGeneralGroup=dvmrpGeneralGroup, dvmrpNeighborRcvBadPkts=dvmrpNeighborRcvBadPkts, dvmrpNeighborLoss=dvmrpNeighborLoss, dvmrpStdMIB=dvmrpStdMIB, dvmrpPruneSourceMask=dvmrpPruneSourceMask, dvmrpRouteExpiryTime=dvmrpRouteExpiryTime, dvmrpNeighborMajorVersion=dvmrpNeighborMajorVersion, dvmrpRouteNextHopEntry=dvmrpRouteNextHopEntry, dvmrpInterfaceMetric=dvmrpInterfaceMetric, dvmrpNeighborGroup=dvmrpNeighborGroup, dvmrpInterfaceEntry=dvmrpInterfaceEntry, dvmrpPruneEntry=dvmrpPruneEntry, dvmrpNeighborIfIndex=dvmrpNeighborIfIndex, dvmrpInterfaceStatus=dvmrpInterfaceStatus, dvmrpPruneTable=dvmrpPruneTable, dvmrpGenerationId=dvmrpGenerationId, dvmrpMIBConformance=dvmrpMIBConformance, dvmrpInterfaceTable=dvmrpInterfaceTable, dvmrpInterfaceGroup=dvmrpInterfaceGroup, dvmrpRouteMetric=dvmrpRouteMetric, dvmrpRoutingGroup=dvmrpRoutingGroup, dvmrpVersionString=dvmrpVersionString, dvmrpMIBCompliance=dvmrpMIBCompliance, dvmrpNeighborGenerationId=dvmrpNeighborGenerationId, dvmrpNumRoutes=dvmrpNumRoutes, dvmrpTreeGroup=dvmrpTreeGroup, dvmrpMIBObjects=dvmrpMIBObjects)
|
mesh_meshes_begin = 0
mesh_mp_score_a = 1
mesh_mp_score_b = 2
mesh_load_window = 3
mesh_checkbox_off = 4
mesh_checkbox_on = 5
mesh_white_plane = 6
mesh_white_dot = 7
mesh_player_dot = 8
mesh_flag_infantry = 9
mesh_flag_archers = 10
mesh_flag_cavalry = 11
mesh_inv_slot = 12
mesh_mp_ingame_menu = 13
mesh_mp_inventory_left = 14
mesh_mp_inventory_right = 15
mesh_mp_inventory_choose = 16
mesh_mp_inventory_slot_glove = 17
mesh_mp_inventory_slot_horse = 18
mesh_mp_inventory_slot_armor = 19
mesh_mp_inventory_slot_helmet = 20
mesh_mp_inventory_slot_boot = 21
mesh_mp_inventory_slot_empty = 22
mesh_mp_inventory_slot_equip = 23
mesh_mp_inventory_left_arrow = 24
mesh_mp_inventory_right_arrow = 25
mesh_mp_ui_host_main = 26
mesh_mp_ui_command_panel = 27
mesh_mp_ui_command_border_l = 28
mesh_mp_ui_command_border_r = 29
mesh_mp_ui_welcome_panel = 30
mesh_flag_project_sw = 31
mesh_flag_project_vg = 32
mesh_flag_project_kh = 33
mesh_flag_project_nd = 34
mesh_flag_project_rh = 35
mesh_flag_project_sr = 36
mesh_flag_projects_end = 37
mesh_flag_project_sw_miss = 38
mesh_flag_project_vg_miss = 39
mesh_flag_project_kh_miss = 40
mesh_flag_project_nd_miss = 41
mesh_flag_project_rh_miss = 42
mesh_flag_project_sr_miss = 43
mesh_flag_project_misses_end = 44
mesh_banner_a01 = 45
mesh_banner_a02 = 46
mesh_banner_a03 = 47
mesh_banner_a04 = 48
mesh_banner_a05 = 49
mesh_banner_a06 = 50
mesh_banner_a07 = 51
mesh_banner_a08 = 52
mesh_banner_a09 = 53
mesh_banner_a10 = 54
mesh_banner_a11 = 55
mesh_banner_a12 = 56
mesh_banner_a13 = 57
mesh_banner_a14 = 58
mesh_banner_a15 = 59
mesh_banner_a16 = 60
mesh_banner_a17 = 61
mesh_banner_a18 = 62
mesh_banner_a19 = 63
mesh_banner_a20 = 64
mesh_banner_a21 = 65
mesh_banner_b01 = 66
mesh_banner_b02 = 67
mesh_banner_b03 = 68
mesh_banner_b04 = 69
mesh_banner_b05 = 70
mesh_banner_b06 = 71
mesh_banner_b07 = 72
mesh_banner_b08 = 73
mesh_banner_b09 = 74
mesh_banner_b10 = 75
mesh_banner_b11 = 76
mesh_banner_b12 = 77
mesh_banner_b13 = 78
mesh_banner_b14 = 79
mesh_banner_b15 = 80
mesh_banner_b16 = 81
mesh_banner_b17 = 82
mesh_banner_b18 = 83
mesh_banner_b19 = 84
mesh_banner_b20 = 85
mesh_banner_b21 = 86
mesh_banner_c01 = 87
mesh_banner_c02 = 88
mesh_banner_c03 = 89
mesh_banner_c04 = 90
mesh_banner_c05 = 91
mesh_banner_c06 = 92
mesh_banner_c07 = 93
mesh_banner_c08 = 94
mesh_banner_c09 = 95
mesh_banner_c10 = 96
mesh_banner_c11 = 97
mesh_banner_c12 = 98
mesh_banner_c13 = 99
mesh_banner_c14 = 100
mesh_banner_c15 = 101
mesh_banner_c16 = 102
mesh_banner_c17 = 103
mesh_banner_c18 = 104
mesh_banner_c19 = 105
mesh_banner_c20 = 106
mesh_banner_c21 = 107
mesh_banner_d01 = 108
mesh_banner_d02 = 109
mesh_banner_d03 = 110
mesh_banner_d04 = 111
mesh_banner_d05 = 112
mesh_banner_d06 = 113
mesh_banner_d07 = 114
mesh_banner_d08 = 115
mesh_banner_d09 = 116
mesh_banner_d10 = 117
mesh_banner_d11 = 118
mesh_banner_d12 = 119
mesh_banner_d13 = 120
mesh_banner_d14 = 121
mesh_banner_d15 = 122
mesh_banner_d16 = 123
mesh_banner_d17 = 124
mesh_banner_d18 = 125
mesh_banner_d19 = 126
mesh_banner_d20 = 127
mesh_banner_d21 = 128
mesh_banner_e01 = 129
mesh_banner_e02 = 130
mesh_banner_e03 = 131
mesh_banner_e04 = 132
mesh_banner_e05 = 133
mesh_banner_e06 = 134
mesh_banner_e07 = 135
mesh_banner_e08 = 136
mesh_banner_kingdom_a = 137
mesh_banner_kingdom_b = 138
mesh_banner_kingdom_c = 139
mesh_banner_kingdom_d = 140
mesh_banner_kingdom_e = 141
mesh_banner_kingdom_f = 142
mesh_banner_f21 = 143
mesh_banners_default_a = 144
mesh_banners_default_b = 145
mesh_banners_default_c = 146
mesh_banners_default_d = 147
mesh_banners_default_e = 148
mesh_troop_label_banner = 149
mesh_ui_kingdom_shield_1 = 150
mesh_ui_kingdom_shield_2 = 151
mesh_ui_kingdom_shield_3 = 152
mesh_ui_kingdom_shield_4 = 153
mesh_ui_kingdom_shield_5 = 154
mesh_ui_kingdom_shield_6 = 155
mesh_mouse_arrow_down = 156
mesh_mouse_arrow_right = 157
mesh_mouse_arrow_left = 158
mesh_mouse_arrow_up = 159
mesh_mouse_arrow_plus = 160
mesh_mouse_left_click = 161
mesh_mouse_right_click = 162
mesh_main_menu_background = 163
mesh_loading_background = 164
mesh_white_bg_plane_a = 165
mesh_cb_ui_main = 166
mesh_cb_ui_maps_scene_french_farm = 167
mesh_cb_ui_maps_scene_landshut = 168
mesh_cb_ui_maps_scene_river_crossing = 169
mesh_cb_ui_maps_scene_spanish_village = 170
mesh_cb_ui_maps_scene_strangefields = 171
mesh_cb_ui_maps_scene_01 = 172
mesh_cb_ui_maps_scene_02 = 173
mesh_cb_ui_maps_scene_03 = 174
mesh_cb_ui_maps_scene_04 = 175
mesh_cb_ui_maps_scene_05 = 176
mesh_cb_ui_maps_scene_06 = 177
mesh_cb_ui_maps_scene_07 = 178
mesh_cb_ui_maps_scene_08 = 179
mesh_cb_ui_maps_scene_09 = 180
mesh_ui_kingdom_shield_7 = 181
mesh_flag_project_rb = 182
mesh_flag_project_rb_miss = 183
mesh_ui_kingdom_shield_neutral = 184
mesh_ui_team_select_shield_aus = 185
mesh_ui_team_select_shield_bri = 186
mesh_ui_team_select_shield_fra = 187
mesh_ui_team_select_shield_pru = 188
mesh_ui_team_select_shield_rus = 189
mesh_ui_team_select_shield_reb = 190
mesh_ui_team_select_shield_neu = 191
mesh_construct_mesh_stakes = 192
mesh_construct_mesh_stakes2 = 193
mesh_construct_mesh_sandbags = 194
mesh_construct_mesh_cdf_tri = 195
mesh_construct_mesh_gabion = 196
mesh_construct_mesh_fence = 197
mesh_construct_mesh_plank = 198
mesh_construct_mesh_earthwork = 199
mesh_construct_mesh_explosives = 200
mesh_bonus_icon_melee = 201
mesh_bonus_icon_accuracy = 202
mesh_bonus_icon_speed = 203
mesh_bonus_icon_reload = 204
mesh_bonus_icon_artillery = 205
mesh_bonus_icon_commander = 206
mesh_arty_icon_take_ammo = 207
mesh_arty_icon_put_ammo = 208
mesh_arty_icon_ram = 209
mesh_arty_icon_move_up = 210
mesh_arty_icon_take_control = 211
mesh_item_select_no_select = 212
mesh_mm_spyglass_ui = 213
mesh_target_plate = 214
mesh_scn_mp_arabian_harbour_select = 215
mesh_scn_mp_arabian_village_select = 216
mesh_scn_mp_ardennes_select = 217
mesh_scn_mp_avignon_select = 218
mesh_scn_mp_bordino_select = 219
mesh_scn_mp_champs_elysees_select = 220
mesh_scn_mp_columbia_farm_select = 221
mesh_scn_mp_european_city_summer_select = 222
mesh_scn_mp_european_city_winter_select = 223
mesh_scn_mp_fort_beaver_select = 224
mesh_scn_mp_fort_boyd_select = 225
mesh_scn_mp_fort_fleetwood_select = 226
mesh_scn_mp_fort_lyon_select = 227
mesh_scn_mp_fort_refleax_select = 228
mesh_scn_mp_fort_vincey_select = 229
mesh_scn_mp_french_farm_select = 230
mesh_scn_mp_german_village_select = 231
mesh_scn_mp_hougoumont_select = 232
mesh_scn_mp_hungarian_plains_select = 233
mesh_scn_mp_la_haye_sainte_select = 234
mesh_scn_mp_landshut_select = 235
mesh_scn_mp_minden_select = 236
mesh_scn_mp_oaksfield_select = 237
mesh_scn_mp_quatre_bras_select = 238
mesh_scn_mp_river_crossing_select = 239
mesh_scn_mp_roxburgh_select = 240
mesh_scn_mp_russian_village_select = 241
mesh_scn_mp_schemmerbach_select = 242
mesh_scn_mp_slovenian_village_select = 243
mesh_scn_mp_spanish_farm_select = 244
mesh_scn_mp_spanish_mountain_pass_select = 245
mesh_scn_mp_spanish_village_select = 246
mesh_scn_mp_strangefields_select = 247
mesh_scn_mp_swamp_select = 248
mesh_scn_mp_walloon_farm_select = 249
mesh_scn_mp_testing_map_select = 250
mesh_scn_mp_random_plain_select = 251
mesh_scn_mp_random_steppe_select = 252
mesh_scn_mp_random_desert_select = 253
mesh_scn_mp_random_snow_select = 254
mesh_meshes_end = 255
|
# hanoi: int -> int
# calcula el numero de movimientos necesarios aara mover
# una torre de n discos de una vara a otra
# usando 3 varas y siguiendo las restricciones del puzzle hanoi
# ejemplo: hanoi(0) debe dar 0, hanoi(1) debe dar 1, hanoi(2) debe dar 3
def hanoi(n):
if n < 2:
return n
else:
return 1+ 2* hanoi(n-1)
#test
assert hanoi(0) == 0
assert hanoi(1) == 1
assert hanoi(4) == 15
assert hanoi(5) == 31
|
class Solution(object):
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
|
# BUG Can live for several minutes after decapitation
# Either change death-time or remove need for head entirely
"""
TODO BAK-AAAW
# BUG If you read me as a seperate code-tag you are a dumb, dumb, dumb crawler.
''' TODO Include me with bak-aaaw too! '''
""" |
date = input("enter the date: ").split()
dd = int(date[0])
yyyy = int(date[2])
mm = date[1]
l = []
l.append(yyyy)
l.append(mm)
l.append(dd)
t = tuple(l)
print(t)
|
menu_item=0
namelist = []
while menu_item != 9:
print("----------------------------")
print("1. Mencetak List")
print("2. Menambahkan nama ke dalam list")
print("3. Menghapus nama dari list")
print("4. Mengubah data dari dalam list")
print("9. Keluar")
menu_item= int(input("Pilih menu: "))
if menu_item == 1:
current = 0
if len(namelist) > 0:
while current < len(namelist):
print(current, ".", namelist[current])
current = current + 1
else:
print("List Kosong")
elif menu_item == 2:
name = input("Masukkan nama: ")
namelist.append(name)
elif menu_item == 3:
del_name = input("Nama yang ingin dihapus: ")
if del_name in namelist:
#namelist.remove(del_name) dapat digunakan
item_number = namelist.index(del_name)
del namelist[item_number]
#Kode di atas hanya menghapus nama pertama yang ada.
#Kode di bawah ini menghapus semua nama
"""
while del_name in namelist:
item_number = namelist.index(del_name)
del namelist[item_number]
"""
else:
print(del_name, "tidak ditemukan")
elif menu_item == 4:
old_name = input("Nama apa yang ingin diubah: ")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("Nama baru: ")
namelist[item_number] = new_name
else:
print(old_name, "tidak ditemukan")
print("Selamat tinggal") |
#
# baseparser.py
#
# Base class for Modbus message parser
#
class ModbusBaseParser:
"""Base class for Modbus message parsing.
"""
def __init__(self):
pass
def msgs_from_bytes(self, b):
"""Parse messages from a byte string
"""
|
"""
Write a function:
def missing_integer(A):
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
"""
def missing_integer(A):
for index in range(1, len(A)):
if index not in A:
return index
return len(A)+1
example1 = [1, 3, 6, 4, 1, 2]
example2 = [1, 2, 3]
example3 = [-1, -3]
print(missing_integer(example1))
print(missing_integer(example2))
print(missing_integer(example3))
"""
5
4
1
""" |
a, b = input().split()
a = int(a)
b = int(b)
if a > b:
print(">")
elif a < b:
print("<")
else:
print("==")
|
n = int(input("Enter a number: "))
for i in range(1, n+1):
count = 0
for j in range(1, n+1):
if i%j==0:
count= count+1
if count==2:
print(i)
|
#what is python
#added by @Dima
print("What is Data Types?")
print("_______________________________________________________")
print("Collections of data put together like array ")
print("________________________________________________________")
print("there are four data types in the Python ")
print("________________________________________________________")
print("""1)--List is a collection which is ordered and changeable.
Allows duplicate members.""")
print("________________________________________________________")
print("""2)--Tuple is a collection which is ordered and unchangeable
Allows duplicate members.""")
print("________________________________________________________")
print("""3)--Set is a collection which is unordered and unindexed.
No duplicate members.""")
print("________________________________________________________")
print("""3)--Dictionary is a collection which is unordered,
changeable and indexed. No duplicate members.""")
input("press close to exit")
|
# V2
"""
02. both_ends
Dada uma string s, retorne uma string feita com os dois primeiros
e os dois ultimos caracteres da string original.
Exemplo: 'spring' retorna 'spng'. Entretanto, se o tamanho da string
for menor que 2, retorne uma string vazia.
"""
def both_ends(string: str) -> str:
# +++ SUA SOLUÇÃO +++
return '' if len(string) < 2 else string[:2] + string[-2:]
# --- Daqui para baixo são apenas códigos auxiliáries de teste. ---
def test(f, in_, expected):
"""
Executa a função f com o parâmetro in_ e compara o resultado com expected.
:return: Exibe uma mensagem indicando se a função f está correta ou não.
"""
out = f(in_)
if out == expected:
sign = '✅'
info = ''
else:
sign = '❌'
info = f'e o correto é {expected!r}'
print(f'{sign} {f.__name__}({in_!r}) retornou {out!r} {info}')
if __name__ == '__main__':
# Testes que verificam o resultado do seu código em alguns cenários.
test(both_ends, 'spring', 'spng')
test(both_ends, 'Hello', 'Helo')
test(both_ends, 'a', '')
test(both_ends, 'xyz', 'xyyz')
|
format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
minimal_format = "%(message)s"
def _get_formatter_and_handler(use_minimal_format: bool = False):
logging_dict = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"colored": {
"()": "coloredlogs.ColoredFormatter",
"format": minimal_format if use_minimal_format else format,
"datefmt": "%m-%d %H:%M:%S",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "colored",
},
},
"loggers": {},
}
return logging_dict
def get_logging_config(django_log_level: str, wkz_log_level: str):
logging_dict = _get_formatter_and_handler()
logging_dict["loggers"] = {
"django": {
"handlers": ["console"],
"level": django_log_level,
},
"wizer": {
"handlers": ["console"],
"level": wkz_log_level,
},
}
return logging_dict
|
#!/bin/python3
# Set .union() Operation
# https://www.hackerrank.com/challenges/py-set-union/problem
if __name__ == '__main__':
n = int(input())
students_n = set(map(int, input().split()))
b = int(input())
students_b = set(map(int, input().split()))
print(len(students_n | students_b)) |
'''
Сортировка
'''
n = int(input())
a = [int(j) for j in input().split()]
a.sort()
print(*a)
|
def ddd():
for i in 'fasdffghdfghjhfgj':
yield i
a = ddd()
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
|
# Customer States
C_CALLING = 0
C_WAITING = 1
C_IN_VEHICLE = 2
C_ARRIVED = 3
C_DISAPPEARED = 4
# Vehicle States
V_IDLE = 0
V_CRUISING = 1
V_OCCUPIED = 2
V_ASSIGNED = 3
V_OFF_DUTY = 4 |
# app seettings
EC2_ACCESS_ID = 'A***Q'
EC2_ACCESS_KEY = 'R***I'
YCSB_SIZE =0
MCROUTER_NOISE = 0
MEMCACHED_OD_SIZE = 1
MEMCACHED_SPOT_SIZE = 0
G_M_MIN = 7.5*1024
G_M_MAX = 7.5*1024
G_C_MIN = 2
G_C_MAX = 2
M_DEFAULT = 7.5*1024
C_DEFAULT = 2
G_M_MIN_2 = 7.5*1024
G_M_MAX_2 = 7.5*1024
G_C_MIN_2 = 2
G_C_MAX_2 = 2
M_DEFAULT_2 = 7.5*1024
C_DEFAULT_2 = 2
|
def avg_grade(name, *args):
if args:
avg = sum(args) / len(args)
print(f'{name}, your average grade is: {avg}')
else:
print(f'No grades available for {name}')
avg_grade('Joe')
avg_grade('Doe', 90, 95, 100)
|
# B_R_R
# M_S_A_W
"""
Coding Problem on Iterators and Generators:
First, using Iterators, we will write a code that pass in a sentence and print out all words in the sentence in line.
Then, we will do the same thing with generators.
"""
class Sentence:
def __init__(self, sentence):
self.sentence=sentence
self.index=0
self.words=self.sentence.split()
def __iter__(self):
return self
def __next__(self):
if self.index>=len(self.words):
raise StopIteration
index=self.index
self.index+=1
return self.words[index]
my_sent=Sentence("Bo nomi parvardigori olamiyon og'oz kardam")
for sent in my_sent:
print(sent)
# Below is generators code:
def my_sentence(sentence):
for word in sentence.split():
yield word
my_sent=my_sentence("Bo nomi Xudovandi Karim sar kardam")
for sent in my_sent:
print(sent)
|
def read_input():
n = int(input())
return (
[input() for _ in range(n)],
input()
)
def find_position(matrix, symbol):
for i in range(len(matrix)):
line = matrix[i]
if symbol in line:
return (i, line.index(symbol))
return None
(matrix, symbol) = read_input()
result = find_position(matrix, symbol)
if result:
(row, col) = result
print(f'({row}, {col})')
else:
print(f'{symbol} does not occur in the matrix')
|
# (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def sanitize_identifier(identifier):
# type: (str) -> str
"""
Get santized identifier name for identifiers which happen to be python
keywords.
"""
keywords = (
"and",
"as",
"assert",
"break",
"class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"exec",
"finally",
"for",
"from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"not",
"or",
"pass",
"print",
"raise",
"return",
"try",
"while",
"with",
"yield",
)
return "{}_".format(identifier) if identifier in keywords else identifier
|
numero = int(input('Digite um número: '))
base = int(input('Entre as opções: '
'\n[1] Binário'
'\n[2] Octal'
'\n[3] Hexadecimal'
'\nQual a base de conversão? '))
if base == 1:
print(f'> {numero} convertido em BINÁRIO = {bin(numero)[2:]}.')
elif base == 2:
print(f'> {numero} convertido para OCTAL = {oct(numero)[2:]}.')
elif base == 3:
print(f'> {numero} convertido para HEXADECIMAL = {hex(numero)[2:]}.')
else:
print('>>> Opção inválida!')
'''O resultado aparece 0b = binario, 0o = octal e 0x = hexa
por isso, se utiliza o conceito de fatiamento em strings,
só que em números.
Exemplo = numero[2:] -> aparece a partir do 2 e vai até o final.''' |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
subboxes = [set() for _ in range(9)]
for i, row in enumerate(board):
for j, elem in enumerate(row):
if elem == '.': continue
if elem in rows[i]: return False
if elem in cols[j]: return False
if elem in subboxes[i // 3 * 3 + j // 3]: return False
rows[i].add(elem)
cols[j].add(elem)
subboxes[i // 3 * 3 + j // 3].add(elem)
return True |
#string: temperatura
Gc = float(input("Digite grados Centigrados: "))
Gk = (Gc + 273.15)
print("el valor de los grados kelvin es el siguiente: ",Gk)
|
class Triangular:
### Constructor ###
def __init__(self, init, end, center=None, peak=1, floor=0):
# initialize attributes
self._init = init
self._end = end
if center:
#using property to test if its bewtween init and end
self.center = center
else:
self._center = (end + init) / 2
self._peak = peak
self._floor = floor
### Desctructor ###
def __close__(self):
# releases attributes
self._init = None
self._end = None
self._center = None
self._peak = None
self._floor = None
### Getters and Setter (as Properties) ###
## init
@property
def init(self):
return self._init
@init.setter
def init(self, init):
if type(init) == float or type(init) == int:
self._init = init
else:
raise ValueError(
'Error: Function initial element must be float or integer')
## end
@property
def end(self):
return self._end
@end.setter
def end(self, end):
if type(end) == float or type(end) == int:
self._end = end
else:
raise ValueError(
'Error: Function end element must be float or integer')
## center
@property
def center(self):
return self._center
@center.setter
def center(self, center):
if type(center) == float or type(center) == int:
if center > self._init and center < self._end:
self._center = center
else:
raise ValueError(
'Error: Center of the function must be between init and end'
)
else:
raise ValueError(
'Error: Function center element must be float or integer')
## peak
@property
def peak(self):
return self._peak
@peak.setter
def peak(self, peak):
if type(peak) == float or type(peak) == int:
self._peak = peak
else:
raise ValueError(
'Error: Function peak element must be float or integer')
## floor
@property
def floor(self):
return self._floor
@floor.setter
def floor(self, floor):
if type(floor) == float or type(floor) == int:
self._floor = floor
else:
raise ValueError(
'Error: Function floor element must be float or integer')
### Methods ###
def function(self, x):
if x <= self._init:
return self._floor
elif x <= self._center:
delta_y = self._peak - self._floor
delta_x = self._center - self._init
slope = delta_y / delta_x
return slope * (x - self._init) + self._floor
elif x <= self._end:
delta_y = self._floor - self._peak
delta_x = self._end - self._center
slope = delta_y / delta_x
return slope * (x - self._center) + self._peak
else:
return self._floor |
current = [0, 1]
someList = []
while True:
for n in range(0, 2):
current[n] += 1
print(current)
someList.append(current[:]) #aqui faz uma cópia da lista e usa referêwncia para esta cópia, não a original
if current == [2, 3]:
break
print(someList)
#https://pt.stackoverflow.com/q/425908/101
|
# Python - 3.6.0
test.describe('Fixed tests')
test.assert_equals(whatday(1), 'Sunday')
test.assert_equals(whatday(2), 'Monday')
test.assert_equals(whatday(3), 'Tuesday')
test.assert_equals(whatday(8), 'Wrong, please enter a number between 1 and 7')
test.assert_equals(whatday(20), 'Wrong, please enter a number between 1 and 7')
|
def last_vowel(s):
"""(str) -> str
Return the last vowel in s if one exists; otherwise, return None.
>>> last_vowel("cauliflower")
"e"
>>> last_vowel("pfft")
None
"""
i = len(s) - 1
while i >= 0:
if s[i] in 'aeiouAEIOU':
return s[i]
i = i - 1
return None
def get_answer(prompt):
''' (str) -> str
Use prompt to ask the user for a "yes" or "no"
answer and continue asking until the user gives a valid response. Return the answer.
'''
answer = input(prompt)
while not (answer == 'yes' or answer == 'no'):
answer = input(prompt)
return answer
def up_to_vowel(s):
''' (str) -> str
Return a substring of a s from index 0 up to but not including the first bowel in s.
>>> up_to_vowel('hello')
'h'
>>> up_to_vowel('there')
'th'
>>> up_to_vowel('cs')
'cs'
'''
before_vowel = ''
i = 0
while i < len(s) and not (s[i] in 'aeiouAEIOU'):
before_vowel = before_vowel + s[i]
i = i + 1
return before_vowel
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
'''
list
'''
print("==========list=============")
students = ["jack", "tony", "john"]
students.append("kevin")
students.insert(1, "lisa")
students.pop()
students.pop(0)
print(students)
print(len(students))
print(students[0])
print(students[-1])
'''
tuple
'''
print("\n==========tuple=============")
t = (1, 2, 3, 4, 5, [6, 7])
print(t[2])
print(t[-1])
t[-1][1] = 8
print(t)
'''
练习
'''
print("\n==========练习=============")
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
print(L[0][0])
print(L[1][1])
print(L[-1][-1])
|
#
# PySNMP MIB module TPLINK-PORTMIRROR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-PORTMIRROR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, TimeTicks, Counter32, Gauge32, IpAddress, Unsigned32, Counter64, Bits, iso, ObjectIdentity, MibIdentifier, NotificationType, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "TimeTicks", "Counter32", "Gauge32", "IpAddress", "Unsigned32", "Counter64", "Bits", "iso", "ObjectIdentity", "MibIdentifier", "NotificationType", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
tplinkMgmt, = mibBuilder.importSymbols("TPLINK-MIB", "tplinkMgmt")
tplinkPortMirrorMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11863, 6, 11))
tplinkPortMirrorMIB.setRevisions(('2012-12-14 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: tplinkPortMirrorMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: tplinkPortMirrorMIB.setLastUpdated('201212140000Z')
if mibBuilder.loadTexts: tplinkPortMirrorMIB.setOrganization('TPLINK')
if mibBuilder.loadTexts: tplinkPortMirrorMIB.setContactInfo('www.tplink.com.cn')
if mibBuilder.loadTexts: tplinkPortMirrorMIB.setDescription('The config of the port mirror.')
tplinkPortMirrorMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1))
tplinkPortMirrorMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11863, 6, 11, 2))
tpPortMirrorTable = MibTable((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1), )
if mibBuilder.loadTexts: tpPortMirrorTable.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorTable.setDescription('')
tpPortMirrorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1), ).setIndexNames((0, "TPLINK-PORTMIRROR-MIB", "tpPortMirrorSession"))
if mibBuilder.loadTexts: tpPortMirrorEntry.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorEntry.setDescription('')
tpPortMirrorSession = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tpPortMirrorSession.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorSession.setDescription('This object indicates the session number of the mirror group.')
tpPortMirrorDestination = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 2), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpPortMirrorDestination.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorDestination.setDescription(' This object indicates a destination port which monitors specified ports on the switch, should be given as 1/0/1. Note: The member of LAG cannot be assigned as a destination port.')
tpPortMirrorIngressSource = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpPortMirrorIngressSource.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorIngressSource.setDescription(" This object indicates a list of the source ports. Any packets received from these ports will be copyed to the assigned destination port. This should be given as 1/0/1,1/0/2-12. Note: The ports in other sessions and destination port can't add to this list.")
tpPortMirrorEgressSource = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 4), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpPortMirrorEgressSource.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorEgressSource.setDescription(" This object indicates a list of the source ports. Any packets sended out from these ports will be copyed to the assigned destination ports.This should be given as 1/0/1,1/0/2-12. Note: The ports in other sessions and destination port can't add to this list.")
tpPortMirrorBothSource = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 5), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpPortMirrorBothSource.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorBothSource.setDescription(" This object indicates a list of the source ports. Any packets received or sended out from these ports will be copyed to the assigned destination ports.This should be given as 1/0/1,1/0/2-12. Note: The ports in other sessions and destination port can't add to this list.")
tpPortMirrorSessionState = MibTableColumn((1, 3, 6, 1, 4, 1, 11863, 6, 11, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("negative", 1), ("active", 2), ("clear", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tpPortMirrorSessionState.setStatus('current')
if mibBuilder.loadTexts: tpPortMirrorSessionState.setDescription(' This object indicates the state of mirror session.If a session has been assigned both destination port and source ports, then the value of this object changes to active(2). Otherwise the value of this object is to be negative(1). When the value of this object is assigned to clear(3), then the configuration of this session will be cleared, and the state changes to negative(1). Be aware of that only clear(3) can be assigned to this object.')
mibBuilder.exportSymbols("TPLINK-PORTMIRROR-MIB", tpPortMirrorIngressSource=tpPortMirrorIngressSource, tpPortMirrorTable=tpPortMirrorTable, tpPortMirrorBothSource=tpPortMirrorBothSource, tplinkPortMirrorMIBNotifications=tplinkPortMirrorMIBNotifications, tpPortMirrorEgressSource=tpPortMirrorEgressSource, tpPortMirrorSessionState=tpPortMirrorSessionState, tplinkPortMirrorMIBObjects=tplinkPortMirrorMIBObjects, tpPortMirrorEntry=tpPortMirrorEntry, tpPortMirrorDestination=tpPortMirrorDestination, tplinkPortMirrorMIB=tplinkPortMirrorMIB, tpPortMirrorSession=tpPortMirrorSession, PYSNMP_MODULE_ID=tplinkPortMirrorMIB)
|
File = open("File PROTEK/Data2.txt", "w")
while True:
nim = input('Masukan NIM:')
nama = input('Masukan Nama:')
alamat = input('Masukan Alamat:')
print('')
File.write(nim + '|' + nama + '|' + alamat + '\n')
repeat = input('Apakah ingin memasukan data lagi?(y/n):')
print('')
if(repeat in {'n','N'}):
File.close()
break
|
# 看了Topics知道这个是用栈来解决的题目。看了别人的解答才明白怎么回事。
#
# 使用一个栈作为辅助,遍历数字字符串,当当前的字符比栈最后的字符小的时候,说明要把栈的最后的这个字符删除掉。为什么呢?你想,把栈最后的字符删除掉,然后用现在的字符进行替换,是不是数字比以前的那种情况更小了?所以同样的道理,做一个while循环!这个很重要,可是我没有想到。在每一个数字处理的时候,都要做一个循环,使得栈里面最后的数字比当前数字大的都弹出去。
#
# 最后,如果K还没用完,那要删除哪里的字符呢?毋庸置疑肯定是最后的字符,因为前面的字符都是小字符。
class Solution:
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
stack = []
if k > len(num):
return ''
elif k == len(num):
return '0'
for n in num:
while stack and k and stack[-1] > n:
stack.pop()
k -= 1
stack.append(n)
while k:
stack.pop()
k -= 1
return str(int(''.join(stack)))
s = Solution()
s.removeKdigits("1432219", 3)
|
# Lv-677_Ivan_Vaulin
# Task2. Write a script that checks the login that the user enters.
# If the login is "First", then greet the users. If the login is different, send an error message.
# (need to use loop while)
user_name = input('Hello, please input your Log in:')
while user_name != 'First':
user_name = input('Error: wrong username, please try one more time. Username:')
else:
print('Greeting. Access granted!!!', user_name) |
n = input('Digite algo:\n')
print('O tipo primitivo do que foi digitado é:', type(n))
print('Só tem epaços?', (n.isspace()))
print('Só tem números?', (n.isnumeric()))
print(n.isalpha())
print(n.isalnum())
print(n.isupper())
print(n.islower())
print(n.istitle())
|
# 读取data.txt文件中 数据如下:
# 小张 13888888888
# 小李 13999999999
# 小赵 13777777777
# 写程序读取数据,打印出姓名和电话号码
try:
f = open('data.txt', 'rt', encoding='utf-8') # 设置编码
while True:
s = f.readline()
if not s:
break
s = s.rstrip().lstrip() # 去掉左右的空格、制表符、换行符等
info = s.split(' ')
print("姓名:%s,电话:%s" % (info[0], info[1])) # 过滤掉空格 换行等
f.close()
except IOError:
pass
|
"""
1272. Remove Interval
Medium
Given a sorted list of disjoint intervals, each interval intervals[i] = [a, b] represents the set of real numbers x such that a <= x < b.
We remove the intersections between any interval in intervals and the interval toBeRemoved.
Return a sorted list of intervals after all such removals.
Example 1:
Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output: [[0,1],[6,7]]
Example 2:
Input: intervals = [[0,5]], toBeRemoved = [2,3]
Output: [[0,2],[3,5]]
Example 3:
Input: intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
Output: [[-5,-4],[-3,-2],[4,5],[8,9]]
Constraints:
1 <= intervals.length <= 10^4
-10^9 <= intervals[i][0] < intervals[i][1] <= 10^9
"""
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
res = []
for a, b in intervals:
if a < toBeRemoved[0]:
res.append([a, min(b, toBeRemoved[0])])
if b > toBeRemoved[1]:
res.append([max(a, toBeRemoved[1]), b])
return res
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
res = []
for a, b in intervals:
if a < toBeRemoved[0]:
res += [a, min(b, toBeRemoved[0])],
if b > toBeRemoved[1]:
res += [max(a, toBeRemoved[1]), b],
return res |
# -*- coding: UTF-8 -*-
# Copyright 2013 Felix Friedrich, Felix Schwarz
# Copyright 2015, 2019 Felix Schwarz
# The source code in this file is licensed under the MIT license.
# SPDX-License-Identifier: MIT
__all__ = ['Result']
class Result(object):
def __init__(self, value, **data):
self.value = value
self.data = data
def __repr__(self):
klassname = self.__class__.__name__
extra_data = [repr(self.value)]
for key, value in sorted(self.data.items()):
extra_data.append('%s=%r' % (key, value))
return '%s(%s)' % (klassname, ', '.join(extra_data))
def __eq__(self, other):
if isinstance(other, self.value.__class__):
return self.value == other
elif hasattr(other, 'value'):
return self.value == other.value
return False
def __ne__(self, other):
return not self.__eq__(other)
def __bool__(self):
return bool(self.value)
# Python 2 compatibility
__nonzero__ = __bool__
def __len__(self):
return len(self.value)
def __getattr__(self, key):
if key in self.data:
return self.data[key]
elif key.startswith('set_'):
attr_name = key[4:]
if attr_name in self.data:
return self.__build_setter(attr_name)
klassname = self.__class__.__name__
msg = '%r object has no attribute %r' % (klassname, key)
raise AttributeError(msg)
def __build_setter(self, attr_name):
def setter(value):
self.data[attr_name] = value
setter.__name__ = 'set_'+attr_name
return setter
def __setattr__(self, key, value):
if key in ('data', 'value'):
# instance attributes, set by constructor
self.__dict__[key] = value
return
if key not in self.data:
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, key))
setter = getattr(self, 'set_'+key)
setter(value)
|
#
# Runtime: 44 ms, faster than 96.86% of Python3 online submissions for Flatten Binary Tree to Linked List.
# Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Flatten Binary Tree to Linked List.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: 'TreeNode') -> 'None':
"""
Do not return anything, modify root in-place instead.
"""
if not root: return None
self.flatten(root.left)
self.flatten(root.right)
tmp = root
if not tmp.left: return None # 节点的左指针为空不执行
tmp = tmp.left #
while tmp.right: tmp = tmp.right
tmp.right = root.right #
root.right = root.left # 左指针转换到右边
root.left = None # 节点左指针置空
'''
前序遍历(中左右)
'''
|
"""
Refaça o Exercício 009, mostrando a tabuada de um número que o usuário
escolher, só que agora utilizando um laço for.
"""
n = int(input('Digite um número inteiro: '))
print('='*20)
print('> Tabuada do {}'.format(n))
for c in range(1, 11):
print('\t{} X {} = {}'.format(n, c, n * c))
print('='*20)
|
# Test that systemctl will accept service names both with or without suffix.
def test_dot_service(sysvenv):
service = sysvenv.create_service("foo")
service.will_do("status", 3)
service.direct_enable()
out, err, status = sysvenv.systemctl("status", "foo.service")
assert status == 3
assert service.did("status")
|
#!/usr/bin/python3
# 9x9 values in a sudoku
COUNT_NUMBERS = int(9)
"""
a sudoku of indices, columns and rows
colum 0 1 2 3 4 5 6 7 8 | row
________________________________________________|_____
sudoku = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, | 0
9, 10, 11, 12, 13, 14, 15, 16, 17, | 1
18, 19, 20, 21, 22, 23, 24, 25, 26, | 2
27, 28, 29, 30, 31, 32, 33, 34, 35, | 3
36, 37, 38, 39, 40, 41, 42, 43, 44, | 4
45, 46, 47, 48, 49, 50, 51, 52, 53, | 5
54, 55, 56, 57, 58, 59, 60, 61, 62, | 6
63, 64, 65, 66, 67, 68, 69, 70, 71, | 7
72, 73, 74, 75, 76, 77, 78, 79, 80 | 8
]
"""
# the sudoku puzzle | 0 == unset
sudoku = [ 5, 3, 0, 0, 7, 0, 0, 0, 0,
6, 0, 0, 1, 9, 5, 0, 0, 0,
0, 9, 8, 0, 0, 0, 0, 6, 0,
8, 0, 0, 0, 6, 0, 0, 0, 3,
4, 0, 0, 8, 0, 3, 0, 0, 1,
7, 0, 0, 0, 2, 0, 0, 0, 6,
0, 6, 0, 0, 0, 0, 2, 8, 0,
0, 0, 0, 4, 1, 9, 0, 0, 5,
0, 0, 0, 0, 8, 0, 0, 7, 9 ]
# contains all possible solutions to given sudoku puzzle
solved_sudokus = []
# returns the row and column number of given index
def get_row_column_from_index(index):
row = index // COUNT_NUMBERS
column = index - (row * COUNT_NUMBERS)
return row, column
# returns the index given by row and column
def get_index_from_row_column(row, column):
return row * COUNT_NUMBERS + column
# returns the row number index at index of sudoku
def get_row_index(index):
return index // COUNT_NUMBERS
# returns the column number index at index of sudoku
def get_column_index(index):
return int(index % COUNT_NUMBERS)
# returns a horizontal subset of the sudoku at index position (row)
def get_horizontal_slice_by(index, grid=sudoku):
row_index = get_row_index(index) * COUNT_NUMBERS
values = grid[row_index : row_index + COUNT_NUMBERS]
return values
# returns a vertical subset of the sudoku at index position (column)
def get_vertical_slice_by(index, grid=sudoku):
col = get_column_index(index)
values = [grid[x * COUNT_NUMBERS + col] for x in range(COUNT_NUMBERS)]
return values
# returns a 3x3 subset of the sudoku at index position
def get_3x3_slice_by(index, grid=sudoku):
col_start = (get_column_index(index) // 3) * 3
row_start = (get_row_index(index) // 3) * 3
start = row_start * COUNT_NUMBERS + col_start
values = []
for row in range(3):
for col in range(3):
i = start + (COUNT_NUMBERS * row) + col
values.append(grid[i])
return values
# def is_possible(row, column, number, grid=sudoku):
# check row
for i in range(9):
if grid[row * COUNT_NUMBERS + i] == number:
return False
# check column
for i in range(9):
if grid[column + COUNT_NUMBERS * i] == number:
return False
# check 3x3 area
col0 = (column//3)*3
row0 = (row//3)*3
for r in range(3):
for c in range(3):
if grid[(row0 + r) * COUNT_NUMBERS + (col0 + c)] == number:
return False
return True
# checks if it's possible to put given number into sudoku at given index
def is_possible(index, number, grid=sudoku):
if number in get_horizontal_slice_by(index, sudoku):
return False
elif number in get_vertical_slice_by(index, sudoku):
return False
elif number in get_3x3_slice_by(index, sudoku):
return False
else:
return True
# print sudoku visually as 9x9 grid
def print_sudoku(grid=sudoku, ending=""):
for i,value in enumerate(grid):
val = f"{value:<2}"
# horizontal separator
if i!=0 and not (i/9)%3:
print(f"\n{'– '*16}\n{val}", end=" ")
# print row
elif not i%9:
print(f"\n{val}", end=" ")
# print 3x3 seperator
elif not i%3:
print(f"|{val:>4}", end=" ")
# just print value
else:
print(f"{val}", end=" ")
print(f"\n{ending}")
# solve sudoku puzzle via backtracking and recursion
def solve(grid=sudoku):
for row in range(COUNT_NUMBERS):
for column in range(COUNT_NUMBERS):
index = get_index_from_row_column(row, column)
if grid[index] == 0:
for n in range(1, 10):
if is_possible(index=index, number=n, grid=sudoku):
grid[index] = n
solve(grid=sudoku)
grid[index] = 0
return
solved_sudokus.append(grid.copy())
# main function, will solve sudoku puzzle
def main():
solve(sudoku)
count = len(solved_sudokus)
multiple = count > 1
print(f"There {'are' if multiple else 'is'} {count} soluiton{'s' if multiple else ''}")
for s in solved_sudokus:
print(f"\n{count}. solution:")
print_sudoku(s)
# running main function
if __name__ == "__main__":
main()
|
num_list = []
num_list.append(1)
num_list.append(2)
num_list.append(3)
print(num_list[1]) |
class BaseModule:
"""
Base module class to be extended by feature modules.
"""
command_char = ''
# To be updated in subclasses
module_name = ''
module_description = ''
commands = []
def __init__(self, user_cmd_char):
"""
Sets command prefix while initializing.
:param user_cmd_char: command prefix.
"""
self.command_char = user_cmd_char
def get_module_name(self):
"""
Returns name of the module.
:return: name of the module in string.
"""
return self.module_name
def get_module_description(self):
"""
Returns description of the module.
:return: description of the module in string.
"""
return self.module_description
def get_all_commands(self):
"""
Returns all commands of the module.
:return: commands of the module in string list.
"""
return self.commands
async def parse_command(self, bundle):
"""
Decides which command should be executed and calls it.
To be implemented on subclasses.
:param bundle Dictionary passed in from caller.
:return: no return value.
"""
pass
|
#!/usr/bin/env python
# Paths
VIDEOS_PATH = '~/Desktop/Downloaded Youtube Videos'
VIDEOS_PATH_WIN = '/mnt/e/Alex/Videos/Youtube'
|
# Variables that contain the user credentials to access Twitter API
ACCESS_TOKEN ="< Enter your Twitter Access Token >"
ACCESS_TOKEN_SECRET ="< Enter your Access Token Secret >"
CONSUMER_KEY = "< Enter Consumer Key >"
CONSUMER_SECRET = "< Enter Consumer Key Secret >" |
""" https://adventofcode.com/2018/day/4 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
l = [line[:-1] for line in f.readlines()]
l.sort()
return l
class Guard:
def __init__(self, id):
self.id = int(id)
self.idStr = id
self.timeAsleep = 0
self.minutes = [0 for min in range(60)]
def sleep(self, start, end):
self.timeAsleep += (end - start)
for i in range(start, end):
self.minutes[i] += 1
def evaluateLines(vals : list):
curID = -1
start = -1
guards = {}
for val in vals:
timestamp = val[1:17]
event = val[19:]
if "#" in event:
curID = event.split()[1][1:]
if curID not in guards:
guards[curID] = Guard(curID)
elif event == "falls asleep":
start = int(timestamp[14:16])
else: # event == "wakes up"
end = int(timestamp[14:16])
guards[curID].sleep(start, end)
return guards
def part1(guards : dict):
maxID = ""
maxSleep = 0
for guard in guards:
if guards[guard].timeAsleep > maxSleep:
maxSleep = guards[guard].timeAsleep
maxID = guard
guard = guards[maxID]
return guard.id * guard.minutes.index(max(guard.minutes))
def part2(guards : dict):
maxID = ""
maxAmount = 0
for guard in guards:
cur = max(guards[guard].minutes)
if cur > maxAmount:
maxAmount = cur
maxID = guard
guard = guards[maxID]
return guard.id * guard.minutes.index(max(guard.minutes))
if __name__ == "__main__":
vals = readFile()
guards = evaluateLines(vals)
print(f"Part 1: {part1(guards)}")
print(f"Part 2: {part2(guards)}") |
RESPONSE_MOCK = [
{
"request_id": "REQUEST_UUID",
"results": [
{
"company_id": "COMPANY_UUID",
"companies": [
{
"cnpj": "CNPJ DA EMPRESA",
"company_name": "Razão Social",
"trading_name": "Nome fantasia",
"email": "[email protected]",
"phone": "Telefone da empresa",
"address_street": "ENDEREÇO SEM O NUMERO",
"address_number": "NUMERO",
"address_complement": "COMPLEMENTO",
"address_district": "BAIRRO",
"address_zipcode": "CEP",
"address_region": "ESTADO",
"address_country": "PAÍS DE ORIGEM",
"qsa": [
{
"first_name": "Primeiro nome",
"last_name": "Ultimo nome",
"qual": "Função do sócio na empresa"
}
]
}
]
}
]
},
{
"request_id": "REQUEST_UUID2",
"results": [
{
"company_id": "COMPANY_UUID",
"companies": [
{
"cnpj": "CNPJ DA EMPRESA",
"company_name": "Razão Social",
"trading_name": "Nome fantasia",
"email": "[email protected]",
"phone": "Telefone da empresa",
"address_street": "ENDEREÇO SEM O NUMERO",
"address_number": "NUMERO",
"address_complement": "COMPLEMENTO",
"address_district": "BAIRRO",
"address_zipcode": "CEP",
"address_region": "ESTADO",
"address_country": "PAÍS DE ORIGEM",
"qsa": [
{
"first_name": "Primeiro nome",
"last_name": "Ultimo nome",
"qual": "Função do sócio na empresa"
}
]
}
]
}
]
},
]
|
ft_name = 'points'
featuretype_api = datastore_api.featuretype(name=ft_name, data={
"featureType": {
"circularArcPresent": False,
"enabled": True,
"forcedDecimal": False,
"maxFeatures": 0,
"name": ft_name,
"nativeName": ft_name,
"numDecimals": 0,
"overridingServiceSRS": False,
"padWithZeros": False,
"projectionPolicy": "FORCE_DECLARED",
"serviceConfiguration": False,
"skipNumberMatched": False,
"srs": "EPSG:404000",
"title": ft_name,
"attributes": {
"attribute": {
"binding": "java.lang.String",
"maxOccurs": 1,
"minOccurs": 0,
"name": "point",
"nillable": True
}
},
"keywords": {
"string": [
"features",
ft_name
]
},
"latLonBoundingBox": {
"maxx": -68.036694,
"maxy": 49.211179,
"minx": -124.571077,
"miny": 25.404663,
"crs": "EPSG:4326"
},
"nativeBoundingBox": {
"minx": -90,
"maxx": 90,
"miny": -180,
"maxy": 180,
"crs": "EPSG:4326"
},
}
}) |
# Time: O(k * n^2)
# Space: O(n^2)
class Solution(object):
def knightProbability(self, N, K, r, c):
"""
:type N: int
:type K: int
:type r: int
:type c: int
:rtype: float
"""
directions = \
[[ 1, 2], [ 1, -2], [ 2, 1], [ 2, -1], \
[-1, 2], [-1, -2], [-2, 1], [-2, -1]]
dp = [[[1 for _ in xrange(N)] for _ in xrange(N)] for _ in xrange(2)]
for step in xrange(1, K+1):
for i in xrange(N):
for j in xrange(N):
dp[step%2][i][j] = 0
for direction in directions:
rr, cc = i+direction[0], j+direction[1]
if 0 <= cc < N and 0 <= rr < N:
dp[step%2][i][j] += 0.125 * dp[(step-1)%2][rr][cc]
return dp[K%2][r][c]
|
class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:
step = sign = 1
result = [[r0, c0]]
r, c = r0, c0
while len(result) < R*C:
for _ in range(step):
c += sign
if 0 <= r < R and 0 <= c < C:
result.append([r, c])
for _ in range(step):
r += sign
if 0 <= r < R and 0 <= c < C:
result.append([r, c])
step += 1
sign *= -1
return result
|
# -*- coding: utf-8 -*-
def includeme(config):
config.register_service_factory('.services.user.rename_user_factory', name='rename_user')
config.include('.views')
config.add_route('admin_index', '/')
config.add_route('admin_admins', '/admins')
config.add_route('admin_badge', '/badge')
config.add_route('admin_features', '/features')
config.add_route('admin_cohorts', '/features/cohorts')
config.add_route('admin_cohorts_edit', '/features/cohorts/{id}')
config.add_route('admin_groups', '/groups')
config.add_route('admin_groups_csv', '/groups.csv')
config.add_route('admin_nipsa', '/nipsa')
config.add_route('admin_staff', '/staff')
config.add_route('admin_users', '/users')
config.add_route('admin_users_activate', '/users/activate')
config.add_route('admin_users_delete', '/users/delete')
config.add_route('admin_users_rename', '/users/rename')
|
## Iterative approach - BFS - Using Queue
# 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 invertTree(self, root: TreeNode) -> TreeNode:
# ITERATIVE - USING QUEUE
if root is None: return None
queue = deque([root])
while queue:
current = queue.popleft()
current.left, current.right = current.right, current.left
if current.left:
queue.append(current.left)
if current.right:
queue.append(current.right)
return root
|
"""
Given the root of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if there the node does not have a right child.
Example 1:
Input: root = [1,2,3]
Output: 1
Explanation:
Tilt of node 2 : |0-0| = 0 (no children)
Tilt of node 3 : |0-0| = 0 (no children)
Tile of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)
Sum of every tilt : 0 + 0 + 1 = 1
Example 2:
Input: root = [4,2,9,3,5,null,7]
Output: 15
Explanation:
Tilt of node 3 : |0-0| = 0 (no children)
Tilt of node 5 : |0-0| = 0 (no children)
Tilt of node 7 : |0-0| = 0 (no children)
Tilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)
Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)
Tilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)
Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15
Example 3:
Input: root = [21,7,14,1,1,2,2,3,3]
Output: 9
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def find_tilt(root):
if root is None:
return 0, 0
lstilt, ls = find_tilt(root.left)
rstilt, rs = find_tilt(root.right)
return abs(ls - rs) + lstilt + rstilt, ls + rs + root.val
stilt, s = find_tilt(root)
return stilt |
class ExtractJSON:
@staticmethod
def get_json(path:str) -> str:
"""
Return an extract JSON from a file
"""
try:
return open(path, "r").readlines()[0]
except ValueError:
print("ERROR: file not found.")
exit(-1)
return None |
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles.append('honda')
print(motorcycles)
motorcycles = []
motorcycles.append('suzuki')
motorcycles.append('honda')
motorcycles.append('bmw')
print(motorcycles)
motorcycles.insert(0, 'ducati')
print(motorcycles)
motorcycles.insert(2, 'yamaha')
print(motorcycles)
del motorcycles[3]
print(motorcycles)
print('\npop example')
popped = motorcycles.pop()
print(motorcycles)
print(popped)
print('\npop from first position')
popped = motorcycles.pop(0)
print(motorcycles)
print(popped)
print('\nappend at the end and remove by value: only removes first ocurrence')
motorcycles.append('suzuki')
motorcycles.remove('suzuki')
print(motorcycles)
print('\nremove by value using var')
remove_this = 'yamaha'
motorcycles.remove(remove_this)
print(motorcycles)
|
# -*- coding: utf-8 -*-
class StaticBase(object):
"""
Base class for StaticModel framework class.
.. todo::
KDJ: What is the reason this class exists? Can it be merged with
StaticModel?
"""
def __init__(self):
if self.__class__ is StaticBase:
raise NotImplementedError
self.inInitial = False
def initial(self):
""" """
msg = "Class needs to implement 'initial' method"
raise NotImplementedError(msg)
def setDebug(self):
""" """
msg = "Class needs to implement 'setDebug' method"
raise NotImplementedError(msg)
def _inInitial(self):
return self.inInitial
def _setInInitial(self,
value):
assert isinstance(value, bool)
self.inInitial = value
|
#
# PySNMP MIB module HP-ICF-LAYER3VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-LAYER3VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:21:56 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion")
hpSwitch, = mibBuilder.importSymbols("HP-ICF-OID", "hpSwitch")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
Gauge32, TimeTicks, Bits, Unsigned32, Counter32, ObjectIdentity, Integer32, IpAddress, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, ModuleIdentity, NotificationType, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "TimeTicks", "Bits", "Unsigned32", "Counter32", "ObjectIdentity", "Integer32", "IpAddress", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "ModuleIdentity", "NotificationType", "MibIdentifier")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
hpicfLayer3VlanConfigMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70))
hpicfLayer3VlanConfigMIB.setRevisions(('2010-03-23 00:00',))
if mibBuilder.loadTexts: hpicfLayer3VlanConfigMIB.setLastUpdated('201003230000Z')
if mibBuilder.loadTexts: hpicfLayer3VlanConfigMIB.setOrganization('HP Networking')
hpicfLayer3VlanConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 1))
hpicfLayer3VlanConfigConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 2))
hpicfLayer3VlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 1, 1), )
if mibBuilder.loadTexts: hpicfLayer3VlanConfigTable.setStatus('current')
hpicfLayer3VlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hpicfLayer3VlanConfigEntry.setStatus('current')
hpicfLayer3VlanStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpicfLayer3VlanStatus.setStatus('current')
hpicfL3VlanConfigMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 2, 1))
hpicfLayer3VlanConfigMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 2, 2))
hpicfL3VlanConfigMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 2, 1, 1)).setObjects(("HP-ICF-LAYER3VLAN-MIB", "hpicfLayer3VlanConfigGroup"), ("HP-ICF-LAYER3VLAN-MIB", "hpicfLayer3VlanConfigGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfL3VlanConfigMIBCompliance = hpicfL3VlanConfigMIBCompliance.setStatus('current')
hpicfLayer3VlanConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 5, 1, 70, 2, 2, 1)).setObjects(("HP-ICF-LAYER3VLAN-MIB", "hpicfLayer3VlanStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
hpicfLayer3VlanConfigGroup = hpicfLayer3VlanConfigGroup.setStatus('current')
mibBuilder.exportSymbols("HP-ICF-LAYER3VLAN-MIB", hpicfLayer3VlanConfig=hpicfLayer3VlanConfig, PYSNMP_MODULE_ID=hpicfLayer3VlanConfigMIB, hpicfLayer3VlanConfigTable=hpicfLayer3VlanConfigTable, hpicfLayer3VlanConfigConformance=hpicfLayer3VlanConfigConformance, hpicfLayer3VlanConfigGroup=hpicfLayer3VlanConfigGroup, hpicfLayer3VlanStatus=hpicfLayer3VlanStatus, hpicfL3VlanConfigMIBCompliance=hpicfL3VlanConfigMIBCompliance, hpicfLayer3VlanConfigMIB=hpicfLayer3VlanConfigMIB, hpicfLayer3VlanConfigEntry=hpicfLayer3VlanConfigEntry, hpicfLayer3VlanConfigMIBGroups=hpicfLayer3VlanConfigMIBGroups, hpicfL3VlanConfigMIBCompliances=hpicfL3VlanConfigMIBCompliances)
|
class BaseClient(object):
def __init__(self, username, password, randsalt):
## password = {MD5(pwrd) for old clients, SHA256(pwrd + salt) for new clients}
## randsalt = {"" for old clients, random 16-byte binary string for new clients}
## (here "old" means user was registered over an unencrypted link, without salt)
self.set_user_pwrd_salt(username, (password, randsalt))
## note: do not call on Client instances prior to login
def has_legacy_password(self):
return (len(self.randsalt) == 0)
def set_user_pwrd_salt(self, user_name = "", pwrd_hash_salt = ("", "")):
assert(type(pwrd_hash_salt) == tuple)
self.username = user_name
self.password = pwrd_hash_salt[0]
self.randsalt = pwrd_hash_salt[1]
def set_pwrd_salt(self, pwrd_hash_salt):
assert(type(pwrd_hash_salt) == tuple)
self.password = pwrd_hash_salt[0]
self.randsalt = pwrd_hash_salt[1]
|
# %% [696. *Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/)
# 問題:正規表現'(0+1+|1+0+)'にマッチする個数を返せ。ただし0と1は同数とする
# 解法:itertools.groupbyを用いる
class Solution:
def countBinarySubstrings(self, s: str) -> int:
lst = [len(list(g)) for _, g in itertools.groupby(s)]
return sum(min(i, j) for i, j in zip(lst, lst[1:]))
|
TITLE = "Metadata extractor"
SAVE = "Save"
OPEN = "Open"
EXTRACT = "Extract"
DELETE = "Delete"
META_TITLE = "title"
META_NAMES = "names"
META_CONTENT = "content"
META_LOCATIONS = "locations"
META_KEYWORD = "keyword"
META_REF = "reference"
TYPE_TXT = "txt"
TYPE_ISO19115v2 = "iso19115v2"
TYPE_FGDC = "fgdc"
LABLE_NAME = "Name"
LABLE_ORGANISATION = "Organisation"
LABLE_PHONE = "Phone"
LABLE_FACS = "Facs"
LABLE_DELIVERY_POINT = "Delivery point"
LABLE_CITY = "City"
LABLE_AREA = "Area"
LABLE_POSTAL_CODE = "Postal code"
LABLE_COUNTRY = "Country"
LABLE_EMAIL = "Email"
LABLE_TYPE = "Type"
LABLE_WEST = "West"
LABLE_EAST = "East"
LABLE_NORTH = "North"
LABLE_SOUTH = "South"
LABLE_LINK = "Link"
LABLE_ORIGIN = "Origin"
LABLE_TITLE = "Title"
LABLE_DATE = "Date"
LABLE_DATE_BEGIN = "Date begin"
LABLE_DATE_END = "Date end"
LABLE_DESCRIPT_ABSTRACT = "Abstract"
LABLE_DESCRIPT_PURPOSE = "Purpose"
LABLE_DESCRIPT_SUPPLEMENTAL = "Supplemental"
LABLE_STATUS_PROGRESS = "Progress"
LABLE_POSTAL_STATUS_UPDATE = "Update"
LABLE_ACCESS = "Access"
LABLE_UUID = "UUID"
LABLE_CB_UUID = "Generate random UUID"
LABLE_LOCATION = "Locations"
LABLE_KEY_WORD = "Key words"
DIALOG_TITLE_ABOUT = "About"
DIALOG_TITLE_SETTINGS = "Settings"
DIALOG_BTN_OK = "OK"
LABLE_ABOUT_NAME = "Name"
LABLE_ABOUT_VERSION = "Version"
LABLE_ABOUT_AUTHOR = "Author"
LABLE_HOME_PAGE = "Home page"
TOOLTIP_DELETE_ELEMENT = "Delete element"
TOOLTIP_ADD_REFERENCE = "Add reference"
TOOLTIP_ADD_LOCATION = "Add location"
TOOLTIP_ADD_KEYWORD = "Add keyword"
TOOLTIP_ADD_PERSON = "Add person"
TOOLTIP_OPEN_PDF = "Open PDF"
TOOLTIP_SAVE_METADATA = "Save metadata"
TOOLTIP_EXTRACT_METADATA = "Extract metadata"
TAB_CONTROL = "Control"
TAB_INFO = "Info"
TAB_CONTACT = "Contact"
TAB_PERSON = "Person"
TAB_KEYWORD = "Keyword"
TAB_LOCATION = "Location"
TAB_REFERENCE = "Reference"
BTN_ADD = "Add"
MENU_ABOUT = "About"
MENU_EXIT = "Exit"
MENU_FILE = "&File"
MENU_QUESTION = "&?"
MENU_HELP = "Help"
MENU_LOAD = "Load"
MENU_FILE_LOAD = "Load file"
MENU_EXTRACT = "Extract"
MENU_SAVE = "Save"
MENU_OPEN = "Open"
MENU_SETTINGS = "Settings"
MENU_TOOLTIP_HELP = "Help"
MENU_TOOLTIP_ABOUT = "About"
MENU_TOOLTIP_OPEN_PDF = "Open pdf file"
MENU_TOOLTIP_LOAD_METADATA = "Load metadata"
MENU_TOOLTIP_LOAD_FILE_METADATA = "Load file metadata"
MENU_TOOLTIP_EXTRACT_METADATA = "Extract metadata"
MENU_TOOLTIP_SAVE_METADATA = "Save file with metadata"
MENU_TOOLTIP_EXIT = "Exit application"
MENU_TOOLTIP_SETTINGS = "Settings"
ICON_CLOSE = "data/icons/close.png"
ICON_OPEN = "data/icons/open.png"
ICON_SAVE = "data/icons/save.png"
ICON_PROCESS = "data/icons/process.png"
ICON_LOAD = "data/icons/load.png"
|
# ORDENANDO UMA LISTA DE FORMA PERMANENTE COM O MÉTODO sort()
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# ORDENANDO UMA LISTA EM ORDEM ALFABÉTICA INVERSA
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
# ORDENANDO UMA LISTA TEMPORARIAMENTE COM O MÉTODO sorted()
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
# EXIBINDO UMA LISTA EM ORDEM INVERSA
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse() # o método reverse() muda a ordem da lista permanentemente
print(cars) # basta usar o método um segunda vez restaurar a ordem.
# DESCOBRINDO O TAMANHO DE UMA LISTA
cars = ['bmw', 'audi', 'toyota', 'subaru'] # rodar no IDLE do python
len(cars) |
class SpaceAge(object):
def __init__(self, seconds):
self.seconds = seconds
def on_earth(self):
return round(self.seconds / 31557600, 2)
def on_mercury(self):
earth = self.on_earth()
return round(earth / 0.2408467, 2)
def on_venus(self):
return round(self.seconds/ 31557600 / 0.61519726, 2)
def on_mars(self):
earth = self.on_earth()
return round(earth / 1.8808158, 2)
def on_jupiter(self):
earth = self.on_earth()
return round(earth / 11.862615, 2)
def on_saturn(self):
earth = self.on_earth()
return round(earth / 29.447498, 2)
def on_uranus(self):
earth = self.on_earth()
return round(earth / 84.016846, 2)
def on_neptune(self):
earth = self.on_earth()
return round(earth / 164.79132, 2)
|
class Tester(object):
def __init__(self):
self.results = dict()
self.params = dict()
self.problem_data = dict()
def set_params(self, params):
self.params = params |
"""
Forçando tipos de dados com decoradores
-> Função zip()
a = (1, 3, 5)
b = (2, 4, 6)
c = zip(a, b)
(1, 2), (3, 4), (5, 6)
"""
def forca_tipo(*tipos):
def decorador(funcao):
def converte(*args, **kwargs):
novo_args = []
for (valor, tipo) in zip(args, tipos):
novo_args.append(tipo(valor)) # str('Paulo'), int('3')
return funcao(*novo_args, **kwargs)
return converte
return decorador
@forca_tipo(str, int)
def repete_msg(msg, vezes):
for vez in range(int(vezes)):
print(msg)
repete_msg('Paulo', '3')
@forca_tipo(float, float)
def dividir(a, b):
print(a / b)
dividir('1', '5')
|
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
stack = []
s3 = -float("inf")
for n in nums[::-1]:
if n < s3: return True
while stack and stack[-1] < n: s3 = stack.pop()
stack.append(n)
return False |
class SlackResponseTool:
@classmethod
def response2is_ok(cls, response):
return response["ok"] is True
@classmethod
def response2j_resopnse(cls, response):
return response.data
|
#!/usr/bin/env python
NAME = 'Cloudflare (Cloudflare Inc.)'
def is_waf(self):
# This should be given first priority (most reliable)
if self.matchcookie('__cfduid'):
return True
# Not all servers return cloudflare-nginx, only nginx ones
if self.matchheader(('server', 'cloudflare-nginx')) or self.matchheader(('server', 'cloudflare')):
return True
# Found a new nice fingerprint for cloudflare
if self.matchheader(('cf-ray', '.*')):
return True
return False |
s = input()
K = int(input())
n = len(s)
substr = set()
for i in range(n):
for j in range(i + 1, i + 1 + K):
if j <= n:
substr.add(s[i:j])
substr = sorted(list(substr))
print(substr[K - 1])
|
def exc():
a=10
b=0
try:
c=a/b
except(ZeroDivisionError ):
print("Divide by zero")
exc()
|
"""
More list manipulations
"""
def split(in_list, index):
"""
Parameters
----------
in_list: list
index: int
Returns
----------
Two lists, splitting in_list by 'index'
Examples
----------
>>> split(['a', 'b', 'c', 'd'], 3)
(['a', 'b', 'c'], ['d'])
"""
list1 = in_list[:index]
list2 = in_list[index:]
return list1, list2
|
__version__ = "0.3.43"
def doc_version():
"""Use this number in the documentation to avoid triggering updates
of the whole documentation each time the last part of the version is
changed."""
parts = __version__.split(".")
return parts[0] + "." + parts[1]
|
"""
Bars Module
"""
def starbar(num):
print('*' * num)
def hashbar(num):
print('#' * num)
def simplebar(num):
print('-' * num)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def is_odd(num):
return num % 2 == 1
def not_empty(s):
return s and s.strip()
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
# 生成从3开始的奇数
def ge_num():
n = 1
while True:
n = n + 2
yield n
# 筛选函数
def not_divi(n):
return lambda x: x % n >0
# 产生素数序列
def prime():
yield 2
num_list = ge_num() # 初始化序列
while True:
n = next(num_list)
yield n
new_num_list = filter(not_divi(n), num_list) # filter 过滤构造新的序列
for x in prime():
if x < 1000:
print(x)
else:
break
# 判断一个数是否是回数
def is_palindrome(n):
strn = str(n)
i = 0
if strn[i] == strn[len(strn) - i - 1]:
return True
else:
return False
l = list(filter(is_palindrome, range(1, 1000)))
print(l) |
A, B, K = map(int, input().split())
for i, num in enumerate(range(A, B + 1)):
if i + 1 > K:
break
print(num)
x = []
for i, num in enumerate(range(B, A-1, -1)):
if i + 1 > K:
break
x.append(num)
x.sort()
k = B - A +1
for i in x:
if k < 2 * K:
k += 1
else:
print(i)
|
s = sum(range(1, 101)) ** 2
ss = sum(list(map(lambda x: x ** 2, range(1, 101))))
print(s - ss)
|
#-*- coding: utf-8 -*-
class SQLForge:
"""
SQLForge
This class is in charge of providing methods to craft SQL queries. Basically,
the methods already implemented fit with most of the DBMS.
"""
def __init__(self, context):
""" Constructor
context: context to associate the forge with.
"""
self.context = context
def wrap_bisec(self, sql):
"""
Wrap a bisection-based query.
This method must be overridden to provide a way to use bisection given
a DBMS. There is no universal way to perform this, so it has to be
implemented in each DBMS plugin.
"""
raise NotImplementedError('You must define the wrap_bisec() method')
def wrap_string(self, string):
"""
Wraps a string.
This method encode the given string and/or add delimiters if required.
"""
if self.context.require_string_encoding():
out = 'CHAR('
for car in string:
out += str(ord(car))+','
out = out[:-1] + ')'
else:
return "%c%s%c" % (self.context.get_string_delimiter(),string,self.context.get_string_delimiter())
return out
def wrap_sql(self, sql):
"""
Wraps SQL query
This method wraps an SQL query given the specified context.
"""
q = self.context.get_string_delimiter()
if self.context.is_blind():
if self.context.require_truncate():
if self.context.in_string():
return "%c OR (%s=%s) %s" % (q,sql,self.wrap_field(self.context.get_default_value()),self.context.get_comment())
elif self.context.in_int():
return "%s OR (%s)=%s %s" % (self.context.get_default_value(), sql, self.wrap_field(self.context.get_default_value()), self.context.getComment())
else:
if self.context.in_string():
return "%c OR (%s=%s) AND %c1%c=%c1" % (q,sql,self.wrap_field(self.context.get_default_value()),q,q,q)
elif self.context.in_int():
return "%s OR (%s)=%s " % (self.context.get_default_value(), sql,self.wrap_field(self.context.get_default_value()))
else:
if self.context.require_truncate():
if self.context.in_string():
return "%c AND 1=0 UNION %s %s" % (q, sql, self.context.getComment())
elif self.context.in_int():
return "%s AND 1=0 UNION %s %s" % (self.context.get_default_value(), sql, self.context.get_comment())
else:
if self.context.in_string():
return "%c AND 1=0 UNION %s" % (q, sql)
elif self.context.in_int():
return "%s AND 1=0 UNION %s" % (self.context.get_default_value(), sql)
def wrap_field(self,field):
"""
Wrap a field with delimiters if required.
"""
q = self.context.get_string_delimiter()
if self.context.in_string():
return "%c%s%c" % (q,field,q)
else:
return "%s"%field
def wrap_ending_field(self, field):
"""
Wrap the last field with a delimiter if required.
"""
q = self.context.get_string_delimiter()
if self.context.in_string():
return "%c%s" % (q,field)
else:
return "%s"%field
def string_len(self, string):
"""
Forge a piece of SQL retrieving the length of a string.
"""
return "LENGTH(%s)" % string
def get_char(self, string, pos):
"""
Forge a piece of SQL returning the n-th character of a string.
"""
return "SUBSTRING(%s,%d,1)" % (string,pos)
def concat_str(self, str1, str2):
"""
Forge a piece of SQL concatenating two strings.
"""
return "CONCAT(%s,%s)" % (str1, str2)
def ascii(self, char):
"""
Forge a piece of SQL returning the ascii code of a character.
"""
return "ASCII(%s)" % char
def count(self, records):
"""
Forge a piece of SQL returning the number of rows from a set of records.
"""
sql= "(SELECT COUNT(*) FROM (%s) AS T1)" % records
return sql
def take(self,records, index):
"""
Forge a piece of SQL returning the n-th record of a set.
"""
return "(%s LIMIT %d,1)" % (records, index)
def select_all(self, table, db):
"""
Forge a piece of SQL returning all records of a given table.
"""
return "(SELECT * FROM %s.%s)" % (db, table)
def get_table_field_record(self, field, table, db, pos):
"""
Forge a piece of SQL returning one record with one column from a table.
"""
return "(SELECT %s FROM (SELECT * FROM %s.%s) as t0 LIMIT %d,1)"%(field,db,table,pos)
def forge_cdt(self, val, cmp):
"""
Forge a piece of SQL creating a condition.
"""
return "(%s)<%d" % (val,cmp)
def forge_second_query(self, sql):
"""
Basic inband query builder.
Builds the second part of an inband injection (following the UNION).
"""
query = 'SELECT '
columns= []
fields = self.context.get_inband_fields()
tag = self.context.get_inband_tag()
for i in range(len(fields)):
if i==self.context.get_inband_target():
columns.append(self.concat_str(self.wrap_string(tag),self.concat_str(sql, self.wrap_string(tag))))
else:
if fields[i]=='s':
columns.append(self.wrap_string('0'))
elif fields[i]=='i':
columns.append('0')
return query + ','.join(columns)
def get_version(self):
"""
Forge a piece of SQL returning the DBMS version.
Must be overridden by each DBMS plugin.
"""
raise NotImplementedError('You must provide the get_version() method.')
def get_user(self):
"""
Forge a piece of SQL returning the current username.
"""
return 'username()'
def get_current_database(self):
"""
Forge a piece of SQL returning the current database name.
"""
return 'database()'
def get_databases(self):
"""
Forge a piece of SQL returning all the known databases.
"""
raise NotImplementedError('You must define the "get_databases" function.')
def get_database(self, id):
"""
Forge a piece of SQL returning the name of the id-th database.
"""
return self.take(self.get_databases(), id)
def get_nb_databases(self):
"""
Forge a piece of SQL returning the number of databases.
"""
return self.count(self.get_databases())
def get_database_name(self, id):
"""
Forge a piece of SQL returning the name of id-th database.
"""
return self.take(self.get_databases(),id)
def get_tables(self,db):
"""
Forge a piece of SQL returning all the tables of the provided database (db).
db: target database name.
"""
raise NotImplementedError('You must provide the get_tables() method.')
def get_nb_tables(self,db):
"""
Forge a piece of SQL returning the number of tables.
db: target database name.
"""
return self.count(self.get_tables(db))
def get_table_name(self, id, db):
"""
Forge a piece of SQL returning the name of a table.
id: table index
db: target database name.
"""
return self.take(self.get_tables(db), id)
def get_fields(self, table, db):
"""
Forge a piece of SQL returning all the existing fields of a table.
table: target table name
db: target database name
"""
raise NotImplementedError('You must provide the get_fields() method.')
def get_nb_fields(self, table, db):
"""
Forge a piece of SQL returning the number of fields.
table: target table name
db: target database name
"""
return self.count(self.get_fields(table,db))
def get_field_name(self, table, id, db):
"""
Forge a piece of SQL returning the field name
table: target table name
db: target database name
id: field index
"""
return self.take(self.get_fields(table, db), id)
def get_string_len(self, sql):
"""
Forge a piece of SQL returning the length of a string/subquery.
sql: source string or sql
"""
return self.string_len(sql)
def get_string_char(self, sql, pos):
"""
Forge a piece of SQL returning the ascii code of a string/sql
sql: source string or sql
pos: character position
"""
return self.ascii(self.get_char(sql, pos))
|
class Solution(object):
def generateParenthesis(self, n):
# corner case
if n == 0:
return []
# level: tree level
# openCount: open bracket count
def dfs(level, n1, n2, n, stack, ret, openCount):
if level == 2 * n:
ret.append("".join(stack[:]))
# dfs
if n1 < n:
stack.append("(")
dfs(level + 1, n1 + 1, n2, n, stack, ret, openCount + 1)
stack.pop()
if openCount >= 1 and n2 < n:
stack.append(")")
dfs(level + 1, n1, n2 + 1, n, stack, ret, openCount - 1)
stack.pop()
stack = list()
ret = list()
dfs(0, 0, 0, n, stack, ret, 0)
return ret |
def find(n: int):
for i in range(1, 1000001):
total = 0
for j in str(i):
total += int(j)
total += i
if total == n:
print(i)
return
print(0)
find(int(input()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.