content stringlengths 7 1.05M |
|---|
# We can easily adjust the code from the most common character
# to the most common word by splitting the paragraph into a
# list of words instead of characters:
myParagraph = "In the year 1878 I took my degree of Doctor of Medicine of the University of London, and proceeded to Netley to go through the course prescribed for surgeons in the army. Having completed my studies there, I was duly attached to the Fifth Northumberland Fusiliers as Assistant Surgeon. The regiment was stationed in India at the time, and before I could join it, the second Afghan war had broken out. On landing at Bombay, I learned that my corps had advanced through the passes, and was already deep in the enemy’s country. I followed, however, with many other officers who were in the same situation as myself, and succeeded in reaching Candahar in safety, where I found my regiment, and at once entered upon my new duties."
# get the "words" in the paragraph by splitting on the spaces:
words = myParagraph.split(" ")
# Note that I've changed the variables to reflect that I am
# looking at "words" and not "char". This is not required,
# but helps in understanding the code
uniqueWords = set(words)
mostCommonWord = []
mCWFreq = 0
for word in uniqueWords:
if word != " ":
# check the frequency inside the "words" list and NOT
# the myParagraph variable, as that would detect
# partial words (e.g., "these" will count as an
# instance of "the")
freq = words.count(word)
if freq > mCWFreq:
mCWFreq = freq
mostCommonWord = [word]
elif freq == mCWFreq and word not in mostCommonWord:
mostCommonWord.append(word)
print(f"The most common word(s) is/are {mostCommonWord}, which occur(s) {mCWFreq} time(s)!") |
# All endpoint constants for the User resource
USER_ADD_DEVICE_TOKEN = "/push/{token_type}"
USER_BAN_FROM_CHANNELS_WITH_CUSTOM_TYPES = "/banned_channel_custom_types"
USER_BLOCK = "/block"
USER_CHOOSE_PUSH_MESSAGE_TEMPLATE = "/push/template"
USER_LIST_BANNED_CHANNELS = "/ban"
USER_LIST_BLOCKED_USERS = "/block"
USER_LIST_DEVICE_TOKENS = "/push/{token_type}"
USER_LIST_MUTED_CHANNELS = "/mute"
USER_MARK_AS_READ_ALL = "/mark_as_read_all"
USER_MUTE_FROM_CHANNELS_WITH_CUSTOM_TYPES = "/muted_channel_custom_types"
USER_MY_GROUP_CHANNELS = "/my_group_channels"
USER_REGISTER_OPERATOR_CHANNELS_CUSTOM_TYPES = "/operating_channel_custom_types"
USER_REMOVE_ALL_DEVICE_TOKENS = "/push"
USER_REMOVE_DEVICE_TOKEN = "/push/{token_type}/{token}"
USER_REMOVE_DEVICE_TOKEN_FROM_OWNER = "/push/device_tokens/{token_type}/{token}"
USER_RESET_PUSH_PREFERENCE = "/push_preference"
USER_UNBLOCK = "/block/{target_id}"
USER_UNREAD_CHANNEL_COUNT = "/unread_channel_count"
USER_UNREAD_ITEM_COUNT = "/unread_item_count"
USER_UNREAD_MESSAGE_COUNT = "/unread_message_count"
USER_UPDATE_CHANNEL_INVITE_PREFERENCE = "/channel_invitation_preference"
USER_UPDATE_COUNT_PREFERENCE_OF_CHANNEL = "/count_preference/{channel_url}"
USER_UPDATE_PUSH_PREFERENCE = "/push_preference"
USER_UPDATE_PUSH_PREFERENCE_FOR_CHANNEL = "/push_preference/{channel_url}"
USER_VIEW_CHANNEL_INVITE_PREFERENCE = "/channel_invitation_preference"
USER_COUNT_PREFERENCE_OF_CHANNEL = "/count_preference/{channel_url}"
USER_VIEW_DEVICE_TOKEN_OWNER = "/push/device_tokens/{token_type}/{token}"
USER_VIEW_GROUP_CHANNEL_COUNT_BY_JOIN_STATUS = "/group_channel_count"
USER_VIEW_PUSH_PREFERENCE = "/push_preference"
USER_VIEW_PUSH_PREFERENCE_FOR_CHANNEL = "/push_preference/{channel_url}"
USER_CREATE_METADATA = "/metadata"
USER_DELETE_METADATA = "/metadata"
USER_UPDATE_METADATA = "/metadata"
USER_VIEW_METADATA = "/metadata"
|
def dict_equal(first, second):
"""
This is a utility function used in testing to determine if two dictionaries are, in a nested sense, equal (ie they have the same keys and values at all levels).
:param dict first: The first dictionary to compare.
:param dict second: The second dictionary to compare.
:return: Whether or not the dictionaries are (recursively) equal.
:rtype: bool
"""
if not set(first.keys()) == set(second.keys()):
return False
for k1, v1 in first.items():
if isinstance(v1, dict) and isinstance(second[k1], dict):
if not dict_equal(v1, second[k1]):
return False
elif not isinstance(v1, dict) and not isinstance(second[k1], dict):
if v1 != second[k1]:
return False
else:
return False
return True
|
def aumentar(n, taxa=0):
res = n + (n * taxa / 100)
return res # moeda(res)
# return res
def diminuir(n=0, taxa=0):
res = n - (n * taxa / 100)
return res # moeda(res)
def dobro(n=0):
res = n * 2
return res # moeda(res)
def metade(n):
res = n / 2
return res # moeda(res)
def moeda(n, m='R$'):
res = f'{m} {n:.2f}'.replace(".", ",")
return res
|
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
left, right = 0, len(A) - 1
result = []
while left <= right:
leftSqr = A[left] * A[left]
rightSqr = A[right] * A[right]
if leftSqr >= rightSqr:
result.insert(0, leftSqr)
left += 1
else:
result.insert(0, rightSqr)
right -= 1
return result |
class MyMath:
def __init__(self):
self.answer = 0
def Add(self, first_number, second_number):
self.answer = first_number + second_number
def Subtract(self, first_number, second_number):
self.answer = first_number - second_number
def __str__(self):
return str(self.answer)
class Person:
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
person1 = Person("John", 23)
person2 = Person("Anne", 102)
person1.showAge()
person2.showName()
math = MyMath()
math.Add(10,20)
print(math)
math.Subtract(10, 20)
print(math) |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
noteList = [{'freq': 8.1757989200000001, 'name': 'C', 'octave': 0},
{'freq': 8.6619572199999997, 'name': 'C#', 'octave': 0},
{'freq': 9.1770239999999994, 'name': 'D', 'octave': 0},
{'freq': 9.7227182400000007, 'name': 'D#', 'octave': 0},
{'freq': 10.300861149999999, 'name': 'E', 'octave': 0},
{'freq': 10.91338223, 'name': 'F', 'octave': 0},
{'freq': 11.56232571, 'name': 'F#', 'octave': 0},
{'freq': 12.249857370000001, 'name': 'G', 'octave': 0},
{'freq': 12.9782718, 'name': 'G#', 'octave': 0},
{'freq': 13.75, 'name': 'A', 'octave': 0},
{'freq': 14.56761755, 'name': 'A#', 'octave': 0},
{'freq': 15.43385316, 'name': 'B', 'octave': 0},
{'freq': 16.351597829999999, 'name': 'C', 'octave': 1},
{'freq': 17.323914439999999, 'name': 'C#', 'octave': 1},
{'freq': 18.354047990000002, 'name': 'D', 'octave': 1},
{'freq': 19.445436480000001, 'name': 'D#', 'octave': 1},
{'freq': 20.60172231, 'name': 'E', 'octave': 1},
{'freq': 21.82676446, 'name': 'F', 'octave': 1},
{'freq': 23.124651419999999, 'name': 'F#', 'octave': 1},
{'freq': 24.499714749999999, 'name': 'G', 'octave': 1},
{'freq': 25.9565436, 'name': 'G#', 'octave': 1},
{'freq': 27.5, 'name': 'A', 'octave': 1},
{'freq': 29.135235089999998, 'name': 'A#', 'octave': 1},
{'freq': 30.867706330000001, 'name': 'B', 'octave': 1},
{'freq': 32.703195659999999, 'name': 'C', 'octave': 2},
{'freq': 34.647828869999998, 'name': 'C#', 'octave': 2},
{'freq': 36.708095989999997, 'name': 'D', 'octave': 2},
{'freq': 38.890872969999997, 'name': 'D#', 'octave': 2},
{'freq': 41.203444609999998, 'name': 'E', 'octave': 2},
{'freq': 43.65352893, 'name': 'F', 'octave': 2},
{'freq': 46.249302839999999, 'name': 'F#', 'octave': 2},
{'freq': 48.999429499999998, 'name': 'G', 'octave': 2},
{'freq': 51.9130872, 'name': 'G#', 'octave': 2},
{'freq': 55.0, 'name': 'A', 'octave': 2},
{'freq': 58.270470189999998, 'name': 'A#', 'octave': 2},
{'freq': 61.735412660000001, 'name': 'B', 'octave': 2},
{'freq': 65.406391330000005, 'name': 'C', 'octave': 3},
{'freq': 69.295657739999996, 'name': 'C#', 'octave': 3},
{'freq': 73.416191979999994, 'name': 'D', 'octave': 3},
{'freq': 77.78174593, 'name': 'D#', 'octave': 3},
{'freq': 82.406889230000004, 'name': 'E', 'octave': 3},
{'freq': 87.30705786, 'name': 'F', 'octave': 3},
{'freq': 92.498605679999997, 'name': 'F#', 'octave': 3},
{'freq': 97.998858999999996, 'name': 'G', 'octave': 3},
{'freq': 103.8261744, 'name': 'G#', 'octave': 3},
{'freq': 110.0, 'name': 'A', 'octave': 3},
{'freq': 116.5409404, 'name': 'A#', 'octave': 3},
{'freq': 123.4708253, 'name': 'B', 'octave': 3},
{'freq': 130.81278270000001, 'name': 'C', 'octave': 4},
{'freq': 138.59131550000001, 'name': 'C#', 'octave': 4},
{'freq': 146.83238399999999, 'name': 'D', 'octave': 4},
{'freq': 155.5634919, 'name': 'D#', 'octave': 4},
{'freq': 164.81377850000001, 'name': 'E', 'octave': 4},
{'freq': 174.61411570000001, 'name': 'F', 'octave': 4},
{'freq': 184.9972114, 'name': 'F#', 'octave': 4},
{'freq': 195.99771799999999, 'name': 'G', 'octave': 4},
{'freq': 207.6523488, 'name': 'G#', 'octave': 4},
{'freq': 220.0, 'name': 'A', 'octave': 4},
{'freq': 233.08188079999999, 'name': 'A#', 'octave': 4},
{'freq': 246.9416506, 'name': 'B', 'octave': 4},
{'freq': 261.62556530000001, 'name': 'C', 'octave': 5},
{'freq': 277.18263100000001, 'name': 'C#', 'octave': 5},
{'freq': 293.66476790000002, 'name': 'D', 'octave': 5},
{'freq': 311.12698369999998, 'name': 'D#', 'octave': 5},
{'freq': 329.6275569, 'name': 'E', 'octave': 5},
{'freq': 349.22823140000003, 'name': 'F', 'octave': 5},
{'freq': 369.99442269999997, 'name': 'F#', 'octave': 5},
{'freq': 391.99543599999998, 'name': 'G', 'octave': 5},
{'freq': 415.3046976, 'name': 'G#', 'octave': 5},
{'freq': 440.0, 'name': 'A', 'octave': 5},
{'freq': 466.16376150000002, 'name': 'A#', 'octave': 5},
{'freq': 493.88330130000003, 'name': 'B', 'octave': 5},
{'freq': 523.25113060000001, 'name': 'C', 'octave': 6},
{'freq': 554.36526200000003, 'name': 'C#', 'octave': 6},
{'freq': 587.32953580000003, 'name': 'D', 'octave': 6},
{'freq': 622.25396739999996, 'name': 'D#', 'octave': 6},
{'freq': 659.2551138, 'name': 'E', 'octave': 6},
{'freq': 698.45646290000002, 'name': 'F', 'octave': 6},
{'freq': 739.98884539999995, 'name': 'F#', 'octave': 6},
{'freq': 783.99087199999997, 'name': 'G', 'octave': 6},
{'freq': 830.60939519999999, 'name': 'G#', 'octave': 6},
{'freq': 880.0, 'name': 'A', 'octave': 6},
{'freq': 932.32752300000004, 'name': 'A#', 'octave': 6},
{'freq': 987.76660249999998, 'name': 'B', 'octave': 6},
{'freq': 1046.5022610000001, 'name': 'C', 'octave': 7},
{'freq': 1108.7305240000001, 'name': 'C#', 'octave': 7},
{'freq': 1174.6590719999999, 'name': 'D', 'octave': 7},
{'freq': 1244.5079350000001, 'name': 'D#', 'octave': 7},
{'freq': 1318.5102280000001, 'name': 'E', 'octave': 7},
{'freq': 1396.912926, 'name': 'F', 'octave': 7},
{'freq': 1479.977691, 'name': 'F#', 'octave': 7},
{'freq': 1567.9817439999999, 'name': 'G', 'octave': 7},
{'freq': 1661.2187899999999, 'name': 'G#', 'octave': 7},
{'freq': 1760.0, 'name': 'A', 'octave': 7},
{'freq': 1864.6550460000001, 'name': 'A#', 'octave': 7},
{'freq': 1975.533205, 'name': 'B', 'octave': 7},
{'freq': 2093.0045220000002, 'name': 'C', 'octave': 8},
{'freq': 2217.4610480000001, 'name': 'C#', 'octave': 8},
{'freq': 2349.318143, 'name': 'D', 'octave': 8},
{'freq': 2489.0158700000002, 'name': 'D#', 'octave': 8},
{'freq': 2637.0204549999999, 'name': 'E', 'octave': 8},
{'freq': 2793.8258510000001, 'name': 'F', 'octave': 8},
{'freq': 2959.9553820000001, 'name': 'F#', 'octave': 8},
{'freq': 3135.9634879999999, 'name': 'G', 'octave': 8},
{'freq': 3322.4375810000001, 'name': 'G#', 'octave': 8},
{'freq': 3520.0, 'name': 'A', 'octave': 8},
{'freq': 3729.3100920000002, 'name': 'A#', 'octave': 8},
{'freq': 3951.0664099999999, 'name': 'B', 'octave': 8},
{'freq': 4186.0090449999998, 'name': 'C', 'octave': 9},
{'freq': 4434.9220960000002, 'name': 'C#', 'octave': 9},
{'freq': 4698.6362870000003, 'name': 'D', 'octave': 9},
{'freq': 4978.0317400000004, 'name': 'D#', 'octave': 9},
{'freq': 5274.0409110000001, 'name': 'E', 'octave': 9},
{'freq': 5587.6517030000005, 'name': 'F', 'octave': 9},
{'freq': 5919.9107629999999, 'name': 'F#', 'octave': 9},
{'freq': 6271.9269759999997, 'name': 'G', 'octave': 9},
{'freq': 6644.8751609999999, 'name': 'G#', 'octave': 9},
{'freq': 7040.0, 'name': 'A', 'octave': 9},
{'freq': 7458.6201840000003, 'name': 'A#', 'octave': 9},
{'freq': 7902.1328199999998, 'name': 'B', 'octave': 9},
{'freq': 8372.0180899999996, 'name': 'C', 'octave': 10},
{'freq': 8869.8441910000001, 'name': 'C#', 'octave': 10},
{'freq': 9397.2725730000002, 'name': 'D', 'octave': 10},
{'freq': 9956.0634790000004, 'name': 'D#', 'octave': 10},
{'freq': 10548.081819999999, 'name': 'E', 'octave': 10},
{'freq': 11175.30341, 'name': 'F', 'octave': 10},
{'freq': 11839.821529999999, 'name': 'F#', 'octave': 10},
{'freq': 12543.853950000001, 'name': 'G', 'octave': 10}]
|
rules = {
"username": {
"presence": True,
"unique_user": True,
"not_google_username": True,
"name": "usuario"
},
"last_name": {"presence": True, "name": "apellido"},
"first_name": {"presence": True, "name": "nombre"},
"email": {"presence": True, "email": True, "unique_mail": True, "name": "email"},
"password": {
"presence": True,
"min_length": 6,
"name": "contraseña",
},
"confirm_password": {
"presence": True,
"min_length": 6,
"name": "confirmar contraseña",
"compare_fields": "password",
},
}
|
"""Python replacement for overlapSelect.
For a chain and a set of genes returns:
gene: how many bases this chain overlap in exons.
"""
__author__ = "Bogdan Kirilenko, 2020."
__version__ = "1.0"
__email__ = "kirilenk@mpi-cbg.de"
__credits__ = ["Michael Hiller", "Virag Sharma", "David Jebb"]
def make_bed_ranges(bed_line):
"""Convert a bed line to a set of ranges."""
line_info = bed_line.split("\t")
glob_start = int(line_info[1])
# glob_end = int(line_info[2])
gene_name = line_info[3]
block_starts = [glob_start + int(x) for x in line_info[11].split(",") if x != ""]
block_sizes = [int(x) for x in line_info[10].split(",") if x != ""]
blocks_num = int(line_info[9])
block_ends = [block_starts[i] + block_sizes[i] for i in range(blocks_num)]
genes = [gene_name for _ in range(blocks_num)]
return list(zip(block_starts, block_ends, genes))
def parse_bed(bed_lines):
"""Return sorted genic regions."""
ranges = []
for bed_line in bed_lines.split("\n")[:-1]:
gene_ranges = make_bed_ranges(bed_line)
ranges.extend(gene_ranges)
return list(sorted(ranges, key=lambda x: x[0]))
def chain_reader(chain):
"""Return chain blocks one by one."""
chain_data = chain.split("\n")
chain_head = chain_data[0]
del chain_data[0]
# define starting point
progress = int(chain_head.split()[5])
blocks_num = len(chain_data)
for i in range(blocks_num):
block_info = chain_data[i].split()
if len(block_info) == 1:
block_size = int(block_info[0])
block_start = progress
block_end = block_start + block_size
yield block_start, block_end
break # end the loop
block_size = int(block_info[0])
dt = int(block_info[1])
block_start = progress
block_end = block_start + block_size
progress = block_end + dt
yield block_start, block_end
def intersect(ch_block, be_block):
"""Return intersection size."""
return min(ch_block[1], be_block[1]) - max(ch_block[0], be_block[0])
def overlap_select(bed, chain):
"""Entry point."""
ranges = parse_bed(bed)
genes = [x[2] for x in ranges]
# accumulate intersections
bed_overlaps = {gene: 0 for gene in genes}
chain_len = 0 # sum of chain blocks
start_with = 0
# init blocks generator
for block in chain_reader(chain):
# add to len
chain_len += block[1] - block[0]
FLAG = False # was intersection or not?
FIRST = True
while True:
if FIRST: # start with previous start, first iteration
bed_num = start_with
FIRST = False # guarantee that this condition works ONCE per loop
else: # just increase the pointer
bed_num += 1 # to avoid inf loop
if bed_num >= len(ranges):
break # beds are over
exon = ranges[bed_num]
if block[1] < exon[0]: # too late
break # means that bed is "righter" than chain
block_vs_exon = intersect(block, (exon[0], exon[1]))
if block_vs_exon > 0:
if not FLAG: # the FIRST intersection of this chain
start_with = bed_num # guarantee that I will assign to starts with
# only the FIRST intersection (if it took place)
FLAG = True # otherwise starts with will be preserved
# save the intersection
bed_overlaps[exon[2]] += block_vs_exon
else: # we recorded all the region with intersections
if block[0] > exon[1]: # too early
# in case like:
# gene A EEEEE----------------------------------------EEEEEE #
# gene B EEEEEEEEEE #
# gene C EEEEEEEEE #
# chain ccccc #
# at gene A I will get FLAG = True and NO intersection with gene B
# --> I will miss gene C in this case without this condition.
continue
elif FLAG: # this is not a nested gene
break # and all intersections are saved --> proceed to the next chain
# return the required values
return chain_len, bed_overlaps
|
COLUMN_VARIABLES = ['M_t', 'H_t', 'W_t']
RAW_DATA_DIRECTORY = './sample_data'
TRAIN_TEST_SPLIT_VALS = {'test_1':'2017-08-06', 'test_2':'2017-01-15',
'test_3':'2017-05-14', 'test_4':'2016-10-16'}
|
# URI Online Judge 2762
entrada = input().split('.')
saida = str(int(entrada[1])) + '.' + entrada[0]
print(saida) |
dinero=2000
preciodelhelado=100
incrementodelpreciodelhelado=1.20
edad=19
hambrequesatisfaceelhelado=edad
hambresatisfecho=edad
n=0
while (hambresatisfecho<85 and dinero>0):
dinero=dinero-(preciodelhelado)
hambresatisfecho=hambresatisfecho+hambrequesatisfaceelhelado
preciodelhelado=preciodelhelado*incrementodelpreciodelhelado
n=n+1
print("te tienes que comer", n, "helados para llenarte")
print("te queda", dinero, "euros") |
class DisabledFormMixin():
def __init__(self):
for (_, field) in self.fields.items():
field.widget.attrs['disabled'] = True
field.widget.attrs['readonly'] = True
|
{
"targets": [
{
"target_name": "greet",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": [
"./src/cpp/greeting.cpp",
"./src/cpp/count.cpp",
"./src/cpp/custom_object.cpp",
"./src/cpp/index.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
"defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],
}
]
}
|
def get_register_info(registers, register_name):
return registers[register_name].bit_offset
def get_register_location_in_frame_data(registers, register_name, start_word_index=0):
bit_offset = get_register_info(registers, register_name)
word_index = (bit_offset >> 5) - start_word_index
bit_index = bit_offset % 32
return word_index, bit_index
def get_register_value_from_frame_data(registers, register_name, register_width, frame_data, start_word_index=0, fast=False):
value = 0
for i in range(register_width):
if register_width == 1:
name = register_name
else:
name = register_name + '[' + str(i) + ']'
word_index, bit_index = get_register_location_in_frame_data(registers, name, start_word_index)
if fast:
bit_value = ((int(frame_data[word_index], 2) >> bit_index) & 0x1) ^ 0x1
else:
bit_value = ((frame_data[word_index] >> bit_index) & 0x1) ^ 0x1
value = value | (bit_value << i)
return value |
files = [
"midi.vhdl", "midi.ucf", "clock_divider.vhdl", "shift_out.vhdl",
]
|
#
# PySNMP MIB module ENDRUNTECHNOLOGIES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENDRUNTECHNOLOGIES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:02:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Bits, ObjectIdentity, TimeTicks, IpAddress, ModuleIdentity, iso, Counter32, Unsigned32, MibIdentifier, Counter64, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, enterprises, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "ObjectIdentity", "TimeTicks", "IpAddress", "ModuleIdentity", "iso", "Counter32", "Unsigned32", "MibIdentifier", "Counter64", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "enterprises", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
endRunTechnologiesMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 13827))
endRunTechnologies = ModuleIdentity((1, 3, 6, 1, 4, 1, 13827, 0))
if mibBuilder.loadTexts: endRunTechnologies.setLastUpdated('0208190000Z')
if mibBuilder.loadTexts: endRunTechnologies.setOrganization('EndRun Technologies LLC')
if mibBuilder.loadTexts: endRunTechnologies.setContactInfo('Technical Support 1-877-749-3878 snmpsupport@endruntechnologies.com')
if mibBuilder.loadTexts: endRunTechnologies.setDescription('EndRun Technologies Enterprise MIB')
praecisCntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1))
cntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 0))
cntptrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0))
cdma = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 1))
cdmatrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0))
cntpTrapLeapIndBitsChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cntpLeapIndBits"))
if mibBuilder.loadTexts: cntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts: cntpTrapLeapIndBitsChange.setDescription('A cntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included cntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
cntpTrapStratumChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 0, 0, 2)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cntpStratum"))
if mibBuilder.loadTexts: cntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts: cntpTrapStratumChange.setDescription('A cntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, cntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
cntpRxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpRxPkts.setStatus('current')
if mibBuilder.loadTexts: cntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
cntpTxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpTxPkts.setStatus('current')
if mibBuilder.loadTexts: cntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
cntpIgnoredPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts: cntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
cntpDroppedPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts: cntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
cntpAuthFail = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpAuthFail.setStatus('current')
if mibBuilder.loadTexts: cntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
cntpTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: cntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with CDMA the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cntpLeapIndBits = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("noFaultorLeap", 0), ("leapInsWarning", 1), ("leapDelWarning", 2), ("unSynchronized", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts: cntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to cntpLeapIndBits.')
cntpSyncSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpSyncSource.setStatus('current')
if mibBuilder.loadTexts: cntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of CDMA, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is free running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to cntpSyncSource if it is CDMA. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
cntpOffsetToCDMAReference = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpOffsetToCDMAReference.setStatus('current')
if mibBuilder.loadTexts: cntpOffsetToCDMAReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the CDMA reference time. Positive values imply that the NTP server clock is ahead of the CDMA reference time.')
cntpStratum = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 11, 16))).clone(namedValues=NamedValues(("cntpStratumOne", 1), ("cntpStratumFlywheeling", 11), ("cntpStratumUnsync", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpStratum.setStatus('current')
if mibBuilder.loadTexts: cntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
cntpVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 0, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cntpVersion.setStatus('current')
if mibBuilder.loadTexts: cntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
cdmaTrapFaultStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 1, 1, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "cdmaFaultStatus"))
if mibBuilder.loadTexts: cdmaTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts: cdmaTrapFaultStatusChange.setDescription('A cdmaTrapFaultStatusChange trap signifies that the value of the fault status word reported by the CDMA sub-system has changed. The current value is contained in the included cdmaFaultStatus.')
cdmaFaultStatus = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 1), Bits().clone(namedValues=NamedValues(("cdmaNotUsed", 0), ("cdmaNTPNotPolling", 1), ("cdmaLOFailure", 2), ("cdmaLOPLLFlt", 3), ("cdmaFLASHWriteFlt", 4), ("cdmaFPGACfgFlt", 5), ("cdmaNoSignalTimeout", 6), ("cdmaDACNearLimit", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFaultStatus.setStatus('current')
if mibBuilder.loadTexts: cdmaFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the CDMA fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the cdmastat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Local Oscillator PLL fault. Bit 2: Local Oscillator PLL failed. Bit 1: NTP daemon is not polling the CDMA reference clock. Bit 0: Not Used.")
cdmaTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: cdmaTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 6 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 6 and implies a worst case time error of 100 microseconds. During periods of signal loss, the CDMA sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
cdmaSigProcState = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 4, 8))).clone(namedValues=NamedValues(("cdmaAcquiring", 0), ("cdmaDetected", 1), ("cdmaCodeLocking", 2), ("cdmaCarrierLocking", 4), ("cdmaLocked", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaSigProcState.setStatus('current')
if mibBuilder.loadTexts: cdmaSigProcState.setDescription('Current CDMA signal processor state. One of 0, 1, 2, 4 or 8, with 0 indicating the acquisition state and 8 the fully locked on state.')
cdmaChannel = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("priAbandclass0subclass0", 0), ("priBbandclass0subclass0", 1), ("secAbandclass0subclass0", 2), ("secBbandclass0subclass0", 3), ("priAbandclass0subclass1", 4), ("priBbandclass0subclass1", 5), ("secAbandclass0subclass1", 6), ("secBbandclass0subclass1", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaChannel.setStatus('current')
if mibBuilder.loadTexts: cdmaChannel.setDescription('Current CDMA frequency band and channel being used. Channels 0-3 are the North American cellular channels. Channels 4-7 are the South Korean cellular channels.')
cdmaPNO = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 511))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaPNO.setStatus('current')
if mibBuilder.loadTexts: cdmaPNO.setDescription('Current Pseudo Noise Offset of the base station being tracked. The value ranges from 0 to 511 and is in units of 64 Pseudo Noise Code chips. This offset serves as a base station identifier that is analogous to the Pseudo Random Noise (PRN) codes used by the individual satellites in the GPS system.')
cdmaAGC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaAGC.setStatus('current')
if mibBuilder.loadTexts: cdmaAGC.setDescription('Current 8 bit, Automatic Gain Control (AGC) DAC value. Typical values are around 200, but proximity to the base station, type of building construction and orientation within the building have a strong influence on this value. More positive values have the effect of increasing the RF gain.')
cdmaVCDAC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaVCDAC.setStatus('current')
if mibBuilder.loadTexts: cdmaVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
cdmaCarrierToNoiseRatio = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaCarrierToNoiseRatio.setStatus('current')
if mibBuilder.loadTexts: cdmaCarrierToNoiseRatio.setDescription('ASCII string representing the current received CDMA signal carrier-to-noise ratio, a unitless quantity. Numbers less than 2.5 indicate a very weak signal condition.')
cdmaFrameErrorRate = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFrameErrorRate.setStatus('current')
if mibBuilder.loadTexts: cdmaFrameErrorRate.setDescription('ASCII string representing the current sync channel message error rate, a number ranging from 0.000 to 1.000. It indicates the proportion of messages received that fail the Cyclical Redundancy Check.')
cdmaLeapMode = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaLeapMode.setStatus('current')
if mibBuilder.loadTexts: cdmaLeapMode.setDescription('ASCII string showing the current leap second mode of operation for the CDMA sub-system. It is either AUTO or USER. If the mode is USER, then the current and future values of the UTC to GPS leap second offset is also included.')
cdmaCurrentLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 11), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: cdmaCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
cdmaFutureLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 12), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: cdmaFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
cdmaVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 1, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdmaVersion.setStatus('current')
if mibBuilder.loadTexts: cdmaVersion.setDescription('ASCII string showing the CDMA sub-system firmware and FPGA versions.')
praecisGntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2))
gntp = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 0))
gntptrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0))
gps = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 1))
gpstrap = MibIdentifier((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0))
gntpTrapLeapIndBitsChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gntpLeapIndBits"))
if mibBuilder.loadTexts: gntpTrapLeapIndBitsChange.setStatus('current')
if mibBuilder.loadTexts: gntpTrapLeapIndBitsChange.setDescription('A gntpTrapNTPLeapIndBitsChange trap signifies that the value of the leap indicator bits contained in the NTP reply packets sent by the time server has changed. The current value of these bits is contained in the included gntpLeapIndBits. The decimal value of these bits ranges from 0 to 3: 0 is the no fault, no leap warning condition 1 is the no fault, leap second insertion warning condition 2 is the no fault, leap second deletion warning condition 3 is the unsynchronized, alarm condition')
gntpTrapStratumChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 0, 0, 2)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gntpStratum"))
if mibBuilder.loadTexts: gntpTrapStratumChange.setStatus('current')
if mibBuilder.loadTexts: gntpTrapStratumChange.setDescription('A gntpTrapStratumChange trap signifies that the value of the stratum field contained in the NTP reply packets sent by the time server has changed. The current value is contained in the included variable, gntpStratum. The decimal value of this field ranges from 1 to 16: 1 is the synchronized, actively locked to the reference UTC source stratum 11 is the synchronized, but flywheeling on the local real time clock stratum 16 is the unsynchronized stratum level')
gntpRxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpRxPkts.setStatus('current')
if mibBuilder.loadTexts: gntpRxPkts.setDescription('Total number of NTP request packets received by the NTP daemon.')
gntpTxPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpTxPkts.setStatus('current')
if mibBuilder.loadTexts: gntpTxPkts.setDescription('Total number of NTP reply packets transmitted by the NTP daemon.')
gntpIgnoredPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpIgnoredPkts.setStatus('current')
if mibBuilder.loadTexts: gntpIgnoredPkts.setDescription('Total number of NTP request packets ignored by the NTP daemon.')
gntpDroppedPkts = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpDroppedPkts.setStatus('current')
if mibBuilder.loadTexts: gntpDroppedPkts.setDescription('Total number of NTP request packets dropped by the NTP daemon.')
gntpAuthFail = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpAuthFail.setStatus('current')
if mibBuilder.loadTexts: gntpAuthFail.setDescription('Total number of authentication failures detected by the NTP daemon.')
gntpTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan1us", 4), ("lessthan10us", 5), ("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: gntpTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation with GPS the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gntpLeapIndBits = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("noFaultorLeap", 0), ("leapInsWarning", 1), ("leapDelWarning", 2), ("unSynchronized", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpLeapIndBits.setStatus('current')
if mibBuilder.loadTexts: gntpLeapIndBits.setDescription('This is a status code indicating: normal operation, a leap second to be inserted in the last minute of the current day, a leap second to be deleted in the last second of the day or an alarm condition indicating loss of timing synchronization. The leap indicator field of NTP reply packets sent from this server is set to gntpLeapIndBits.')
gntpSyncSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpSyncSource.setStatus('current')
if mibBuilder.loadTexts: gntpSyncSource.setDescription('This is an ASCII string identifying the synchronization source for this NTP server. It is one of GPS, CPU or NONE. If it is NONE, then the server is not synchronized, has its Leap Indicator Bits in the Alarm state and is running at Stratum 16. If it is CPU, then the server is running on its NTP disciplined CPU clock at Stratum 11. Check the Stratum, Leap Indicator Bits and Time Figure of Merit for further information. NTP reply packets from this server will have the reference identifier field set to gntpSyncSource if it is GPS. Otherwise it will be set to either 127.127.1.0 (CPU) or 0.0.0.0 (NONE).')
gntpOffsetToGPSReference = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpOffsetToGPSReference.setStatus('current')
if mibBuilder.loadTexts: gntpOffsetToGPSReference.setDescription('This is an ASCII string containing the floating value of the current offset in units of seconds of the NTP server CPU clock to the GPS reference time. Positive values imply that the NTP server clock is ahead of the GPS reference time.')
gntpStratum = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 11, 16))).clone(namedValues=NamedValues(("gntpStratumOne", 1), ("gntpStratumFlywheeling", 11), ("gntpStratumUnsync", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpStratum.setStatus('current')
if mibBuilder.loadTexts: gntpStratum.setDescription('This is an integer showing the current stratum level being reported by the NTP daemon in its reply packets to clients. If it is 1, then the server is fully synchronized and delivering Stratum 1 accuracy. If it is 16, then the server is unambiguously unsynchronized. If it is 11, and the previous stratum value was 1, then the server is flywheeling on the local CPU clock. However, if the previous stratum value was 16, then the server has synchronized to its CPU Real Time Clock. NTP clients on the network should be configured to not use the time from this server if the stratum is not 1.')
gntpVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 0, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gntpVersion.setStatus('current')
if mibBuilder.loadTexts: gntpVersion.setDescription('This is an ASCII string showing the NTP server firmware version.')
gpsTrapFaultStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 13827, 2, 1, 0, 1)).setObjects(("ENDRUNTECHNOLOGIES-MIB", "gpsFaultStatus"))
if mibBuilder.loadTexts: gpsTrapFaultStatusChange.setStatus('current')
if mibBuilder.loadTexts: gpsTrapFaultStatusChange.setDescription('A gpsTrapFaultStatusChange trap signifies that the value of the fault status word reported by the GPS sub-system has changed. The current value is contained in the included gpsFaultStatus.')
gpsFaultStatus = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 1), Bits().clone(namedValues=NamedValues(("gpsAntennaFlt", 0), ("gpsNTPNotPolling", 1), ("gpsnotused0", 2), ("gpsnotused1", 3), ("gpsFLASHWriteFlt", 4), ("gpsFPGACfgFlt", 5), ("gpsNoSignalTimeout", 6), ("gpsDACNearLimit", 7)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsFaultStatus.setStatus('current')
if mibBuilder.loadTexts: gpsFaultStatus.setDescription("This is a bit string contained in one character representing the least significant two nibbles of the GPS fault status word. Unfortunately, SNMP numbers the bits in the reverse order, so that the enumerated values are backwards from the description contained in the User's Manual for the fault status field returned by the gpsstat command. Each bit indicates a fault when set. Currently defined fault states encoded in this value: Bit 7: DAC controlling the TCXO is near the high or low limit. Bit 6: Time Figure of Merit has been 9 (unsynchronized) for 1 hour. Bit 5: Field Programmable Gate Array (FPGA) did not configure properly. Bit 4: FLASH memory had a write fault. Bit 3: Not Used. Bit 2: Not Used. Bit 1: NTP daemon is not polling the GPS reference clock. Bit 0: GPS antenna or feedline is shorted or open.")
gpsTimeFigureOfMerit = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("lessthan1us", 4), ("lessthan10us", 5), ("lessthan100us", 6), ("lessthan1ms", 7), ("lessthan10ms", 8), ("greaterthan10ms", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsTimeFigureOfMerit.setStatus('current')
if mibBuilder.loadTexts: gpsTimeFigureOfMerit.setDescription('The Time Figure of Merit (TFOM) value ranges from 4 to 9 and indicates the current estimate of the worst case time error. It is a logarithmic scale, with each increment indicating a tenfold increase in the worst case time error boundaries. The scale is referenced to a worst case time error of 100 picoseconds, equivalent to a TFOM of zero. During normal locked operation the TFOM is 4 and implies a worst case time error of 1 microsecond. During periods of signal loss, the GPS sub-system will compute an extrapolated worst case time error. One hour after the worst case time error has reached the value equivalent to a TFOM of 9, the NTP server will cease to send stratum 1 reply packets and an Alarm LED will be energized.')
gpsSigProcState = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("gpsAcquiring", 0), ("gpsLocking", 1), ("gpsLocked", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsSigProcState.setStatus('current')
if mibBuilder.loadTexts: gpsSigProcState.setDescription('Current GPS signal processor state. One of 0, 1 or 2, with 0 being the acquisition state and 2 the fully locked on state.')
gpsNumTrackSats = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsNumTrackSats.setStatus('current')
if mibBuilder.loadTexts: gpsNumTrackSats.setDescription('Current number of GPS satellites being tracked.')
gpsVCDAC = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsVCDAC.setStatus('current')
if mibBuilder.loadTexts: gpsVCDAC.setDescription('Current 16 bit, Voltage Controlled TCXO DAC value. Typical range is 20000 to 40000, where more positive numbers have the effect of raising the TCXO frequency.')
gpsAvgCarrierToNoiseRatiodB = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsAvgCarrierToNoiseRatiodB.setStatus('current')
if mibBuilder.loadTexts: gpsAvgCarrierToNoiseRatiodB.setDescription('ASCII string representing the current average carrier to noise ratio of all tracked satellites, in units of dB. Values less than 35 indicate weak signal conditions.')
gpsReferencePosition = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsReferencePosition.setStatus('current')
if mibBuilder.loadTexts: gpsReferencePosition.setDescription('WGS-84 latitude, longitude and height above the reference ellipsoid of the GPS antenna. Ellipsoid height may deviate from local Mean Sea Level by as much as 100 meters.')
gpsRefPosSource = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 8), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 3))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsRefPosSource.setStatus('current')
if mibBuilder.loadTexts: gpsRefPosSource.setDescription('ASCII string indicating the source of the GPS antenna reference position. It is one of: USR (user supplied), AVG (automatically determined by averaging thousands of 3-D position fixes, UNK (unknown).')
gpsCurrentLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 9), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsCurrentLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: gpsCurrentLeapSeconds.setDescription('This value is the current difference in seconds between GPS time and UTC time. GPS time is ahead of UTC time by this amount.')
gpsFutureLeapSeconds = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsFutureLeapSeconds.setStatus('current')
if mibBuilder.loadTexts: gpsFutureLeapSeconds.setDescription('This value is the future difference in seconds between GPS time and UTC time. Leap seconds may be inserted or deleted from the UTC timescale twice during the year: Dec 31 and June 30 at UTC midnight. If this value is the same as cdmaCurrentLeapSeconds, then no leap second insertion or deletion will occur at the next possible time. If it is different, then the change will take affect at the next possible time. GPS time will be ahead of UTC time by this amount.')
gpsVersion = MibScalar((1, 3, 6, 1, 4, 1, 13827, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: gpsVersion.setStatus('current')
if mibBuilder.loadTexts: gpsVersion.setDescription('ASCII string showing the GPS sub-system firmware and FPGA versions.')
mibBuilder.exportSymbols("ENDRUNTECHNOLOGIES-MIB", cntptrap=cntptrap, cntpDroppedPkts=cntpDroppedPkts, cdmaSigProcState=cdmaSigProcState, cdmaAGC=cdmaAGC, cdmaFutureLeapSeconds=cdmaFutureLeapSeconds, cntpAuthFail=cntpAuthFail, cdmaCurrentLeapSeconds=cdmaCurrentLeapSeconds, gntpIgnoredPkts=gntpIgnoredPkts, cdmaFaultStatus=cdmaFaultStatus, gpsAvgCarrierToNoiseRatiodB=gpsAvgCarrierToNoiseRatiodB, cdmaTimeFigureOfMerit=cdmaTimeFigureOfMerit, gntpVersion=gntpVersion, cdmaTrapFaultStatusChange=cdmaTrapFaultStatusChange, gpsReferencePosition=gpsReferencePosition, gpsFaultStatus=gpsFaultStatus, cdmatrap=cdmatrap, gntp=gntp, cntpTimeFigureOfMerit=cntpTimeFigureOfMerit, cdmaCarrierToNoiseRatio=cdmaCarrierToNoiseRatio, cdmaFrameErrorRate=cdmaFrameErrorRate, gntpTrapStratumChange=gntpTrapStratumChange, praecisGntp=praecisGntp, gntpLeapIndBits=gntpLeapIndBits, gntpRxPkts=gntpRxPkts, gntpTxPkts=gntpTxPkts, cdmaVCDAC=cdmaVCDAC, gntpOffsetToGPSReference=gntpOffsetToGPSReference, cntpIgnoredPkts=cntpIgnoredPkts, gntpTrapLeapIndBitsChange=gntpTrapLeapIndBitsChange, gntpDroppedPkts=gntpDroppedPkts, cntpStratum=cntpStratum, gntpStratum=gntpStratum, cntpOffsetToCDMAReference=cntpOffsetToCDMAReference, gpsSigProcState=gpsSigProcState, cdmaLeapMode=cdmaLeapMode, gpsRefPosSource=gpsRefPosSource, gntpSyncSource=gntpSyncSource, gpsVCDAC=gpsVCDAC, gpsNumTrackSats=gpsNumTrackSats, cntpTrapLeapIndBitsChange=cntpTrapLeapIndBitsChange, endRunTechnologiesMIB=endRunTechnologiesMIB, cdmaPNO=cdmaPNO, endRunTechnologies=endRunTechnologies, gntpAuthFail=gntpAuthFail, cntpSyncSource=cntpSyncSource, gpsCurrentLeapSeconds=gpsCurrentLeapSeconds, praecisCntp=praecisCntp, cntp=cntp, cntpRxPkts=cntpRxPkts, gntptrap=gntptrap, gpstrap=gpstrap, cdma=cdma, cntpVersion=cntpVersion, cntpTxPkts=cntpTxPkts, cntpLeapIndBits=cntpLeapIndBits, cdmaChannel=cdmaChannel, cdmaVersion=cdmaVersion, gpsTrapFaultStatusChange=gpsTrapFaultStatusChange, gpsFutureLeapSeconds=gpsFutureLeapSeconds, gntpTimeFigureOfMerit=gntpTimeFigureOfMerit, cntpTrapStratumChange=cntpTrapStratumChange, PYSNMP_MODULE_ID=endRunTechnologies, gps=gps, gpsVersion=gpsVersion, gpsTimeFigureOfMerit=gpsTimeFigureOfMerit)
|
def max_pairwise_product(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def max_pairwise_product_Fast(numbers):
n = len(numbers)
max_index1 = -1
for i in range(n):
if (max_index1 == -1) | (numbers[i] > numbers[max_index1]):
max_index1 = i
max_index2 = -1
for j in range(n):
if (j != max_index1) & ((max_index2 == -1) | (numbers[j] > numbers[max_index2])):
max_index2 = j
return ((numbers[max_index1])) * numbers[max_index2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product_Fast(input_numbers))
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage provides tools for reading and writing CRTF (CASA Region
Text Format) region files.
"""
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# [公共] API 启动环境
RUN_MODE = "__BKDATA_RUN_MODE__" # PRODUCT/DEVELOP
RUN_VERSION = "__BKDATA_RUN_VERSION__"
# [专属] 项目部署相关信息
pizza_port = __BKDATA_RESOURCECENTERAPI_PORT__
BIND_IP_ADDRESS = "__BKDATA_RESOURCECENTERAPI_HOST__"
APP_NAME = 'resourcecenter'
# [公共] 其他模块 API 参数
AUTH_API_HOST = "__BKDATA_AUTHAPI_HOST__"
AUTH_API_PORT = __BKDATA_AUTHAPI_PORT__
ACCESS_API_HOST = "__BKDATA_ACCESSAPI_HOST__"
ACCESS_API_PORT = __BKDATA_ACCESSAPI_PORT__
DATABUS_API_HOST = "__BKDATA_DATABUSAPI_HOST__"
DATABUS_API_PORT = __BKDATA_DATABUSAPI_PORT__
DATAFLOW_API_HOST = "__BKDATA_DATAFLOWAPI_HOST__"
DATAFLOW_API_PORT = __BKDATA_DATAFLOWAPI_PORT__
DATAMANAGE_API_HOST = "__BKDATA_DATAMANAGEAPI_HOST__"
DATAMANAGE_API_PORT = __BKDATA_DATAMANAGEAPI_PORT__
DATAQUERY_API_HOST = "__BKDATA_DATAQUERYAPI_HOST__"
DATAQUERY_API_PORT = __BKDATA_DATAQUERYAPI_PORT__
JOBNAVI_API_HOST = "__BKDATA_JOBNAVIAPI_HOST__"
JOBNAVI_API_PORT = __BKDATA_JOBNAVIAPI_PORT__
META_API_HOST = "__BKDATA_METAAPI_HOST__"
META_API_PORT = __BKDATA_METAAPI_PORT__
STOREKIT_API_HOST = "__BKDATA_STOREKITAPI_HOST__"
STOREKIT_API_PORT = __BKDATA_STOREKITAPI_PORT__
TDW_API_HOST = "__BKDATA_TDWAPI_HOST__"
TDW_API_PORT = __BKDATA_TDWAPI_PORT__
RESOURCECENTER_API_HOST = "__BKDATA_RESOURCECENTERAPI_HOST__"
RESOURCECENTER_API_PORT = __BKDATA_RESOURCECENTERAPI_PORT__
# [公共] 第三方系统 URL
CC_API_URL = "http://__PAAS_FQDN__/component/compapi/cc/"
JOB_API_URL = "http://__PAAS_FQDN__/component/compapi/job/"
TOF_API_URL = "http://__PAAS_FQDN__/component/compapi/tof/"
SMCS_API_URL = "http://__PAAS_FQDN__/component/compapi/smcs/"
GSE_API_URL = "http://__PAAS_FQDN__/component/compapi/gse/"
CMSI_API_URL = "http://__PAAS_FQDN__/component/compapi/cmsi/"
BK_LOGIN_API_URL = "http://__PAAS_HOST__:__PAAS_HTTP_PORT__/api/c/compapi/v2/bk_login/"
ES_LOG_API_URL = "http://__LOG_SEARCH__"
# [公共] 运行时区设置
TIME_ZONE = '__BK_TIMEZONE__'
# PaaS注册之后生成的APP_ID, APP_TOKEN, BK_PAAS_HOST
APP_ID = "__APP_CODE__"
APP_TOKEN = "__APP_TOKEN__"
BK_PAAS_HOST = "http://__PAAS_HOST__:__PAAS_HTTP_PORT__"
SECRET_KEY = "__DJANGO_SECRET_KEY__"
# [公共] 加解密配置
CRYPT_INSTANCE_KEY = "__CRYPT_INSTANCE_KEY__"
CRYPT_ROOT_KEY = "__BKDATA_ROOT_KEY__"
CRYPT_ROOT_IV = "__BKDATA_ROOT_IV__"
# [可选] MYSQL01 配置,提供给数据集成「基础版」使用
CONFIG_DB_HOST = "__MYSQL_DATAHUB_IP0__"
CONFIG_DB_PORT = __MYSQL_DATAHUB_PORT__
CONFIG_DB_USER = "__MYSQL_DATAHUB_USER__"
CONFIG_DB_PASSWORD = "__MYSQL_DATAHUB_PASS__"
# [专属] resourcecenter api 配置
# 资源系统运营数据存储的类型
RESOURCE_CENTER_METRIC_STORAGE_TYPE = "mysql"
# 存储集群可以采集的类型
RESOURCE_CENTER_COLLECT_STORAGE_TYPES = ["hdfs", "tspider", "es", "druid", "hermes", "clickhouse"]
# 存储集群的运营数据结果RT
STORAGE_METRIC_DATA_RT = '591_resource_storage_metrics_1h_batch'
# 计算资源可以采集的集群类型
RESOURCE_CENTER_COLLECT_PROCESSING_CLUSTER_TYPES = ['flink-yarn-session', 'flink-yarn-cluster', 'spark']
# 计算集群队列名名规则模板
PROCESSING_CLUSTER_QUEUE_TEMPLATE = {
'flink-yarn-session': "root.dataflow.stream.{cluster_group_id}.session",
'flink-yarn-cluster': "root.dataflow.stream.{cluster_group_id}.cluster",
'spark': "root.dataflow.batch.{cluster_group_id}",
}
# 计算集群队列名类型
YARN_QUEUE_TYPE = "yarn"
K8S_QUEUE_TYPE = "k8s"
PROCESSING_CLUSTER_QUEUE_TYPE = {
'flink-yarn-session': YARN_QUEUE_TYPE,
'flink-yarn-cluster': YARN_QUEUE_TYPE,
'spark': YARN_QUEUE_TYPE,
'k8s-cluster': K8S_QUEUE_TYPE,
}
SPARK_JOB_CLUSTER_TYPES = ['spark']
SPARK_APPLICATION_TYPE = 'SPARK'
FLINK_JOB_CLUSTER_TYPES = ['flink-yarn-session', 'flink-yarn-cluster']
FLINK_APPLICATION_TYPE = "Apache Flink"
YARN_APPLICATION_TYPES = [SPARK_APPLICATION_TYPE, FLINK_APPLICATION_TYPE]
# k8s api url
K8S_RESOURCE_QUOTA_URL = "{cluster_domain}/api/v1/namespaces/{cluster_name}/resourcequotas/{cluster_name}"
K8S_METRICS_URL = "{cluster_domain}/apis/metrics.k8s.io/v1beta1/namespaces/{cluster_name}/pods"
# 计算集群统计任务的窗口长度
PROCESSING_METRIC_CALCULATION_WINDOW_LENGTH = 3600
# 计算集群的运营数据结果RT
PROCESSING_METRIC_DATA_RT = "591_resource_processing_capacity_clean"
# 默认查询结果集大小限制
DEFAULT_RESULT_SET_LIMIT = 100
# 任务提交记录最小保存时间(单位:天)
MINIMUM_JOB_SUBMIT_RECORD_KEEP_TIME_DAY = 15
DEFAULT_RESOURCE_GROUP_ID = 'default'
|
## Find the prime numbers from 1 - 20
primeCheck = 0
for index in range(2,21):
# print("index values are",index)
for num in range(2,index):
# print("----> num is ",num)
if index%num == 0:
primeCheck = 0
print("Number ",index," not a prime")
break
else:
primeCheck = 1
#print("This is a prime number ",index)
if primeCheck == 1:
print("This is a prime number ",index) |
class _AVLNode():
_BALANCE_FACTOR_LIMIT = 2;
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.size = 1
self._height = 0
self._balance_factor = 0
def search(self, key):
if key == self.value:
return self
elif key < self.value:
return self.left.search(key) if self._has_left_child() else None
else:
return self.right.search(key) if self._has_right_child() else None
def insert(self, value):
if value == self.value:
new_height = self._height
elif value < self.value:
if self.left is None:
self.left = _AVLNode(value)
new_height = max(self._height, 1)
else:
self.left = self.left.insert(value)
new_height = (max(self._height, self.left._height + 1)
if self._has_left_child()
else self._height)
else:
if self.right is None:
self.right = _AVLNode(value)
new_height = max(self._height, 1)
else:
self.right = self.right.insert(value)
new_height = (max(self._height, self.right._height + 1)
if self._has_right_child()
else self._height)
self._height = new_height
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
else:
new_subtree_root = self
self.size = self._recalculate_size()
return new_subtree_root
def delete(self, value):
new_subtree_root = self
if value < self.value:
self.left = (self.left.delete(value)
if self.left is not None
else None)
elif value > self.value:
self.right = (self.right.delete(value)
if self.right is not None
else None)
elif self._has_two_children():
self.value = self.right._min().value
self.right = self.right.delete(self.value)
else:
new_subtree_root = (self.left
if self.left is not None
else self.right)
self._height = self._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
if self._needs_rebalancing():
new_subtree_root = self._rebalance()
self.size = self._recalculate_size()
return new_subtree_root
def _min(self):
return self.left._min() if self._has_left_child() else self
def _needs_rebalancing(self):
return abs(self._balance_factor) >= _AVLNode._BALANCE_FACTOR_LIMIT
def _calculate_balance_factor(self):
right_subtree_height = (self.right._height
if self._has_right_child()
else -1)
left_subtree_height = (self.left._height
if self._has_left_child()
else -1)
return right_subtree_height - left_subtree_height
def _rebalance(self):
if self.right is None:
tallest_child = self.left
elif self.left is None:
tallest_child = self.right
else:
tallest_child = (self.right
if self.right._height > self.left._height
else self.left)
if tallest_child is self.left:
if tallest_child._is_right_heavy(): # Left-Right
return (self._rotate_right(
tallest_child._rotate_left(tallest_child.right)))
else: # Left-Left
return self._rotate_right(tallest_child)
elif tallest_child is self.right:
if tallest_child._is_left_heavy(): # Right-Left
return (self._rotate_left(
tallest_child._rotate_right(tallest_child.left)))
else: # Right-Right
return self._rotate_left(tallest_child)
def _rotate_left(self, pivot):
self.right = pivot.left
pivot.left = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _rotate_right(self, pivot):
self.left = pivot.right
pivot.right = self
self._height = self._recalculate_height()
pivot._height = pivot._recalculate_height()
self._balance_factor = self._calculate_balance_factor()
pivot.balance_factor = pivot._calculate_balance_factor()
self.size = self._recalculate_size()
pivot.size = pivot._recalculate_size()
return pivot
def _recalculate_height(self):
return max(self.left._height if self._has_left_child() else -1,
self.right._height if self._has_right_child() else -1) + 1
def _recalculate_size(self):
size = 1
if self._has_left_child():
size += self.left.size
if self._has_right_child():
size += self.right.size
return size
def _has_two_children(self):
return self._has_left_child() and self._has_right_child()
def _has_left_child(self):
return self.left is not None
def _has_right_child(self):
return self.right is not None
def _is_right_heavy(self):
return self._balance_factor > 0
def _is_left_heavy(self):
return self._balance_factor < 0
|
#
# lithospheres
#
# =============================================================================
lith200 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,45e3,45e3,75e3,400e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith250 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,160e3,0.0e0,350e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith240 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,150e3,0.0e0,360e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith280 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,80e3,10e3,155e3,320e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith160 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,55e3,70e3,0.0e0,440e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith180 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,45e3,45e3,55e3,420e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.78e-6
},
"matMC": {
"H": 1.78e-6
},
"matLC": {
"H": 0.82e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 12.4460937e-3
}
}
# =============================================================================
lith120 = {
"numlayers": 6,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matSLM'],
"thicknesses": [15e3,10e3,10e3,85.0e3,0.0e0,480e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.2e-6
},
"matMC": {
"H": 1.2e-6
},
"matLC": {
"H": 0.473e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 20.59375e-3
}
}
# =============================================================================
lith125 = {
"numlayers": 7,
"nature_layers": ['matUC','matMC','matLC','matLM1','matLM2','matLM3','matSLM'],
"thicknesses": [15e3,10e3,10e3,90e3,0.0e0,0.0e0,475e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcLM1','thermBcLM2','thermBcLM3','thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H": 1.299e-6
},
"matMC": {
"H": 1.299e-6
},
"matLC": {
"H": 0.498e-6
},
"matLM1": {
"rho": 3300
},
"matLM2": {
"rho": 3300
},
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 19.5e-3
}
}
# =============================================================================
ridge_NoOc_NoDiffLayer = {
"numlayers": 1,
"nature_layers": ['matSLM'],
"thicknesses": [600e3],
"thermalBc": ['thermBcSLM'],
"matSLM": {
"rho": 3300
},
"thermBcSLM": {
"temp_top": 0.0e0,
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 19.5e-3
}
}
# =============================================================================
ridge_Oc6_5_NoDiffLayer = {
"numlayers": 5,
"nature_layers": ['matUC','matMC','matLC','matSLMd','matSLM'],
"thicknesses": [6.5e3, 0.0e0, 0.0e0, 118.5e3, 475.0e3],
"thermalBc": ['thermBcUC','thermBcMC','thermBcLC','thermBcSLMd', 'thermBcSLM'],
"matUC": {
"temp_top": 0.0e0,
"H" : 0.0e0,
"rho": 2900.e0
},
"matMC": {
"H": 0.0e0,
"rho": 2900.e0
},
"matLC": {
"H": 0.0e0,
"rho": 2900.e0
},
"matSLMd": {
"rho": 3300,
"H": 0.0e0
},
"matSLM": {
"rho": 3300
},
"thermBcSLMd": {
"temp_bottom": 1603.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 437.2421875e-3
},
"thermBcSLM": {
"temp_bottom": 1793.15e0,
"temp_potential": 1553.15e0,
"q_bottom": 437.2421875e-3
}
}
|
def solution(A):
refSum = len(A) + 1
curSum = 0
for i in range(0, len(A)):
refSum += i + 1
curSum += A[i]
return refSum - curSum
assert 1 == solution([])
assert 2 == solution([ 1 ])
assert 1 == solution([ 2 ])
assert 4 == solution([ 2, 3, 1, 5 ])
MaxArrSize = 100000 # by the task
stressTestArr = []
for i in range(MaxArrSize):
stressTestArr.append(i + 1)
assert MaxArrSize + 1 == solution(stressTestArr)
|
class Punto2D():
def __init__(self, x, y) -> None:
self.x = x
self.y = y
def traslacion(self, a, b):
punto = [self.x + a, self.y + b]
print(punto)
|
# encoding: utf-8
SECRET_KEY='JACK_ZH' # session key
TITLE='zWiki' # wiki title
CONTENT_DIR="markdown" # wiki(blog) save file dir
USER_CONFIG_DIR="content" # ...
PRIVATE=False # logout edit del ... flag
SHOWPRIVATE=False # logout show flag
UPLOAD_DIR="./static/upload"
# from 畅言: http://changyan.sohu.com/install/code/pc
SOHUCS_APPID = "cyrE7gU83"
SOHUCS_CONF = "prod_1f3b1e3a86d5da44e0295ab22fb27033" |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
ans = []
dfs = [[root,0]]
while dfs:
cur,i = dfs.pop()
if i >= len(ans): ans.append(0)
ans[i] += cur.val
if cur.left: dfs.append([cur.left,i+1])
if cur.right: dfs.append([cur.right,i])
return ans
|
dataset_type = 'UnconditionalImageDataset'
train_pipeline = [
dict(
type='LoadImageFromFile',
key='real_img',
io_backend='disk',
),
dict(type='Resize', keys=['real_img'], scale=(512, 384)),
dict(
type='NumpyPad',
keys=['real_img'],
padding=((64, 64), (0, 0), (0, 0)),
),
dict(type='Flip', keys=['real_img'], direction='horizontal'),
dict(
type='Normalize',
keys=['real_img'],
mean=[127.5] * 3,
std=[127.5] * 3,
to_rgb=False),
dict(type='ImageToTensor', keys=['real_img']),
dict(type='Collect', keys=['real_img'], meta_keys=['real_img_path'])
]
# `samples_per_gpu` and `imgs_root` need to be set.
data = dict(
samples_per_gpu=None,
workers_per_gpu=4,
train=dict(
type='RepeatDataset',
times=5,
dataset=dict(
type=dataset_type, imgs_root=None, pipeline=train_pipeline)),
val=dict(type=dataset_type, imgs_root=None, pipeline=train_pipeline))
|
__all__ = ['FirankaError', 'NotInDomainError', 'DomainError']
class FirankaError(Exception):
"""
Base class for firanka's exceptions
"""
class DomainError(FirankaError, ValueError):
"""Has something to do with the domain :)"""
class NotInDomainError(DomainError):
"""
Requested index is beyond this domain
"""
def __init__(self, index, domain, *args, **kwargs):
super().__init__(u'NotInDomainError: %s not in %s' % (index, domain), index, domain,
*args, **kwargs)
self.index = index
self.domain = domain
|
id_to_glfunc = {
160: "glAlphaFunc",
161: "GL_ALPHA_TEST",
162: "glBlendFunc",
163: "glBlendEquationSeparate",
164: "GL_BLEND",
165: "glCullFace",
166: "GL_CULL_FACE",
167: "glDepthFunc",
168: "glDepthMask",
169: "GL_DEPTH_TEST",
172: "glColorMask"
}
glBool_options = {
1: "GL_TRUE",
0: "GL_FALSE"
}
glEnable_options = {
1: "glEnable",
0: "glDisable"
}
glBlendFunc_options = {
0x0000: "GL_ZERO",
0x0001: "GL_ONE",
0x0300: "GL_SRC_COLOR",
0x0301: "GL_ONE_MINUS_SRC_COLOR",
0x0302: "GL_SRC_ALPHA",
0x0303: "GL_ONE_MINUS_SRC_ALPHA",
0x0304: "GL_DST_ALPHA",
0x0305: "GL_ONE_MINUS_DST_ALPHA"
}
glBlendEquationSeparate_options = {
0x8006: "GL_FUNC_ADD",
0x800A: "GL_FUNC_SUBTRACT",
0x800B: "GL_FUNC_REVERSE_SUBTRACT",
0x8007: "GL_MIN",
0x8008: "GL_MAX"
}
glCullFace_options = {
0x0404: "GL_FRONT",
0x0405: "GL_BACK",
0x0408: "GL_FRONT_AND_BACK"
}
glComparison_options = {
0x0200: "GL_NEVER",
0x0201: "GL_LESS",
0x0202: "GL_EQUAL",
0x0203: "GL_LEQUAL",
0x0204: "GL_GREATER",
0x0205: "GL_NOTEQUAL",
0x0206: "GL_GEQUAL",
0x0207: "GL_ALWAYS"
}
|
"""Guarde en lista `naturales` los primeros 100 números naturales (desde el 1)
usando el bucle while
"""
i = 1
naturales = list()
while i <= 100:
naturales.append(i)
i = i+1
"""Guarde en `acumulado` una lista con el siguiente patrón:
['1','1 2','1 2 3','1 2 3 4','1 2 3 4 5',...,'...47 48 49 50']
Hasta el número 50.
"""
acumulado = list()
for i in range (1,51,1):
if i > 1:
acumulado.append(acumulado[i-2] + ' ' + str(i))
else:
acumulado.append(str(i))
"""Guarde en `suma100` el entero de la suma de todos los números entre 1 y 100:
"""
suma100 = 0
for i in range(1,101,1):
suma100+=i
"""Guarde en `tabla100` un string con los primeros 10 múltiplos del número 134,
separados por coma, así:
'134,268,...'
"""
tabla100 = ''
for i in range(1,11,1):
tabla100 = tabla100 + ','if (i>1) else tabla100
tabla100 += str (134 * i)
"""Guardar en `multiplos3` la cantidad de números que son múltiplos de 3 y
menores o iguales a 300 en la lista `lista1` que se define a continuación (la lista
está ordenada).
"""
lista1 = [12, 15, 20, 27, 32, 39, 42, 48, 55, 66, 75, 82, 89, 91, 93, 105, 123, 132, 150, 180, 201, 203, 231, 250, 260, 267, 300, 304, 310, 312, 321, 326]
multiplos3 = 0
for numero in (lista1):
if numero >= 300:
break
if numero % 3 == 0:
multiplos3+=1
"""Guardar en `regresivo50` una lista con la cuenta regresiva desde el número
50 hasta el 1, así:
[
'50 49 48 47...',
'49 48 47 46...',
...
'5 4 3 2 1',
'4 3 2 1',
'3 2 1',
'2 1',
'1'
]
"""
regresivo50 = list()
for veces in range (1,51,1):
salida = ''
for numero in range (51-veces,0,-1):
salida += str(numero) + ('' if (numero == 1) else ' ' )
regresivo50.append(salida)
"""Invierta la siguiente lista usando el bucle for y guarde el resultado en
`invertido` (sin hacer uso de la función `reversed` ni del método `reverse`)
"""
lista2 = list(range(1, 70, 5))
invertido = list()
i = 0;
for obj in lista2:
if i > 0:
invertido.insert(0, obj)
else:
invertido.append(obj)
i+=1
"""Guardar en `primos` una lista con todos los números primos desde el 37 al 300
Nota: Un número primo es un número entero que no se puede calcular multiplicando
otros números enteros.
"""
def primo(numero):
for i in range(2,int(numero/2)+1,1):
if numero % i == 0:
return False
return True
primos = list()
for numero in range(37,301,1):
if (primo(numero)):
primos.append(numero)
"""Guardar en `fibonacci` una lista con los primeros 60 términos de la serie de
Fibonacci.
Nota: En la serie de Fibonacci, los 2 primeros términos son 0 y 1, y a partir
del segundo cada uno se calcula sumando los dos anteriores términos de la serie.
[0, 1, 1, 2, 3, 5, 8, ...]
"""
anterior1 = 0
anterior2 = 1
fibonacci = list()
for numero in range (1,61,1):
fibonacci.append(anterior1)
pivot = anterior1
anterior1 = anterior2
anterior2 = pivot + anterior2
"""Guardar en `factorial` el factorial de 30
El factorial (símbolo:!) Significa multiplicar todos los números enteros desde
el 1 hasta el número elegido.
Por ejemplo, el factorial de 5 se calcula así:
5! = 5 × 4 × 3 × 2 × 1 = 120
"""
factorial =1
for i in range (30,1,-1):
factorial*=i
"""Guarde en lista `pares` los elementos de la siguiente lista que esten
presentes en posiciones pares, pero solo hasta la posición 80.
"""
lista3 = [941, 149, 672, 208, 99, 562, 749, 947, 251, 750, 889, 596, 836, 742, 512, 19, 674, 142, 272, 773, 859, 598, 898, 930, 119, 107, 798, 447, 348, 402, 33, 678, 460, 144, 168, 290, 929, 254, 233, 563, 48, 249, 890, 871, 484, 265, 831, 694, 366, 499, 271, 123, 870, 986, 449, 894, 347, 346, 519, 969, 242, 57, 985, 250, 490, 93, 999, 373, 355, 466, 416, 937, 214, 707, 834, 126, 698, 268, 217, 406, 334, 285, 429, 130, 393, 396, 936, 572, 688, 765, 404, 970, 159, 98, 545, 412, 629, 361, 70, 602]
pares = list()
for i in range(0,81,2):
pares.append(lista3[i]);
"""Guarde en lista `cubos` el cubo (potencia elevada a la 3) de los números del
1 al 100.
"""
cubos = list()
for i in range(1,101,1):
cubos.append(i * i * i)
"""Encuentre la suma de la serie 2 +22 + 222 + 2222 + .. hasta sumar 10 términos
y guardar resultado en variable `suma_2s`
"""
suma_2s = 0;
for i in range(1,11,1):
for j in range(0,i,1):
suma_2s += (10**(j))*2
"""Guardar en un string llamado `patron` el siguiente patrón llegando a una
cantidad máxima de asteriscos de 30.
*
**
***
****
*****
******
*******
********
*********
********
*******
******
*****
****
***
**
*
"""
patron = ''
caracteres = '*'
for i in range(0,30,1):
patron+= caracteres +'\n'
caracteres+= '*'
patron += patron[len(patron)-33::-1] |
class Page:
def __init__(browser, fix, driver):
browser.fix = fix
browser.driver = driver
def find_element(browser, *locator):
return browser.fix.driver.find_element(*locator)
def find_elements(browser, *locator):
return browser.fix.driver.find_elements(*locator)
def click(browser, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
def input(browser, text, *locator):
e = browser.fix.driver.find_element(*locator)
e.click()
e.send_keys(text)
|
'''
module for implementation
of Z algorithm for
pattern matching
'''
def z_arr(string: str, z: list):
'''
fills z array for given
string
'''
len_str = len(string)
l, r, k = 0, 0, 0
for i in range (1, len_str):
if (i > r):
l, r = i, i
while (r < len_str and string[r - l] == string[r]):
r += 1
z[i] = r - l
r -= 1
else:
k = i - l
if (z[k] < r - i + 1):
z[i] = z[k]
else:
l = i
while (r < len_str and string[r - l] == string[r]):
r += 1
z[i] = r - l
r -= 1
def z_algorithm(text: str, pattern: str):
'''
returns all occurences
of pattern in the given
text
'''
result = []
concat = pattern + "$" + text
len_con = len(concat)
z = [0] * len_con
z_arr(concat, z)
for i in range (len_con):
if (z[i] == len(pattern)):
result.append(i - len(pattern) - 1)
return result
'''
PyAlgo
Devansh Singh, 2021
''' |
class Solution:
def largestTimeFromDigits(self, A):
"""
:type A: List[int]
:rtype: str
"""
maxtime = ""
for i in range(4):
for j in range(4):
for k in range(4):
if i == j or i == k or k == j:
continue
h = A[i] * 10 + A[j]
m = A[k] * 10 + A[6 - i - j - k]
if 0 <= h < 24 and 0 <= m < 60:
time = "%02d:%02d" % (h, m)
if time > maxtime:
maxtime = time
return maxtime
if __name__ == '__main__':
solution = Solution()
print(solution.largestTimeFromDigits([1,2,3,4]))
print(solution.largestTimeFromDigits([5,5,5,5]))
print(solution.largestTimeFromDigits([0,0,0,0]))
print(solution.largestTimeFromDigits([2,0,6,6]))
print(solution.largestTimeFromDigits([0,2,7,6]))
else:
pass
|
def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Your code here
midIndex = round(len(aStr)/2)
if len(aStr) == 0 or len(aStr) == 1 and char != aStr[0]:
return False
# elif len(aStr) == 1 and char != aStr[0]:
# return False
elif char == aStr[midIndex]:
return True
elif char < aStr[midIndex]:
return isIn(char, aStr[:midIndex])
else:
return isIn(char, aStr[midIndex+1:])
print(isIn('e', 'bcfhhiklnrsvxxy')) |
def tablero_a_cadena(tablero):
cadena = ""
for fila in tablero:
cadena += str(fila) + "\n"
return cadena
def obtener_nombre_pieza(simbolo):
"""
(str) -> str
>>> obtener_nombre_pieza('p')
'Peon blanco'
>>> obtener_nombre_pieza('R')
'Rey Negro'
Retorna el nombre de la pieza del ajedrez dado su simbolo
:param simbolo: la representacion de la pieza segun el enunciado
:return: El nombre y color de la pieza
"""
tipo = 'Negro'
if simbolo.islower():
tipo = 'blanco'
retorno = simbolo.lower()
if retorno == 'p':
return 'Peon '+tipo
elif retorno == 't':
return 'Torre ' + tipo
elif retorno == 'k':
return 'Caballo ' + tipo
elif retorno == 'a':
return 'Alfil ' + tipo
elif retorno == 'q':
return 'Reina ' + tipo
elif retorno == 'r':
return 'Rey ' + tipo
else:
return 'No es una pieza'
def mover_rey(tablero,x_inicial,x_final,y_inicial, y_final):
"""
Funcion que define el movimiento del rey
:param tablero:
:param x_inicial:
:param x_final:
:param y_inicial:
:param y_final:
:return:
"""
pass
esRey = None
auxiliar_x = x_final
#Validar si es rey
if (x_inicial == x_final or y_inicial == y_final):
esRey = tablero[x_inicial][y_inicial] in 'Rr'
#Validar si el movimiento en x es mayor a una casilla
if auxiliar_x != x_final + 1:
#Valida si la posicion en y es vacia
if esRey:
for x in range(x_inicial + 1, x_final):
if (tablero[x][y_final] != ''):
for y in range (y_inicial, y_final):
print([x_inicial],[y])
else:
raise ValueError("El camino esta bloqueado")
else:
print('No es un rey')
else:
raise ValueError("El movimiento no es válido")
else:
raise ValueError('No es un rey')
#Validamos si en el movimiento final hay un aliado o enemigo
if esRey == 't':
if tablero[x_final][y_final] == 't':
raise ValueError('No puedo matar aliados')
if esRey:
for x in range(x_inicial + 1, x_final):
if (tablero[x][y_final] == ''):
for y in range (y_inicial, y_final):
print([x_inicial],[y])
else:
raise ValueError("El camino esta bloqueado")
break
else:
esRey == tablero[x_final][y_final]
else:
if tablero[x_final][y_final] == 'T':
raise ValueError('No puedo matar aliados')
else:
esRey == tablero[x_final][y_final]
# def mover_torre(tablero, x_inicial, x_final, y_inicial, y_final):
# """
# define la movilidad de la torre en el tablero
# :param tablero: matriz que representa el tablero de juego
# :param x_inicial: posicion de la torre en x inicial
# :param y_inicial: posicion de la torre en x final
# :param x_final: posicion de la torre en y inicial
# :param y_final: posicion de la torre en y final
# :return:
# """
# #Si no hay posiciones diferentes no hay movimiento
# if x_inicial == x_final and y_inicial == y_final:
# raise ValueError("No se realizaron movimientos")
# #Valida si es movimiento en el eje X o Y
# elif x_inicial == x_final:
# #Valida que color de ficha es T o t
# if tablero[x_inicial][y_inicial] == 't'or tablero[x_inicial][y_inicial] == 'T':
# for x in range(y_inicial, y_final + 1):
# # Recorre el movimiento y valida si se puede realizar
# if tablero[x][x_inicial] != "":
# raise ValueError("movimiento no valido")
# else:
# return tablero
# else:
# # Valida que color de ficha es T o t
# if tablero[x_inicial][y_inicial] == 't' or tablero[x_inicial][y_inicial] == 'T':
# # Recorre el movimiento y valida si se puede realizar
# for x in range(x_inicial, x_final + 1):
# if tablero[x][y_inicial] != "":
# raise ValueError("movimiento no valido")
# else:
# return tablero
def mover_torre(tablero, x_inicial, y_inicial, x_final, y_final):
# Valido que se este moviendo una torre
if tablero[y_inicial][x_inicial].lower() == 't':
# Valido que se este moviendo en y
if x_inicial == x_final and y_inicial != y_final:
# Si me muevo hacia abajo
if y_inicial < y_final:
y_auxiliar = y_inicial + 1
# Si no me muevo hacia abajo
else:
y_auxiliar = y_inicial - 1
# Reviso el camino por obstaculos
for y in range(y_auxiliar, y_final):
if tablero[y][x_inicial] != ' ':
raise Exception('No hay camino para mover la torre')
# Valido el movimiento en x
elif x_inicial != x_final and y_inicial == y_final:
# validar si me muevo a la derecha
if x_inicial < x_final:
x_auxiliar = x_inicial + 1
else:
x_auxiliar = x_inicial - 1
# Reviso el camino por obtaculos
for x in range(x_auxiliar, x_final):
if tablero[x][y_inicial] != ' ':
raise Exception('No hay camino para mover la torre')
else:
raise Exception('Movimiento invalido para la torre')
if tablero[y_final][x_inicial] == ' ' \
or (tablero[y_inicial][x_inicial].islower() != tablero[y_final][x_inicial].islower()):
tablero[y_final][x_inicial] = tablero[y_inicial][x_inicial]
tablero[y_inicial][x_inicial] = ' '
else:
raise Exception('No puedo comer mis propias piezas')
else:
raise Exception('La pieza en x = {0} y={1} no es una torre'.format(x_inicial,y_inicial))
return tablero
|
INPUT = 314
pos = 0
l = [0]
for i in range(1,2018):
pos = (pos + INPUT) % len(l) + 1
l.insert(pos, i)
pos += 1
if pos == len(l):
pos = 0
print("Part 1", l[pos])
size = 1
pos = 0
val = 1
for i in range(1,50000001):
pos = (pos + INPUT) % size + 1
if pos == 1:
val = size
size += 1
print("Part 2", val) |
counter = 0
def handler(event, context):
global counter
result = {"counter": counter}
counter += 1
return result
|
# Advent Of Code 2018, day 11, part 1
# http://adventofcode.com/2018/day/11
# solution by ByteCommander, 2018-12-11
with open("inputs/aoc2018_11.txt") as file:
serial = int(file.read())
def get_power(x_, y_):
rack_id = x_ + 10
power_lv = (rack_id * y_ + serial) * rack_id
return power_lv % 1000 // 100 - 5
biggest = None # (total power, (x, y))
for x in range(1, 301):
for y in range(1, 301):
big_square = sum(get_power(x + dx, y + dy) for dx in range(3) for dy in range(3))
if biggest is None or big_square > biggest[0]:
biggest = (big_square, (x, y))
print(f"The highest powered 3x3 square has {biggest[0]} total power "
f"and the coordinates {','.join(map(str, biggest[1]))}")
|
class Contorno:
def __init__(self, x, altura):
self.x = x
self.altura = altura
def __str__(self):
return str([self.x, self.altura])
class Edificio:
def __init__(self, izquierda, altura, derecha):
self.izquierda = izquierda
self.altura = altura
self.derecha = derecha
def conquista(listaA, listaB):
contornos = []
alturaA = 0
alturaB = 0
alturaActual = 0
while(listaA or listaB):
if(not listaB or (listaA and listaA[0].x < listaB[0].x)):
contorno = listaA.pop(0)
alturaA = contorno.altura
else:
contorno = listaB.pop(0)
alturaB = contorno.altura
alturaMax = max(alturaA, alturaB)
if alturaActual != alturaMax:
contornos.append(Contorno(contorno.x, alturaMax))
alturaActual = alturaMax
return contornos
def obtenerContorno(listaDeEdificios):
if len(listaDeEdificios) == 1:
edificio = listaDeEdificios[0]
return [Contorno(edificio.izquierda, edificio.altura), Contorno(edificio.derecha, 0)]
return conquista(
obtenerContorno(listaDeEdificios[:len(listaDeEdificios) // 2]),
obtenerContorno(listaDeEdificios[len(listaDeEdificios) // 2:])
)
def tuplasAEdificios(tuplas):
return [Edificio(a, b, c) for a,b,c in tuplas]
tuplas = [ (4,5,8) , (1,15,5) , (16,11,19) , (10,12,11) , (7,7,15) ]
# esperado (1,15) , (5,5) , (7,7) , (10,12) , (11,7) , (15,0) , (16,11) , (19,0)
result = obtenerContorno(tuplasAEdificios(tuplas))
for r in result:
print(r)
print('otra tuplaa')
otraTupla = [ (1, 11, 5), (2, 6, 7), (3, 13, 9), (12, 7, 16) , (14, 3, 25), (19,18,22) ]
# esperado Contorno: (1,11),(3,13),(9,0),(12,7),(16,3),(19,18),(22,3),(25,0)
result = obtenerContorno(tuplasAEdificios(otraTupla))
for r in result:
print(r)
|
#Famous Quote:
Famous_person = "M. S. Dhoni"
Quote = "Hardwork, dedication, persevrance, disipline, etc all is required. But what matters the most in life is HONESTY."
print(Famous_person+" once said, \"" + Quote + "\"")
|
EAST, NORTH, WEST, SOUTH = range(4)
def move(pos, dir):
x, y = pos
if dir == EAST:
return x + 1, y
if dir == WEST:
return x - 1, y
if dir == NORTH:
return x, y + 1
if dir == SOUTH:
return x, y - 1
def generate_spiral(n):
g = {}
x = 1
direction = EAST
pos= (0, 0)
s = 1
while x <= n:
for i in range(2):
for j in range(s):
g[x] = pos
pos = move(pos, direction)
x += 1
direction = (direction+1)%4
s += 1
return g
def num_steps_to(pos):
x, y = pos
return abs(x) + abs(y)
def main():
n = int(input())
g = generate_spiral(n)
print(num_steps_to(g[n]))
if __name__ == '__main__':
main() |
def insertionSort(listku):
for index in range(1,len(listku)):
current_element = listku[index]
i = index
while current_element < listku[i-1] and i > 0:
listku[i] = listku[i-1]
i = i-1
listku[i] = current_element
jumlah = int(input("Berapa banyak element yang diinginkan : "))
list1 = [int(input()) for i in range (jumlah)]
insertionSort(list1)
print (list1)
|
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite outro número: '))
print('')
if n1 > n2 and n1 > n3:
print('Maior: {}'.format(n1))
elif n2 > n1 and n2 > n3:
print('Maior: {}'.format(n2))
else:
print('Maior: {}'.format(n3))
if n1 < n2 and n1 < n3:
print('Menor: {}'.format(n1))
elif n2 < n1 and n2 < n3:
print('Menor: {}'.format(n2))
else:
print('Menor: {}'.format(n3))
|
"""Generic contsnts"""
# Byte order magic numbers
# ----------------------------------------
ORDER_MAGIC_LE = 0x1A2B3C4D
ORDER_MAGIC_BE = 0x4D3C2B1A
SIZE_NOTSET = 0xFFFFFFFFFFFFFFFF # 64bit "-1"
# Endianness constants
ENDIAN_NATIVE = 0 # '='
ENDIAN_LITTLE = 1 # '<'
ENDIAN_BIG = 2 # '>'
|
a = 2
b = 7
area = a * b
print(area)
c = 7
d = 8
area1 = c * d
print(area1)
e = 12
f = 5
area2 = e * f
print(area2)
side_g = int(input())
side_h = int(input())
print(side_g * side_h) |
#code
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def Push(self,new_data):
temp = self.head
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.prev = temp
def PrintDList(self):
temp = self.head
if self.head is None:
return
while temp is not None:
print(temp.data,end=" ")
temp = temp.next
print()
def ReversePrint(self):
temp = self.head
while temp.next is not None:
temp = temp.next
rev = temp
while rev is not None:
print(rev.data,end=" ")
rev = rev.prev
print()
if (__name__ == "__main__"):
arr = [8,2,3,1,7]
dlist = DoublyLinkedList()
for i in arr :
dlist.Push(i)
dlist.PrintDList()
dlist.ReversePrint()
|
class Model:
"""An object backed by a plain data structure.
For compatibility with JSON serialisation it's important that the inner
data structure not contain anything which cannot be serialised. This is
the responsibility of the implementer.
"""
# An optional schema to apply to the contents when set
validator = None
# Custom message to add to any validation errors
validation_error_title = None
def __init__(self, raw, validate=True):
"""
:param raw: The raw data to add to this object
"""
self.raw = raw
if validate and raw is not None:
self.validate()
def validate(self, error_title=None):
"""
Validate the contents of this object against the schema (if any)
If `validation_error_title` is set, then this will be used as a default
`error_title`.
:param error_title: A custom error message when errors are found
:raise SchemaValidationError: When errors are found
"""
if error_title is None:
error_title = self.validation_error_title
if self.validator is not None:
self.validator.validate_all(self.raw, error_title)
@classmethod
def extract_raw(cls, item):
"""Get raw data from a model, or return item if it is not a Model."""
if isinstance(item, Model):
return item.raw
return item
@classmethod
def dict_from_populated(cls, **kwargs):
"""Get a dict where keys only appear if the values are not None.
This is quite convenient for a lot of models."""
return {key: value for key, value in kwargs.items() if value is not None}
def __repr__(self):
return f"<{self.__class__.__name__}: {self.raw}>"
|
# -*- coding: utf-8 -*-
def test_add_contact(app, db, json_contacts, check_ui):
contact = json_contacts
old_contacts = db.get_contact_list()
app.contact.add_new(contact)
app.contact.check_add_new_success(db, contact, old_contacts, check_ui)
|
def get_greater(project_arr):
version0 = project_arr[0].split(',')[1].lower()
version1 = project_arr[1].split(',')[1].lower()
split_char = None
if '.' in version0:
split_char = '.'
elif '_' in version0:
split_char = '_'
if split_char == None:
if version0 < version1:
return project_arr[0].split(',') , project_arr[1].split(',')
else:
return project_arr[1].split(',') , project_arr[0].split(',')
version0_splited = version0.split(split_char)
version1_splited = version1.split(split_char)
for i in range(len(version0_splited)):
number0 = version0_splited[i]
if (i + 1) > len(version1_splited):
break
number1 = version1_splited[i]
if number0.isdigit() and number1.isdigit():
if int(number0) < int(number1):
return project_arr[0].split(',') , project_arr[1].split(',')
elif int(number0) > int(number1):
return project_arr[1].split(',') , project_arr[0].split(',')
else:
if number0.lower() < number1.lower():
return project_arr[0].split(',') , project_arr[1].split(',')
elif number0.lower() > number1.lower():
return project_arr[1].split(',') , project_arr[0].split(',')
return project_arr[0].split(',') , project_arr[1].split(',')
projects = {}
with open('result.csv', 'r') as f:
skip_line = True
for line in f:
if skip_line:
skip_line = False
continue
line = line.strip()
projectname = line.split(',')[0]
if projectname not in projects:
projects[projectname] = [line]
else:
projects[projectname].append(line)
with open('compare.csv', 'w') as f:
f.write('projectname,diff loc,diff blocks,diff % disciplined,diff disciplined\n')
for project in projects:
if len(projects[project]) < 2:
continue
#first, second = ['','']
first,second = get_greater(projects[project])
#if projects[project][0].split(',')[1].lower() < projects[project][1].split(',')[1].lower():
# first = projects[project][0].split(',')
# second = projects[project][1].split(',')
#else:
# first = projects[project][1].split(',')
# second = projects[project][0].split(',')
diff_loc = int(second[3]) - int(first[3])
diff_blocks = int(second[4]) - int(first[4])
diff_disciplined = float(second[5]) - float(first[5])
diff_n_disciplined = int(second[-1]) - int(first[-1])
f.write(project + ',' + str(diff_loc) + ',' + str(diff_blocks) + ',' + \
str(round(diff_disciplined,2)) + ',' + str(diff_n_disciplined) + '\n') |
#Get states and coordinates and generates a csv file
lats = []
lons = []
states = []
lat = 0.0
lon = 0.0
infile = 'all_states.json'
with open(infile, 'r') as f:
for line in f:
if ('coordinates' in line):
lon = float(f.readline().strip().split(',')[0])
lat = float(f.readline().strip().split(',')[0])
#Pick only US states
if ('state' in line):
st = line.strip().split(':')[1]
print(st)
temp = f.readline()
country = f.readline().split(',')[0]
if ('country' in country):
country = country.split(':')[1]
else:
country = ""
if (len(st) < 40 and "United States of America" in country):
states.append(st)
lons.append(lon)
lats.append(lat)
with open("geo.dat", "w") as f:
f.write("state, lat, lon\n")
tam = len(states)
i = 0
while (i < tam):
line = states[i] + " " + str(lats[i]) + ", " + str(lons[i]) + "\n"
f.write(line)
i+=1
|
# Allows us to read a espionage
def read_espionage(espionage, structures):
ans = {}
carefull = False
espionage = espionage.split('\n')
line = espionage[0].split(' ')
j = 4
while line[j][0] != '[':
j += 1
ans.update({'planet':' '.join(line[4:j])})
ans.update({'coordinates':line[j]})
ans.update({'date':'{} {}'.format(line[j+1], line[j+2])})
i = 2
name = ' '.join(espionage[i].split(' ')[1:])[1:]
pos = name.find('(')
if pos != -1:
name = name[:pos]
ans.update({'name':name})
ans.update({'inactive':pos!=-1})
i += 1
ans.update({'counterspionage':espionage[i].split(' ')[3]})
i += 3
line = espionage[i].split(' ')
resources = {}
resources.update({'metal':line[0]})
resources.update({'crystal':line[1]})
resources.update({'deuteryum':line[2]})
resources.update({'energy':line[3]})
ans.update({'resources':resources})
pipeline = ['ships','defense','buildings','research']
for element in pipeline:
i += 2
line = espionage[i].replace('.','')
care, entities = read_entities(line,structures[element])
if care:
carefull = True
ans.update({element:entities})
ans.update({'care':carefull})
return ans
def read_entity(structure,line):
num_structure = 0
#print(':' + structure + ': ---> :' + line[:len(structure)] + ':')
if structure == line[:len(structure)]:
line = line[len(structure)+1:]
j = 1
while j-1 < len(line) and line[:j].isdigit():
j += 1
num_structure = int(line[:j-1])
line = line[j-1:]
return line, num_structure
def read_entities(line, structure):
ans = {}
length = len(line)
while line != '':
for s in structure:
line, num = read_entity(structure[s], line)
if num != 0:
ans.update({s:num})
if len(line) == length:
break;
return len(ans) == 0, ans |
# dataset settings
dataset_type = 'TianchiDataset' # 上一步中你定义的数据集的名字
data_root = 'data/tianchi_aug' # 数据集存储路径
iamge_scale_t = (768, 768)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) # 数据集的均值和标准差,空引用默认的,也可以网上搜代码计算
crop_size = (512, 512) # 数据增强时裁剪的大小
train_pipeline = [
# dict(type='LoadImageFromFile'),
# dict(type='LoadAnnotations'),
dict(type='RandomMosaic', prob=1, img_scale=iamge_scale_t),
dict(type='Resize', img_scale=iamge_scale_t,
ratio_range=(0.5, 2.0)), # img_scale图像尺寸
dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75),
dict(type='RandomFlip', prob=0.5),
dict(type='RandomCutOut', prob=0.5, n_holes = 3, cutout_shape = [(4, 4), (4, 8), (8, 4),(8, 8), (16, 8), (8, 16),
(16, 16), (16, 32), (32, 16) ]),
dict(type='RandomRotate', prob = 0.5, degree=90),
dict(type='PhotoMetricDistortion'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_semantic_seg']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1024, 1024), # img_scale图像尺寸
# img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
train_dataset_mosaic = dict(
type='MultiImageMixDataset',
dataset=dict(
type=dataset_type,
data_root=data_root,
img_dir='images/training', # 训练图像路径
ann_dir='annotations/training', # 训练mask路径
pipeline=[
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations')
],
),
pipeline=train_pipeline
)
train_dataset = dict(
type=dataset_type,
data_root=data_root,
img_dir='images/training', # 训练图像路径
ann_dir='annotations/training', # 训练mask路径
pipeline=train_pipeline)
data = dict(
train=train_dataset_mosaic,
val=dict(
type=dataset_type,
data_root=data_root,
img_dir='images/validation', # 验证图像路径
ann_dir='annotations/validation', # 验证mask路径
pipeline=test_pipeline),
test=dict(
type=dataset_type,
data_root=data_root,
img_dir='test/img', # 测试图像路径
ann_dir=None, # 测试mask路径
pipeline=test_pipeline)
)
|
##########################
###### MINI-MAX ######
##########################
class MiniMax:
# print utility value of root node (assuming it is max)
# print names of all nodes visited during search
def __init__(self, root):
#self.game_tree = game_tree # GameTree
self.root = root # GameNode
#self.currentNode = None # GameNode
self.successors = root.children # List of GameNodes
return
def minimax(self, node):
# first, find the max value
#best_val = self.max_value(node) # should be root node of tree
# second, find the node which HAS that max value
# --> means we need to propagate the values back up the
# tree as part of our minimax algorithm
successors = node.children
#print ("MiniMax: Utility Value of Root Node: = " + str(best_val))
# find the node with our best move
best_move = None
best_val = -1
for elem in successors: # ---> Need to propagate values up tree for this to work
print("Looking at ",elem.move, "with value: ", elem.value)
if elem.value >= best_val:
best_move = elem.move
best_val = elem.value
# return that best value that we've found
print("Best move is: ",best_move)
return best_move
def max_value(self, node):
#print ("MiniMax-->MAX: Visited Node :: " + str(node.move))
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
max_value = -infinity
successors_states = self.getSuccessors(node)
for state in successors_states:
max_value = max(max_value, self.min_value(state))
return max_value
def min_value(self, node):
#print ("MiniMax-->MIN: Visited Node :: " + str(node.move))
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
min_value = infinity
successor_states = self.getSuccessors(node)
for state in successor_states:
min_value = min(min_value, self.max_value(state))
return min_value
# #
# UTILITY METHODS #
# #
# successor states in a game tree are the child nodes...
def getSuccessors(self, node):
assert node is not None
return node.children
# return true if the node has NO children (successor states)
# return false if the node has children (successor states)
def isTerminal(self, node):
assert node is not None
return len(node.children) == 0
def getUtility(self, node):
assert node is not None
return node.value
|
# Creating a dictionary called 'birthdays' containing famous people's names as
# key and their birthday date as values.
birthdays = {
'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
# Creating a function 'print_birthdays' to display, through a for loop, the
# names of the people whose birthday date we have.
def print_birthdays():
print('''Welcome to the birthday dictionary. We know the birthdays of these
people:''')
for name in birthdays:
print(name)
# Creating a function 'return_birthday' to return the date of the requested
# famous person in the form of {famous person's name}'s birthday is
# {famous person's birthday date}; in case the requested famous person is
# not in our dictionary, we return the message 'Sadly, we don't have
# {famous person's name}'s birthday'.
def return_birthday(name):
if name in birthdays:
print('{}\'s birthday is {}.'.format(name, birthdays[name]))
else:
print('Sadly, we don\'t have {}\'s birthday.'.format(name))
def name_is_valid(name): # Check whether an input name is valid according to
# some conditions
if len(name) > 20:
return False
if name not in birthdays:
return False
if name.islower():
return False
return True
def just_the_surname(name): # Return just the surname of the person
if name in birthdays:
fullname = [name]
fullname = fullname[0].split()
return fullname[1]
def not_digit(name): # Check whether the input is a digit
if not name.isdigit():
return True
|
# See: https://docs.djangoproject.com/en/1.5/ref/settings/#authentication-backends
AUTH_USER_MODEL = 'auth.User'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
|
# https://codeforces.com/problemset/problem/1519/B
t = int(input())
cases = [list(map(int, input().split())) for _ in range(t)]
for case in cases:
if (case[0]-1) + (case[0] * (case[1]-1)) == case[2]:
print('YES')
else:
print('NO') |
subt = ''
file = 'BookCorpus2'
groups = ['ArXiv', 'BookCorpus2', 'Books3', 'DM Mathematics', 'Enron Emails', 'EuroParl', 'FreeLaw', 'Github', 'Gutenberg (PG-19)', 'HackerNews', 'NIH ExPorter', 'OpenSubtitles', 'OpenWebText2', 'Pile-CC', 'PhilPapers', 'PubMed Central', 'PubMed Abstracts', 'StackExchange', 'Ubuntu IRC', 'USPTO Backgrounds', 'Wikipedia (en)', 'YoutubeSubtitles']
for element in groups:
for a in range(0, 15):
print(f'{element}{a}')
with open(f'{element}{a}', 'r') as f:
subt = f.read()
subt = subt.encode('ascii', 'ignore').decode('unicode_escape')
# subt.join(subtL)
with open(f'lb/{element}{a}', "w") as f:
f.write(subt)
print(f'end of {a}') |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( s , t ) :
count = 0
for i in range ( 0 , len ( t ) ) :
if ( count == len ( s ) ) :
break
if ( t [ i ] == s [ count ] ) :
count = count + 1
return count
#TOFILL
if __name__ == '__main__':
param = [
('nObYIOjEQZ','uARTDTQbmGI',),
('84574','8538229',),
('1010001010010','11',),
('DjZtAfUudk','OewGm',),
('550','132744553919',),
('1110','0101',),
('GywyxwH','LPQqEqrDZiwY',),
('67318370914755','9928',),
('11011000000101','00000',),
('G','V',)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) |
class No:
def __init__(self, valor):
self.valor = valor
self.proximo = None
self.anterior = None
def mostrar_no(self):
print(self.valor)
class FilaListaDuplamenteEncadeada:
def __init__(self):
self.primeiro = None
self.ultimo = None
def __fila_vazia(self):
return self.primeiro == None
def enfileirar(self, valor):
novo = No(valor)
if self.__fila_vazia():
self.primeiro = novo
else:
self.ultimo.proximo = novo
novo.anterior = self.ultimo
self.ultimo = novo
def mostrar_fila(self):
atual = self.primeiro
while atual != None:
atual.mostrar_no()
atual = atual.proximo
def desenfileirar(self):
temp = self.primeiro
if self.primeiro.proximo == None:
self.ultimo = None
else:
self.primeiro.proximo.anterior = None
self.primeiro = self.primeiro.proximo
return temp
fila = FilaListaDuplamenteEncadeada()
fila.enfileirar(4)
fila.enfileirar(3)
fila.enfileirar(2)
fila.enfileirar(1)
fila.enfileirar(0)
print('-'*7)
fila.mostrar_fila()
fila.desenfileirar()
fila.desenfileirar()
fila.desenfileirar()
fila.enfileirar(8)
print('-'*7)
fila.mostrar_fila()
|
class SinglyLinkedList:
def __init__(self, single_link_node_factory, *args, **kwargs):
super().__init__(*args, **kwargs)
self._linked_node_factory = single_link_node_factory
self._header = self._linked_node_factory()
self._tail = None
def __iter__(self):
return iter(self.head)
def __repr__(self):
return f"{self.__module__}.{self.__class__.__name__}()"
def __str__(self):
return self.__repr__()
def append(self, value=None):
self.insert(value)
def insert(self, value=None, link_before=None):
if link_before is not None:
link_after = link_before.next_link
link_before.next_link = self._linked_node_factory(value, link_after)
elif self.is_empty:
self._header.next_link = self._linked_node_factory(value)
self._tail = self._header.next_link
else:
old_tail = self._tail
old_tail.next_link = self._linked_node_factory(value)
self._tail = old_tail.next_link
def find(self, value):
if self.is_empty:
return None
current_link = self.head
while current_link is not None:
if current_link.value == value:
break
current_link = current_link.next_link
return current_link
@property
def head(self):
return self._header.next_link
@property
def tail(self):
return self._tail
@property
def is_empty(self):
return self.head is None
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def distribute_coins(self, root: TreeNode) -> int:
self.result = 0
self.post_order(root)
return self.result
def post_order(self, root) -> int:
if root is not None:
left = self.post_order(root.left)
right = self.post_order(root.right)
val = left + right + root.val - 1
self.result += abs(val)
return val
return 0
|
class Broker:
def purchase_shares():
raise NotImplementedError
def sell_shares():
raise NotImplementedError |
# https://leetcode.com/problems/delete-operation-for-two-strings/
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for i in range(len(word1) + 1):
dp[i][0] = i
for i in range(len(word2) + 1):
dp[0][i] = i
for i in range(1, len(word1) + 1):
for j in range(1, len(word2) + 1):
# 如果当前的两个字符是相同的,那么直接取左上角
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
# 否则从左和上选一个最小的,加 1
else:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1
return dp[-1][-1]
s = Solution()
print(s.minDistance('sea', 'eat'))
print(s.minDistance('leetcode', 'etco'))
|
print("#===Welcome to DNA/mRNA/tRNA/Anino Acid (Protein) Sequence Converter===#")
start = input("Press Enter to continue...")
while True:
if start == "":
print("Check Available Options:")
print("1. DNA")
print("2. mRNA")
print("3. tRNA")
print("4. Amino Acid(Protein)")
print("")
command = (input("Select input option(1-4): "))
if command == "1":
print("1. mRNA")
print("2. tRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the DNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "A"
elif x.upper() == "T":
result += "U"
elif x.upper() == "C":
result += "C"
elif x.upper() == "G":
result += "G"
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "T":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
else: print("Invalid Command")
print(result)
elif command == "2":
print("1. DNA")
print("2. tRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the mRNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "A"
elif x.upper() == "T":
result += "U"
elif x.upper() == "C":
result += "C"
elif x.upper() == "G":
result += "G"
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
else: print("Invalid Command")
elif command == "3":
print("1. DNA")
print("2. mRNA")
command2 = (input("Select output option(1,2): "))
data = input("Enter the tRNA sequence: ")
result = ""
if command2 == "1":
for x in data:
if x.upper() == "A":
result += "T"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
elif command2 == "2":
for x in data:
if x.upper() == "A":
result += "U"
elif x.upper() == "U":
result += "A"
elif x.upper() == "C":
result += "G"
elif x.upper() == "G":
result += "C"
print(result)
elif command2 == "3":
print(data)
else: print("Invalid Command")
elif command == "4":
data = input("Enter mRNA sequence: ")
result = ""
array = []
if len(data)%3 != 0:
print("Invalid Sequence")
else:
for x in range(len(array)):
if array[x] == "UUU" or array[x] == "UUC":
result += "Phe"+"-"
elif array[x] == "UUA" or array[x] == "UUG" or array[x] == "CUU" or array[x] == "CUC" or array[x] == "CUA" or array[x] == "CUG":
result += "Leu"+"-"
elif array[x] == "UCU" or array[x] == "UCC" or array[x] == "UCA" or array[x] == "UCG" or array[x] == "AGU" or array[x] == "AGC":
result += "Ser"+"-"
elif array[x] == "UAU" or array[x] == "UAC":
result += "Tyr"+"-"
elif array[x] == "UGU" or array[x] == "UGC":
result += "Cys"+"-"
elif array[x] == "CCU" or array[x] == "CCC" or array[x] == "CCA" or array[x] == "CAG":
result += "Pro"+"-"
elif array[x] == "CAU" or array[x] == "CAC":
result += "His"+"-"
elif array[x] == "CAA" or array[x] == "CAG":
result += "Gin"+"-"
elif array[x] == "CGU" or array[x] == "CGC" or array[x] == "CGA" or array[x] == "CGG" or array[x] == "AGA" or array[x] == "AGG":
result += "Arg"+"-"
elif array[x] == "UGG":
result += "Trp"+"-"
elif array[x] == "AUG":
result += "Met"+"-"
elif array[x] == "AUU" or array[x] == "AUC" or array[x] == "AUA":
result += "Ile"+"-"
elif array[x] == "ACU" or array[x] == "ACC" or array[x] == "ACA" or array[x] == "ACG":
result += "Thr"+"-"
elif array[x] == "AAU" or array[x] == "AAC":
result += "Asn"+"-"
elif array[x] == "AAA" or array[x] == "AAG":
result += "Lys"+"-"
elif array[x] == "GUU" or array[x] == "GUC" or array[x] == "GUA" or array[x] == "GUG":
result += "Val"+"-"
elif array[x] == "GCU" or array[x] == "GCC" or array[x] == "GCA" or array[x] == "GCG":
result += "Ala"+"-"
elif array[x] == "GGU" or array[x] == "GGC" or array[x] == "GGA" or array[x] == "GGG":
result += "Gly"+"-"
elif array[x] == "GAU" or array[x] == "GAC":
result += "Asp"+"-"
elif array[x] == "GAA" or array[x] == "GAG":
result += "Glu"+"-"
else:
pass
final = result[:-1]
print(final)
else:
print("Something Went Wrong")
else:
break
self = input() |
# Recitation Lab 5 Question 1: Program to find smallest power of 2 greater than or equal to a number
# Author: Asmit De
# Date: 03/02/2017
# Input number
num = int(input('Enter a number: '))
# Initialize variable to the lowest power of 2
powervalue = 2
# Run loop until powervalue becomes greater than or equal to num
while powervalue < num:
# Generate the next power of 2 and update powervalue (just double it!)
powervalue *= 2
# Display final powervalue
print('The smallest power of 2 greater than or equal to', num, 'is', powervalue) |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Escribir un programa que solicite al usuario ingresar un número de
decimales y almacénelo en una variable. A continuación, el programa
debe solicitar al usuario que ingrese un número entero y guardarlo en
otra variable. En una tercera variable se deberá guardar el resultado
de la suma de los dos números ingresados por el usuario. Por último, se
debe mostrar en pantalla el texto "El resultado de la suma es [suma]",
donde "[suma]" se reemplazará por el resultado de la operación.
"""
a = float(input("Ingrese un número de decimales: "))
b = int(input("Ingrese un número entero: "))
c = a + b
print(f"El resultado de la suma es {c}") |
tabela_brasileirao = ('Palmeiras', 'Bragantino', 'Atlético-PR', 'Atlético-MG', 'Fortaleza', 'Bahia', 'Santos',
'Atlético-GO', 'Ceará', 'Corinthians', 'Fluminense', 'Flamengo', 'Juventude', 'Internacional',
'América-MG', 'São Paulo', 'Sport', 'Cuiabá', 'Chapecoense', 'Grêmio')
print(f'\nOS 5 PRIMEIROS COLOCADOS FORAM\n{tabela_brasileirao[0:5]}')
print(f'\nOS QUATRO PRIMEIROS ÚLTIMOS FORAM\n{tabela_brasileirao[-4:]}')
print(f'\nTIMES EM ORDEM ALFABÉTICA\n{sorted(tabela_brasileirao)}')
print('\nA POSIÇÃO EM QUE SE ENCONTRA:', tabela_brasileirao.index('Chapecoense') + 1)
|
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])
def test_reverse_words():
s = Solution()
assert "blue is sky the" == s.reverseWords("the sky is blue")
assert "world! hello" == s.reverseWords(" hello world! ")
assert "example good a" == s.reverseWords("a good example")
|
players = { "name" : "Messi", "age" : 32, "goals": 800, "cap" : 700}
players.keys()
for k in players.keys():
print(k) |
#maximo
def maximo(a,b):
if a > b:
return a
else:
return b
|
n = int(input()) #lost fights
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
lost_fights_count = 0
helmet_brakes = 0
sword_brakes = 0
shield_brakes = 0
armor_brakes = 0
total_shield_brakes = 0
for x in range(n):
lost_fights_count += 1
if lost_fights_count % 2 == 0:
helmet_brakes += 1
if lost_fights_count % 3 == 0:
sword_brakes += 1
if lost_fights_count % 2 == 0:
shield_brakes += 1
total_shield_brakes += 1
if shield_brakes % 2 == 0 and shield_brakes != 0:
armor_brakes += 1
shield_brakes = 0
expenses = (helmet_brakes * helmet_price) + (sword_brakes * sword_price) \
+ (total_shield_brakes * shield_price) + (armor_brakes * armor_price)
print(f"Gladiator expenses: {expenses:.2f} aureus")
|
#!/usr/bin/env python
# coding: utf-8
# In[5]:
def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def parent(i):
return i // 2
def MaxHeapify(lis, heap_size, i):
l = left(i)
r = right(i)
largest = 0
temp = 0
if (l <= heap_size) and lis[l] > lis[i]:
largest = l
else:
largest = i
if (r <= heap_size) and lis[r] > lis[largest]:
largest = r
if (largest != i):
temp = lis[i]
lis[i] = lis[largest]
lis[largest] = temp
MaxHeapify(lis, heap_size, largest)
def build_max_heap(lis, heap_size):
k = heap_size//2
while k >= 1:
MaxHeapify(lis, heap_size, k)
k = k - 1
return lis
lis = [0,12,7,13,5,10,17,1,2,3]
print(build_max_heap(lis, len(lis)-1))
|
"""ENum values dictionary for the Home Connect integration."""
enum_list = {
"BSH.Common.Status.OperationState" : "Operation State",
"BSH.Common.EnumType.OperationState.Inactive" : "Inactive",
"BSH.Common.EnumType.OperationState.Ready" : "Ready",
"BSH.Common.EnumType.OperationState.DelayedStart" : "Delayed Start",
"BSH.Common.EnumType.OperationState.Run" : "Run",
"BSH.Common.EnumType.OperationState.Pause" : "Pause",
"BSH.Common.EnumType.OperationState.ActionRequired" : "Action Required",
"BSH.Common.EnumType.OperationState.Finished" : "Finished",
"BSH.Common.EnumType.OperationState.Error" : "Error",
"BSH.Common.EnumType.OperationState.Aborting" : "Aborting",
"BSH.Common.Setting.PowerState" : "Power State",
"BSH.Common.EnumType.PowerState.Off" : "Off",
"BSH.Common.EnumType.PowerState.On" : "On",
"BSH.Common.EnumType.PowerState.Standby" : "Standby",
"BSH.Common.Setting.TemperatureUnit" : "Temperature Units",
"BSH.Common.EnumType.TemperatureUnit.Celsius" : "Celsius",
"BSH.Common.EnumType.TemperatureUnit.Fahrenheit" : "Fahrenheit",
"BSH.Common.Status.DoorState" : "Door State",
"BSH.Common.EnumType.DoorState.Open" : "Open",
"BSH.Common.EnumType.DoorState.Closed" : "Closed",
"BSH.Common.EnumType.DoorState.Locked" : "Locked",
"BSH.Common.Status.LocalControlActive" : "Local Control Activation",
"BSH.Common.Status.RemoteControlActive": "Remote Control Activation",
"BSH.Common.Status.RemoteControlStartAllowed" : "Remote Control Allowed",
"BSH.Common.Root.ActiveProgram" : "Active Program",
"BSH.Common.Root.SelectedProgram" : "Selected Program",
"BSH.Common.Option.RemainingProgramTime" : "Remaining Program Time",
"BSH.Common.Option.ElapsedProgramTime" : "Elapsed Program Time",
"BSH.Common.Option.ProgramProgress" : "Program Progress",
"BSH.Common.Option.Duration" : "Program Duration",
"BSH.Common.Event.ProgramFinished" : "Program Finished",
"BSH.Common.Event.AlarmClockElapsed" : "Alarm Clock Elapsed",
"LaundryCare.Dryer.Event.DryingProcessFinished" : "Drying Process Finished",
"BSH.Common.EnumType.EventPresentState.Present" : "Event Present",
"BSH.Common.EnumType.EventPresentState.Off" : "Event Off",
"BSH.Common.EnumType.EventPresentState.Confirmed" : "Event Confirmed",
"LaundryCare.Dryer.Program.Cotton" : "Cotton",
"LaundryCare.Dryer.Program.Synthetic" : "Synthetic",
"LaundryCare.Dryer.Program.Mix" : "Mix Textiles",
"LaundryCare.Dryer.Program.Blankets" : "Blankets",
"LaundryCare.Dryer.Program.BusinessShirts" : "Business Shirts",
"LaundryCare.Dryer.Program.DownFeathers" : "Down Feathers",
"LaundryCare.Dryer.Program.Hygiene" : "Hygiene",
"LaundryCare.Dryer.Program.Jeans" : "Jeans",
"LaundryCare.Dryer.Program.Outdoor" : "Outdoor",
"LaundryCare.Dryer.Program.SyntheticRefresh" : "Synthetic Refresh",
"LaundryCare.Dryer.Program.Towels" : "Towels",
"LaundryCare.Dryer.Program.Delicates" : "Delicates",
"LaundryCare.Dryer.Program.Super40" : "Super 40'",
"LaundryCare.Dryer.Program.Shirts15" : "Shirts 15'",
"LaundryCare.Dryer.Program.Pillow" : "Pillow",
"LaundryCare.Dryer.Program.AntiShrink" : "Anti-Shrink",
"LaundryCare.Dryer.Program.WoolFinish" : "Wool",
"LaundryCare.Dryer.Program.MyTime.MyDryingTime" : "Variable Time",
"LaundryCare.Dryer.Program.TimeCold" : "Variable Time - Cold",
"LaundryCare.Dryer.Program.TimeWarm" : "Variable Time - Warm",
"LaundryCare.Dryer.Program.InBasket" : "Variable Time - In Basket",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold20" : "Fix Time 20'- Cold",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold30" : "Fix Time 30'- Cold",
"LaundryCare.Dryer.Program.TimeColdFix.TimeCold60" : "Fix Time 60'- Cold",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm30" : "Fix Time 30'- Warm",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm40" : "Fix Time 40'- Warm",
"LaundryCare.Dryer.Program.TimeWarmFix.TimeWarm60" : "Fix Time 60'- Warm",
"LaundryCare.Dryer.Program.Dessous" : "Dessous",
"LaundryCare.Dryer.Option.DryingTarget" : "Drying Target",
"LaundryCare.Dryer.EnumType.DryingTarget.IronDry" : "Iron Dry",
"LaundryCare.Dryer.EnumType.DryingTarget.CupboardDry" : "Cupboard Dry",
"LaundryCare.Dryer.EnumType.DryingTarget.CupboardDryPlus" : "Cupboard Dry Plus",
}
|
lista = [];
lista.append(float(input("Digite o primeiro elemento")));
lista.append(float(input("Digite o segundo elemento")));
lista.append(float(input("Digite o terceiro elemento")));
lista.sort();
print(lista)
|
class HeapBinaryMin:
def __init__(self, data=[]):
self.data = data
self.build_max_heap()
def build_min_heap(self):
pass
def get_min(self):
return self.data[0]
def extract_min(self):
popped, self.data[0] = self.data[0], self.data[-1]
return popped
def insert(self, A: list):
current = len(self.data)
self.data.append(A)
while self.data[current] < self.data[self.parent(current)]:
self.data[current], self.data[self.parent(current)] = self.data[self.parent(current)], self.data[current]
current = self.parent(current)
def min_heapify(self, index):
pass
def parent(self, index: int) -> int:
'''Returns position of parent of element at index'''
return index // 2
def left_child(self, index: int) -> int:
'''Returns position of left child of element at index'''
return 2 * index
def right_child(self, index):
'''Returns position of right child of element at index'''
return 2 * index + 1
|
class ClassifierBase(object):
def getClassDistribution(self, instance):
raise NotImplementedError("This must be implemented by a concrete adapter.")
def classify(self, instance):
raise NotImplementedError("This must be implemented by a concrete adapter.")
|
i=int(input('enter a year'))
if (i%4)==0:
if (i%100)==0:
if (i%400)==0:
print('leap year')
else:
print('not a lep year')
else:
print('not a lep year')
else:
print('not a lep year')
|
# -- MocaMultiProcessLock --------------------------------------------------------------------------
class MocaMultiProcessLock:
__slots__ = ("_rlock", "_blocking", "_acquired")
def __init__(self, rlock, blocking):
self._rlock = rlock
self._blocking = blocking
self._acquired = False
@property
def acquired(self):
return self._acquired
def __enter__(self):
self._acquired = self._rlock.acquire(blocking=self._blocking)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self._acquired:
self._rlock.release()
# -------------------------------------------------------------------------- MocaMultiProcessLock --
|
'''
Problem Statement : Single Number
Link : https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3283/
score : accepted
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
for i in nums:
if nums.count(i)==1:
return i
|
## PARAMETERS TO CALCULATE LEARNING TIME
"----------------------------------------------------------------------------------------------------------------------"
############################################# Imports ##################################################################
"----------------------------------------------------------------------------------------------------------------------"
"--- Standard library imports ---"
"--- Third party imports ---"
"--- Local application imports ---"
"----------------------------------------------------------------------------------------------------------------------"
############### Test parameters ########################################################################################
"----------------------------------------------------------------------------------------------------------------------"
"--------------- Sample videos ---------------"
## Sample video to use module to determine duration time
duration_test_path = "/Users/rp_mbp/Desktop/USMLE STEP 1/Kaplan USMLE Step 1 Videos 2020/01 Anatomy 34h27m/01 Embryology & Histology/01 Gonad Development - Gonad Development.mp4"
"--------------- Test directory ---------------"
## Fictional directory to algorithm to convert dictionary into dataframe
test_dict_dir = {
"Topic_1": {
"Subtopic_1.1": {
"Class_1.1.1": {
"duration": 0.5
},
"Class_1.1.2": {
"duration": 0.75
},
"Class_1.1.3": {
"duration": 0.8
},
},
"Subtopic_1.2": {
"Class_1.2.1": {
"duration": 0.5
},
"Class_1.2.2": {
"duration": 0.75
},
"Class_1.2.3": {
"duration": 0.8
},
},
},
"Topic_2": {
"Subtopic_2.1": {
"Class_2.1.1": {
"duration": 0.5
},
"Class_2.1.2": {
"duration": 0.75
},
"Class_2.1.3": {
"duration": 0.8
},
},
"Subtopic_2.2": {
"Class_2.2.1": {
"duration": 0.5
},
"Class_2.2.2": {
"duration": 0.75
},
"Class_2.2.3": {
"duration": 0.8
},
},
},
}
"----------------------------------------------------------------------------------------------------------------------"
"----------------------------------------------------------------------------------------------------------------------"
############################################# END OF FILE ##############################################################
"----------------------------------------------------------------------------------------------------------------------"
"----------------------------------------------------------------------------------------------------------------------"
|
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config_type='servod'
revs = [513]
inas = [('ina3221', '0x40:0', 'pp1000_a_pmic', 7.6, 0.010, 'rem', True), # PR127, ppvar_sys_pmic_v1
('ina3221', '0x40:1', 'ppvar_bl_pwr', 7.6, 0.005, 'rem', True), # F1, originally fuse
('ina3221', '0x40:2', 'ppvar_vcc', 7.6, 0.010, 'rem', True), # PR87, +8.4VB_VCC1_VIN
('ina3221', '0x41:0', 'pp5000_a', 5.0, 0.005, 'rem', True), # PR160
('ina3221', '0x41:1', 'pp5000_a_pmic', 7.6, 0.010, 'rem', True), # PR159, ppvar_sys_pmic_v5
('ina3221', '0x41:2', 'pp1800_a', 1.8, 0.010, 'rem', True), # PR137
('ina3221', '0x42:0', 'pp1200_vddq', 1.2, 0.005, 'rem', True), # PR152
('ina3221', '0x42:1', 'pp0600_ddrvtt', 0.6, 0.010, 'rem', True), # PR929
('ina3221', '0x42:2', 'pp1200_vddq_pmic', 7.6, 0.000, 'rem', False), # PR151, ppvar_sys_pmic_v4
('ina3221', '0x43:0', 'pp1800_a_pmic', 3.3, 0.000, 'rem', False), # PR1236, vinvr2_650830
('ina3221', '0x43:1', 'pp0600_ddrvtt_pmic', 1.2, 0.000, 'rem', False), # PR931, pp1200_vddq_ddrvttin
('ina3221', '0x43:2', 'pp3300_dsw_pmic', 7.6, 0.010, 'rem', True), # PR140, ppvar_sys_pmic_v3
# ('ina219', '0x44', 'ppvar_vcc2', 7.6, 0.010, 'rem', True), # PR92, +8.4VB_VCC2_VIN, not stuffed
('ina219', '0x45', 'ppvar_sa', 7.6, 0.010, 'rem', True), # PR99
('ina219', '0x46', 'pp3300_dsw', 3.3, 0.005, 'rem', True), # PR138
('ina219', '0x47', 'vbat', 7.6, 0.010, 'rem', True), # PR11
('ina219', '0x48', 'ppvar_gt', 7.6, 0.010, 'rem', True), # PR97
('ina219', '0x49', 'pp3300_s', 3.3, 0.010, 'rem', True), # R4920
('ina219', '0x4a', 'pp3300_dx_wlan', 3.3, 0.010, 'rem', True), # R381
('ina219', '0x4b', 'pp1000_a', 1.0, 0.005, 'rem', True), # PR128
('ina219', '0x4c', 'pp3300_dx_edp', 3.3, 0.010, 'rem', True), # R378
('ina219', '0x4d', 'pp3300_dsw_ec', 3.3, 0.010, 'rem', True)] # R953
|
"""
Basic Variables
"""
# Create a variable that represents your favorite number, and add a note to remind yourself what this variable represents. Now print it out without re-typing the number.
fave_num = 12
print(fave_num)
# Create another variable that represents your favorite color, and do the same steps as above.
fave_color = 'blue'
print(fave_color)
|
#!/usr/bin/env python3
with open("input.txt", "r") as f:
lines = [int(x) for x in f.read().splitlines()]
def part1(lines, preamble = 25):
for i, line in enumerate(lines[preamble:], preamble):
possible = lines[i - preamble : i]
for a in possible:
for b in possible:
if a + b == line:
break
else:
continue
break
else:
return line
def part2(lines, target):
for i, current in enumerate(lines):
sum = 0
for j in range(i + 1, len(lines)):
if sum == target:
group = lines[i : j - 1]
return min(group) + max(group)
if sum > target:
break
sum += lines[j]
j += 1
print(num := part1(lines))
print(part2(lines, num))
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name' : 'Invoicing',
'version' : '1.1',
'summary': 'Send Invoices and Track Payments',
'sequence': 30,
'description': """
Invoicing & Payments
====================
The specific and easy-to-use Invoicing system in Odoo allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your vendors and customers.
You could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. This module also offers you an easy method of registering payments, without having to encode complete abstracts of account.
""",
'category': 'Accounting',
'website': 'https://www.odoo.com/page/billing',
'images' : ['images/accounts.jpeg','images/bank_statement.jpeg','images/cash_register.jpeg','images/chart_of_accounts.jpeg','images/customer_invoice.jpeg','images/journal_entries.jpeg'],
'depends' : ['base_setup', 'product', 'analytic', 'report', 'web_planner'],
'data': [
'security/account_security.xml',
'security/ir.model.access.csv',
'data/data_account_type.xml',
'data/account_data.xml',
'views/account_menuitem.xml',
'views/account_payment_view.xml',
'wizard/account_reconcile_view.xml',
'wizard/account_unreconcile_view.xml',
'wizard/account_move_reversal_view.xml',
'views/account_view.xml',
'views/account_report.xml',
'wizard/account_invoice_refund_view.xml',
'wizard/account_validate_move_view.xml',
'wizard/account_invoice_state_view.xml',
'wizard/pos_box.xml',
'views/account_end_fy.xml',
'views/account_invoice_view.xml',
'data/invoice_action_data.xml',
'views/partner_view.xml',
'views/product_view.xml',
'views/account_analytic_view.xml',
'views/res_config_view.xml',
'views/account_tip_data.xml',
'views/account.xml',
'views/report_invoice.xml',
'report/account_invoice_report_view.xml',
'report/inherited_layouts.xml',
'views/account_journal_dashboard_view.xml',
'views/report_overdue.xml',
'views/web_planner_data.xml',
'views/report_overdue.xml',
'wizard/account_report_common_view.xml',
'wizard/account_report_print_journal_view.xml',
'views/report_journal.xml',
'wizard/account_report_partner_ledger_view.xml',
'views/report_partnerledger.xml',
'wizard/account_report_general_ledger_view.xml',
'views/report_generalledger.xml',
'wizard/account_report_trial_balance_view.xml',
'views/report_trialbalance.xml',
'views/account_financial_report_data.xml',
'wizard/account_financial_report_view.xml',
'views/report_financial.xml',
'wizard/account_report_aged_partner_balance_view.xml',
'views/report_agedpartnerbalance.xml',
'views/tax_adjustments.xml',
'wizard/wizard_tax_adjustments_view.xml',
],
'demo': [
'demo/account_demo.xml',
],
'qweb': [
"static/src/xml/account_reconciliation.xml",
"static/src/xml/account_payment.xml",
"static/src/xml/account_report_backend.xml",
],
'installable': True,
'application': True,
'auto_install': False,
'post_init_hook': '_auto_install_l10n',
}
|
class HTMLTable:
"""Class to easily generate a ranking table in HTML for WordPress"""
def __init__(self, columns: int):
self.columns = columns
self.header = str()
self.rows = list()
def add_header(self, *cells):
if len(cells) != self.columns:
return
self.header = '<thead><tr>'
for cell in cells:
self.header += f'<th>{cell}</th>'
self.header += '</tr></thead>'
def add_row(self, *cells):
if len(cells) != self.columns:
return
row = str()
if len(self.rows) % 2 != 0:
row += '<tr class="table-row-even">'
else:
row += '<tr class="table-row-odd">'
for cell in cells:
try:
int(cell)
row += f'<td class="data-number">{cell}</td>'
except ValueError:
row += f'<td class="data-text">{cell}</td>'
row += '</tr>'
self.rows.append(row)
def generate(self):
html = '<figure class="wp-block-table tg is-style-stripes"><table>'
if len(self.header) > 0:
html += self.header
if len(self.rows) > 0:
html += '<tbody>'
for row in self.rows:
html += row
html += '</tbody>'
html += '</figure></table>'
return html
|
Cell = DT('Cell', ('vitality', int))
def main():
assert match(Cell(50), ("Cell(n)", lambda n: n + 1)) == 51, "Match"
m = match(Cell(20))
if m('Cell(21)'):
assert False, "Wrong block intlit match"
elif m('Cell(x)'):
assert m.x == 20, "Block intlit binding"
return 0
|
# Author: Ben Wichser
# Date: 12/13/2019
# Description: Play the breakout game. What's the score after winning? see www.adventofcode.com/2019 (day 13) for more information
class IntCode:
"""
IntCode Computer.
Public Data Members:
code_list -- intcode instruction set
Public Methods:
intcode_run -- runs computer.
"""
def __init__(self, code_list):
"""
Creates IntCode computer. Sets i (index, int) and relative_base to zero. Accepts code_list (instructions, list).
"""
self.code_list = code_list
self.i = 0
self.relative_base = 0
self.code_list[0] = 2
def intcode_run(self, computer_input):
"""
Runs computer. Returns output from code 4 or 'Halt' from code 99
"""
self.computer_input = computer_input
while True:
# reads raw opcode
self.raw_opcode = self.code_list[self.i]
self.i += 1
# does intcode operation direction parsing
(self.opcode, self.raw_parameter_code_list) = self.__intcode_parse(self.raw_opcode)
# Ensure the parameter code list is correct length for the code.
self.parameter_code_list = self.__parameter_code_sizer(
self.opcode, self.raw_parameter_code_list)
# Create actual list of parameters for each opcode operation
self.parameter_list = []
# grabs parameters, as necessary
self.index = 0
while len(self.parameter_list) < len(self.parameter_code_list):
self.parameter_list.append(self.__parameter_tuple_maker(
self.parameter_code_list[self.index], self.code_list, self.i))
self.i += 1
self.index += 1
if self.opcode == 1:
self.__intcode_one(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 2:
self.__intcode_two(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 3:
self.__intcode_three(self.parameter_list, self.code_list,
self.relative_base, self.computer_input)
elif self.opcode == 4:
return self.__intcode_four(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 5:
self.i = self.__intcode_five(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 6:
self.i = self.__intcode_six(self.parameter_list, self.code_list, self.relative_base, self.i)
elif self.opcode == 7:
self.__intcode_seven(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 8:
self.__intcode_eight(self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 9:
self.relative_base = self.__intcode_nine(
self.parameter_list, self.code_list, self.relative_base)
elif self.opcode == 99:
return self.__intcode_ninetynine(self.parameter_list, self.code_list)
else:
print('and I oop... opcode error')
def __intcode_parse(self, code):
"""Private. Accepts intcode. Parses intcode and returns individual parameters. """
self.code = code
self.actual_code = self.code % 100
self.parameter_piece = self.code - self.actual_code
self.parameter_piece = self.parameter_piece // 100
self.parameter_code_list = []
while self.parameter_piece > 0:
self.parameter_code_list.append(self.parameter_piece % 10)
self.parameter_piece = self.parameter_piece // 10
return (self.actual_code, self.parameter_code_list)
def __parameter_code_sizer(self, opcode, raw_parameter_code_list):
"""Ensures parameter code list is the correct length, according to the particular opcode."""
self.parameter_lengths = {1: 3, 2: 3, 3: 1, 4: 1,
5: 2, 6: 2, 7: 3, 8: 3, 9: 1, 99: 0}
while len(self.raw_parameter_code_list) < self.parameter_lengths[self.opcode]:
self.raw_parameter_code_list.append(0)
return self.raw_parameter_code_list
def __code_list_lengthener(self, code_list, parameter):
"""Ensures that code_list is long enough to accept an item in its parameter-th location"""
while len(self.code_list) < parameter + 1:
self.code_list.append(0)
return self.code_list
def __parameter_tuple_maker(self, parameter_code, code_list, i):
"""
Accepts parameter_code, code_list, relative_base, and i.
Returns parameter_code, parameter tuple for opcode operation.
"""
return (parameter_code, self.code_list[i])
def __parameter_tuple_parser(self, parameter_tuple, code_list, relative_base):
"""
Accepts parameter_tuple, code_list, and relative_base. Returns parameter for use in intcode operation.
"""
if parameter_tuple[0] == 0:
self.__code_list_lengthener(self.code_list, parameter_tuple[1])
return self.code_list[parameter_tuple[1]]
elif parameter_tuple[0] == 1:
return parameter_tuple[1]
elif parameter_tuple[0] == 2:
self.__code_list_lengthener(self.code_list, parameter_tuple[1]+ self.relative_base)
return self.code_list[parameter_tuple[1] + relative_base]
else:
print('And I oop.... parameter_tuple_parser')
def __intcode_one(self, parameter_list, code_list, relative_base):
"""Adds elements in the parameter_list's first two elements. Places sum in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]
] = self.parameter_list[0] + self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[-1][1]+ self.relative_base)
self.code_list[self.parameter_list[-1][1] +
self.relative_base] = self.parameter_list[0] + self.parameter_list[1]
else:
print("And I oop... intcode_one")
return True
def __intcode_two(self, parameter_list, code_list, relative_base):
"""Multiplies elements in the parameter_list's first two elements. Places product in parameter_list[2]. Returns True. """
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1][1])
self.code_list[self.parameter_list[-1][1]
] = self.parameter_list[0] * self.parameter_list[1]
elif self.parameter_list[-1][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[-1][1] + self.relative_base)
self.code_list[self.parameter_list[-1][1] +
self.relative_base] = self.parameter_list[0] * self.parameter_list[1]
else:
print("And I oop...intcode_two")
return True
def __intcode_three(self, parameter_list, code_list, relative_base, computer_input):
""" Accepts input and places it in parameter_list[0] place in code_list. Returns True. """
if self.parameter_list[0][0] == 0:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[0][1])
self.code_list[self.parameter_list[0][1]] = computer_input
elif self.parameter_list[0][0] == 2:
self.code_list = self.__code_list_lengthener(
self.code_list, self.parameter_list[0][1]+ self.relative_base)
self.code_list[self.parameter_list[0][1] + self.relative_base] = computer_input
else:
print("And I oop...intcode_three")
return True
def __intcode_four(self, parameter_list, code_list, relative_base):
""" Returns item in parameter_list[0] place in code_list. """
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
return self.parameter_list[-1]
def __intcode_five(self, parameter_list, code_list, relative_base, i):
"""If first parameter is non-zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(
self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] != 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_six(self, parameter_list, code_list, relative_base, i):
"""If first parameter is zero, sets instruction pointer to second parameter. Returns i"""
for j in range(len(self.parameter_list)):
self.parameter_list[j] = self.__parameter_tuple_parser(
self.parameter_list[j], self.code_list, self.relative_base)
if self.parameter_list[0] == 0:
self.i = self.parameter_list[-1]
return self.i
def __intcode_seven(self, parameter_list, code_list, relative_base):
"""If first parameter is less than second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] < self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_eight(self, parameter_list, code_list, relative_base):
"""If first parameter is equal to second parameter, stores 1 in third parameter. Else stores 0 in third parameter. Returns True"""
for i in range(len(self.parameter_list) - 1):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
if self.parameter_list[-1][0] == 0:
self.parameter_list[-1] = self.parameter_list[-1][1]
elif self.parameter_list[-1][0] == 2:
self.parameter_list[-1] = self.parameter_list[-1][1] + self.relative_base
if self.parameter_list[0] == self.parameter_list[1]:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[parameter_list[-1]] = 1
else:
self.code_list = self.__code_list_lengthener(self.code_list, self.parameter_list[-1])
self.code_list[self.parameter_list[-1]] = 0
return True
def __intcode_nine(self, parameter_list, code_list, relative_base):
""" Adjust the relative base by the first parameter. Returns new relative_base"""
for i in range(len(self.parameter_list)):
self.parameter_list[i] = self.__parameter_tuple_parser(
self.parameter_list[i], self.code_list, self.relative_base)
self.relative_base += self.parameter_list[0]
return self.relative_base
def __intcode_ninetynine(self, parameter_list, code_list):
"""Returns False, so we can exit loop and script."""
return 'Halt'
class Breakout:
"""
Breakout Game. Requires IntCode Computer.
Public Data Members:
width - width of the game board
height -- height of the game board
Public Methods:
play_game - plays the Breakout Game
print_grid - prints the game board
"""
def __init__(self, width, height):
"""
Initializes the breakout game. Sets the game's width and height according to inputs. Initializes initial locations of _ball_location and _paddle_location, each to (0,0).
"""
self.width = width
self.height = height
self._ball_location = (0,0)
self._paddle_location = (0,0)
self._grid = self.__grid_maker(self.width, self.height)
def play_game(self, computer):
"""
Autoplays the breakout game, using intcode computer object for calculations.
"""
self.computer = computer
instruction_list = []
keep_going = True
while keep_going:
while len(instruction_list) < 3:
self._computer_input = self.__input_generator(self._ball_location, self._paddle_location)
output = self.computer.intcode_run(self._computer_input)
if output == 'Halt':
keep_going = False
else:
instruction_list.append(output)
game_won = self.__win_check(instruction_list)
if game_won == True:
keep_going = False
else:
self._grid, self._ball_location, self._paddle_location = self.__update_game(self._grid, instruction_list)
self.print_grid(self._grid)
instruction_list = []
def print_grid(self, grid):
"""Prints the game grid."""
for row in grid:
for column in row:
if column !='.':
print(column, end='')
print('')
return True
def __input_generator(self, ball_location, paddle_location):
""" Private. Accepts ball and paddle locations. Produces and returns the input for computer (paddle movement)."""
if ball_location[1] > paddle_location[1]:
computer_input = 1
elif ball_location[1] < paddle_location[1]:
computer_input = -1
else:
computer_input = 0
return computer_input
def __grid_maker(self, width, height):
"""Private method. Accepts width, height (ints). Returns width x height grid with '.' as values."""
grid = [['.' for _ in range(width)] for _ in range(height)]
return grid
def __update_game(self, grid, instruction_list):
"""Updates the game board according to rules."""
location_y = instruction_list[1]
location_x = instruction_list[0]
tile = instruction_list[2]
if tile == 0:
grid[location_y][location_x] = ' '
elif tile == 1:
grid[location_y][location_x] = '#'
elif tile == 2:
grid[location_y][location_x] = 'B'
elif tile == 3:
grid[location_y][location_x] = '_'
self._paddle_location = (location_y, location_x)
elif tile == 4:
grid[location_y][location_x] = 'O'
self._ball_location = (location_y, location_x)
else:
print('And I oop...play_game')
return grid, self._ball_location, self._paddle_location
def __win_check(self, instruction_list):
"""Private. Checks to see if the game is won. If so, returns True and prints score. Else returns false."""
if instruction_list[0] == -1 and instruction_list[1] == 0:
number_of_blocks = 0
for k in range(len(self._grid)):
for j in range(len(self._grid[k])):
if self._grid[k][j] == 'B':
number_of_blocks += 1
if number_of_blocks == 0:
print('You won! Final score:', instruction_list[2])
return True
return False
code_list = [1,380,379,385,1008,2531,381039,381,1005,381,12,99,109,2532,1101,0,0,383,1101,0,0,382,21002,382,1,1,21002,383,1,2,21101,0,37,0,1106,0,578,4,382,4,383,204,1,1001,382,1,382,1007,382,43,381,1005,381,22,1001,383,1,383,1007,383,22,381,1005,381,18,1006,385,69,99,104,-1,104,0,4,386,3,384,1007,384,0,381,1005,381,94,107,0,384,381,1005,381,108,1106,0,161,107,1,392,381,1006,381,161,1101,-1,0,384,1105,1,119,1007,392,41,381,1006,381,161,1102,1,1,384,20101,0,392,1,21102,20,1,2,21101,0,0,3,21101,138,0,0,1106,0,549,1,392,384,392,20102,1,392,1,21102,20,1,2,21102,1,3,3,21101,0,161,0,1105,1,549,1101,0,0,384,20001,388,390,1,21001,389,0,2,21102,180,1,0,1105,1,578,1206,1,213,1208,1,2,381,1006,381,205,20001,388,390,1,20101,0,389,2,21101,205,0,0,1106,0,393,1002,390,-1,390,1102,1,1,384,20101,0,388,1,20001,389,391,2,21101,0,228,0,1106,0,578,1206,1,261,1208,1,2,381,1006,381,253,21001,388,0,1,20001,389,391,2,21102,253,1,0,1106,0,393,1002,391,-1,391,1101,0,1,384,1005,384,161,20001,388,390,1,20001,389,391,2,21101,0,279,0,1105,1,578,1206,1,316,1208,1,2,381,1006,381,304,20001,388,390,1,20001,389,391,2,21101,304,0,0,1106,0,393,1002,390,-1,390,1002,391,-1,391,1101,0,1,384,1005,384,161,21002,388,1,1,21002,389,1,2,21101,0,0,3,21102,1,338,0,1106,0,549,1,388,390,388,1,389,391,389,21002,388,1,1,20101,0,389,2,21101,4,0,3,21102,1,365,0,1106,0,549,1007,389,21,381,1005,381,75,104,-1,104,0,104,0,99,0,1,0,0,0,0,0,0,291,19,17,1,1,21,109,3,22101,0,-2,1,21202,-1,1,2,21102,0,1,3,21102,1,414,0,1105,1,549,22102,1,-2,1,22101,0,-1,2,21102,1,429,0,1106,0,601,1202,1,1,435,1,386,0,386,104,-1,104,0,4,386,1001,387,-1,387,1005,387,451,99,109,-3,2106,0,0,109,8,22202,-7,-6,-3,22201,-3,-5,-3,21202,-4,64,-2,2207,-3,-2,381,1005,381,492,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,481,21202,-4,8,-2,2207,-3,-2,381,1005,381,518,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,507,2207,-3,-4,381,1005,381,540,21202,-4,-1,-1,22201,-3,-1,-3,2207,-3,-4,381,1006,381,529,22101,0,-3,-7,109,-8,2106,0,0,109,4,1202,-2,43,566,201,-3,566,566,101,639,566,566,1202,-1,1,0,204,-3,204,-2,204,-1,109,-4,2106,0,0,109,3,1202,-1,43,593,201,-2,593,593,101,639,593,593,21002,0,1,-2,109,-3,2106,0,0,109,3,22102,22,-2,1,22201,1,-1,1,21102,479,1,2,21101,0,201,3,21101,946,0,4,21102,630,1,0,1105,1,456,21201,1,1585,-2,109,-3,2106,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,0,0,0,2,2,0,2,2,0,0,2,0,2,2,0,2,2,2,2,2,0,1,1,0,2,0,2,2,2,2,2,2,0,2,2,0,2,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,2,0,2,0,2,0,0,0,0,0,0,1,1,0,2,2,0,2,0,0,0,2,2,0,2,0,0,0,2,0,0,0,0,2,2,2,0,2,0,0,0,2,0,2,2,0,0,2,0,2,0,2,2,0,1,1,0,0,2,0,2,0,0,2,2,2,2,2,0,2,0,2,2,0,0,0,2,2,0,0,2,2,0,2,2,2,0,0,2,0,2,0,2,0,0,2,0,1,1,0,2,0,2,0,2,2,2,0,0,0,0,0,0,2,0,2,0,0,2,0,2,0,0,2,0,0,0,0,2,2,0,2,2,0,0,2,0,0,0,0,1,1,0,0,0,2,2,2,2,0,2,2,2,2,0,2,0,0,2,2,0,2,2,2,0,0,0,2,2,0,0,2,2,0,0,0,0,2,2,0,0,2,0,1,1,0,0,0,0,0,0,2,2,2,2,2,2,0,0,2,2,0,0,2,2,2,0,0,2,2,2,0,2,0,2,0,0,2,0,2,2,2,0,2,0,0,1,1,0,2,0,0,0,0,2,2,2,0,0,2,0,0,2,0,2,2,2,2,0,2,0,2,0,0,0,0,2,0,2,2,0,2,2,0,2,2,0,2,0,1,1,0,0,2,2,0,2,2,0,2,0,2,0,2,0,2,0,0,0,0,2,2,2,2,0,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,0,0,1,1,0,0,2,0,0,2,2,2,0,2,0,0,2,2,0,2,2,0,0,0,2,2,0,2,2,2,0,0,2,0,0,0,0,2,2,2,0,0,0,2,0,1,1,0,0,2,2,0,0,2,0,2,2,2,2,0,2,2,2,2,2,2,2,2,2,0,2,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,2,0,1,1,0,0,0,2,2,2,0,2,0,0,0,0,2,2,2,2,2,2,2,2,0,0,0,2,2,2,2,2,0,0,2,0,0,0,0,2,2,0,2,2,0,1,1,0,2,0,0,2,2,0,2,0,0,0,2,2,2,2,2,2,0,2,2,0,2,0,2,2,0,2,2,0,2,2,2,2,2,0,0,2,0,0,0,0,1,1,0,2,0,0,2,0,2,0,0,2,0,0,2,2,2,2,2,0,2,0,2,2,0,2,2,0,0,2,2,0,0,0,2,2,0,2,2,0,2,2,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,37,59,35,82,55,63,50,72,81,61,59,5,1,69,3,36,79,19,94,73,56,24,20,10,1,25,20,49,14,41,74,10,1,48,97,35,54,11,81,35,36,54,58,49,82,25,96,37,51,26,65,35,51,78,95,58,66,62,83,44,62,53,19,35,90,77,50,38,53,16,24,10,59,72,21,24,91,15,80,80,83,67,27,51,49,31,38,51,10,47,22,68,71,30,19,57,64,6,63,91,63,34,53,95,87,27,83,15,5,2,22,23,34,80,75,27,15,88,73,28,23,4,85,54,68,43,55,31,81,78,16,88,75,85,8,9,27,82,95,34,86,94,31,33,42,94,26,98,73,73,74,89,43,1,55,63,21,93,97,18,57,41,66,83,32,13,67,23,80,22,95,8,68,26,8,76,22,10,53,56,76,11,82,77,83,31,43,49,45,19,72,13,7,21,40,58,94,67,16,84,38,11,62,22,56,5,2,42,2,38,37,83,3,74,9,4,52,91,38,45,31,60,81,52,19,7,54,49,64,73,26,11,38,84,49,79,48,92,48,28,88,71,8,66,86,44,90,21,73,33,15,5,34,34,30,66,29,13,59,30,7,52,59,77,71,4,42,28,73,50,40,77,33,18,66,5,36,49,98,48,29,32,21,10,18,2,79,44,67,19,26,64,27,92,29,3,19,67,73,44,41,49,45,34,61,65,97,56,4,44,85,38,19,43,61,10,97,44,3,93,86,71,36,52,95,36,13,28,53,2,79,66,92,38,8,92,47,40,78,51,67,22,42,76,49,41,23,47,49,87,81,26,11,20,17,11,93,64,78,63,29,80,54,20,62,45,78,38,6,14,14,62,86,10,17,77,60,20,77,42,6,68,28,62,37,44,17,85,16,33,55,85,11,35,2,8,3,88,4,67,16,97,51,40,72,70,45,28,36,47,48,95,60,77,63,1,31,54,52,18,25,46,39,58,86,26,75,48,85,34,56,93,16,98,36,24,61,63,90,32,93,16,53,48,74,73,95,43,81,55,85,29,32,91,34,4,14,3,24,41,44,64,7,78,19,17,75,71,16,22,75,78,89,93,12,90,54,38,61,3,54,61,69,58,17,27,46,75,19,13,46,53,33,87,25,65,67,22,50,90,53,98,11,54,52,57,4,49,92,73,26,70,43,12,7,70,7,58,13,8,27,12,20,86,45,3,98,56,66,58,47,52,87,79,31,37,48,56,46,26,50,75,1,24,96,67,94,11,56,57,7,58,2,21,57,40,64,73,81,13,58,68,45,32,55,13,91,43,59,62,34,28,44,35,68,35,70,1,78,77,69,3,38,11,63,12,56,13,20,82,58,59,22,69,34,82,80,86,15,30,92,39,49,75,27,83,59,89,35,86,19,26,18,50,9,91,82,4,63,57,22,96,54,72,3,76,8,19,24,81,92,76,86,48,70,72,72,75,97,36,95,44,53,40,81,81,33,7,55,58,23,13,24,16,24,67,88,13,32,98,62,71,49,72,52,34,9,61,78,33,72,38,30,35,17,66,35,81,79,62,45,64,11,67,69,49,33,91,74,24,21,36,84,14,75,87,21,57,88,79,70,74,62,4,45,35,76,1,84,74,59,25,3,88,38,34,97,82,31,17,56,95,40,21,77,9,4,1,40,68,60,26,45,55,17,51,7,34,82,27,82,24,72,84,42,72,23,11,48,42,51,22,49,9,80,31,51,39,15,64,44,40,36,67,97,70,39,48,71,75,12,62,11,22,19,80,78,11,58,98,98,69,3,6,14,29,41,10,76,27,5,58,18,22,73,80,34,53,51,87,5,31,13,82,34,10,59,20,10,39,89,12,59,84,31,66,73,7,19,69,86,85,2,34,20,87,28,98,19,50,74,95,69,87,63,63,67,11,47,56,38,9,28,25,46,69,28,63,95,65,83,41,19,78,50,96,77,52,84,37,71,92,51,92,35,97,46,17,71,43,58,54,26,38,9,90,56,9,55,85,52,63,20,8,63,23,24,63,81,22,86,11,90,74,23,19,52,53,22,52,15,85,13,37,52,69,36,10,68,20,54,77,35,15,17,46,88,38,57,69,15,38,60,70,40,17,12,79,33,17,88,90,72,2,62,23,91,41,18,56,22,38,35,37,11,23,381039]
#create computer
computer = IntCode(code_list)
# Create game
height = 25
width = 45
this_game = Breakout(width, height)
this_game.play_game(computer)
|
#!/usr/bin/env python3
mat_mul = __import__('8-ridin_bareback').mat_mul
mat1 = [[1, 2],
[3, 4],
[5, 6]]
mat2 = [[1, 2, 3, 4],
[5, 6, 7, 8]]
print(mat_mul(mat1, mat2))
|
OK = 0
ERROR = 1
INVALID_ARGUMENT = 2
INTERNAL_ERROR = 3
REQUIRE_LANG = 4
REQUIRE_CAPTCHA = 5
CAPTCHA_ERROR = 6
VALIDATE_CODE_ERROR = 7
PROTECT_OPERATE_ERROR = 8
PROTECT_OPERATE_REQUIRED = 9
REQUIRE_NUMBER = 10
IMAGE_FORMAT_ERROR = 11
FILE_FORMAT_ERROR = 12
IMAGE_TOO_BIG = 13
CANCEL_FAILED = 14
EDIT_FAILED = 15
ADD_FAILED = 16
CAN_NOT_CANCEL = 17
STATUS_PASS = 18
DELETE_ERROR = 19
STATUS_FINISH = 20
STATUS_CREATED = 21
STATUS_NOT_PASS = 22
IP_NOT_ALLOW = 23
ACCESS_ID_NOT_EXIST = 24
SIGNATURE_ERROR = 25
STATUS_PROCESSING = 26
TOO_MANY_REQUESTS = 27
CAPTCHA_WAS_USED = 28
SMS_REQUEST_TOO_MANY = 29
CAS_ERROR = 30
APP_UPDATE_CONFIG_EXISTS = 31
APP_VERSION_LESS = 32
APP_UPDATE_LOG_REPEAT = 33
INVALID_APP_CLIENT_VERSION = 34
MESSAGES = {
# 0-99 common error
0: 'OK',
1: 'Error',
2: 'Invalid argument',
3: 'Internal error',
4: 'The header is missing a accept-language',
5: 'Captcha is missing',
6: 'Captcha error',
7: 'Verification code error',
8: 'Protect operate error',
9: 'Protect operate is required.',
10: 'Number is required.',
11: 'Only supports upload png/jpg/jpeg/bmp/gif image format.',
12: 'Only supports upload .xls file format.',
13: 'Only supports upload 6M.',
14: 'Cancel failed',
15: 'Edit failed',
16: 'Add failed',
17: 'Can not cancel',
18: 'Status pass',
19: 'Delete error',
20: 'Status finish',
21: 'Status created',
22: 'Status not pass',
23: 'IP not allow',
24: 'Access id not exist',
25: 'Signature error',
26: 'Status processing',
27: 'Too many requests',
28: 'Captcha was used',
29: 'Sms request too many',
30: 'Cas api error',
31: 'App update config exists',
32: 'App version less than current',
33: 'App update log repeat',
34: 'Invalid app1 client version',
} |
class Computer:
__IMAGES = [
r'''
.----.
.---------. | == |
|.-"""""-.| |----|
|| || | == |
|| || |----|
|'-.....-'| |::::|
`"")---(""` |___.|
/:::::::::::\" _ "
/:::=======:::\`\`\
`"""""""""""""` '-'
''',
r'''
.----.
.---------. | == |
|.-"""""-.| |----|
|| * * || | == |
|| \---/ || |----|
|'-.....-'| |::::|
`"")---(""` |___.|
/:::::::::::\" _ "
/:::=======:::\`\`\
`"""""""""""""` '-'
''',
]
def __init__(
self,
is_turned_on=True,
keyboard='Redragon Karura',
mouse='Common Genius',
monitor='Samsung S19C300',
speakers='Common Genius',
case='Sentey 199',
cpu='Amd Bulldozer FX 6300'
):
self.__is_turned_on = is_turned_on
self.__keyboard = keyboard
self.__mouse = mouse
self.__monitor = monitor
self.__speakers = speakers
self.__case = case
self.__cpu = cpu
def on(self):
self.__is_turned_on = True
def off(self):
self.__is_turned_on = False
def show(self):
if self.__is_turned_on:
print(self.__IMAGES[1])
else:
print(self.__IMAGES[0])
# Getters and Setters
def get_keyboard(self):
return self.__keyboard
def get_mouse(self):
return self.__mouse
def get_monitor(self):
return self.__monitor
def get_speakers(self):
return self.__speakers
def get_case(self):
return self.__case
def get_cpu(self):
return self.__keyboard
def set_keyboard(self, keyboard):
self.__keyboard = keyboard
def set_mouse(self, mouse):
self.__mouse = mouse
def set_monitor(self, monitor):
self.__monitor = monitor
def set_speakers(self, speakers):
self.__speakers = speakers
def set_case(self, case):
self.__case = case
def set_cpu(self, cpu):
self.__cpu = cpu
def run():
pc_nasa = Computer()
if __name__ == '__main__':
run()
|
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
def my_startswith(haystack: str, needle: str, start: int):
if len(needle) + start > len(haystack):
return False
for i in range(len(needle)):
if haystack[start + i] != needle[i]:
return False
return True
if needle == '':
return 0
for i in range(len(haystack) - len(needle) + 1):
if my_startswith(haystack, needle, i):
return i
return -1
|
# -*- coding: utf-8 -*-
{
'name': "eJob Recruitment",
'sequence': 1,
'summary': """
A job recruitment module.""",
'description': """
A job recruitment module
""",
'author': "Kamrul",
'website': "http://www.yourcompany.com",
'category': 'Services',
'version': '0.1',
'license': 'LGPL-3',
'website': "http://www.yourcompany.com",
'depends': ['base', 'mail', 'hr', 'website'],
'data': [
'security/security.xml',
'security/ir.model.access.csv',
'data/application_sequence.xml',
'views/all_munu_items.xml',
'views/job_position_views.xml',
'views/job_applicant_views.xml',
'views/recruit_stage_views.xml',
'views/tags_views.xml',
'views/department_views.xml',
'views/employee_views.xml',
'views/website_view_form.xml',
'views/website_job_view.xml',
'reports/applicant_report.xml',
],
'demo': [
# 'demo/demo.xml',
],
'installable': True,
'application': True,
'auto_install': False,
}
|
"""
Finds the maximum path sum in a given triangle of numbers
"""
def max_path_sum_in_triangle(triangle):
"""
Finds the maximum sum path in a triangle(tree) and returns it
:param triangle:
:return: maximum sum path in the given tree
:rtype: int
"""
length = len(triangle)
for _ in range(length - 1):
a = triangle[-1]
b = triangle[-2]
for y in range(len(b)):
b[y] += max(a[y], a[y + 1])
triangle.pop(-1)
triangle[-1] = b
return triangle[0][0]
if __name__ == "__main__":
triangle_1 = [
[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48],
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31],
[4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23],
]
print(f"Maximum path sum in {triangle_1} is {max_path_sum_in_triangle(triangle_1)}")
with open("triangle.txt", "r") as numbers:
triangle_2 = []
for line in numbers:
k = [int(x) for x in line.split(" ")]
triangle_2.append(k)
print(f"Maximum path sum in {triangle_2} is {max_path_sum_in_triangle(triangle_2)}")
|
#
# PySNMP MIB module ELTEX-MES-COPY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-COPY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:01:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
eltMesCopy, = mibBuilder.importSymbols("ELTEX-MES", "eltMesCopy")
InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress")
RlCopyLocationType, = mibBuilder.importSymbols("RADLAN-COPY-MIB", "RlCopyLocationType")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
TimeTicks, Bits, Integer32, NotificationType, ObjectIdentity, Gauge32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Unsigned32, IpAddress, iso, ModuleIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Bits", "Integer32", "NotificationType", "ObjectIdentity", "Gauge32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Unsigned32", "IpAddress", "iso", "ModuleIdentity", "Counter64")
RowStatus, DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention")
eltCopyAutoBackupEnable = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupEnable.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupEnable.setDescription('Enabling on automatic backup configuration.')
eltCopyAutoBackupTimeout = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 2), Unsigned32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupTimeout.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupTimeout.setDescription(' This MIB should be used in order to change the time-interval of automatic copy of running-config to external server. The value should be the number of minutes for the interval of time from the backup.')
eltCopyAutoBackupFilePath = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupFilePath.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupFilePath.setDescription('The name of the destination file.')
eltCopyAutoBackupServerAddress = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupServerAddress.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupServerAddress.setDescription('The Inet address of the destination remote host')
eltCopyAutoBackupOnWrite = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 5), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyAutoBackupOnWrite.setStatus('current')
if mibBuilder.loadTexts: eltCopyAutoBackupOnWrite.setDescription('Performing automatic backups every time you write configuration in memory.')
class EltCopyUserBackupStatus(TextualConvention, Integer32):
description = 'Starting backup manually.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("starting", 1), ("stopped", 2))
eltCopyUserBackupStart = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 6), EltCopyUserBackupStatus().clone('stopped')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyUserBackupStart.setStatus('current')
if mibBuilder.loadTexts: eltCopyUserBackupStart.setDescription('Starting backup manually.')
eltCopyBackupHistoryEnable = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 7), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryEnable.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryEnable.setDescription('Performing automatic backups every time you write configuration in memory.')
eltCopyBackupHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8), )
if mibBuilder.loadTexts: eltCopyBackupHistoryTable.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryTable.setDescription('A DHCP interface configuration table.')
eltCopyBackupHistoryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1), ).setIndexNames((0, "ELTEX-MES-COPY-MIB", "eltCopyBackupHistoryIndex"))
if mibBuilder.loadTexts: eltCopyBackupHistoryEntry.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryEntry.setDescription('A DHCP interface configuration entry.')
eltCopyBackupHistoryIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 1), Integer32())
if mibBuilder.loadTexts: eltCopyBackupHistoryIndex.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryIndex.setDescription('An arbitrary incremental index for the profiles table. Zero for next free index.')
eltCopyBackupHistoryDateTime = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 2), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryDateTime.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryDateTime.setDescription('Name of profile.')
eltCopyBackupHistoryDstLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 3), RlCopyLocationType()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryDstLocation.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryDstLocation.setDescription('Destination File Location')
eltCopyBackupHistoryServerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 4), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryServerAddr.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryServerAddr.setDescription('Name of profile.')
eltCopyBackupHistoryFilePath = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 5), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryFilePath.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryFilePath.setDescription('Name of profile.')
eltCopyBackupHistoryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 8, 1, 6), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryStatus.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryStatus.setDescription('The status of a table entry. Only three statuses are aceptable: CreateAndGo to create, Active to update,Destroy to delete. All other values cause error.')
eltCopyBackupHistoryAction = MibScalar((1, 3, 6, 1, 4, 1, 35265, 1, 23, 3, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noAction", 1), ("clearNow", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltCopyBackupHistoryAction.setStatus('current')
if mibBuilder.loadTexts: eltCopyBackupHistoryAction.setDescription('Used to clear backup Table.')
mibBuilder.exportSymbols("ELTEX-MES-COPY-MIB", eltCopyBackupHistoryFilePath=eltCopyBackupHistoryFilePath, eltCopyAutoBackupOnWrite=eltCopyAutoBackupOnWrite, eltCopyBackupHistoryDateTime=eltCopyBackupHistoryDateTime, eltCopyBackupHistoryServerAddr=eltCopyBackupHistoryServerAddr, eltCopyBackupHistoryTable=eltCopyBackupHistoryTable, eltCopyBackupHistoryDstLocation=eltCopyBackupHistoryDstLocation, eltCopyBackupHistoryEntry=eltCopyBackupHistoryEntry, EltCopyUserBackupStatus=EltCopyUserBackupStatus, eltCopyAutoBackupEnable=eltCopyAutoBackupEnable, eltCopyBackupHistoryEnable=eltCopyBackupHistoryEnable, eltCopyBackupHistoryAction=eltCopyBackupHistoryAction, eltCopyBackupHistoryIndex=eltCopyBackupHistoryIndex, eltCopyAutoBackupTimeout=eltCopyAutoBackupTimeout, eltCopyAutoBackupFilePath=eltCopyAutoBackupFilePath, eltCopyUserBackupStart=eltCopyUserBackupStart, eltCopyBackupHistoryStatus=eltCopyBackupHistoryStatus, eltCopyAutoBackupServerAddress=eltCopyAutoBackupServerAddress)
|
#Input: length of the series N
n=int(input())
if n <=0 or n >100: #Check for boundary conditions
print("invalid")
else: # Check for in range conditions
for i in range(1,n+1):
if i%2==0: #For even positions
sum=0
for j in range(1, i+1):
sum=sum+(j*j)
print(sum,end=' ')
else: #For odd positions
print(2*i,end=' ')
|
#
# PySNMP MIB module RADLAN-rndMng (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-rndMng
# Produced by pysmi-0.3.4 at Wed May 1 14:51:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType")
rnd, = mibBuilder.importSymbols("RADLAN-MIB", "rnd")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, Counter64, Bits, ModuleIdentity, Gauge32, MibIdentifier, Counter32, ObjectIdentity, IpAddress, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, NotificationType, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "Bits", "ModuleIdentity", "Gauge32", "MibIdentifier", "Counter32", "ObjectIdentity", "IpAddress", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "NotificationType", "iso")
RowStatus, TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "TruthValue", "DisplayString")
rndMng = ModuleIdentity((1, 3, 6, 1, 4, 1, 89, 1))
rndMng.setRevisions(('2012-12-04 00:00', '2012-04-04 00:00', '2009-02-24 00:00', '2007-10-24 00:00', '2006-06-20 00:00', '2004-06-01 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rndMng.setRevisionsDescriptions(('Added rlSysNameTable object.', 'Added rlScheduledReload object.', 'Added rlRunningCDBequalToStartupCDB object.', 'Added rlGroupManagement branch.', 'Added rlRebootDelay object', 'Initial version of this MIB.',))
if mibBuilder.loadTexts: rndMng.setLastUpdated('201212040000Z')
if mibBuilder.loadTexts: rndMng.setOrganization('Radlan Computer Communications Ltd.')
if mibBuilder.loadTexts: rndMng.setContactInfo('radlan.com')
if mibBuilder.loadTexts: rndMng.setDescription('The private MIB module definition for RND general management MIB.')
rndSysId = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rndSysId.setStatus('current')
if mibBuilder.loadTexts: rndSysId.setDescription('Identification of an RND device. The device type for each integer clarifies the sysObjectID in MIB - II.')
rndAction = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27))).clone(namedValues=NamedValues(("reset", 1), ("sendNetworkTab", 2), ("deleteNetworkTab", 3), ("sendRoutingTab", 4), ("deleteRoutingTab", 5), ("sendLanTab", 6), ("deleteLanTab", 7), ("deleteArpTab", 8), ("sendArpTab", 9), ("deleteRouteTab", 10), ("sendRouteTab", 11), ("backupSPFRoutingTab", 12), ("backupIPRoutingTab", 13), ("backupNetworkTab", 14), ("backupLanTab", 15), ("backupArpTab", 16), ("backupIPXRipTab", 17), ("backupIPXSAPTab", 18), ("resetStartupCDB", 19), ("eraseStartupCDB", 20), ("deleteZeroHopRoutingAllocTab", 21), ("slipDisconnect", 22), ("deleteDynamicLanTab", 23), ("eraseRunningCDB", 24), ("copyStartupToRunning", 25), ("none", 26), ("resetToFactoryDefaults", 27)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rndAction.setStatus('current')
if mibBuilder.loadTexts: rndAction.setDescription('This variable enables the operator to perform one of the specified actions on the tables maintained by the network device. Send actions require support of proprietery File exchange protocol.')
rndFileName = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 3), OctetString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rndFileName.setStatus('current')
if mibBuilder.loadTexts: rndFileName.setDescription('The name of the file used internally by RND for transferring tables maintained by network devices, using a prorietary File exchange protocol.')
rlSnmpVersionSupported = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSnmpVersionSupported.setStatus('current')
if mibBuilder.loadTexts: rlSnmpVersionSupported.setDescription('Indicates the snmp versions that are supported by this device.')
rlSnmpMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlSnmpMibVersion.setStatus('current')
if mibBuilder.loadTexts: rlSnmpMibVersion.setDescription('Indicates the snmp support version that is supported by this device.')
rlCpuUtilEnable = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 6), TruthValue().clone('true')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlCpuUtilEnable.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilEnable.setDescription('Enables measurement of the device CPU utilization. In order to get real values for rlCpuUtilDuringLastSecond, rlCpuUtilDuringLastMinute and rlCpuUtilDuringLast5Minutes, the value of this object must be true.')
rlCpuUtilDuringLastSecond = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLastSecond.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLastSecond.setDescription('Percentage of the device CPU utilization during last second. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last second).')
rlCpuUtilDuringLastMinute = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLastMinute.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLastMinute.setDescription('Percentage of the device CPU utilization during last minute. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last minute).')
rlCpuUtilDuringLast5Minutes = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 101))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlCpuUtilDuringLast5Minutes.setStatus('current')
if mibBuilder.loadTexts: rlCpuUtilDuringLast5Minutes.setDescription('Percentage of the device CPU utilization during the last 5 minutes. The value 101 is a dummy value, indicating that the CPU utilization was not measured (since measurement is disabled or was disabled during last 5 minutes).')
rlRebootDelay = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 10), TimeTicks()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlRebootDelay.setStatus('current')
if mibBuilder.loadTexts: rlRebootDelay.setDescription('Setting the variable will cause the device to reboot rlRebootDelay timeticks from the moment this variable was set. If not set, the variable will return a value of 4294967295. If set to 4294967295, reboot action is cancelled. The maximum delay is set by the host parameter: reboot_delay_max')
rlGroupManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 89, 1, 11))
rlGroupMngQuery = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("query", 1), ("idle", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlGroupMngQuery.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngQuery.setDescription('Setting value query will cause the device to query for UPNP devices on the network. The device will always return value idle for GET.')
rlGroupMngQueryPeriod = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 2), Integer32()).setUnits('seconds').setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlGroupMngQueryPeriod.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngQueryPeriod.setDescription('Sets desired interval between queries for UPNP devices on the network. Setting 0 will result in no such query. Note that the actual query interval might be less than the set value if another application running in the device requested a shorter interval. Likewise setting 0 will not necessarily stop periodic queries if another application is still interested in periodic polling.')
rlGroupMngLastUpdate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 11, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngLastUpdate.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngLastUpdate.setDescription('The last time rlGroupMng MIB was updated.')
rlGroupMngDevicesTable = MibTable((1, 3, 6, 1, 4, 1, 89, 1, 11, 4), )
if mibBuilder.loadTexts: rlGroupMngDevicesTable.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDevicesTable.setDescription('The table showing the discovered devices.')
rlGroupMngDeviceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1), ).setIndexNames((0, "RADLAN-rndMng", "rlGroupMngDeviceIdType"), (0, "RADLAN-rndMng", "rlGroupMngDeviceId"), (0, "RADLAN-rndMng", "rlGroupMngSubdevice"))
if mibBuilder.loadTexts: rlGroupMngDeviceEntry.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceEntry.setDescription(' The row definition for this table.')
rlGroupMngDeviceIdType = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 1), InetAddressType())
if mibBuilder.loadTexts: rlGroupMngDeviceIdType.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceIdType.setDescription('The IP address type of the discovered device ')
rlGroupMngDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 2), InetAddress())
if mibBuilder.loadTexts: rlGroupMngDeviceId.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceId.setDescription('The IP address of the discovered device ')
rlGroupMngSubdevice = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 3), Integer32())
if mibBuilder.loadTexts: rlGroupMngSubdevice.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngSubdevice.setDescription('A subdevice within the rlGroupMngDeviceId. Only subdevices with greatest specifity will be kept (specific UUID device is more specific than basic device which is in turn more specific than root device. ')
rlGroupMngDeviceDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceDescription.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceDescription.setDescription('The discovery protocol description of the device.')
rlGroupMngGroupMngEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngGroupMngEnabled.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngGroupMngEnabled.setDescription('Indicates whether the device has Group Management enable.')
rlGroupMngGroupLLDPDeviceId = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngGroupLLDPDeviceId.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngGroupLLDPDeviceId.setDescription('The LLDP device id. If it is empty the device id is not known (either it is a non-MTS device or a non-LLDP supporting MTS device.')
rlGroupMngDeviceVendor = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceVendor.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceVendor.setDescription('The vendor of the device. If empty the vendor is not known.')
rlGroupMngDeviceAdvertisedCachingTime = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 8), Integer32()).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceAdvertisedCachingTime.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceAdvertisedCachingTime.setDescription('The caching time advertised by the device. If no update for this device has been received during this caching time the system will assume that the device has left the network and will therefore remove its entry from the table.')
rlGroupMngDeviceLocationURL = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 9), DisplayString()).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceLocationURL.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceLocationURL.setDescription('The URL inidicating the location of the XML presenting the details of the device.')
rlGroupMngDeviceLastSeen = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 11, 4, 1, 10), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlGroupMngDeviceLastSeen.setStatus('current')
if mibBuilder.loadTexts: rlGroupMngDeviceLastSeen.setDescription('The value of sysUpTime at the moment of last reception of an update for this device. ')
rlRunningCDBequalToStartupCDB = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 13), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlRunningCDBequalToStartupCDB.setStatus('current')
if mibBuilder.loadTexts: rlRunningCDBequalToStartupCDB.setDescription('Indicates whether there are changes in running CDB that were not saved in flash.')
rlClearMib = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 14), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlClearMib.setStatus('current')
if mibBuilder.loadTexts: rlClearMib.setDescription('Clear MIB value for scalars or tables: Delete all entries for tables with dynamic entries. Set table entries default values for table with static entries. Set scalar default value.')
rlScheduledReload = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 15), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlScheduledReload.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReload.setDescription("Used for requesting a delayed reload of the device in a specific desired time, should be configured in one of the following formats: 'athhmmddMM' , 'inhhhmmm' or '', setting this value to an empty string will result in request for cancellation of a (previously) committed system reload. to complete the request, the 'rlScheduledReloadCommit' must also be set to either TRUE (apply) or FALSE (discard) for completion of the transaction. failing from doing so will result in an indefinite lock of the API")
rlScheduledReloadPendingDate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 16), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 24))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlScheduledReloadPendingDate.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadPendingDate.setDescription("Displays the most recently requested scheduled-reload due date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no pending/scheduled reload request, string will be empty")
rlScheduledReloadApprovedDate = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 24))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlScheduledReloadApprovedDate.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadApprovedDate.setDescription("Displays the most recently approved/committed scheduled-reload date in 'inhhhmmathhmmssddMMYYYYw' format. where 'w' stands for weekDay (1-7). if there is no committed scheduled-reload , string will be empty")
rlScheduledReloadCommit = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 18), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlScheduledReloadCommit.setStatus('current')
if mibBuilder.loadTexts: rlScheduledReloadCommit.setDescription("commits the pending scheduled-reload request, and completes the transaction. when this value is set to TRUE, the system is instructed to perform the requested reload operation at the requested date/time as was given in 'rlScheduledReload'. setting this value to FALSE will discard the request.")
rlSysNameTable = MibTable((1, 3, 6, 1, 4, 1, 89, 1, 19), )
if mibBuilder.loadTexts: rlSysNameTable.setStatus('current')
if mibBuilder.loadTexts: rlSysNameTable.setDescription('Holds the current system name configuration.')
rlSysNameEntry = MibTableRow((1, 3, 6, 1, 4, 1, 89, 1, 19, 1), ).setIndexNames((0, "RADLAN-rndMng", "rlSysNameSource"), (0, "RADLAN-rndMng", "rlSysNameIfIndex"))
if mibBuilder.loadTexts: rlSysNameEntry.setStatus('current')
if mibBuilder.loadTexts: rlSysNameEntry.setDescription('The row definition of this table.')
rlSysNameSource = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("dhcpv6", 1), ("dhcpv4", 2), ("static", 3))).clone('static'))
if mibBuilder.loadTexts: rlSysNameSource.setStatus('current')
if mibBuilder.loadTexts: rlSysNameSource.setDescription("The system name source. 'static' if defined by user through CLI, 'dhcpv6' or 'dhcpv4' if received by DHCP network protocol.")
rlSysNameIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 2), InterfaceIndex().clone(1))
if mibBuilder.loadTexts: rlSysNameIfIndex.setStatus('current')
if mibBuilder.loadTexts: rlSysNameIfIndex.setDescription('The IfIndex from which the system-name configuration was received, for static entries, value will always be 1.')
rlSysNameName = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlSysNameName.setStatus('current')
if mibBuilder.loadTexts: rlSysNameName.setDescription("An administratively-assigned name for this managed node. By convention, this is the node's fully-qualified domain name. If the name is unknown, the value is the zero-length string.")
rlSysNameRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 89, 1, 19, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlSysNameRowStatus.setStatus('current')
if mibBuilder.loadTexts: rlSysNameRowStatus.setDescription('The row status variable, used according to row installation and removal conventions.')
rlErrdisableLinkFlappingCause = MibScalar((1, 3, 6, 1, 4, 1, 89, 1, 20), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlErrdisableLinkFlappingCause.setStatus('current')
if mibBuilder.loadTexts: rlErrdisableLinkFlappingCause.setDescription('Enable/Disable Link flapping error disable in the switch.')
mibBuilder.exportSymbols("RADLAN-rndMng", rlGroupMngDeviceAdvertisedCachingTime=rlGroupMngDeviceAdvertisedCachingTime, rlGroupManagement=rlGroupManagement, rlCpuUtilDuringLastMinute=rlCpuUtilDuringLastMinute, rlGroupMngDevicesTable=rlGroupMngDevicesTable, rlCpuUtilDuringLast5Minutes=rlCpuUtilDuringLast5Minutes, rlSysNameIfIndex=rlSysNameIfIndex, rlGroupMngDeviceIdType=rlGroupMngDeviceIdType, rlSysNameSource=rlSysNameSource, rlGroupMngLastUpdate=rlGroupMngLastUpdate, rlGroupMngDeviceLastSeen=rlGroupMngDeviceLastSeen, rndAction=rndAction, rlGroupMngDeviceLocationURL=rlGroupMngDeviceLocationURL, rlGroupMngDeviceVendor=rlGroupMngDeviceVendor, rlSysNameName=rlSysNameName, rlGroupMngDeviceEntry=rlGroupMngDeviceEntry, rlScheduledReloadApprovedDate=rlScheduledReloadApprovedDate, rndMng=rndMng, rlScheduledReloadCommit=rlScheduledReloadCommit, rndSysId=rndSysId, rlGroupMngSubdevice=rlGroupMngSubdevice, rlGroupMngDeviceDescription=rlGroupMngDeviceDescription, rlScheduledReload=rlScheduledReload, rlGroupMngQueryPeriod=rlGroupMngQueryPeriod, rlGroupMngDeviceId=rlGroupMngDeviceId, rlErrdisableLinkFlappingCause=rlErrdisableLinkFlappingCause, rlCpuUtilEnable=rlCpuUtilEnable, rlSnmpMibVersion=rlSnmpMibVersion, rlSysNameTable=rlSysNameTable, rndFileName=rndFileName, rlRebootDelay=rlRebootDelay, rlRunningCDBequalToStartupCDB=rlRunningCDBequalToStartupCDB, PYSNMP_MODULE_ID=rndMng, rlSnmpVersionSupported=rlSnmpVersionSupported, rlScheduledReloadPendingDate=rlScheduledReloadPendingDate, rlSysNameRowStatus=rlSysNameRowStatus, rlGroupMngGroupLLDPDeviceId=rlGroupMngGroupLLDPDeviceId, rlGroupMngQuery=rlGroupMngQuery, rlSysNameEntry=rlSysNameEntry, rlGroupMngGroupMngEnabled=rlGroupMngGroupMngEnabled, rlCpuUtilDuringLastSecond=rlCpuUtilDuringLastSecond, rlClearMib=rlClearMib)
|
s = '100'
print(s)
s = 'abc1234-09232<>?323'
print(s)
s = 'abc 123'
print(s)
s = ' '
print(s)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 8 17:29:02 2021
@author: dopiwoo
Given a binary tree and a number 'S', find if the tree has a path from root-to-leaf such that the sum of all the node
values of that path equals 'S'.
"""
class TreeNode:
def __init__(self, val: int = 0, left: 'TreeNode' = None, right: 'TreeNode' = None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return str(self.val)
def has_path(root: TreeNode, path_sum: int) -> bool:
"""
Time Complexity: O(N)
Space Complexity: O(N)
Parameters
----------
root : TreeNode
Input binary tree.
path_sum : int
Input number 'S'.
Returns
-------
bool
Whether the tree has a path from root-to-leaf such that the sum of all the node values of that path equals 'S'.
"""
if not root:
return False
if path_sum == root.val and not root.left and not root.right:
return True
return has_path(root.left, path_sum - root.val) or has_path(root.right, path_sum - root.val)
if __name__ == '__main__':
root_node = TreeNode(12)
root_node.left = TreeNode(7)
root_node.right = TreeNode(1)
root_node.left.left = TreeNode(9)
root_node.right.left = TreeNode(10)
root_node.right.right = TreeNode(5)
print(has_path(root_node, 23))
print(has_path(root_node, 16))
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class ProtocolProp(object):
def __init__(self, propName=None, propDesc=None, inputLength=None, inputDefault=None, unique=None, required=None):
"""
:param propName: (Optional) 属性名称
:param propDesc: (Optional) 属性描述
:param inputLength: (Optional) 属性值长度限制
:param inputDefault: (Optional) 属性默认值
:param unique: (Optional) 是否必填,0-非唯一,1-唯一
:param required: (Optional) 是否必填,0-非必填,1-必填
"""
self.propName = propName
self.propDesc = propDesc
self.inputLength = inputLength
self.inputDefault = inputDefault
self.unique = unique
self.required = required
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.