content
stringlengths 7
1.05M
|
|---|
ies = []
ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."})
ies.append({ "ie_type" : "Cause", "ie_value" : "Cause", "presence" : "M", "instance" : "0", "comment" : "This IE shall indicate the acceptance or the rejection of the corresponding request message."})
ies.append({ "ie_type" : "UP Function Features", "ie_value" : "UP Function Features", "presence" : "O", "instance" : "0", "comment" : "If present, this IE shall indicate the supported Features when the sending node is the UP function."})
ies.append({ "ie_type" : "CP Function Features", "ie_value" : "CP Function Features", "presence" : "O", "instance" : "0", "comment" : "If present, this IE shall indicate the supported Features when the sending node is the CP function."})
msg_list[key]["ies"] = ies
|
''' This is a sample input, you can change it of course
but you have to follow rules of the questions '''
compressed_string = "2[1[b]10[c]]a"
def decompress(str=compressed_string):
string = ""
number_stack = []
replace_index_stack = []
bracket_index_stack = []
i = 0
while i < len(str):
if str[i] == "[":
# storing indexes in coressponding stacks
replace_index_stack.insert(0, i - len(string))
number_stack.insert(0, int(string))
bracket_index_stack.insert(0, i+1)
string = ""
elif str[i] == "]":
# updating base string with uncompressed part
temp = str[bracket_index_stack[0]:i] * number_stack[0]
str = str.replace(str[replace_index_stack[0]:i+1], temp)
# updating index to next position from decompressed part
i = replace_index_stack[0]+len(temp)
# poping the top item from stacks which is used already
number_stack.pop(0)
replace_index_stack.pop(0)
bracket_index_stack.pop(0)
string = ""
continue
else:
string += str[i]
i += 1
return str
print(decompress())
|
# Problem 6 MIT Midterm #
# The function isMyNumber is used to hide a secret number (integer).
# It takes an integer guess as a parameter and compares it to the secret number.
# It returns:
# -1 if the parameter x is less than the secret number
# 0 if the parameter x is correct
# 1 if the parameter x is greater than the secret number
def isMyNumber(guess):
"""
Procedure that hides a secret number.
:param guess: integer number
:return:
-1 if guess is less than the secret number
0 if guess is equal to the secret number
1 if guess is greater than the secret number
"""
secretnum = 5
if guess == secretnum:
return 0
elif guess < secretnum:
return -1
else:
return 1
# The following function, jumpAndBackPedal, attempts to guess a secret number.
# The only way it can interact with the secret number is through the isMyNumber function explained above
# Unfortunately, the implementation given does not correctly return the secret number.
# Please fix the errors in the code such that jumpAndBackpedal correctly returns the secret number.
def jumpAndBackpedal(isMyNumber):
"""
:param isMyNumber: function that hides a secret number
:return: secret number
"""
# start guess
guess = 0
# if isMyNumber returns 0, guess is secretnumber
if isMyNumber(guess) == 0:
return guess
# if isMyNumber does not return 0, guess is not yet correct
else:
# keep guessing until right guess
foundNumber = False
while not foundNumber:
# if guess is too high, isMyNumber returns 1
# so guess needs to be decreased
if isMyNumber(guess) == 1:
guess = guess - 1
# else if guess is too low, isMyNumber returns -1
# so guess needs to be increased
elif isMyNumber(guess) == -1:
guess = guess + 1
# else if finally guess is secret number, isMyNumber returns 0
else:
# break loop with flag
foundNumber = True
return guess
# print secret number, retuned
print (jumpAndBackpedal(isMyNumber))
|
def add(a,b):
return a+b
def sub(a,b):
return a-b
def multiply(a,b):
return a*b
def div(a,b):
return a/b
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
if self.head is None:
self.head = Node(data)
else:
temp = self.head
self.head = Node(data)
self.head.next = temp
def reverse(self, node):
if node.next is None:
self.head = node
return
self.reverse(node.next)
temp = node.next
temp.next = node
node.next = None
def printList(self):
if self.head is None:
print("LinkedList is empty")
else:
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
for i in range(0, 5):
llist.add(i)
llist.reverse(llist.head)
llist.printList()
|
#!/usr/bin/python
x = int(raw_input("Ingrese el input1: "))
print(not x)
|
'''
Visit the link : https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%202&url=worlds%2Ftutorial_en%2Fhurdle2.json
'''
def turn_right():
turn_left()
turn_left()
turn_left()
def complete():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
while not at_goal():
complete()
|
# Reads two grades and prints average
grade1 = float(input('Digite a primeira nota: '))
grade2 = float(input('Digite a segunda nota: '))
grade_average = (grade1 + grade2) / 2
print('Tirando {:.1f} e {:.1f}, a média é {:.1f}'.format(grade1, grade2, grade_average))
if grade_average < 5:
print('O aluno(a) está REPROVADO')
elif grade_average >= 7:
print('O aluno(a) está APROVADO')
else:
print('O aluno(a) está em RECUPERAÇÃO')
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# http://www.accesstoinsight.org/tipitaka/index.html
PaliTextTitle = {
'Tipiṭaka (Mūla)': 'Pāḷi Canon',
'Vinayapiṭaka': 'The Basket of the Discipline',
'Suttapiṭaka': 'The Basket of Discourses',
'Dīghanikāya': 'Long Discourses',
'Dīgha nikāya': 'Long Discourses',
'Sīlakkhandhavaggapāḷi':'The Division Concerning Morality',
'Brahmajālasuttaṃ': 'The All-embracing Net of Views',
'Sāmaññaphalasuttaṃ': 'The Fruits of the Contemplative Life',
# 'Ambaṭṭhasuttaṃ': '',
# 'Soṇadaṇḍasuttaṃ': '',
# 'Kūṭadantasuttaṃ': '',
# 'Mahālisuttaṃ': '',
# 'Jāliyasuttaṃ': '',
# 'Mahāsīhanādasuttaṃ': '',
'Poṭṭhapādasuttaṃ': 'About Poṭṭhapāda',
# 'Subhasuttaṃ': '',
'Kevaṭṭasuttaṃ': 'To Kevaṭṭa',
'Lohiccasuttaṃ': 'To Lohicca',
# 'Tevijjasuttaṃ': '',
'Mahāvaggapāḷi':'The Large Division',
# 'Mahāpadānasuttaṃ': '',
'Mahānidānasuttaṃ': 'The Great Causes Discourse',
'Mahāparinibbānasuttaṃ': 'Last Days of the Buddha/The Great Discourse on the Total Unbinding',
# 'Mahāsudassanasuttaṃ': '',
# 'Janavasabhasuttaṃ': '',
# 'Mahāgovindasuttaṃ': '',
'Mahāsamayasuttaṃ': 'The Great Assembly/The Great Meeting',
'Sakkapañhasuttaṃ': "Sakka's Questions",
'Mahāsatipaṭṭhānasuttaṃ': 'The Great Frames of Reference',
# 'Pāyāsisuttaṃ': '',
'Pāthikavaggapāḷi':'The Pāthika Division',
# 'Pāthikasuttaṃ': '',
# 'Udumbarikasuttaṃ': '',
'Cakkavattisuttaṃ': 'The Wheel-turning Emperor',
# 'Aggaññasuttaṃ': '',
# 'Sampasādanīyasuttaṃ': '',
# 'Pāsādikasuttaṃ': '',
# 'Lakkhaṇasuttaṃ': '',
'Siṅgālasuttaṃ': "The Buddha's Advice to Sigalaka/The Discourse to Sigala",
'Āṭānāṭiyasuttaṃ': 'Discourse on Āṭānāṭiya',
# 'Saṅgītisuttaṃ': '',
# 'Dasuttarasuttaṃ': '',
'Majjhimanikāya': 'Middle-length Discourses',
'Saṃyuttanikāya': 'Grouped" Discourses',
'Sagāthāvaggapāḷi': 'The Section of Verses',
# 'Devatāsaṃyuttaṃ': '',
# 'Devaputtasaṃyuttaṃ': '',
# 'Kosalasaṃyuttaṃ': '',
# 'Mārasaṃyuttaṃ': '',
# 'Bhikkhunīsaṃyuttaṃ': '',
# 'Brahmasaṃyuttaṃ': '',
# 'Brāhmaṇasaṃyuttaṃ': '',
# 'Vaṅgīsasaṃyuttaṃ': '',
# 'Vanasaṃyuttaṃ': '',
# 'Yakkhasaṃyuttaṃ': '',
# 'Sakkasaṃyuttaṃ': '',
'Nidānavaggapāḷi': 'The Section on Causation',
# 'Nidānasaṃyuttaṃ': '',
# 'Abhisamayasaṃyuttaṃ': '',
# 'Dhātusaṃyuttaṃ': '',
# 'Anamataggasaṃyuttaṃ': '',
# 'Kassapasaṃyuttaṃ': '',
# 'Lābhasakkārasaṃyuttaṃ': '',
# 'Rāhulasaṃyuttaṃ': '',
# 'Lakkhaṇasaṃyuttaṃ': '',
# 'Opammasaṃyuttaṃ': '',
# 'Bhikkhusaṃyuttaṃ': '',
'Khandhavaggapāḷi': 'The Section on the Aggregates',
# 'Khandhasaṃyuttaṃ': '',
# 'Rādhasaṃyuttaṃ': '',
# 'Diṭṭhisaṃyuttaṃ': '',
# 'Okkantasaṃyuttaṃ': '',
# 'Uppādasaṃyuttaṃ': '',
# 'Kilesasaṃyuttaṃ': '',
# 'Sāriputtasaṃyuttaṃ': '',
# 'Nāgasaṃyuttaṃ': '',
# 'Supaṇṇasaṃyuttaṃ': '',
# 'Gandhabbakāyasaṃyuttaṃ': '',
# 'Valāhakasaṃyuttaṃ': '',
# 'Vacchagottasaṃyuttaṃ': '',
# 'Jhānasaṃyuttaṃ': '',
'Saḷāyatanavaggapāḷi': 'The Section on the Six Sense Bases',
# 'Saḷāyatanasaṃyuttaṃ': '六處相應',
# 'Vedanāsaṃyuttaṃ': '受相應',
# 'Mātugāmasaṃyuttaṃ': '女人相應',
# 'Jambukhādakasaṃyuttaṃ': '閻浮車相應',
# 'Sāmaṇḍakasaṃyuttaṃ': '沙門出家相應',
# 'Moggallānasaṃyuttaṃ': '目犍連相應',
# 'Cittasaṃyuttaṃ': '質多相應',
# 'Gāmaṇisaṃyuttaṃ': '聚落主相應',
# 'Asaṅkhatasaṃyuttaṃ': '無為相應',
# 'Abyākatasaṃyuttaṃ': '無記相應',
'Mahāvaggapāḷi': 'The Great Section',
# 'Maggasaṃyuttaṃ': '道相應',
# 'Bojjhaṅgasaṃyuttaṃ': '覺支相應',
# 'Satipaṭṭhānasaṃyuttaṃ': '念處相應',
# 'Indriyasaṃyuttaṃ': '根相應',
# 'Sammappadhānasaṃyuttaṃ': '正勤相應',
# 'Balasaṃyuttaṃ': '力相應',
# 'Iddhipādasaṃyuttaṃ': '神足相應',
# 'Anuruddhasaṃyuttaṃ': '阿那律相應',
# 'Jhānasaṃyuttaṃ': '靜慮相應',
# 'Ānāpānasaṃyuttaṃ': '入出息相應',
# 'Sotāpattisaṃyuttaṃ': '入流 (須陀洹)相應',
# 'Saccasaṃyuttaṃ': '諦相應',
'Aṅguttaranikāya': 'Further-factored Discourses',
'Ekakanipātapāḷi': 'Book of the Ones',
# 'Rūpādivaggo': '色等品',
# 'Nīvaraṇappahānavaggo': '斷蓋品',
# 'Akammaniyavaggo': '無堪忍品',
# 'Adantavaggo': '無調品',
# 'Paṇihitaacchavaggo': '向與隱覆品',
# 'Accharāsaṅghātavaggo': '彈指品',
# 'Vīriyārambhādivaggo': '發精進等品',
# 'Kalyāṇamittādivaggo': '善友等品',
# 'Pamādādivaggo': '放逸等品',
# 'Dutiyapamādādivaggo': '',
# 'Adhammavaggo': '非法等品',
# 'Anāpattivaggo': '無范等品',
# 'Ekapuggalavaggo': '一人品',
# 'Etadaggavaggo': '是第一品',
# 'Aṭṭhānapāḷi': '無有是處品',
# 'Ekadhammapāḷi': '一法品',
# 'Pasādakaradhammavaggo': '種子品',
# 'Aparaaccharāsaṅghātavaggo': '末伽梨品',
# 'Kāyagatāsativaggo': '不放逸品',
# 'Amatavaggo': '靜慮品',
'Dukanipātapāḷi': 'Book of the Twos',
# 'Kammakaraṇavaggo': '科刑罰品',
# 'Adhikaraṇavaggo': '靜論品',
# 'Bālavaggo': '愚人品',
# 'Samacittavaggo': '等心品',
# 'Parisavaggo': '會眾品',
# 'Puggalavaggo': '人品',
# 'Sukhavaggo': '樂品',
# 'Sanimittavaggo': '有品',
# 'Dhammavaggo': '法品',
# 'Bālavaggo': '愚者品',
# 'Āsāduppajahavaggo': '希望品',
# 'Āyācanavaggo': '希求品',
# 'Dānavaggo': '施品',
# 'Santhāravaggo': '覆護品',
# 'Samāpattivaggo': '入定品',
# 'Kodhapeyyālaṃ': '忿品',
# 'Akusalapeyyālaṃ': '(律廣說)品',
# 'Vinayapeyyālaṃ': '',
# 'Rāgapeyyālaṃ': '',
'Tikanipātapāḷi': 'Book of the Threes',
# 'Bālavaggo': '愚人品',
# 'Rathakāravaggo': '車匠品',
# 'Puggalavaggo': '補特羅品',
# 'Devadūtavaggo': '天使品',
# 'Cūḷavaggo': '小品',
# 'Brāhmaṇavaggo': '婆羅門品',
# 'Mahāvaggo': '大品',
# 'Ānandavaggo': '阿難品',
# 'Samaṇavaggo': '沙門品',
# 'Loṇakapallavaggo': '掬鹽品',
# 'Sambodhavaggo': '等覺品',
# 'Āpāyikavaggo': '惡趣品',
# 'Kusināravaggo': '古西那拉品',
# 'Yodhājīvavaggo': '戰士品',
# 'Maṅgalavaggo': '吉祥品',
# 'Acelakavaggo': '裸形品',
# 'Kammapathapeyyālaṃ': '',
# 'Rāgapeyyālaṃ': '',
'Catukkanipātapāḷi': 'Book of the Fours',
'Pañcakanipātapāḷi': 'Book of the Fives',
'Chakkanipātapāḷi': 'Book of the Sixes',
'Sattakanipātapāḷi': 'Book of the Sevens',
'Aṭṭhakādinipātapāḷi': 'Book of the Eights',
'Navakanipātapāḷi': 'Book of the Nines',
'Dasakanipātapāḷi': 'Book of the Tens',
'Ekādasakanipātapāḷi': 'Book of the Elevens',
# 'Nissayavaggo': '依止品',
# 'Anussativaggo': '憶念品',
# 'Sāmaññavaggo': '沙門品',
# 'Rāgapeyyālaṃ': '貪品',
'Khuddakanikāya': 'Collection of Short Discourses',
# 'Khuddakanikāya': 'Division of Short Books',
'Khuddakapāṭhapāḷi': 'The Short Passages',
'Saraṇattayaṃ': 'Saranagamana — Going for Refuge',
'Dasasikkhāpadaṃ': 'The Ten Training Rules',
'Dvattiṃsākāro': 'The 32 Parts',
'Kumārapañhā': "Samanera Pañha — The Novice's Questions",
'Maṅgalasuttaṃ': 'Protection',
'Ratanasuttaṃ': 'Treasures',
'Tirokuṭṭasuttaṃ': 'Tirokudda Kanda — Hungry Shades Outside the Walls',
'Nidhikaṇḍasuttaṃ': 'The Reserve Fund',
'Mettasuttaṃ': 'Karaniya Metta Sutta — Good Will',
'Dhammapadapāḷi': 'The Path of Dhamma',
'Yamakavaggo': 'Pairs',
'Appamādavaggo': 'Heedfulness',
'Cittavaggo': 'The Mind',
'Pupphavaggo': 'Blossoms',
'Bālavaggo': 'Fools',
'Paṇḍitavaggo': 'The Wise',
'Arahantavaggo': 'Arahants',
'Sahassavaggo': 'Thousands',
'Pāpavaggo': 'Evil',
'Daṇḍavaggo': 'The Rod',
'Jarāvaggo': 'Aging',
'Attavaggo': 'Self',
'Lokavaggo': 'Worlds',
'Buddhavaggo': 'Awakened',
'Sukhavaggo': 'Happy',
'Piyavaggo': 'Dear Ones',
'Kodhavaggo': 'Anger',
'Malavaggo': 'Impurities',
'Dhammaṭṭhavaggo': 'The Judge',
'Maggavaggo': 'The Path',
'Pakiṇṇakavaggo': 'Miscellany',
'Nirayavaggo': 'Hell',
'Nāgavaggo': 'Elephants',
'Taṇhāvaggo': 'Craving',
'Bhikkhuvaggo': 'Monks',
'Brāhmaṇavaggo': 'Brahmans',
'Udānapāḷi': 'Exclamations',
'Itivuttakapāḷi': 'The Thus-saids',
'Suttanipātapāḷi': 'The Discourses Collection',
'Uragavaggo': 'The Snake Chapter',
'Cūḷavaggo': 'The Lesser Chapter',
'Mahāvaggo': 'The Great Chapter',
'Aṭṭhakavaggo': 'The Octet Chapter',
'Pārāyanavaggo': 'The Chapter on the Way to the Far Shore',
'Vimānavatthupāḷi': 'Stories of the Celestial Mansions',
'Petavatthupāḷi': 'Stories of the Hungry Ghosts',
'Theragāthāpāḷi': 'Verses of the Elder Monks',
'Therīgāthāpāḷi': 'Verses of the Elder Nuns',
'Apadānapāḷi': 'Stories',
'Buddhavaṃsapāḷi': 'History of the Buddhas',
'Cariyāpiṭakapāḷi': 'Basket of Conduct',
'Jātakapāḷi': 'Birth Stories',
# 'Mahāniddesapāḷi': '大義釋',
# 'Cūḷaniddesapāḷi': '小義釋',
'Paṭisambhidāmaggapāḷi': 'Path of Discrimination',
# 'Nettippakaraṇapāḷi': '導論',
'Milindapañhapāḷi': 'Questions of Milinda',
# 'Peṭakopadesapāḷi': '藏釋 (三藏知津)',
#'Abhidhammapiṭaka': '',
'Dhammasaṅgaṇīpāḷi': 'Enumeration of Phenomena',
'Vibhaṅgapāḷi': 'The Book of Analysis',
# 'Vibhaṅgapāḷi': 'The Book of Treatises',
'Dhātukathāpāḷi': 'Discourse on Elements',
# 'Dhātukathāpāḷi': 'Discussion with Reference to the Elements',
'Puggalapaññattipāḷi': 'A Designation of Human Types',
# 'Puggalapaññattipāḷi': 'Description of Individuals',
'Kathāvatthupāḷi': 'Points of Controversy',
'Yamakapāḷi': 'The Book of Pairs',
'Paṭṭhānapāḷi': 'The Book of Relations',
'Aṭṭhakathā': 'Commentaries',
'Tīkā': 'Sub-commentaries',
'Abhidhammatthasaṅgaho': 'A Comprehensive Manual of Abhidhamma',
'Visuddhimagga': 'The Path of Purification',
'Sīlaniddeso': 'DESCRIPTION OF VIRTUE',
'Dhutaṅganiddeso': 'THE ASCETIC PRACTICES',
'Kammaṭṭhānaggahaṇaniddeso': 'TAKING A MEDITATION SUBJECT',
'Pathavīkasiṇaniddeso': 'THE EARTH KASIṆA',
'Sesakasiṇaniddeso': 'THE REMAINING KASIṆAS',
'Asubhakammaṭṭhānaniddeso': 'FOULNESS AS A MEDITATION SUBJECT',
'Chaanussatiniddeso': 'SIX RECOLLECTIONS',
'Anussatikammaṭṭhānaniddeso': 'OTHER RECOLLECTIONS AS MEDITATION SUBJECTS',
'Brahmavihāraniddeso': 'THE DIVINE ABIDINGS',
'Āruppaniddeso': 'THE IMMATERIAL STATES',
'Samādhiniddeso': 'CONCENTRATION—CONCLUSION: NUTRIMENT AND THE ELEMENTS',
'Iddhividhaniddeso': 'THE SUPERNORMAL POWERS',
'Abhiññāniddeso': 'OTHER DIRECT-KNOWLEDGES',
'Khandhaniddeso': 'THE AGGREGATES',
'Āyatanadhātuniddeso': 'THE BASES AND ELEMENTS',
'Indriyasaccaniddeso': 'THE FACULTIES AND TRUTHS',
'Paññābhūminiddeso': 'THE SOIL OF UNDERSTANDING—CONCLUSION: DEPENDENT ORIGINATION',
'Diṭṭhivisuddhiniddeso': 'PURIFICATION OF VIEW',
'Kaṅkhāvitaraṇavisuddhiniddeso': 'PURIFICATION BY OVERCOMING DOUBT',
'Maggāmaggañāṇadassanavisuddhiniddeso': 'PURIFICATION BY KNOWLEDGE AND VISION OF WHAT IS THE PATH AND WHAT IS NOT THE PATH',
'Paṭipadāñāṇadassanavisuddhiniddeso': 'PURIFICATION BY KNOWLEDGE AND VISION OF THE WAY',
'Ñāṇadassanavisuddhiniddeso': 'PURIFICATION BY KNOWLEDGE AND VISION',
'Paññābhāvanānisaṃsaniddeso': 'THE BENEFITS IN DEVELOPING UNDERSTANDING',
' ': ' '
}
|
# Copyright 2017 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.
DEPS = [
'bisect_tester_staging',
'chromium',
'chromium_tests',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/step',
]
def RunSteps(api):
api.path.c.dynamic_paths['bisect_results'] = api.path['start_dir'].join(
'bisect_results')
api.chromium.set_config('chromium')
test = api.chromium_tests.steps.BisectTestStaging()
test.pre_run(api, '')
try:
test.run(api, '')
finally:
api.step('details', [])
api.step.active_result.presentation.logs['details'] = [
'compile_targets: %r' % test.compile_targets(api),
'uses_local_devices: %r' % test.uses_local_devices,
]
def GenTests(api):
bisect_config = {
'test_type': 'perf',
'command': './tools/perf/run_benchmark -v '
'--browser=android-chromium --output-format=valueset '
'page_cycler_v2.intl_ar_fa_he',
'metric': 'warm_times/page_load_time',
'repeat_count': '2',
'max_time_minutes': '5',
'truncate_percent': '25',
'bug_id': '425582',
'gs_bucket': 'chrome-perf',
'builder_host': 'master4.golo.chromium.org',
'builder_port': '8341'
}
yield (
api.test('basic') +
api.properties(
bisect_config=bisect_config,
buildername='test_buildername',
bot_id='test_bot_id')
)
|
"""
Problem Statement: Print Indentation Correctly
Given a string "(hello word (bye bye))"
Need to print:
(
hello
word
(
bye
bye
)
)
Language: Python
Written by: Mostofa Adib Shakib
References:
=> https://leetcode.com/discuss/interview-question/409902/Snap-or-phone-or-print-indentation-correctly
"""
def printIndentationCorrectly(s):
n = len(s)
i=0
count = 0
while i < n:
char = s[i]
if char == ' ':
i+=1
elif char == '(':
print(count * ' ' + char)
count += 1
i+=1
elif char == ')':
count -=1
print(count * ' ' + char)
i+=1
else:
j = i
while j < n and s[j] != ' ' and s[j] != ')':
j+=1
print(count * ' ' + s[i:j])
i = j
# Driver Code
testStringOne = "(hello word (bye bye))"
testStringTwo = '( (hi))'
printIndentationCorrectly(testStringOne)
printIndentationCorrectly(testStringTwo)
|
# Taum and B'day
# Calculate the minimum cost required to buy some amounts of two types of gifts when costs of each type and the rate of conversion from one form to another is provided.
#
# https://www.hackerrank.com/challenges/taum-and-bday/problem
#
def taumBday(b, w, x, y, z):
# Complete this function
# x : cost of b
# y : cost of w
# z : cost of b <-> w
return min(x * b + y * w, # coût avec aucune transformation
(y + z) * b + y * w, # coût en transformant b en w
x * b + (x + z) * w) # coût en transformant w en b
if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
b, w = input().strip().split(' ')
b, w = [int(b), int(w)]
x, y, z = input().strip().split(' ')
x, y, z = [int(x), int(y), int(z)]
result = taumBday(b, w, x, y, z)
print(result)
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
# $builtin-init-module$
# These values are injected by our boot process. flake8 has no knowledge about
# their definitions and will complain without these circular assignments.
_Unbound = _Unbound # noqa: F821
def _ContextVar_guard(obj):
_builtin()
def _Token_guard(obj):
_builtin()
def _builtin():
"""This function acts as a marker to `freeze_modules.py` it should never
actually be called."""
_unimplemented()
def _address(c):
_builtin()
def _anyset_check(obj):
_builtin()
def _async_generator_finalizer(obj):
_builtin()
def _async_generator_guard(obj):
_builtin()
def _async_generator_op_iter_get_state(obj):
_builtin()
def _base_exception_cause(self):
_builtin()
def _base_exception_context(self):
_builtin()
def _base_exception_set_cause(self, value):
_builtin()
def _base_exception_set_context(self, value):
_builtin()
def _base_exception_set_traceback(self, value):
_builtin()
def _base_exception_traceback(self):
_builtin()
def _bool_check(self):
"$intrinsic$"
_builtin()
def _bool_guard(self):
"$intrinsic$"
_builtin()
def _bound_method(fn, owner):
_builtin()
def _bound_method_guard(obj):
_builtin()
def _builtin_type(name):
"""Returns the builtin type with name `name`. This even works before the
type is initialized via a `class` statement and is intended to be used when
a builtin type definition requires to reference itself."""
_builtin()
def _byte_guard(obj):
_builtin()
def _bytearray_append(obj, item):
_builtin()
def _bytearray_check(obj):
"$intrinsic$"
_builtin()
def _bytearray_clear(obj):
_builtin()
def _bytearray_contains(obj, key):
_builtin()
def _bytearray_contains_byteslike(obj, key):
_builtin()
def _bytearray_copy(obj):
_builtin()
def _bytearray_delitem(self, key):
_builtin()
def _bytearray_delslice(self, start, stop, step):
_builtin()
def _bytearray_getitem(self, key):
_builtin()
def _bytearray_getslice(self, start, stop, step):
_builtin()
def _bytearray_guard(obj):
"$intrinsic$"
_builtin()
def _bytearray_join(self, iterable):
_builtin()
def _bytearray_len(self):
"$intrinsic$"
_builtin()
def _bytearray_ljust(self, width, fillbyte):
_builtin()
def _bytearray_rjust(self, width, fillbyte):
_builtin()
def _bytearray_setitem(self, key, value):
_builtin()
def _bytearray_setslice(self, start, stop, step, value):
_builtin()
def _bytes_check(obj):
"$intrinsic$"
_builtin()
def _bytes_contains(obj, key):
_builtin()
def _bytes_decode(obj, encoding):
_builtin()
def _bytes_decode_ascii(obj):
_builtin()
def _bytes_decode_utf_8(obj):
_builtin()
def _bytes_from_bytes(cls, value):
_builtin()
def _bytes_from_ints(source):
_builtin()
def _bytes_getitem(self, index):
_builtin()
def _bytes_getslice(self, start, stop, step):
_builtin()
def _bytes_guard(obj):
"$intrinsic$"
_builtin()
def _bytes_join(self, iterable):
_builtin()
def _bytes_len(self):
"$intrinsic$"
_builtin()
def _bytes_ljust(self, width, fillbyte):
_builtin()
def _bytes_maketrans(frm, to):
_builtin()
def _bytes_repeat(self, count):
_builtin()
def _bytes_replace(self, old, new, count):
_builtin()
def _bytes_split(self, sep, maxsplit):
_builtin()
def _bytes_split_whitespace(self, maxsplit):
_builtin()
def _byteslike_check(obj):
"$intrinsic$"
_builtin()
def _byteslike_compare_digest(a, b):
_builtin()
def _byteslike_count(self, sub, start, end):
_builtin()
def _byteslike_endswith(self, suffix, start, end):
_builtin()
def _byteslike_find_byteslike(self, sub, start, end):
_builtin()
def _byteslike_find_int(self, sub, start, end):
_builtin()
def _byteslike_guard(obj):
"$intrinsic$"
_builtin()
def _byteslike_rfind_byteslike(self, sub, start, end):
_builtin()
def _byteslike_rfind_int(self, sub, start, end):
_builtin()
def _byteslike_startswith(self, prefix, start, end):
_builtin()
def _caller_function():
_builtin()
def _caller_locals():
_builtin()
def _classmethod(function):
_builtin()
def _classmethod_isabstract(self):
_builtin()
def _code_check(obj):
_builtin()
def _code_guard(c):
_builtin()
def _code_new(
cls,
argcount,
posonlyargcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
code,
consts,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars,
cellvars,
):
_builtin()
def _code_set_filename(code, filename):
_builtin()
def _complex_check(obj):
"$intrinsic$"
_builtin()
def _complex_checkexact(obj):
_builtin()
def _complex_imag(c):
_builtin()
def _complex_new(cls, imag, real):
_builtin()
def _complex_real(c):
_builtin()
def _compute_mro(type):
_builtin()
def _deque_guard(obj):
"$intrinsic$"
_builtin()
def _dict_check(obj):
"$intrinsic$"
_builtin()
def _dict_check_exact(obj):
"$intrinsic$"
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_get(self, key, default=None):
_builtin()
def _dict_guard(obj):
"$intrinsic$"
_builtin()
def _dict_items_guard(self):
_builtin()
def _dict_keys_guard(self):
_builtin()
def _dict_len(self):
"$intrinsic$"
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_setitem(self, key, value):
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_update(self, other, kwargs):
_builtin()
def _divmod(number, divisor):
_builtin()
def _exec(code, module, implicit_globals):
_builtin()
def _float_check(obj):
"$intrinsic$"
_builtin()
def _float_check_exact(obj):
"$intrinsic$"
_builtin()
def _float_divmod(number, divisor):
_builtin()
def _float_format(
value, format_code, precision, skip_sign, add_dot_0, use_alt_formatting
):
_builtin()
def _float_guard(obj):
"$intrinsic$"
_builtin()
def _float_new_from_byteslike(cls, obj):
_builtin()
def _float_new_from_float(cls, obj):
_builtin()
def _float_new_from_str(cls, obj):
_builtin()
def _float_signbit(value):
_builtin()
def _frozenset_check(obj):
"$intrinsic$"
_builtin()
def _frozenset_guard(obj):
"$intrinsic$"
_builtin()
def _function_annotations(obj):
_builtin()
def _function_closure(obj):
_builtin()
def _function_defaults(obj):
_builtin()
def _function_globals(obj):
_builtin()
def _function_guard(obj):
"$intrinsic$"
_builtin()
def _function_kwdefaults(obj):
_builtin()
def _function_lineno(function, pc):
_builtin()
def _function_new(self, code, mod, name, defaults, closure):
_builtin()
def _function_set_annotations(obj, annotations):
_builtin()
def _function_set_defaults(obj, defaults):
_builtin()
def _function_set_kwdefaults(obj, kwdefaults):
_builtin()
def _gc():
_builtin()
def _get_asyncgen_hooks():
_builtin()
def _get_member_byte(addr):
_builtin()
def _get_member_char(addr):
_builtin()
def _get_member_double(addr):
_builtin()
def _get_member_float(addr):
_builtin()
def _get_member_int(addr):
_builtin()
def _get_member_long(addr):
_builtin()
def _get_member_pyobject(addr, name):
_builtin()
def _get_member_short(addr):
_builtin()
def _get_member_string(addr):
_builtin()
def _get_member_ubyte(addr):
_builtin()
def _get_member_uint(addr):
_builtin()
def _get_member_ulong(addr):
_builtin()
def _get_member_ushort(addr):
_builtin()
def _heap_dump(filename):
_builtin()
def _instance_dunder_dict_set(obj, dict):
_builtin()
def _instance_delattr(obj, name):
_builtin()
def _instance_getattr(obj, name):
_builtin()
def _instance_guard(obj):
_builtin()
def _instance_overflow_dict(obj):
_builtin()
def _instance_setattr(obj, name, value):
_builtin()
def _instancemethod_func(obj):
_builtin()
def _int_check(obj):
"$intrinsic$"
_builtin()
def _int_check_exact(obj):
"$intrinsic$"
_builtin()
def _int_ctor(cls, x=_Unbound, base=_Unbound):
_builtin()
def _int_ctor_obj(cls, x):
_builtin()
def _int_from_bytes(cls, bytes, byteorder_big, signed):
_builtin()
def _int_guard(obj):
"$intrinsic$"
_builtin()
def _int_new_from_byteslike(cls, x, base):
_builtin()
def _int_new_from_int(cls, value):
_builtin()
def _int_new_from_str(cls, x, base):
_builtin()
def _jit(func):
"""Compile the function's body to native code. Return the function. Useful
as a decorator:
@_jit
def foo:
pass
"""
_builtin()
def _jit_fromlist(funcs):
"""Compile a list of function objects to native code."""
for func in funcs:
_jit(func)
def _jit_fromtype(type):
_type_guard(type)
for item in type.__dict__.values():
_jit(item)
def _jit_iscompiled(func):
"""Return True if the given function is compiled and False otherwise."""
_builtin()
def _list_append(self, item):
"$intrinsic$"
_builtin()
def _list_check(obj):
"$intrinsic$"
_builtin()
def _list_check_exact(obj):
"$intrinsic$"
_builtin()
def _list_ctor(cls, iterable=()):
_builtin()
def _list_delitem(self, key):
_builtin()
def _list_delslice(self, start, stop, step):
_builtin()
def _list_extend(self, other):
_builtin()
def _list_getitem(self, key):
"$intrinsic$"
_builtin()
def _list_getslice(self, start, stop, step):
_builtin()
def _list_guard(obj):
"$intrinsic$"
_builtin()
def _list_len(self):
"$intrinsic$"
_builtin()
def _list_new(size, fill=None):
_builtin()
def _list_setitem(self, key, value):
"$intrinsic$"
_builtin()
def _list_setslice(self, start, stop, step, value):
_builtin()
def _list_sort(list):
_builtin()
def _list_sort_by_key(list):
_builtin()
def _list_swap(list, i, j):
_builtin()
def _lt(a, b):
"Same as a < b."
return a < b
def _lt_key(obj, other):
return _tuple_getitem(obj, 0) < _tuple_getitem(other, 0)
def _mappingproxy_guard(obj):
_builtin()
def _mappingproxy_mapping(obj):
_builtin()
def _mappingproxy_set_mapping(obj, mapping):
_builtin()
def _memoryview_check(obj):
_builtin()
def _memoryview_getitem(obj, key):
_builtin()
def _memoryview_getslice(self, start, stop, step):
_builtin()
def _memoryview_guard(obj):
"$intrinsic$"
_builtin()
def _memoryview_itemsize(obj):
_builtin()
def _memoryview_nbytes(self):
_builtin()
def _memoryview_setitem(self, key, value):
_builtin()
def _memoryview_setslice(self, start, stop, step, value):
_builtin()
def _memoryview_start(self):
_builtin()
def _mmap_check(obj):
_builtin()
def _module_dir(module):
_builtin()
def _module_proxy(module):
_builtin()
def _module_proxy_check(obj):
_builtin()
def _module_proxy_guard(module):
_builtin()
def _module_proxy_keys(self):
_builtin()
def _module_proxy_setitem(self, key, value):
_builtin()
def _module_proxy_values(self):
_builtin()
def _iter(self):
_builtin()
def _object_class_set(obj, name):
_builtin()
def _object_keys(self):
_builtin()
def _object_type_getattr(obj, name):
"""Looks up the named attribute on the object's type, resolving descriptors.
Behaves like _PyObject_LookupSpecial."""
_builtin()
def _object_type_hasattr(obj, name):
_builtin()
def _os_write(fd, buf):
_builtin()
def _os_error_subclass_from_errno(errno):
_builtin()
def _profiler_install(new_thread_func, call_func, return_func):
_builtin()
def _profiler_exclude(callable):
"""Call `callable` and disable opcode counting in the current thread for the
duration of the call."""
_builtin()
def _property(fget=None, fset=None, fdel=None, doc=None):
"""Has the same effect as property(), but can be used for bootstrapping."""
_builtin()
def _property_isabstract(self):
_builtin()
def _pyobject_offset(instance, offset):
_builtin()
def _range_check(obj):
"$intrinsic$"
_builtin()
def _range_guard(obj):
"$intrinsic$"
_builtin()
def _range_len(self):
_builtin()
def _readline(prompt):
_builtin()
def _repr_enter(obj):
_builtin()
def _repr_leave(obj):
_builtin()
def _seq_index(obj):
"$intrinsic$"
_builtin()
def _seq_iterable(obj):
"$intrinsic$"
_builtin()
def _seq_set_index(obj, index):
"$intrinsic$"
_builtin()
def _seq_set_iterable(obj, iterable):
"$intrinsic$"
_builtin()
def _set_check(obj):
"$intrinsic$"
_builtin()
def _set_function_flag_iterable_coroutine(code):
_builtin()
def _set_guard(obj):
"$intrinsic$"
_builtin()
def _set_len(self):
"$intrinsic$"
_builtin()
def _set_member_double(addr, value):
_builtin()
def _set_member_float(addr, value):
_builtin()
def _set_member_integral(addr, value, num_bytes):
_builtin()
def _set_member_integral_unsigned(addr, value, num_bytes):
_builtin()
def _set_member_pyobject(addr, value):
_builtin()
def _slice_check(obj):
"$intrinsic$"
_builtin()
def _slice_guard(obj):
"$intrinsic$"
_builtin()
def _slice_start(start, step, length):
_builtin()
def _staticmethod(func):
_builtin()
def _slice_start_long(start, step, length):
_builtin()
def _slice_step(step):
_builtin()
def _slice_step_long(step):
_builtin()
def _slice_stop(stop, step, length):
_builtin()
def _slice_stop_long(stop, step, length):
_builtin()
def _staticmethod_isabstract(self):
_builtin()
def _stop_iteration_ctor(cls, *args):
_builtin()
def _str_array_clear(self):
_builtin()
def _str_array_ctor(cls, source=_Unbound):
_builtin()
def _str_array_iadd(self, other):
_builtin()
def _str_center(self, width, fillchar):
_builtin()
def _str_check(obj):
"$intrinsic$"
_builtin()
def _str_check_exact(obj):
"$intrinsic$"
_builtin()
def _str_compare_digest(a, b):
_builtin()
def _str_count(self, sub, start, end):
_builtin()
def _str_ctor(cls, obj=_Unbound, encoding=_Unbound, errors=_Unbound):
"$intrinsic$"
_builtin()
def _str_ctor_obj(cls, obj):
_builtin()
def _str_encode(self, encoding):
_builtin()
def _str_encode_ascii(self):
_builtin()
def _str_endswith(self, suffix, start, end):
_builtin()
def _str_getitem(self, key):
_builtin()
def _str_getslice(self, start, stop, step):
_builtin()
def _str_guard(obj):
"$intrinsic$"
_builtin()
def _str_ischr(obj):
_builtin()
def _str_join(sep, iterable):
_builtin()
def _str_ljust(self, width, fillchar):
_builtin()
def _str_escape_non_ascii(s):
_builtin()
def _str_find(self, sub, start, end):
_builtin()
def _str_from_str(cls, value):
_builtin()
def _str_len(self):
"$intrinsic$"
_builtin()
def _str_mod_fast_path(self, other):
_builtin()
def _str_partition(self, sep):
_builtin()
def _str_replace(self, old, newstr, count):
_builtin()
def _str_rfind(self, sub, start, end):
_builtin()
def _str_rjust(self, width, fillchar):
_builtin()
def _str_rpartition(self, sep):
_builtin()
def _str_split(self, sep, maxsplit):
_builtin()
def _str_splitlines(self, keepends):
_builtin()
def _str_startswith(self, prefix, start, end):
_builtin()
def _str_translate(obj, table):
_builtin()
def _structseq_getitem(structseq, index):
_builtin()
def _structseq_new_type(name, field_names, is_heaptype=True, num_in_sequence=_Unbound):
_builtin()
def _structseq_setitem(structseq, index, value):
_builtin()
def _super(cls):
_builtin()
def _super_ctor(cls, type=_Unbound, type_or_obj=_Unbound):
_builtin()
def _traceback_frame_get(self):
_builtin()
def _traceback_lineno_get(self):
_builtin()
def _traceback_next_get(self):
_builtin()
def _traceback_next_set(self, new_next):
_builtin()
def _tuple_check(obj):
"$intrinsic$"
_builtin()
def _tuple_check_exact(obj):
"$intrinsic$"
_builtin()
def _tuple_getitem(self, index):
"$intrinsic$"
_builtin()
def _tuple_getslice(self, start, stop, step):
_builtin()
def _tuple_guard(obj):
"$intrinsic$"
_builtin()
def _tuple_len(self):
"$intrinsic$"
_builtin()
def _tuple_new(cls, old_tuple):
_builtin()
def _type(obj):
"$intrinsic$"
_builtin()
def _type_ctor(cls, obj):
_builtin()
def _type_abstractmethods_del(self):
_builtin()
def _type_abstractmethods_get(self):
_builtin()
def _type_abstractmethods_set(self, value):
_builtin()
def _type_bases_del(self):
_builtin()
def _type_bases_get(self):
_builtin()
def _type_bases_set(self, value):
_builtin()
def _type_check(obj):
"$intrinsic$"
_builtin()
def _type_check_exact(obj):
"$intrinsic$"
_builtin()
def _type_dunder_call(self, *args, **kwargs):
_builtin()
def _type_guard(obj):
"$intrinsic$"
_builtin()
def _type_issubclass(subclass, superclass):
"$intrinsic$"
_builtin()
def _type_module_get(self):
_builtin()
def _type_module_set(self, value):
_builtin()
def _type_name_get(self):
_builtin()
def _type_name_set(self, value):
_builtin()
def _type_proxy(type_obj):
_builtin()
def _type_new(cls, name, bases, dict, is_heaptype):
_builtin()
def _type_proxy_check(obj):
_builtin()
def _type_proxy_get(self, key, default):
_builtin()
def _type_proxy_guard(obj):
_builtin()
def _type_proxy_keys(self):
_builtin()
def _type_proxy_len(self):
_builtin()
def _type_proxy_values(self):
_builtin()
def _type_qualname_get(self):
_builtin()
def _type_qualname_set(self, value):
_builtin()
def _type_subclass_guard(subclass, superclass):
"$intrinsic$"
_builtin()
def _unimplemented():
"""Prints a message and a stacktrace, and stops the program execution."""
_builtin()
def _warn(message, category=None, stacklevel=1, source=None):
"""Calls warnings.warn."""
_builtin()
def _weakref_callback(self):
_builtin()
def _weakref_check(self):
"$intrinsic$"
_builtin()
def _weakref_guard(self):
"$intrinsic$"
_builtin()
def _weakref_referent(self):
_builtin()
maxunicode = maxunicode # noqa: F821
|
def longestCommonSubsequence(str1, str2):
if not str1 or not str2:
return []
dp = [[0 for _ in range(len(str2))] for __ in range(len(str1))]
commons = []
inc = 0
for i in range(len(str1)):
if str1[i] == str2[0]:
inc = 1
dp[i][0] = inc
inc = 0
for j in range(len(str2)):
if str2[j] == str1[0]:
inc = 1
dp[0][j] = inc
for i in range(1, len(str1)):
for j in range(1, len(str2)):
if str1[i] == str2[j]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
row = len(str1) - 1
col = len(str2) - 1
while row >= 0 and col >= 0:
if col - 1 >= 0 and dp[row][col] == dp[row][col - 1]:
col -= 1
elif row - 1 >= 0 and dp[row][col] == dp[row - 1][col]:
row -= 1
else:
if str1[row] == str2[col]:
commons.insert(0, str1[row])
row -= 1
col -= 1
return commons
|
# -*- coding: utf-8 -*-
class Node:
def __init__(self, node_type):
self.type = node_type
self.node_problems = []
@property
def name(self):
return ""
@property
def problems(self):
return self.node_problems
class ValueNode(Node):
def __init__(self, node_type, value):
super().__init__(node_type)
self.value = value
class ParentNode(Node):
def __init__(self, node_type):
super().__init__(node_type)
self.__children = []
self.__children_map = {}
@property
def problems(self):
pbs = self.node_problems.copy()
for chld in self.__children:
pbs.extend(chld.problems)
return pbs
def _get_children(self, name=None):
if name is None:
return self.__children
else:
return self.__children_map.get(name, [])
def _add_child(self, child):
self.__children.append(child)
if child.name not in self.__children_map:
self.__children_map[child.name] = [child]
else:
self.__children_map[child.name].append(child)
|
'''
https://leetcode.com/problems/maximum-subarray/
'''
class Solution(object):
def maxSubArray(self, nums):
if len(nums) == 1:
return nums[0]
m = nums[0]
h = {0:nums[0]}
for i in range(1, len(nums)):
# we loop through the array and store the longest subarray which ends at element i-1 (inclusive)
# adding the element at index i to the maximum sum at index i - 1 would result in a higher sum than simply
# starting a new array with length 1 (only including one element, arr[i]), then we update the dictionary
# to account for the inclusion of the element at index i.
# if the element at index[i] + the value of the max subarray at i-1 is not higher than
# the value of arr[i], we simply start a new array at arr[i], becuase that new array would, by definition,
# be of a greater value than whatever array ended at index i-1.
# example:
# arr [1,4,-6,8,1]
# h [1,5,-1,8,9]
#notice how at index 0,1 and 2, we add element i to the previous sum,
# but at index 3, we do not add the element to the previous indexed sum, we
# simply set the max array value to the value of the element. becuase max(8, 8 + (-1)) = 8.
#and for index 4, we also add the item at i to the previous sum
h[i] = max(nums[i], nums[i] + h[i-1])
if h[i] > m: # we see if the max sum at index i is higher than the currently recorded max sum
# if True, we update the max sum.
m = h[i]
# we return the max sum (int)
return m
|
input = open('input.txt', 'r').read().split("\n")
# Part 1
x = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
distance = int(line_elements[1])
if cmd == 'forward':
x += distance
elif cmd == 'down':
depth += distance
else:
depth += -distance
print('X: ' + str(x))
print('Depth: ' + str(depth))
# Part 2
aim = 0
horizontal = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
value = int(line_elements[1])
if cmd == 'forward':
horizontal += value
depth += aim * value
elif cmd == 'down':
aim += value
else:
aim += -value
print('Part 2')
print('X: ' + str(x))
print('Depth: ' + str(depth))
print('Answer: ' + str(x * depth))
|
_base_ = [
'../../_base_/models/swav/r50.py',
'../../_base_/datasets/imagenet/swav_mcrop-2-6_sz224_96_bs32.py',
'../../_base_/default_runtime.py',
]
# model settings
model = dict(
type='SwAV',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3,), # no conv-1, x-1: stage-x
norm_cfg=dict(type='SyncBN'),
style='pytorch'),
neck=dict(
type='SwAVNeck',
in_channels=2048, hid_channels=2048, out_channels=128,
with_avg_pool=True),
head=dict(
type='SwAVHead',
feat_dim=128, # equal to neck['out_channels']
epsilon=0.05,
temperature=0.1,
num_crops=[2, 6],)
)
# interval for accumulate gradient
update_interval = 8 # total: 8 x bs64 x 8 accumulates = bs4096
# additional hooks
custom_hooks = [
dict(type='SwAVHook',
priority='VERY_HIGH',
batch_size=64,
epoch_queue_starts=15,
crops_for_assign=[0, 1],
feat_dim=128,
queue_length=3840)
]
# optimizer
optimizer = dict(
type='LARS',
lr=0.6 * 16, # lr=0.6 / bs256
momentum=0.9, weight_decay=1e-6,
paramwise_options={
'(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0., lars_exclude=True),
'bias': dict(weight_decay=0., lars_exclude=True),
})
# apex
use_fp16 = True
fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic'))
# optimizer args
optimizer_config = dict(
update_interval=update_interval, use_fp16=use_fp16, grad_clip=None,
cancel_grad=dict(prototypes=2503), # cancel grad of `prototypes` for 1 ep
)
# lr scheduler
lr_config = dict(
policy='CosineAnnealing',
by_epoch=False, min_lr=6e-4,
warmup='linear',
warmup_iters=10, warmup_by_epoch=True,
warmup_ratio=1e-5,
)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=200)
|
# File: vmray_consts.py
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
VMRAY_JSON_SERVER = "vmray_server"
VMRAY_JSON_API_KEY = "vmray_api_key"
VMRAY_JSON_DISABLE_CERT = "disable_cert_verification"
VMRAY_ERR_SERVER_CONNECTION = "Could not connect to server. {}"
VMRAY_ERR_CONNECTIVITY_TEST = "Connectivity test failed"
VMRAY_SUCC_CONNECTIVITY_TEST = "Connectivity test passed"
VMRAY_ERR_UNSUPPORTED_HASH = "Unsupported hash"
VMRAY_ERR_SAMPLE_NOT_FOUND = "Could not find sample"
VMRAY_ERR_OPEN_ZIP = "Could not open zip file"
VMRAY_ERR_ADD_VAULT = "Could not add file to vault"
VMRAY_ERR_MULTIPART = "File is a multipart sample. Multipart samples are not supported"
VMRAY_ERR_MALFORMED_ZIP = "Malformed zip"
VMRAY_ERR_SUBMIT_FILE = "Could not submit file"
VMRAY_ERR_GET_SUBMISSION = "Could not get submission"
VMRAY_ERR_SUBMISSION_NOT_FINISHED = "Submission is not finished"
VMRAY_ERR_NO_SUBMISSIONS = "Sample has no submissions"
VMRAY_ERR_FILE_EXISTS = "File already exists"
VMRAY_ERR_REST_API = "REST API Error"
VMRAY_ERR_CODE_MSG = "Error code unavailable"
VMRAY_ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
VMRAY_PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
VMRAY_ERR_SERVER_RES = "Error processing server response. {}"
VMRAY_INVALID_INTEGER_ERR_MSG = "Please provide a valid integer value in the {}"
VMRAY_NEGATIVE_INTEGER_ERR_MSG = "Please provide a valid non-negative integer value in the {}"
ACTION_ID_VMRAY_GET_FILE = "get_file"
ACTION_ID_VMRAY_DETONATE_FILE = "detonate_file"
ACTION_ID_VMRAY_DETONATE_URL = "detonate_url"
ACTION_ID_VMRAY_GET_REPORT = "get_report"
ACTION_ID_VMRAY_GET_INFO = "get_info"
VMRAY_DEFAULT_PASSWORD = b"infected"
DEFAULT_TIMEOUT = 60 * 10
VMRAY_SEVERITY_NOT_SUSPICIOUS = "not_suspicious"
VMRAY_SEVERITY_SUSPICIOUS = "suspicious"
VMRAY_SEVERITY_MALICIOUS = "malicious"
VMRAY_SEVERITY_BLACKLISTED = "blacklisted"
VMRAY_SEVERITY_WHITELISTED = "whitelisted"
VMRAY_SEVERITY_UNKNOWN = "unknown"
VMRAY_SEVERITY_ERROR = "error"
SAMPLE_TYPE_MAPPING = {
"Apple Script": "apple script",
"Archive": "archive",
"CFB File": "compound binary file",
"Email (EML)": "email",
"Email (MSG)": "email",
"Excel Document": "xls",
"HTML Application": "html application",
"HTML Application (Shell Link)": "html application",
"HTML Document": "html document",
"Hanword Document": "hanword document",
"JScript": "jscript",
"Java Archive": "jar",
"Java Class": "java class",
"macOS App": "macos app",
"macOS Executable": "macos executable",
"macOS PKG": "macos installer",
"MHTML Document": "mhtml document",
"MSI Setup": "msi",
"Macromedia Flash": "flash",
"Microsoft Access Database": "mdb",
"Microsoft Project Document": "mpp",
"Microsoft Publisher Document": "pub",
"Microsoft Visio Document": "vsd",
"PDF Document": "pdf",
"PowerShell Script": "powershell",
"PowerShell Script (Shell Link)": "powershell",
"Powerpoint Document": "ppt",
"Python Script": "python script",
"RTF Document": "rtf",
"Shell Script": "shell script",
"URL": "url",
"VBScript": "vbscript",
"Windows ActiveX Control (x86-32)": "pe file",
"Windows ActiveX Control (x86-64)": "pe file",
"Windows Batch File": "batch file",
"Windows Batch File (Shell Link)": "batch file",
"Windows DLL (x86-32)": "dll",
"Windows DLL (x86-64)": "dll",
"Windows Driver (x86-32)": "pe file",
"Windows Driver (x86-64)": "pe file",
"Windows Exe (Shell Link)": "pe file",
"Windows Exe (x86-32)": "pe file",
"Windows Exe (x86-64)": "pe file",
"Windows Help File": "windows help file",
"Windows Script File": "windows script file",
"Word Document": "doc",
}
|
IDENTIFIER = 'everything'
NEWSPAPER_DIR = 'newspapers_everything'
RESULTS_DIR = 'results_everything'
MIN_FREQUENCY = 50
EPOCHS = 40
MODEL_OPTIONS = {
'vector_size': 100,
'alpha': 0.1,
'window': 8,
'sample': 0.00001,
'workers': 8
}
VOCABULARY = f'{IDENTIFIER}.dict'
|
a, b, c = map(int, input().split())
x = max(a, b, c)
total = a + b + c
if x % 2 != total % 2:
x += 1
print((3 * x - total) // 2)
|
class BentPlateTestingTool(object):
""" BentPlateTestingTool() """
def CreateByFaces(self, part1, face1, part2, face2):
""" CreateByFaces(self: BentPlateTestingTool,part1: Part,face1: IList[Point],part2: Part,face2: IList[Point]) -> BentPlate """
pass
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.rst = list()
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# Recursive method
self.inorder_traverse(root)
return self.rst
# TODO: Iteration method
def inorder_traverse(self, root):
if root:
self.inorder_traverse(root.left)
if root.val is not None:
self.rst.append(root.val)
self.inorder_traverse(root.right)
|
count = 0
sum = 0
while True:
X = float(input(''))
if X >= 0 and X <= 10:
count += 1
sum += X
if count == 2:
average = sum / count
print('media = %0.2f' %average)
break
else:
print('nota invalida')
|
commands = []
while True:
try: line = input()
except: break
if not line: break
commands.append(line.split())
for starting_a in range(155, 160):
d = {'a': starting_a, 'b': 0, 'c': 0, 'd': 0}
i = 0
out = []
while len(out) < 100:
if commands[i][0] == 'inc' and commands[i+1][0] == 'dec' and commands[i+2][0] == 'jnz' and commands[i+1][1] == commands[i+2][1] and commands[i+2][2] == '-2':
d[commands[i][1]] += d[commands[i+1][1]]
d[commands[i+1][1]] = 0
i += 3
continue
elif commands[i][0] == 'cpy':
a, b = commands[i][1:]
if a.isalpha():
d[b] = d[a]
elif b.isalpha():
d[b] = int(a)
elif commands[i][0] == 'inc':
d[commands[i][1]] += 1
elif commands[i][0] == 'dec':
d[commands[i][1]] -= 1
elif commands[i][0] == 'jnz':
a, b = commands[i][1:]
if a.isalpha():
if d[a] != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
else:
if int(a) != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
elif commands[i][0] == 'tgl':
a = commands[i][1]
if a.isalpha(): a = d[a]
else: a = int(a)
if i + a >= 0 and i + a < len(commands):
command = commands[i + a][0]
if command == 'inc': command = 'dec'
elif command == 'dec': command = 'inc'
elif command == 'jnz': command = 'cpy'
elif command == 'cpy': command = 'jnz'
elif command == 'tgl': command = 'inc'
commands[i + a][0] = command
elif commands[i][0] == 'out':
out.append(d[commands[i][1]])
i += 1
if out == [i % 2 for i in range(100)]:
print(starting_a)
|
tiles = [
(17, 20946, 50678), # https://www.openstreetmap.org/way/215472849
(17, 20959, 50673), # https://www.openstreetmap.org/node/1713279804
(17, 20961, 50675), # https://www.openstreetmap.org/node/3188857553
(17, 20969, 50656), # https://www.openstreetmap.org/node/3396659022
(17, 21013, 50637), # https://www.openstreetmap.org/node/1467717312
(17, 21019, 50617), # https://www.openstreetmap.org/node/2286100659
(17, 21028, 50645), # https://www.openstreetmap.org/node/3711137981
(17, 38597, 49266), # https://www.openstreetmap.org/node/3810578539
(17, 38598, 49259), # http://www.openstreetmap.org/node/2678466844
(17, 38600, 49261), # https://www.openstreetmap.org/node/1429062988
(17, 38601, 49258), # https://www.openstreetmap.org/node/1058296287
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'pois',
{ 'kind': 'toys' })
|
def method1(n: int) -> int:
c = 0
while n:
c += n & 1
n >>= 1
return c
def method2(n: int) -> int:
if n == 0:
return 0
else:
return (n & 1) + method2(n >> 1)
if __name__ == "__main__":
"""
from timeit import timeit
print(timeit(lambda: method1(9), number=10000)) # 0.0034751240000332473
print(timeit(lambda: method2(9), number=10000)) # 0.006590511000013066
"""
|
"""These stopwords are taken from
- people.stanford.edu/widner/content/text-mining-middle-ages (slide 13)
- textifier.com/resources/common-english-words.txt
- en.wikipedia.org/wiki/Middle_English
- en.wiktionary.org/wiki/Category:Middle_English_prepositions
- en.wiktionary.org/wiki/Category:MIddle_English_determiners
- en.wiktionary.org/wiki/Category:MIddle_English_conjunctions"""
STOPS_LIST = ['ac',
'afore',
'ake',
'an',
'because',
'ek',
'fore',
'for',
'forthi',
'whan',
'whanne',
'whilis',
'if',
'yf',
'yif',
'yiff',
'yit',
'yet',
'and',
'or',
'any',
'but',
'a',
'y',
'ne',
'no',
'not',
'nor',
'nat',
'however',
'o',
'than',
'n',
'nn',
'nnn',
'to',
'with',
'wyth',
'at',
'as',
'of',
'off',
'from',
'on',
'before',
'by',
'after',
'about',
'above',
'across',
'among',
'against',
'below',
'between',
'during',
'into',
'in',
'out',
'over',
'under',
'abord',
'aboven',
'afore',
'aftir',
'bi',
'bifor',
'bisyde',
'bitwixten',
'byfore',
'bytwene',
'down',
'doun',
'embe',
'fra',
'ine',
'mid',
'sanz',
'tyll',
'umbe',
'vnto',
'vpon',
'withouten',
'with',
'wth',
'wtout',
'can',
'cannot',
"can't",
't',
'could',
'did',
'do',
'does',
'wyl',
'will',
'would',
'haven',
'hast',
'haþ',
'havende',
'hadde',
'haddest',
'hadden',
'had',
"hadn't",
'has',
"hasn't",
'hasn',
'have',
"haven't",
'haven',
'having',
'be',
'ben',
'been',
'am',
'art',
'is',
'ys',
'aren',
'are',
"aren't",
'bende',
"isn't",
'isn',
'wæs',
'was',
"wasn't",
'wasn',
'weren',
'were',
"weren't",
'þe',
'the',
'þat',
'þenne',
'þis',
'whiche',
'which',
'while',
'who',
'whom',
'what',
'when',
'where',
'why',
'that',
"that's",
's',
'there',
'ther',
'þer',
"there's",
'these',
'this',
'those',
'boþe',
'thilke',
'eiþer',
'either',
'neither',
'al',
'all',
'also',
'ane',
'ic',
'ich',
'i',
"i'd",
'd',
"i'll",
'll',
"i'm",
'm',
"i've",
've',
'me',
'mi',
'my',
'minen',
'min',
'mire',
'minre',
'myself',
'þu',
'þou',
'tu',
'þeou',
'thi',
'you',
'þe',
'þi',
'ti',
'þin',
'þyn',
'þeself',
"you'd",
"you'll",
"you're",
're',
"you've",
'your',
'yours',
'yourself',
'yourselves',
'thee',
'thy',
'thou',
'ye',
'thine',
'he',
"he'd",
"he'll",
"he's",
'she',
'sche',
"she'd",
"she'll",
"she's",
'her',
'heo',
'hie',
'hies',
'hire',
'hir',
'hers',
'hio',
'heore',
'herself',
'him',
'hine',
'hisse',
'hes',
'himself',
'his',
'hys',
'hym',
'hit',
'yt',
'it',
'its',
"it's",
'tis',
'twas',
'itself',
'þay',
'youre',
'hyr',
'hem',
'we',
"we'd",
"we'll",
"we're",
"we've",
'us',
'ous',
'our',
'ure',
'ures',
'urne',
'ours',
'oures',
'ourselves',
'their',
'theirs',
'them',
'themselves',
'thai',
'thei',
'they',
"they'd",
"they'll",
"they're",
"they've",
'whan']
|
'''
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Input: num1 = [3], nums2 = [3]
Output: 1
Input: [1,2], [4,6]
Output: 0
Input: nums1 = [0,0,0,0], nums2 = [0,0,0,0,0]
Output: 4
Precondition:
len(nums1) = m
len(nums2) = n
m, n >= 1
C1: single elements in both, same
C2: single elements in both, not same
C3: 0 as a result
C4: result > 0
C5: result = len(min(m,n))
Algo:
Brute Force: O(mn*min(m,n))
For each element in nums1, try to find same element in nums2 O(mn)
if found, extend as long as possible
return the longest size
DP:
dp[i][j]: common prefix length for nums1[i:] and nums2[j:]
dp[i][j] = dp[i+1][j+1] if nums1[i] = nums2[j]
dp[m][n] = 0
result: max of all possible i,j in dp[i][j]
Runtime: O(mn)
Space: O(mn)
'''
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if nums1[i] == nums2[j]:
dp[i][j] = dp[i+1][j+1] + 1
return max(max(x) for x in dp)
|
def data_generator_enabled(request):
return {'DATA_GENERATOR_ENABLED': True}
|
class Encoders:
def __init__(self, aStar):
self.aStar = aStar
self.countLeft = 0
self.countRight = 0
self.lastCountLeft = 0
self.lastCountRight = 0
self.countSignLeft = 1
self.countSignRight = -1
self.aStar.reset_encoders()
def readCounts(self):
countLeft, countRight = self.aStar.read_encoders()
diffLeft = (countLeft - self.lastCountLeft) % 0x10000
if diffLeft >= 0x8000:
diffLeft -= 0x10000
diffRight = (countRight - self.lastCountRight) % 0x10000
if diffRight >= 0x8000:
diffRight -= 0x10000
self.countLeft += self.countSignLeft * diffLeft
self.countRight += self.countSignRight * diffRight
self.lastCountLeft = countLeft
self.lastCountRight = countRight
return self.countLeft, self.countRight
def reset(self):
self.countLeft = 0
self.countRight = 0
|
def DectoHex(n):
if isinstance(n,int) == True:
hexnum = hex(n)[2:]
return hexnum.upper()
else:
intnum = int(n)
hexnum = hex(intnum)[2:]
return hexnum.upper()
|
params = [
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 85.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'alpha',
'title': 'Stolaroff',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 15.0,
'xnumber': 10,
'validation': False,
'validationcase': 'Stolaroff2018',
'batterytechnology': 'current'
},
{
'validation': False,
'validationcase': 'Ostler2009',
'drone': True,
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 89.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'Ostler2009',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 30.0,
'xnumber': 20,
'batterytechnology': 'current'
},
{
'drone': True,
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 89.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'FreeFLY_Alta8',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 10.0,
'xnumber': 100,
'validation': False,
'validationcase': 'FreeFLYAlta8',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'FreeFLY_Alta8',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 1.0,
'xnumber': 20,
'validation': False,
'validationcase': 'FireFLY6Pro',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'power',
'title': 'First_test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.5,
'xend': 1.5,
'xnumber': 10,
'validation': False,
'validationcase': 'Dorling2017_3S',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'power',
'title': 'First_test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.5,
'xend': 1.5,
'xnumber': 10,
'validation': False,
'validationcase': 'Dorling2017_4S',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'DiFranco',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 16.0,
'xnumber': 20,
'validation': False,
'validationcase': 'DiFranco2016',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'Stolaroff',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 16.0,
'xnumber': 20,
'validation': False,
'validationcase': 'Chang2016',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'Abdilla 2015 Endurance vs Payload Validation Test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.4,
'xend': 0.55,
'xnumber': 20,
'validation': False,
'validationcase': 'Abdilla2015endurance',
'batterytechnology': 'current'
}
]
|
## Python INTRO for TD Users
## Kike Ramírez
## May, 2018
## Understanding python strings.
string1 = "I Love Python!"
## Print first character
print ("string1[0]:",string1[0])
## Print characters from 3 to 5!
print ("string1[2:5]:",string1[2:5])
## Print last character only
print ("string1[-1]:",string1[-1])
## Print all but last character
print ("string1[:-1]:",string1[:-1])
# Print characters from 3 to end
print ("string1[2:]:",string1[2:])
|
__ = "-=> FILL ME IN! <=-"
def assert_equal(expected, actual):
assert expected == actual, '%r == %r' % (expected, actual)
# double quoted strings are strings
string = "Hello, world."
assert_equal(__, isinstance(string, str))
# single quoted strings are also strings
string = 'Goodbye, world.'
assert_equal(__, isinstance(string, str))
# triple quote strings are also strings
string = """Howdy, world!"""
assert_equal(__, isinstance(string, str))
# triple single quotes work too
string = '''Bonjour tout le monde!'''
assert_equal(__, isinstance(string, str))
# raw strings are also strings
string = r"Konnichi wa, world!"
assert_equal(__, isinstance(string, str))
# use single quotes to create string with double quotes
string = 'He said, "Go Away."'
assert_equal(__, string)
# use double quotes to create strings with single quotes
string = "Don't"
assert_equal(__, string)
# use backslash for escaping quotes in strings
a = "He said, \"Don't\""
b = 'He said, "Don\'t"'
assert_equal(__, (a == b))
# use backslash at the end of a line to continue onto the next line
string = "It was the best of times,\n\
as the worst of times."
assert_equal(__, len(string))
# triple quoted strings can span lines
string = """
Howdy,
world!
"""
assert_equal(__, len(string))
# triple quoted strings need less escaping
a = "Hello \"world\"."
b = """Hello "world"."""
assert_equal(__, (a == b))
# escaping quotes at the end of triple quoted string
string = """Hello "world\""""
assert_equal(__, string)
# plus concatenates strings
string = "Hello, " + "world"
assert_equal(__, string)
# adjacent strings are concatenated automatically
string = "Hello" ", " "world"
assert_equal(__, string)
# plus will not modify original strings
hi = "Hello, "
there = "world"
string = hi + there
assert_equal(__, hi)
assert_equal(__, there)
# plus equals will append to end of string
hi = "Hello, "
there = "world"
hi += there
assert_equal(__, hi)
# plus equals also leaves original string unmodified
original = "Hello, "
hi = original
there = "world"
hi += there
assert_equal(__, original)
# most strings interpret escape characters
string = "\n"
assert_equal('\n', string)
assert_equal("""\n""", string)
assert_equal(__, len(string))
# a character in string can be accesses like in list
string = "Hello"
assert_equal(__, string[1])
# you can check weather a character is in string
string = "Hello"
assert_equal(__, 'H' in string)
assert_equal(__, 'Z' in string)
|
"""
>>> nCr(4, 2)
6
"""
def nCr(n, k):
# C = [[0] * (k+1) for i in range(n+1)]
# for i in range(n+1):
# C[i][0] = 1
# for i in range(1, k+1):
# C[0][i] = 0
# for i in range(1, n+1):
# for j in range(1, k+1):
# C[i][j] = C[i-1][j-1] + C[i-1][j]
# return C
C = [0] * (k+1)
C[0] = 1
for i in range(n):
print(i)
C_backup = C[:]
for j in range(1, k+1):
C[j] += C_backup[j-1]
return C[k]
print(nCr(4, 2))
print(nCr(5, 4))
print(nCr(6, 3))
|
skip_files = ["Fleece+CoreFoundation.h"]
excluded = ["FLStr","operatorslice","operatorFLSlice","FLMutableArray_Retain","FLMutableArray_Release","FLMutableDict_Retain","FLMutableDict_Release","FLEncoder_NewWritingToFile","FLSliceResult_Free"]
default_param_name = {"FLValue":"value","FLSliceResult":"slice","FLSlice":"slice","FLArray":"array","FLArrayIterator*":"i","FLDictIterator*":"i","FLDict":"dict","FLDictKey":"key","FLKeyPath":"keyPath","FLDictKey*":"dictKey","FLSharedKeys":"shared","FLEncoder":"encoder","long":"l","ulong":"u","bool":"b","float":"f","double":"d","FLError*":"outError","int64_t":"l","uint64_t":"u","FLString":"str","FLStringResult":"str"}
param_bridge_types = ["FLSlice", "FLString", "size_t", "size_t*"]
force_no_bridge = ["FLSlice_Compare", "FLSlice_Equal","FLSliceResult_Retain","FLSliceResult_Release","FLSlice_Copy","FLDoc_FromResultData"]
return_bridge_types = ["FLSliceResult", "FLSlice", "size_t", "FLString", "FLStringResult"]
type_map = {"int32_t":"int","uint32_t":"uint","int64_t":"long","uint64_t":"ulong","size_t":"UIntPtr","size_t*":"UIntPtr*","unsigned":"uint","FLValue":"FLValue*","FLDict":"FLDict*","FLArray":"FLArray*","FLEncoder":"FLEncoder*","FLSharedKeys":"FLSharedKeys*","FLKeyPath":"FLKeyPath*","FLDoc":"FLDoc*","FLDeepIterator":"FLDeepIterator*"}
literals = {"FLSlice_Compare":".nobridge .int FLSlice_Compare FLSlice:left FLSlice:right"}
reserved = ["string","base"]
|
'''
Напишите программу, которая объявляет переменную "s" и присваивает ей значение
"Мы изучаем язык программирования Python".
После инициализации переменной программа должна напечатать значение этой переменной.
Sample Input:
Sample Output:
Мы изучаем язык программирования Python
'''
s = 'Мы изучаем язык программирования Python'
print(s)
|
"""This application overrides to django-machina's forum_conversation app."""
# pylint: disable=invalid-name
default_app_config = (
"ashley.machina_extensions.forum_conversation.apps.ForumConversationAppConfig"
)
|
# [351] Android Unlock Patterns
# Description
# Given an Android 3x3 key lock screen and two integers m and n, where 1 <= m <= n <= 9,
# count the total number of unlock patterns of the Android lock screen, which consist
# of minimum of m keys and maximum n keys.
# Rules for a valid pattern:
# 1) Each pattern must connect at least m keys and at most n keys.
# 2) All the keys must be distinct.
# 3) If the line connecting two consecutive keys in the pattern passes through any other keys,
# the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
# 4) The order of keys used matters.
# Explanation:
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | 8 | 9 |
# Invalid move: 4 - 1 - 3 - 6
# Line 1 - 3 passes through key 2 which had not been selected in the pattern.
# Invalid move: 4 - 1 - 9 - 2
# Line 1 - 9 passes through key 5 which had not been selected in the pattern.
# Valid move: 2 - 4 - 1 - 3 - 6
# Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
# Valid move: 6 - 5 - 4 - 1 - 9 - 2
# Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
# Example
# Example 1
# Input: m = 1, n = 1
# Output: 9
# Example 2
# Input: m = 1, n = 2
# Output: 65
class Solution:
"""
@param m: an integer
@param n: an integer
@return: the total number of unlock patterns of the Android lock screen
"""
def __init__(self):
self.count = 0
self.res = []
self.corners = [[0,0], [0,2], [2,0], [2, 2]]
def numberOfPatterns(self, m, n):
# Write your code here
nums = [i for i in range(9)]
self.dfs(m, n, [], 0, nums)
# for res in self.res:
# print(res)
return self.count
def dfs(self, m, n, curr, start, nums):
if len(curr) > n:
return
if m <= len(curr) <= n:
self.count += 1
self.res.append(curr[:])
for i in range(start, len(nums)):
if nums[i] not in curr:
curr.append(nums[i])
if self.valid(curr):
self.dfs(m, n, curr, 0, nums)
curr.pop()
def valid(self, points):
prev_x, prev_y = points[0] // 3, points[0] % 3
record = set([(prev_x, prev_y)])
for i in range(1, len(points)):
x, y = points[i] // 3, points[i] % 3
if not ( (abs(x - prev_x) == 1 and abs(y - prev_y) == 0) \
or (abs(x - prev_x) == 0 and abs(y - prev_y) == 1) \
or (abs(x - prev_x) == 1 and abs(y - prev_y) == 1) \
or (abs(x - prev_x) == 1 and abs(y - prev_y) == 2) \
or (abs(x - prev_x) == 2 and abs(y - prev_y) == 1) ):
if (abs(x - prev_x) == 0 and abs(y - prev_y) == 2):
if (x, max(y, prev_y) - 1) not in record:
return False
if (abs(x - prev_x) == 2 and abs(y - prev_y) == 0):
if (max(x, prev_x) - 1, y) not in record:
return False
if x + y == prev_x + prev_y or x - y == prev_x - prev_y:
if (1, 1) not in record:
return False
record.add((x, y))
prev_x, prev_y = x, y
return True
|
#!/usr/bin/env python
# encoding: utf-8
# author: pyclearl
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# leetcode这里要注释掉才能AC
class Solution(object):
def __init__(self):
self.carry = 0
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p, q = l1, l2
result = curr = ListNode(0)
while p or q:
val_p = p.val if p else 0
val_q = q.val if q else 0
_sum = self.carry + val_p + val_q
self.carry = _sum / 10
curr.next = ListNode(_sum % 10)
curr = curr.next
if p:
p = p.next
if q:
q = q.next
if self.carry > 0:
curr.next = ListNode(self.carry)
return result.next
if __name__ == "__main__":
pass
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
class GroupTransform:
"""
GroupTransform
"""
def __init__(self):
pass
def getTransform(self, index):
pass
def getNumTransforms(self):
pass
def appendTransform(self, transform):
pass
|
# Python - 3.4.3
def calculator(x, y, op):
# 使用根據運算子建立對應的計算值並回傳
return {
'+': x + y,
'-': x - y,
'*': x * y,
'/': x / y
}.get(op, 'unknown value')
|
#somando dois numeros
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
s = n1 + n2
print('{} mais {} é igual a {}'.format(n1, n2, s))
# int 7, -4, 0 9875
# float 4.5 0.076 -15.223 3.1415333 7.0
# bool True False
# str alfanumerico ' '
|
'''
Created on 27 Aug 2010
@author: dev
solr configurations
'''
solr_base_url = "http://solr:8983/solr/"
solr_urls = {
'all' : solr_base_url + 'all',
'locations' : solr_base_url + 'locations',
'comments' : solr_base_url + 'comments',
'images' : solr_base_url + 'images',
'works' : solr_base_url + 'works',
'people' : solr_base_url + 'people',
'manifestations' : solr_base_url + 'manifestations',
'institutions' : solr_base_url + 'institutions',
'resources' : solr_base_url + 'resources',
}
solr_urls_stage = {
'all' : solr_base_url + 'all_stage',
'locations' : solr_base_url + 'locations_stage',
'comments' : solr_base_url + 'comments_stage',
'images' : solr_base_url + 'images_stage',
'works' : solr_base_url + 'works_stage',
'people' : solr_base_url + 'people_stage',
'manifestations' : solr_base_url + 'manifestations_stage',
'institutions' : solr_base_url + 'institutions_stage',
'resources' : solr_base_url + 'resources_stage',
}
|
'''Faça um programa que leia um número digitado pelo usuário. Depois, informe todos os
números primos gerados até o número digitado pelo usuário.'''
n = int(input("Verificar números primos até:"))
cont=0
nPrimos = []
for i in range(2,n):
if (n % i == 0):
cont += 1
if(cont==0):
nPrimos.append(n)
print(nPrimos)
|
def clean_version(
version: str,
*,
build: bool = False,
patch: bool = False,
commit: bool = False,
drop_v: bool = False,
flat: bool = False,
):
"Clean up and transform the many flavours of versions"
# 'v1.13.0-103-gb137d064e' --> 'v1.13-103'
if version in ["", "-"]:
return version
nibbles = version.split("-")
if not patch:
if nibbles[0] >= "1.10.0" and nibbles[0].endswith(".0"):
# remove the last ".0"
nibbles[0] = nibbles[0][0:-2]
if len(nibbles) == 1:
version = nibbles[0]
elif build and build != "dirty":
if not commit:
version = "-".join(nibbles[0:-1])
else:
version = "-".join(nibbles)
else:
# version = "-".join((nibbles[0], LATEST))
# HACK: this is not always right, but good enough most of the time
version = "latest"
if flat:
version = version.strip().replace(".", "_")
if drop_v:
version = version.lstrip("v")
else:
# prefix with `v` but not before latest
if not version.startswith("v") and version.lower() != "latest":
version = "v" + version
return version
|
print("Insert an in integer")
n = input()
nn = n + n
nnn = nn + n
result = int(n) + int(nn) + int(nnn)
print(result)
|
"""
Metaclass of Response and Request
"""
class ResponseMeta(type):
"""
Meta class of Response
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Response', 'ResendResponse']:
mcs.register(clazz, attrs['TYPE'])
return clazz
class RequestMeta(type):
"""
Meta class of Request
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Request']:
mcs.register(clazz, attrs['TYPE'])
return clazz
|
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
'''All Gold are equal'''
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ""
direction = Direction("right")
def can_grab(self, thing):
'''Explorer can only grab gold'''
return thing.__class__ == Gold
class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 #Probability to spawn a pit in a location. (From Chapter 7.2)
#Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super(WumpusEnvironment, self).__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
'''Spawn items to the world based on probabilities from the book'''
"WALLS"
self.add_walls()
"PITS"
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x,y), True)
self.add_thing(Breeze(), (x - 1,y), True)
self.add_thing(Breeze(), (x,y - 1), True)
self.add_thing(Breeze(), (x + 1,y), True)
self.add_thing(Breeze(), (x,y + 1), True)
"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude = (1,1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)
"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude = (1,1)), True)
#self.add_thing(Gold(), (2,1), True) Making debugging a whole lot easier
"AGENT"
self.add_thing(Explorer(program), (1,1), True)
def get_world(self, show_walls = True):
'''returns the items in the world'''
result = []
x_start,y_start = (0,0) if show_walls else (1,1)
x_end,y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x,y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass = Thing):
'''Returns percepts from a given location, and replaces some items with percepts from chapter 7.'''
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()
}
'''Agents don't need to get their percepts'''
thing_percepts[agent.__class__] = None
'''Gold only glitters in its cell'''
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
'''Returns things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]'''
x,y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1,y)))
result.append(self.percepts_from(agent, (x + 1,y)))
result.append(self.percepts_from(agent, (x,y - 1)))
result.append(self.percepts_from(agent, (x,y + 1)))
result.append(self.percepts_from(agent, (x,y)))
'''The wumpus gives out a a loud scream once it's killed.'''
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and not wumpus[0].alive and not wumpus[0].screamed:
result[-1].append(Scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
'''Modify the state of the environment based on the agent's actions
Performance score taken directly out of the book'''
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action == 'TurnRight':
agent.direction = agent.direction + Direction.R
agent.performance -= 1
elif action == 'TurnLeft':
agent.direction = agent.direction + Direction.L
agent.performance -= 1
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location)
if agent.can_grab(thing)]
if len(things):
print("Grabbing", things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1,1): #Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
'''The arrow travels straight down the path the agent is facing'''
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while(self.is_inbounds(arrow_travel)):
wumpus = [thing for thing in self.list_things_at(arrow_travel)
if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)
agent.has_arrow = False
def in_danger(self, agent):
'''Checks if Explorer is in danger (Pit or Wumpus), if he is, kill him'''
for thing in self.list_things_at(agent.location):
if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive):
agent.alive = False
agent.performance -= 1000
agent.killed_by = thing.__class__.__name__
return True
return False
def is_done(self):
'''The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)'''
explorer = [agent for agent in self.agents if isinstance(agent, Explorer) ]
if len(explorer):
if explorer[0].alive:
return False
else:
print("Death by {} [-1000].".format(explorer[0].killed_by))
else:
print("Explorer climbed out {}."
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
return True
#Almost done. Arrow needs to be implemented
|
print('\033[1m>>> SOMA E MÉDIA <<<\033[m')
soma = 0
c = 0
for c in range(5):
c += 1
num = int(input(f'- {c}º VALOR: '))
soma += num
media = soma/c
print(f'A SOMA DOS VALORES É: {soma}')
print(f'A MÉDIA DOS VALORES É: {media:.2f}')
|
"""
########################B6-Dictionary(字典)#########################
"""
"""
字典(dictionary)是Python中另一个非常有用的内置数据类型。
列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。
键(key)必须使用不可变类型。在同一个字典中,键(key)必须是唯一的。
"""
dict = {}
dict['one'] = "one的value"
dict[2] = "two"
tinydict = {'name': 'lanhuigu', 'age': 27}
print(dict['one']) # 输出键为 'one' 的值
print(dict[2]) # 输出键为 2 的值
print(tinydict) # 输出完整的字典
print(tinydict.keys()) # 输出所有键
print(tinydict.values()) # 输出所有值
|
"""2019 Advent of Code, Day 1"""
with open("input", "r+") as file:
puzzle_input = file.readlines()
def mass(item):
"""Calculate the fuel required for an item, and the fuel required for that fuel, and so on"""
fuel = item // 3 - 2
if fuel < 0:
return 0
return fuel + mass(fuel)
SUM = 0
SUM_2 = 0
for module in puzzle_input:
SUM += int(module) // 3 - 2
SUM_2 += mass(int(module))
print(SUM, SUM_2)
|
class Command(object):
"""
By using the NAMES command, a user can list all nicknames that are
visible to him. For more details on what is visible and what is not,
see "Internet Relay Chat: Channel Management" [IRC-CHAN]. The
<channel> parameter specifies which channel(s) to return information
about. There is no error reply for bad channel names.
If no <channel> parameter is given, a list of all channels and their
occupants is returned. At the end of this list, a list of users who
are visible but either not on any channel or not on a visible channel
are listed as being on `channel' "*".
If the <target> parameter is specified, the request is forwarded to
that server which will generate the reply.
Wildcards are allowed in the <target> parameter.
Numerics:
ERR_TOOMANYMATCHES ERR_NOSUCHSERVER
RPL_NAMREPLY RPL_ENDOFNAMES
Examples:
NAMES #twilight_zone,#42 ; Command to list visible users on
#twilight_zone and #42
NAMES ; Command to list all visible
channels and users
"""
@staticmethod
def can_names(server, client, channel=None):
pass
"""
<- :gunslinger.shadowfire.org 353 kevin = #gopugs :kevin Sven fragtion FlaMeBeRg @GameBot ~@Russ!
<- :gunslinger.shadowfire.org 353 kevin = #gopugs :Lithium!~AndrewMoh@SF-3740E9DA.andrewmohawk.com Webtricity!web@staff.shadowfire.org
"""
@staticmethod
def on_names(server, client, channel=None):
chan = server.get_channel(channel)
# Send end of list
if not channel or not chan:
client.send_366("*")
return
# Send channel with empty users.
if client not in chan.users:
client.send_353(channel, [])
client.send_366(channel)
return
# Send proper names list now. Split into lists of max 6 users
users = chan.users
temp = []
for user in users:
temp.append(user.hostmask)
if len(temp) == 6:
client.send_353(channel, temp)
temp = []
client.send_353(channel, temp)
client.send_366(channel)
|
print(divmod(100, 7))
print(7 > 2 and 1 > 6)
print(7 > 2 or 1 > 6)
number_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
print(number_list[2:8])
print(number_list[0:9:3])
print(number_list[0:10:3])
|
# https://docs.python.org/3/library/functions.html#built-in-functions
my_results = [True, True, 2*2==4, True]
print(all(my_results)) # all statements in the sequence should be truthy to get True else we get False
my_results.append(False)
print(my_results)
print(all(my_results)) #In logic this is called universal quantor, all my)_results must be truthy for all to return True
print(any(my_results)) # any just needs one true result inside, existences kvantors, one or more items are true
print(len(my_results))
my_results.append(9000)
print("max", max(my_results)) # we only have 1 or 0 in my_results
my_results.append(-30)
print(my_results)
print("min", min(my_results))
print("summa", sum(my_results)) # well when summing booleans True is 1 and False is 0
# print(min(my_results))
|
#!/usr/bin/env pyrate
build_output = ['makefile']
ex_d = executable('exampleM2_debug.bin', 'test.cpp foo.cpp', compiler_opts = '-O0')
ex_r = executable('exampleM2_release.bin', 'test.cpp foo.cpp', compiler_opts = '-O3')
default_targets = ex_r
|
class DescriptionError(Exception):
pass
class ParseError(DescriptionError):
pass
class GettingError(DescriptionError):
pass
|
MyAttr = 'eval:1'
My_Attr = 'eval:foo=1;bar=2;foo+bar'
attr_1 = 'tango:a/b/c/d'
attr_2 = 'a/b/c/d'
attr1 = 'eval:"Hello_World!!"'
foo = 'eval:/@Foo/True'
# 1foo = 'eval:2'
Foo = 'eval:False'
res_attr = 'res:attr1'
dev1 = 'tango:a/b/c' # invalid for attribute
dev2 = 'eval:@foo' # invalid for attribute
|
# Problem 1
# 1'den 1000'e kadar olan sayılardan mükemmel sayı olanları ekrana yazdırın.
# Bunun için bir sayının mükemmel olup olmadığını dönen bir tane fonksiyon
# yazın.
# Bir sayının bölenlerinin toplamı kendine eşitse bu sayı mükemmel bir
# sayıdır. Örnek olarak 6 mükemmel bir sayıdır (1 + 2 + 3 = 6).
def perfNum(tpNum):
tpSum = 0
for i in range(1,tpNum):
if tpNum % i == 0:
tpSum += i
return tpSum == tpNum
for x in range(1,1001):
if (perfNum(x)):
print("Mükemmel Sayı: ",x)
#******************************************************************
# Problem 3
# Kullanıcıdan 2 tane sayı alarak bu sayıların en küçük ortak katlarını (EKOK)
# dönen bir tane fonksiyon yazın.
def find_ekok(tpNum1,tpNum2):
i = 2
ekok = 1
while True:
if tpNum1 % i == 0 and tpNum2 % i == 0:
ekok *= i
tpNum1 //= i
tpNum2 //= i
elif tpNum1 % i == 0 and tpNum2 % i == 0:
ekok *= i
tpNum1 //= i
elif tpNum1 % i != 0 and tpNum2 % i == 0:
ekok *= i
tpNum2 //= i
else:
i += 1
if tpNum1 == 1 and tpNum2 == 1:
break
return ekok
num1 = int(input("Birinci Sayıyı giriniz: "))
num2 = int(input("İkinci Sayıyı giriniz: "))
print("Ekok",find_ekok(num1,num2))
#******************************************************************
# Problem 4
# Kullanıcıdan 2 basamaklı bir sayı alın ve bu sayının okunuşunu
# bulan bir fonksiyon yazın.
def spellNum(tpNum):
onesDigit = tpNum % 10
tensDigit = tpNum // 10
return tensDigitList[tensDigit] + " " + onesDigitList[onesDigit]
tensDigitList = ["","On","Yirmi","Otuz","Kırk","Elli","Altmış","Yetmiş","Seksen","Doksan"]
onesDigitList = ["","Bir","İki","Üç","Dört","Beş","Altı","Yedi","Sekiz","Dokuz"]
num = int(input("Bir sayı giriniz: "))
print(num,"'ın okunuşu:",spellNum(num))
#******************************************************************
# Problem 5
# 1'den 100'e kadar olan sayılardan pisagor üçgeni oluşturanları
# ekrana yazdıran bir fonksiyon yazın.(a <= 100,b <= 100)
def pisFind():
pisListe = list()
for x in range(1, 101):
for y in range(1, 101):
z = ((x ** 2) + (y ** 2)) ** 0.5
if (z == int(z)):
pisListe.append((x, y, int(z)))
return pisListe
for i in pisFind():
print(i)
|
# Program to input a number and find it's sum of digits
n = int(input("Enter the number: "))
tot = 0
while(n>0):
d = n%10
tot = tot+d
n=n//10
print("Sum of Digits is:",tot)
|
def func():
print("func() in one.py")
print("TOP LEVEL ONE.PY")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py has been imported")
|
class NessusObject(object):
def __init__(self, server):
self._id = None
self._server = server
def save(self):
if self._id is None:
return getattr(self._server, "create_%s" % self.__class__.__name__.lower())(self)
else:
return getattr(self._server, "update_%s" % self.__class__.__name__.lower())(self)
def delete(self):
if self._id is not None:
return getattr(self._server, "delete_%s" % self.__class__.__name__.lower())(self)
@property
def id(self):
return self._id
@id.setter
def id(self, _id):
self._id = _id
|
#Find structs by field type.
#@author Rena
#@category Struct
#@keybinding
#@menupath
#@toolbar
StringColumnDisplay = ghidra.app.tablechooser.StringColumnDisplay
AddressableRowObject = ghidra.app.tablechooser.AddressableRowObject
TableChooserExecutor = ghidra.app.tablechooser.TableChooserExecutor
DTM = state.tool.getService(ghidra.app.services.DataTypeManagerService)
AF = currentProgram.getAddressFactory()
DT = currentProgram.getDataTypeManager()
listing = currentProgram.getListing()
mem = currentProgram.getMemory()
def addrToInt(addr):
return int(str(addr), 16)
def intToAddr(addr):
return AF.getAddress("0x%08X" % addr)
class Executor(TableChooserExecutor):
def getButtonName(self):
return "Edit Structure"
def execute(self, row):
DTM.edit(row.struc) # show the structure editor
return False # do not remove row
class StructNameColumn(StringColumnDisplay):
def getColumnName(self):
return "Struct Name"
def getColumnValue(self, row):
return row.struc.displayName
class StructLengthColumn(StringColumnDisplay):
def getColumnName(self):
return "Struct Size"
def getColumnValue(self, row):
return row.struc.length
class StructListResult(AddressableRowObject):
def __init__(self, struc):
self.struc = struc
def getAddress(self):
return intToAddr(self.struc.length)
def run():
# XXX find a way to make this UI better.
# criteria is eg:
# B8=*int (a struct with an int* at 0xB8)
# B8=* (a struct with any pointer at 0xB8)
# B8=2 (a struct with any field at 0xB8 with length 2)
# B8=*2 (a struct with a pointer at 0xB8 to something with length 2)
# B8 (a struct with any field starting at 0xB8)
params = askString("Find Struct", "Enter search criteria")
params = params.split(';')
monitor.initialize(len(params))
candidates = list(DT.allStructures)
def showResults():
executor = Executor()
tbl = createTableChooserDialog("Matching Structs", executor)
tbl.addCustomColumn(StructNameColumn())
tbl.addCustomColumn(StructLengthColumn())
#printf("show %d results\n", len(candidates))
for res in candidates:
#printf("%s\n", res.displayName)
tbl.add(StructListResult(res))
tbl.show()
tbl.setMessage("%d results" % len(candidates))
def removeResult(struc):
candidates.remove(struc)
#print("remove", struc.name, "#res", len(candidates))
def checkComponent(struc, comp, offset, typ):
# return True if match, False if not.
# does component match given offset/type?
if comp.offset != offset: return False
if typ is None: return True # match any type at this offset
# if this is a pointer, walk the dataType chain
# to reach the base type
tp = typ
dt = comp.dataType
while tp.startswith('*'):
if (not hasattr(dt, 'dataType')) or dt.dataType is None:
#printf("[X] %s.%s @%X type is %s\n", struc.name,
# comp.fieldName, offset, str(getattr(dt, 'dataType')))
return False
dt = dt.dataType
tp = tp[1:]
# check the name
# remove spaces for simplicity
tp = tp.replace(' ', '')
nm = dt.name.replace(' ', '')
if tp.isnumeric():
#printf("[%s] %s.%s @%X size is %d\n",
# "O" if dt.length == int(tp) else "X",
# struc.name, comp.fieldName, offset, dt.length)
if dt.length == int(tp):
return True
else:
#printf("[%s] %s.%s @%X type is %d\n",
# "O" if nm == tp else "X",
# struc.name, comp.fieldName, offset, dt.length)
if nm == tp:
return True
#comp.dataType.name, numElements, elementLength, length, dataType
#comp.fieldName, comment, endOffset, bitFieldComponent, dataType, length, offset, ordinal
return False
def evaluateParam(param):
param = param.split('=')
offset = int(param[0], 16)
if len(param) < 2:
# no type given - find any struct which has a field
# beginning at this offset.
typ = None
else:
# user specified a type for the field
typ = param[1]
#printf("Evaluate '%s', #res=%d\n", param, len(candidates))
remove = []
for struc in candidates:
monitor.checkCanceled()
#monitor.incrementProgress(1)
#monitor.setMessage("Checking %s" % struc.displayName)
#print("check", struc.displayName)
match = False
for comp in struc.components:
if checkComponent(struc, comp, offset, typ):
match = True
break
if not match: remove.append(struc)
for struc in remove: removeResult(struc)
#printf("Evaluated '%s', #res=%d\n", param, len(candidates))
for param in params:
monitor.checkCanceled()
monitor.incrementProgress(1)
monitor.setMessage("Checking %s" % param)
evaluateParam(param)
if len(candidates) == 0: break
#popup("Found %d matches (see console)" % len(candidates))
showResults()
run()
|
expected_output = {
"interface": {
"GigabitEthernet1/0/1": {
"out": {
"mcast_pkts": 188396,
"bcast_pkts": 0,
"ucast_pkts": 124435064,
"name": "GigabitEthernet1/0/1",
"octets": 24884341205,
},
"in": {
"mcast_pkts": 214513,
"bcast_pkts": 0,
"ucast_pkts": 15716712,
"name": "GigabitEthernet1/0/1",
"octets": 3161931167,
},
}
}
}
|
# %% [1071. Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/)
# 問題:str1とstr2を分割する文字列を返せ(存在しないときは空文字列)。s = t * nのときtはsを分割する
# 解法:math.gcdを用いる
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
n = math.gcd(n1 := len(str1), n2 := len(str2))
s = str1[:n]
return s * (s * (n1 // n) == str1 and s * (n2 // n) == str2)
|
def doador():
nome = str(input('Qual o seu nome senhor(a)?'))
print('Meu nome é {}'.format(nome))
idade = int(input('Qual a sua idade?'))
print('Minha idade é {}'.format(idade))
peso = float(input('Digite o seu peso'))
print('Meu peso é {}'.format(peso))
if idade >= 18 and peso >= 50:
print('Muito bem senhor(a) {}, você pode doar sangue.'.format(nome))
else:
print('Desculpe mas você não pode doar sangue, obrigado pela colaboração!')
doador()
|
DOMAIN = "echonet_lite"
MANUFACTURER = {
0x0B: "Panasonic",
0x69: "Toshiba",
0x2f: "AIPHONE",
}
CONF_STATE_CLASS = "state_class"
|
"""
Container for Configuration related errors.
"""
class ConfigError(Exception):
""" Generic exception raised by
configuration errors.
"""
def __init__(self, expr, msg):
self.expression = expr
self.message = msg
def __str__(self):
return self.message
|
files = ['avalon_mm_bfm_pkg.vhd',
'avalon_st_bfm_pkg.vhd',
'axilite_bfm_pkg.vhd',
'axistream_bfm_pkg.vhd',
'gmii_bfm_pkg.vhd',
'gpio_bfm_pkg.vhd',
'i2c_bfm_pkg.vhd',
'rgmii_bfm_pkg.vhd',
'sbi_bfm_pkg.vhd',
'spi_bfm_pkg.vhd',
'uart_bfm_pkg.vhd',
]
|
#pragma repy restrictions.loose
# create a junk.py file
myfo = open("junk.py","w")
print >> myfo, "print 'Hello world'"
myfo.close()
removefile("junk.py") # should be removed...
|
"""
How to find GCD (Greater Common Divisor) of two numbers using recursion?
Based on Euclidean Algorithm
"""
def GCD(n1, n2):
assert n1 != 0 and n2 != 0 and int(n1) == n1 and int(n2) == n2, "error"
if n1 < 0:
n1 *= -1
if n2 < 0:
n2 *= -1
if n1 % n2 == 0:
return n2
return GCD(n2, n1 % n2)
def GCD2(n1, n2):
if n1 == n2:
return n1
elif n1 > n2:
return GCD2(n1 - n2, n2)
else:
return GCD2(n1, n2 - n1)
print(GCD(48, 18))
print(GCD2(48, 18))
|
a = ['a','b','c']
b = ['1','2','3','4','5','6']
c = list(zip(*b))
print(a)
print(c)
for d,e in zip(c,a):
print(d)
print(e)
|
#!/usr/bin/env python
# coding: utf-8
# # Mendel's First Law
# ## Problem
#
# Probability is the mathematical study of randomly occurring phenomena. We will model such a phenomenon with a random variable, which is simply a variable that can take a number of different distinct outcomes depending on the result of an underlying random process.
#
# For example, say that we have a bag containing 3 red balls and 2 blue balls. If we let **X** represent the random variable corresponding to the color of a drawn ball, then the probability of each of the two outcomes is given by **Pr(X = red) = 35** and **Pr(X = blue) = 25**.
#
# Random variables can be combined to yield new random variables. Returning to the ball example, let Y model the color of a second ball drawn from the bag (without replacing the first ball). The probability of Y being red depends on whether the first ball was red or blue. To represent all outcomes of X and Y, we therefore use a probability tree diagram. This branching diagram represents all possible individual probabilities for X and Y, with outcomes at the endpoints ("leaves") of the tree. The probability of any outcome is given by the product of probabilities along the path from the beginning of the tree; see Figure 2 for an illustrative example.
#
# An event is simply a collection of outcomes. Because outcomes are distinct, the probability of an event can be written as the sum of the probabilities of its constituent outcomes. For our colored ball example, let **A** be the event **"Y is blue."** **Pr(A)** is equal to the sum of the probabilities of two different outcomes:
# >**Pr(X = blue and Y = blue) + Pr(X = red and Y = blue)**, or **310 + 110 = 25**.
#
# > **Given:** Three positive integers **k**, **m**, and **n**, representing a population containing **k + m + n** organisms: **k** individuals are homozygous dominant for a factor, **m** are heterozygous, and **n** are homozygous recessive.
#
# > **Return:** The probability that two randomly selected mating organisms will produce an individual possessing a dominant allele (and thus displaying the dominant phenotype). Assume that any two organisms can mate.
# In[ ]:
def mendel(x, y, z):
#calculate the probability of recessive traits only
total = x + y + z
twoRecess = (z/total)*((z-1)/(total-1))
twoHetero = (y/total)*((y-1)/(total-1))
heteroRecess = (z/total)*(y/(total-1)) + (y/total)*(z/(total-1))
recessProb = twoRecess + twoHetero*1/4 + heteroRecess*1/2
print(1-recessProb) # take the complement
# In[ ]:
with open ("rosalind_iprb.txt", "r") as file: #replace filename with your filename
line = file.readline().split()
x, y, z = [int(n) for n in line]
print(x, y, z)
file.close()
print(mendel(x, y, z))
|
# examples on set and dict comprehensions
# EXAMPLES OF SET COMPREHENSION
# making a set comprehension is actually really easy
# instead of a list, we'll just use a set notation as follows:
my_list = [char for char in 'hello']
my_set = {char for char in 'hello'}
print(my_list)
print(my_set)
my_list1 = [num for num in range(10)]
my_set1 = {num for num in range(10)}
print(my_list1)
print(my_set1)
my_list2 = [num ** 2 for num in range(50) if num % 2 == 0]
my_set2 = {num ** 2 for num in range(50) if num % 2 == 0}
print(my_list2)
print(my_set2)
# EXAMPLE OF DICT COMPREHENSIONS
# Example 1:
simple_dict = {'a': 1, 'b': 2}
my_dict = {k: v ** 2 for k, v in simple_dict.items()}
# for each of the key:value pair in the simple_dict, we raise the value by the power of 2 and add it to my_dict
print(my_dict)
# Example 2: if we only want the even values from simple_dict to be in my_dict, then, we have the following dict comprehension
my_dict2 = {k: v ** 2 for k, v in simple_dict.items() if v % 2 == 0}
print(my_dict2)
# Example 3: If we want to make a dict from a list where the list item is the key and item*2 is the value in the dict, using dict comprehension:
my_dict3 = {item: item * 2 for item in [1, 2, 3]}
print(my_dict3)
'''
Output:
------
['h', 'e', 'l', 'l', 'o']
{'o', 'h', 'l', 'e'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304]
{0, 256, 1024, 2304, 4, 900, 1156, 16, 144, 400, 784, 1296, 1936, 36, 676, 1444, 64, 576, 1600, 196, 324, 2116, 100, 484, 1764}
{'a': 1, 'b': 4}
{'b': 4}
{1: 2, 2: 4, 3: 6}
'''
|
class binding_(object):
"""Register key bindings with the object binding."""
def __init__(self):
self.bindings = {}
def __call__(self, key):
def register(func):
def decorator(model, nav, io, *args, **kwargs):
res = func(model, nav, io, *args, **kwargs)
return res
self.bindings[key] = decorator
return decorator
return register
# this object works as a decorator for registering key bindings
binding = binding_()
|
class HtmlReportException(Exception):
pass
class HtmlReport:
def __init__(self):
self.path = None
self.file = None
self.header = None
self.start_time = None
self.is_initialized = False
def __del__(self):
if self.is_initialized and self.file:
self.write('</body></html>\n')
self.file.close()
def set_path(self, path):
self.path = path
def initialize_file(self, path):
if self.is_initialized:
self.file = open(path, 'w', encoding='utf-8', buffering=1)
def write(self, string):
if self.is_initialized:
if not self.file:
raise HtmlReportException('HTML report is not initialized')
self.file.write(string.encode('utf-8').decode('utf-8', errors='ignore'))
|
SIZE = 9
INPUT_LEVEL_DIR = "File.txt"
INPUT_CONSTRAINTS_DIR = "Constraints.txt"
OUTPUT_SOLUTION_DIR = "Solution.txt"
ASSIGNED_VALUE_NUM = 0
|
class Mother:
@staticmethod
def take_screenshot():
print('I can make a screenshot')
@staticmethod
def receive_email():
print('I can receive email')
class Father:
@staticmethod
def drive_car():
print('I can drive a car ')
@staticmethod
def play_music():
print(f'Play music while driving')
class Grandfather:
@staticmethod
def smoke():
print('I can drive a car ')
@staticmethod
def sing():
print(f'Play music while driving')
class Kid(Mother, Father, Grandfather):
def behave(self):
self.take_screenshot()
self.drive_car()
self.smoke()
kid = Kid()
kid.behave()
kid.drive_car()
print(Kid.mro())
|
def get_tokens():
return _tokens
def get_inverse_tokens():
flipped = dict()
for key in _tokens:
flipped[_tokens[key]] = key
return flipped
_tokens = dict([
(b'\x01', '>DMS'),
(b'\x02', '>Dec'),
(b'\x03', '>Frac'),
(b'\x04', '→'),
(b'\x05', 'BoxPlot'),
(b'\x06', '['),
(b'\x07', ']'),
(b'\x08', '{'),
(b'\x09', '}'),
# I'm not sure what this operator is, so for now I'm not supporting it.
# As-is, this may cause problems with building 8Xp files.
# (b'\x0A', 'r'),
(b'\x0B', '°'),
(b'\x0C', '^-1'),
(b'\x0D', '^2'),
(b'\x0E', '^T'),
(b'\x0F', '^3'),
(b'\x10', '('),
(b'\x11', ')'),
(b'\x12', 'round('),
(b'\x13', 'pxl-Test('),
(b'\x14', 'augment('),
(b'\x15', 'rowSwap('),
(b'\x16', 'row+('),
(b'\x17', '*row('),
(b'\x18', '*row+('),
(b'\x19', 'max('),
(b'\x1A', 'min('),
(b'\x1B', 'R>Pr('),
(b'\x1C', 'R>P[theta]('),
(b'\x1D', 'P>Rx('),
(b'\x1E', 'P>Ry('),
(b'\x1F', 'median('),
(b'\x20', 'randM('),
(b'\x21', 'mean('),
(b'\x22', 'solve('),
(b'\x23', 'seq('),
(b'\x24', 'fnInt('),
(b'\x25', 'nDeriv('),
# Unknown function
# (b'\x26', ''),
(b'\x27', 'fMin('),
(b'\x28', 'fMax('),
(b'\x29', ' '),
(b'\x2A', '"'),
(b'\x2B', ','),
(b'\x2C', 'imaginary'),
(b'\x2D', '!'),
(b'\x2E', 'CubicReg '),
(b'\x2F', 'QuartReg '),
(b'\x3A', '.'),
# Alternate notation of E
(b'\x3B', '10^'),
(b'\x3C', ' or '),
(b'\x3D', ' xor '),
(b'\x3E', ':'),
(b'\x3F', '\n'),
(b'\x40', ' and '),
(b'\x41', 'A'),
(b'\x42', 'B'),
(b'\x43', 'C'),
(b'\x44', 'D'),
(b'\x45', 'E'),
(b'\x46', 'F'),
(b'\x47', 'G'),
(b'\x48', 'H'),
(b'\x49', 'I'),
(b'\x4A', 'J'),
(b'\x4B', 'K'),
(b'\x4C', 'L'),
(b'\x4D', 'M'),
(b'\x4E', 'N'),
(b'\x4F', 'O'),
(b'\x50', 'P'),
(b'\x51', 'Q'),
(b'\x52', 'R'),
(b'\x53', 'S'),
(b'\x54', 'T'),
(b'\x55', 'U'),
(b'\x56', 'V'),
(b'\x57', 'W'),
(b'\x58', 'X'),
(b'\x59', 'Y'),
(b'\x5A', 'Z'),
(b'\x30', '0'),
(b'\x31', '1'),
(b'\x32', '2'),
(b'\x33', '3'),
(b'\x34', '4'),
(b'\x35', '5'),
(b'\x36', '6'),
(b'\x37', '7'),
(b'\x38', '8'),
(b'\x39', '9'),
(b'\x5B', '[theta]'),
# System variables (incomplete: TODO)
(b'\x5C\x00', '[A]'),
(b'\x5C\x01', '[B]'),
(b'\x5C\x02', '[C]'),
(b'\x5C\x03', '[D]'),
(b'\x5C\x04', '[E]'),
(b'\x5C\x05', '[F]'),
(b'\x5C\x06', '[G]'),
(b'\x5C\x07', '[H]'),
(b'\x5C\x08', '[I]'),
(b'\x5C\x09', '[J]'),
(b'\x5D\x00', 'l1'),
(b'\x5D\x01', 'l2'),
(b'\x5D\x02', 'l3'),
(b'\x5D\x03', 'l4'),
(b'\x5D\x04', 'l5'),
(b'\x5D\x05', 'l6'),
(b'\x5D\x06', 'l7'),
(b'\x5D\x07', 'l8'),
(b'\x5D\x08', 'l0'),
(b'\x5E\x10', 'y1'),
(b'\x5E\x11', 'y2'),
(b'\x5E\x12', 'y3'),
(b'\x5E\x13', 'y4'),
(b'\x5E\x14', 'y5'),
(b'\x5E\x15', 'y6'),
(b'\x5E\x16', 'y7'),
(b'\x5E\x17', 'y8'),
(b'\x5E\x18', 'y9'),
(b'\x5E\x19', 'y0'),
(b'\x5E\x40', 'r_1'),
(b'\x5E\x41', 'r_2'),
(b'\x5E\x42', 'r_3'),
(b'\x5E\x43', 'r_4'),
(b'\x5E\x44', 'r_5'),
(b'\x5E\x45', 'r_6'),
# Not currently supported. Will cause problems with re-compiling
#(b'\x5E\x80', 'u'),
#(b'\x5E\x81', 'v'),
(b'\x5E\x20', 'x1t'),
(b'\x5E\x21', 'y1t'),
(b'\x5E\x22', 'x2t'),
(b'\x5E\x23', 'y2t'),
(b'\x5E\x24', 'x3t'),
(b'\x5E\x25', 'y3t'),
(b'\x5E\x26', 'x4t'),
(b'\x5E\x27', 'y4t'),
(b'\x5E\x28', 'x5t'),
(b'\x5E\x29', 'y5t'),
(b'\x5E\x2A', 'x6t'),
(b'\x5E\x2B', 'y6t'),
# Unknown
#(b'\x5E\x00', '')
(b'\x5F', 'prgm'),
(b'\x60\x00', 'Pic1'),
(b'\x60\x01', 'Pic2'),
(b'\x60\x02', 'Pic3'),
(b'\x60\x03', 'Pic4'),
(b'\x60\x04', 'Pic5'),
(b'\x60\x05', 'Pic6'),
(b'\x60\x06', 'Pic7'),
(b'\x60\x07', 'Pic8'),
(b'\x60\x08', 'Pic9'),
(b'\x60\x09', 'Pic0'),
(b'\x61\x00', 'GDB1'),
(b'\x61\x01', 'GDB2'),
(b'\x61\x02', 'GDB3'),
(b'\x61\x03', 'GDB4'),
(b'\x61\x04', 'GDB5'),
(b'\x61\x05', 'GDB6'),
(b'\x61\x06', 'GDB7'),
(b'\x61\x07', 'GDB8'),
(b'\x61\x08', 'GDB9'),
(b'\x61\x09', 'GDB0'),
# Unknown
#(b'\x62\x00', ''),
(b'\x62\x01', 'RegEq'),
# Unsupported for now, will break parsing
#(b'\x62\x02', 'n'),
(b'\x62\x03', '[x-bar]'),
(b'\x62\x04', '[Summ x]'),
(b'\x62\x05', '[Summ x^2]'),
(b'\x62\x06', 'Sx'),
(b'\x62\x07', '[sigma]x'),
(b'\x62\x08', 'minX'),
(b'\x62\x09', 'maxX'),
(b'\x62\x0A', 'minY'),
(b'\x62\x0B', 'maxY'),
(b'\x62\x0C', '[y-bar]'),
(b'\x62\x0D', '[Summ y]'),
(b'\x62\x0E', '[Summ y^2]'),
(b'\x62\x0F', 'Sy'),
(b'\x62\x10', '[sigma]y'),
(b'\x62\x11', '[Summ xy]'),
# Unsupported as-is, will break re-compiling
#(b'\x62\x12', 'r'),
(b'\x62\x13', 'Med'),
(b'\x62\x14', 'Q1'),
(b'\x62\x15', 'Q3'),
# Unsupported as-is, will break re-compiling
#(b'\x62\x16', 'a'),
#(b'\x62\x17', 'b'),
#(b'\x62\x18', 'c'),
#(b'\x62\x19', 'd'),
#(b'\x62\x1A', 'e'),
(b'\x62\x1B', 'x1'),
(b'\x62\x1C', 'x2'),
(b'\x62\x1D', 'x3'),
(b'\x62\x1E', 'y1'),
(b'\x62\x1F', 'y2'),
(b'\x62\x20', 'y3'),
# Unsupported as-is, will break re-compiling
#(b'\x62\x21', 'n'),
#(b'\x62\x22', 'p'),
#(b'\x62\x23', 'z'),
#(b'\x62\x24', 't'),
(b'\x62\x25', '[chi]2'),
(b'\x62\x26', '[fin]'),
(b'\x62\x27', 'df'),
(b'\x62\x28', '[p-hat]'),
(b'\x62\x29', '[p-hat]1'),
(b'\x62\x2A', '[p-hat]2'),
(b'\x62\x2B', '[x-bar]1'),
(b'\x62\x2C', 'Sx1'),
(b'\x62\x2D', 'n_1'),
(b'\x62\x2E', '[x-bar]2'),
(b'\x62\x2F', 'Sx2'),
(b'\x62\x30', 'n_2'),
(b'\x62\x31', 'Sxp'),
(b'\x62\x32', 'lower'),
(b'\x62\x33', 'upper'),
# Unsupported as-is, will break re-compiling
#(b'\x62\x34', 's'),
(b'\x62\x35', 'r2'),
(b'\x62\x36', 'R2'),
# This may be a duplicate of the df above
#(b'\x62\x37', 'df'),
(b'\x62\x38', 'SS'),
(b'\x62\x39', 'MS'),
# More potential duplicates
#(b'\x62\x3A', 'df'),
#(b'\x62\x3B', 'SS'),
#(b'\x62\x3C', 'MS'),
(b'\x63\x00', 'ZXscl'),
(b'\x63\x01', 'ZYscl'),
(b'\x63\x02', 'Xscl'),
(b'\x63\x03', 'Yscl'),
(b'\x63\x04', 'U_nStart'),
(b'\x63\x05', 'V_nStart'),
(b'\x63\x06', 'U_(n-1)'),
(b'\x63\x07', 'V_(n-1)'),
# \x63\xx values are not complete
(b'\x64', 'Radian'),
(b'\x65', 'Degree'),
(b'\x66', 'Normal'),
(b'\x67', 'Sci'),
(b'\x68', 'Eng'),
(b'\x69', 'Float'),
(b'\x6A', '='),
(b'\x6B', '<'),
(b'\x6C', '>'),
(b'\x6D', '<='),
(b'\x6E', '>='),
(b'\x6F', '!='),
(b'\x70', '+'),
(b'\x71', '–'),
(b'\x72', 'Ans'),
(b'\x73', 'Fix '),
(b'\x74', 'Horiz'),
(b'\x75', 'Full'),
(b'\x76', 'Func'),
(b'\x77', 'Param'),
(b'\x78', 'Polar'),
(b'\x79', 'Seq'),
(b'\x7A', 'IndpntAuto'),
(b'\x7B', 'IndpntAsk'),
(b'\x7C', 'DependAuto'),
(b'\x7D', 'DependAsk'),
# 73 ** (Graph Options)
(b'\x7E\x00', 'Sequential'),
(b'\x7E\x01', 'Simul'),
(b'\x7E\x02', 'PolarGC'),
(b'\x7E\x03', 'RectGC'),
(b'\x7E\x04', 'CoordOn'),
(b'\x7E\x05', 'CoordOff'),
(b'\x7E\x06', 'Connected'),
(b'\x7E\x07', 'Dot'),
(b'\x7E\x08', 'AxesOn'),
(b'\x7E\x09', 'AxesOff'),
(b'\x7E\x0A', 'GridOn'),
(b'\x7E\x0B', 'GridOff'),
(b'\x7E\x0C', 'LabelOn'),
(b'\x7E\x0D', 'LabelOff'),
(b'\x7E\x0E', 'Web'),
(b'\x7E\x0F', 'Time'),
(b'\x7E\x10', 'uvAxes'),
(b'\x7E\x11', 'vwAxes'),
(b'\x7E\x12', 'uwAxes'),
# End of 7E Options
(b'\x7F', '[box]'),
(b'\x80', '[cross]'),
(b'\x81', '[dot]'),
(b'\x82', '*'),
(b'\x83', '/'),
(b'\x84', 'Trace'),
(b'\x85', 'ClrDraw'),
(b'\x86', 'ZStandard'),
(b'\x87', 'ZTrig'),
(b'\x88', 'ZBox'),
(b'\x89', 'Zoom_In'),
(b'\x8A', 'Zoom_Out'),
(b'\x8B', 'ZSquare'),
(b'\x8C', 'ZInteger'),
(b'\x8D', 'ZPrevious'),
(b'\x8E', 'ZDecimal'),
(b'\x8F', 'ZoomStat'),
(b'\x90', 'ZoomRcl'),
(b'\x91', 'PrintScreen'),
(b'\x92', 'ZoomSto'),
(b'\x93', 'Text('),
(b'\x94', ' nPr '),
(b'\x95', ' nCr '),
(b'\x96', 'FnOn '),
(b'\x97', 'FnOff '),
(b'\x98', 'StorePic '),
(b'\x99', 'RecallPic '),
(b'\x9A', 'StoreGDB '),
(b'\x9B', 'RecallGDB '),
(b'\x9C', 'Line('),
(b'\x9D', 'Vertical '),
(b'\x9E', 'Pt-On('),
(b'\x9F', 'Pt-Off('),
(b'\xA0', 'Pt-Change( '),
(b'\xA1', 'Pxl-On( '),
(b'\xA2', 'Pxl-Off( '),
(b'\xA3', 'Pxl-Change( '),
(b'\xA4', 'Shade('),
(b'\xA5', 'Circle('),
(b'\xA6', 'Horizontal '),
(b'\xA7', 'Tangent('),
(b'\xA8', 'DrawInv '),
(b'\xA9', 'DrawF '),
# System variables (TODO)
(b'\xAA\x00', 'Str1'),
(b'\xAA\x01', 'Str2'),
(b'\xAA\x02', 'Str3'),
(b'\xAA\x03', 'Str4'),
(b'\xAA\x04', 'Str5'),
(b'\xAA\x05', 'Str6'),
(b'\xAA\x06', 'Str7'),
(b'\xAA\x07', 'Str8'),
(b'\xAA\x08', 'Str9'),
(b'\xAA\x09', 'Str0'),
(b'\xAB', 'rand'),
(b'\xAC', '[pi]'),
(b'\xAD', 'getKey'),
(b'\xAE', '\''),
(b'\xAF', '?'),
(b'\xB0', '-'),
(b'\xB1', 'int('),
(b'\xB2', 'abs('),
(b'\xB3', 'det('),
(b'\xB4', 'identity('),
(b'\xB5', 'dim('),
(b'\xB6', 'sum('),
(b'\xB7', 'prod('),
(b'\xB8', 'not('),
(b'\xB9', 'iPart('),
(b'\xBA', 'fPart('),
# BB tokens (two-byte), Incomplete TODO
(b'\xBB\x00', 'npv('),
(b'\xBB\x01', 'irr('),
(b'\xBB\x02', 'bal('),
(b'\xBB\x03', 'SummPrn('),
(b'\xBB\x04', 'SummInt('),
(b'\xBB\x05', '>Nom('),
(b'\xBB\x06', '>Eff('),
(b'\xBB\x07', 'dbd('),
(b'\xBB\x08', 'Icm('),
(b'\xBB\x09', 'gcd('),
(b'\xBB\x0A', 'randInt('),
(b'\xBB\x0B', 'randBin('),
(b'\xBB\x0C', 'sub('),
(b'\xBB\x0D', 'stdDev('),
(b'\xBB\x0E', 'variance('),
(b'\xBB\x0F', 'inString('),
(b'\xBB\xB0', 'a'),
(b'\xBB\xB1', 'b'),
(b'\xBB\xB2', 'c'),
(b'\xBB\xB3', 'd'),
(b'\xBB\xB4', 'e'),
(b'\xBB\xB5', 'f'),
(b'\xBB\xB6', 'g'),
(b'\xBB\xB7', 'h'),
(b'\xBB\xB8', 'i'),
(b'\xBB\xB9', 'j'),
(b'\xBB\xBA', 'k'),
(b'\xBB\xBC', 'l'),
(b'\xBB\xBD', 'm'),
(b'\xBB\xBE', 'n'),
(b'\xBB\xBF', 'o'),
(b'\xBB\xC0', 'p'),
(b'\xBB\xC1', 'q'),
(b'\xBB\xC2', 'r'),
(b'\xBB\xC3', 's'),
(b'\xBB\xC4', 't'),
(b'\xBB\xC5', 'u'),
(b'\xBB\xC6', 'v'),
(b'\xBB\xC7', 'w'),
(b'\xBB\xC8', 'x'),
(b'\xBB\xC9', 'y'),
(b'\xBB\xCA', 'z'),
# end of xBB
(b'\xBC', 'sqrt('),
(b'\xBD', 'cubrt('),
(b'\xBE', 'ln ('),
(b'\xBF', 'e^('),
(b'\xC0', 'log('),
(b'\xC1', '10^('),
(b'\xC2', 'sin('),
(b'\xC3', 'sin^-1('),
(b'\xC4', 'cos('),
(b'\xC5', 'cos^-1('),
(b'\xC6', 'tan('),
(b'\xC7', 'tan^-1('),
(b'\xC8', 'sinh('),
(b'\xC9', 'sinh^-1('),
(b'\xCA', 'cosh('),
(b'\xCB', 'cosh^-1('),
(b'\xCC', 'tanh('),
(b'\xCD', 'tanh^-1('),
(b'\xCE', 'If '),
(b'\xCF', 'Then'),
(b'\xD0', 'Else'),
(b'\xD1', 'While '),
(b'\xD2', 'Repeat '),
(b'\xD3', 'For '),
(b'\xD4', 'End'),
(b'\xD5', 'Return'),
(b'\xD6', 'Lbl '),
(b'\xD7', 'Goto '),
(b'\xD8', 'Pause '),
(b'\xD9', 'Stop'),
(b'\xDA', 'IS>('),
(b'\xDB', 'DS>('),
(b'\xDC', 'Input '),
(b'\xDD', 'Prompt '),
(b'\xDE', 'Disp '),
(b'\xDF', 'DispGraph'),
(b'\xE0', 'Output('),
(b'\xE1', 'ClrHome'),
(b'\xE2', 'Fill('),
(b'\xE3', 'SortA('),
(b'\xE4', 'SortD('),
(b'\xE5', 'DispTable'),
(b'\xE6', 'Menu('),
(b'\xE7', 'Send('),
(b'\xE8', 'Get('),
(b'\xE9', 'PlotsOn '),
(b'\xEA', 'PlotsOff '),
# No idea what this operator is, so we're not supporting it until I
# know how it fits in things so encoding don't break with it
#(b'\xEB', 'L'),
(b'\xEC', 'Plot1('),
(b'\xED', 'Plot2('),
(b'\xEE', 'Plot3('),
# Unknown
#(b'\xEF', ''),
(b'\xF0', '^'),
(b'\xF1', '[xth root]'),
(b'\xF2', '1-Var Stats '),
(b'\xF3', '2-Var Stats '),
(b'\xF4', 'LinReg(a+bx) '),
(b'\xF5', 'ExpReg '),
(b'\xF6', 'LnReg '),
(b'\xF7', 'PwrReg '),
(b'\xF8', 'Med-Med '),
(b'\xF9', 'QuadReg '),
(b'\xFA', 'ClrList '),
(b'\xFB', 'ClrTable'),
(b'\xFC', 'Histogram'),
(b'\xFD', 'xyLine'),
(b'\xFE', 'Scatter'),
(b'\xFF', 'LinReg(ax+b) '),
])
|
class NewsModule:
def __init__(self):
pass
def update(self):
pass
|
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_Virtual_data_setup.ipynb (unless otherwise specified).
__all__ = ['Get_sub_watersheds']
# Cell
def Get_sub_watersheds(watershed, order_max, order_min = 4):
'''Obtains the sub-watersheds a different orders starting from the order_max and
ending on the order_min, there is no return, it only updates the watershed.Table'''
orders = np.arange(order_max, order_min, -1).tolist()
for Prun in orders:
#Finds the connections points
Ho = Prun
watershed.Table['prun_'+str(Ho)] = 0
idx = watershed.Table.loc[watershed.Table['h_order']>=Ho].index
for i in idx:
size = watershed.Table.loc[(watershed.Table['dest'] == i) & (watershed.Table['h_order'] >= Ho-1)]
if size.shape[0] >= 2:
watershed.Table.loc[size.index, 'prun_'+str(Ho)] = 1
#Finds all the links that belong to a pruning level
idx = watershed.Table.loc[watershed.Table['prun_'+str(Ho)] == 1].sort_values(by = ['Acum'], ascending = False).index
cont = 2
for i in idx:
#Finds the watershed upstream
t = am.hlmModel(linkid=i)
idx_t = watershed.Table.index.intersection(t.Table.index)
#Assign that pruning level to the sub-watershed
watershed.Table.loc[idx_t, 'prun_'+str(Ho)] = cont
#Go to next pruning level
cont += 1
print('Prun %d done' % Prun)
|
class Slot:
def __init__(self, name="", description = ""):
self.type = type # categorical, verbatim
self.name = name
self.description = description
self.values = ["not-present"]
self.values_descriptions = ["Ignore me, I'm used for programming."]
def len (self):
return len(self.values)
def add_value (self, value, value_description=""):
if value not in self.values:
self.values.append(value)
self.values_descriptions.append(value_description)
def __repr__(self):
str = "Slot [{}]:\n".format(self.name)
str+= "\tDescription: {}\n".format(self.description)
if self.type is not "verbatim":
str+= "\tValues: CATEGORICAL, {} values\n".format(len(self.values_descriptions))
for i in range (len(self.values)):
str+= "\t\t{}\t{}\n".format(self.values[i], self.values_descriptions[i])
else:
str+= "\tValues: VERBATIM\n"
return str
class Slots: # this is for one MEI only
def __init__(self):
self.slots = []
def add_slot_value_pair(self, slot_name, slot_value, slot_description = ""):
found = False
for slot in self.slots:
if slot.name == slot_name:
found = True
break
if not found:
self.slots.append(Slot(slot_name, slot_description))
for slot in self.slots:
if slot.name == slot_name:
slot.add_value(slot_value)
def get_slot_object(self, slot_name):
for slot in self.slots:
if slot.name == slot_name:
return slot
raise Exception("Slot not found: "+slot_name)
def __repr__(self):
str = "Slots object contains {} slots:\n".format(len(self.slots))
str+= "_"*60+"\n"
for slot in self.slots:
str+=slot.__repr__()
return str
|
# Check if removing an edge of a binary tree can divide
# the tree in two equal halves
# Count the number of nodes, say n. Then traverse the tree
# in bottom up manner and check if n - s = s
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count(root):
if not root:
return 0
return count(root.left) + count(root.right) + 1
def check_util(root, n):
if root == None:
return False
# Check for root
if count(root) == n - count(root):
return True
# Check for all the other nodes
return check_util(root.left, n) or check_util(root.right, n)
def check(root):
n = count(rot)
return check_util(root, n)
|
"""
Задача:
Дано три отсортированных массива чисел.
Они могут быть как одинаковой, так и разной длинны.
Во всех массивах есть минимум одно общее число.
Найти:
Любое общее число которое есть во всех трех массивах
Пример:
на вход:
[1, 2, 3, 4, 5, 100],
[6, 7, 8, 9, 100],
[10, 20, 21, 22, 23, 24, 100],
на выход: 100
"""
def solution(arr1: list, arr2: list, arr3: list) -> int:
"""
Работаем с указателями в рамках каждого массива
:param arr1:
:param arr2:
:param arr3:
:return:
"""
pointer_arr1 = 0
pointer_arr2 = 0
pointer_arr3 = 0
if len(arr1) == 0 or len(arr2) == 0 or len(arr3) == 0:
return 0
while True:
if arr1[pointer_arr1] == arr2[pointer_arr2] and arr2[pointer_arr2] == arr3[pointer_arr3]:
return arr1[pointer_arr1]
if arr1[pointer_arr1] > arr2[pointer_arr2]:
pointer_arr2 += 1
elif arr2[pointer_arr2] > arr3[pointer_arr3]:
pointer_arr3 += 1
elif arr3[pointer_arr3] > arr1[pointer_arr1]:
pointer_arr1 += 1
|
class Cipher:
def __init__(self, codestring):
# Hints:
# Does the capitalization of the words or letter matter here?
# Is hello the same as Hello or even hElLo in terms of definition? Yes
# Maybe we should convert everything to uppercase
# Add your code here
self.alphabet = None # Add alphabet here by replacing None with the answer
self.codestring = ""
for letter in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
if None not in codestring: # Replace None with answer
self.codestring += None # Replace None with answer
self.codestring = codestring + self.codestring
self.code = {}
for (a,b) in zip(self.codestring.upper(), None): # Replace None & "None2" with the answers
self.code["None2"] = None
self.inverse = {}
for (a,b) in zip(None, self.alphabet):
self.inverse[None] = "None2" # Replace None & "None2" with the answers
def encode(self, plaintext):
# Add your code here
encoded_string = ""
for c in None: #Replace None with the answer
if c.isalpha():
encoded_string += None #Replace None with the answer
else:
encoded_string += None
return "".join(encoded_string)
def decode(self, ciphertext):
# Add your code here
decoded_string = ""
for c in None: #Replace None with the answer
if None: #Replace None with the answer
decoded_string += self.code[None] #Replace None with the answer
else:
None #Replace None with the answer (it's 1 line of code)
return "".join(decoded_string)
|
# coding: utf-8
#########################################################################
# 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> #
# author yeeku.H.lee kongyeeku@163.com #
# #
# version 1.0 #
# #
# Copyright (C), 2001-2018, yeeku.H.Lee #
# #
# This program is protected by copyright laws. #
# #
# Program Name: #
# #
# <br>Date: #
#########################################################################
user_name = 'Charlie'
user_age = 8
# 同时输出多个变量和字符串
print("读者名:" , user_name, "年龄:", user_age)
# 同时输出多个变量和字符串,指定分隔符
print("读者名:" , user_name, "年龄:", user_age, sep='|')
# 指定end参数,指定输出之后不再换行
print(40, '\t', end="")
print(50, '\t', end="")
print(60, '\t', end="")
f = open("poem.txt", "w") # 打开文件以便写入
print('沧海月明珠有泪', file=f)
print('蓝田日暖玉生烟', file=f)
f.close()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""A wrapper for sys.stdout etc that provides tell() for current position"""
class StdIOWrapper:
def __init__(self, stream):
self.stream = stream
self.pos = 0
self.closed = 0
def __getattr__(self, attrname, default=None):
return getattr(self.stream, attrname, default)
def close(self):
if not self.closed:
self.closed = 1
self.stream.close()
def seek(self, pos, mode=0):
raise ValueError("I/O operation on closed file")
def tell(self):
if self.closed:
raise ValueError("I/O operation on closed file")
return self.pos
def write(self, s):
if self.closed:
raise ValueError("I/O operation on closed file")
self.stream.write(s)
self.pos += len(s)
def writelines(self, lines):
if self.closed:
raise ValueError("I/O operation on closed file")
self.stream.writelines(lines)
self.pos += len("".join(lines))
|
description = 'FRM II FAK40 information (cooling water system)'
group = 'lowlevel'
tango_base = 'tango://ictrlfs.ictrl.frm2:10000/frm2/'
devices = dict(
FAK40_Cap = device('nicos.devices.entangle.AnalogInput',
tangodevice = tango_base +'fak40/CF001',
description = 'The capacity of the cooling water system',
pollinterval = 60,
maxage = 120,
),
FAK40_Press = device('nicos.devices.entangle.AnalogInput',
tangodevice = tango_base +'fak40/CP001',
description = 'The pressure inside the cooling water system',
pollinterval = 60,
maxage = 120,
),
)
|
# Ejercicio 6
# Al realizar una consulta en un registro hemos obtenido una cadena de texto corrupta al revés.
# Al parecer contiene el nombre de un alumno y la nota de un exámen.
# ¿Cómo podríamos formatear la cadena y conseguir una estructura como la siguiente?
# Nombre Apellido ha sacado un Nota de nota.
cadena = "zeréP nauJ,01"
# Completa el ejercicio aquí
cadena_volteada = cadena[::-1]
print((cadena_volteada[3:]), 'a sacado una nota de', (cadena_volteada[:2]))
|
#
# PySNMP MIB module DHCP-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/DHCP-SERVER-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:33:35 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
Integer32, Counter64, iso, Bits, Unsigned32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, Counter32, Gauge32, MibIdentifier, TimeTicks, enterprises, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "iso", "Bits", "Unsigned32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "Counter32", "Gauge32", "MibIdentifier", "TimeTicks", "enterprises", "ModuleIdentity")
RowStatus, TruthValue, TextualConvention, DisplayString, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TextualConvention", "DisplayString", "DateAndTime")
lucent = MibIdentifier((1, 3, 6, 1, 4, 1, 1751))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1))
mibs = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 2))
ipspg = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48))
ipspgServices = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1))
ipspgDHCP = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1))
ipspgDNS = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 2))
ipspgTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2))
dhcpServMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServMib.setLastUpdated('0606220830Z')
if mibBuilder.loadTexts: dhcpServMib.setOrganization('Lucent Technologies')
if mibBuilder.loadTexts: dhcpServMib.setContactInfo(' James Offutt Postal: Lucent Technologies 400 Lapp Road Malvern, PA 19355 USA Tel: +1 610-722-7900 Fax: +1 610-725-8559')
if mibBuilder.loadTexts: dhcpServMib.setDescription('The Vendor Specific MIB module for entities implementing the server side of the Bootstrap Protocol (BOOTP) and the Dynamic Host Configuration protocol (DHCP) for Internet Protocol version 4 (IPv4).')
dhcpServMibTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0))
if mibBuilder.loadTexts: dhcpServMibTraps.setStatus('current')
if mibBuilder.loadTexts: dhcpServMibTraps.setDescription('DHCP Server MIB traps.')
dhcpServMibObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServMibObjects.setStatus('current')
if mibBuilder.loadTexts: dhcpServMibObjects.setDescription('DHCP Server MIB objects are all defined in this branch.')
dhcpServSystem = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServSystem.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystem.setDescription('Group of objects that are related to the overall system.')
dhcpServSubnetCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2))
if mibBuilder.loadTexts: dhcpServSubnetCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServSubnetCounters.setDescription('Group of objects that count various subnet data values')
dhcpServBootpCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3))
if mibBuilder.loadTexts: dhcpServBootpCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCounters.setDescription('Group of objects that count various BOOTP events.')
dhcpServDhcpCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4))
if mibBuilder.loadTexts: dhcpServDhcpCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCounters.setDescription('Group of objects that count various DHCP Statistics.')
dhcpServBootpStatistics = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5))
if mibBuilder.loadTexts: dhcpServBootpStatistics.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatistics.setDescription('Group of objects that measure various BOOTP statistics.')
dhcpServDhcpStatistics = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6))
if mibBuilder.loadTexts: dhcpServDhcpStatistics.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatistics.setDescription('Group of objects that measure various DHCP statistics.')
dhcpServConfiguration = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7))
if mibBuilder.loadTexts: dhcpServConfiguration.setStatus('current')
if mibBuilder.loadTexts: dhcpServConfiguration.setDescription('Objects that contain pre-configured and Dynamic Config. Info.')
dhcpServFailover = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8))
if mibBuilder.loadTexts: dhcpServFailover.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailover.setDescription('Objects that contain partner server info.')
class DhcpServTimeInterval(TextualConvention, Gauge32):
description = 'The number of milli-seconds that has elapsed since some epoch. Systems that cannot measure events to the milli-second resolution SHOULD round this value to the next available resolution that the system supports.'
status = 'current'
dhcpServSystemDescr = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemDescr.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemDescr.setDescription('A textual description of the server. This value should include the full name and version identification of the server. This string MUST contain only printable NVT ASCII characters.')
dhcpServSystemStatus = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("starting", 0), ("running", 1), ("stopping", 2), ("stopped", 3), ("reload", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemStatus.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemStatus.setDescription(' Dhcp System Server Status ')
dhcpServSystemUpTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemUpTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemUpTime.setDescription('If the server has a persistent state (e.g., a process), this value will be the seconds elapsed since it started. For software without persistant state, this value will be zero.')
dhcpServSystemResetTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemResetTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemResetTime.setDescription("If the server has a persistent state (e.g., a process) and supports a `reset' operation (e.g., can be told to re-read configuration files), this value will be the seconds elapsed since the last time the name server was `reset.' For software that does not have persistence or does not support a `reset' operation, this value will be zero.")
dhcpServCountUsedSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountUsedSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountUsedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued at least one lease.')
dhcpServCountUnusedSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountUnusedSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountUnusedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued no leases.')
dhcpServCountFullSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountFullSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountFullSubnets.setDescription('The number subnets managed by the server (i.e. configured), in which the address pools have been exhausted.')
dhcpServBootpCountRequests = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountRequests.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountRequests.setDescription('The number of packets received that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcpServBootpCountInvalids = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountInvalids.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountInvalids.setDescription('The number of packets received that do not contain a Message Type of 1 (BOOTREQUEST) in the first octet or are not valid BOOTP packets (e.g.: too short, invalid field in packet header).')
dhcpServBootpCountReplies = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountReplies.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountReplies.setDescription('The number of packets sent that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcpServBootpCountDroppedUnknownClients = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountDroppedUnknownClients.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountDroppedUnknownClients.setDescription('The number of BOOTP packets dropped due to the server not recognizing or not providing service to the hardware address received in the incoming packet.')
dhcpServBootpCountDroppedNotServingSubnet = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountDroppedNotServingSubnet.setDescription('The number of BOOTP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcpServDhcpCountDiscovers = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDiscovers.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDiscovers.setDescription('The number of DHCPDISCOVER (option 53 with value 1) packets received.')
dhcpServDhcpCountRequests = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountRequests.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountRequests.setDescription('The number of DHCPREQUEST (option 53 with value 3) packets received.')
dhcpServDhcpCountReleases = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountReleases.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountReleases.setDescription('The number of DHCPRELEASE (option 53 with value 7) packets received.')
dhcpServDhcpCountDeclines = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDeclines.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDeclines.setDescription('The number of DHCPDECLINE (option 53 with value 4) packets received.')
dhcpServDhcpCountInforms = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountInforms.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountInforms.setDescription('The number of DHCPINFORM (option 53 with value 8) packets received.')
dhcpServDhcpCountInvalids = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountInvalids.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountInvalids.setDescription('The number of DHCP packets received whose DHCP message type (i.e.: option number 53) is not understood or handled by the server.')
dhcpServDhcpCountOffers = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountOffers.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountOffers.setDescription('The number of DHCPOFFER (option 53 with value 2) packets sent.')
dhcpServDhcpCountAcks = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountAcks.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountAcks.setDescription('The number of DHCPACK (option 53 with value 5) packets sent.')
dhcpServDhcpCountNacks = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountNacks.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountNacks.setDescription('The number of DHCPNACK (option 53 with value 6) packets sent.')
dhcpServDhcpCountDroppedUnknownClient = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedUnknownClient.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedUnknownClient.setDescription('The number of DHCP packets dropped due to the server not recognizing or not providing service to the client-id and/or hardware address received in the incoming packet.')
dhcpServDhcpCountDroppedNotServingSubnet = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedNotServingSubnet.setDescription('The number of DHCP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcpServBootpStatMinArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 1), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServBootpStatMaxArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 2), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServBootpStatLastArrivalTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatLastArrivalTime.setDescription('The number of seconds since the last valid BOOTP message was received by the server. Invalid messages do not cause this value to change. If valid no messages have been received, then this object contains a zero value.')
dhcpServBootpStatMinResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 4), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServBootpStatMaxResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 5), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServBootpStatSumResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 6), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMinArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 1), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMaxArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 2), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServDhcpStatLastArrivalTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatLastArrivalTime.setDescription('The number of seconds since the last valid DHCP message was received by the server. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMinResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 4), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMaxResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 5), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatSumResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 6), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServRangeTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2), )
if mibBuilder.loadTexts: dhcpServRangeTable.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeTable.setDescription('A list of ranges that are configured on this server.')
dhcpServRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "dhcpServRangeSubnetAddr"), (0, "DHCP-SERVER-MIB", "dhcpServRangeStart"))
if mibBuilder.loadTexts: dhcpServRangeEntry.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeEntry.setDescription('A logical row in the serverRangeTable.')
dhcpServRangeSubnetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeSubnetAddr.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeSubnetAddr.setDescription('The IP address defining a subnet')
dhcpServRangeSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeSubnetMask.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeSubnetMask.setDescription('The subnet mask (DHCP option 1) provided to any client offered an address from this range.')
dhcpServRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeStart.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeStart.setDescription('Start of Subnet Address, Index for Conceptual Tabl, Type IP address ')
dhcpServRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 4), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeEnd.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeEnd.setDescription('The IP address of the last address in the range. The value of range end must be greater than or equal to the value of range start.')
dhcpServRangeInUse = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeInUse.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeInUse.setDescription('The number of addresses in this range that are currently in use. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcpServRangeOutstandingOffers = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeOutstandingOffers.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeOutstandingOffers.setDescription('The number of outstanding DHCPOFFER messages for this range is reported with this value. An offer is outstanding if the server has sent a DHCPOFFER message to a client, but has not yet received a DHCPREQUEST message from the client nor has the server-specific timeout (limiting the time in which a client can respond to the offer message) for the offer message expired.')
dhcpServRangeUnavailable = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeUnavailable.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeUnavailable.setDescription(' Dhcp Server IP Addresses unavailable in a Subnet ')
dhcpServRangeType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("manBootp", 1), ("autoBootp", 2), ("manDhcp", 3), ("autoDhcp", 4), ("dynamicDhcp", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeType.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeType.setDescription('Dhcp Server Client Lease Type ')
dhcpServRangeUnused = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 9), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeUnused.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeUnused.setDescription('The number of addresses in this range that are currently unused. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcpServFailoverTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1), )
if mibBuilder.loadTexts: dhcpServFailoverTable.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverTable.setDescription('A list of partner server.')
dhcpServFailoverEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "dhcpServFailoverPartnerAddr"))
if mibBuilder.loadTexts: dhcpServFailoverEntry.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverEntry.setDescription('A logical row in the serverFailoverTable.')
dhcpServFailoverPartnerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerAddr.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerAddr.setDescription('The IP address defining a partner server')
dhcpServFailoverPartnerType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("failover", 2), ("unconfigured", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerType.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerType.setDescription('Dhcp Server Failover server type ')
dhcpServFailoverPartnerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unknown", 0), ("syncing", 1), ("active", 2), ("inactive", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerStatus.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerStatus.setDescription('Dhcp Server Partner status ')
dhcpServFailoverPartnerPolltime = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerPolltime.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerPolltime.setDescription('The last time there was a successfull communication with the partner server. This value is local time in seconds since some epoch.')
ipspgDhcpTrapTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1), )
if mibBuilder.loadTexts: ipspgDhcpTrapTable.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrapTable.setDescription("The agent's table of IPSPG alarm information.")
ipspgDhcpTrapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "ipspgDhcpTrIndex"))
if mibBuilder.loadTexts: ipspgDhcpTrapEntry.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrapEntry.setDescription('Information about the last alarm trap generated by the agent.')
ipspgDhcpTrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrIndex.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrIndex.setDescription('Index into the IPSPG Alarm traps')
ipspgDhcpTrSequence = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrSequence.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrSequence.setDescription('Counter of the number of IPSPG alarm traps since the agent was last initialized')
ipspgDhcpTrId = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 3))).clone(namedValues=NamedValues(("monitor", 1), ("analyzer", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrId.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrId.setDescription('The application which generated this IPSPG alarm.')
ipspgDhcpTrText = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrText.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrText.setDescription('An ASCII string describing the IPSPG alarm condition/cause.')
ipspgDhcpTrPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("inform", 1), ("warning", 2), ("minor", 3), ("major", 4), ("critical", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrPriority.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrPriority.setDescription('The priority level as set on the agent for this Calss and Type of trap.')
ipspgDhcpTrClass = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrClass.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrClass.setDescription('The Class number of the described IPSPG alarm.')
ipspgDhcpTrType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrType.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrType.setDescription('The type number of the described IPSPG alarm.')
ipspgDhcpTrTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrTime.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrTime.setDescription('The time that the condition or event occurred which caused generation of this alarm. This value is given in seconds since 00:00:00 Greenwich mean time (GMT) January 1, 1970.')
ipspgDhcpTrSuspect = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrSuspect.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrSuspect.setDescription('An ASCII string describing the host which caused the IPSPG alarm.')
ipspgDhcpTrDiagId = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrDiagId.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrDiagId.setDescription('An integer describing the diagnosis which triggered this IPSPG alarm.')
dhcpServerStarted = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 1)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerStarted.setStatus('current')
if mibBuilder.loadTexts: dhcpServerStarted.setDescription('The monitor has determined that the DHCP server has been started.')
dhcpServerStopped = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 2)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerStopped.setStatus('current')
if mibBuilder.loadTexts: dhcpServerStopped.setDescription('The monitor has determined that the DHCP server has been stopped.')
dhcpServerReload = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 3)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerReload.setStatus('current')
if mibBuilder.loadTexts: dhcpServerReload.setDescription('The monitor has determined that the DHCP server has been reloaded.')
dhcpServerSubnetDepleted = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 4)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetDepleted.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetDepleted.setDescription('The monitor has determined that the DHCP server has run out of addresses in a subnet.')
dhcpServerBadPacket = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 5)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerBadPacket.setStatus('current')
if mibBuilder.loadTexts: dhcpServerBadPacket.setDescription('The monitor has determined that the DHCP server has received a bad DHCP or Bootp packet.')
dhcpServerFailoverActive = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 6)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerFailoverActive.setStatus('current')
if mibBuilder.loadTexts: dhcpServerFailoverActive.setDescription('This trap is issued by the secondary server. It indicates a primary partner server is down and its scopes are now being served by this failover server.')
dhcpServerFailoverReturnedControl = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 7)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerFailoverReturnedControl.setStatus('current')
if mibBuilder.loadTexts: dhcpServerFailoverReturnedControl.setDescription('This trap is issued by the secondary server. It indicates that the failover server has returned control to its primary partner.')
dhcpServerSubnetThresholdExceeded = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 8)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetThresholdExceeded.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetThresholdExceeded.setDescription('This trap is issued when subnet threshold is exceeded.')
dhcpServerSubnetThresholdDescent = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 9)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetThresholdDescent.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetThresholdDescent.setDescription('This trap is issued when subnet unavailable lease percentage falls below the descent threshold value.')
dhcpServerDropUnknownClient = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 10)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerDropUnknownClient.setStatus('current')
if mibBuilder.loadTexts: dhcpServerDropUnknownClient.setDescription('This trap is issued when the server drops a client message because the client MAC address is either in a MAC exclusion pool or is not in an inclusion pool.')
dhcpServerPingResponseReceived = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 11)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerPingResponseReceived.setStatus('current')
if mibBuilder.loadTexts: dhcpServerPingResponseReceived.setDescription('This trap is issued when the server receives a ping response.')
mibBuilder.exportSymbols("DHCP-SERVER-MIB", dhcpServDhcpStatMaxArrivalInterval=dhcpServDhcpStatMaxArrivalInterval, dhcpServDhcpStatMinResponseTime=dhcpServDhcpStatMinResponseTime, dhcpServDhcpStatMaxResponseTime=dhcpServDhcpStatMaxResponseTime, dhcpServDhcpStatistics=dhcpServDhcpStatistics, dhcpServDhcpCountDeclines=dhcpServDhcpCountDeclines, dhcpServBootpCounters=dhcpServBootpCounters, dhcpServBootpCountInvalids=dhcpServBootpCountInvalids, dhcpServBootpStatMaxResponseTime=dhcpServBootpStatMaxResponseTime, ipspgDhcpTrText=ipspgDhcpTrText, dhcpServFailover=dhcpServFailover, dhcpServSystem=dhcpServSystem, dhcpServMibTraps=dhcpServMibTraps, DhcpServTimeInterval=DhcpServTimeInterval, PYSNMP_MODULE_ID=dhcpServMib, dhcpServDhcpStatMinArrivalInterval=dhcpServDhcpStatMinArrivalInterval, ipspgDhcpTrClass=ipspgDhcpTrClass, dhcpServMib=dhcpServMib, dhcpServBootpStatMaxArrivalInterval=dhcpServBootpStatMaxArrivalInterval, dhcpServRangeEntry=dhcpServRangeEntry, dhcpServRangeInUse=dhcpServRangeInUse, dhcpServDhcpCountDiscovers=dhcpServDhcpCountDiscovers, dhcpServBootpCountDroppedUnknownClients=dhcpServBootpCountDroppedUnknownClients, dhcpServBootpCountReplies=dhcpServBootpCountReplies, ipspgDhcpTrPriority=ipspgDhcpTrPriority, dhcpServerFailoverReturnedControl=dhcpServerFailoverReturnedControl, dhcpServDhcpCountAcks=dhcpServDhcpCountAcks, ipspgDhcpTrTime=ipspgDhcpTrTime, dhcpServFailoverPartnerType=dhcpServFailoverPartnerType, dhcpServConfiguration=dhcpServConfiguration, dhcpServRangeEnd=dhcpServRangeEnd, dhcpServCountUsedSubnets=dhcpServCountUsedSubnets, dhcpServerStarted=dhcpServerStarted, ipspgDhcpTrSuspect=ipspgDhcpTrSuspect, dhcpServBootpCountDroppedNotServingSubnet=dhcpServBootpCountDroppedNotServingSubnet, dhcpServDhcpCountReleases=dhcpServDhcpCountReleases, ipspgDhcpTrapEntry=ipspgDhcpTrapEntry, dhcpServDhcpCountDroppedUnknownClient=dhcpServDhcpCountDroppedUnknownClient, dhcpServRangeOutstandingOffers=dhcpServRangeOutstandingOffers, dhcpServDhcpCountNacks=dhcpServDhcpCountNacks, dhcpServerDropUnknownClient=dhcpServerDropUnknownClient, lucent=lucent, mibs=mibs, ipspgDhcpTrapTable=ipspgDhcpTrapTable, dhcpServRangeUnavailable=dhcpServRangeUnavailable, dhcpServerReload=dhcpServerReload, dhcpServRangeUnused=dhcpServRangeUnused, dhcpServCountFullSubnets=dhcpServCountFullSubnets, dhcpServRangeSubnetMask=dhcpServRangeSubnetMask, dhcpServDhcpCountDroppedNotServingSubnet=dhcpServDhcpCountDroppedNotServingSubnet, dhcpServRangeType=dhcpServRangeType, dhcpServRangeTable=dhcpServRangeTable, dhcpServSystemDescr=dhcpServSystemDescr, ipspgDhcpTrSequence=ipspgDhcpTrSequence, dhcpServerFailoverActive=dhcpServerFailoverActive, dhcpServerStopped=dhcpServerStopped, ipspgTrap=ipspgTrap, ipspgDhcpTrId=ipspgDhcpTrId, dhcpServerBadPacket=dhcpServerBadPacket, ipspgServices=ipspgServices, ipspgDhcpTrType=ipspgDhcpTrType, dhcpServDhcpCountRequests=dhcpServDhcpCountRequests, dhcpServDhcpCountInforms=dhcpServDhcpCountInforms, dhcpServDhcpCountOffers=dhcpServDhcpCountOffers, products=products, dhcpServerSubnetThresholdExceeded=dhcpServerSubnetThresholdExceeded, ipspgDhcpTrIndex=ipspgDhcpTrIndex, dhcpServerPingResponseReceived=dhcpServerPingResponseReceived, dhcpServRangeStart=dhcpServRangeStart, dhcpServSubnetCounters=dhcpServSubnetCounters, dhcpServFailoverPartnerAddr=dhcpServFailoverPartnerAddr, dhcpServDhcpStatLastArrivalTime=dhcpServDhcpStatLastArrivalTime, ipspgDNS=ipspgDNS, dhcpServerSubnetDepleted=dhcpServerSubnetDepleted, ipspg=ipspg, dhcpServBootpCountRequests=dhcpServBootpCountRequests, dhcpServFailoverPartnerPolltime=dhcpServFailoverPartnerPolltime, dhcpServDhcpStatSumResponseTime=dhcpServDhcpStatSumResponseTime, dhcpServSystemUpTime=dhcpServSystemUpTime, dhcpServBootpStatMinResponseTime=dhcpServBootpStatMinResponseTime, dhcpServBootpStatSumResponseTime=dhcpServBootpStatSumResponseTime, dhcpServFailoverEntry=dhcpServFailoverEntry, ipspgDhcpTrDiagId=ipspgDhcpTrDiagId, ipspgDHCP=ipspgDHCP, dhcpServCountUnusedSubnets=dhcpServCountUnusedSubnets, dhcpServFailoverPartnerStatus=dhcpServFailoverPartnerStatus, dhcpServMibObjects=dhcpServMibObjects, dhcpServDhcpCounters=dhcpServDhcpCounters, dhcpServerSubnetThresholdDescent=dhcpServerSubnetThresholdDescent, dhcpServBootpStatMinArrivalInterval=dhcpServBootpStatMinArrivalInterval, dhcpServSystemResetTime=dhcpServSystemResetTime, dhcpServFailoverTable=dhcpServFailoverTable, dhcpServBootpStatistics=dhcpServBootpStatistics, dhcpServDhcpCountInvalids=dhcpServDhcpCountInvalids, dhcpServSystemStatus=dhcpServSystemStatus, dhcpServBootpStatLastArrivalTime=dhcpServBootpStatLastArrivalTime, dhcpServRangeSubnetAddr=dhcpServRangeSubnetAddr)
|
# Text for update_startup_screen()
startup_screen_1 = "Bienvenue au"
startup_screen_2 = "LightningATM"
startup_screen_3 = "- veuillez insérer des pièces -"
# Text for error_screen()
error_screen_1 = "Une erreur s'est produite:"
# Text for update_qr_request()
qr_request_1 = "Veuillez scanner"
qr_request_2 = "votre facture"
qr_request_3 = "Scan en cours..."
qr_request_4 = "pour "
qr_request_5 = " sats."
# Text for update_qr_failed()
qr_failed_1 = "Le scan a échoué."
qr_failed_2 = "Veuillez réessayer."
# Text for update_payout_screen()
payout_screen_1 = " sats"
payout_screen_2 = "en chemain!"
# text for update_payment_failed()
payment_failed_1 = "Le paiement a échoué!"
payment_failed_2 = "Veuillez contacter"
payment_failed_3 = "l'opérateur."
# Text for update_thankyou_screen()
thankyou_screen_1 = "Profitez de vos nouveaux"
thankyou_screen_2 = "satoshis!!"
thankyou_screen_3 = "#bitcoin #lightning"
# Text for update_nocoin_screen()
nocoin_screen_1 = "Pièces non ajoutées!"
nocoin_screen_2 = "Veuillez ajouter"
nocoin_screen_3 = "des pièces en premier"
# Text for update_lnurl_generation()
lnurl_generation_1 = "Génération du"
lnurl_generation_2 = "QR code à scanner"
# Text for update_shutdown_screen()
shutdown_screen_1 = "ATM éteinte!"
shutdown_screen_2 = "Veuillez contacter"
shutdown_screen_3 = "l'opérateur."
# Text for update_wallet_scan()
wallet_scan_1 = "Veuillez scanner"
wallet_scan_2 = "la référence de"
wallet_scan_3 = "votre portefeuille."
# Text for update_lntxbot_balance()
lntxbot_balance_1 = "Succès!!"
lntxbot_balance_2 = "Solde actuel:"
lntxbot_balance_3 = " sats"
# Text for update_btcpay_lnd()
btcpay_lnd_1 = "Succès!!"
btcpay_lnd_2 = "Scanné avec succès"
btcpay_lnd_3 = "BTCPay LND Portefeuille."
# Text for draw_lnurl_qr()
lnurl_qr_1 = "Scanner pour"
lnurl_qr_2 = "recevoir"
# Text for update_amount_screen()
amount_screen_1 = " sats"
amount_screen_2 = "Taux"
amount_screen_3 = "= "
amount_screen_4 = " sats/"
amount_screen_5 = "Frais"
amount_screen_6 = "= "
amount_screen_7 = "% ("
amount_screen_8 = " sats)"
# Text for update_lnurl_cancel_notice
lnurl_cancel_notice_1 = "Preparation au LNURL"
lnurl_cancel_notice_2 = "(Non compatible LNURL?"
lnurl_cancel_notice_3 = "Appuyer sur le bouton pour annuler)"
# Text for update_button_fault()
button_fault_1 = "Oh Sorry.."
button_fault_2 = "Button fault.."
button_fault_3 = "Try again!"
# Text for update_wallet_fault()
wallet_fault_1 = "Wallet fault.."
wallet_fault_2 = "No wallet data."
wallet_fault_3 = "Set it first!"
|
def residual(s:dict, y, x):
""" Return residuals
:param s: state - supply empty dict on first call
:param y: incoming observation
:param x: term structure of predictions out k steps ahead, made after y received
:returns k-vector of residuals
"""
k = len(x)
if not s:
s = {'predictions': [[] for _ in range(k)]} # Holds the cavalcade
else:
assert len(x) == len(s['predictions']) # 'k' is immutable
assessable = s['predictions'].pop(0)
z = [0 for _ in range(k)]
if assessable:
for j, xi in assessable:
z[j] = y - xi
s['predictions'].append(list())
for j, xj in enumerate(x):
s['predictions'][j].append((j, xj))
return z, s
|
html_head = r"""<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script type="text/javascript">
var subjs = []
function updateCounts(){
var counts = {report:{"-1":0, "1":0, "0":0}}
subjs.forEach(function(val, idx, arr){
counts.report[val.report] += 1;
})
$("#nrpass").text(counts.report["1"])
$("#nrfail").text(counts.report["0"])
$("#nrtodo").text(counts.report["-1"])
}
function qc_update(run_id, stage, value) {
if (stage == 'report') {
subjs[run_id][stage] = parseInt(value)
updateCounts();
}
else {
subjs[run_id][stage] = value
}
}
function update_all(stage, value) {
subjs.forEach( subj => {subj[stage]=value})
}
function get_csv(items) {
// https://stackoverflow.com/questions/44396943/generate-a-csv-file-from-a-javascript-array-of-objects
let csv = ''
// Loop the array of objects
for(let row = 0; row < items.length; row++){
let keysAmount = Object.keys(items[row]).length
let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\r\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? '\t' : '\r\n' )
keysCounter++
}
let keysCounterb = 0
for(let key in items[row]){
csv += items[row][key] + (keysCounterb+1 < keysAmount ? '\t' : '\r\n' )
keysCounterb++
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? '\t' : '\r\n' )
keysCounter++
}
}
keysCounter = 0
}
// Once we are done looping, download the .csv by creating a link
// if a link has already been created, update it
if (document.querySelector('#download-csv') == null){
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'thistextissolongitmustabsolutelybeuniqueright');
document.body.appendChild(link)
} else {
let link = document.querySelector('#download-csv')
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'thistextissolongitmustabsolutelybeuniqueright');
}
document.querySelector('#download-csv').click()
}
function parse_id(idstr) {
return idstr.split('_')[0].split('-')[1]
}
var observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
eid = parse_id(entry.target.id)
if (entry['intersectionRatio'] == 1 && subjs[eid]['been_on_screen'] == false) {
subjs[eid]['been_on_screen'] = true
}
else if (entry['intersectionRatio'] == 0 && subjs[eid]['been_on_screen'] == true && subjs[eid]['report'] == -1) {
subjs[eid]['report'] = 1
observer.unobserve(entry.target)
updateCounts();
radioid = 'inlineRadio' + eid
document.querySelectorAll('[name=' + radioid + ']')[0].checked = true
}
/* Here's where we deal with every intersection */
});
}
, {root:document.querySelector('#scrollArea'), threshold:[0,1]});
</script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<style type="text/css">
.sub-report-title {}
.run-title {}
h1 { padding-top: 35px; }
h2 { padding-top: 20px; }
h3 { padding-top: 15px; }
.elem-desc {}
.elem-caption {
margin-top: 15px
margin-bottom: 0;
}
.elem-filename {}
div.elem-image {
width: 100%;
page-break-before:always;
}
.elem-image object.svg-reportlet {
width: 100%;
padding-bottom: 5px;
}
body {
padding: 65px 10px 10px;
}
.boiler-html {
font-family: "Bitstream Charter", "Georgia", Times;
margin: 20px 25px;
padding: 10px;
background-color: #F8F9FA;
}
div#boilerplate pre {
margin: 20px 25px;
padding: 10px;
background-color: #F8F9FA;
}
</style>
</head>
<body>"""
html_foot = """<script type="text/javascript">
function toggle(id) {
var element = document.getElementById(id);
if(element.style.display == 'block')
element.style.display = 'none';
else
element.style.display = 'block';
}
</script>
<script>
updateCounts();
document.querySelectorAll('[id^="id"]').forEach(img => {observer.observe(img)})
</script>
</body>
</html>"""
reviewer_initials = """
<p> Initials: <input type="text" id="initials_box" oninput="update_all('rater', this.value)"></p>
"""
nav= """<nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light">
<div class="navbar-header">
Ratings: <span id="nrpass" class="badge badge-success">0</span> <span id="nrfail" class="badge badge-danger">0</span> <span id="nrtodo" class="badge badge-warning">0</span>
</div>
<div class="navbar-text">
<button type="button" class="btn btn-info btn-sm" id="csv_download" onclick="get_csv(subjs)">Download TSV</button>
</div>
</div>
</nav>"""
def _generate_html_head(dl_file_name):
"""
generate an html head block where the name of the downloaded file is set appropriately.
Parameters
----------
dl_file_name : str
Returns
-------
str
"""
return html_head.replace('thistextissolongitmustabsolutelybeuniqueright', dl_file_name)
|
"""Dot notation for dictionary."""
class Map(dict):
"""dot.notation access to dictionary attributes.
Args:
dict (dict): dictionary to map.
"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
|
# 并查集模板
class UnionFind:
'''
适用范围:连通性检测
'''
def __init__(self, n: int):
self.parent = list(range(n))
self.size = [1] * n
self.n = n
# 当前连通分量数目
self.setCount = n
def findset(self, x: int) -> int:
if self.parent[x] == x:
return x
self.parent[x] = self.findset(self.parent[x])
return self.parent[x]
def un(self, x: int, y: int) -> bool:
'''
unite合并
'''
x, y = self.findset(x), self.findset(y)
if x == y:
return False
if self.size[x] < self.size[y]:
x, y = y, x
self.parent[y] = x
self.size[x] += self.size[y]
self.setCount -= 1
return True
def co(self, x: int, y: int) -> bool:
'''
connected连通性
'''
x, y = self.findset(x), self.findset(y)
return x == y
|
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1
def maxLevelSum(root):
# Code here
h = {}
level = 0
getLevelSum(root, level, h)
return max(h.values())
def getLevelSum(root, level, h):
if root == None:
return
if level not in h:
h[level] = 0
h[level] += root.data
getLevelSum(root.left, level+1, h)
getLevelSum(root.right, level+1, h)
|
'''
Семипроцентный барьер
'''
parties = []
votes = []
sum_votes = 0
with open('input.txt', 'r', encoding='utf8') as file:
flag = False
for line in file:
line_el = line.split()
line = line.replace('\n', '')
if (line_el[0][1:] == 'PARTIES:'):
continue
elif (line_el[0] == 'VOTES:'):
flag = True
continue
if (flag):
sum_votes += 1
votes[parties.index(line)] += 1
else:
parties.append(line)
votes.append(0)
for id in range(len(parties)):
if (votes[id] / sum_votes >= 0.07):
print(parties[id])
|
# Copyright 2017 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.
class BigQueryObject(object):
"""A BigQueryObject holds data that will be read from/written to BigQuery."""
def __eq__(self, other):
return self.__dict__ == other.__dict__
@staticmethod
def get_bigquery_attributes():
"""Returns a list of attributes that exist in the BigQuery schema.
These attributes should be strings.
"""
raise NotImplementedError()
def as_bigquery_row(self):
"""Returns data in a suitable format for writing to BigQuery.
The default behavior constructs a dictionary from the attributes listed
by get_bigquery_attributes and their values. This behavior can be
overridden.
"""
return {attr: self.__dict__.get(attr)
for attr in self.get_bigquery_attributes()}
@classmethod
def from_bigquery_row(cls, row):
"""Creates an instance of cls from a BigQuery row.
Args:
row: dictionary in the form {field: value} where field is in
get_bigquery_attributes().
"""
obj = cls()
for field, value in row.items():
obj.__dict__[field] = value
return obj
class CQAttempt(BigQueryObject):
"""A CQAttempt represents a single CQ attempt.
It is created by aggregating all CQEvents for a given attempt.
"""
def __init__(self):
# Consistent between events for a given attempt
self.attempt_start_msec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.dry_run = False
# Patch event timestamps
self.first_start_msec = None
self.last_start_msec = None
self.first_stop_msec = None
self.last_stop_msec = None
self.patch_committed_msec = None
self.patch_started_to_commit_msec = None
self.patch_failed_msec = None
self.vcs_commit_latency_sec = None
self.click_to_failure_sec = None
self.click_to_patch_committed_sec = None
self.click_to_result_sec = None
# Patch event bools
self.committed = False
self.was_throttled = False
self.waited_for_tree = False
self.failed = False
# Verifier event timestamps
self.first_verifier_trigger_msec = None
self.patch_verifier_pass_msec = None
self.cq_launch_latency_sec = None
self.verifier_pass_latency_sec = None
self.tree_check_and_throttle_latency_sec = None
# Verifier event bools
self.no_tryjobs_launched = False
self.custom_trybots = False
self.failure_reason = None
self.max_failure_msec = None
self.fail_type = None
self.infra_failures = 0
self.compile_failures = 0
self.test_failures = 0
self.invalid_test_results_failures = 0
self.patch_failures = 0
self.total_failures = 0
self.contributing_bbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return [
'attempt_start_msec',
'first_start_msec',
'last_start_msec',
'cq_name',
'first_stop_msec',
'last_stop_msec',
'committed',
'was_throttled',
'waited_for_tree',
'issue',
'patchset',
'dry_run',
'cq_launch_latency_sec',
'verifier_pass_latency_sec',
'tree_check_and_throttle_latency_sec',
'no_tryjobs_launched',
'custom_trybots',
'failed',
'infra_failures',
'compile_failures',
'test_failures',
'invalid_test_results_failures',
'patch_failures',
'total_failures',
'fail_type',
'contributing_bbucket_ids',
'vcs_commit_latency_sec',
'click_to_patch_committed_sec',
'click_to_failure_sec',
'click_to_result_sec',
'earliest_equivalent_patchset',
'attempt_key',
]
class CQEvent(BigQueryObject):
"""A CQEvent represents event data reported to BigQuery from CQ.
CQEvents are aggregated to make CQAttempts.
"""
def __init__(self):
self.timestamp_millis = None
self.action = None
self.attempt_start_usec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.failure_reason = None
self.dry_run = False
self.contributing_buildbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return [
'timestamp_millis',
'action',
'attempt_start_usec',
'cq_name',
'issue',
'patchset',
'dry_run',
'failure_reason',
'contributing_buildbucket_ids',
'earliest_equivalent_patchset',
'attempt_key',
]
|
A = [10,13,7]
B = [1,2,3,4,5,6]
def sum_all(A, B):
ASum = sum(A)
#print(ASum)
BSum = sum(B)
#print(BSum)
TSum = ASum+BSum
#print(TSum)
return ASum, BSum, TSum
ASum, BSum, TSum = sum_all(A,B)
print('The sum of list 1 is '+str(ASum))
print('The sum of list 2 is '+str(BSum))
print('The sum of both lists is '+str(TSum))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.