content
stringlengths 7
1.05M
|
|---|
DECIMALS = {"GNG-8d7e05" : 1000000000000000000,
"MEX-4183e7" : 1000000000000000000,
"LKMEX-9acade" : 1000000000000000000,
"WATER-104d38" : 1000000000000000000}
TOKEN_TYPE = {"GNG-8d7e05" : "token",
"MEX-4183e7" : "token",
"WARMY-cc922b": "NFT",
"LKMEX-9acade" : "META",
"WATER-104d38" : "token",
"COLORS-14cff1" : "NFT"}
AUTHORIZED_TOKENS = ["GNG-8d7e05",
"MEX-4183e7",
"WARMY-cc922b",
"LKMEX-9acade",
"WATER-104d38",
"COLORS-14cff1"]
TOKEN_TYPE_U8 = {"Fungible" : "00",
"NonFungible" : "01",
"SemiFungible" : "02",
"Meta" : "03"}
|
def bubblesort(unsorted):
counter = 0
# Vorerst Endlosschleife
while True:
# Bis auf Weiteres gilt die Liste als sortiert
is_sorted = True
# Erstes bis vorletztes Element
for i in range(0, len(unsorted) - 1):
counter += 1
# Aktuelles Element größer als sein Nachfolger?
if unsorted[i] > unsorted[i + 1]:
# Elemente vertauschen
unsorted[i], unsorted[i + 1] = unsorted[i + 1], unsorted[i]
# Feststellung: Liste ist noch nicht sortiert
is_sorted = False
# Falls hier sortiert, Ende
if is_sorted:
break
return counter
if __name__ == '__main__':
list1 = [7, 2, 9, 1, 8, 4, 6, 3, 5, 0, 9]
list2 = ['Katze', 'Hund', 'Elefant', 'Maus', 'Affe', 'Giraffe']
list3 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
s1 = bubblesort(list1)
print(f"{list1}: {s1} Durchläufe")
s2 = bubblesort(list2)
print(f"{list2}: {s2} Durchläufe")
s3 = bubblesort(list3)
print(f"{list3}: {s3} Durchläufe")
|
class Mime(object):
def __init__(self,content_type, category, extension, stream=False, use_file_name=False):
self.content_type = content_type
self.category = category
self.extension = extension
self.stream = stream
self.use_file_name = use_file_name
class Mimes(object):
@staticmethod
def all():
return [
Mime("application/javascript","scripts",".js"),
Mime("text/javascript","scripts",".js"),
Mime("application/x-javascript","scripts",".js"),
Mime("text/css","styles",".css"),
Mime("application/json","data",".json"),
Mime("text/json","data",".json"),
Mime("text/x-json","data",".xml"),
Mime("application/xml","data",".xml"),
Mime("text/xml","data",".xml"),
Mime("application/rss+xml","data",".xml"),
Mime("text/plain","data",".txt"),
Mime("image/jpg","images",".jpg", True),
Mime("image/jpeg","images",".jpg", True),
Mime("image/png","images",".png", True),
Mime("image/gif","images",".gif", True),
Mime("image/bmp","images",".bmp", True),
Mime("image/tiff","images",".tiff", True),
Mime("image/x-icon","images",".ico", True),
Mime("image/vnd.microsoft.icon","images",".ico",True),
Mime("font/woff","fonts",".woff",True,True),
Mime("font/woff2","fonts",".woff2",True,True),
Mime("application/font-woff","fonts",".woff",True,True),
Mime("application/font-woff2","fonts",".woff2",True,True),
Mime("image/svg+xml","fonts",".svg", True,True),
Mime("application/octet-stream","fonts","ttf",True,True),
Mime("application/octet-stream","fonts","eot",True,True),
Mime("application/vnd.ms-fontobject","fonts","eot",True,True)
]
@staticmethod
def by_content_type(content_type):
if content_type:
m = filter(lambda x: x.content_type.lower() == content_type.lower(), Mimes.all())
if len(m) > 0:
return m[0]
return False
@staticmethod
def by_extension(extension):
if extension:
m = filter(lambda x: x.extension.lower() == extension.lower(),Mimes.all())
if len(m) > 0:
return m[0]
return False
|
class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through spectra
"""
def __init__(self, peak_id, x, y, z):
self.peak_id = peak_id
self.x = x
self.y = y
self.z = z
self.length = len(x) + len(y) + len(z)
def add_coordinates(self, x, y, z):
"""Adds x, y, z co-ordinates to their respective lists."""
self.x.extend(x)
self.y.extend(y)
self.z.extend(z)
def remove_coordinates(self, amount):
"""Removes number of co-ordinates to solve missing data problem (https://en.wikipedia.org/wiki/Missing_data)
(Length of peak data will differ across all peaks, so remove redundant
data to ensure peak data matches average length of all detected peak data."""
for i in range(amount):
self.x.pop()
self.y.pop()
self.z.pop()
def peak_length(self):
self.length = len(self.z)
return self.length
def x_coordinates(self):
return self.x
def y_coordinates(self):
return self.y
def z_coordinates(self):
return self.z
|
_base_ = './classifier.py'
model = dict(
type='TaskIncrementalLwF',
head=dict(
type='TaskIncLwfHead'
)
)
|
if 'photo' in longpoll[pack['userid']]['object']['attachments'][0]:
ret = longpoll[pack['userid']]['object']['attachments'][0]['photo']['sizes']
num = 0
for size in ret:
if size['width'] > num:
num = size['width']
url = size['url']
index = requests.get('https://yandex.ru/images/search?url='+url+'&rpt=imageview').text
index = html.fromstring(index)
tags = index.xpath('//div[@class="tags__wrapper"]/a')
out = ''
for tag in tags:
out += '• '+BeautifulSoup(etree.tostring(tag).decode(),'lxml').text+'\n'
apisay('Я думаю на изображении что-то из этого: \n'+out,pack['toho'])
else:
apisay('Картинку сунуть забыл',pack['toho'])
|
def part_one(inputs):
return get_acc(inputs, False)
def part_two(inputs):
for current_line in range(len(inputs)):
backup = inputs[current_line]
try:
if inputs[current_line][:3] == 'nop' and inputs[current_line][4:] != '+0':
inputs[current_line] = 'jmp' + inputs[current_line][3:]
return get_acc(inputs, True)
elif inputs[current_line][:3] == 'jmp':
inputs[current_line] = 'nop' + inputs[current_line][3:]
return get_acc(inputs, True)
except:
inputs[current_line] = backup
def get_acc(inputs, raise_on_loop):
executed_lines = set()
acc = 0
current_line = 0
while current_line not in executed_lines:
if current_line >= len(inputs):
return acc
executed_lines.add(current_line)
if inputs[current_line][:3] == 'nop':
current_line += 1
elif inputs[current_line][:3] == 'jmp':
current_line += int(inputs[current_line][4:])
elif inputs[current_line][:3] == 'acc':
acc += int(inputs[current_line][4:])
current_line += 1
if raise_on_loop:
raise
else:
return acc
test_inputs = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6""".split('\n')
assert part_one(test_inputs) == 5
assert part_two(test_inputs) == 8
with open('day8.input') as f:
inputs = f.read().splitlines()
print(part_one(inputs))
print(part_two(inputs))
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Make subpackages available:
__all__ = ['blockstorage', 'compute', 'config', 'database', 'dns', 'firewall', 'identity', 'images', 'loadbalancer', 'networking', 'objectstorage', 'vpnaas']
|
DWARVES_NUM = 9
dwarves = [int(input()) for _ in range(DWARVES_NUM)]
sum = sum(dwarves)
two_fake_sum = sum - 100
for i in range(DWARVES_NUM):
for j in range(DWARVES_NUM):
if i != j and dwarves[i] + dwarves[j] == two_fake_sum:
fake1 = i
fake2 = j
dwarves.pop(fake1)
dwarves.pop(fake2)
print('\n'.join([str(x) for x in dwarves]))
# Better solution (by CianLR):
#
# from itertools import combinations
#
# dvs = [int(input()) for _ in range(9)]
# for selects in combinations(dvs, 7):
# if sum(selects) == 100:
# print('\n'.join([str(x) for x in selects]))
# break
|
'''
Since lists are mutable, this means that we will be using lists for
things where we might intend to manipulate the list of data, so how
can we do that? Turns out we can do all sorts of things.
We can add, remove, count, sort, search, and do quite a few other things
to python lists.
'''
# first we need an example list:
x = [1,6,3,2,6,1,2,6,7]
# lets add something.
# we can do .append, which will add something to the end of the list, like:
x.append(55)
print(x)
# what if you have an exact place that you'd like to put something in a list?
x.insert(2,33)
print(x)
# so the reason that went in the 3rd place, again, is because we start
# at the zero element, then go 1, 2.. .and so on.
# now we can remove things... .remove will remove the first instance
# of the value in the list. If it doesn't exist, there will be an error:
x.remove(6)
print(x)
#next, remember how we can reference an item by index in a list? like:
print(x[5])
# well we can also search for this index, like so:
print(x.index(1))
# now here, we can see that it actually returned a 0, meaning the
# first element was a 1... when we knew there was another with an index of 5.
# so instead we might want to know before-hand how many examples there are.
print(x.count(1))
# so we see there are actually 2 of them
# we can also sort the list:
x.sort()
print(x)
# what if these were strings? like:
y = ['Jan','Dan','Bob','Alice','Jon','Jack']
y.sort()
print(y)
# noooo problemo!
# You can also just reverse a list, but, before we go there, we should note that
# all of these manipulations are mutating the list. keep in mind that any
# changes you make will modify the existing variable.
|
while True:
try:
a = float(input())
except EOFError:
break
print('|{:.4f}|={:.4f}'.format(a, abs(a)))
|
# Given an array with n objects colored red, white or blue,
# sort them in-place so that objects of the same color are adjacent,
# with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2
# to represent the color red, white, and blue respectively.
# Note: You are not suppose to use the library's sort function for this problem.
# Example:
# Input: [2,0,2,1,1,0]
# Output: [0,0,1,1,2,2]
# Follow up:
# A rather straight forward solution is a two-pass algorithm using counting sort.
# First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
# Could you come up with a one-pass algorithm using only constant space?
# from collections import Counter
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# M1. 计数排序
# 首先遍历一遍原数组,分别记录 红色(0),白色(1),蓝色(2) 的个数。
# 然后更新原数组,按个数分别赋上 红色(0),白色(1),蓝色(2)。
# count = Counter(nums)
# for i in range(len(nums)):
# if i < count[0]:
# nums[i] = 0
# elif i < count[0] + count[1]:
# nums[i] = 1
# else:
# nums[i] = 2
# M2.三指针法 p0, p2, curr
# https://leetcode.com/problems/sort-colors/solution/
# for all idx < p0 : nums[idx < p0] = 0
# curr is an index of element under consideration
p0 = curr = 0
# for all idx > p2 : nums[idx > p2] = 2
p2 = len(nums) - 1
while curr <= p2:
if nums[curr] == 0:
nums[p0], nums[curr] = nums[curr], nums[p0]
p0 += 1
curr += 1
elif nums[curr] == 2:
nums[curr], nums[p2] = nums[p2], nums[curr]
p2 -= 1
else:
curr += 1
# M3. 冒泡排序
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i] > nums[j]:
nums[i], nums[j] = nums[j], nums[i]
|
def computador_escolhe_jogada(fn, fm):
repetir = True
pecas_tirar_pc = 1
aux = fn
while pecas_tirar_pc <= fm and repetir:
fn = aux - pecas_tirar_pc
if fn % (fm + 1) == 0:
repetir = False
else:
pecas_tirar_pc = pecas_tirar_pc + 1
if pecas_tirar_pc == 1:
print("O computador tirou uma peça.")
else:
print("O computador tirou", pecas_tirar_pc, "peças.")
return pecas_tirar_pc
def usuario_escolhe_jogada(fn, fm):
repetir = True
while repetir == True:
pecas_tirar = int(input("Quantas peças você vai tirar? "))
print("")
if pecas_tirar <= fm and pecas_tirar > 0:
repetir = False
else:
print("Oops! Jogada inválida! Tente de novo.")
print("")
if pecas_tirar == 1:
print("Você tirou uma peça.")
else:
print("Voce tirou", pecas_tirar, "peças.")
return pecas_tirar
def sobra(fn):
if fn == 1:
print("Agora resta apenas uma peça no tabuleiro.")
print("")
elif fn > 1:
print("Agora restam", fn, "peças no tabuleiro.")
print("")
def partida():
n = int(input("Quantas peças? "))
m = int(input("Limite de peças por jogada? "))
print("")
if n % (m + 1) == 0:
print("Voce começa!")
print("")
while n > 0:
tiradas = usuario_escolhe_jogada(n, m)
n = n - tiradas
sobra(n)
if n == 0:
print("Você ganhou!")
print("")
else:
tiradas_pc = computador_escolhe_jogada(n, m)
n = n - tiradas_pc
sobra(n)
if n == 0:
sobra(n)
print("Fim do jogo! O computador ganhou!")
print("")
else:
print("Computador começa!")
print("")
while n > 0:
tiradas_pc = computador_escolhe_jogada(n, m)
n = n - tiradas_pc
sobra(n)
if n == 0:
print("Fim do jogo! O computador ganhou!")
print("")
else:
tiradas = usuario_escolhe_jogada(n, m)
n = n - tiradas
sobra(n)
if n == 0:
print("Você ganhou!")
print("")
def campeonato():
rodada = 1
while rodada <= 3:
print("**** Rodada", rodada, "****")
print("")
partida()
rodada = rodada + 1
def main():
print("Bem-vindo ao jogo do NIM! Escolha:")
print("")
print("1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
print("")
tipo_game = int(input())
print("")
if tipo_game == 1:
print("Voce escolheu uma partida isolada!")
print("")
partida()
else:
print("Voce escolheu um campeonato!")
print("")
campeonato()
print("")
print("**** Final do campeonato! *****")
print("")
print("Placar: Você 0 x 3 Computador")
main()
|
# lower case because appears as wcl section and wcl sections are converted to lowercase
META_HEADERS = 'h'
META_COMPUTE = 'c'
META_WCL = 'w'
META_COPY = 'p'
META_REQUIRED = 'r'
META_OPTIONAL = 'o'
FILETYPE_METADATA = 'filetype_metadata'
FILE_HEADER_INFO = 'file_header'
USE_HOME_ARCHIVE_INPUT = 'use_home_archive_input'
USE_HOME_ARCHIVE_OUTPUT = 'use_home_archive_output'
FM_PREFER_UNCOMPRESSED = [None, '.fz', '.gz']
FM_PREFER_COMPRESSED = ['.fz', '.gz', None]
FM_UNCOMPRESSED_ONLY = [None]
FM_COMPRESSED_ONLY = ['.fz', '.gz']
FM_EXIT_SUCCESS = 0
FM_EXIT_FAILURE = 1
FW_MSG_ERROR = 3
FW_MSG_WARN = 2
FW_MSG_INFO = 1
PROV_USED_TABLE = "OPM_USED"
#PROV_WGB_TABLE = "OPM_WAS_GENERATED_BY"
PROV_WDF_TABLE = "OPM_WAS_DERIVED_FROM"
PROV_TASK_ID = "TASK_ID"
PROV_FILE_ID = "DESFILE_ID"
PROV_PARENT_ID = "PARENT_DESFILE_ID"
PROV_CHILD_ID = "CHILD_DESFILE_ID"
|
"""Top-level package for mkdocs-github-dashboard."""
__author__ = """mkdocs-github-dashboard"""
__email__ = 'ms.kataoka@gmail.com'
__version__ = '0.1.0'
|
# -*- coding: utf-8 -*-
def main():
m, n = map(int, input().split())
unit = m // n
print(m - (unit * (n - 1)))
if __name__ == '__main__':
main()
|
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n=len(prices)
if k>n//2:
return sum([prices[i+1]-prices[i] if prices[i+1]>prices[i] else 0 for i in range(n-1)])
G=[[0]*n for _ in range(k+1)]
for i in range(1,k+1):
L=[0 for _ in range(n)]
for j in range(1,n):
p=prices[j]-prices[j-1]
# cal local max
L[j]=max(G[i-1][j-1]+p, L[j-1]+p)
# cal global max
G[i][j]=max(G[i][j-1], L[j])
return G[-1][-1]
|
rows = int(input())
number = 1
for i in range(rows):
for j in range(i + 1):
print(number, end=' ')
number += 1
print()
|
# list examples
z=[1,2,3]
assert z.__class__ == list
assert isinstance(z,list)
assert str(z)=="[1, 2, 3]"
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[]
print(a)
a.extend('ab')
print(a)
a.extend([1,2,33])
print(a)
# tuple
t = (1,8)
assert t.__class__ == tuple
assert isinstance(t,tuple)
assert str(t)=='(1, 8)'
|
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
# initialization:
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
# state: dp[i] represents how many ways to reach step i
# function: dp[i] = dp[i - 1] + dp[i - 2]
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
# answer: dp[n] represents the number of ways to reach n
return dp[n]
|
Name=input("enter the name ")
l=len(Name)
s=""
while l>0:
s+=Name[l-1]
l-=1
if s==Name:
print(" Name Plindrome "+Name)
else:
print("Name not Plindrome "+Name)
|
#
# PySNMP MIB module OPENBSD-SENSORS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPENBSD-SENSORS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:51 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, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
openBSD, = mibBuilder.importSymbols("OPENBSD-BASE-MIB", "openBSD")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Gauge32, ModuleIdentity, IpAddress, MibIdentifier, Integer32, Bits, iso, Unsigned32, NotificationType, TimeTicks, Counter64, ObjectIdentity, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "ModuleIdentity", "IpAddress", "MibIdentifier", "Integer32", "Bits", "iso", "Unsigned32", "NotificationType", "TimeTicks", "Counter64", "ObjectIdentity", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
sensorsMIBObjects = ModuleIdentity((1, 3, 6, 1, 4, 1, 30155, 2))
sensorsMIBObjects.setRevisions(('2012-09-20 00:00', '2012-01-31 00:00', '2008-12-23 00:00',))
if mibBuilder.loadTexts: sensorsMIBObjects.setLastUpdated('201209200000Z')
if mibBuilder.loadTexts: sensorsMIBObjects.setOrganization('OpenBSD')
sensors = MibIdentifier((1, 3, 6, 1, 4, 1, 30155, 2, 1))
sensorNumber = MibScalar((1, 3, 6, 1, 4, 1, 30155, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorNumber.setStatus('current')
sensorTable = MibTable((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2), )
if mibBuilder.loadTexts: sensorTable.setStatus('current')
sensorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1), ).setIndexNames((0, "OPENBSD-SENSORS-MIB", "sensorIndex"))
if mibBuilder.loadTexts: sensorEntry.setStatus('current')
sensorIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorIndex.setStatus('current')
sensorDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorDescr.setStatus('current')
sensorType = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20))).clone(namedValues=NamedValues(("temperature", 0), ("fan", 1), ("voltsdc", 2), ("voltsac", 3), ("resistance", 4), ("power", 5), ("current", 6), ("watthour", 7), ("amphour", 8), ("indicator", 9), ("raw", 10), ("percent", 11), ("illuminance", 12), ("drive", 13), ("timedelta", 14), ("humidity", 15), ("freq", 16), ("angle", 17), ("distance", 18), ("pressure", 19), ("accel", 20)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorType.setStatus('current')
sensorDevice = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 4), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorDevice.setStatus('current')
sensorValue = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 5), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorValue.setStatus('current')
sensorUnits = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 6), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorUnits.setStatus('current')
sensorStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 30155, 2, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("unspecified", 0), ("ok", 1), ("warn", 2), ("critical", 3), ("unknown", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sensorStatus.setStatus('current')
mibBuilder.exportSymbols("OPENBSD-SENSORS-MIB", sensorType=sensorType, sensorEntry=sensorEntry, sensors=sensors, sensorTable=sensorTable, sensorDevice=sensorDevice, sensorUnits=sensorUnits, sensorNumber=sensorNumber, sensorStatus=sensorStatus, sensorValue=sensorValue, sensorIndex=sensorIndex, sensorsMIBObjects=sensorsMIBObjects, PYSNMP_MODULE_ID=sensorsMIBObjects, sensorDescr=sensorDescr)
|
"""
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D in this turn or the next one, go full D.
Difference between oliveOneCM is that it requires 2 turns of good relations instead of 1.
"""
# memory[0] is 2 or 1 if it is currently doing the olive branch procedure, memory[1] is true if it is playing all D.
def strategy(history, memory):
if history.shape[1] == 0:
return 1, [0, False]
elif history[1][-1] == 0 and history[0][-1] == 1: # new betrayal
if history.shape[1] > 2 and history[0][-2] == 0: # just exited apology cycle
return 1, [2, False]
elif memory[0] > 0: # betrayed during the 'good relations' period
memory[1] = True
elif history[1][-1] == 1 and memory[0] > 0:
memory[0] -= 1
if memory[1]:
return 0, memory
return history[1][-1], memory
|
# Define a Product class. Objects should have 3 variables for price, code, and quantity
class Product:
def __init__(self, price=0.00, code='aaaa', quantity=0):
self.price = price
self.code = code
self.quantity = quantity
def __repr__(self):
return f'Product({self.price!r}, {self.code!r}, {self.quantity!r})'
def __str__(self):
return f'The product code is: {self.code}'
# Define an inventory class and a function for calculating the total value of the inventory.
class Inventory:
def __init__(self):
self.products_list = []
def add_product(self, product):
self.products_list.append(product)
return self.products_list
def total_value(self):
return sum(product.price * product.quantity for product in self.products_list)
|
"""
Counts total number of documents.
"""
def do_query(archives, config_file=None, logger=None, context=None):
"""
Iterate through archives and return all titles grouped by year.
"""
# [archive, archive, ...]
documents = archives.flatMap(
lambda archive: [(document.year, document) for document in list(archive)])
info = documents.map(lambda d: (d[0], d[1].title)) \
.groupByKey() \
.map(lambda d: (d[0], list(d[1]))) \
.collect()
return info
|
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = []
for i in range(n//2):
ans.append(i+1)
ans.append(-i-1)
if n % 2 != 0:
ans.append(0)
return ans
|
INCHES_PER_FOOT = 12.0 # 12 inches in a foot
INCHES_PER_YARD = INCHES_PER_FOOT * 3.0 # 3 feet in a yard
UNITS = ("in", "ft", "yd")
def inches_to_feet(x, reverse=False):
"""
Terminal command | pyment -w -o numpydoc inches_to_feet.py
Flags
-w | overwrite
-o <style> | styleput in NumPy Documentation style
Convert lengths between inches and feet
Parameters
----------
x : numpy.ndarray
Lengths in feet
reverse : bool, optional
If true this function converts from feet to inches
instead of the default behavior of inches to feet
(Default value = False)
Returns
-------
numpy.ndarray
[According documentation style 'numpydoc' at MODULE level]
"""
if reverse:
return x * INCHES_PER_FOOT
else:
return x / INCHES_PER_FOOT
|
"""
Initial settings for Up and Down the River
"""
class Settings() :
def __init__(self) :
"""Initializes static settings"""
#Screen Settings
self.screen_width = 1400
self.screen_height = 800
self.bg_color = (34, 139, 34)
#Basic settings
self.number_of_players_option = [3, 4, 5, 6, 7, 8]
self.number_of_players = int()
self.game_difficulty_option = ["Easy", "Intermediate", "Hard"]
self.game_difficulty = str()
self.starting_round = 1
self.max_rounds_available = 9
self.max_rounds = int()
#trick card screen settings
self.trick_x = self.screen_width * .35 #trick set
self.trick_y = (self.screen_height / 2) - (.071875 * self.screen_height) #Set for card to be centered
def set_round_array(self):
#Sets an array for number of cards to be dealt in a given round
self.round_array = []
for round in range(self.starting_round, self.max_rounds+1):
self.round_array.append(round)
for round in range(self.starting_round, self.max_rounds+1):
self.round_array.insert(self.max_rounds, round) #continually adds to countdown from max to 1
|
test = {
'name': 'Problem 5',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> expr = read_line('(+ 2 2)')
>>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors
4
>>> expr = read_line('(+ (+ 2 2) (+ 1 3) (* 1 4))')
>>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors
12
>>> expr = read_line('(yolo)')
>>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors
SchemeError
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': r"""
>>> from scheme_reader import *
>>> from scheme import *
""",
'teardown': '',
'type': 'doctest'
},
{
'cases': [
{
'code': r"""
scm> (+ 2 3) ; Type SchemeError if you think this errors
5
scm> (* (+ 3 2) (+ 1 7)) ; Type SchemeError if you think this errors
40
scm> (1 2) ; Type SchemeError if you think this errors
SchemeError
scm> (1 (print 0)) ; check_procedure should be called before operands are evaluated
SchemeError
""",
'hidden': False,
'locked': False
},
{
'code': r"""
scm> (+)
0
scm> (odd? 13)
#t
scm> (car (list 1 2 3 4))
1
scm> (car car)
SchemeError
scm> (odd? 1 2 3)
SchemeError
""",
'hidden': False,
'locked': False
},
{
'code': r"""
scm> (+ (+ 1) (* 2 3) (+ 5) (+ 6 (+ 7)))
25
scm> (*)
1
scm> (-)
SchemeError
scm> (car (cdr (cdr (list 1 2 3 4))))
3
scm> (car cdr (list 1))
SchemeError
scm> (* (car (cdr (cdr (list 1 2 3 4)))) (car (cdr (list 1 2 3 4))))
6
scm> (* (car (cdr (cdr (list 1 2 3 4)))) (cdr (cdr (list 1 2 3 4))))
SchemeError
scm> (+ (/ 1 0))
SchemeError
""",
'hidden': False,
'locked': False
},
{
'code': r"""
scm> ((/ 1 0) (print 5)) ; operator should be evaluated before operands
SchemeError
scm> (null? (print 5)) ; operands should only be evaluated once
5
#f
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'scheme'
}
]
}
|
class A:
def __init__(self, a):
pass
class B(A):
def __init__(self, a=1):
A.__init__(self, a)
|
#!/usr/bin/env python
# coding: utf-8
# # section 7: Exceptions :
#
# ### writer : Faranak Alikhah 1954128
# ### 1.Exceptions :
#
#
# In[ ]:
n=int(input())
for i in range(n):
try:
a,b=map(int,input().split())
print(a//b)# need to be integer
except Exception as e:
print ("Error Code:",e)
#
|
class HealthController:
"""
Manages interactions with the /health endpoints
"""
def __init__(self, client):
self.client = client
def check_health(self):
"""
GET request ot the /health endpoint
:return: Requests Response Object
"""
return self.client.call_api('GET', "/health")
|
class ContainerSpec():
REPLACEABLE_ARGS = ['randcon', 'oracle_server', 'bootnodes', 'genesis_time']
def __init__(self, cname, cimage, centry):
self.name = cname
self.image = cimage
self.entrypoint = centry
self.args = {}
def append_args(self, **kwargs):
self.args.update(kwargs)
def update_deployment(self, dep):
containers = dep['spec']['template']['spec']['containers']
for c in containers:
if c['name'] == self.name:
#update the container specs
if self.image:
c['image'] = self.image
if self.entrypoint:
c['command'] = self.entrypoint
c['args'] = self._update_args(c['args'], **(self.args))
break
return dep
def _update_args(self, args_input_yaml, **kwargs):
for k in kwargs:
replaced = False
if k in ContainerSpec.REPLACEABLE_ARGS:
for i, arg in enumerate(args_input_yaml):
if arg[2:].replace('-', '_') == k:
# replace the value
args_input_yaml[i + 1] = kwargs[k]
replaced = True
break
if not replaced:
args_input_yaml += (['--{0}'.format(k.replace('_', '-')), kwargs[k]])
return args_input_yaml
|
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/80471495
# IDEA : OPERATION : INVERSE -> Exclusive or (1->0, 0->1)
# NOTE : Exclusive or
# In [29]: x=1
# In [30]: x
# Out[30]: 1
# In [31]: x^=1
# In [32]: x
# Out[32]: 0
# In [33]: x=0
# In [34]: x
# Out[34]: 0
# In [35]: x^=1
# In [36]: x
# Out[36]: 1
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rows = len(A)
cols = len(A[0])
for row in range(rows):
A[row] = A[row][::-1]
for col in range(cols):
A[row][col] ^= 1
return A
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/80471495
# IDEA : GREEDY
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
M, N = len(A), len(A[0])
res = [[0] * N for _ in range(M)]
for i in range(M):
for j in range(N):
res[i][j] = 1 - A[i][N - 1 - j]
return res
# V2
# Time: O(n^2)
# Space: O(1)
class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for row in A:
for i in range((len(row)+1) // 2):
row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1
return A
|
#
# This file is part of snmpresponder software.
#
# Copyright (c) 2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpresponder/license.html
#
class Numbers(object):
current = 0
def getId(self):
self.current += 1
if self.current > 65535:
self.current = 0
return self.current
numbers = Numbers()
getId = numbers.getId
|
"""
This is the "Rotate Image" problem on Leetcode: https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/770
"""
# Out of Place Solution
def rotate_out_of_place(matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
"""
Idea #1: Swaps
A: moving the upper left corner over to the right spot [0, len(maxtrix[0]) - 1]
B: move the other elements one element up
0,0, 0,1, 0,2
[1,2,3], [1, 0, 0]
[4,5,6], -> 0, 0, 0
[7,8,9] 0, 0, 0
"""
NUMCOLS = len(matrix[0])
NUMROWS = len(matrix)
# initialize the 2d matrix
new_matrix = [[0 for i in range(NUMCOLS)] for j in range(NUMROWS)]
# populate the cols in the new matrix, with rows from the original
for index_row, row in enumerate(matrix):
for (
index_col,
value,
) in enumerate(row):
# calculate the shared column
new_col = NUMROWS - (index_row + 1)
# calculating the new row
new_row = index_col
new_matrix[new_row][new_col] = value
print(new_matrix)
matrix = new_matrix
return matrix
# In-place solution
def rotate_inplace(matrix):
"""Performs the same task as above, in constant space complexity.
:type matrix: List[List[int]]
:rtype: None
"""
# useful constants
NUM_ROWS, NUM_COLS = len(matrix), len(matrix[0])
# A: Reverse the rows in the Matrix
row_index_start, row_index_end = 0, NUM_ROWS - 1
while row_index_start < row_index_end:
# swap rows around the middle row, or until the indicies overlap
matrix[row_index_start], matrix[row_index_end] = (
matrix[row_index_end],
matrix[row_index_start],
)
# move the indices
row_index_start += 1
row_index_end -= 1
# B: Swap elements along the left-right, up-down diagonal
for diagonal_index in range(NUM_ROWS):
# index the elements to swap around the diagonal element
for swap_elem in range(diagonal_index + 1):
# index the elements to swap
next_to_diagonal = matrix[diagonal_index][diagonal_index - swap_elem]
above_diagonal = matrix[diagonal_index - swap_elem][diagonal_index]
# make the swap
matrix[diagonal_index][diagonal_index - swap_elem] = above_diagonal
matrix[diagonal_index - swap_elem][diagonal_index] = next_to_diagonal
print(matrix)
return None
if __name__ == "__main__":
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(rotate_inplace(matrix))
|
def _get_dart_host(config):
elb_params = config['cloudformation_stacks']['elb']['boto_args']['Parameters']
rs_name_param = _get_element(elb_params, 'ParameterKey', 'RecordSetName')
dart_host = rs_name_param['ParameterValue']
return dart_host
def _get_element(l, k, v):
for e in l:
if e[k] == v:
return e
raise Exception('element with %s: %s not found' % (k, v))
|
# Calculate the smallest Multiple
def smallestMultiple(n):
smallestMultiple = 1
while(True):
evenMultiple = True
for i in range(1, int(n) + 1):
if(smallestMultiple % i != 0):
evenMultiple = False
break
if(evenMultiple):
return smallestMultiple
smallestMultiple += 1
if __name__ == "__main__":
# Get user input
n = input("Enter an integer n: ")
print("Smallest positive number that is evenly divisible by all of the numbers from 1 to", n)
# Print results
print("{:,}".format(smallestMultiple(n)))
|
class User:
'''
Class that generates a new instance of a passlocker user
__init__method that helps us to define properties for our objects
Args:
name:New user name
password:New user password
'''
user_list=[]
def __init__(self,name,password):
self.name=name
self.password=password
def save_user(self):
'''
save user method that saves user obj into user list
'''
User.user_list.append(self)
@classmethod
def display_users(cls):
'''
Method that returns users using the password locker app
'''
return cls.user_list
@classmethod
def user_verified(cls,name,password):
'''
Method that takes a user login info & returns a boolean true if the details are correct
Args:
name:User name to search
password:password to match
Return:
Boolean true if they both match to a user & false if it doesn't
'''
for user in cls.user_list:
if user.name==name and user.password==password:
return True
return False
|
# output: ok
def foo(x):
yield 1
yield x
iter = foo(2)
assert next(iter) == 1
assert next(iter) == 2
def bar(array):
for x in array:
yield 2 * x
iter = bar([1, 2, 3])
assert next(iter) == 2
assert next(iter) == 4
assert next(iter) == 6
def collect(iter):
result = []
for x in iter:
result.append(x)
return result
r = collect(foo(0))
assert len(r) == 2
assert r[0] == 1
assert r[1] == 0
def noExcept(f):
try:
yield f()
except:
yield None
def a():
return 1
def b():
raise Exception()
assert(collect(noExcept(a)) == [1])
assert(collect(noExcept(b)) == [None])
print('ok')
|
RTL_LANGUAGES = {
'he', 'ar', 'arc', 'dv', 'fa', 'ha',
'khw', 'ks', 'ku', 'ps', 'ur', 'yi',
}
COLORS = {
'primary': '#0d6efd', 'blue': '#0d6efd', 'secondary': '#6c757d',
'success': '#198754', 'green': '#198754', 'danger': '#dc3545',
'red': '#dc3545', 'warning': '#ffc107', 'yellow': '#ffc107',
'info': '#0dcaf0', 'cyan': '#0dcaf0', 'gray': '#adb5bd',
'dark': '#000', 'black': '#000', 'white': '#fff',
'teal': '#20c997', 'orange': '#fd7e14', 'pink': '#d63384',
'purple': '#6f42c1', 'indigo': '#6610f2', 'light': '#f8f9fa',
}
DEFAULT_ASSESSMENT_BUTTON_COLOR = '#0d6efd' # primary
DEFAULT_ASSESSMENT_BUTTON_ACTIVE_COLOR = '#fff' # white
|
COINBASE_MATURITY = 500
INITIAL_BLOCK_REWARD = 20000
INITIAL_HASH_UTXO_ROOT = 0x21b463e3b52f6201c0ad6c991be0485b6ef8c092e64583ffa655cc1b171fe856
INITIAL_HASH_STATE_ROOT = 0x9514771014c9ae803d8cea2731b2063e83de44802b40dce2d06acd02d0ff65e9
MAX_BLOCK_BASE_SIZE = 2000000
BEERCHAIN_MIN_GAS_PRICE = 40
BEERCHAIN_MIN_GAS_PRICE_STR = "0.00000040"
NUM_DEFAULT_DGP_CONTRACTS = 5
MPOS_PARTICIPANTS = 10
LAST_POW_BLOCK = 5000
BLOCKS_BEFORE_PROPOSAL_EXPIRATION = 216
|
class AgentTrainer(object):#作为MADDPGtrainer的父类,以下函数在子类中被重构
def __init__(self, name, model, obs_shape, act_space, args):
raise NotImplemented()
def action(self, obs):
raise NotImplemented()#如果这个方法行不通就找别的方法来完成https://www.jianshu.com/p/a8613baefa30
def process_experience(self, obs, act, rew, new_obs, done, terminal):
raise NotImplemented()
def preupdate(self):
raise NotImplemented()
def update(self, agents):
raise NotImplemented()
|
# 461. Hamming Distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1')
|
print("Trick or Treat!")
row1 = ["🎃", "🎃", "🎃"]
row2 = ["🎃", "🎃", "🎃"]
row3 = ["🎃", "🎃", "🎃"]
maps = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = str(input("Where do you want to put the skull?: "))
horizontal = int(position[0])
vertical = int(position[1])
selected_row = maps[vertical - 1]
selected_row[horizontal - 1] = "💀"
print(f"{row1}\n{row2}\n{row3}")
|
MATERIALS = [
"gold", "silver", "bronze", "copper",
"iron", "titanium", "stone", "lithium",
"wood", "glass", "bone", "diamond"
]
PLACES = [
"cemetery", "forest", "desert", "cave",
"church", "school", "montain", "waterfall",
"prison", "garden", "crossroad", "nexus"
]
AMULETS = [
"warrior", "thief", "wizard", "barbarian",
"scholar", "paladin", "mimic", "blacksmith",
"sailor", "priest", "artist", "stargazer"
]
POTIONS = [
"stealth", "valor", "rage", "blood",
"youth", "fortune", "knowledge", "strife",
"secret", "oblivion", "purity", "justice"
]
SUMMONINGS = [
"pact", "conjuration", "connection", "calling",
"luring", "convincing", "order", "will",
"challenge", "binding", "capturing", "offering"
]
BANISHMENTS = [
"burning", "burying", "banishing", "cutting",
"sealing", "hanging", "drowing", "purifying"
]
|
# -*- coding: utf-8 -*-
a = ['doge1','doge2','doge3','doge4']
print(a)
|
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
elif nums[mid] > target:
hi = mid
else:
return mid
return lo
|
#
# PySNMP MIB module DAVID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DAVID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
DisplayString, = mibBuilder.importSymbols("RFC1155-SMI", "DisplayString")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, IpAddress, Integer32, iso, ModuleIdentity, Gauge32, Counter32, Bits, ObjectIdentity, MibIdentifier, TimeTicks, Counter64, Unsigned32, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "IpAddress", "Integer32", "iso", "ModuleIdentity", "Gauge32", "Counter32", "Bits", "ObjectIdentity", "MibIdentifier", "TimeTicks", "Counter64", "Unsigned32", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
david = MibIdentifier((1, 3, 6, 1, 4, 1, 66))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1))
davidExpressNet = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3))
exNetChassis = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 1))
exNetEthernet = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2))
exNetConcentrator = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1))
exNetModule = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2))
exNetPort = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3))
exNetMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4))
exNetChassisType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("other", 1), ("m6102", 2), ("m6103", 3), ("m6310tel", 4), ("m6310rj", 5), ("m6318st", 6), ("m6318sma", 7), ("reserved", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisType.setStatus('mandatory')
exNetChassisBkplType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("expressNet", 2), ("reserved", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisBkplType.setStatus('mandatory')
exNetChassisBkplRev = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisBkplRev.setStatus('mandatory')
exNetChassisPsType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("standardXfmr", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisPsType.setStatus('mandatory')
exNetChassisPsStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("failed", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisPsStatus.setStatus('mandatory')
exNetSlotConfigTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7), )
if mibBuilder.loadTexts: exNetSlotConfigTable.setStatus('mandatory')
exNetSlotConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1), ).setIndexNames((0, "DAVID-MIB", "exNetSlotIndex"))
if mibBuilder.loadTexts: exNetSlotConfigEntry.setStatus('mandatory')
exNetSlotIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetSlotIndex.setStatus('mandatory')
exNetBoardId = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardId.setStatus('mandatory')
exNetBoardType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("empty", 1), ("other", 2), ("m6203", 3), ("m6201", 4), ("m6311", 5), ("m6312", 6), ("m6313st", 7), ("m6313sma", 8), ("m6006", 9), ("reserved", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardType.setStatus('mandatory')
exNetBoardDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardDescr.setStatus('mandatory')
exNetBoardNumOfPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 7, 1, 40), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetBoardNumOfPorts.setStatus('mandatory')
exNetChassisCapacity = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetChassisCapacity.setStatus('mandatory')
exNetConcRetimingStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("off", 1), ("on", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcRetimingStatus.setStatus('mandatory')
exNetConcFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFrmsRxOk.setStatus('mandatory')
exNetConcOctetsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcOctetsRxOk.setStatus('mandatory')
exNetConcMcastFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcMcastFrmsRxOk.setStatus('mandatory')
exNetConcBcastFrmsRxOk = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcBcastFrmsRxOk.setStatus('mandatory')
exNetConcColls = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcColls.setStatus('mandatory')
exNetConcTooLongErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcTooLongErrors.setStatus('mandatory')
exNetConcRuntErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcRuntErrors.setStatus('mandatory')
exNetConcFragErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFragErrors.setStatus('mandatory')
exNetConcAlignErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcAlignErrors.setStatus('mandatory')
exNetConcFcsErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFcsErrors.setStatus('mandatory')
exNetConcLateCollErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcLateCollErrors.setStatus('mandatory')
exNetConcName = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetConcName.setStatus('mandatory')
exNetConcJabbers = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcJabbers.setStatus('mandatory')
exNetConcSfdErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcSfdErrors.setStatus('mandatory')
exNetConcAutoPartitions = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcAutoPartitions.setStatus('mandatory')
exNetConcOosBitRate = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcOosBitRate.setStatus('mandatory')
exNetConcLinkErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcLinkErrors.setStatus('mandatory')
exNetConcFrameErrors = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcFrameErrors.setStatus('mandatory')
exNetConcNetUtilization = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 47), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcNetUtilization.setStatus('mandatory')
exNetConcResetTimeStamp = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 48), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetConcResetTimeStamp.setStatus('mandatory')
exNetConcReset = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 1, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2), ("resetToDefault", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetConcReset.setStatus('mandatory')
exNetModuleTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1), )
if mibBuilder.loadTexts: exNetModuleTable.setStatus('mandatory')
exNetModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1), ).setIndexNames((0, "DAVID-MIB", "exNetModuleIndex"))
if mibBuilder.loadTexts: exNetModuleEntry.setStatus('mandatory')
exNetModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleIndex.setStatus('mandatory')
exNetModuleType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("empty", 1), ("other", 2), ("m6203", 3), ("m6201", 4), ("m6311", 5), ("m6312", 6), ("m6313st", 7), ("m6313sma", 8), ("m6006", 9), ("reserved", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleType.setStatus('mandatory')
exNetModuleHwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleHwVer.setStatus('mandatory')
exNetModuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ok", 1), ("noComms", 2), ("selfTestFail", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleStatus.setStatus('mandatory')
exNetModuleReset = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2), ("resetToDefault", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleReset.setStatus('mandatory')
exNetModulePartStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("partition", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModulePartStatus.setStatus('mandatory')
exNetModuleNmCntlStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notNmControl", 1), ("nmControl", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleNmCntlStatus.setStatus('mandatory')
exNetModulePsStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("fail", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModulePsStatus.setStatus('mandatory')
exNetModuleFrmsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFrmsRxOk.setStatus('mandatory')
exNetModuleOctetsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleOctetsRxOk.setStatus('mandatory')
exNetModuleColls = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleColls.setStatus('mandatory')
exNetModuleTooLongErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleTooLongErrors.setStatus('mandatory')
exNetModuleRuntErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleRuntErrors.setStatus('mandatory')
exNetModuleAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleAlignErrors.setStatus('mandatory')
exNetModuleFcsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFcsErrors.setStatus('mandatory')
exNetModuleLateCollErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLateCollErrors.setStatus('mandatory')
exNetModuleName = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleName.setStatus('mandatory')
exNetModuleJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleJabbers.setStatus('mandatory')
exNetModuleSfdErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleSfdErrors.setStatus('mandatory')
exNetModuleAutoPartitions = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleAutoPartitions.setStatus('mandatory')
exNetModuleOosBitRate = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleOosBitRate.setStatus('mandatory')
exNetModuleLinkErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLinkErrors.setStatus('mandatory')
exNetModuleFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFrameErrors.setStatus('mandatory')
exNetModuleFragErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFragErrors.setStatus('mandatory')
exNetModulePortConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 48), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModulePortConfig.setStatus('mandatory')
exNetModuleLinkStatConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 49), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetModuleLinkStatConfig.setStatus('mandatory')
exNetModuleResetTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 50), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleResetTimeStamp.setStatus('mandatory')
exNetModuleLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 51), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleLinkStatus.setStatus('mandatory')
exNetModuleFwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 52), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFwVer.setStatus('mandatory')
exNetModuleFwFeaturePkg = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 53), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleFwFeaturePkg.setStatus('mandatory')
exNetModuleSelfTestResult = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 2, 1, 1, 54), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetModuleSelfTestResult.setStatus('mandatory')
exNetPortTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1), )
if mibBuilder.loadTexts: exNetPortTable.setStatus('mandatory')
exNetPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1), ).setIndexNames((0, "DAVID-MIB", "exNetPortModuleIndex"), (0, "DAVID-MIB", "exNetPortIndex"))
if mibBuilder.loadTexts: exNetPortEntry.setStatus('mandatory')
exNetPortModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortModuleIndex.setStatus('mandatory')
exNetPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortIndex.setStatus('mandatory')
exNetPortLinkStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("off", 1), ("on", 2), ("other", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLinkStatus.setStatus('mandatory')
exNetPortPartStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("enabled", 1), ("partition", 2), ("autoPartition", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortPartStatus.setStatus('mandatory')
exNetPortJabberStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("jabbering", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortJabberStatus.setStatus('mandatory')
exNetPortFrmsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFrmsRxOk.setStatus('mandatory')
exNetPortOctetsRxOk = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortOctetsRxOk.setStatus('mandatory')
exNetPortColls = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortColls.setStatus('mandatory')
exNetPortTooLongErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortTooLongErrors.setStatus('mandatory')
exNetPortRuntErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortRuntErrors.setStatus('mandatory')
exNetPortAlignErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortAlignErrors.setStatus('mandatory')
exNetPortFcsErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFcsErrors.setStatus('mandatory')
exNetPortLateCollErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLateCollErrors.setStatus('mandatory')
exNetPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 40), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortName.setStatus('mandatory')
exNetPortJabbers = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 41), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortJabbers.setStatus('mandatory')
exNetPortSfdErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 42), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortSfdErrors.setStatus('mandatory')
exNetPortAutoPartitions = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 43), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortAutoPartitions.setStatus('mandatory')
exNetPortOosBitRate = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 44), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortOosBitRate.setStatus('mandatory')
exNetPortLinkErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 45), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortLinkErrors.setStatus('mandatory')
exNetPortFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 46), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFrameErrors.setStatus('mandatory')
exNetPortFragErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortFragErrors.setStatus('mandatory')
exNetPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 48), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("repeater", 2), ("tenBasefAsync", 3), ("tenBasefSync", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortType.setStatus('mandatory')
exNetPortMauType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 49), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("other", 1), ("tenBase5", 2), ("tenBaseT", 3), ("fOIRL", 4), ("tenBase2", 5), ("tenBaseFA", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetPortMauType.setStatus('mandatory')
exNetPortConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("enabled", 2), ("disabled", 3), ("txDisabled", 4), ("rxDisabled", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortConfig.setStatus('mandatory')
exNetPortLinkStatConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 51), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("enabled", 2), ("disabled", 3), ("txDisabled", 4), ("rxDisabled", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortLinkStatConfig.setStatus('mandatory')
exNetPortPolarity = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 52), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("positive", 2), ("negative", 3), ("txNegative", 4), ("rxNegative", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortPolarity.setStatus('mandatory')
exNetPortTransmitTest = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 3, 1, 1, 53), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetPortTransmitTest.setStatus('mandatory')
exNetMgmtType = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("tbd", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtType.setStatus('mandatory')
exNetMgmtHwVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtHwVer.setStatus('mandatory')
exNetMgmtFwVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtFwVer.setStatus('mandatory')
exNetMgmtSwMajorVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtSwMajorVer.setStatus('mandatory')
exNetMgmtSwMinorVer = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtSwMinorVer.setStatus('mandatory')
exNetMgmtStatus = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtStatus.setStatus('mandatory')
exNetMgmtMode = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtMode.setStatus('mandatory')
exNetMgmtReset = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notReset", 1), ("reset", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtReset.setStatus('mandatory')
exNetMgmtRestart = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notRestart", 1), ("restart", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtRestart.setStatus('mandatory')
exNetMgmtIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 10), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtIpAddr.setStatus('mandatory')
exNetMgmtNetMask = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 11), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtNetMask.setStatus('mandatory')
exNetMgmtDefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 12), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtDefaultGateway.setStatus('mandatory')
exNetMgmtBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: exNetMgmtBaudRate.setStatus('mandatory')
exNetMgmtLocation = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 19), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtLocation.setStatus('mandatory')
exNetMgmtTrapReceiverTable = MibTable((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20), )
if mibBuilder.loadTexts: exNetMgmtTrapReceiverTable.setStatus('mandatory')
exNetMgmtTrapReceiverEntry = MibTableRow((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1), ).setIndexNames((0, "DAVID-MIB", "exNetMgmtTrapReceiverAddr"))
if mibBuilder.loadTexts: exNetMgmtTrapReceiverEntry.setStatus('mandatory')
exNetMgmtTrapType = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2))).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapType.setStatus('mandatory')
exNetMgmtTrapReceiverAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapReceiverAddr.setStatus('mandatory')
exNetMgmtTrapReceiverComm = MibTableColumn((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 20, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(20, 20)).setFixedLength(20)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtTrapReceiverComm.setStatus('mandatory')
exNetMgmtAuthTrap = MibScalar((1, 3, 6, 1, 4, 1, 66, 1, 3, 2, 4, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: exNetMgmtAuthTrap.setStatus('mandatory')
mibBuilder.exportSymbols("DAVID-MIB", exNetPortIndex=exNetPortIndex, exNetMgmtAuthTrap=exNetMgmtAuthTrap, exNetModuleOctetsRxOk=exNetModuleOctetsRxOk, exNetPortPartStatus=exNetPortPartStatus, exNetPortSfdErrors=exNetPortSfdErrors, exNetConcAlignErrors=exNetConcAlignErrors, exNetPortLinkErrors=exNetPortLinkErrors, exNetChassisCapacity=exNetChassisCapacity, exNetMgmtHwVer=exNetMgmtHwVer, exNetConcAutoPartitions=exNetConcAutoPartitions, exNetMgmtDefaultGateway=exNetMgmtDefaultGateway, exNetChassisBkplType=exNetChassisBkplType, exNetMgmt=exNetMgmt, exNetModuleRuntErrors=exNetModuleRuntErrors, exNetMgmtTrapReceiverTable=exNetMgmtTrapReceiverTable, exNetConcentrator=exNetConcentrator, exNetConcLinkErrors=exNetConcLinkErrors, exNetModuleSfdErrors=exNetModuleSfdErrors, exNetModuleFwVer=exNetModuleFwVer, exNetModulePortConfig=exNetModulePortConfig, exNetChassisPsStatus=exNetChassisPsStatus, exNetModuleEntry=exNetModuleEntry, exNetPortLateCollErrors=exNetPortLateCollErrors, exNetModuleNmCntlStatus=exNetModuleNmCntlStatus, exNetMgmtFwVer=exNetMgmtFwVer, exNetConcResetTimeStamp=exNetConcResetTimeStamp, exNetModuleSelfTestResult=exNetModuleSelfTestResult, exNetModule=exNetModule, exNetMgmtLocation=exNetMgmtLocation, exNetSlotIndex=exNetSlotIndex, exNetModuleAutoPartitions=exNetModuleAutoPartitions, exNetSlotConfigTable=exNetSlotConfigTable, exNetPortPolarity=exNetPortPolarity, exNetPortJabberStatus=exNetPortJabberStatus, exNetConcJabbers=exNetConcJabbers, exNetPortTable=exNetPortTable, exNetMgmtMode=exNetMgmtMode, exNetMgmtTrapReceiverComm=exNetMgmtTrapReceiverComm, exNetMgmtSwMajorVer=exNetMgmtSwMajorVer, exNetBoardId=exNetBoardId, exNetConcOctetsRxOk=exNetConcOctetsRxOk, exNetModuleStatus=exNetModuleStatus, exNetMgmtStatus=exNetMgmtStatus, exNetMgmtReset=exNetMgmtReset, exNetModuleHwVer=exNetModuleHwVer, exNetModuleIndex=exNetModuleIndex, davidExpressNet=davidExpressNet, exNetConcBcastFrmsRxOk=exNetConcBcastFrmsRxOk, exNetPortLinkStatus=exNetPortLinkStatus, exNetConcMcastFrmsRxOk=exNetConcMcastFrmsRxOk, exNetModuleType=exNetModuleType, exNetConcLateCollErrors=exNetConcLateCollErrors, exNetMgmtSwMinorVer=exNetMgmtSwMinorVer, exNetPortFrmsRxOk=exNetPortFrmsRxOk, exNetModuleFrmsRxOk=exNetModuleFrmsRxOk, exNetPortColls=exNetPortColls, exNetModuleName=exNetModuleName, exNetModuleLinkStatConfig=exNetModuleLinkStatConfig, exNetConcRetimingStatus=exNetConcRetimingStatus, exNetModuleColls=exNetModuleColls, exNetPortTooLongErrors=exNetPortTooLongErrors, exNetConcOosBitRate=exNetConcOosBitRate, exNetMgmtBaudRate=exNetMgmtBaudRate, exNetPortModuleIndex=exNetPortModuleIndex, exNetBoardNumOfPorts=exNetBoardNumOfPorts, exNetPortFrameErrors=exNetPortFrameErrors, exNetConcSfdErrors=exNetConcSfdErrors, exNetMgmtTrapReceiverAddr=exNetMgmtTrapReceiverAddr, exNetModuleFragErrors=exNetModuleFragErrors, exNetChassisPsType=exNetChassisPsType, exNetBoardDescr=exNetBoardDescr, exNetPortEntry=exNetPortEntry, exNetModuleLateCollErrors=exNetModuleLateCollErrors, exNetPortMauType=exNetPortMauType, exNetConcReset=exNetConcReset, exNetModuleTable=exNetModuleTable, david=david, exNetModuleTooLongErrors=exNetModuleTooLongErrors, exNetSlotConfigEntry=exNetSlotConfigEntry, exNetModulePsStatus=exNetModulePsStatus, exNetModuleFwFeaturePkg=exNetModuleFwFeaturePkg, exNetConcFrameErrors=exNetConcFrameErrors, exNetPortOosBitRate=exNetPortOosBitRate, exNetConcFragErrors=exNetConcFragErrors, exNetConcTooLongErrors=exNetConcTooLongErrors, exNetModuleLinkStatus=exNetModuleLinkStatus, exNetChassisType=exNetChassisType, exNetModuleResetTimeStamp=exNetModuleResetTimeStamp, exNetPortAlignErrors=exNetPortAlignErrors, exNetPortFcsErrors=exNetPortFcsErrors, exNetBoardType=exNetBoardType, exNetEthernet=exNetEthernet, exNetPortType=exNetPortType, exNetConcRuntErrors=exNetConcRuntErrors, exNetConcColls=exNetConcColls, exNetConcFrmsRxOk=exNetConcFrmsRxOk, exNetModulePartStatus=exNetModulePartStatus, exNetPortName=exNetPortName, exNetPortTransmitTest=exNetPortTransmitTest, exNetPortJabbers=exNetPortJabbers, exNetMgmtIpAddr=exNetMgmtIpAddr, exNetPortConfig=exNetPortConfig, exNetModuleJabbers=exNetModuleJabbers, exNetPortLinkStatConfig=exNetPortLinkStatConfig, exNetMgmtNetMask=exNetMgmtNetMask, exNetPortOctetsRxOk=exNetPortOctetsRxOk, exNetModuleOosBitRate=exNetModuleOosBitRate, exNetModuleReset=exNetModuleReset, exNetModuleFrameErrors=exNetModuleFrameErrors, exNetPortAutoPartitions=exNetPortAutoPartitions, exNetModuleFcsErrors=exNetModuleFcsErrors, exNetMgmtTrapType=exNetMgmtTrapType, exNetChassis=exNetChassis, exNetConcName=exNetConcName, products=products, exNetModuleLinkErrors=exNetModuleLinkErrors, exNetModuleAlignErrors=exNetModuleAlignErrors, exNetMgmtType=exNetMgmtType, exNetConcFcsErrors=exNetConcFcsErrors, exNetMgmtTrapReceiverEntry=exNetMgmtTrapReceiverEntry, exNetPortFragErrors=exNetPortFragErrors, exNetPort=exNetPort, exNetMgmtRestart=exNetMgmtRestart, exNetConcNetUtilization=exNetConcNetUtilization, exNetChassisBkplRev=exNetChassisBkplRev, exNetPortRuntErrors=exNetPortRuntErrors)
|
journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months+1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_money >= journey_cost:
print(f"Bravo! You can go to Disneyland and you will have {diff:.2f}lv. for souvenirs.")
else:
print(f"Sorry. You need {diff:.2f}lv. more.")
|
#Crie um programa que calcule determinado(Qualquer valor) desconto,
# e aplique esse desconto no final da comprar daquele usuario
#Entrada de Dados
nomeC = str(input('Seja Bem-Vindo!\nInfome seu nome completo, por favor.')).upper()
nomeProduto = str(input('Informe o nome do produto: ')).upper()
valorP = float(input('Informe o valor do produto: R$'))
valorDesconto = float(input('Informe o valor do desconto: Por exemplo 10% ou 15%'))
#Processamento de dados
desconto = valorP - valorP * (valorDesconto / 100)
# Saída de Dados
print(f'Nome do cliente: {nomeC}\nNome do Produto: {nomeProduto}\nValor do Produto: {valorP:.2f}\nValor do desconto aplicado: {valorDesconto:.2f}\nValor Final: {desconto:.2f}')
|
subscription_data=\
{
"description": "A subscription to get info about Room1",
"subject": {
"entities": [
{
"id": "Room1",
"type": "Room",
}
],
"condition": {
"attrs": [
"p3"
]
}
},
"notification": {
"http": {
"url": "http://192.168.100.162:8888"
},
"attrs": [
"p1",
"p2",
"p3"
]
},
"expires": "2040-01-01T14:00:00.00Z",
"throttling": 5
}
#data to test the following code for broker.thinBroker.go:946
'''
subReqv2 := SubscriptionRequest{}
err := r.DecodeJsonPayload(&subReqv2)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
'''
subscriptionWrongPaylaod=\
{
"description": "A subscription to get info about Room1",
"subject": {
"entities": [
{
"id": "Room1",
"type": "Room",
"ispattern":"false"
}
],
"condition": {
"attrs": [
"p3"
]
}
},
"notification": {
"http": {
"url": "http://192.168.100.162:8888"
},
"attrs": [
"p1",
"p2",
"p3"
]
},
"expires": "2040-01-01T14:00:00.00Z",
"throttling": 5
}
v1SubData=\
{
"entities": [
{
"id": "Room1",
"type": "Room",
}
],
"reference": "http://192.168.100.162:8668/ngsi10/updateContext"
}
updateDataWithupdateaction=\
{
"contextElements": [
{
"entityId": {
"id": "Room1",
"type": "Room"
},
"attributes": [
{
"name": "p1",
"type": "float",
"value": 60
},
{
"name": "p3",
"type": "float",
"value": 69
},
{
"name": "p2",
"type": "float",
"value": 32
}
],
"domainMetadata": [
{
"name": "location",
"type": "point",
"value": {
"latitude": 49.406393,
"longitude": 8.684208
}
}
]
}
],
"updateAction": "UPDATE"
}
createDataWithupdateaction=\
{
"contextElements": [
{
"entityId": {
"id": "Room1",
"type": "Room"
},
"attributes": [
{
"name": "p1",
"type": "float",
"value": 90
},
{
"name": "p3",
"type": "float",
"value": 70
},
{
"name": "p2",
"type": "float",
"value": 12
}
],
"domainMetadata": [
{
"name": "location",
"type": "point",
"value": {
"latitude": 49.406393,
"longitude": 8.684208
}
}
]
}
],
"updateAction": "CRETAE"
}
deleteDataWithupdateaction=\
{
"contextElements": [
{
"entityId": {
"id": "Room1",
"type": "Room"
},
"attributes": [
{
"name": "p1",
"type": "float",
"value": 12
},
{
"name": "p3",
"type": "float",
"value": 13
},
{
"name": "p2",
"type": "float",
"value": 14
}
],
"domainMetadata": [
{
"name": "location",
"type": "point",
"value": {
"latitude": 49.406393,
"longitude": 8.684208
}
}
]
}
],
"updateAction": "DELETE"
}
|
with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents)
|
class HistoryStatement:
def __init__(self, hashPrev, hashUploaded, username, comment=""):
self.hashPrev = hashPrev
self.hashUploaded = hashUploaded
self.username = username
self.comment = comment
def to_bytes(self):
buf = bytearray()
buf.extend(self.hashPrev)
buf.extend(self.hashUploaded)
buf.extend(self.username.encode('ascii'))
for _ in range(0, 50 - len(self.username)):
buf.append(0)
buf.extend(self.comment.encode('ascii'))
return buf
def sign(self, key):
return key.sign(self.to_bytes())
pass
def from_bytes(buf):
hashPrev = bytearray(buf[:32])
hashUploaded = bytearray(buf[32:64])
usernameUntrimmed = buf[64:114]
username = ""
i = 0
while usernameUntrimmed[i] != 0:
username += chr(usernameUntrimmed[i])
i += 1
comment = bytes(buf[114:]).decode('ascii')
return HistoryStatement(hashPrev, hashUploaded, username, comment)
def __str__(self):
return "<HistoryStatement %s uploaded %s, previous was %s, comment: %s>" % (self.username, self.hashUploaded, self.hashPrev, self.comment)
|
_base_ = [
'../_base_/models/upernet_swin.py', '../_base_/datasets/uvo_finetune.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(
pretrained='PATH/TO/YOUR/swin_large_patch4_window12_384_22k.pth',
backbone=dict(
pretrain_img_size=384,
embed_dims=192,
depths=[2, 2, 18, 2],
num_heads=[6, 12, 24, 48],
drop_path_rate=0.2,
window_size=12),
decode_head=dict(
in_channels=[192, 384, 768, 1536],
num_classes=2,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
auxiliary_head=dict(
in_channels=768,
num_classes=2,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0))
)
# AdamW optimizer, no weight decay for position embedding & layer norm
# in backbone
optimizer = dict(
_delete_=True,
type='AdamW',
lr=0.00006 / 10,
betas=(0.9, 0.999),
weight_decay=0.01,
paramwise_cfg=dict(
custom_keys={
'absolute_pos_embed': dict(decay_mult=0.),
'relative_position_bias_table': dict(decay_mult=0.),
'norm': dict(decay_mult=0.)
}))
lr_config = dict(
_delete_=True,
policy='poly',
warmup='linear',
warmup_iters=1500,
warmup_ratio=5e-7,
power=1.0,
min_lr=0.0,
by_epoch=False)
# By default, models are trained on 8 GPUs with 2 images per GPU
data = dict(
samples_per_gpu=4,
workers_per_gpu=4,
)
load_from = '/tmp-network/user/ydu/mmsegmentation/work_dirs/biggest_model_clean_w_jitter/iter_300000.pth'
runner = dict(type='IterBasedRunner', max_iters=100000)
checkpoint_config = dict(by_epoch=False, interval=5000)
evaluation = dict(interval=5000, metric='mIoU', pre_eval=True)
|
class IDependency:
pass
class IScoped(IDependency):
pass
def __del__(self):
pass
class ISingleton(IDependency):
pass
|
h = int(input())
x = int(input())
y = int(input())
result = 'Outside'
# Base, left vertical, left horizontal, middle left etc.
if (3*h >= x >= 0 == y) or (x == 0 <= y <= h) or (0 <= x <= h == y) or (x == h <= y <= 4*h) or \
(h <= x <= 2*h and y == 4*h) or (x == 2*h and h <= y <= 4*h) or (2*h <= x <= 3*h and y == h) or \
(x == 3*h and 0 <= y <= h):
result = 'Border'
elif (0 < x < 3*h and 0 < y < h) or (h < x < 2*h and 0 < y < 4*h):
result = 'Inside'
print(result)
|
# https://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion
def hsv_to_rgb(h, s, v):
if s == 0.0: return (v, v, v)
i = int(h*6.) # XXX assume int() truncates!
f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
if i == 0: return (v, t, p)
if i == 1: return (q, v, p)
if i == 2: return (p, v, t)
if i == 3: return (p, q, v)
if i == 4: return (t, p, v)
if i == 5: return (v, p, q)
|
class Parameter:
def __init__(self,
name,
prior,
initial_value,
transform=None,
fixed=False):
self.name = name
self.prior = prior
self.transform = (lambda x: x) if transform is None else transform
self.value = initial_value
self.fixed = fixed
def propose(self, *args):
if self.fixed:
return self.value
assert self.proposal_dist is not None, 'proposal_dist must not be None if you use propose()'
return self.proposal_dist(*args).sample().numpy()
|
class Solution:
labs = []
def __init__(self, T):
self.z = 0
self.x = []
for i in range(T):
self.x.append(0)
def calculate_z(self):
if len(self.labs) == 0:
return 0
self.z = 0
for i in range(len(self.labs)):
for j in range(self.x[i]+1):
self.z += self.labs[i].P[j]
def __str__(self):
return "Z = {:.3f}, x = {}".format(self.z, self.x)
def __eq__(self, value):
if isinstance(value, Solution):
if len(self.x) != len(value.x):
return False
for i in range(len(self.x)):
if self.x[i] != value.x[i]:
return False
return True
return NotImplemented
def __lt__(self, value):
return self.z < value.z
def __le__(self, value):
return self.z <= value.z
def __gt__(self, value):
return self.z > value.z
def __ge__(self, value):
return self.z >= value.z
|
symbol = input()
count = int(input())
c = 0
for i in range(count):
if input() == symbol:
c += 1
print(c)
|
#!/usr/bin/python
'''
Priority queue with random access updates
-----------------------------------------
.. autoclass:: PrioQueue
:members:
:special-members:
'''
#-----------------------------------------------------------------------------
class PrioQueue:
'''
Priority queue that supports updating priority of arbitrary elements and
removing arbitrary elements.
Entry with lowest priority value is returned first.
Mutation operations (:meth:`set()`, :meth:`pop()`, :meth:`remove()`, and
:meth:`update()`) have complexity of ``O(log(n))``. Read operations
(:meth:`length()` and :meth:`peek()`) have complexity of ``O(1)``.
'''
#-------------------------------------------------------
# element container {{{
class _Element:
def __init__(self, prio, entry, pos, key):
self.prio = prio
self.entry = entry
self.pos = pos
self.key = key
def __cmp__(self, other):
return cmp(self.prio, other.prio) or \
cmp(id(self.entry), id(other.entry))
# }}}
#-------------------------------------------------------
def __init__(self, make_key = None):
'''
:param make_key: element-to-hashable converter function
If :obj:`make_key` is left unspecified, an identity function is used
(which means that the queue can only hold hashable objects).
'''
# children: (2 * i + 1), (2 * i + 2)
# parent: (i - 1) / 2
self._heap = []
self._keys = {}
if make_key is not None:
self._make_key = make_key
else:
self._make_key = lambda x: x
#-------------------------------------------------------
# dict-like operations {{{
def __len__(self):
'''
:return: queue length
Return length of the queue.
'''
return len(self._heap)
def __contains__(self, entry):
'''
:param entry: entry to check
:return: ``True`` if :obj:`entry` is in queue, ``False`` otherwise
Check whether the queue contains an entry.
'''
return (self._make_key(entry) in self._keys)
def __setitem__(self, entry, priority):
'''
:param entry: entry to add/update
:param priority: entry's priority
Set priority for an entry, either by adding a new or updating an
existing one.
'''
self.set(entry, priority)
def __getitem__(self, entry):
'''
:param entry: entry to get priority of
:return: priority
:throws: :exc:`KeyError` if entry is not in the queue
Get priority of an entry.
'''
key = self._make_key(entry)
return self._keys[key].prio # NOTE: allow the KeyError to propagate
def __delitem__(self, entry):
'''
:param entry: entry to remove
Remove an entry from the queue.
'''
self.remove(entry)
# }}}
#-------------------------------------------------------
# main operations {{{
def __iter__(self):
'''
:return: iterator
Iterate over the entries in the queue.
Order of the entries is unspecified.
'''
for element in self._heap:
yield element.entry
def iterentries(self):
'''
:return: iterator
Iterate over the entries in the queue.
Order of the entries is unspecified.
'''
for element in self._heap:
yield element.entry
def entries(self):
'''
:return: list of entries
Retrieve list of entries stored in the queue.
Order of the entries is unspecified.
'''
return [e.entry for e in self._heap]
def length(self):
'''
:return: queue length
Return length of the queue.
'''
return len(self._heap)
def set(self, entry, priority):
'''
:param entry: entry to add/update
:param priority: entry's priority
Set priority for an entry, either by adding a new or updating an
existing one.
'''
key = self._make_key(entry)
if key not in self._keys:
element = PrioQueue._Element(priority, entry, len(self._heap), key)
self._keys[key] = element
self._heap.append(element)
else:
element = self._keys[key]
element.prio = priority
self._heapify(element.pos)
def pop(self):
'''
:return: tuple ``(priority, entry)``
:throws: :exc:`IndexError` when the queue is empty
Return the entry with lowest priority value. The entry is immediately
removed from the queue.
'''
if len(self._heap) == 0:
raise IndexError("queue is empty")
element = self._heap[0]
del self._keys[element.key]
if len(self._heap) > 1:
self._heap[0] = self._heap.pop()
self._heap[0].pos = 0
self._heapify_downwards(0)
else:
# this was the last element in the queue
self._heap.pop()
return (element.prio, element.entry)
def peek(self):
'''
:return: tuple ``(priority, entry)``
:throws: :exc:`IndexError` when the queue is empty
Return the entry with lowest priority value. The entry is not removed
from the queue.
'''
if len(self._heap) == 0:
raise IndexError("queue is empty")
return (self._heap[0].prio, self._heap[0].entry)
def remove(self, entry):
'''
:return: priority of :obj:`entry` or ``None`` when :obj:`entry` was
not found
Remove an arbitrary entry from the queue.
'''
key = self._make_key(entry)
if key not in self._keys:
return None
element = self._keys.pop(key)
if element.pos < len(self._heap) - 1:
# somewhere in the middle of the queue
self._heap[element.pos] = self._heap.pop()
self._heap[element.pos].pos = element.pos
self._heapify(element.pos)
else:
# this was the last element in the queue
self._heap.pop()
return element.prio
def update(self, entry, priority):
'''
:param entry: entry to update
:param priority: entry's new priority
:return: old priority of the entry
:throws: :exc:`KeyError` if entry is not in the queue
Update priority of an arbitrary entry.
'''
key = self._make_key(entry)
element = self._keys[key] # NOTE: allow the KeyError to propagate
old_priority = element.prio
element.prio = priority
self._heapify(element.pos)
return old_priority
# }}}
#-------------------------------------------------------
# maintain heap property {{{
def _heapify(self, i):
if i > 0 and self._heap[i] < self._heap[(i - 1) / 2]:
self._heapify_upwards(i)
else:
self._heapify_downwards(i)
def _heapify_upwards(self, i):
p = (i - 1) / 2 # parent index
while p >= 0 and self._heap[i] < self._heap[p]:
# swap element and its parent
(self._heap[i], self._heap[p]) = (self._heap[p], self._heap[i])
# update positions of the elements
self._heap[i].pos = i
self._heap[p].pos = p
# now check if the parent node satisfies heap property
i = p
p = (i - 1) / 2
def _heapify_downwards(self, i):
c = 2 * i + 1 # children: (2 * i + 1), (2 * i + 2)
while c < len(self._heap):
# select the smaller child (if the other child exists)
if c + 1 < len(self._heap) and self._heap[c + 1] < self._heap[c]:
c += 1
if self._heap[i] < self._heap[c]:
# heap property satisfied, nothing left to do
return
# swap element and its smaller child
(self._heap[i], self._heap[c]) = (self._heap[c], self._heap[i])
# update positions of the elements
self._heap[i].pos = i
self._heap[c].pos = c
# now check if the smaller child satisfies heap property
i = c
c = 2 * i + 1
# }}}
#-------------------------------------------------------
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker
|
SETTINGS_TMPL = '''import os
from glueplate import Glue as _
settings = _(
blog = _(
title = '{blog_title}',
base_url = '{base_url}',
language = '{language}',
),
dir = _(
output = os.path.abspath(os.path.join('..', 'out'))
),
GLUE_PLATE_PLUS_BEFORE_template_dirs = [os.path.abspath(os.path.join('.', 'templates')),],
multiprocess = {multicore},
)
'''
ABOUT_TMPL = '''About {blog_title}
=========================================================
:slug: about
:date: {year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}
'''
QUESTIONS = [
{
'type': 'input',
'name': 'blog_title',
'message': 'What\'s your blog title',
},
{
'type': 'input',
'name': 'base_url',
'message': 'input your blog base url. like https://www.tsuyukimakoto.com',
},
{
'type': 'input',
'name': 'language',
'message': 'input your blog language like ja',
},
]
BIISAN_DATA_DIR = 'biisan_data'
|
# code to find if given string
# is K-Palindrome or not
"""
Explanation
Process all characters one by one staring from either from left or right sides of both strings.
Let us traverse from the right corner, there are two possibilities for every pair of character being traversed.
If last characters of two strings are same, we ignore last characters and get count for remaining strings.
So we recur for lengths m-1 and n-1 where m is length of str1 and n is length of str2.
If last characters are not same, we consider remove operation on last character of first string and
last character of second string, recursively compute minimum cost for the operations and take minimum of two values.
Remove last char from str1: Recur for m-1 and n.
Remove last char from str2: Recur for m and n-1.
"""
# Find if given string
# is K-Palindrome or not
def isKPalRec(str1, str2, m, n):
# If first string is empty,
# the only option is to remove
# all characters of second string
if not m: return n
# If second string is empty,
# the only option is to remove
# all characters of first string
if not n: return m
# If last characters of two strings
# are same, ignore last characters
# and get count for remaining strings.
if str1[m-1] == str2[n-1]:
return isKPalRec(str1, str2, m-1, n-1)
# If last characters are not same,
# 1. Remove last char from str1 and recur for m-1 and n
# 2. Remove last char from str2 and recur for m and n-1
# Take minimum of above two operations
res = 1 + min(isKPalRec(str1, str2, m-1, n), # Remove from str1
(isKPalRec(str1, str2, m, n-1))) # Remove from str2
return res
# Returns true if str is k palindrome.
def isKPal(string, k):
revStr = string[::-1]
l = len(string)
return (isKPalRec(string, revStr, l, l) <= k * 2)
# Driver program
string = "acdcb"
k = 2
print("Yes" if isKPal(string, k) else "No")
|
class Dog:
kind = 'canine'
tricks = [] #mistaken use
def __init__(self, name):
self.name = name
self.tricksInstance = []
def add_trick(self, trick):
self.tricks.append(trick)
def add_trick_instance(self, trick):
self.tricksInstance.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
print(d.kind, d.name)
print(e.kind, e.name)
d.add_trick('roll over')
e.add_trick('play dead')
print(d.tricks)
d.add_trick_instance('roll over')
e.add_trick_instance('play dead')
print(d.tricksInstance)
print(e.tricksInstance)
|
#!/usr/bin/env python3
#----------------------------------------------------------------------------------------------------------------------#
# #
# Tuplex: Blazing Fast Python Data Science #
# #
# #
# (c) 2017 - 2021, Tuplex team #
# Created by Leonhard Spiegelberg first on 8/3/2021 #
# License: Apache 2.0 #
#----------------------------------------------------------------------------------------------------------------------#
# this file contains Framework specific exceptions
class TuplexException(Exception):
"""Base Exception class on which all Tuplex Framework specific exceptions are based"""
pass
class UDFCodeExtractionError(TuplexException):
"""thrown when UDF code extraction/reflection failed"""
pass
|
# The following is the homework 4 for course MIS3500
# This assignment is Home Work 4
def file_read():
add = 0 # variable for adding total
counter = 0 # counter to understand how many counts are there
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open("AAPL.txt", "r")
lines = file.readlines() # This line reads the lines in the file
for line in lines:
price = float(line)
prices.append(price)
add += price
counter += 1
# Getting back to Moving Average
i = 0
for price in prices:
if i >= 5:
current_price = price
moving_average = (prices[i-1] + prices[i-2] + prices[i-3] + prices[i-4] + prices[i-5]) / 5
# print("The Moving Average for last 5 days is", moving_average)
if (current_price < 0.95*moving_average) and buy == 0:
buy = current_price
print("Buying the Stock",buy)
if first_buy == 0:
first_buy = buy
print("The first buy is at: ", first_buy)
elif (current_price > 1.05*moving_average) and buy!=0:
print("Selling stock at: ", current_price)
iterative_profit = current_price - buy
buy = 0
print("This trade Profit is: ", iterative_profit)
total_profit += iterative_profit
print("")
i += 1 # Iteration changes the loop process
# Now processing the profits
print("-----------------------We will see the total profits earned from the first buy----------------------")
final_profit_percent = (total_profit/first_buy) * 100
print("")
print("The total profit percentage is: ", final_profit_percent)
print("")
# Unrelated but was in the class video so added
total_avg = add/counter
print("Total Average for price for the whole list is: ", total_avg)
# The main function goes here
file_read()
|
# -*- coding: utf-8 -*-
# @Time : 2021-07-31 19:34
# @Author : Ze Yi Sun
# @Site : BUAA
# @File : question.py
# @Software: PyCharm
class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return "None"
def check_correctness(self, answer: str) -> bool:
return True
class ChoiceQuestion(Question):
def __init__(self, statement: str, correct_answer: set):
super().__init__(statement)
self.correct_answer = correct_answer
def show(self):
return self.statement
def check_correctness(self, answer: set) -> bool:
if answer == self.correct_answer:
return True
else:
return False
def answer(self):
return self.correct_answer
class JudgmentQuestion(Question):
def __init__(self, statement: str, correct_answer: str):
super().__init__(statement)
self.correct_answer = correct_answer
def show(self):
return self.statement
def check_correctness(self, answer: str) -> bool:
if answer == self.correct_answer:
return True
else:
return False
def answer(self):
if self.correct_answer == "n":
return "False"
else:
return "True"
class ShortAnswerQuestion(Question):
def __init__(self, statement: str, standard_answer: str):
super().__init__(statement)
self.correct_answer = standard_answer
def show(self):
return self.statement
def check_correctness(self, answer: str) -> bool:
if answer == self.correct_answer:
return True
else:
return False
def answer(self):
return self.correct_answer
|
class Solution(object):
def validMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
i=0
j=len(arr)-1
while i<j and (arr[i] < arr[i+1]):
i+=1
while j>0 and (arr[j-1] > arr[j]):
j-=1
return i > 0 and j < len(arr)-1 and i==j
|
"""Top-level package for BakpdlBot."""
__author__ = """Mick Boekhoff"""
__email__ = 'mickboekhoff@hotmail.com'
__version__ = '0.1.0'
|
class Solution:
def countSubstrings(self, s: str) -> int:
p = len(s)
dp = [[i,i+1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i-1]:
if j-1 >= 0 and s[j-1] == s[i]:
p += 1
dp[i].append(j-1)
return p
|
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
#
row = len(grid)
col = len(grid[0])
#print(row,col)
temp = [[0 for i in range(col)] for j in range(row)]
#print(temp)
temp[0][0] = grid[0][0]
for j in range(1,col):
temp[0][j] = grid[0][j] + temp[0][j-1]
for i in range(1,row):
temp[i][0] = grid[i][0] + temp[i-1][0]
for i in range(1,row):
for j in range(1,col):
temp[i][j] = min(temp[i-1][j],temp[i][j-1]) + grid[i][j]
return(temp[row-1][col-1])
|
artifacts = {
"io_bazel_rules_scala_scala_library": {
"artifact": "org.scala-lang:scala-library:2.11.12",
"sha256": "0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce",
},
"io_bazel_rules_scala_scala_compiler": {
"artifact": "org.scala-lang:scala-compiler:2.11.12",
"sha256": "3e892546b72ab547cb77de4d840bcfd05c853e73390fed7370a8f19acb0735a0",
},
"io_bazel_rules_scala_scala_reflect": {
"artifact": "org.scala-lang:scala-reflect:2.11.12",
"sha256": "6ba385b450a6311a15c918cf8688b9af9327c6104f0ecbd35933cfcd3095fe04",
},
"io_bazel_rules_scala_scalatest": {
"artifact": "org.scalatest:scalatest_2.11:3.2.9",
"sha256": "45affb34dd5b567fa943a7e155118ae6ab6c4db2fd34ca6a6c62ea129a1675be",
},
"io_bazel_rules_scala_scalatest_compatible": {
"artifact": "org.scalatest:scalatest-compatible:jar:3.2.9",
"sha256": "7e5f1193af2fd88c432c4b80ce3641e4b1d062f421d8a0fcc43af9a19bb7c2eb",
},
"io_bazel_rules_scala_scalatest_core": {
"artifact": "org.scalatest:scalatest-core_2.11:3.2.9",
"sha256": "003cb40f78cbbffaf38203b09c776d06593974edf1883a933c1bbc0293a2f280",
},
"io_bazel_rules_scala_scalatest_featurespec": {
"artifact": "org.scalatest:scalatest-featurespec_2.11:3.2.9",
"sha256": "41567216bbd338625e77cd74ca669c88f59ff2da8adeb362657671bb43c4e462",
},
"io_bazel_rules_scala_scalatest_flatspec": {
"artifact": "org.scalatest:scalatest-flatspec_2.11:3.2.9",
"sha256": "3e89091214985782ff912559b7eb1ce085f6117db8cff65663e97325dc264b91",
},
"io_bazel_rules_scala_scalatest_freespec": {
"artifact": "org.scalatest:scalatest-freespec_2.11:3.2.9",
"sha256": "7c3e26ac0fa165263e4dac5dd303518660f581f0f8b0c20ba0b8b4a833ac9b9e",
},
"io_bazel_rules_scala_scalatest_funsuite": {
"artifact": "org.scalatest:scalatest-funsuite_2.11:3.2.9",
"sha256": "dc2100fe45b577c464f01933d8e605c3364dbac9ba24cd65222a5a4f3000717c",
},
"io_bazel_rules_scala_scalatest_funspec": {
"artifact": "org.scalatest:scalatest-funspec_2.11:3.2.9",
"sha256": "6ed2de364aacafcb3390144501ed4e0d24b7ff1431e8b9e6503d3af4bc160196",
},
"io_bazel_rules_scala_scalatest_matchers_core": {
"artifact": "org.scalatest:scalatest-matchers-core_2.11:3.2.9",
"sha256": "06eb7b5f3a8e8124c3a92e5c597a75ccdfa3fae022bc037770327d8e9c0759b4",
},
"io_bazel_rules_scala_scalatest_shouldmatchers": {
"artifact": "org.scalatest:scalatest-shouldmatchers_2.11:3.2.9",
"sha256": "444545c33a3af8d7a5166ea4766f376a5f2c209854c7eb630786c8cb3f48a706",
},
"io_bazel_rules_scala_scalatest_mustmatchers": {
"artifact": "org.scalatest:scalatest-mustmatchers_2.11:3.2.9",
"sha256": "b0ba6b9db7a2d1a4f7a3cf45b034b65481e31da8748abc2f2750cf22619d5a45",
},
"io_bazel_rules_scala_scalactic": {
"artifact": "org.scalactic:scalactic_2.11:3.2.9",
"sha256": "97b439fe61d1c655a8b29cdab8182b15b41b2308923786a348fc7b9f8f72b660",
},
"io_bazel_rules_scala_scala_xml": {
"artifact": "org.scala-lang.modules:scala-xml_2.11:1.2.0",
"sha256": "eaddac168ef1e28978af768706490fa4358323a08964c25fa1027c52238e3702",
},
"io_bazel_rules_scala_scala_parser_combinators": {
"artifact": "org.scala-lang.modules:scala-parser-combinators_2.11:1.1.2",
"sha256": "3e0889e95f5324da6420461f7147cb508241ed957ac5cfedc25eef19c5448f26",
},
"org_scalameta_common": {
"artifact": "org.scalameta:common_2.11:4.3.0",
"sha256": "6330798bcbd78d14d371202749f32efda0465c3be5fd057a6055a67e21335ba0",
"deps": [
"@com_lihaoyi_sourcecode",
"@io_bazel_rules_scala_scala_library",
],
},
"org_scalameta_fastparse": {
"artifact": "org.scalameta:fastparse_2.11:1.0.1",
"sha256": "49ecc30a4b47efc0038099da0c97515cf8f754ea631ea9f9935b36ca7d41b733",
"deps": [
"@com_lihaoyi_sourcecode",
"@io_bazel_rules_scala_scala_library",
"@org_scalameta_fastparse_utils",
],
},
"org_scalameta_fastparse_utils": {
"artifact": "org.scalameta:fastparse-utils_2.11:1.0.1",
"sha256": "93f58db540e53178a686621f7a9c401307a529b68e051e38804394a2a86cea94",
"deps": [
"@com_lihaoyi_sourcecode",
"@io_bazel_rules_scala_scala_library",
],
},
"org_scala_lang_modules_scala_collection_compat": {
"artifact": "org.scala-lang.modules:scala-collection-compat_2.11:2.1.2",
"sha256": "e9667b8b7276aeb42599f536fe4d7caab06eabc55e9995572267ad60c7a11c8b",
"deps": [
"@io_bazel_rules_scala_scala_library",
],
},
"org_scalameta_parsers": {
"artifact": "org.scalameta:parsers_2.11:4.3.0",
"sha256": "724382abfac27b32dec6c21210562bc7e1b09b5268ccb704abe66dcc8844beeb",
"deps": [
"@io_bazel_rules_scala_scala_library",
"@org_scalameta_trees",
],
},
"org_scalameta_scalafmt_core": {
"artifact": "org.scalameta:scalafmt-core_2.11:2.3.2",
"sha256": "6bf391e0e1d7369fda83ddaf7be4d267bf4cbccdf2cc31ff941999a78c30e67f",
"deps": [
"@com_geirsson_metaconfig_core",
"@com_geirsson_metaconfig_typesafe_config",
"@io_bazel_rules_scala_scala_library",
"@io_bazel_rules_scala_scala_reflect",
"@org_scalameta_scalameta",
"@org_scala_lang_modules_scala_collection_compat",
],
},
"org_scalameta_scalameta": {
"artifact": "org.scalameta:scalameta_2.11:4.3.0",
"sha256": "94fe739295447cd3ae877c279ccde1def06baea02d9c76a504dda23de1d90516",
"deps": [
"@io_bazel_rules_scala_scala_library",
"@org_scala_lang_scalap",
"@org_scalameta_parsers",
],
},
"org_scalameta_trees": {
"artifact": "org.scalameta:trees_2.11:4.3.0",
"sha256": "d24d5d63d8deafe646d455c822593a66adc6fdf17c8373754a3834a6e92a8a72",
"deps": [
"@com_thesamet_scalapb_scalapb_runtime",
"@io_bazel_rules_scala_scala_library",
"@org_scalameta_common",
"@org_scalameta_fastparse",
],
},
"org_typelevel_paiges_core": {
"artifact": "org.typelevel:paiges-core_2.11:0.2.4",
"sha256": "aa66fbe0457ca5cb5b9e522d4cb873623bb376a2e1ff58c464b5194c1d87c241",
"deps": [
"@io_bazel_rules_scala_scala_library",
],
},
"com_typesafe_config": {
"artifact": "com.typesafe:config:1.3.3",
"sha256": "b5f1d6071f1548d05be82f59f9039c7d37a1787bd8e3c677e31ee275af4a4621",
},
"org_scala_lang_scalap": {
"artifact": "org.scala-lang:scalap:2.11.12",
"sha256": "a6dd7203ce4af9d6185023d5dba9993eb8e80584ff4b1f6dec574a2aba4cd2b7",
"deps": [
"@io_bazel_rules_scala_scala_compiler",
],
},
"com_thesamet_scalapb_lenses": {
"artifact": "com.thesamet.scalapb:lenses_2.11:0.9.0",
"sha256": "f4809760edee6abc97a7fe9b7fd6ae5fe1006795b1dc3963ab4e317a72f1a385",
"deps": [
"@io_bazel_rules_scala_scala_library",
],
},
"com_thesamet_scalapb_scalapb_runtime": {
"artifact": "com.thesamet.scalapb:scalapb-runtime_2.11:0.9.0",
"sha256": "ab1e449a18a9ce411eb3fec31bdbca5dd5fae4475b1557bb5e235a7b54738757",
"deps": [
"@com_google_protobuf_protobuf_java",
"@com_lihaoyi_fastparse",
"@com_thesamet_scalapb_lenses",
"@io_bazel_rules_scala_scala_library",
],
},
"com_lihaoyi_fansi": {
"artifact": "com.lihaoyi:fansi_2.11:0.2.5",
"sha256": "1ff0a8304f322c1442e6bcf28fab07abf3cf560dd24573dbe671249aee5fc488",
"deps": [
"@com_lihaoyi_sourcecode",
"@io_bazel_rules_scala_scala_library",
],
},
"com_lihaoyi_fastparse": {
"artifact": "com.lihaoyi:fastparse_2.11:2.1.2",
"sha256": "5c5d81f90ada03ac5b21b161864a52558133951031ee5f6bf4d979e8baa03628",
"deps": [
"@com_lihaoyi_sourcecode",
],
},
"com_lihaoyi_pprint": {
"artifact": "com.lihaoyi:pprint_2.11:0.5.3",
"sha256": "fb5e4921e7dff734d049e752a482d3a031380d3eea5caa76c991312dee9e6991",
"deps": [
"@com_lihaoyi_fansi",
"@com_lihaoyi_sourcecode",
"@io_bazel_rules_scala_scala_library",
],
},
"com_lihaoyi_sourcecode": {
"artifact": "com.lihaoyi:sourcecode_2.11:0.1.7",
"sha256": "33516d7fd9411f74f05acfd5274e1b1889b7841d1993736118803fc727b2d5fc",
"deps": [
"@io_bazel_rules_scala_scala_library",
],
},
"com_google_protobuf_protobuf_java": {
"artifact": "com.google.protobuf:protobuf-java:3.10.0",
"sha256": "161d7d61a8cb3970891c299578702fd079646e032329d6c2cabf998d191437c9",
},
"com_geirsson_metaconfig_core": {
"artifact": "com.geirsson:metaconfig-core_2.11:0.9.4",
"sha256": "5d5704a1f1c4f74aed26248eeb9b577274d570b167cec0bf51d2908609c29118",
"deps": [
"@com_lihaoyi_pprint",
"@io_bazel_rules_scala_scala_library",
"@org_typelevel_paiges_core",
"@org_scala_lang_modules_scala_collection_compat",
],
},
"com_geirsson_metaconfig_typesafe_config": {
"artifact": "com.geirsson:metaconfig-typesafe-config_2.11:0.9.4",
"sha256": "52d2913640f4592402aeb2f0cec5004893d02acf26df4aa1cf8d4dcb0d2b21c7",
"deps": [
"@com_geirsson_metaconfig_core",
"@com_typesafe_config",
"@io_bazel_rules_scala_scala_library",
"@org_scala_lang_modules_scala_collection_compat",
],
},
"io_bazel_rules_scala_org_openjdk_jmh_jmh_core": {
"artifact": "org.openjdk.jmh:jmh-core:1.20",
"sha256": "1688db5110ea6413bf63662113ed38084106ab1149e020c58c5ac22b91b842ca",
},
"io_bazel_rules_scala_org_openjdk_jmh_jmh_generator_asm": {
"artifact": "org.openjdk.jmh:jmh-generator-asm:1.20",
"sha256": "2dd4798b0c9120326310cda3864cc2e0035b8476346713d54a28d1adab1414a5",
},
"io_bazel_rules_scala_org_openjdk_jmh_jmh_generator_reflection": {
"artifact": "org.openjdk.jmh:jmh-generator-reflection:1.20",
"sha256": "57706f7c8278272594a9afc42753aaf9ba0ba05980bae0673b8195908d21204e",
},
"io_bazel_rules_scala_org_ows2_asm_asm": {
"artifact": "org.ow2.asm:asm:6.1.1",
"sha256": "dd3b546415dd4bade2ebe3b47c7828ab0623ee2336604068e2d81023f9f8d833",
},
"io_bazel_rules_scala_net_sf_jopt_simple_jopt_simple": {
"artifact": "net.sf.jopt-simple:jopt-simple:4.6",
"sha256": "3fcfbe3203c2ea521bf7640484fd35d6303186ea2e08e72f032d640ca067ffda",
},
"io_bazel_rules_scala_org_apache_commons_commons_math3": {
"artifact": "org.apache.commons:commons-math3:3.6.1",
"sha256": "1e56d7b058d28b65abd256b8458e3885b674c1d588fa43cd7d1cbb9c7ef2b308",
},
"io_bazel_rules_scala_junit_junit": {
"artifact": "junit:junit:4.12",
"sha256": "59721f0805e223d84b90677887d9ff567dc534d7c502ca903c0c2b17f05c116a",
},
"io_bazel_rules_scala_org_hamcrest_hamcrest_core": {
"artifact": "org.hamcrest:hamcrest-core:1.3",
"sha256": "66fdef91e9739348df7a096aa384a5685f4e875584cce89386a7a47251c4d8e9",
},
"io_bazel_rules_scala_org_specs2_specs2_common": {
"artifact": "org.specs2:specs2-common_2.11:4.4.1",
"sha256": "52d7c0da58725606e98c6e8c81d2efe632053520a25da9140116d04a4abf9d2c",
"deps": [
"@io_bazel_rules_scala_org_specs2_specs2_fp",
],
},
"io_bazel_rules_scala_org_specs2_specs2_core": {
"artifact": "org.specs2:specs2-core_2.11:4.4.1",
"sha256": "8e95cb7e347e7a87e7a80466cbd88419ece1aaacb35c32e8bd7d299a623b31b9",
"deps": [
"@io_bazel_rules_scala_org_specs2_specs2_common",
"@io_bazel_rules_scala_org_specs2_specs2_matcher",
],
},
"io_bazel_rules_scala_org_specs2_specs2_fp": {
"artifact": "org.specs2:specs2-fp_2.11:4.4.1",
"sha256": "e43006fdd0726ffcd1e04c6c4d795176f5f765cc787cc09baebe1fcb009e4462",
},
"io_bazel_rules_scala_org_specs2_specs2_matcher": {
"artifact": "org.specs2:specs2-matcher_2.11:4.4.1",
"sha256": "448e5ab89d4d650d23030fdbee66a010a07dcac5e4c3e73ef5fe39ca1aace1cd",
"deps": [
"@io_bazel_rules_scala_org_specs2_specs2_common",
],
},
"io_bazel_rules_scala_org_specs2_specs2_junit": {
"artifact": "org.specs2:specs2-junit_2.11:4.4.1",
"sha256": "a8549d52e87896624200fe35ef7b841c1c698a8fb5d97d29bf082762aea9bb72",
"deps": [
"@io_bazel_rules_scala_org_specs2_specs2_core",
],
},
"scala_proto_rules_scalapb_plugin": {
"artifact": "com.thesamet.scalapb:compilerplugin_2.11:0.9.7",
"sha256": "2d6793fa2565953ef2b5094fc37fae4933f3c42e4cb4048d54e7f358ec104a87",
},
"scala_proto_rules_protoc_bridge": {
"artifact": "com.thesamet.scalapb:protoc-bridge_2.11:0.7.14",
"sha256": "314e34bf331b10758ff7a780560c8b5a5b09e057695a643e33ab548e3d94aa03",
},
"scala_proto_rules_scalapb_runtime": {
"artifact": "com.thesamet.scalapb:scalapb-runtime_2.11:0.9.7",
"sha256": "5131033e9536727891a38004ec707a93af1166cb8283c7db711c2c105fbf289e",
},
"scala_proto_rules_scalapb_runtime_grpc": {
"artifact": "com.thesamet.scalapb:scalapb-runtime-grpc_2.11:0.9.7",
"sha256": "24d19df500ce6450d8f7aa72a9bad675fa4f3650f7736d548aa714058f887e23",
},
"scala_proto_rules_scalapb_lenses": {
"artifact": "com.thesamet.scalapb:lenses_2.11:0.9.7",
"sha256": "f8e3b526ceac998652b296014e9ab4c0ab906a40837dd1dfcf6948b6f5a1a8bf",
},
"scala_proto_rules_scalapb_fastparse": {
"artifact": "com.lihaoyi:fastparse_2.11:2.1.2",
"sha256": "5c5d81f90ada03ac5b21b161864a52558133951031ee5f6bf4d979e8baa03628",
},
"scala_proto_rules_grpc_core": {
"artifact": "io.grpc:grpc-core:1.24.0",
"sha256": "8fc900625a9330b1c155b5423844d21be0a5574fe218a63170a16796c6f7880e",
},
"scala_proto_rules_grpc_api": {
"artifact": "io.grpc:grpc-api:1.24.0",
"sha256": "553978366e04ee8ddba64afde3b3cf2ac021a2f3c2db2831b6491d742b558598",
},
"scala_proto_rules_grpc_stub": {
"artifact": "io.grpc:grpc-stub:1.24.0",
"sha256": "eaa9201896a77a0822e26621b538c7154f00441a51c9b14dc9e1ec1f2acfb815",
},
"scala_proto_rules_grpc_protobuf": {
"artifact": "io.grpc:grpc-protobuf:1.24.0",
"sha256": "88cd0838ea32893d92cb214ea58908351854ed8de7730be07d5f7d19025dd0bc",
},
"scala_proto_rules_grpc_netty": {
"artifact": "io.grpc:grpc-netty:1.24.0",
"sha256": "8478333706ba442a354c2ddb8832d80a5aef71016e8a9cf07e7bf6e8c298f042",
},
"scala_proto_rules_grpc_context": {
"artifact": "io.grpc:grpc-context:1.24.0",
"sha256": "1f0546e18789f7445d1c5a157010a11bc038bbb31544cdb60d9da3848efcfeea",
},
"scala_proto_rules_perfmark_api": {
"artifact": "io.perfmark:perfmark-api:0.17.0",
"sha256": "816c11409b8a0c6c9ce1cda14bed526e7b4da0e772da67c5b7b88eefd41520f9",
},
"scala_proto_rules_guava": {
"artifact": "com.google.guava:guava:26.0-android",
"sha256": "1d044ebb866ef08b7d04e998b4260c9b52fab6e6d6b68d207859486bb3686cd5",
},
"scala_proto_rules_google_instrumentation": {
"artifact": "com.google.instrumentation:instrumentation-api:0.3.0",
"sha256": "671f7147487877f606af2c7e39399c8d178c492982827305d3b1c7f5b04f1145",
},
"scala_proto_rules_netty_codec": {
"artifact": "io.netty:netty-codec:4.1.32.Final",
"sha256": "dbd6cea7d7bf5a2604e87337cb67c9468730d599be56511ed0979aacb309f879",
},
"scala_proto_rules_netty_codec_http": {
"artifact": "io.netty:netty-codec-http:4.1.32.Final",
"sha256": "db2c22744f6a4950d1817e4e1a26692e53052c5d54abe6cceecd7df33f4eaac3",
},
"scala_proto_rules_netty_codec_socks": {
"artifact": "io.netty:netty-codec-socks:4.1.32.Final",
"sha256": "fe2f2e97d6c65dc280623dcfd24337d8a5c7377049c120842f2c59fb83d7408a",
},
"scala_proto_rules_netty_codec_http2": {
"artifact": "io.netty:netty-codec-http2:4.1.32.Final",
"sha256": "4d4c6cfc1f19efb969b9b0ae6cc977462d202867f7dcfee6e9069977e623a2f5",
},
"scala_proto_rules_netty_handler": {
"artifact": "io.netty:netty-handler:4.1.32.Final",
"sha256": "07d9756e48b5f6edc756e33e8b848fb27ff0b1ae087dab5addca6c6bf17cac2d",
},
"scala_proto_rules_netty_buffer": {
"artifact": "io.netty:netty-buffer:4.1.32.Final",
"sha256": "8ac0e30048636bd79ae205c4f9f5d7544290abd3a7ed39d8b6d97dfe3795afc1",
},
"scala_proto_rules_netty_transport": {
"artifact": "io.netty:netty-transport:4.1.32.Final",
"sha256": "175bae0d227d7932c0c965c983efbb3cf01f39abe934f5c4071d0319784715fb",
},
"scala_proto_rules_netty_resolver": {
"artifact": "io.netty:netty-resolver:4.1.32.Final",
"sha256": "9b4a19982047a95ea4791a7ad7ad385c7a08c2ac75f0a3509cc213cb32a726ae",
},
"scala_proto_rules_netty_common": {
"artifact": "io.netty:netty-common:4.1.32.Final",
"sha256": "cc993e660f8f8e3b033f1d25a9e2f70151666bdf878d460a6508cb23daa696dc",
},
"scala_proto_rules_netty_handler_proxy": {
"artifact": "io.netty:netty-handler-proxy:4.1.32.Final",
"sha256": "10d1081ed114bb0e76ebbb5331b66a6c3189cbdefdba232733fc9ca308a6ea34",
},
"scala_proto_rules_opencensus_api": {
"artifact": "io.opencensus:opencensus-api:0.22.1",
"sha256": "62a0503ee81856ba66e3cde65dee3132facb723a4fa5191609c84ce4cad36127",
},
"scala_proto_rules_opencensus_impl": {
"artifact": "io.opencensus:opencensus-impl:0.22.1",
"sha256": "9e8b209da08d1f5db2b355e781b9b969b2e0dab934cc806e33f1ab3baed4f25a",
},
"scala_proto_rules_disruptor": {
"artifact": "com.lmax:disruptor:3.4.2",
"sha256": "f412ecbb235c2460b45e63584109723dea8d94b819c78c9bfc38f50cba8546c0",
},
"scala_proto_rules_opencensus_impl_core": {
"artifact": "io.opencensus:opencensus-impl-core:0.22.1",
"sha256": "04607d100e34bacdb38f93c571c5b7c642a1a6d873191e25d49899668514db68",
},
"scala_proto_rules_opencensus_contrib_grpc_metrics": {
"artifact": "io.opencensus:opencensus-contrib-grpc-metrics:0.22.1",
"sha256": "3f6f4d5bd332c516282583a01a7c940702608a49ed6e62eb87ef3b1d320d144b",
},
"io_bazel_rules_scala_mustache": {
"artifact": "com.github.spullara.mustache.java:compiler:0.8.18",
"sha256": "ddabc1ef897fd72319a761d29525fd61be57dc25d04d825f863f83cc89000e66",
},
"io_bazel_rules_scala_guava": {
"artifact": "com.google.guava:guava:21.0",
"sha256": "972139718abc8a4893fa78cba8cf7b2c903f35c97aaf44fa3031b0669948b480",
},
"libthrift": {
"artifact": "org.apache.thrift:libthrift:0.10.0",
"sha256": "8591718c1884ac8001b4c5ca80f349c0a6deec691de0af720c5e3bc3a581dada",
},
"io_bazel_rules_scala_scrooge_core": {
"artifact": "com.twitter:scrooge-core_2.11:21.2.0",
"sha256": "d6cef1408e34b9989ea8bc4c567dac922db6248baffe2eeaa618a5b354edd2bb",
},
"io_bazel_rules_scala_scrooge_generator": {
"artifact": "com.twitter:scrooge-generator_2.11:21.2.0",
"sha256": "87094f01df2c0670063ab6ebe156bb1a1bcdabeb95bc45552660b030287d6acb",
"runtime_deps": [
"@io_bazel_rules_scala_guava",
"@io_bazel_rules_scala_mustache",
"@io_bazel_rules_scala_scopt",
],
},
"io_bazel_rules_scala_util_core": {
"artifact": "com.twitter:util-core_2.11:21.2.0",
"sha256": "31c33d494ca5a877c1e5b5c1f569341e1d36e7b2c8b3fb0356fb2b6d4a3907ca",
},
"io_bazel_rules_scala_util_logging": {
"artifact": "com.twitter:util-logging_2.11:21.2.0",
"sha256": "f3b62465963fbf0fe9860036e6255337996bb48a1a3f21a29503a2750d34f319",
},
"io_bazel_rules_scala_javax_annotation_api": {
"artifact": "javax.annotation:javax.annotation-api:1.3.2",
"sha256": "e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b",
},
"io_bazel_rules_scala_scopt": {
"artifact": "com.github.scopt:scopt_2.11:4.0.0-RC2",
"sha256": "956dfc89d3208e4a6d8bbfe0205410c082cee90c4ce08be30f97c044dffc3435",
},
# test only
"com_twitter__scalding_date": {
"testonly": True,
"artifact": "com.twitter:scalding-date_2.11:0.17.0",
"sha256": "bf743cd6d224a4568d6486a2b794143e23145d2afd7a1d2de412d49e45bdb308",
},
"org_typelevel__cats_core": {
"testonly": True,
"artifact": "org.typelevel:cats-core_2.11:0.9.0",
"sha256": "3fda7a27114b0d178107ace5c2cf04e91e9951810690421768e65038999ffca5",
},
"com_google_guava_guava_21_0_with_file": {
"testonly": True,
"artifact": "com.google.guava:guava:21.0",
"sha256": "972139718abc8a4893fa78cba8cf7b2c903f35c97aaf44fa3031b0669948b480",
},
"com_github_jnr_jffi_native": {
"testonly": True,
"artifact": "com.github.jnr:jffi:jar:native:1.2.17",
"sha256": "4eb582bc99d96c8df92fc6f0f608fd123d278223982555ba16219bf8be9f75a9",
},
"org_apache_commons_commons_lang_3_5": {
"testonly": True,
"artifact": "org.apache.commons:commons-lang3:3.5",
"sha256": "8ac96fc686512d777fca85e144f196cd7cfe0c0aec23127229497d1a38ff651c",
},
"org_springframework_spring_core": {
"testonly": True,
"artifact": "org.springframework:spring-core:5.1.5.RELEASE",
"sha256": "f771b605019eb9d2cf8f60c25c050233e39487ff54d74c93d687ea8de8b7285a",
},
"org_springframework_spring_tx": {
"testonly": True,
"artifact": "org.springframework:spring-tx:5.1.5.RELEASE",
"sha256": "666f72b73c7e6b34e5bb92a0d77a14cdeef491c00fcb07a1e89eb62b08500135",
"deps": [
"@org_springframework_spring_core",
],
},
"com_google_guava_guava_21_0": {
"testonly": True,
"artifact": "com.google.guava:guava:21.0",
"sha256": "972139718abc8a4893fa78cba8cf7b2c903f35c97aaf44fa3031b0669948b480",
"deps": [
"@org_springframework_spring_core",
],
},
"org_spire_math_kind_projector": {
"testonly": True,
"artifact": "org.spire-math:kind-projector_2.11:0.9.10",
"sha256": "897460d4488b7dd6ac9198937d6417b36cc6ec8ab3693fdf2c532652f26c4373",
},
}
|
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
|
# The opcode tables were taken from Mammon_'s Guide to Writing Disassemblers in Perl, You Morons!"
# and the bastard project. http://www.eccentrix.com/members/mammon/
INSTR_PREFIX = 0xF0000000
ADDRMETH_MASK = 0x00FF0000
ADDRMETH_A = 0x00010000 # Direct address with segment prefix
ADDRMETH_B = 0x00020000 # VEX.vvvv field selects general purpose register
ADDRMETH_C = 0x00030000 # MODRM reg field defines control register
ADDRMETH_D = 0x00040000 # MODRM reg field defines debug register
ADDRMETH_E = 0x00050000 # MODRM byte defines reg/memory address
ADDRMETH_F = 0x00060000 # EFLAGS/RFLAGS register
ADDRMETH_G = 0x00070000 # MODRM byte defines general-purpose reg
ADDRMETH_H = 0x00080000 # VEX.vvvv field selects 128bit XMM or 256bit YMM register
ADDRMETH_I = 0x00090000 # Immediate data follows
ADDRMETH_J = 0x000A0000 # Immediate value is relative to EIP
ADDRMETH_L = 0x000B0000 # An immediate value follows, but bits[7:4] signifies an xmm register
ADDRMETH_M = 0x000C0000 # MODRM mod field can refer only to memory
ADDRMETH_N = 0x000D0000 # R/M field of MODRM selects a packed-quadword, MMX register
ADDRMETH_O = 0x000E0000 # Displacement follows (without modrm/sib)
ADDRMETH_P = 0x000F0000 # MODRM reg field defines MMX register
ADDRMETH_Q = 0x00100000 # MODRM defines MMX register or memory
ADDRMETH_R = 0x00110000 # MODRM mod field can only refer to register
ADDRMETH_S = 0x00120000 # MODRM reg field defines segment register
ADDRMETH_U = 0x00130000 # MODRM R/M field defines XMM register
ADDRMETH_V = 0x00140000 # MODRM reg field defines XMM register
ADDRMETH_W = 0x00150000 # MODRM defines XMM register or memory
ADDRMETH_X = 0x00160000 # Memory addressed by DS:rSI
ADDRMETH_Y = 0x00170000 # Memory addressd by ES:rDI
ADDRMETH_VEXH = 0x00180000 # Maybe Ignore the VEX.vvvv field based on what the ModRM bytes are
ADDRMETH_LAST = ADDRMETH_VEXH
ADDRMETH_VEXSKIP = 0x00800000 # This operand should be skipped if we're not in VEX mode
OPTYPE_a = 0x01000000 # 2/4 two one-word operands in memory or two double-word operands in memory (operand-size attribute)
OPTYPE_b = 0x02000000 # 1 always 1 byte
OPTYPE_c = 0x03000000 # 1/2 byte or word, depending on operand
OPTYPE_d = 0x04000000 # 4 double-word
OPTYPE_ds = 0x04000000 # 4 double-word
OPTYPE_dq = 0x05000000 # 16 double quad-word
OPTYPE_p = 0x06000000 # 4/6 32-bit or 48-bit pointer
OPTYPE_pi = 0x07000000 # 8 quadword MMX register
OPTYPE_ps = 0x08000000 # 16 128-bit single-precision float (packed?)
OPTYPE_pd = 0x08000000 # ?? should be a double-precision float?
OPTYPE_q = 0x09000000 # 8 quad-word
OPTYPE_qp = 0x09000000 # 8 quad-word
OPTYPE_qq = 0x0A000000 # 8 quad-word
OPTYPE_s = 0x0B000000 # 6 6-byte pseudo descriptor
OPTYPE_ss = 0x0C000000 # ?? Scalar of 128-bit single-precision float
OPTYPE_si = 0x0D000000 # 4 Doubleword integer register
OPTYPE_sd = 0x0E000000 # Scalar double precision float
OPTYPE_v = 0x0F000000 # 2/4 word or double-word, depending on operand
OPTYPE_w = 0x10000000 # 2 always word
OPTYPE_x = 0x11000000 # 2 double-quadword or quad-quadword
OPTYPE_y = 0x12000000 # 4/8 dword or qword
OPTYPE_z = 0x13000000 # 2/4 is this OPTYPE_z? word for 16-bit operand size or doubleword for 32 or 64-bit operand-size
OPTYPE_fs = 0x14000000
OPTYPE_fd = 0x15000000
OPTYPE_fe = 0x16000000
OPTYPE_fb = 0x17000000
OPTYPE_fv = 0x18000000
# FIXME this should probably be a list rather than a dictionary
OPERSIZE = {
0: (2, 4, 8), # We will only end up here on regs embedded in opcodes
OPTYPE_a: (2, 4, 4),
OPTYPE_b: (1, 1, 1),
OPTYPE_c: (1, 2, 2), # 1/2 byte or word, depending on operand
OPTYPE_d: (4, 4, 4), # 4 double-word
OPTYPE_dq: (16, 16, 16), # 16 double quad-word
OPTYPE_p: (4, 6, 6), # 4/6 32-bit or 48-bit pointer
OPTYPE_pi: (8, 8, 8), # 8 quadword MMX register
OPTYPE_ps: (16, 16, 16), # 16 128-bit single-precision float
OPTYPE_pd: (16, 16, 16), # ?? should be a double-precision float?
OPTYPE_q: (8, 8, 8), # 8 quad-word
OPTYPE_qq: (32, 32, 32), # 32 quad-quad-word
OPTYPE_s: (6, 10, 10), # 6 6-byte pseudo descriptor
OPTYPE_ss: (16, 16, 16), # ?? Scalar of 128-bit single-precision float
OPTYPE_si: (4, 4, 4), # 4 Doubleword integer register
OPTYPE_sd: (16, 16, 16), # ??? Scalar of 128-bit double-precision float
OPTYPE_v: (2, 4, 8), # 2/4 word or double-word, depending on operand
OPTYPE_w: (2, 2, 2), # 2 always word
OPTYPE_x: (16, 16, 32), # 16/32 double-quadword or quad-quadword
OPTYPE_y: (4, 4, 8), # 4/8 dword or qword in 64-bit mode
OPTYPE_z: (2, 4, 4), # word for 16-bit operand size or doubleword for 32 or 64-bit operand-size
# Floating point crazyness FIXME these are mostly wrong
OPTYPE_fs: (4, 4, 4),
OPTYPE_fd: (8, 8, 8),
OPTYPE_fe: (10, 10, 10),
OPTYPE_fb: (10, 10, 10),
OPTYPE_fv: (14, 14, 28),
}
INS_NOPREF = 0x10000 # This instruction diallows prefixes, and if it does, it's a different insttruction
INS_VEXREQ = 0x20000 # This instructions requires VEX
INS_VEXNOPREF = 0x40000 # This instruction doesn't get the "v" prefix common to VEX instructions
INS_EXEC = 0x1000
INS_ARITH = 0x2000
INS_LOGIC = 0x3000
INS_STACK = 0x4000
INS_COND = 0x5000
INS_LOAD = 0x6000
INS_ARRAY = 0x7000
INS_BIT = 0x8000
INS_FLAG = 0x9000
INS_FPU = 0xA000
INS_TRAPS = 0xD000
INS_SYSTEM = 0xE000
INS_OTHER = 0xF000
INS_BRANCH = INS_EXEC | 0x01
INS_BRANCHCC = INS_EXEC | 0x02
INS_CALL = INS_EXEC | 0x03
INS_CALLCC = INS_EXEC | 0x04
INS_RET = INS_EXEC | 0x05
INS_LOOP = INS_EXEC | 0x06
INS_ADD = INS_ARITH | 0x01
INS_SUB = INS_ARITH | 0x02
INS_MUL = INS_ARITH | 0x03
INS_DIV = INS_ARITH | 0x04
INS_INC = INS_ARITH | 0x05
INS_DEC = INS_ARITH | 0x06
INS_SHL = INS_ARITH | 0x07
INS_SHR = INS_ARITH | 0x08
INS_ROL = INS_ARITH | 0x09
INS_ROR = INS_ARITH | 0x0A
INS_ABS = INS_ARITH | 0x0B
INS_AND = INS_LOGIC | 0x01
INS_OR = INS_LOGIC | 0x02
INS_XOR = INS_LOGIC | 0x03
INS_NOT = INS_LOGIC | 0x04
INS_NEG = INS_LOGIC | 0x05
INS_PUSH = INS_STACK | 0x01
INS_POP = INS_STACK | 0x02
INS_PUSHREGS = INS_STACK | 0x03
INS_POPREGS = INS_STACK | 0x04
INS_PUSHFLAGS = INS_STACK | 0x05
INS_POPFLAGS = INS_STACK | 0x06
INS_ENTER = INS_STACK | 0x07
INS_LEAVE = INS_STACK | 0x08
INS_TEST = INS_COND | 0x01
INS_CMP = INS_COND | 0x02
INS_MOV = INS_LOAD | 0x01
INS_MOVCC = INS_LOAD | 0x02
INS_XCHG = INS_LOAD | 0x03
INS_XCHGCC = INS_LOAD | 0x04
INS_LEA = INS_LOAD | 0x05
INS_STRCMP = INS_ARRAY | 0x01
INS_STRLOAD = INS_ARRAY | 0x02
INS_STRMOV = INS_ARRAY | 0x03
INS_STRSTOR = INS_ARRAY | 0x04
INS_XLAT = INS_ARRAY | 0x05
INS_BITTEST = INS_BIT | 0x01
INS_BITSET = INS_BIT | 0x02
INS_BITCLR = INS_BIT | 0x03
INS_CLEARCF = INS_FLAG | 0x01
INS_CLEARZF = INS_FLAG | 0x02
INS_CLEAROF = INS_FLAG | 0x03
INS_CLEARDF = INS_FLAG | 0x04
INS_CLEARSF = INS_FLAG | 0x05
INS_CLEARPF = INS_FLAG | 0x06
INS_SETCF = INS_FLAG | 0x07
INS_SETZF = INS_FLAG | 0x08
INS_SETOF = INS_FLAG | 0x09
INS_SETDF = INS_FLAG | 0x0A
INS_SETSF = INS_FLAG | 0x0B
INS_SETPF = INS_FLAG | 0x0C
INS_CLEARAF = INS_FLAG | 0x0D
INS_SETAF = INS_FLAG | 0x0E
INS_TOGCF = INS_FLAG | 0x10 # /* toggle */
INS_TOGZF = INS_FLAG | 0x20
INS_TOGOF = INS_FLAG | 0x30
INS_TOGDF = INS_FLAG | 0x40
INS_TOGSF = INS_FLAG | 0x50
INS_TOGPF = INS_FLAG | 0x60
INS_TRAP = INS_TRAPS | 0x01 # generate trap
INS_TRAPCC = INS_TRAPS | 0x02 # conditional trap gen
INS_TRET = INS_TRAPS | 0x03 # return from trap
INS_BOUNDS = INS_TRAPS | 0x04 # gen bounds trap
INS_DEBUG = INS_TRAPS | 0x05 # gen breakpoint trap
INS_TRACE = INS_TRAPS | 0x06 # gen single step trap
INS_INVALIDOP = INS_TRAPS | 0x07 # gen invalid instruction
INS_OFLOW = INS_TRAPS | 0x08 # gen overflow trap
#/* INS_SYSTEM */
INS_HALT = INS_SYSTEM | 0x01 # halt machine
INS_IN = INS_SYSTEM | 0x02 # input form port
INS_OUT = INS_SYSTEM | 0x03 # output to port
INS_CPUID = INS_SYSTEM | 0x04 # iden
INS_NOP = INS_OTHER | 0x01
INS_BCDCONV = INS_OTHER | 0x02 # convert to/from BCD
INS_SZCONV = INS_OTHER | 0x03 # convert size of operand
INS_CRYPT = INS_OTHER | 0x4 # AES-NI instruction support
OP_R = 0x001
OP_W = 0x002
OP_X = 0x004
OP_64AUTO = 0x008 # operand is in 64bit mode with amd64!
# So these this exists is because in the opcode mappings intel puts out, they very
# *specifically* call out things like pmovsx* using U/M for their operand mappings,
# but *not* W. The reason for this being there
# is a size difference between the U and M portions, whereas W uses a uniform size for both
OP_MEM_B = 0x010 # force only *memory* to be 8 bit.
OP_MEM_W = 0x020 # force only *memory* to be 16 bit.
OP_MEM_D = 0x030 # force only *memory* to be 32 bit.
OP_MEM_Q = 0x040 # force only *memory* to be 64 bit.
OP_MEM_DQ = 0x050 # force only *memory* to be 128 bit.
OP_MEM_QQ = 0x060 # force only *memory* to be 256 bit.
OP_MEMMASK = 0x070 # this forces the memory to be a different size than the register. Reaches into OP_EXTRA_MEMSIZES
OP_NOVEXL = 0x080 # don't apply VEX.L here (even though it's set). TLDR: always 128/xmm reg
OP_EXTRA_MEMSIZES = [None, 1, 2, 4, 8, 16, 32]
OP_UNK = 0x000
OP_REG = 0x100
OP_IMM = 0x200
OP_REL = 0x300
OP_ADDR = 0x400
OP_EXPR = 0x500
OP_PTR = 0x600
OP_OFF = 0x700
OP_SIGNED = 0x001000
OP_STRING = 0x002000
OP_CONST = 0x004000
OP_NOREX = 0x008000
ARG_NONE = 0
cpu_8086 = 0x00001000
cpu_80286 = 0x00002000
cpu_80386 = 0x00003000
cpu_80387 = 0x00004000
cpu_80486 = 0x00005000
cpu_PENTIUM = 0x00006000
cpu_PENTPRO = 0x00007000
cpu_PENTMMX = 0x00008000
cpu_PENTIUM2 = 0x00009000
cpu_AMD64 = 0x0000a000
cpu_AESNI = 0x0000b000
cpu_AVX = 0x0000c000
cpu_BMI = 0x0000d000
#eventually, change this for your own codes
#ADDEXP_SCALE_OFFSET= 0
#ADDEXP_INDEX_OFFSET= 8
#ADDEXP_BASE_OFFSET = 16
#ADDEXP_DISP_OFFSET = 24
#MODRM_EA = 1
#MODRM_reg= 0
ADDRMETH_MASK = 0x00FF0000
OPTYPE_MASK = 0xFF000000
OPFLAGS_MASK = 0x0000FFFF
# NOTE: some notes from the intel manual...
# REX.W overrides 66, but alternate registers (via REX.B etc..) can have 66 to be 16 bit..
# REX.R only modifies reg for GPR/SSE(SIMD)/ctrl/debug addressing modes.
# REX.X only modifies the SIB index value
# REX.B modifies modrm r/m field, or SIB base (if SIB present), or opcode reg.
# We inherit all the regular intel prefixes...
# VEX replaces REX, and mixing them is invalid
PREFIX_REX = 0x100000 # Shows that the rex prefix is present
PREFIX_REX_B = 0x010000 # Bit 0 in REX prefix (0x41) means ModR/M r/m field, SIB base, or opcode reg
PREFIX_REX_X = 0x020000 # Bit 1 in REX prefix (0x42) means SIB index extension
PREFIX_REX_R = 0x040000 # Bit 2 in REX prefix (0x44) means ModR/M reg extention
PREFIX_REX_W = 0x080000 # Bit 3 in REX prefix (0x48) means 64 bit operand
PREFIX_REX_MASK = PREFIX_REX_B | PREFIX_REX_X | PREFIX_REX_W | PREFIX_REX_R
PREFIX_REX_RXB = PREFIX_REX_B | PREFIX_REX_X | PREFIX_REX_R
|
class StubCursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return self.row, self.column
@coords.setter
def coords(self, coords):
self.row, self.column = coords
|
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2010-2019 fasiondog/hikyuu
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class MARKET:
SH = 'SH'
SZ = 'SZ'
class MARKETID:
SH = 1
SZ = 2
class STOCKTYPE:
BLOCK = 0 #板块
A = 1 #A股
INDEX = 2 #指数
B = 3 #B股
FUND = 4 #基金(非ETF)
ETF = 5 #ETF
ND = 6 #国债
BOND = 7 #其他债券
GEM = 8 #创业板
BTC = 9 #数字币
def get_stktype_list(quotations=None):
"""
根据行情类别获取股票类别元组
:param quotations: 'stock'(股票) | 'fund'(基金) | 'bond'(债券)
:rtype: tuple
:return: 股票类别元组
"""
if not quotations:
return (1, 2, 3, 4, 5, 6, 7, 8, 9)
result = []
for quotation in quotations:
new_quotation = quotation.lower()
if new_quotation == 'stock':
result += [STOCKTYPE.A, STOCKTYPE.INDEX, STOCKTYPE.B, STOCKTYPE.GEM]
elif new_quotation == 'fund':
result += [STOCKTYPE.FUND, STOCKTYPE.ETF]
elif new_quotation == 'bond':
result += [STOCKTYPE.ND, STOCKTYPE.BOND]
else:
print('Unknow quotation: {}'.format(quotation))
return tuple(result)
|
cont = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez')
n = int(input('Digite um número entre 0 e 10: '))
print(f'Você digitou o número {cont[n]}.')
|
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
return a + b
if __name__ == '__main__':
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
obj = Calculator(a, b)
choice = 1
while choice != 0:
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("0. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print("Result: ", obj.add())
elif choice == 2:
print("Result: ", obj.sub())
elif choice == 3:
print("Result: ", obj.mul())
elif choice == 4:
print("Result: ", round(obj.div(), 2))
elif choice == 0:
print("Exiting!")
else:
print("Invalid choice!!")
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'verbose_libraries_build%': 0,
'instrumented_libraries_jobs%': 1,
'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang',
'instrumented_libraries_cxx%': '<!(cd <(DEPTH) && pwd -P)/<(make_clang_dir)/bin/clang++',
},
'libdir': 'lib',
'ubuntu_release': '<!(lsb_release -cs)',
'conditions': [
['asan==1', {
'sanitizer_type': 'asan',
}],
['msan==1', {
'sanitizer_type': 'msan',
}],
['tsan==1', {
'sanitizer_type': 'tsan',
}],
['use_goma==1', {
'cc': '<(gomadir)/gomacc <(instrumented_libraries_cc)',
'cxx': '<(gomadir)/gomacc <(instrumented_libraries_cxx)',
}, {
'cc': '<(instrumented_libraries_cc)',
'cxx': '<(instrumented_libraries_cxx)',
}],
],
'target_defaults': {
'build_method': 'destdir',
# Every package must have --disable-static in configure flags to avoid
# building unnecessary static libs. Ideally we should add it here.
# Unfortunately, zlib1g doesn't support that flag and for some reason it
# can't be removed with a GYP exclusion list. So instead we add that flag
# manually to every package but zlib1g.
'extra_configure_flags': [],
'jobs': '<(instrumented_libraries_jobs)',
'package_cflags': [
'-O2',
'-gline-tables-only',
'-fPIC',
'-w',
'-U_FORITFY_SOURCE',
'-fno-omit-frame-pointer'
],
'package_ldflags': [
'-Wl,-z,origin',
# We set RPATH=XORIGIN when building the package and replace it with
# $ORIGIN later. The reason is that this flag goes through configure/make
# differently for different packages. Because of this, we can't escape the
# $ character in a way that would work for every package.
'-Wl,-R,XORIGIN/.'
],
'patch': '',
'pre_build': '',
'asan_blacklist': '',
'msan_blacklist': '',
'tsan_blacklist': '',
'conditions': [
['asan==1', {
'package_cflags': ['-fsanitize=address'],
'package_ldflags': ['-fsanitize=address'],
}],
['msan==1', {
'package_cflags': [
'-fsanitize=memory',
'-fsanitize-memory-track-origins=<(msan_track_origins)'
],
'package_ldflags': ['-fsanitize=memory'],
}],
['tsan==1', {
'package_cflags': ['-fsanitize=thread'],
'package_ldflags': ['-fsanitize=thread'],
}],
],
},
'targets': [
{
'target_name': 'prebuilt_instrumented_libraries',
'type': 'none',
'variables': {
'prune_self_dependency': 1,
# Don't add this target to the dependencies of targets with type=none.
'link_dependency': 1,
'conditions': [
['msan==1', {
'conditions': [
['msan_track_origins==2', {
'archive_prefix': 'msan-chained-origins',
}, {
'conditions': [
['msan_track_origins==0', {
'archive_prefix': 'msan-no-origins',
}, {
'archive_prefix': 'UNSUPPORTED_CONFIGURATION'
}],
]}],
]}, {
'archive_prefix': 'UNSUPPORTED_CONFIGURATION'
}],
],
},
'actions': [
{
'action_name': 'unpack_<(archive_prefix)-<(_ubuntu_release).tgz',
'inputs': [
'binaries/<(archive_prefix)-<(_ubuntu_release).tgz',
],
'outputs': [
'<(PRODUCT_DIR)/instrumented_libraries_prebuilt/<(archive_prefix).txt',
],
'action': [
'scripts/unpack_binaries.py',
'<(archive_prefix)',
'binaries',
'<(PRODUCT_DIR)/instrumented_libraries_prebuilt/',
],
},
],
'direct_dependent_settings': {
'target_conditions': [
['_toolset=="target"', {
'ldflags': [
# Add a relative RPATH entry to Chromium binaries. This puts
# instrumented DSOs before system-installed versions in library
# search path.
'-Wl,-R,\$$ORIGIN/instrumented_libraries_prebuilt/<(_sanitizer_type)/<(_libdir)/',
'-Wl,-z,origin',
],
}],
],
},
},
{
'target_name': 'instrumented_libraries',
'type': 'none',
'variables': {
'prune_self_dependency': 1,
# Don't add this target to the dependencies of targets with type=none.
'link_dependency': 1,
},
# NOTE: Please keep install-build-deps.sh in sync with this list.
'dependencies': [
'<(_sanitizer_type)-freetype',
'<(_sanitizer_type)-libcairo2',
'<(_sanitizer_type)-libexpat1',
'<(_sanitizer_type)-libffi6',
'<(_sanitizer_type)-libgcrypt11',
'<(_sanitizer_type)-libgpg-error0',
'<(_sanitizer_type)-libnspr4',
'<(_sanitizer_type)-libp11-kit0',
'<(_sanitizer_type)-libpcre3',
'<(_sanitizer_type)-libpng12-0',
'<(_sanitizer_type)-libx11-6',
'<(_sanitizer_type)-libxau6',
'<(_sanitizer_type)-libxcb1',
'<(_sanitizer_type)-libxcomposite1',
'<(_sanitizer_type)-libxcursor1',
'<(_sanitizer_type)-libxdamage1',
'<(_sanitizer_type)-libxdmcp6',
'<(_sanitizer_type)-libxext6',
'<(_sanitizer_type)-libxfixes3',
'<(_sanitizer_type)-libxi6',
'<(_sanitizer_type)-libxinerama1',
'<(_sanitizer_type)-libxrandr2',
'<(_sanitizer_type)-libxrender1',
'<(_sanitizer_type)-libxss1',
'<(_sanitizer_type)-libxtst6',
'<(_sanitizer_type)-zlib1g',
'<(_sanitizer_type)-libglib2.0-0',
'<(_sanitizer_type)-libdbus-1-3',
'<(_sanitizer_type)-libdbus-glib-1-2',
'<(_sanitizer_type)-nss',
'<(_sanitizer_type)-libfontconfig1',
'<(_sanitizer_type)-pulseaudio',
'<(_sanitizer_type)-libasound2',
'<(_sanitizer_type)-pango1.0',
'<(_sanitizer_type)-libcap2',
'<(_sanitizer_type)-udev',
'<(_sanitizer_type)-libgnome-keyring0',
'<(_sanitizer_type)-libgtk2.0-0',
'<(_sanitizer_type)-libgdk-pixbuf2.0-0',
'<(_sanitizer_type)-libpci3',
'<(_sanitizer_type)-libdbusmenu-glib4',
'<(_sanitizer_type)-libgconf-2-4',
'<(_sanitizer_type)-libappindicator1',
'<(_sanitizer_type)-libdbusmenu',
'<(_sanitizer_type)-atk1.0',
'<(_sanitizer_type)-libunity9',
'<(_sanitizer_type)-dee',
'<(_sanitizer_type)-libpixman-1-0',
'<(_sanitizer_type)-brltty',
'<(_sanitizer_type)-libva1',
'<(_sanitizer_type)-libcredentialkit_pkcs11-stub',
],
'conditions': [
['"<(_ubuntu_release)"=="precise"', {
'dependencies': [
'<(_sanitizer_type)-libtasn1-3',
],
}, {
'dependencies': [
# Trusty and above.
'<(_sanitizer_type)-libtasn1-6',
'<(_sanitizer_type)-harfbuzz',
'<(_sanitizer_type)-libsecret',
],
}],
['msan==1', {
'dependencies': [
'<(_sanitizer_type)-libcups2',
],
}],
['tsan==1', {
'dependencies!': [
'<(_sanitizer_type)-libpng12-0',
],
}],
],
'direct_dependent_settings': {
'target_conditions': [
['_toolset=="target"', {
'ldflags': [
# Add a relative RPATH entry to Chromium binaries. This puts
# instrumented DSOs before system-installed versions in library
# search path.
'-Wl,-R,\$$ORIGIN/instrumented_libraries/<(_sanitizer_type)/<(_libdir)/',
'-Wl,-z,origin',
],
}],
],
},
},
{
'package_name': 'freetype',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'pre_build': 'scripts/pre-build/freetype.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libcairo2',
'dependencies=': [],
'extra_configure_flags': [
'--disable-gtk-doc',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libdbus-1-3',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--disable-libaudit',
'--enable-apparmor',
'--enable-systemd',
'--libexecdir=/lib/dbus-1.0',
'--with-systemdsystemunitdir=/lib/systemd/system',
'--disable-tests',
'--exec-prefix=/',
# From dh_auto_configure.
'--prefix=/usr',
'--localstatedir=/var',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libdbus-glib-1-2',
'dependencies=': [],
'extra_configure_flags': [
# Use system dbus-binding-tool. The just-built one is instrumented but
# doesn't have the correct RPATH, and will crash.
'--with-dbus-binding-tool=dbus-binding-tool',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libexpat1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libffi6',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libfontconfig1',
'dependencies=': [],
'extra_configure_flags': [
'--disable-docs',
'--sysconfdir=/etc/',
'--disable-static',
# From debian/rules.
'--with-add-fonts=/usr/X11R6/lib/X11/fonts,/usr/local/share/fonts',
],
'conditions': [
['"<(_ubuntu_release)"=="precise"', {
'patch': 'patches/libfontconfig.precise.diff',
}, {
'patch': 'patches/libfontconfig.trusty.diff',
}],
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgcrypt11',
'dependencies=': [],
'package_ldflags': ['-Wl,-z,muldefs'],
'extra_configure_flags': [
# From debian/rules.
'--enable-noexecstack',
'--enable-ld-version-script',
'--disable-static',
# http://crbug.com/344505
'--disable-asm'
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libglib2.0-0',
'dependencies=': [],
'extra_configure_flags': [
'--disable-gtk-doc',
'--disable-gtk-doc-html',
'--disable-gtk-doc-pdf',
'--disable-static',
],
'asan_blacklist': 'blacklists/asan/libglib2.0-0.txt',
'msan_blacklist': 'blacklists/msan/libglib2.0-0.txt',
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgpg-error0',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libnspr4',
'dependencies=': [],
'extra_configure_flags': [
'--enable-64bit',
'--disable-static',
# TSan reports data races on debug variables.
'--disable-debug',
],
'pre_build': 'scripts/pre-build/libnspr4.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libp11-kit0',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
# Required on Trusty due to autoconf version mismatch.
'pre_build': 'scripts/pre-build/autoreconf.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libpcre3',
'dependencies=': [],
'extra_configure_flags': [
'--enable-utf8',
'--enable-unicode-properties',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libpixman-1-0',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--disable-gtk',
'--disable-silent-rules',
# Avoid a clang issue. http://crbug.com/449183
'--disable-mmx',
],
'patch': 'patches/libpixman-1-0.diff',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libpng12-0',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libx11-6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-specs',
'--disable-static',
],
'msan_blacklist': 'blacklists/msan/libx11-6.txt',
# Required on Trusty due to autoconf version mismatch.
'pre_build': 'scripts/pre-build/autoreconf.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxau6',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxcb1',
'dependencies=': [],
'extra_configure_flags': [
'--disable-build-docs',
'--disable-static',
],
'conditions': [
['"<(_ubuntu_release)"=="precise"', {
# Backport fix for https://bugs.freedesktop.org/show_bug.cgi?id=54671
'patch': 'patches/libxcb1.precise.diff',
}],
],
# Required on Trusty due to autoconf version mismatch.
'pre_build': 'scripts/pre-build/autoreconf.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxcomposite1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxcursor1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxdamage1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxdmcp6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-docs',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxext6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-specs',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxfixes3',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxi6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-specs',
'--disable-docs',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxinerama1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxrandr2',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxrender1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxss1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libxtst6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-specs',
'--disable-static',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'zlib1g',
'dependencies=': [],
# --disable-static is not supported
'patch': 'patches/zlib1g.diff',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'nss',
'dependencies=': [
# TODO(eugenis): get rid of this dependency
'<(_sanitizer_type)-libnspr4',
],
'patch': 'patches/nss.diff',
'build_method': 'custom_nss',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'pulseaudio',
'dependencies=': [],
'conditions': [
['"<(_ubuntu_release)"=="precise"', {
'patch': 'patches/pulseaudio.precise.diff',
'jobs': 1,
}, {
# New location of libpulsecommon.
'package_ldflags': [ '-Wl,-R,XORIGIN/pulseaudio/.' ],
}],
],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--enable-x11',
'--disable-hal-compat',
# Disable some ARM-related code that fails compilation. No idea why
# this even impacts x86-64 builds.
'--disable-neon-opt'
],
'pre_build': 'scripts/pre-build/pulseaudio.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libasound2',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'pre_build': 'scripts/pre-build/libasound2.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libcups2',
'dependencies=': [],
'patch': 'patches/libcups2.diff',
'jobs': 1,
'extra_configure_flags': [
'--disable-static',
# All from debian/rules.
'--localedir=/usr/share/cups/locale',
'--enable-slp',
'--enable-libpaper',
'--enable-ssl',
'--enable-gnutls',
'--disable-openssl',
'--enable-threads',
'--enable-debug',
'--enable-dbus',
'--with-dbusdir=/etc/dbus-1',
'--enable-gssapi',
'--enable-avahi',
'--with-pdftops=/usr/bin/gs',
'--disable-launchd',
'--with-cups-group=lp',
'--with-system-groups=lpadmin',
'--with-printcap=/var/run/cups/printcap',
'--with-log-file-perm=0640',
'--with-local_protocols="CUPS dnssd"',
'--with-remote_protocols="CUPS dnssd"',
'--enable-libusb',
],
'pre_build': 'scripts/pre-build/libcups2.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'pango1.0',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# Avoid https://bugs.gentoo.org/show_bug.cgi?id=425620
'--enable-introspection=no',
# Pango is normally used with dynamically loaded modules. However,
# ensuring pango is able to find instrumented versions of those modules
# is a huge pain in the neck. Let's link them statically instead, and
# hope for the best.
'--with-included-modules=yes'
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libcap2',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'build_method': 'custom_libcap',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'udev',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# Without this flag there's a linking step that doesn't honor LDFLAGS
# and fails.
# TODO(eugenis): find a better fix.
'--disable-gudev'
],
'pre_build': 'scripts/pre-build/udev.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libtasn1-3',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--enable-ld-version-script',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libtasn1-6',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--enable-ld-version-script',
],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgnome-keyring0',
'extra_configure_flags': [
'--disable-static',
'--enable-tests=no',
# Make the build less problematic.
'--disable-introspection',
],
'package_ldflags': ['-Wl,--as-needed'],
'dependencies=': [],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgtk2.0-0',
'package_cflags': ['-Wno-return-type'],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--prefix=/usr',
'--sysconfdir=/etc',
'--enable-test-print-backend',
'--enable-introspection=no',
'--with-xinput=yes',
],
'dependencies=': [],
'conditions': [
['"<(_ubuntu_release)"=="precise"', {
'patch': 'patches/libgtk2.0-0.precise.diff',
}, {
'patch': 'patches/libgtk2.0-0.trusty.diff',
}],
],
'pre_build': 'scripts/pre-build/libgtk2.0-0.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgdk-pixbuf2.0-0',
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--with-libjasper',
'--with-x11',
# Make the build less problematic.
'--disable-introspection',
# Do not use loadable modules. Same as with Pango, there's no easy way
# to make gdk-pixbuf pick instrumented versions over system-installed
# ones.
'--disable-modules',
],
'dependencies=': [],
'pre_build': 'scripts/pre-build/libgdk-pixbuf2.0-0.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libpci3',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'build_method': 'custom_libpci3',
'jobs': 1,
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libdbusmenu-glib4',
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--disable-scrollkeeper',
'--enable-gtk-doc',
# --enable-introspection introduces a build step that attempts to run
# a just-built binary and crashes. Vala requires introspection.
# TODO(eugenis): find a better fix.
'--disable-introspection',
'--disable-vala',
],
'dependencies=': [],
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libgconf-2-4',
'extra_configure_flags': [
'--disable-static',
# From debian/rules. (Even though --with-gtk=3.0 doesn't make sense.)
'--with-gtk=3.0',
'--disable-orbit',
# See above.
'--disable-introspection',
],
'dependencies=': [],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libappindicator1',
'extra_configure_flags': [
'--disable-static',
# See above.
'--disable-introspection',
],
'dependencies=': [],
'jobs': 1,
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libdbusmenu',
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--disable-scrollkeeper',
'--with-gtk=2',
# See above.
'--disable-introspection',
'--disable-vala',
],
'dependencies=': [],
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'atk1.0',
'extra_configure_flags': [
'--disable-static',
# See above.
'--disable-introspection',
],
'dependencies=': [],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libunity9',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'dee',
'extra_configure_flags': [
'--disable-static',
# See above.
'--disable-introspection',
],
'dependencies=': [],
'pre_build': 'scripts/pre-build/autogen.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'harfbuzz',
'package_cflags': ['-Wno-c++11-narrowing'],
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--with-graphite2=yes',
'--with-gobject',
# See above.
'--disable-introspection',
],
'dependencies=': [],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'brltty',
'extra_configure_flags': [
'--disable-static',
# From debian/rules.
'--without-viavoice',
'--without-theta',
'--without-swift',
'--bindir=/sbin',
'--with-curses=ncursesw',
'--disable-stripping',
# We don't need any of those.
'--disable-java-bindings',
'--disable-lisp-bindings',
'--disable-ocaml-bindings',
'--disable-python-bindings',
'--disable-tcl-bindings'
],
'dependencies=': [],
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libva1',
'dependencies=': [],
'extra_configure_flags': ['--disable-static'],
# Backport a use-after-free fix:
# http://cgit.freedesktop.org/libva/diff/va/va.c?h=staging&id=d4988142a3f2256e38c5c5cdcdfc1b4f5f3c1ea9
'patch': 'patches/libva1.diff',
'pre_build': 'scripts/pre-build/libva1.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
'package_name': 'libsecret',
'dependencies=': [],
'extra_configure_flags': [
'--disable-static',
# See above.
'--disable-introspection',
],
'pre_build': 'scripts/pre-build/autoreconf.sh',
'includes': ['standard_instrumented_package_target.gypi'],
},
{
# Creates a stub to convince NSS to not load the system-wide uninstrumented library.
# It appears that just an empty file is enough.
'package_name': 'libcredentialkit_pkcs11-stub',
'target_name': '<(_sanitizer_type)-<(_package_name)',
'type': 'none',
'actions': [
{
'action_name': '<(_package_name)',
'inputs': [],
'outputs': [
'<(PRODUCT_DIR)/instrumented_libraries/<(_sanitizer_type)/<(_package_name).txt',
],
'action': [
'touch',
'<(PRODUCT_DIR)/instrumented_libraries/<(_sanitizer_type)/lib/libcredentialkit_pkcs11.so.0',
'<(PRODUCT_DIR)/instrumented_libraries/<(_sanitizer_type)/<(_package_name).txt',
],
},
],
},
],
}
|
'''
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
'''
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
for i in range(len(nums)):
if count < 2 or nums[count - 2] != nums[i]:
nums[count] = nums[i]
count += 1
return count
if __name__ == "__main__":
l = [1, 1, 1, 2, 2, 3]
r = Solution().removeDuplicates(l)
assert l == [1, 1, 2, 2, 3, 3]
assert r == 5
|
# Write a Python program to add an item in a tuple
tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
#2nd method
tuple = tuplex[:3] + (23,56,7)
print(tuple)
#3rd method
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
|
class ActionBatchAppliance(object):
def __init__(self):
super(ActionBatchAppliance, self).__init__()
def updateNetworkApplianceConnectivityMonitoringDestinations(self, networkId: str, **kwargs):
"""
**Update the connectivity testing destinations for an MX network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-connectivity-monitoring-destinations
- networkId (string): (required)
- destinations (array): The list of connectivity monitoring destinations
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'connectivityMonitoringDestinations'],
'operation': 'updateNetworkApplianceConnectivityMonitoringDestinations'
}
resource = f'/networks/{networkId}/appliance/connectivityMonitoringDestinations'
body_params = ['destinations', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceFirewallL7FirewallRules(self, networkId: str, **kwargs):
"""
**Update the MX L7 firewall rules for an MX network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-firewall-l-7-firewall-rules
- networkId (string): (required)
- rules (array): An ordered array of the MX L7 firewall rules
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'firewall', 'l7FirewallRules'],
'operation': 'updateNetworkApplianceFirewallL7FirewallRules'
}
resource = f'/networks/{networkId}/appliance/firewall/l7FirewallRules'
body_params = ['rules', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkAppliancePort(self, networkId: str, portId: str, **kwargs):
"""
**Update the per-port VLAN settings for a single MX port.**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-port
- networkId (string): (required)
- portId (string): (required)
- enabled (boolean): The status of the port
- dropUntaggedTraffic (boolean): Trunk port can Drop all Untagged traffic. When true, no VLAN is required. Access ports cannot have dropUntaggedTraffic set to true.
- type (string): The type of the port: 'access' or 'trunk'.
- vlan (integer): Native VLAN when the port is in Trunk mode. Access VLAN when the port is in Access mode.
- allowedVlans (string): Comma-delimited list of the VLAN ID's allowed on the port, or 'all' to permit all VLAN's on the port.
- accessPolicy (string): The name of the policy. Only applicable to Access ports. Valid values are: 'open', '8021x-radius', 'mac-radius', 'hybris-radius' for MX64 or Z3 or any MX supporting the per port authentication feature. Otherwise, 'open' is the only valid value and 'open' is the default value if the field is missing.
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'ports'],
'operation': 'updateNetworkAppliancePort'
}
resource = f'/networks/{networkId}/appliance/ports/{portId}'
body_params = ['enabled', 'dropUntaggedTraffic', 'type', 'vlan', 'allowedVlans', 'accessPolicy', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceSingleLan(self, networkId: str, **kwargs):
"""
**Update single LAN configuration**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-single-lan
- networkId (string): (required)
- subnet (string): The subnet of the single LAN configuration
- applianceIp (string): The appliance IP address of the single LAN
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'singleLan'],
'operation': 'updateNetworkApplianceSingleLan'
}
resource = f'/networks/{networkId}/appliance/singleLan'
body_params = ['subnet', 'applianceIp', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def createNetworkApplianceTrafficShapingCustomPerformanceClass(self, networkId: str, name: str, **kwargs):
"""
**Add a custom performance class for an MX network**
https://developer.cisco.com/meraki/api-v1/#!create-network-appliance-traffic-shaping-custom-performance-class
- networkId (string): (required)
- name (string): Name of the custom performance class
- maxLatency (integer): Maximum latency in milliseconds
- maxJitter (integer): Maximum jitter in milliseconds
- maxLossPercentage (integer): Maximum percentage of packet loss
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'customPerformanceClasses'],
'operation': 'createNetworkApplianceTrafficShapingCustomPerformanceClass'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/customPerformanceClasses'
body_params = ['name', 'maxLatency', 'maxJitter', 'maxLossPercentage', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "create",
"body": payload
}
return action
def updateNetworkApplianceTrafficShapingCustomPerformanceClass(self, networkId: str, customPerformanceClassId: str, **kwargs):
"""
**Update a custom performance class for an MX network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-traffic-shaping-custom-performance-class
- networkId (string): (required)
- customPerformanceClassId (string): (required)
- name (string): Name of the custom performance class
- maxLatency (integer): Maximum latency in milliseconds
- maxJitter (integer): Maximum jitter in milliseconds
- maxLossPercentage (integer): Maximum percentage of packet loss
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'customPerformanceClasses'],
'operation': 'updateNetworkApplianceTrafficShapingCustomPerformanceClass'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/customPerformanceClasses/{customPerformanceClassId}'
body_params = ['name', 'maxLatency', 'maxJitter', 'maxLossPercentage', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def deleteNetworkApplianceTrafficShapingCustomPerformanceClass(self, networkId: str, customPerformanceClassId: str):
"""
**Delete a custom performance class from an MX network**
https://developer.cisco.com/meraki/api-v1/#!delete-network-appliance-traffic-shaping-custom-performance-class
- networkId (string): (required)
- customPerformanceClassId (string): (required)
"""
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'customPerformanceClasses'],
'operation': 'deleteNetworkApplianceTrafficShapingCustomPerformanceClass'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/customPerformanceClasses/{customPerformanceClassId}'
action = {
"resource": resource,
"operation": "destroy",
"body": payload
}
return action
def updateNetworkApplianceTrafficShapingRules(self, networkId: str, **kwargs):
"""
**Update the traffic shaping settings rules for an MX network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-traffic-shaping-rules
- networkId (string): (required)
- defaultRulesEnabled (boolean): Whether default traffic shaping rules are enabled (true) or disabled (false). There are 4 default rules, which can be seen on your network's traffic shaping page. Note that default rules count against the rule limit of 8.
- rules (array): An array of traffic shaping rules. Rules are applied in the order that
they are specified in. An empty list (or null) means no rules. Note that
you are allowed a maximum of 8 rules.
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'rules'],
'operation': 'updateNetworkApplianceTrafficShapingRules'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/rules'
body_params = ['defaultRulesEnabled', 'rules', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceTrafficShapingUplinkBandwidth(self, networkId: str, **kwargs):
"""
**Updates the uplink bandwidth settings for your MX network.**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-traffic-shaping-uplink-bandwidth
- networkId (string): (required)
- bandwidthLimits (object): A mapping of uplinks to their bandwidth settings (be sure to check which uplinks are supported for your network)
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'uplinkBandwidth'],
'operation': 'updateNetworkApplianceTrafficShapingUplinkBandwidth'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/uplinkBandwidth'
body_params = ['bandwidthLimits', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceTrafficShapingUplinkSelection(self, networkId: str, **kwargs):
"""
**Update uplink selection settings for an MX network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-traffic-shaping-uplink-selection
- networkId (string): (required)
- activeActiveAutoVpnEnabled (boolean): Toggle for enabling or disabling active-active AutoVPN
- defaultUplink (string): The default uplink. Must be one of: 'wan1' or 'wan2'
- loadBalancingEnabled (boolean): Toggle for enabling or disabling load balancing
- wanTrafficUplinkPreferences (array): Array of uplink preference rules for WAN traffic
- vpnTrafficUplinkPreferences (array): Array of uplink preference rules for VPN traffic
"""
kwargs.update(locals())
if 'defaultUplink' in kwargs:
options = ['wan1', 'wan2']
assert kwargs['defaultUplink'] in options, f'''"defaultUplink" cannot be "{kwargs['defaultUplink']}", & must be set to one of: {options}'''
metadata = {
'tags': ['appliance', 'configure', 'trafficShaping', 'uplinkSelection'],
'operation': 'updateNetworkApplianceTrafficShapingUplinkSelection'
}
resource = f'/networks/{networkId}/appliance/trafficShaping/uplinkSelection'
body_params = ['activeActiveAutoVpnEnabled', 'defaultUplink', 'loadBalancingEnabled', 'wanTrafficUplinkPreferences', 'vpnTrafficUplinkPreferences', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def createNetworkApplianceVlan(self, networkId: str, id: str, name: str, **kwargs):
"""
**Add a VLAN**
https://developer.cisco.com/meraki/api-v1/#!create-network-appliance-vlan
- networkId (string): (required)
- id (string): The VLAN ID of the new VLAN (must be between 1 and 4094)
- name (string): The name of the new VLAN
- subnet (string): The subnet of the VLAN
- applianceIp (string): The local IP of the appliance on the VLAN
- groupPolicyId (string): The id of the desired group policy to apply to the VLAN
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'vlans'],
'operation': 'createNetworkApplianceVlan'
}
resource = f'/networks/{networkId}/appliance/vlans'
body_params = ['id', 'name', 'subnet', 'applianceIp', 'groupPolicyId', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "create",
"body": payload
}
return action
def updateNetworkApplianceVlansSettings(self, networkId: str, **kwargs):
"""
**Enable/Disable VLANs for the given network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-vlans-settings
- networkId (string): (required)
- vlansEnabled (boolean): Boolean indicating whether to enable (true) or disable (false) VLANs for the network
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'vlans', 'settings'],
'operation': 'updateNetworkApplianceVlansSettings'
}
resource = f'/networks/{networkId}/appliance/vlans/settings'
body_params = ['vlansEnabled', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceVlan(self, networkId: str, vlanId: str, **kwargs):
"""
**Update a VLAN**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-vlan
- networkId (string): (required)
- vlanId (string): (required)
- name (string): The name of the VLAN
- subnet (string): The subnet of the VLAN
- applianceIp (string): The local IP of the appliance on the VLAN
- groupPolicyId (string): The id of the desired group policy to apply to the VLAN
- vpnNatSubnet (string): The translated VPN subnet if VPN and VPN subnet translation are enabled on the VLAN
- dhcpHandling (string): The appliance's handling of DHCP requests on this VLAN. One of: 'Run a DHCP server', 'Relay DHCP to another server' or 'Do not respond to DHCP requests'
- dhcpRelayServerIps (array): The IPs of the DHCP servers that DHCP requests should be relayed to
- dhcpLeaseTime (string): The term of DHCP leases if the appliance is running a DHCP server on this VLAN. One of: '30 minutes', '1 hour', '4 hours', '12 hours', '1 day' or '1 week'
- dhcpBootOptionsEnabled (boolean): Use DHCP boot options specified in other properties
- dhcpBootNextServer (string): DHCP boot option to direct boot clients to the server to load the boot file from
- dhcpBootFilename (string): DHCP boot option for boot filename
- fixedIpAssignments (object): The DHCP fixed IP assignments on the VLAN. This should be an object that contains mappings from MAC addresses to objects that themselves each contain "ip" and "name" string fields. See the sample request/response for more details.
- reservedIpRanges (array): The DHCP reserved IP ranges on the VLAN
- dnsNameservers (string): The DNS nameservers used for DHCP responses, either "upstream_dns", "google_dns", "opendns", or a newline seperated string of IP addresses or domain names
- dhcpOptions (array): The list of DHCP options that will be included in DHCP responses. Each object in the list should have "code", "type", and "value" properties.
"""
kwargs.update(locals())
if 'dhcpHandling' in kwargs:
options = ['Run a DHCP server', 'Relay DHCP to another server', 'Do not respond to DHCP requests']
assert kwargs['dhcpHandling'] in options, f'''"dhcpHandling" cannot be "{kwargs['dhcpHandling']}", & must be set to one of: {options}'''
if 'dhcpLeaseTime' in kwargs:
options = ['30 minutes', '1 hour', '4 hours', '12 hours', '1 day', '1 week']
assert kwargs['dhcpLeaseTime'] in options, f'''"dhcpLeaseTime" cannot be "{kwargs['dhcpLeaseTime']}", & must be set to one of: {options}'''
metadata = {
'tags': ['appliance', 'configure', 'vlans'],
'operation': 'updateNetworkApplianceVlan'
}
resource = f'/networks/{networkId}/appliance/vlans/{vlanId}'
body_params = ['name', 'subnet', 'applianceIp', 'groupPolicyId', 'vpnNatSubnet', 'dhcpHandling', 'dhcpRelayServerIps', 'dhcpLeaseTime', 'dhcpBootOptionsEnabled', 'dhcpBootNextServer', 'dhcpBootFilename', 'fixedIpAssignments', 'reservedIpRanges', 'dnsNameservers', 'dhcpOptions', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def deleteNetworkApplianceVlan(self, networkId: str, vlanId: str):
"""
**Delete a VLAN from a network**
https://developer.cisco.com/meraki/api-v1/#!delete-network-appliance-vlan
- networkId (string): (required)
- vlanId (string): (required)
"""
metadata = {
'tags': ['appliance', 'configure', 'vlans'],
'operation': 'deleteNetworkApplianceVlan'
}
resource = f'/networks/{networkId}/appliance/vlans/{vlanId}'
action = {
"resource": resource,
"operation": "destroy",
"body": payload
}
return action
def updateNetworkApplianceVpnBgp(self, networkId: str, enabled: bool, **kwargs):
"""
**Update a Hub BGP Configuration**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-vpn-bgp
- networkId (string): (required)
- enabled (boolean): Boolean value to enable or disable the BGP configuration. When BGP is enabled, the asNumber (ASN) will be autopopulated with the preconfigured ASN at other Hubs or a default value if there is no ASN configured.
- asNumber (integer): An Autonomous System Number (ASN) is required if you are to run BGP and peer with another BGP Speaker outside of the Auto VPN domain. This ASN will be applied to the entire Auto VPN domain. The entire 4-byte ASN range is supported. So, the ASN must be an integer between 1 and 4294967295. When absent, this field is not updated. If no value exists then it defaults to 64512.
- ibgpHoldTimer (integer): The IBGP holdtimer in seconds. The IBGP holdtimer must be an integer between 12 and 240. When absent, this field is not updated. If no value exists then it defaults to 240.
- neighbors (array): List of BGP neighbors. This list replaces the existing set of neighbors. When absent, this field is not updated.
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'vpn', 'bgp'],
'operation': 'updateNetworkApplianceVpnBgp'
}
resource = f'/networks/{networkId}/appliance/vpn/bgp'
body_params = ['enabled', 'asNumber', 'ibgpHoldTimer', 'neighbors', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceVpnSiteToSiteVpn(self, networkId: str, mode: str, **kwargs):
"""
**Update the site-to-site VPN settings of a network**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-vpn-site-to-site-vpn
- networkId (string): (required)
- mode (string): The site-to-site VPN mode. Can be one of 'none', 'spoke' or 'hub'
- hubs (array): The list of VPN hubs, in order of preference. In spoke mode, at least 1 hub is required.
- subnets (array): The list of subnets and their VPN presence.
"""
kwargs.update(locals())
if 'mode' in kwargs:
options = ['none', 'spoke', 'hub']
assert kwargs['mode'] in options, f'''"mode" cannot be "{kwargs['mode']}", & must be set to one of: {options}'''
metadata = {
'tags': ['appliance', 'configure', 'vpn', 'siteToSiteVpn'],
'operation': 'updateNetworkApplianceVpnSiteToSiteVpn'
}
resource = f'/networks/{networkId}/appliance/vpn/siteToSiteVpn'
body_params = ['mode', 'hubs', 'subnets', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def updateNetworkApplianceWarmSpare(self, networkId: str, enabled: bool, **kwargs):
"""
**Update MX warm spare settings**
https://developer.cisco.com/meraki/api-v1/#!update-network-appliance-warm-spare
- networkId (string): (required)
- enabled (boolean): Enable warm spare
- spareSerial (string): Serial number of the warm spare appliance
- uplinkMode (string): Uplink mode, either virtual or public
- virtualIp1 (string): The WAN 1 shared IP
- virtualIp2 (string): The WAN 2 shared IP
"""
kwargs.update(locals())
metadata = {
'tags': ['appliance', 'configure', 'warmSpare'],
'operation': 'updateNetworkApplianceWarmSpare'
}
resource = f'/networks/{networkId}/appliance/warmSpare'
body_params = ['enabled', 'spareSerial', 'uplinkMode', 'virtualIp1', 'virtualIp2', ]
payload = {k.strip(): v for k, v in kwargs.items() if k.strip() in body_params}
action = {
"resource": resource,
"operation": "update",
"body": payload
}
return action
def swapNetworkApplianceWarmSpare(self, networkId: str):
"""
**Swap MX primary and warm spare appliances**
https://developer.cisco.com/meraki/api-v1/#!swap-network-appliance-warm-spare
- networkId (string): (required)
"""
metadata = {
'tags': ['appliance', 'configure', 'warmSpare'],
'operation': 'swapNetworkApplianceWarmSpare'
}
resource = f'/networks/{networkId}/appliance/warmSpare/swap'
action = {
"resource": resource,
"operation": "create",
"body": payload
}
return action
|
contador = 0
file = open("funciones_matematicas.py","w")
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input("Ingrese ecuacion: ")
def agregar_funcion():
f = open("funciones_matematicas.py","w")
ecuacion = input("Ingrese ecuacion: ")
f.write("funcs = \{}\n")
f.write("def f1(x):\n")
f.write("\treturn "+ecuacion)
f.close()
def test_func():
f = open("funciones_matematicas.py","w")
f.write("def f():\n")
f.write("\tprint(\"hola\")")
f.close()
|
class SlotPickleMixin(object):
"""
This mixin makes it possible to pickle/unpickle objects with __slots__ defined.
Origin: http://code.activestate.com/recipes/578433-mixin-for-pickling-objects-with-__slots__/
"""
def __getstate__(self):
return dict(
(slot, getattr(self, slot))
for slot in self.__slots__
if hasattr(self, slot)
)
def __setstate__(self, state):
for slot, value in state.items():
setattr(self, slot, value)
|
N = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)]))
|
p = int(input('Digite o primeiro termo de uma PA: '))
r = int(input('Digite uma razão de uma PA: '))
d = p + 9 * r
print('OS 10 PRIMEIROS TERMOS DESSA PA É:')
for c in range(p, d + r, r):
print(c, end=' ')
|
def solution(lottos, win_nums):
answer = []
zeros=0
for i in lottos:
if(i==0) : zeros+=1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6:1,5:2,4:3,3:4,2:5,1:6,0:6}
answer.append(_dict[len(correct)+zeros])
answer.append(_dict[len(correct)])
return answer
|
class Solution:
def solve(self, path):
ans = []
for part in path:
if part == "..":
if ans: ans.pop()
elif part != ".": ans.append(part)
return ans
|
# https://www.codewars.com/kata/523a86aa4230ebb5420001e1
def letterCounter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
wordMap = letterCounter(word)
for w in words:
if wordMap == letterCounter(w):
anag.append(w)
return anag
|
# %%
def Naive(N):
is_prime = True
if N <= 1 :
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return(is_prime)
def main():
N = 139
print(f"{N} prime ? : {Naive(N)}")
if __name__=="__main__":
main()
# %%
|
'''
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
'''
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length-1):
if sequence[i] == sequence[i+1]:
dp[i+1] = dp[i] + 1
else:
dp[i+1] = dp[i]
# print(dp)
ans = []
for fake_i in range(m):
l, r = [int(x) for x in input().split()]
ans.append(dp[r-1]-dp[l-1])
print('\n'.join(map(str,ans)))
|
def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
if digit in adjacent_digits.keys():
adjacent_digits[digit] += 1
else:
adjacent_digits[digit] = 2
else:
digit = password % 10
if 2 in adjacent_digits.values():
return True
else:
return False
def has_decreasing_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit < password % 10:
return True
else:
digit = password % 10
return False
def part_one(passwords):
count = 0
for password in passwords:
if has_adjacent_digits(password) and \
not has_decreasing_digits(password):
count += 1
print("Number of passwords meeting the criteria: {}".format(count))
def part_two(passwords):
count = 0
for password in passwords:
if has_two_adjacent_digits(password) and \
not has_decreasing_digits(password):
count += 1
print("Number of passwords meeting the criteria: {}".format(count))
if __name__ == "__main__":
passwords = range(152085, 670283)
part_one(passwords)
part_two(passwords)
|
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
|
print('Vamos calcular o aumento do seu salário')
salario = float(input('Digite o valor do seu salário R$'))
if salario > 1250:
aumento = salario * 0.10
print('Seu \033[4;31maumento\033[m será de \033[1;34mR${:.2f}\033[m, salário total R${:.2f}'.format(aumento, salario + aumento))
else:
aumento = salario * 0.15
print('Seu \033[4;33maumento\033[m será de \033[1;36mR${:.2f}\033[m, salário toral R${:.2f}'.format(aumento, salario + aumento))
|
#!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""
Author: Wang, Jun
Email: wangjun41@baidu.com
Date: 2018-11-16
"""
class BaseException(Exception):
"base exception"
def __init__(self, msg):
self.msg = msg
class UnsupportedError(BaseException):
"""Not support"""
def __init__(self, msg):
self.msg = msg
class RequestMethodNotImplemented(UnsupportedError):
"""Request method not implemented"""
def __init__(self, msg):
self.msg = msg
class ParameterNotFound(BaseException):
"""Parameter not Found"""
def __init__(self, msg):
self.msg = msg
class ExcelFormError(BaseException):
"""Excel form is invalid"""
def __init__(self, msg):
self.msg = msg
|
# Copyright 2010 Google Inc.
#
# 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 RIFF_WAVE_Checks(WAVE_block):
fmt_chunk = None;
fact_chunk = None;
data_chunk = None;
# format_description = 'WAVE - Unknown format';
if 'fmt ' not in WAVE_block._named_chunks:
WAVE_block.warnings.append('expected one "fmt " block, found none');
else:
fmt_chunk = WAVE_block._named_chunks['fmt '][0];
# format_description = 'WAVE - %s' % fmt_chunk._data.format_description;
if 'fact' not in WAVE_block._named_chunks:
if not fmt_chunk._data.is_PCM:
WAVE_block.warnings.append('expected one "fact" block, found none');
else:
fact_chunk = WAVE_block._named_chunks['fact'][0];
if 'data' not in WAVE_block._named_chunks:
WAVE_block.warnings.append('expected one "data" block, found none');
else:
data_chunk = WAVE_block._named_chunks['data'][0];
# d_chunks = set();
# d_blocks = set();
# for chunk_name in WAVE_block._named_chunks.keys():
# if chunk_name == 'LIST':
# for chunk in WAVE_block._named_chunks[chunk_name]:
# for block_name in chunk._named_blocks.keys():
# d_blocks.add(block_name.strip());
# elif chunk_name not in ['fmt ', 'data']:
# d_chunks.add(chunk_name.strip());
# if d_chunks:
# format_description += ' + chunks=' + ','.join(d_chunks);
# if d_blocks:
# format_description += ' + blocks=' + ','.join(d_blocks);
for name, chunks in WAVE_block._named_chunks.items():
if name == 'fmt ':
for chunk in chunks:
if len(chunks) > 1:
chunk._name.warnings.append( \
'expected only one "fmt " chunk, found %d' % len(chunks));
RIFF_WAVE_fmt_Checks(WAVE_block, chunk);
if name == 'fact':
for chunk in chunks:
if len(chunks) > 1:
chunk._name.warnings.append( \
'expected only one "fact" chunk, found %d' % len(chunks));
RIFF_WAVE_fact_Checks(WAVE_block, chunk);
if name == 'cue ':
for chunk in chunks:
if len(chunks) > 1:
chunk._name.warnings.append( \
'expected only one "cue " chunk, found %d' % len(chunks));
RIFF_WAVE_cue_Checks(WAVE_block, chunk);
if name == 'PEAK':
for chunk in chunks:
RIFF_WAVE_PEAK_Checks(WAVE_block, chunk);
if name == 'data':
for chunk in chunks:
if len(chunks) > 1:
chunk._name.warnings.append( \
'expected only one "data" chunk, found %d' % len(chunks));
RIFF_WAVE_data_Checks(WAVE_block, chunk);
# WAVE_block.notes.append(format_description);
def RIFF_WAVE_fmt_Checks(WAVE_block, fmt_chunk):
pass;
def RIFF_WAVE_fact_Checks(WAVE_block, fact_chunk):
pass;
def RIFF_WAVE_cue_Checks(WAVE_block, cue_chunk):
pass;
def RIFF_WAVE_PEAK_Checks(WAVE_block, PEAK_chunk):
# Check if peak positions are valid?
pass;
def RIFF_WAVE_data_Checks(WAVE_block, data_chunk):
pass;
|
# Problem 1- Summation of primes
# https://projecteuler.net/problem=10
# Answer =
def question():
print("""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.""")
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
def prime_lister(bound):
prime_list = []
for num in range(bound):
if is_prime(num):
prime_list.append(num)
return prime_list
def solve(bound):
prime_list = prime_lister(bound)
return sum(prime_list)
def main():
question()
print(f"The answer is {solve(2000000)}")
main()
|
#!/usr/bin/env python
# coding: utf-8
# # 7: Dictionaries Solutions
#
# 1. Below are two lists, `keys` and `values`. Combine these into a single dictionary.
#
# ```python
# keys = ['Ben', 'Ethan', 'Stefani']
# values = [1, 29, 28]
# ```
# Expected output:
# ```python
# {'Ben': 1, 'Ethan': 29, 'Stefani': 28}
# ```
# _Hint: look up the `zip()` function..._
# In[1]:
keys = ['Ben', 'Ethan', 'Stefani']
values = [1, 29, 28]
# Cheat way of doing it - if you thought of a clever way, good on you!
my_dict = dict(zip(keys, values))
print(my_dict)
# 2. Below are two dictionaries. Merge them into a single dictionary.
#
# ```python
# dict1 = {'Ben': 1, 'Ethan': 29}
# dict2 = {'Stefani': 28, 'Madonna': 16, "RuPaul": 17}
# ```
# Expected output:
# ```python
# {'Ben': 1, 'Ethan': 29, 'Stefani': 28, 'Madonna': 16, 'RuPaul': 17}
# ```
# In[6]:
dict1 = {'Ben': 1, 'Ethan': 29}
dict2 = {'Stefani': 28, 'Madonna': 16, "RuPaul": 17}
'''
In Python 3.9+, we can use `dict3 = dict1 | dict2`
In Python 3.5+ we can use `dict3 = {**dict1, **dict2}`
But I'll show you the long, non-cheat way anyway
'''
def merge_two_dicts(x, y) :
z = x.copy() # Start with all entries in x
z.update(y) # Then, add in the entries of y
return z # Return
dict3 = merge_two_dicts(dict1, dict2)
print(dict3)
# 3. From the dictionary given below, extract the keys `name` and `salary` and add them to a new dictionary.
#
# Dictionary:
# ```python
# sample_dict = {
# "name": "Ethan",
# "age": 21,
# "salary": 1000000,
# "city": "Glasgow"
# }
# ```
# Expected output:
# ```python
# {'name': 'Ethan', 'salary': 1000000}
# ```
# In[14]:
sampleDict = {
"name": "Ethan",
"age": 21,
"salary": 1000000,
"city": "Glasgow"
}
keys = ["name", "salary"]
newDict = {k: sampleDict[k] for k in keys}
print(newDict)
# In[ ]:
|
np = int(input('Say a number: '))
som = 0
for i in range(1,np):
if np%i == 0:
print (i),
som += i
if som == np:
print('It is a perfect number!')
else:
print ('It is not a perfect number')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.