content
stringlengths
7
1.05M
n = float(input()) whole = int(n) fractional = int(round((n % 1), 2) * 100) print(whole, fractional)
frase = str(input('Digite uma palavra para saber, se ela é um políndromo: ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for letra in range(len(junto)-1,-1,-1): inverso += junto[letra] if junto == inverso: print('A palavra {} é um políndromo '.format(frase)) print(inverso) else: print('A palavra {} não é uma políndromo'.format(frase)) print(inverso)
class Spam(object): def __init__(self, key, value): self.list_ = [value] self.dict_ = {key : value} self.list_.append(value) self.dict_[key] = value print(f'List: {self.list_}') print(f'Dict: {self.dict_}') Spam('Key 1', 'Value 1') Spam('Key 2', 'Value 2')
lista = [5,7,9,2,4,3,1,6,8] comparaciones = 0 for i in range(len(lista) -1): #recorre la lista for j in range(len(lista)-1): #sirve para comparar los elementos de la lista #print('Comparando: ' , lista[j], "con ", lista[j+1]) if(lista[j] > lista[j+1]): #lista[j], lista[j+1] = lista[j+1] , lista[j] comparaciones += 1 temporal = lista[j] lista[j] = lista[j+1] lista[j+1] = temporal #print("Intecambiando: ", lista[j], "por ", lista[j+1]) print(lista) print(lista) #OPTIMIZAR CODIGO #CONCENTINELA lista = [5,7,9,2,4,3,1,6,8] comparaciones = 0 hay_cambios = True while hay_cambios: #recorre la lista hay_cambios = False for j in range(len(lista)-1): #sirve para comparar los elementos de la lista #print('Comparando: ' , lista[j], "con ", lista[j+1]) comparaciones += 1 if(lista[j] > lista[j+1]): #lista[j], lista[j+1] = lista[j+1] , lista[j] temporal = lista[j] lista[j] = lista[j+1] lista[j+1] = temporal hay_cambios = True #print("Intecambiando: ", lista[j], "por ", lista[j+1]) print(lista) print(comparaciones) lista = [5,7,9,2,4,3,1,6,8] comparaciones = 0 for i in range(len(lista) -1): #recorre la lista for j in range(len(lista) - i -1): #sirve para comparar los elementos de la lista #print('Comparando: ' , lista[j], "con ", lista[j+1]) if(lista[j] > lista[j+1]): #lista[j], lista[j+1] = lista[j+1] , lista[j] comparaciones += 1 temporal = lista[j] lista[j] = lista[j+1] lista[j+1] = temporal print(lista) #print("Intecambiando: ", lista[j], "por ", lista[j+1]) print(lista) print(comparaciones) lista = [5,7,9,2,4,3,1,6,8] comparaciones = 0 hay_cambios = True i = 0 while hay_cambios and i < len(lista)-1: #recorre la lista hay_cambios = False for j in range(len(lista) -i -1): #sirve para comparar los elementos de la lista #print('Comparando: ' , lista[j], "con ", lista[j+1]) comparaciones += 1 if(lista[j] > lista[j+1]): #lista[j], lista[j+1] = lista[j+1] , lista[j] temporal = lista[j] lista[j] = lista[j+1] lista[j+1] = temporal hay_cambios = True #print("Intecambiando: ", lista[j], "por ", lista[j+1]) i +=1 print(lista) print(comparaciones)
#Programa que pergunte a distancia de uma viagem, e cobre 0.50 cents por km até 200km e .45 para viagens mais longas distancia = int(input('Digite a distancia em km da sua viagem: ')) if distancia > 200: valor = (distancia * 0.45) else: valor = (distancia * 0.50) print(f'O valor cobrado pela sua viagem de {distancia}km, será de: {valor:.2f}R$')
# # PySNMP MIB module SW-TRUNK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-TRUNK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:05:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") enterprises, Gauge32, ObjectIdentity, Integer32, Counter32, ModuleIdentity, Bits, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, NotificationType, Unsigned32, MibIdentifier, iso, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "Gauge32", "ObjectIdentity", "Integer32", "Counter32", "ModuleIdentity", "Bits", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "NotificationType", "Unsigned32", "MibIdentifier", "iso", "Counter64") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class TrunkSetList(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 1) fixedLength = 1 marconi = MibIdentifier((1, 3, 6, 1, 4, 1, 326)) systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2)) external = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20)) dlink = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1)) dlinkcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1)) golf = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2)) golfproducts = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1)) es2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3)) golfcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2)) marconi_mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel("marconi-mgmt") es2000Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28)) swL2Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2)) swPortTrunk = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6)) swPortTrunkCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1), ) if mibBuilder.loadTexts: swPortTrunkCtrlTable.setStatus('mandatory') swPortTrunkCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1), ).setIndexNames((0, "SW-TRUNK-MIB", "swPortTrunkCtrlIndex")) if mibBuilder.loadTexts: swPortTrunkCtrlEntry.setStatus('mandatory') swPortTrunkCtrlIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkCtrlIndex.setStatus('mandatory') swPortTrunkCtrlAnchorPort = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swPortTrunkCtrlAnchorPort.setStatus('mandatory') swPortTrunkCtrlMasterPort = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkCtrlMasterPort.setStatus('mandatory') swPortTrunkCtrlName = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swPortTrunkCtrlName.setStatus('mandatory') swPortTrunkCtrlMember = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 5), TrunkSetList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swPortTrunkCtrlMember.setStatus('mandatory') swPortTrunkCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swPortTrunkCtrlState.setStatus('mandatory') swPortTrunkMemberTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2), ) if mibBuilder.loadTexts: swPortTrunkMemberTable.setStatus('mandatory') swPortTrunkMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1), ).setIndexNames((0, "SW-TRUNK-MIB", "swPortTrunkMemberIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberUnitIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberModuleIndex"), (0, "SW-TRUNK-MIB", "swPortTrunkMemberPortIndex")) if mibBuilder.loadTexts: swPortTrunkMemberEntry.setStatus('mandatory') swPortTrunkMemberIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkMemberIndex.setStatus('mandatory') swPortTrunkMemberUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkMemberUnitIndex.setStatus('mandatory') swPortTrunkMemberModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkMemberModuleIndex.setStatus('mandatory') swPortTrunkMemberPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 6, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swPortTrunkMemberPortIndex.setStatus('mandatory') mibBuilder.exportSymbols("SW-TRUNK-MIB", TrunkSetList=TrunkSetList, swPortTrunkMemberIndex=swPortTrunkMemberIndex, swPortTrunkCtrlAnchorPort=swPortTrunkCtrlAnchorPort, marconi=marconi, swPortTrunkCtrlName=swPortTrunkCtrlName, swPortTrunkCtrlTable=swPortTrunkCtrlTable, dlinkcommon=dlinkcommon, external=external, swPortTrunkCtrlIndex=swPortTrunkCtrlIndex, swPortTrunkMemberPortIndex=swPortTrunkMemberPortIndex, swPortTrunkMemberUnitIndex=swPortTrunkMemberUnitIndex, systems=systems, dlink=dlink, swPortTrunkMemberModuleIndex=swPortTrunkMemberModuleIndex, swPortTrunkCtrlEntry=swPortTrunkCtrlEntry, golfcommon=golfcommon, swPortTrunkMemberEntry=swPortTrunkMemberEntry, swPortTrunkCtrlMember=swPortTrunkCtrlMember, es2000Mgmt=es2000Mgmt, golf=golf, swPortTrunkMemberTable=swPortTrunkMemberTable, swPortTrunk=swPortTrunk, swPortTrunkCtrlState=swPortTrunkCtrlState, swPortTrunkCtrlMasterPort=swPortTrunkCtrlMasterPort, marconi_mgmt=marconi_mgmt, swL2Mgmt=swL2Mgmt, es2000=es2000, golfproducts=golfproducts)
class Twitter(): Consumer_Key = '' Consumer_Secret = '' Access_Token = '' Access_Token_Secret = '' CONNECTION_STRING = "sqlite:///Twitter.db" LANG = ["en"]
feature_types = { # features with continuous numeric values "continuous": [ "number_diagnoses", "time_in_hospital", "number_inpatient", "number_emergency", "num_procedures", "num_medications", "num_lab_procedures"], # features which describe buckets of a continuous-valued feature "range": ["age", "weight"], # features which take one of two or more non-continuous values "categorical": [ "diabetesMed", "chlorpropamide", "repaglinide", "medical_specialty", "rosiglitazone", "miglitol", "glipizide", "acetohexamide", "admission_source_id", "glipizide-metformin", "glyburide", "metformin", "tolbutamide", "pioglitazone", "glimepiride-pioglitazone", "glimepiride", "glyburide-metformin", "A1Cresult", "troglitazone", "metformin-rosiglitazone", "max_glu_serum", "acarbose", "metformin-pioglitazone", "payer_code", "discharge_disposition_id", "change", "gender", "nateglinide", "tolazamide", "race", "number_outpatient", "insulin", "admission_type_id", "diag_1", "diag_2", "diag_3"], # features which are either unique or constant for all samples "constant": ["patient_nbr", "encounter_id", "examide", "citoglipton"]}
def main() : #Create a set lstOrganizations = {"sharjeelswork", "Fiserv", "R Systems"} print(lstOrganizations) # Sets are unordered, so the items will appear in a random order. """Access Items You cannot access items in a set by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.""" #Loop through the set, and print the values for organization in lstOrganizations: print(organization) #Check if "banana" is present in the set print("gopesh" in lstOrganizations) """Change Items Once a set is created, you cannot change its items, but you can add new items. Add Items To add one item to a set use the add() method. To add more than one item to a set use the update() method.""" lstOrganizations.add("nashit") print(lstOrganizations) lstOrganizations.update(["Edynamic", "Sitecore"]) print(lstOrganizations) #Get the number of items in a set print(len(lstOrganizations)) #Remove Item : To remove an item in a set, use the remove(), or the discard() method. lstOrganizations.remove("nashit") #If the item to remove does not exist, remove() will raise an error. print(lstOrganizations) #To remove an item, use discard lstOrganizations.discard("Sitecore") #If the item to remove does not exist, discard() will NOT raise an error. print(lstOrganizations) """You can also use the pop(), method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed. The return value of the pop() method is the removed item.""" removedItem = lstOrganizations.pop() print(removedItem) print(lstOrganizations) #The clear() method empties the set lstOrganizations.clear() #The del keyword will delete the set completely del lstOrganizations #The set() Constructor : It is also possible to use the set() constructor to make a set. lstOrganizations = set(("sharjeelswork", "Fiserv", "R Systems")) # note the double round-brackets print(lstOrganizations) main()
arr = [1, 2, 3, 6, 9, 5, 7] # 创建数组 n = len(arr) # 获取数组的长度 for i in range(n): # 进行循环迭代 for j in range(0, n - i - 1): # 循环迭代 if arr[j] > arr[j + 1]: arr[j] = arr[j + 1] arr[j + 1] = arr[j] # 进行交换元素 print(arr)
while True: try: input() alice = set(input().split()) beatriz = set(input().split()) repeticoes = [1 for carta in alice if carta in beatriz] print(min([len(alice), len(beatriz)]) - len(repeticoes)) except EOFError: break
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/10/2017 Updated: 02/04/2018 # Description Given a set P = {(x₁, y₁), ..., (xᵢ, yᵢ)} of 2-dimensional points, then the so-called problem of "polynomial interpolation" consists in finding the polynomial of smallest degree which goes through these points, that is, a polynomial which "interpolates" these points. # References - Dr. prof. Kai Hormann's notes for the Numerical Algorithms course, fall, 2017. - https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.barycentric_interpolate.html - https://en.wikipedia.org/wiki/Lagrange_polynomial """ __all__ = ["barycentric", "compute_weights"] def compute_weights(xs: list) -> list: """Computes and returns the weights (as a list) used in the barycentric form of the Lagrange polynomial. This function avoids checking if the input list xs is well-formed for performance reasons. Time complexity: O(n²).""" n = len(xs) ws = [1] * n for i in range(n): for j in range(n): if j != i: ws[i] *= 1 / (xs[i] - xs[j]) return ws def barycentric(xs: list, ys: list, x0: float, ws: list = None) -> float: """Evaluates, at x coordinate x0, the polynomial that interpolates 2d points (xs[i], ys[i]), for i=0, ..., len(xs) - 1 == len(ys) - 1. In other words, this function returns the y value corresponding to the x coordinate x0 of the polynomial which interpolates the points (xs[i], ys[i]). For reasons of numerical stability, this function does not compute the coefficients of the polynomial. This function uses a "barycentric interpolation" method that treats the problem as a special case of rational function interpolation. This algorithm is quite stable, numerically, but even in a world of exact computation, unless the x coordinates are chosen very carefully, polynomial interpolation itself is a very ill-conditioned process due to the Runge phenomenon. The construction of the interpolation weights is a relatively slow process: it takes O(n²) time. If you want to call this many times with the same x coordinates (but possibly varying the corresponding y values or x0), you can first calculate the weights, using e.g. the function compute_weights in this same module, and then pass them as the parameter ws. If ws is None, then the weights are computed by this function at every call. If ws is not None, it should be a list of the same length as xs and ys and should clearly represent the weights as computed by the function compute_weights in this same module. Time complexity: O(n²), if ws is None, else O(n).""" if len(xs) != len(ys): raise ValueError("Lists xs and ys have different lengths.") if ws is None: ws = compute_weights(xs) else: if len(xs) != len(ws): raise ValueError("Lists xs and ws have different lengths.") n = 0 # Numerator d = 0 # Denominator: sum of all weights. for i in range(len(xs)): if x0 == xs[i]: return ys[i] else: w = ws[i] / (x0 - xs[i]) n += w * ys[i] d += w return n / d
# Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. # According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." # Example: # Input: citations = [3,0,6,1,5] # Output: 3 # Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had # received 3, 0, 6, 1, 5 citations respectively. # Since the researcher has 3 papers with at least 3 citations each and the remaining # two with no more than 3 citations each, her h-index is 3. class Solution: def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ citations.sort() for i in range(len(citations)): if len(citations) - i <= citations[i]: return len(citations) - i return 0 # Time: O(nlog(n)) # Space: O(1) # Difficulty: medium
def square(a): return(a*a) # a=int(input("enter the number")) # square(a) s=[2,3,4,5,6,7,8,9,10] print(list(map(square,s)))
""" @file @brief Exception for Mokadi. """ class MokadiException(Exception): """ Mokadi exception. """ pass # pylint: disable=W0107 class CognitiveException(Exception): """ Failure when calling the API. """ pass # pylint: disable=W0107 class WikipediaException(Exception): """ Issue with :epkg:`wikipedia`. """ pass # pylint: disable=W0107 class MokadiAuthentification(Exception): """ Issue with authentification. """ pass # pylint: disable=W0107
features = [ "mtarg1", "mtarg2", "mtarg3", "roll", "pitch", "LACCX", "LACCY", "LACCZ", "GYROX", "GYROY", "SC1I", "SC2I", "SC3I", "BT1I", "BT2I", "vout", "iout", "cpuUsage", ] fault_features = ["fault", "fault_type", "fault_value", "fault_duration"]
READ_ME =""" INDEXICAL is designed to assist in the creation of book indexes. It offers the following functionality: (1) Analyze a readable PDF, extracting capitalized phrases, italicized phrases, phrases in double quotation marks, and phrases surrounding by parentheses. (2) Filter through the results of (1) to generate a list of proper names and titles, correlating the latter to the former, while defining SUBHEADINGS, and attaching optional SEARCH PHRASES to HEADINGS and SUBHEADINGS, OR A LIST OF THE PAGES in which the ENTRY is found. (3) Run INDIVIDUAL searches on the interpreted PDF. SEARCHES allow unlimited logical complexity, and can be run by PAGE, SENTENCE, or for LITERAL PHRASES over PAGES, DESCRIMINATING BY NUMBER of APPEARANCE for LITERAL SEARCHES and PAGES OF APPEARANCE for all searches. (4) READ in PROPER NAMES, TITLES, and CONCEPTS from an EXCEL FILE. (5) RUN individual searches over a group of entries, and paste the results back into an EXCEL FILE, including the properly formatted results of the search. (6) GENERATE an INDEX from all terms, using, in each case, either the an automatically generates SEARCH PHRASE, the optional preset SEARCH PHRASE, or the pre-determined PAGES. (7) FORMAT THE INDEX, FOLLOWING THE SPECIFICATIONS for ALPHABETIZING and PAGE RANGE DISPLAY of the CHICAGO MANUAL OF SYLE (8) GENERATE a REVERSE INDEX from a given INDEX. (9) SCROLL THROUGH PAGES OF THE TEXT, SHOWING THE INDEXED TERMS for EACH PAGE, and identifying INDEXED TERMS that may not match the PAGE. """
"""Implements a class for Latin Square puzzles. A Latin Square is a square grid of numbers from 1..N, where a number may not be repeated in the same row or column. Such squares form the basis of puzzles like Sudoku, Kenken(tm), and their variants. Classes: LatinSquare: Implements a square puzzle constrained by not repeating values in the same row or column. Functions: build_empty_grid: Build a 2D array (list of lists) for puzzle. char2int: Convert bewteen character and integer representation of a cell value. int2char: Reverse of char2int. count_clues: Given a string or 2D array representing a puzzle, return the number of starting clues in the puzzle. from_string: Given a string representing a puzzle, return the 2D array equivalent. All class methods expect the array version. """ DEFAULT_PUZZLE_SIZE = 9 EMPTY_CELL = None # Have only tested up to 25x25 so set that max size here # higher values may work but aren't tested MAX_PUZZLE_SIZE = 25 MIN_PUZZLE_SIZE = 1 MIN_CELL_VALUE = 1 # 0 evals to False so can be confused with EMPTY_CELL CELL_VALUES = "123456789ABCDEFGHIJKLMNOP" assert MAX_PUZZLE_SIZE == len(CELL_VALUES) def build_empty_grid(grid_size): """Builds a 2D array grid_size * grid_size, each cell element is None.""" assert MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE ret = [[] for x in range(grid_size)] for x in range(grid_size): ret[x] = [EMPTY_CELL for y in range(grid_size)] return ret def char2int(char): """Converts character char to an int representation.""" if char in (".", "0"): return EMPTY_CELL return CELL_VALUES.index(char) + 1 def int2char(value): """Converts back from an int value to character value for a cell.""" if not value: return "." return CELL_VALUES[value - 1] def count_clues(puzzle_grid): """Counts clues in a puzzle_grid, which can be a list of lists or string.""" if isinstance(puzzle_grid, list): return sum([1 for sublist in puzzle_grid for i in sublist if i]) return len(puzzle_grid) - puzzle_grid.count(".") def from_string(puzzle_string): """Takes a string and converts it to a list of lists of integers. Puzzles are expected to be 2D arrays of ints, but it's convenient to store test data as strings (e.g. '89.4...5614.35..9.......8..9.....'). So this will split a string (using period for "empty cell") and return the 2D array. Args: puzzle_string: A string with 1 character per cell. Use uppercase letters for integer values >= 10 (A=10; B=11; etc). Trailing blanks are stripped. Returns: A list of lists of ints. Raises: ValueError: puzzle_string length is not a square (e.g. 4, 9, 16, 25); or a character value in string is out of range. """ s = puzzle_string.rstrip() grid_size = int(len(s) ** (1 / 2)) if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE: raise ValueError(f"puzzle_string {grid_size}x{grid_size} is out of range") if grid_size ** 2 != len(s): raise ValueError(f"puzzle_string {grid_size}x{grid_size} is not a square") ret = build_empty_grid(grid_size) for i, ch in enumerate(s): v = char2int(ch) if v and MIN_CELL_VALUE <= v <= grid_size: ret[i // grid_size][i % grid_size] = v elif v: raise ValueError(f"Cell value {v} at {i} out of range [1:{grid_size}]") return ret class LatinSquare: """Implements a Latin Square "puzzle". A Latin Square is a 2D matrix where the values in each cell cannot be repeated in the same row or column. Dimensions are always square (ie. width==height==grid_size). If no values are passed to constructor, will build an empty grid of size DEFAULT_PUZZLE_SIZE (9). Attributes: size: Dimensions of the square (length, height) in a tuple. num_cells: Total number of cells (grid_size * grid_size) max_value: Equal to grid_size, it's the max value of a cell, and also the grid's length and height. complete_set: Set of values from [1..max_value] that must exist once in each row and column in a solved puzzle. Args: starting_grid: A list of lists of integers (2D array of ints). Pass None to start with an empty grid. grid_size: The number of cells for the width and height of the grid. Default value is 9, for a 9x9 grid (81 cells). If not set, size is set to len(starting_grid), otherwise must be consistent with len(starting_grid) as a check for "bad" data. Raises: ValueError: An inconsistency exists in the starting_grid; or the grid_size is too small or too large (1 to 25) """ def __init__(self, grid_size=None, starting_grid=None): # If a starting_grid is passed, that sets the size if starting_grid and grid_size: if len(starting_grid) != grid_size: raise ValueError(f"starting_grid is not {grid_size}x{grid_size}") elif starting_grid: grid_size = len(starting_grid) elif grid_size is None: grid_size = DEFAULT_PUZZLE_SIZE if not MIN_PUZZLE_SIZE <= grid_size <= MAX_PUZZLE_SIZE: raise ValueError( f"grid_size={grid_size} outside [{MIN_PUZZLE_SIZE}:{MAX_PUZZLE_SIZE}]" ) # Attributes self.size = (grid_size, grid_size) self.num_cells = grid_size * grid_size self.max_value = grid_size self.complete_set = set(range(MIN_CELL_VALUE, grid_size + 1)) # Protected self._grid = build_empty_grid(grid_size) self.__num_empty_cells = grid_size * grid_size # Initialize constraints self.__allowed_values_for_row = [ set(self.complete_set) for i in range(grid_size) ] self.__allowed_values_for_col = [ set(self.complete_set) for i in range(grid_size) ] # Accept a starting puzzle if starting_grid: self.init_puzzle(starting_grid) def init_puzzle(self, starting_grid): """Initializes a puzzle grid based on contents of starting_grid. Clears the existing puzzle and resets internal state (e.g. count of empty cells remaining). Args: starting_grid: A list of lists of integers (2D array of ints). To help catch data errors, must be the same size as what the instance was initialized for. Raises: ValueError: Size of starting_grid (len) is not what was expected from the initial grid_size; or constraint on cell values is violated (e.g. dupicate value in a row) """ self.clear_all() # Check that new grid is correct number of rows if len(starting_grid) != self.max_value: raise ValueError(f"Exepect {self.max_value} rows, got {len(starting_grid)}") # Check that new grid has correct number of cols for x, row in enumerate(starting_grid): if len(row) != self.max_value: raise ValueError( f"Expect {self.max_value} columns in row {x}, got {len(row)}") for y, val in enumerate(row): if val: self.set(x, y, val) def num_empty_cells(self): """Returns the number of empty cells remaining.""" return self.__num_empty_cells def get(self, x, y): """Returns the cell value at (x, y)""" return self._grid[x][y] def set(self, x, y, value): """Sets the call at x,y to value The set operation must obey the rules of the contraints. In this class - no value can be repeated in a row - no value can be repeated in a column If a constraint is violated then a ValueError exception is raised. Args: x, y: Cell position in row, column order. value: Integer value to write into the cell. Raises: ValueError: Cell value out of range [1:max_value] IndexError: x,y location out of range [0:max_value-1] """ if value < MIN_CELL_VALUE or value > self.max_value: raise ValueError(f"Value {value} out of range [{MIN_CELL_VALUE}:{self.max_value}]") if self._grid[x][y] == value: return # Clear value first to update constraints if self._grid[x][y]: self.clear(x, y) # Write value if allowed if value in self.get_allowed_values(x, y): self._grid[x][y] = value self.__num_empty_cells -= 1 else: raise ValueError(f"Value {value} not allowed at {x},{y}") # Update constraints self.__allowed_values_for_row[x].remove(value) self.__allowed_values_for_col[y].remove(value) def clear(self, x, y): """Clears the value for a cell at x,y and update constraints""" # Is OK to "clear" an already empty cell (no-op) if self._grid[x][y] == EMPTY_CELL: return # Stash previous value before clearing, to update constraints prev = self._grid[x][y] self._grid[x][y] = EMPTY_CELL self.__num_empty_cells += 1 # Put previous value back into allowed list self.__allowed_values_for_row[x].add(prev) self.__allowed_values_for_col[y].add(prev) def clear_all(self): """Clears the entire puzzle grid""" for x in range(self.max_value): for y in range(self.max_value): self.clear(x, y) def is_empty(self, x, y): """Returns True if the cell is empty""" return self._grid[x][y] == EMPTY_CELL def find_empty_cell(self): """Returns the next empty cell as tuple (x, y) Search starts at 0,0 and continues along the row. Returns at the first empty cell found. Returns empty tuple if no empty cells left. """ for x, row in enumerate(self._grid): for y, v in enumerate(row): if not v: return (x, y) return () def next_empty_cell(self): """Generator that returns the next empty cell that exists in the grid Search starts at 0,0, just like `find_empty_cell`. However each subsequent call will resume where the previous invocation left off (assuming this is being called as a generator function). Returns an empty tuple at the end of the list. """ for x, row in enumerate(self._grid): for y, v in enumerate(row): if not v: yield (x, y) return () def next_best_empty_cell(self): """Generator method that returns the next "best" empty cell Next best cell is the one with the fewest possible values. Returns an empty tuple when it reaches the end of the list. """ max_possibilities = 1 while max_possibilities <= self.max_value: for x, row in enumerate(self._grid): for y, v in enumerate(row): if not v and len(self.get_allowed_values(x, y)) <= max_possibilities: yield (x, y) max_possibilities += 1 return () def get_row_values(self, x): """Return the list of set values from row x as a list""" return [i for i in self._grid[x] if i != EMPTY_CELL] def get_column_values(self, y): """Return the list of set values from column y as a list""" return [i[y] for i in self._grid if i[y] != EMPTY_CELL] def get_allowed_values(self, x, y): """Returns the current set of allowed values at x,y as a set This is based on the intersection of the sets of allowed values for the same row and column. If there is already a value in a cell, then it is the only allowed value. """ if self._grid[x][y]: return {self._grid[x][y]} return self.__allowed_values_for_row[x] & self.__allowed_values_for_col[y] def is_valid(self): """Returns True if the puzzle is in a valid state, False if rules broken. This fuction should *always* return True, because it should not be possible to get into an invalid state. However since caller clould always access self._grid directly, and since we could introduce a bug, this function can perform an additional check. Empty cells are allowed -- this is not checking that the puzzle is solved. """ for x in range(self.max_value): values = self.get_row_values(x) if len(values) != len(set(values)): return False for y in range(self.max_value): values = self.get_column_values(y) if len(values) != len(set(values)): return False return True def is_solved(self): """Returns True if there are no empty cells left, and the puzzle is valid""" if self.is_valid(): for i in range(self.max_value): for j in range(self.max_value): if self.is_empty(i, j): return False return True return False def __str__(self): """Return a string representation of the puzzle as a 2D grid""" blurb = [["-" if v is None else v for v in row] for row in self._grid] return "\n".join(" ".join(map(str, sl)) for sl in blurb) def __repr__(self): """Return an unambiguous string representation of the puzzle""" puz = "".join([int2char(i) for sublist in self._grid for i in sublist]) ret = f"{self.__class__.__name__}({self.max_value}, '{puz}')" return ret
n1 = cont = soma = 0 n1 = int(input('Digite um número [999 para parar]: ')) while n1 != 999: cont += 1 soma += n1 n1 = int(input('Digite um número [999 para parar]: ')) print('Foram digitados {} números e a soma entre eles é {}'.format(cont, soma))
maxsimal = 0 while True: a = int(input("Masukan bilangan = ")) if maxsimal < a: maxsimal = a if a == 0: break print("Bilangan Terbesarnya Adalah = ", maxsimal)
class Holding(object): def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares): self.name = name self.symbol = symbol self.sector = sector self.market_val_percent = market_val_percent self.market_value = market_value self.number_of_shares = number_of_shares def __eq__(self, other): return ( self.__class__ == other.__class__ and self.name == other.name and self.symbol == other.symbol and self.sector == other.sector and self.market_val_percent == other.market_val_percent and self.market_value == other.market_value and self.number_of_shares == other.number_of_shares )
# rps data for the rock-paper-scissors portion of the red-green game # to be imported by rg.cgi # this file represents the "host throw" for each numbered round rps_data = { 0: "rock", 1: "rock", 2: "scissors", 3: "paper", 4: "paper", 5: "scissors", 6: "rock", 7: "scissors", 8: "paper", 9: "paper", 10: "scissors", 11: "rock", 12: "paper", 13: "paper", 14: "rock", 15: "scissors", 16: "scissors", 17: "scissors", 18: "rock", 19: "scissors", 20: "paper", 21: "rock", 22: "paper", 23: "scissors", 24: "rock", 25: "scissors", 26: "rock", 27: "rock", 28: "paper", 29: "paper", 30: "rock", 31: "paper", 32: "paper", 33: "scissors", 34: "rock", 35: "rock", 36: "scissors", 37: "rock", 38: "rock", 39: "paper", 40: "rock", 41: "rock", 42: "paper", 43: "paper", 44: "paper", 45: "paper", 46: "scissors", 47: "rock", 48: "scissors", 49: "scissors", }
user_info = {} while True: print("\n\t\t\tUnits:metric") name = str(input("Enter your name: ")) height = float(input("Input your height in meters(For instance:1.89): ")) weight = float(input("Input your weight in kilogram(For instance:69): ")) age = int(input("Input your age: ")) sex = str(input("Input your sex: ")) bmi = (weight/(height*height)) print("Your body mass index (or BMI) is: ", round(bmi, 2)) if sex == 'male': if bmi < 15: print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 15 < bmi < 16: print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 16 < bmi < 18.5: print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 18.5 < bmi < 25: print("\n\t\t\tYour BMI is", round(bmi, 2), "Normal(healthy weight):\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 25 < bmi < 30: print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 30 < bmi < 35: print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 35 < bmi < 40: print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif bmi > 40: print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") else: print("There is an error with your input") else: if bmi < 18.5: print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 18.5 < bmi < 24.9: print("\n\t\t\tYour BMI is", round(bmi, 2), "Healthy weight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 25 < bmi < 29.9: print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif bmi > 30: print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") else: print("There is an error with your input") print('\n\n10' + '=' * (int(round(bmi, 0))-10-1)+'|'+'=\ '*(60-int(round(bmi, 0))-1)+'60') if not name: break user_info[name] = height, weight, age, sex print(user_info) print(user_info.get(str(input("Enter your name: "))))
#!/usr/bin/env python #-*- coding: utf-8 -*- def getHeaders(fileName): headers = [] headerList = ['User-Agent','Cookie'] with open(fileName, 'r') as fp: for line in fp.readlines(): name, value = line.split(':', 1) if name in headerList: headers.append((name.strip(), value.strip())) return headers if __name__=="__main__": headers = getHeaders('headersRaw.txt') print(headers)
class ComponentsAssembly: def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args): self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args] def __iter__(self): self.index = 0 return self def __next__(self): if self.index < len(self._components): component = self._components[self.index] self.index += 1 return component raise StopIteration def __getitem__(self, item): return self._components[item] def __setitem__(self, key, value): self._components[key] = value def append(self, item): self._components.append(item)
''' 单例模式 ''' class Singleton(object): def __new__(cls): print(dir(cls)) if not hasattr(cls, 'instance'): # 判断有没有 instance 属性 cls.instance = super(Singleton, cls).__new__(cls) return cls.instance if __name__ == "__main__": s1 = Singleton() print("Object created", s1) s2 = Singleton() print('Object created', s2) ''' Object created <__main__.Singleton object at 0x000002512F7E1AC8> Object created <__main__.Singleton object at 0x000002512F7E1AC8> ''' ''' 通过dir 更方便看到两者的区别 '''
# Lecture 3.6, slide 2 # Defines the value to take the square root of, epsilon, and the number of guesses. x = 9 epsilon = 0.01 numGuesses = 0 # Here, 0 < x < 1, then the low is x and the high is 1 - the sqrt(x) > x if 0 < x < 1. # If x > 1, then the low is 0 and the high is x - the sqrt(x) < x if x > 1. if (x >= 0 and x < 1): low = x high = 1.0 elif (x >= 1): low = 0.0 high = x # Sets the initial answer to the average of low and high. ans = (low + high) / 2.0 # While the answer is still not close enough to epsilon, continue searching. while (abs(ans ** 2 - x) >= epsilon): # For each case, it prints the low and high values. print ('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans)) numGuesses += 1 # If the guess is lower than x, then set the new ans = low. # If the guess is higher than x, then set the new ans = high. if (ans ** 2) < x: low = ans elif (ans ** 2) >= x: high = ans # At the end, the answer is updated. ans = (low + high) / 2.0 # Prints the number of guesses and the final guess. print ('Number of guesses taken: ' + str(numGuesses)) print (str(ans) + ' is close to the squre root of ' + str(x))
# 创建用户名列表 current_users = ['Admin','yang yahu','gao xiangzhou','eric','yang yuhang'] # 创建另一个用户名列表 new_users = ['admin','Yang yahu','li jianfeng','yuan lishan','wang hao'] # 遍历列表 for new_user in new_users: if new_user.lower() and new_user.upper() and new_user.title() in [current_user.lower() and current_user.upper() and current_user.title() for current_user in current_users]: # 列表解析 print(new_user + " has been used," + "you need to input another user name!") else: print(new_user + " has not been used," + "you kan use it!")
# ctx.addClock("csi_rx_i.dphy_clk", 96) # ctx.addClock("video_clk", 24) # ctx.addClock("uart_i.sys_clk_i", 12) ctx.addClock("EXTERNAL_CLK", 12) # ctx.addClock("clk", 25)
class Solution: def soupServings(self, N: int) -> float: def dfs(a: int, b: int) -> float: if a <= 0 and b <= 0: return 0.5 if a <= 0: return 1.0 if b <= 0: return 0.0 if memo[a][b] > 0: return memo[a][b] memo[a][b] = 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + dfs(a - 2, b - 2) + dfs(a - 1, b - 3)) return memo[a][b] memo = [[0.0] * 192 for _ in range(192)] return 1 if N >= 4800 else dfs((N + 24) // 25, (N + 24) // 25)
# First we define a variable "to_find" which contains the alphabet to be checked for in the file # fo is the file which is to be read. to_find="e" fo = open('E:/file1.txt' ,'r+') count=0 for line in fo: for word in line.split(): if word.find(to_find)!=-1: count=count+1 print(count)
DELIVERY_TYPES = ( (1, "Vaginal Birth"), # Execise care when changing... (2, "Caesarian") )
class Solution: def makeGood(self, s: str) -> str: i = 0 string = list(s) while i < len(string) - 1: a = string[i] b = string[i + 1] if a.lower() == b.lower() and a != b: string.pop(i) string.pop(i) i = 0 else: i += 1 return "".join(string) if __name__ == "__main__": # fmt: off test_cases = [ "leEeetcode", "abBAcC", ] results = [ "leetcode", "", ] # fmt: on app = Solution() for test_case, correct_result in zip(test_cases, results): my_result = app.makeGood(test_case) assert ( my_result == correct_result ), f"My result: {my_result}, correct result: {correct_result}\nTest Case: {test_case}"
l,j,k=[list(input()) for i in range(3)] l.extend(j) for i in l: if i not in k : k.append(i) break k.remove(i) print('YES' if k==[] else 'NO')
# # PySNMP MIB module CXQLLC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXQLLC-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:33:22 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") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") cxQLLC, ThruputClass, Alias, SapIndex = mibBuilder.importSymbols("CXProduct-SMI", "cxQLLC", "ThruputClass", "Alias", "SapIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, NotificationType, Gauge32, Unsigned32, MibIdentifier, IpAddress, Counter64, Counter32, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Gauge32", "Unsigned32", "MibIdentifier", "IpAddress", "Counter64", "Counter32", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ModuleIdentity", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class X25Address(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(0, 15) class PacketSize(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9, 10, 11, 12)) namedValues = NamedValues(("bytes16", 4), ("bytes32", 5), ("bytes64", 6), ("bytes128", 7), ("bytes256", 8), ("bytes512", 9), ("bytes1024", 10), ("bytes2048", 11), ("bytes4096", 12)) qllcSapTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1), ) if mibBuilder.loadTexts: qllcSapTable.setReference('Memotec Communications Inc.') if mibBuilder.loadTexts: qllcSapTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapTable.setDescription('A table containing configuration information for each QLLC service access point.') qllcSapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcSapNumber")) if mibBuilder.loadTexts: qllcSapEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapEntry.setDescription('Defines a row in the qllcSapTable. Each row contains the objects which are used to define a service access point.') qllcSapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 1), SapIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcSapNumber.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapNumber.setDescription('Identifies a SAP (service access point) in the qllcSapTable.') qllcSapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllcSapType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("lower", 1), ("upper", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapType.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapType.setDescription("Specifies this SAP (service access point) as either 'upper' or 'lower'. Options: lower (1): This is a lower SAP which communicates with the X.25 layer. upper (2): This is an upper SAP, which acts as an inter-layer port communicating with the SNA Link Conversion layer. Configuration Changed: administrative") qllcSapAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 4), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapAlias.setDescription('Identifies this service access point by a textual name. Names must be unique across all service access points at all layers. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllcSapCompanionAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 5), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapCompanionAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapCompanionAlias.setDescription('Identifies the X.25 SAP that this SAP communicates with. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllcSapSnalcRef = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapSnalcRef.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapSnalcRef.setDescription('This object applies only to lower SAPs (service access points). Determines the upper SAP (service access point) that is associated with this SAP. Range of Values: 0 - 8 Default Value: none Configuration Changed: administrative') qllcSapOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcSapOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapOperationalMode.setDescription('Identifies the operational state of this SAP (service access point). Options: offLine (1): Indicates that this SAP is not operational. onLine (2): Indicates that this SAP is operational.') qllcDteTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2), ) if mibBuilder.loadTexts: qllcDteTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTable.setDescription('The DTE table contains the parameter settings that are used to create an X.25 Call Request packet for calls established by a particular lower service access point for a particular control unit.') qllcDteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcDteSap"), (0, "CXQLLC-MIB", "qllcDteIndex")) if mibBuilder.loadTexts: qllcDteEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteEntry.setDescription('Defines a row in the qllcDteTable. Each row contains the objects which are used to define a the parameters for an X.25 Call Request packet.') qllcDteSap = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 1), SapIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSap.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSap.setDescription('Identifies the SAP (service access point) associated with this entry. Configuration Changed: administrative ') qllcDteIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteIndex.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteIndex.setDescription('Identifies the control unit address associated with this DTE entry. Configuration Changed: administrative ') qllcDteRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllcDteType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("terminalInterfaceUnit", 1), ("hostInterfaceUnit", 2))).clone('terminalInterfaceUnit')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteType.setDescription('Determines the type of interface (HIU or TIU) associated with this DTE. Options: terminalInterfaceUnit (1): The SAP type is a TIU, which means it is connected to one or more control units (secondary link stations). The TIU emulates a primary link station, and polls the attached control units. The SDLC interface can support a total of 64 control units across all TIU SAPs. hostInterfaceUnit (2): The SAP type is an HIU, which means it is connected to an SNA host (primary link station). The HIU emulates the control units connected to a TIU. It responds to polls issued by the host. Default Value: terminalInterfaceUnit (1) Configuration Changed: administrative') qllcDteCalledAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 5), X25Address()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteCalledAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalledAddress.setDescription('Determines the DTE to call to establish a QLLC connection. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllcDteCallingAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 6), X25Address()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteCallingAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCallingAddress.setDescription('Determines the DTE address of the caller. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllcDteDBitCall = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('yes')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteDBitCall.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteDBitCall.setDescription('Determines if segmentation is supported and is to be performed by the QLLC layer for the specific DTE entry. Options: no (1): QLLC does not support segmentation. yes (2): QLLC supports segmentation. (For future use.) Default Value: yes (2) Configuration Changed: administrative and operative') qllcDteWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 7)).clone(7)).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteWindow.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteWindow.setDescription('Determines the transmit and receive window sizes for this DTE. This window size is used when establishing calls from this DTE, or when receiving calls at this DTE. QLLC only supports modulo 8 window size. Range of Values: 1 - 7 Default Value: 7 Configuration Changed: administrative and operative') qllcDtePacketSize = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 9), PacketSize().clone('bytes128')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDtePacketSize.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePacketSize.setDescription('Determines the transmit and receive packet size for this DTE when flow control negotiation (x25SapSbscrFlowCntrlParamNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bytes16 (4): 16 bytes bytes32 (5): 32 bytes bytes64 (6): 64 bytes bytes128 (7): 128 bytes bytes256 (8): 256 bytes bytes512 (9): 512 bytes bytes1024 (10): 1024 bytes bytes2048 (11): 2048 bytes bytes4096 (12): 4096 bytes Default Value: bytes128 (7) Related Objects: x25SapSbscrFlowCntrlParamNegotiation Configuration Changed: administrative and operative') qllcDteThroughput = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 10), ThruputClass().clone('bps9600')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteThroughput.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteThroughput.setDescription('Determines the transmit and receive throughput class for this DTE when flow control negotiation (x25SapSbscrThruputClassNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bps75 (3) bps150 (4) bps300 (5) bps600 (6) bps1200 (7) bps2400 (8) bps4800 (9) bps9600 (10) bps19200 (11) bps38400 (12) bps64000 (13) Default Value: bps9600 (10) Related Objects: x25SapSbscrThruputClassNegotiation Configuration Changed: administrative and operative') qllcDteUserData = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteUserData.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteUserData.setDescription('Determines the data included in the call user data field of each outgoing call initiated by this DTE. Call user data can only be included when calling non-Memotec devices. In this case, up to 12 characters can be specified. The format of the call user data field is determined by the value of the qllcDteMemotec object. Related Object: qllcDteMemotec Range of Values: 0 - 12 characters Default Value: none Configuration Changed: administrative and operative') qllcDteFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 12), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteFacility.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteFacility.setDescription('Determines the facility codes and associated parameters for this DTE. Default Value: 0 Range of Values: 0 - 20 hexadecimal characters Configuration Changed: administrative and operative') qllcDteMemotec = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("nonmemotec", 1), ("cx900", 2), ("legacy", 3), ("pvc", 4))).clone('cx900')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteMemotec.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteMemotec.setDescription('Determines the type of product that the called DTE address is associated with, which in turn determines how the call user data (CUD) field is constructed for all outgoing calls from this DTE. This object also determines whether the call is associated to a Switched Virtual Circuit (SVC) or a Permanent Virtual Circuit (PVC). Options: (1): Called DTE address is a non- Memotec product. CUD field = QLLC protocol ID + value of object qllcDteUserData (2): Called DTE is a Memotec CX900 product. CUD field = QLLC protocol ID + value of object qllcDteIndex (3): Called DTE is an older Memotec product (including CX1000). CUD field = QLLC protocol ID + / + Port Group GE + CU Alias + FF + Port + FF + FF (4): The DTE is connected through a Permanent Virtual Circuit (PVC), and can be either TIU or HIU. Note that if the DTE is configured for an SVC but a PVC call is received, the QLLC layer will attempt to connect to the PVC. Default Value: cx900 (2) Related Objects: qllcDteUserData qllcDteCalledAddress qllcDteConnectMethod Configuration Changed: administrative and operative') qllcDtePvc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('no')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDtePvc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePvc.setDescription('Determines if this DTE makes its calls on a PVC (permanent virtual circuit). Options: no (1): This DTE does not make its calls on a PVC (all calls are switched). yes (2): This DTE makes its calls on a PVC. (For future use.) Default Value: no (1) Configuration Changed: administrative ') qllcDteConnectMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("userdata", 1), ("callingaddress", 2))).clone('userdata')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteConnectMethod.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectMethod.setDescription("Determines if this DTE accepts calls by validating the user-data field, or by matching the calling address with its corresponding called address. Note: This object only applies to the HIU. Options: userdata (1): The HIU DTE validates the call using the user-data field. callingaddress (2): The HIU DTE validates the call by matching the call's calling address with the configured called address. Default Value: userdata (1) Configuration Changed: administrative ") qllcDteControl = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("clearStats", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: qllcDteControl.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteControl.setDescription('Clears all statistics for this service access point. Options: clearStats (1): Clear statistics. Default Value: none Configuration Changed: administrative and operative') qllcDteStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("connected", 1), ("pendingConnect", 2), ("disconnected", 3), ("pendingDisconnect", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteStatus.setDescription('Indicates the connection status of this DTE. Options: connected (1): This DTE is connected. pendingConnect (2): This DTE has issued a call and is waiting for it to complete. disconnected (3): This DTE is not connected. pendingDisconnect (4): This DTE has issued a call clear and is waiting for it to complete. Configuration Changed: administrative and operative') qllcDteOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteOperationalMode.setDescription('Indicates the operational state of this DTE. Options: offLine (1): Indicates that this DTE is not operational. onLine (2): Indicates that this DTE is operational.') qllcDteState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("opened", 1), ("closed", 2), ("xidcmd", 3), ("tstcmd", 4), ("xidrsp", 5), ("tstrsp", 6), ("reset", 7), ("setmode", 8), ("disc", 9), ("reqdisc", 10), ("unknown", 11)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteState.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteState.setDescription('Indicates the state of this DTE with regards to SNA traffic. Options: opened (1): Indicates that this DTE is in data transfer mode (a QSM was sent and a QUA was received). closed (2): Indicates that this DTE is not in data transfer mode (QSM not sent or QUA not received). xidcmd (3): Indicates that an XID was sent by the TIU and received by the HIU. tstcmd (4): Indicates that a TEST was sent by the TIU and received by the HIU. xiddrsp (5): Indicates that the HIU received an XID response from the TIU, or that the TIU received an XID response from the control unit. tsttrsp (6): Indicates that the HIU received a TEST response from the TIU, or that the TIU received a TEST response from the control unit. reset (7): Indicates that an X.25 reset was received. setmode (8): Indicates that a QSM was received. disc (9): Indicates that the HIU received a DISC from the host, or that the TIU sent a DISC to the control unit. reqdisc (10): Indicates that the HIU sent a DISC to the host, or that the TIU received a DISC from the control unit. unknown (11): Indicates that an unknown condition has occurred. ') qllcDteConnectionType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("svc", 2), ("pvc", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteConnectionType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectionType.setDescription('Identifies the type of X.25 connection that the DTE is supporting. Options: none (1): No X.25 connection exists yet. svc (2): The QLLC DTE is transmitting SNA data over a Switched Virtual Circuit (SVC). pvc (3): The QLLC DTE is transmitting SNA data over a Permanent Virtual Circuit (PVC).') qllcDteCalls = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 40), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteCalls.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalls.setDescription('Indicates the number of incoming calls received by this DTE.') qllcDteClears = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 41), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteClears.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteClears.setDescription('Indicates the number of calls cleared by this DTE.') qllcDteTxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 42), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteTxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTxPackets.setDescription('Indicates the number of data packets sent by this DTE.') qllcDteRxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 43), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteRxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRxPackets.setDescription('Indicates the number of data packets received by this DTE.') qllcDteQdc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 44), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQdc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQdc.setDescription('Indicates the number of SNA disconnects sent and received by this DTE.') qllcDteQxid = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 45), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQxid.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQxid.setDescription('Indicates the number of SNA XIDs sent and received by this DTE.') qllcDteQua = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 46), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQua.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQua.setDescription('Indicates the number of unnumbered acknowledgments sent and received by this DTE.') qllcDteQsm = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 47), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQsm.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQsm.setDescription('Indicates the number of SNRMs sent and received by this DTE.') qllcDteX25Reset = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 48), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Reset.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Reset.setDescription('Indicates the number of X.25 resets sent and received by this DTE.') qllcDteSnalcRnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 49), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSnalcRnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRnr.setDescription('Indicates the number of SNA link conversion layer flow control RNRs sent and received by this DTE.') qllcDteSnalcRr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 50), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSnalcRr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRr.setDescription('Indicates the number of SNA link conversion layer flow control RRs sent and received by this DTE.') qllcDteX25Rnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 51), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Rnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rnr.setDescription('Indicates the number of X.25 flow control RNRs sent and received by this DTE.') qllcDteX25Rr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 52), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Rr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rr.setDescription('Indicates the number of X.25 flow control RRs sent and received by this DTE.') qllcMibLevel = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcMibLevel.setStatus('mandatory') if mibBuilder.loadTexts: qllcMibLevel.setDescription('Used to determine current MIB module release supported by the agent. Object is in decimal.') mibBuilder.exportSymbols("CXQLLC-MIB", qllcSapAlias=qllcSapAlias, qllcDteCalls=qllcDteCalls, qllcDteClears=qllcDteClears, qllcSapTable=qllcSapTable, qllcDtePacketSize=qllcDtePacketSize, qllcDteStatus=qllcDteStatus, qllcSapCompanionAlias=qllcSapCompanionAlias, qllcDteRowStatus=qllcDteRowStatus, qllcDteQdc=qllcDteQdc, qllcDtePvc=qllcDtePvc, qllcDteQua=qllcDteQua, qllcSapOperationalMode=qllcSapOperationalMode, qllcDteOperationalMode=qllcDteOperationalMode, qllcDteDBitCall=qllcDteDBitCall, qllcSapRowStatus=qllcSapRowStatus, qllcDteEntry=qllcDteEntry, qllcDteCalledAddress=qllcDteCalledAddress, qllcDteConnectionType=qllcDteConnectionType, qllcDteType=qllcDteType, qllcDteSnalcRr=qllcDteSnalcRr, qllcDteX25Rnr=qllcDteX25Rnr, qllcMibLevel=qllcMibLevel, qllcDteQsm=qllcDteQsm, qllcDteTxPackets=qllcDteTxPackets, qllcDteMemotec=qllcDteMemotec, qllcDteQxid=qllcDteQxid, qllcDteTable=qllcDteTable, qllcDteSap=qllcDteSap, qllcDteThroughput=qllcDteThroughput, qllcDteConnectMethod=qllcDteConnectMethod, qllcDteX25Reset=qllcDteX25Reset, qllcSapNumber=qllcSapNumber, qllcDteSnalcRnr=qllcDteSnalcRnr, qllcSapEntry=qllcSapEntry, qllcDteControl=qllcDteControl, qllcDteFacility=qllcDteFacility, qllcDteState=qllcDteState, PacketSize=PacketSize, qllcSapType=qllcSapType, qllcSapSnalcRef=qllcSapSnalcRef, qllcDteCallingAddress=qllcDteCallingAddress, qllcDteIndex=qllcDteIndex, qllcDteUserData=qllcDteUserData, X25Address=X25Address, qllcDteX25Rr=qllcDteX25Rr, qllcDteRxPackets=qllcDteRxPackets, qllcDteWindow=qllcDteWindow)
class Solution: """ https://leetcode.com/problems/move-zeroes/ Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: 1. You must do this in-place without making a copy of the array. 2. Minimize the total number of operations. """ @staticmethod def moveZeroes(nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place. """ # nums.sort(key=lambda a: a == 0) zero_pos = 0 for i in range(len(nums)): if nums[i] != 0: if zero_pos != i: nums[i], nums[zero_pos] = nums[zero_pos], nums[i] zero_pos += 1
RGB2HEX = 1 RGB2HSV = 2 RGB2HSL = 3 HEX2RGB = 4 HSV2RGB = 5 OPCV_RGB2HSV = 100 OPCV_HSV2RGB = 101
class ImageGroupsComponent: def __init__(self, key=None, imageGroup=None): self.key = 'imagegroups' self.current = None self.animationList = {} self.alpha = 255 self.hue = None self.playing = True if key is not None and imageGroup is not None: self.add(key, imageGroup) def getCurrentImageGroup(self): if self.animationList == {} or self.current is None: return None return self.animationList[self.current] def add(self, state, animation): self.animationList[state] = animation if self.current == None: self.current = state def pause(self): self.playing = False def play(self): self.playing = True def stop(self): self.playing = False self.animationList[self.current].reset()
class Tag(object): def __init__(self, tag_name : str, type_ = None): self.__tag_name = tag_name self.__type : str = type_ if type_ is not None else "" @property def type(self) -> str: return self.__type @property def name(self) -> str: return self.__tag_name def __str__(self) -> str: return self.type + ":" + self.__tag_name def __eq__(self, o: object): return str(o).lower() == str(self).lower() def __hash__(self) -> int: return hash(str(self)) def __repr__(self) -> str: return "<%s>" % str(self)
# super(): COME DELEGARE ALLA CLASSE BASE # Perchè viene utilizzato il metodo super()? # prendiamo l'esempio che segue: class Animale(): def __init__(self,specie): self.specie = specie def razza(self): return f"Io sono della specie {self.specie}" class Cane(Animale): def __init__(self, specie, pelo): self.specie = specie # è una duplicazione della linea 3, non è la soluzione migliore self.pelo = pelo def razza(self): return"bau bau" # L'idea è quella di utilizzare le classi figlie per estendere le funzionalità della clase base e delegare alla classe base tutti # quegli aspetti tipici di una data famiglia di classi (Animali in questo esempio), # altrimenti vanifichiamo l'intero concetto di ereditarietà class Animale(): def __init__(self,specie): self.specie = specie def razza(self): return f"Io sono della specie {self.specie}" class Cane(Animale): def __init__(self, specie, pelo): super().__init__(specie) # super() equivale ad una chiamata alla classe superiore (Animale) self.pelo = pelo super().razza() def razza(self): return"bau bau" c = Cane("cane", pelo = "corto") # sto chidedno a python di invocare il metodo init, #li trova super() che è un modo per chiedere a python # di invocare il metodo init definito nella superclass (Animale) # Ecco a cosa serve il metodo super() serve per non vanificare il concetto di ereditarietà # e di incappare nel meccanismo dell'overide.
''' - DESAFIO 007 - Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. ''' n1 = float(input('Informe a primeira nota: ')) n2 = float(input('Informe a segunda nota: ')) media = (n1 + n2)/2 print('A média é igual a {}'.format(media))
#First go print("Hello, World!") message = "Hello, World!" print(message) #-------> print "Hello World!" is Python 2 syntax, use print("Hello World!") for Python 3
def register(username, password, check_password): if password == check_password: if 8 < len(username) < 40 and 8 < len(password) < 16: print("Успешно") with open("database.txt", "w") as db1: db1.write(username + '\n' + password) code = 1234 return code else: print("Неправильная длина") else: print("Пароли не совпадают") answer = register("testname123", "password123", "password123") def check_code(guess, answer): if answer == guess: print("Все успешно, Добро пожаловать!") else: print("Неверный код") check_code(1234, answer)
# coding=utf-8 class Folding(object): NO = 0 DEVICE = 1 SUBSYSTEM = 2 SERVER = 3 def __init__(self, args): self.args = args def fold(self, data, level): """ Схлапывает значения в дикте до среднего арифметического """ if not data: return 1 if self.args.folding < level: return data result = sum(data.values()) / len(data.keys()) return result if level < Folding.SERVER else {'server': result}
""" This is a module defined in sub-package It defines following importable objects - two module top level functions - one class """ def top_level_function1() -> None: """ This is first top level function """ def top_level_function2() -> None: """ This is second top level function """ class Class: """ A sample class """ def __init__(self) -> None: ''' Initializer that does nothing ''' return
# https://leetcode.com/problems/minimum-depth-of-binary-tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): if not root: return 0 ans = set() def helper(node, depth): if (not node.left) and (not node.right): ans.add(depth) return if node.right: helper(node.right, depth + 1) if node.left: helper(node.left, depth + 1) helper(root, 1) return min(ans)
EXCHANGE_CFFEX = 0 EXCHANGE_SHFE = 1 EXCHANGE_DCE = 2 EXCHANGE_SSEOPT = 3 EXCHANGE_CZCE = 4 EXCHANGE_SZSE = 5 EXCHANGE_SSE = 6 EXCHANGE_UNKNOWN = 7
numerator = int(input("Enter a numerator: ")) denominator = int(input("Enter denominator: ")) while denominator == 0: print("Denominator cannot be 0") denominator = int(input("Enter denominator: ")) if int(numerator / denominator) * denominator == numerator: print("Divides evenly!") else: print("Doesn't divide evenly.")
class Solution: #Function to find sum of weights of edges of the Minimum Spanning Tree. def spanningTree(self, V, adj): #code here ##findpar with rank compression def findpar(x): if parent[x]==x: return x else: parent[x]=findpar(parent[x]) return parent[x] ##Union by rank def union(x,y): lp_x=findpar(x) lp_y=findpar(y) if rank[lp_x]>rank[lp_y]: parent[lp_y]=lp_x elif rank[lp_x]<rank[lp_y]: parent[lp_x]=lp_y else: parent[lp_y]=lp_x rank[lp_x] += 1 # print(adj) s=0 parent=[] E={} rank=[0 for i in range(V)] for i in range(V): parent.append(i) for i in range(len(adj)): edges=adj[i] # print(edges) for edge in edges: u=i v=edge[0] w=edge[1] if (u,v) not in E and (v,u) not in E: E[(u,v)]=w # print(E) Ef={} Ef=sorted(E.items(),key=lambda x:x[1]) # print(Ef) for i in Ef: # print(i) w=i[1] u=i[0][0] v=i[0][1] # print(u,v,w) lp_u=findpar(u) lp_v=findpar(v) if lp_u!=lp_v: union(u,v) s += w return s
class Pegawai: def __init__(self, nama, email, gaji): self.__namaPegawai = nama self.__emailPegawai = email self.__gajiPegawai = gaji # decoration ini digunakan untuk mengakses property # nama pegawai agar dapat diakses tanpa menggunakan # intance.namaPegawai() melainkan instance.namaPegawai @property def namaPegawai(self): return self.__namaPegawai # nama dari decoration harus sama dengan nama property # kemudian diakhiri dengan kata setter untuk menandakan bahwa ini adalah setter dari property @namaPegawai.setter def namaPegawai(self, nama): self.__namaPegawai = nama @property def emailPegawai(self): return self.__emailPegawai @emailPegawai.setter def emailPegawai(self, email): self.__emailPegawai = email @property def gajiPegawai(self): return self.__gajiPegawai @gajiPegawai.setter def gajiPegawai(self, gaji): self.__gajiPegawai = gaji def __str__(self): return "Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}".format(self.namaPegawai,self.emailPegawai,self.gajiPegawai)
snippet_normalize (cr, width, height) cr.set_line_width (0.12) cr.set_line_cap (cairo.LINE_CAP_BUTT) #/* default */ cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8) cr.stroke () cr.set_line_cap (cairo.LINE_CAP_ROUND) cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8) cr.stroke () cr.set_line_cap (cairo.LINE_CAP_SQUARE) cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8) cr.stroke () #/* draw helping lines */ cr.set_source_rgb (1,0.2,0.2) cr.set_line_width (0.01) cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8) cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8) cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8) cr.stroke ()
class DiscreteEnvWrapper: def __init__(self, env): self.__env = env def reset(self): return self.__env.reset() def step(self, action): next_state, reward, done, info = self.__env.step(action) return next_state, reward, done, info def render(self): self.__env.render() def close(self): self.__env.close() def get_random_action(self): return self.__env.action_space.sample() def get_total_actions(self): return self.__env.action_space.n def get_total_states(self): return self.__env.observation_space.n def seed(self, seed=None, set_action_seed=True): if set_action_seed: self.__env.action_space.seed(seed) return self.__env.seed(seed)
def mse(x, target): n = max(x.numel(), target.numel()) return (x - target).pow(2).sum() / n def snr(x, target): noise = (x - target).pow(2).sum() signal = target.pow(2).sum() SNR = 10 * (signal / noise).log10_() return SNR
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: size = len(preorder) root = TreeNode(preorder[0]) s = [] s.append(root) i = 1 while (i < size): temp = None while(len(s)>0 and preorder[i] > s[-1].val): temp = s.pop() if (temp != None): temp.right = TreeNode(preorder[i]) s.append(temp.right) else: temp = s[-1] temp.left = TreeNode(preorder[i]) s.append(temp.left) i = i+1 return root
def get_account(account_id: int): return { 'account_id': 1, 'email': 'noreply@gerenciagram.com', 'first_name': 'Gerenciagram' }
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class SoundModel(object): sound = None path = "" delay = 0 delay_min = 0 delay_max = 0 def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0): self.sound = sound self.path = path self.delay = delay self.delay_min = delay_min self.delay_max = delay_max
max_strlen=[] max_strindex=[] for i in range(1,11): file_name="sample."+str(i) with open(file_name,"rb") as f: offsets=[] len_of_file=[] for strand in f.readlines(): offsets.append(sum(len_of_file)) len_of_file.append(len(strand)) max_strlen.append(max(len_of_file)) max_strindex.append(len_of_file.index(max(len_of_file))) print("The lengths of strand in file {} are:\n{}".format(file_name,str(len_of_file)[1:-1])) print("The offsets for each strand to appear in file {} are:\n{}".format(file_name,str(offsets)[1:-1])) print("The file name of the largest strand that appears is: sample.{}".format(max_strlen.index(max(max_strlen))+1)) # file=open("sample.1","rb") # # print(type(file.readlines()[1][:-1].decode("gbk"))) # # print(len(file.readline()[:-1])) # # e=[] # # for i in file.readlines(): # # e.append(len(i)) # # print(sum(e)) # # print(file.read()) # print(len(file.read()))
tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR') precedence = ( ('left', 'IMPLY'), ('left', '|', '&'), ('right', '~'), ) t_ignore = ' \t' t_IMPLY = r'=>' t_RPAREN = r'\)' t_LPAREN = r'\(' literals = ['|', ',', '&', '~'] def t_PREDICATENAME(t): r'[A-Z][a-zA-Z0-9_]*' t.value = str(t.value) return t def t_PREDICATEVAR(t): r'[a-z]' t.value = str(t.value) return t def t_newline(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1)
#Faça um programa que seja capaz de receber do usario a DISTANCIA de uma viagem #e o TEMPO em que essa viagem aconteceu. O programa deve exibir, no final, a velocidade média # print("VELO IDEAL PARA SUA TRIP") distanc = float(input('Digite a distância')) time = float(input('Digite o tempo da viagem')) veloci_media = distanc / time print('Para a distancia {} e o tempo {} a velocidade média é {} km/h '.format(distanc,time,veloci_media))
for i in range(int(input())): n = int(input()) a = [0 for j in range(32)] for j in range(n): s = input() p = 0 if('a' in s): p|=1 if('e' in s): p|=2 if('i' in s): p|=4 if('o' in s): p|=8 if('u' in s): p|=16 a[p]+=1 c = 0 for j in range(32): for k in range(j+1,32): if(j|k==31): c+=a[j]*a[k] c+=int(a[31]*(a[31]-1)/2) print(c)
begin_unit comment|'# Copyright 2013 OpenStack Foundation' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' name|'import' name|'datetime' newline|'\n' nl|'\n' name|'from' name|'nova' name|'import' name|'db' newline|'\n' nl|'\n' nl|'\n' DECL|variable|FAKE_UUID name|'FAKE_UUID' op|'=' string|"'b48316c5-71e8-45e4-9884-6c78055b9b13'" newline|'\n' DECL|variable|FAKE_REQUEST_ID1 name|'FAKE_REQUEST_ID1' op|'=' string|"'req-3293a3f1-b44c-4609-b8d2-d81b105636b8'" newline|'\n' DECL|variable|FAKE_REQUEST_ID2 name|'FAKE_REQUEST_ID2' op|'=' string|"'req-25517360-b757-47d3-be45-0e8d2a01b36a'" newline|'\n' DECL|variable|FAKE_ACTION_ID1 name|'FAKE_ACTION_ID1' op|'=' number|'123' newline|'\n' DECL|variable|FAKE_ACTION_ID2 name|'FAKE_ACTION_ID2' op|'=' number|'456' newline|'\n' nl|'\n' DECL|variable|FAKE_ACTIONS name|'FAKE_ACTIONS' op|'=' op|'{' nl|'\n' name|'FAKE_UUID' op|':' op|'{' nl|'\n' name|'FAKE_REQUEST_ID1' op|':' op|'{' string|"'id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'action'" op|':' string|"'reboot'" op|',' nl|'\n' string|"'instance_uuid'" op|':' name|'FAKE_UUID' op|',' nl|'\n' string|"'request_id'" op|':' name|'FAKE_REQUEST_ID1' op|',' nl|'\n' string|"'project_id'" op|':' string|"'147'" op|',' nl|'\n' string|"'user_id'" op|':' string|"'789'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'None' op|',' nl|'\n' string|"'message'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' op|',' nl|'\n' name|'FAKE_REQUEST_ID2' op|':' op|'{' string|"'id'" op|':' name|'FAKE_ACTION_ID2' op|',' nl|'\n' string|"'action'" op|':' string|"'resize'" op|',' nl|'\n' string|"'instance_uuid'" op|':' name|'FAKE_UUID' op|',' nl|'\n' string|"'request_id'" op|':' name|'FAKE_REQUEST_ID2' op|',' nl|'\n' string|"'user_id'" op|':' string|"'789'" op|',' nl|'\n' string|"'project_id'" op|':' string|"'842'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'None' op|',' nl|'\n' string|"'message'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' nl|'\n' DECL|variable|FAKE_EVENTS name|'FAKE_EVENTS' op|'=' op|'{' nl|'\n' name|'FAKE_ACTION_ID1' op|':' op|'[' op|'{' string|"'id'" op|':' number|'1' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'event'" op|':' string|"'schedule'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'0' op|',' number|'2' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'2' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Success'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' op|',' nl|'\n' op|'{' string|"'id'" op|':' number|'2' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'event'" op|':' string|"'compute_create'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'3' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'4' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Success'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|']' op|',' nl|'\n' name|'FAKE_ACTION_ID2' op|':' op|'[' op|'{' string|"'id'" op|':' number|'3' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID2' op|',' nl|'\n' string|"'event'" op|':' string|"'schedule'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'3' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'3' op|',' number|'2' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Error'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|']' nl|'\n' op|'}' newline|'\n' nl|'\n' nl|'\n' DECL|function|fake_action_event_start name|'def' name|'fake_action_event_start' op|'(' op|'*' name|'args' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'FAKE_EVENTS' op|'[' name|'FAKE_ACTION_ID1' op|']' op|'[' number|'0' op|']' newline|'\n' nl|'\n' nl|'\n' DECL|function|fake_action_event_finish dedent|'' name|'def' name|'fake_action_event_finish' op|'(' op|'*' name|'args' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'FAKE_EVENTS' op|'[' name|'FAKE_ACTION_ID1' op|']' op|'[' number|'0' op|']' newline|'\n' nl|'\n' nl|'\n' DECL|function|stub_out_action_events dedent|'' name|'def' name|'stub_out_action_events' op|'(' name|'stubs' op|')' op|':' newline|'\n' indent|' ' name|'stubs' op|'.' name|'Set' op|'(' name|'db' op|',' string|"'action_event_start'" op|',' name|'fake_action_event_start' op|')' newline|'\n' name|'stubs' op|'.' name|'Set' op|'(' name|'db' op|',' string|"'action_event_finish'" op|',' name|'fake_action_event_finish' op|')' newline|'\n' dedent|'' endmarker|'' end_unit
## https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ ## Restrictions with multiple metaclasses # class Meta1(type): # pass # class Meta2(type): # pass # class Base1(metaclass=Meta1): # pass # class Base2(metaclass=Meta2): # pass # class Foobar(Base1, Base2): # pass # class Meta(type): # pass # class SubMeta(Meta): # pass class Base1(metaclass=Meta): pass class Base2(metaclass=SubMeta): pass class Foobar(Base1, Base2): pass type(Foobar)
# Copyright © 2020 by Spectrico # Licensed under the MIT License model_file = "model-weights-spectrico-car-colors-recognition-mobilenet_v3-224x224-180420.pb" # path to the car color classifier label_file = "labels.txt" # path to the text file, containing list with the supported makes and models input_layer = "input_1" output_layer = "Predictions/Softmax/Softmax" classifier_input_size = (224, 224) # input size of the classifier
# 14. Longest Common Prefix # Write a function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, return an empty string "". class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ prefix = "" if not strs: return prefix shortest = min(strs, key = len) for i in range(len(shortest)): if all([x.startswith(shortest[:i+1]) for x in strs]): prefix = shortest[:i+1] else: break return prefix
STRING_FILTER = 'string' CHOICE_FILTER = 'choice' BOOLEAN_FILTER = 'boolean' RADIO_FILTER = 'radio' HALF_WIDTH_FILTER = 'half_width' FULL_WIDTH_FILTER = 'full_width' VALID_FILTERS = ( STRING_FILTER, CHOICE_FILTER, BOOLEAN_FILTER, RADIO_FILTER, ) VALID_FILTER_WIDTHS = ( HALF_WIDTH_FILTER, FULL_WIDTH_FILTER, ) SORT_PARAM = 'sort' LAYOUT_PARAM = 'layout' # These constructors are using pascal case to masquerade as classes, but they're simply # generating dictionaries that declare the desired structure for the UI. This helps to # reduce verbosity when declaring options, while also providing an API that'll allow us # to add more features/validation/etc. def ListViewOptions(filters=None, sorts=None, layouts=None): assert isinstance(filters, (dict, type(None))) assert isinstance(sorts, (dict, type(None))) assert isinstance(layouts, (dict, type(None))) return { 'filters': filters, 'sorts': sorts, 'layouts': layouts, } def FilterOptions(children): assert isinstance(children, list) return { 'object_type': 'filter_options', 'children': children, } def FilterGroup(title, children): assert isinstance(title, str) assert isinstance(children, list) for obj in children: assert isinstance(obj, dict) return { 'object_type': 'filter_group', 'title': title, 'children': children, } def Filter( name, label, type, value, results_description, choices=None, multiple=None, clearable=None, width=None, is_default=None, ): if width is None: width = HALF_WIDTH_FILTER assert type in VALID_FILTERS assert width in VALID_FILTER_WIDTHS return { 'object_type': 'filter', 'name': name, 'label': label, 'type': type, 'value': value, 'results_description': results_description, 'choices': choices, 'multiple': multiple, 'clearable': clearable, 'width': width, 'is_default': is_default, } def SortOptions(children): assert isinstance(children, list) return { 'object_type': 'sort_options', 'children': children, } def Sort(label, value, is_selected, results_description, name=None, is_default=None): if name is None: name = SORT_PARAM return { 'object_type': 'sort', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'results_description': results_description, 'is_default': is_default, } def LayoutOptions(children): assert isinstance(children, list) return { 'object_type': 'layout_options', 'children': children, } def Layout(label, value, is_selected, icon_class, template=None, name=None): if name is None: name = LAYOUT_PARAM return { 'object_type': 'layout', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'icon_class': icon_class, 'template': template, }
class Passenger(): def __init__(self, weight, floor, destination, time): self.weight = weight self.floor = floor self.destination = destination self.elevator = None self.created_at = time def enter(self, elevator): ''' Input: the elevator that the passenger attempts to enter ''' if elevator.enter(self): self.elevator = elevator self.elevator.request(self.destination) return True return False def leave_if_arrived(self): if self.destination == self.floor: self.elevator.leave(self) return True return False def update_floor(self, floor): '''Allows the elevator to update the floor attribute of the passenger''' self.floor = floor
# ============================================================ # Title: Keep Talking and Nobody Explodes Solver: Who's on First? # Author: Ryan J. Slater # Date: 4/4/2019 # ============================================================ def solveSimonSays(textList, # List of strings [displayText, topLeft, topRight, middleLeft, middleRight, bottomLeft, bottomRight] bombSpecs): # Dictionary of bomb specs such as serial number last digit, parallel port, battery count, etc # Top Left if textList[0] in ['ur']: return getResponsesFromWord(textList[1]) # Top Right elif textList[0] in ['first', 'okay', 'c']: return getResponsesFromWord(textList[2]) # Middle Left elif textList[0] in ['yes', 'nothing', 'led', 'they are']: return getResponsesFromWord(textList[3]) # Middle Right elif textList[0] in ['blank', 'read', 'red', 'you', 'you\'re', 'their']: return getResponsesFromWord(textList[4]) # Bottom Left elif textList[0] in ['', 'reed', 'leed', 'they\'re']: return getResponsesFromWord(textList[5]) # Bottom Right elif textList[0] in ['display', 'says', 'no', 'lead', 'hold on', 'you are', 'there', 'see', 'cee']: return getResponsesFromWord(textList[6]) def getResponsesFromWord(word): # Word to be used as the key for step 2 # Returns a csv string in the order of words to try if word == 'ready': return 'YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY, NO, FIRST, UHHH, NOTHING, WAIT'.lower() elif word == 'first': return 'LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST'.lower() elif word == 'no': return 'BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE'.lower() elif word == 'blank': return 'WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST'.lower() elif word == 'nothing': return 'UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING, READY'.lower() elif word == 'yes': return 'OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES, LEFT, BLANK, NO, WAIT'.lower() elif word == 'what': return 'UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, OKAY, FIRST, WAIT, YES, PRESS, RIGHT'.lower() elif word == 'uhhh': return 'READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH, MIDDLE, WAIT, FIRST'.lower() elif word == 'left': return 'RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, WAIT, PRESS, READY, OKAY, NOTHING'.lower() elif word == 'right': return 'YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST'.lower() elif word == 'middle': return 'BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES'.lower() elif word == 'okay': return 'MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, READY, BLANK, PRESS, WHAT, RIGHT'.lower() elif word == 'wait': return 'UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT, NOTHING, READY, RIGHT, MIDDLE'.lower() elif word == 'press': return 'RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, BLANK, LEFT, FIRST, WHAT, NO, WAIT'.lower() elif word == 'you': return 'SURE, YOU ARE, YOUR, YOU\'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU, UH UH, LIKE, DONE, U'.lower() elif word == 'you are': return 'YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU\'RE, SURE, UR, YOU ARE'.lower() elif word == 'your': return 'UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU\'RE, YOU, WHAT?, HOLD, LIKE, DONE'.lower() elif word == 'you\'re': return 'YOU, YOU\'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, UH HUH, SURE, DONE, LIKE, HOLD'.lower() elif word == 'ur': return 'DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU\'RE, LIKE, NEXT, UH UH, YOU ARE, YOU'.lower() elif word == 'u': return 'UH HUH, SURE, NEXT, WHAT?, YOU\'RE, UR, UH UH, DONE, U, YOU, LIKE, HOLD, YOU ARE, YOUR'.lower() elif word == 'uh huh': return 'UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, SURE, LIKE, YOU\'RE, UR, U, WHAT?'.lower() elif word == 'uh uh': return 'UR, U, YOU ARE, YOU\'RE, NEXT, UH UH, DONE, YOU, UH HUH, LIKE, YOUR, SURE, HOLD, WHAT?'.lower() elif word == 'what?': return 'YOU, HOLD, YOU\'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?, SURE'.lower() elif word == 'done': return 'SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU\'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE'.lower() elif word == 'next': return 'WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, DONE, YOU ARE, UR, YOU\'RE, U, YOU'.lower() elif word == 'hold': return 'YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU\'RE, NEXT, HOLD, UH HUH, YOUR, LIKE'.lower() elif word == 'sure': return 'YOU ARE, DONE, LIKE, YOU\'RE, YOU, HOLD, UH HUH, UR, SURE, U, WHAT?, NEXT, YOUR, UH UH'.lower() elif word == 'like': return 'YOU\'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE, SURE, YOU ARE, YOUR'.lower()
#coding:utf-8 #pulic BASE_DIR = "/home/dengerqiang/Documents/WORK/" VQA_BASE = BASE_DIR + 'VQA/' DATA10 = VQA_BASE + "data1.0/" DATA20 = VQA_BASE + "data2.0/" IMAGE_DIR = VQA_BASE + "images/" GLOVE_DIR = BASE_DIR + 'glove/' NLTK_DIR = BASE_DIR + "nltk_data" #private WORK_DIR = BASE_DIR+ "VQA/DenseCoAttention/" GLOVE_FILE = "glove.6B.100d.pt" #global arguments RNN_DIM = 100 CNN_TYPE = "resnet152"
#!/usr/bin/python class RedditUser: def __init__( self, name: str, can_submit_guess: bool = True, is_potential_winner: bool = False, num_guesses: int = 0, ): """ Parametrized constructor """ self.name = name self.can_submit_guess = can_submit_guess self.is_potential_winner = is_potential_winner self.num_guesses = num_guesses
def toMinutesArray(times: str): res = [0, 0] startEnd = times.split() hourMin = startEnd[0].split(':') res[0] = int(hourMin[0]) * 60 + int(hourMin[1]) hourMin = startEnd[1].split(':') res[1] = int(hourMin[0]) * 60 + int(hourMin[1]) return res MAX_MINS = 1500 N = int(input()) table = [0] * MAX_MINS res = 0 for i in range(N): startEnd = toMinutesArray(input()) table[startEnd[0]] += 1 table[startEnd[1]] -= 1 for i in range(1, MAX_MINS): table[i] += table[i-1] res = max(res, table[i]) print(res)
# For the central discovery server LOG_FILE = 'discovered.pkl' DISCOVERY_PORT = 4444 MESSAGING_PORT = 8192 PROMPT_FILE = 'prompt' SHARED_FOLDER = 'shared' DOWNLOAD_FOLDER = 'download' CHUNK_SIZE = 1000000
class FindImage: def __init__(self, image_repo): self.image_repo = image_repo def by_ayah_id(self, ayah_id): return self.image_repo.find_by_ayah_id(ayah_id)
# Copyright 2020 Google LLC # # 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 # # https://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. """ Rules for generating ruby code with protoc including rules for ruby, grpc-ruby, and various flavors of gapic-generator-ruby """ load( ":private/ruby_gapic_library_internal.bzl", _ruby_gapic_library_internal = "ruby_gapic_library_internal", ) load("@rules_gapic//:gapic.bzl", "proto_custom_library") ## # A macro over the proto_custom_library that generates a library # using the gapic-generator entrypoint # # name: name of the rule # srcs: proto files wrapped in the proto_library rule # extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings # (e.g. gem-name=a-gem-name-v1) # yml_configs: a list of labels of the yaml configs (or an empty list) # grpc_service_config: a label to the grpc service config # def ruby_gapic_library( name, srcs, extra_protoc_parameters = [], yml_configs = [], grpc_service_config = None, **kwargs): _ruby_gapic_library_internal( name, srcs, Label("//rules_ruby_gapic/gapic-generator:gapic_generator_ruby"), extra_protoc_parameters, yml_configs, grpc_service_config ) ## # A macro over the proto_custom_library that generates a library # using the gapic-generator-cloud entrypoint # # name: name of the rule # srcs: proto files wrapped in the proto_library rule # ruby_cloud_title: cloud gem's title. # It is separated from the extra_protoc_parameters because of issues with build_gen: https://github.com/googleapis/gapic-generator-ruby/issues/539 # ruby_cloud_description: cloud gem's description. # It is separated from the extra_protoc_parameters because of issues with build_gen: https://github.com/googleapis/gapic-generator-ruby/issues/539 # extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings # (e.g. ruby-cloud-gem-name=google-cloud-gem-name-v1) # grpc_service_config: a label to the grpc service config # def ruby_cloud_gapic_library( name, srcs, ruby_cloud_title = "", ruby_cloud_description = "", extra_protoc_parameters = [], grpc_service_config = None, **kwargs): if extra_protoc_parameters: for key_val_string in extra_protoc_parameters: key_val_split = key_val_string.split("=", 1) if len(key_val_split) < 2: fail("Parameter '{key_val_string}' is not in the 'key=value' format".format(key_val_string=key_val_string)) key = key_val_split[0].strip() if key == "ruby-cloud-title": fail("Parameter 'ruby-cloud-title' should be specified in a separate Bazel rule attribute 'ruby_cloud_title'") if key == "ruby-cloud-description": fail("Parameter 'ruby-cloud-description' should be specified in a separate Bazel rule attribute 'ruby_cloud_description'") if ruby_cloud_title: extra_protoc_parameters.append("ruby-cloud-title={value}".format(value = ruby_cloud_title)) if ruby_cloud_description: extra_protoc_parameters.append("ruby-cloud-description={value}".format(value = ruby_cloud_description)) _ruby_gapic_library_internal( name, srcs, Label("//rules_ruby_gapic/gapic-generator-cloud:gapic_generator_cloud"), extra_protoc_parameters, [], grpc_service_config ) ## # A macro over the proto_custom_library that generates a library # using the gapic-generator-ads entrypoint # # name: name of the rule # srcs: proto files wrapped in the proto_library rule # extra_protoc_parameters: a list of the generator parameters in the form of "key=value" strings # (e.g. gem-name=google-ads-googleads) # grpc_service_config: a label to the grpc service config # def ruby_ads_gapic_library( name, srcs, extra_protoc_parameters = [], grpc_service_config = None, **kwargs): _ruby_gapic_library_internal( name, srcs, Label("//rules_ruby_gapic/gapic-generator-ads:gapic_generator_ads"), extra_protoc_parameters, [], grpc_service_config ) ## # A macro over the proto_custom_library that runs protoc with a ruby plugin # # name: name of the rule # deps: proto files wrapped in the proto_library rule # def ruby_proto_library(name, deps, **kwargs): # Build zip file of protoc output proto_custom_library( name = name, deps = deps, output_type = "ruby", output_suffix = ".srcjar", **kwargs ) ## # A macro over the proto_custom_library that runs protoc with a grpc-ruby plugin # # name: name of the rule # srcs: proto files wrapped in the proto_library rule # deps: a ruby_proto_library output # def ruby_grpc_library(name, srcs, deps, **kwargs): # Build zip file of grpc output proto_custom_library( name = name, deps = srcs, plugin = Label("@com_github_grpc_grpc//src/compiler:grpc_ruby_plugin"), output_type = "grpc", output_suffix = ".srcjar", **kwargs )
# -*- coding: utf-8 -*- """ > 005 @ Jane Street ~~~~~~~~~~~~~~~~~~~ ```cons(a, b)``` constructs a pair, and ```car(pair)``` and ```cdr(pair)``` returns the first and last element of that pair. For example, ```car(cons(3, 4))``` returns ```3```, and ```cdr(cons(3, 4))``` returns ```4```. Given this implementation of cons: ```Python def cons(a, b): def pair(f): return f(a, b) return pair ``` Implement ```car``` and ```cdr```. """ def cons(a, b): def pair(f): return f(a, b) return pair def car(f): def left(a, b): return a return f(left) def cdr(f): def right(a, b): return b return f(right) if __name__ == "__main__": assert car(cons(3, 4)) == 3 assert cdr(cons(3, 4)) == 4
# To review... adding up the lengths of strings in a list # e.g. totalLength(["UCSB","Apple","Pie"]) should be: 12 # because len("UCSB")=4, len("Apple")=5, and len("Pie")=3, and 4+5+3 = 12 def totalLength(listOfStrings): " add up length of all the strings " # for now, ignore errors.. assume they are all of type str count = 0 for string in listOfStrings: count = count + len(string) return count def test_totalLength_1(): assert totalLength(["UCSB","Apple","Pie"])==12 def test_totalLength_2(): assert totalLength([])==0 def test_totalLength_3(): assert totalLength(["Cal Poly"])==8
T = int(input('')) X = 0 Y = 0 for i in range(T): B = int(input('')) A1, D1, L1 = map(int, input().split()) A2, D2, L2 = map(int, input().split()) X = (A1 + D1) / 2 if L1 % 2 == 0: X = X + L1 Y = (A2 + D2) / 2 if L2 % 2 == 0: Y = Y + L1 if X == Y: print('Empate') elif X > Y: print('Dabriel') else: print('Guarte')
class Solution: def XXX(self, n: int) -> str: ans = '1#' for i in range(1, n): t, cnt = '', 1 for j in range(1, len(ans)): if ans[j] == ans[j - 1]: cnt += 1 else: t += (str(cnt) + ans[j - 1]) cnt = 1 t += '#' ans = t return ans[:-1]
# This kata was seen in programming competitions with a wide range of variations. A strict bouncy array of numbers, of # length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower # than its neighbours. # For example, the array: # arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] (length = 16) # The two longest bouncy subarrays of arr are # [7,9,6,10,5,11,10,12] (length = 8) and [4,2,5,1,6,4,8] (length = 7) # According to the given definition, the arrays [8,1,4,6,7], [1,2,2,1,4,5], are not bouncy. # For the special case of length 2 arrays, we will consider them strict bouncy if the two elements are different. # The arrays [-1,4] and [0,-10] are both bouncy, while [0,0] is not. # An array of length 1 will be considered strict bouncy itself. # You will be given an array of integers and you should output the longest strict bouncy subarray. # In the case of having more than one bouncy subarray of same length, it should be output the subarray with its first term of lowest index in the original array. # Let's see the result for the first given example. # arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] # longest_bouncy_list(arr) === [7,9,6,10,5,11,10,12] # See more examples in the example tests box. # Features of the random tests # length of the array inputs up to 1000 # -500 <= arr[i] <= 500 # Toy Problem in Progress # Giant Failure - Still in progress def longest_bouncy_list(arr): bounce = '' count = 0 value = [] depths = [[] for i in range(4)] if arr[1:] == arr[:-1]: return [arr[0]] if arr[0] < arr[1]: bounce = 'low' elif arr[0] > arr[1]: bounce = 'high' for x, y in zip(arr[::], arr[1::]): current_depth = 0 if bounce == 'high' and x > y: print("true high:", 'x:', x, 'y:', y) count += 1 bounce = 'low' depths[current_depth].append(x) elif bounce == 'low' and x < y: print("true low:", 'x:', x, 'y:', y) count += 1 bounce = 'high' depths[current_depth].append(x) elif bounce == 'low' and x > y or bounce == 'high' and x < y: current_depth += 1 depths[current_depth].append(x) depths[current_depth].append(y) print('break:', 'x:', x, 'y:', y) print('depths:', depths) arr4 = [10, 8, 1, -11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12, -12, -8, -1, -13, -11, 11] print(longest_bouncy_list(arr4)) # [-11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12] # [13, 2] arr1 = [7, 9, 6, 10, 5, 11, 10, 12, 13, 4, 2, 5, 1, 6, 4, 8] print(longest_bouncy_list(arr1)) # [7, 9, 6, 10, 5, 11, 10, 12] # arr2 = [7, 7, 7, 7, 7] # print(longest_bouncy_list(arr2)) # # [7] # arr3 = [1, 2, 3, 4, 5, 6] # print(longest_bouncy_list(arr3)) # [1,2]
DEFAULTS = { 'label': "{win[title]}", 'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]", 'label_no_window': None, 'max_length': None, 'max_length_ellipsis': '...', 'monitor_exclusive': True, 'ignore_windows': { 'classes': [], 'processes': [], 'titles': [] }, 'callbacks': { 'on_left': 'toggle_label', 'on_middle': 'do_nothing', 'on_right': 'do_nothing' } } VALIDATION_SCHEMA = { 'label': { 'type': 'string', 'default': DEFAULTS['label'] }, 'label_alt': { 'type': 'string', 'default': DEFAULTS['label_alt'] }, 'label_no_window': { 'type': 'string', 'nullable': True, 'default': DEFAULTS['label_no_window'] }, 'max_length': { 'type': 'integer', 'min': 1, 'nullable': True, 'default': DEFAULTS['max_length'] }, 'max_length_ellipsis': { 'type': 'string', 'default': DEFAULTS['max_length_ellipsis'] }, 'monitor_exclusive': { 'type': 'boolean', 'required': False, 'default': DEFAULTS['monitor_exclusive'] }, 'ignore_window': { 'type': 'dict', 'schema': { 'classes': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['classes'] }, 'processes': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['processes'] }, 'titles': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['titles'] } }, 'default': DEFAULTS['ignore_windows'] }, 'callbacks': { 'type': 'dict', 'schema': { 'on_left': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_left'], }, 'on_middle': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_middle'], }, 'on_right': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_right'] } }, 'default': DEFAULTS['callbacks'] } }
""" /* * * Crypto.BI Toolbox * https://Crypto.BI/ * * Author: José Fonseca (https://zefonseca.com/) * * Distributed under the MIT software license, see the accompanying * file COPYING or http://www.opensource.org/licenses/mit-license.php. * */ """ class CBAddress: """ Address related functions and constants. """ DEFAULT_ADDRESS_LENGTH = 34 COINBASE_ADDRESS = "0" * DEFAULT_ADDRESS_LENGTH
#!python3 class Error(Exception): pass class IncompatibleArgumentError(Error): pass class DataShapeError(Error): pass
x = 9 def f(x): return x
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTilt(self, root: TreeNode) -> int: tilt = [0] def dfs(node): if node is None: return 0 left = dfs(node.left) right = dfs(node.right) tilt[0] += abs(left - right) return left + right + node.val dfs(root) return tilt[0]
def test_filtering_sequential_blocks_with_bounded_range( w3, emitter, Emitter, wait_for_transaction): builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = "latest" initial_block_number = w3.eth.block_number builder.toBlock = initial_block_number + 100 filter_ = builder.deploy(w3) for i in range(100): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 100 assert len(filter_.get_new_entries()) == 100 def test_filtering_starting_block_range( w3, emitter, Emitter, wait_for_transaction): for i in range(10): emitter.functions.logNoArgs(which=1).transact() builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) initial_block_number = w3.eth.block_number for i in range(10): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 10 assert len(filter_.get_new_entries()) == 10 def test_requesting_results_with_no_new_blocks(w3, emitter): builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) assert len(filter_.get_new_entries()) == 0
""" reverse words author oinegexruam@ """ def reverse_word(word): word_reverse = '' for i in range(1, len(word) + 1): index_reverse = len(word) - i word_reverse += word[index_reverse] return word_reverse reverse_word(str(input('type a word: ')))
"""Scale a group of active objects up/down as required""" class ScalingGroup: """Scale collection of objects up/down to meet criteria""" def __init__(self, object_pool): self.object_pool = object_pool self.instances = [] def scale_to(self, number): """Adjust number of instances to match number""" current_number = len(self.instances) if current_number < number: # Scale up for _ in range(number - current_number): obj = self.object_pool.acquire() self.instances.append(obj) elif current_number > number: # Scale down for obj in self.instances[number:]: self.object_pool.release(obj) self.instances = self.instances[:number]
arquivo = open("dados.txt", "r") conteudo = arquivo.read() print("Todo o conteúdo do arquivo") print(repr(conteudo), '\n') conteudo_releitura = arquivo.read() print("Releitura de todo o conteúdo do arquivo") print(repr(conteudo_releitura), '\n') arquivo.close() #FECHAMOS E REABRIMOS O ARQUIVO PARA PODER O CURSOS SE POSICIONAR NO INICIO NOVAMENTE arquivo_reaberto = open("dados.txt", "r") conteudo_reaberto = arquivo_reaberto.read() print("Todo o conteúdo do arquivo novamente") print(repr(conteudo_reaberto), '\n') # ATRAVÉS DO SEEK() CONSEGUIMOS POSICIONAR O CURSOR NA LINHA DESEJADA PARA NÃO UTILIZAR O CLOSE() -> OPEN() arquivo_reaberto.seek(0) conteudo_seek = arquivo_reaberto.read() print("Todo o conteúdo do arquivo após o SEEK") print(repr(conteudo_seek)) arquivo_reaberto.close()
num_acc=int(input()) accounts={} for i in range(num_acc): p,b = input().split() accounts[p] = int(b) #print (accounts) num_t=int(input()) trans=[] for i in range(num_t): pf,pt,c,t = input().split() trans.append((int(t),pf,pt,int(c))) trans = sorted(trans) for i in trans: accounts[i[1]]-=i[3] accounts[i[2]]+=i[3] print (num_acc) for i in accounts.keys(): print(i,accounts[i])
count = 1 def show_title(msg): global count print('\n') print('#' * 30) print(count, '.', msg) print('#' * 30) count += 1
# result = 5/3 # if result: data = ['asdf', '123', 'Aa'] names = ['asdf', '123', 'Aa'] # builtin functions that operate on sequences # zip # max # min # sum sum([1, 2, 3]) # generator expressions print(sum(len(x) for x in data)) # all # any print(all(len(x) > 2 for x in data)) print(any(len(x) > 2 for x in data)) # enumerate # reversed for x in reversed(data): pass get_len = lambda x: len(x) def get_length(x): # equiv to "len" or "lambda x: len(x)" return len(x) def get_second_item(x): # equiv to lambda x: x[1] return x[1] # sorted print(sorted(data)) print(sorted(data, key=len)) print(sorted(data, key=get_len)) print(sorted(data, key=get_length)) print(sorted(data, key=(lambda x: len(x)))) print(sorted(names, key=lambda name: name[1])) # result = [] # for x in data: # if len(x) > 3: # result.append(x) # functional programming type functions # filter print(list(filter((lambda x: len(x) > 3), data))) # comprehension syntax is sometimes preferred to using filter print([x for x in data if len(x) > 3]) # map print(list(map((lambda x: len(x) > 3), data))) print(list(map((lambda x: len(x)), data))) print([len(x) for x in data if len(x) > 2]) # reduce def get_length_and_first_two_chars(string): return len(string), string[0], string[1] l, *_ = get_length_and_first_two_chars('abcdef') print(get_length_and_first_two_chars('abcdef')) one_million = 1_000_000 # sometimes you want to define a function # that can take in any of many optional parameters def print_all_args(*args, do_thing = False, **kwargs): # if len(args) == 1 and type(args[0]) == 'int': print(args) print(kwargs) def helper_function(commonly_used_arg, *args, **kwargs): print_all_args(1, commonly_used_arg, 3, '45', *args, myarg=5, do_thing=True, custom_option=False, **kwargs)
__copyright__ = "2015 Cisco Systems, Inc." # Define your areas here. you can add or remove area in areas_container areas_container = [ { "areaId": "area1", "areaName": "Area Name 1", "dimension": { "length": 100, "offsetX": 0, "offsetY": 0, "unit": "FEET", "width": 100 }, "floorRefId": "723402329507758200" }, { "areaId": "area2", "areaName": "Area Name 2", "dimension": { "length": 500, "offsetX": 0, "offsetY": 100, "unit": "FEET", "width": 500 }, "floorRefId": "723402329507758200" }, { "areaId": "area3", "areaName": "Area Name 3", "dimension": { "length": 100, "offsetX": 100, "offsetY": 0, "unit": "FEET", "width": 100 }, "floorRefId": "723402329507758200" } ] # none area area_none = { "areaId": "none" }
# apis_v1/documentation_source/voter_guide_possibility_retrieve_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def voter_guide_possibility_retrieve_doc_template_values(url_root): """ Show documentation about voterGuidePossibilityRetrieve """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, ] optional_query_parameter_list = [ { 'name': 'url_to_scan', 'value': 'string', # boolean, integer, long, string 'description': 'The url where a voter guide can be found. ' 'Either this url or the voter_guide_possibility_id is required.', }, { 'name': 'voter_guide_possibility_id', 'value': 'integer', # boolean, integer, long, string 'description': 'Either this id or a url_to_scan is required.', }, ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. A valid voter_id was not found.', }, { 'code': 'VOTER_GUIDE_POSSIBILITY_NOT_FOUND', 'description': 'A voter guide possibility was not found at that URL.', }, { 'code': 'VOTER_GUIDE_POSSIBILITY_FOUND_WITH_URL', 'description': 'A voter guide possibility entry was found.', }, # { # 'code': '', # 'description': '', # }, ] try_now_link_variables_dict = { 'url_to_scan': 'https://projects.sfchronicle.com/2018/voter-guide/endorsements-list/', } api_response = '{\n' \ ' "status": string,\n' \ ' "success": boolean,\n' \ ' "candidate": dict\n' \ ' {\n' \ ' "candidate_we_vote_id": string,\n' \ ' "candidate_name": string,\n' \ ' "candidate_website": string,\n' \ ' "candidate_twitter_handle": string,\n' \ ' "candidate_email": string,\n' \ ' "candidate_facebook": string,\n' \ ' "we_vote_hosted_profile_image_url_medium": string,\n'\ ' "we_vote_hosted_profile_image_url_tiny": string,\n' \ ' },\n' \ ' "candidates_missing_from_we_vote": boolean,\n' \ ' "cannot_find_endorsements": boolean,\n' \ ' "capture_detailed_comments": boolean,\n' \ ' "contributor_comments": string,\n' \ ' "contributor_email": string,\n' \ ' "hide_from_active_review": boolean,\n' \ ' "ignore_this_source": boolean,\n' \ ' "internal_notes": string,\n' \ ' "organization": dict\n' \ ' {\n' \ ' "organization_we_vote_id": string,\n' \ ' "organization_name": string,\n' \ ' "organization_website": string,\n' \ ' "organization_twitter_handle": string,\n' \ ' "organization_email": string,\n' \ ' "organization_facebook": string,\n' \ ' "we_vote_hosted_profile_image_url_medium": string,\n'\ ' "we_vote_hosted_profile_image_url_tiny": string,\n' \ ' },\n' \ ' "possible_candidate_name": string,\n' \ ' "possible_candidate_twitter_handle": string,\n' \ ' "possible_owner_of_website_candidates_list": list,\n' \ ' [\n' \ ' {\n' \ ' "candidate_we_vote_id": string,\n' \ ' "candidate_name": string,\n' \ ' "candidate_website": string,\n' \ ' "candidate_twitter_handle": string,\n' \ ' "candidate_email": string,\n' \ ' "candidate_facebook": string,\n' \ ' "candidate_photo_url_medium": string,\n'\ ' "candidate_photo_url_tiny": string,\n' \ ' },\n' \ ' ]\n' \ ' "possible_organization_name": string,\n' \ ' "possible_organization_twitter_handle": string,\n' \ ' "possible_owner_of_website_organizations_list": list,\n' \ ' [\n' \ ' {\n' \ ' "organization_id": integer,\n' \ ' "organization_we_vote_id": string,\n' \ ' "organization_name": string,\n' \ ' "organization_website": string,\n' \ ' "organization_twitter_handle": string,\n' \ ' "organization_email": string,\n' \ ' "organization_facebook": string,\n' \ ' "organization_photo_url_medium": string,\n'\ ' "organization_photo_url_tiny": string,\n' \ ' },\n' \ ' ]\n' \ ' "limit_to_this_state_code": string,\n' \ ' "url_to_scan": string,\n' \ ' "voter_device_id": string (88 characters long),\n' \ ' "voter_guide_possibility_edit": string,\n' \ ' "voter_guide_possibility_id": integer,\n' \ ' "voter_guide_possibility_type": string,\n' \ '}' template_values = { 'api_name': 'voterGuidePossibilityRetrieve', 'api_slug': 'voterGuidePossibilityRetrieve', 'api_introduction': "Has a particular web page URL been captured as a possible voter guide?", 'try_now_link': 'apis_v1:voterGuidePossibilityRetrieveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values
Errors = { 400: "BAD_REQUEST_BODY", 401: "UNAUTHORIZED", 403: "ACCESS_DENIED", 404: "NotFoundError", 406: "NotAcceptableError", 409: "ConflictError", 415: "UnsupportedMediaTypeError", 422: "UnprocessableEntityError", 429: "TooManyRequestsError", 500: "API_CONFIGURATION_ERROR", 502: "BadGatewayError", 503: "ServiceUnavailableError", 504: "GatewayTimeoutError" }
response = {"username": "username", "password": "pass"} db = list() def add_user(user_obj): password = response.get("password") if len(password) < 5: return "Password is shorter than 5 characters." else: db.append(user_obj) return "User has been added." print(add_user(response)) print(db)
#errorcodes.py #version 2.0.6 errorList = ["no error", "error code 1", "mrBayes.py: Could not open quartets file", "mrBayes.py: Could not interpret quartets file", "mrBayes.py: Could not open translate file", "mrBayes.py: Could not interpret translate file", "mrBayes.py: Could not interpret condor job name", "mrBayes.py: Could not find tarfile", "mrBayes.py: Could not create data subdirectory", "mrBayes.py: Could not open tarfile", "mrBayes.py: Could not open list of gene files", "mrBayes.py: Could not get gene files from tarfile", "mrBayes.py: Could not get gene files from data directory", "mrBayes.py: Could not interpret read tar.gz", "mrBayes.py: Could not extract file from tar.gz", "mrBayes.py: Could not open gene file", "mrBayes.py: Could not interpret gene file", "mrBayes.py: Could not initialize quartet subset of gene file", "mrBayes.py: Could not write quartet subset of gene file", "mrBayes.py: Could not run mrBayes", "mrBayes.py: Filename mismatch", "mrBayes.py: Could not find expected mcmc output", "mrBayes.py: Could not run mbsum", "mrBayes.py: Could not delete temporary files", "mrBayes.py: Could not create or write results file", "mrBayes.py: Could not create gene group zip file", "mrBayes.py: Could not delete file after zipping", "mrBayes.py: Statistics do not add", "mrBayes.py: Could not write gene group zip file" "zip_mb_output.py: Could not interpret condor job name", "zip_mb_output.py: Could not open target tar file", "zip_mb_output.py: Could not open input tar.gz", "zip_mb_output.py: Could not extract .in file", "zip_mb_output.py: Could not add .in file", "zip_mb_output.py: Could not delete .in file", "zip_mb_output.py: Could not delete input tar.gz", "zip_mb_output.py: Could not get directory.", "zip_mb_output.py: No input tar.gz found", "post_organize: missing node return status", "post_organize: organize.submit returned an error value", "post_organize: Could not update QuartetAnalysis metafile", "post_organize: Could not interpret QuartetAnalysis metafile", "post_organize: missing output suffix", "report_results: missing node return status" "report_results: missing job name", "report_results: run_mrbayes.submit returned a non-zero value", "report_results: Could not read new stats from file", "report_results: Could not open QuartetAnalysis metafile", "report_results: Could not create new statistics line", "report_results: Could not interpret QuartetAnalysis metafile", "report_results: Could not delete stats file", "report_results: missing output suffix", "delete_mb_output: missing node return status", "delete_mb_output: missing job name", "delete_mb_output: error finding quartet index", "delete_mb_output: Could not open QuartetAnalysis metafile", "delete_mb_output: Could not interpret QuartetAnalysis metafile", "delete_mb_output: Could not delete bucky results file", "delete_mb_output: missing output suffix", "fileWriter_condor: Could not initialize", "fileWriter_condor: Less than four taxa found", "fileWriter_condor: Could not open new nexus file", "fileWriter_condor: Could not create or write header", "fileWriter_condor: Could not write data", "fileWriter_condor: Could not write END to data block", "fileWriter_condor: Could not write MrBayes Block", "fileWriter_condor: Could not close new nexus file", "run_bucky.py: Could not open/interpret translate file", "run_bucky.py: Could not interpret job name", "run_bucky.py: Could not interpret gene file", "run_bucky.py: could not open/interpret quartet file in mrBayes.py", "run_bucky.py: number of gene files is zero", "run_bucky.py: could not open/interpret QuartetAnalysis metafile", "run_bucky.py: could not open tar file with mrBayes/mbsum results", "run_bucky.py: mrBayes/mbsum results empty", "run_bucky.py: mrBayes/mbsum results too few", "run_bucky.py: could not extract files from .tar.gz", "run_bucky.py: error in BUCKy", "run_bucky.py: could not write gene stats", "run_bucky.py: could not make gene dictionary", "run_bucky.py: error writing results", "run_bucky.py: error deleting files.", "mrBayes.py: Execution failed", "mrBayes.py: Unknown mrBayes execution error" ] def findErrorCode(errorString): try: errorCode = errorList.index(errorString) except: errorCode = -1 return errorCode def errorString(errorCode): if( errorCode == -1 ): return "unknown error code" try: errorString = errorList[errorCode] except: errorString = "unknown error code" return errorString
size_matrix = int(input()) matrix = [] pls = [] for i in range(size_matrix): matrix.append([x for x in input()]) for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == 'B': pls.append((row, col)) count_food = 0 for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == '*': count_food += 1 row_s = 0 col_s = 0 for search_s in matrix: if "S" in search_s: col_s = search_s.index("S") break else: row_s += 1 first_position_s = matrix[row_s][col_s] countar_stop_food = 0 if pls: exit_B_row = int(pls[1][0]) exit_B_col = int(pls[1][1]) while True: command = input() if not command: break if command == "up": if row_s - 1 >= 0: if matrix[row_s - 1][col_s] == "B": matrix[row_s][col_s] = "." matrix[row_s - 1][col_s] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s - 1][col_s] == "*": matrix[row_s][col_s] = "." matrix[row_s - 1][col_s] = "S" countar_stop_food += 1 row_s -= 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s - 1][col_s] == "-": matrix[row_s - 1][col_s] = "S" matrix[row_s][col_s] = "." row_s -= 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for d in matrix: print(''.join(d)) exit() elif command == "down": if row_s + 1 < len(matrix): if matrix[row_s + 1][col_s] == "B": matrix[row_s][col_s] = "." matrix[row_s + 1][col_s] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s + 1][col_s] == "*": matrix[row_s][col_s] = "." matrix[row_s + 1][col_s] = "S" countar_stop_food += 1 row_s += 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s + 1][col_s] == "-": matrix[row_s + 1][col_s] = "S" matrix[row_s][col_s] = "." row_s += 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for d in matrix: print(''.join(d)) exit() elif command == "left": if col_s - 1 >= 0: if matrix[row_s][col_s - 1] == "B": matrix[row_s][col_s] = "." matrix[row_s][col_s - 1] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s - 1] == "*": matrix[row_s][col_s] = "." matrix[row_s][col_s - 1] = "S" countar_stop_food += 1 col_s -= 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s][col_s - 1] == "-": matrix[row_s][col_s - 1] = "S" matrix[row_s][col_s] = "." col_s -= 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for l in matrix: print(''.join(l)) exit() elif command == "right": if col_s + 1 < len(matrix): if matrix[row_s][col_s + 1] == "B": matrix[row_s][col_s] = "." matrix[row_s][col_s + 1] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s + 1] == "*": matrix[row_s][col_s] = "." matrix[row_s][col_s + 1] = "S" countar_stop_food += 1 col_s += 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for r in matrix: print(''.join(r)) exit() elif matrix[row_s][col_s + 1] == "-": matrix[row_s][col_s + 1] = "S" matrix[row_s][col_s] = "." col_s += 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for r in matrix: print(''.join(r)) exit()
"""createwxdb configuration information. """ #: MongoDb URI where fisb_location DB is located. MONGO_URI = 'mongodb://localhost:27017/'
+ utility('transmissionMgmt',50) + requiresFunction('transmissionMgmt','transmissionF') + utility('transmissionF',100) + requiresFunction('transmissionF','opcF') + implements('opcF','opc',0) + consumesData('transmissionMgmt','engineerWorkstation','statusRestData',False,0,True,1,True,0.5) #Allocation/Deployments +isType('opc','service') +isType('switchA','switch') + networkConnectsToWithAttributes('opc','switchA',True,True,True) #Style validConnection(SourceService,TargetService) <= isType(SourceService,'switch') & isType(TargetService,'service')
class AsyncSerialPy3Mixin: async def read_exactly(self, n): data = bytearray() while len(data) < n: remaining = n - len(data) data += await self.read(remaining) return data async def write_exactly(self, data): while data: res = await self.write(data) data = data[res:]
def test_clear_group(app): while 0 != app.group.count_groups(): app.group.delete_first_group() else: print("Group list is already empty")