content
stringlengths
7
1.05M
bash(''' echo "hello" ''') bash(''' for i in $(seq 1 10); do echo $i sleep 2 done ''')
class Noeud: '''Noeud d'un arbre binaire''' def __init__(self, valeur=None): '''Créé un nœud avec une valeur (None par défaut)''' # valeur (object) : valeur a stocker dans le nœud. On présume que valeur # implémente une méthode pour être comparée à elle-même self.valeur = valeur # gauche (noeud) : référence vers le noeud-fils à gauche self.gauche = None # droite (noeud) : référence vers le noeud-fils à droite self.droite = None # parent (noeud) : référence vers le noeud-parent self.parent = None def assigner_droite(self, noeud): '''Assigne un fils droit au noeud''' self.droite = noeud noeud.parent = self def assigner_gauche(self, noeud): '''Assigne un fils gauche au noeud''' self.gauche = noeud noeud.parent = self def parcours_prefixe(self): '''Affiche le parcours préfixe à partir de cette instance de noeud''' print(self.valeur) if self.gauche != None: self.gauche.parcours_prefixe() if self.droite != None: self.droite.parcours_prefixe() def parcours_infixe(self): '''Affiche le parcours infixe à partir de cette instance de noeud''' if self.gauche != None: self.gauche.parcours_infixe() print(self.valeur) if self.droite != None: self.droite.parcours_infixe() def parcours_suffixe(self): '''Affiche le parcours suffixe à partir de cette instance de noeud''' if self.gauche != None: self.gauche.parcours_suffixe() if self.droite != None: self.droite.parcours_suffixe() print(self.valeur) def parcours_profondeur(self): '''Affiche le parcours en profondeur à partir de cette instance de noeud''' # Initialisation # a_visiter (list(noeud)) : contient la pile des noeuds à visiter a_visiter = [] # noeud_en_cours (noeud) : noeud_en_cours d'exploration noeud_en_cours = None # On ajoute la racine (cette instance) au sommet de la pile a_visiter.append(self) # Début du traitement # Tant qu'on a au moins un noeud à explorer, on l'explore while a_visiter != []: noeud_en_cours = a_visiter.pop() print(noeud_en_cours.valeur) # On ajoute les fils de noeud_en_cours à la pile if noeud_en_cours.gauche != None: a_visiter.append(noeud_en_cours.gauche) if noeud_en_cours.droite != None: a_visiter.append(noeud_en_cours.droite) def parcours_largeur(self): '''Affiche le parcours en profondeur à partir de cette instance de noeud''' # Initialisation # a_visiter (list(noeud)) : contient la file des noeuds à visiter a_visiter = [] # noeud_en_cours (noeud) : noeud_en_cours d'exploration noeud_en_cours = None # On ajoute la racine (cette instance) au bout de la pile a_visiter.append(self) # Début du traitement # Tant qu'on a au moins un noeud à explorer, on l'explore while a_visiter != []: noeud_en_cours = a_visiter.pop(0) print(noeud_en_cours.valeur) # On ajoute les fils de noeud_en_cours à la pile if noeud_en_cours.gauche != None: a_visiter.append(noeud_en_cours.gauche) if noeud_en_cours.droite != None: a_visiter.append(noeud_en_cours.droite) def rotation_droite(self): '''Tourne l'arbre à droite depuis ce noeud''' # Initialisation # pivot (noeud) : nouvelle racine pivot = self.gauche self.gauche = pivot.droite pivot.droite = self self = pivot def rotation_gauche(self): '''Tourne l'arbre à gauche depuis ce noeud''' # Initialisation # pivot (noeud) : nouvelle racine pivot = self.droite self.droite = pivot.gauche pivot.gauche = self self = pivot
# This script generates a theorem for them Z3 SAT solver. The output of this program # is designed to be the input for http://rise4fun.com/z3 # The output of z3 is the coordinates of the queens for a solution to the N Queen problem :) #Prints an assert statement def zassert(x): print("( assert ( {} ) )".format(x)) #Prints a declaration def zdeclare(x, type="Int"): print("( declare-const {} {} )".format(x,type)) #Generates a Z3 proof. # N = number of queens. # G = grid size (8 = chess board) def generate(N, G) : zdeclare("N") #Nuber of queens zdeclare("G") #Board size zassert("= N {}".format(N)) #Init N zassert("= G {}".format(G)) #Init G #Generate queen names queensX = ["P{}_x".format(n) for n in range(0, N) ] queensY = ["P{}_y".format(n) for n in range(0, N) ] #Declare queens for i in range(N): zdeclare(queensX[i]) zdeclare(queensY[i]) #For each queen Position for P in range(N): #Assert bounds zassert(">= {} 0".format(queensX[P])) zassert(">= {} 0".format(queensY[P])) zassert("< {} G".format(queensX[P])) zassert("< {} G".format(queensY[P])) for PP in range(P+1, N): #Assert Horizontal and Vertical Uniqueness zassert("not ( or (= {ax} {bx} ) (= {ay} {by} ) )" .format(ax=queensX[P], bx=queensX[PP], ay=queensY[P], by=queensY[PP])) #Assert Diagonal uniqueness # / angle zassert("not ( exists (( t Int )) ( and ( and ( and ( = (+ {ax} t) {bx} ) ( >= (+ {ax} t) 0 ) ) ( < (+ {ax} t) G ) ) ( and ( and ( = (+ {ay} t) {by} ) ( >= (+ {ay} t) 0 ) ) ( < (+ {ay} t) G ) ) ) )" .format(ax=queensX[P], bx=queensX[PP], ay=queensY[P], by=queensY[PP])) # \ angle zassert("not ( exists (( t Int )) ( and ( and ( and ( = (+ {ax} t) {bx} ) ( >= (+ {ax} t) 0 ) ) ( < (+ {ax} t) G ) ) ( and ( and ( = (- {ay} t) {by} ) ( >= (- {ay} t) 0 ) ) ( < (- {ay} t) G ) ) ) )" .format(ax=queensX[P], bx=queensX[PP], ay=queensY[P], by=queensY[PP])) print("(check-sat)") print("(get-model)") #Generate proof for 8 queens on an 8x8 grid generate(8,8)
# cook your dish here try: t = int(input()) for _ in range(t): r, c, k = map(int, input().rstrip().split(' ')) if r <= k: start_row = 1 else: start_row = r-k if c <= k: start_col = 1 else: start_col = c-k if r+k >= 8: end_row = 8 else: end_row = r+k if c+k >= 8: end_col = 8 else: end_col = c+k print((end_row - start_row + 1)*(end_col - start_col + 1)) except: pass
""" 3047 : ABC URL : https://www.acmicpc.net/problem/3047 Input : 1 5 3 ABC Output : 1 3 5 """ a = list(sorted(map(int, input().split()))) order = input() b = [] for o in order: b.append(a[ord(o) - ord('A')]) print(' '.join(str(c) for c in b))
class Solution: def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ sums = [0] s = 0 for num in nums: s += num sums.append(s) for i in range(len(sums)): for j in range(i + 2, len(sums)): r = (sums[j] - sums[i]) if k != 0 and r % k == 0 or k == 0 and r == 0: return True return False if __name__ == "__main__": print(Solution().checkSubarraySum([23, 2, 4, 6, 7], 6)) print(Solution().checkSubarraySum([23, 4, 2, 6, 7], 6)) print(Solution().checkSubarraySum([0, 0], 0))
'''Defines data and parameters in an easily resuable format.''' # Common sequence alphabets. ALPHABETS = { 'dna': 'ATGCNatgcn-', 'rna': 'AUGCNaugcn', 'peptide': 'ACDEFGHIKLMNPQRSTVWYXacdefghiklmnpqrstvwyx'} COMPLEMENTS = { 'dna': {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G', 'N': 'N', 'a': 't', 't': 'a', 'g': 'c', 'c': 'g', 'n': 'n', '-': '-'}, 'rna': {'A': 'U', 'U': 'A', 'G': 'C', 'C': 'G', 'N': 'N', 'a': 'u', 'u': 'a', 'g': 'c', 'c': 'g', 'n': 'n'}} # The standard codon table. CODON_TABLE = { 'A': ['GCG', 'GCA', 'GCU', 'GCC'], 'R': ['AGG', 'AGA', 'CGG', 'CGA', 'CGU', 'CGC'], 'N': ['AAU', 'AAC'], 'D': ['GAU', 'GAC'], 'C': ['UGU', 'UGC'], '*': ['UGA', 'UAG', 'UAA'], 'Q': ['CAG', 'CAA'], 'E': ['GAG', 'GAA'], 'G': ['GGG', 'GGA', 'GGU', 'GGC'], 'H': ['CAU', 'CAC'], 'I': ['AUA', 'AUU', 'AUC'], 'L': ['UUG', 'UUA', 'CUG', 'CUA', 'CUU', 'CUC'], 'K': ['AAG', 'AAA'], 'M': ['AUG'], 'F': ['UUU', 'UUC'], 'P': ['CCG', 'CCA', 'CCU', 'CCC'], 'S': ['AGU', 'AGC', 'UCG', 'UCA', 'UCU', 'UCC'], 'T': ['ACG', 'ACA', 'ACU', 'ACC'], 'W': ['UGG'], 'Y': ['UAU', 'UAC'], 'V': ['GUG', 'GUA', 'GUU', 'GUC']} # Saccharomyces cerevisiae # source: http://www.kazusa.or.jp/codon/ # (which cites GenBank, i.e. yeast genome project CDS database) CODON_FREQ = { 'sc': { 'GCG': 0.109972396541529, 'GCA': 0.288596474496094, 'GCU': 0.377014739102356, 'GCC': 0.224416389860021, 'AGG': 0.208564104515562, 'AGA': 0.481137590939125, 'CGG': 0.0392677130215486, 'CGA': 0.0676728924436203, 'CGU': 0.144572019635586, 'CGC': 0.0587856794445578, 'AAU': 0.589705127199784, 'AAC': 0.410294872800217, 'GAU': 0.65037901553924, 'GAC': 0.34962098446076, 'UGU': 0.629812614586062, 'UGC': 0.370187385413938, 'UGA': 0.303094329334787, 'UAG': 0.225736095965104, 'UAA': 0.471169574700109, 'CAG': 0.307418833439535, 'CAA': 0.692581166560465, 'GAG': 0.296739610207218, 'GAA': 0.703260389792782, 'GGG': 0.119057918187951, 'GGA': 0.215422869017838, 'GGU': 0.472217600813099, 'GGC': 0.193301611981112, 'CAU': 0.636710255236351, 'CAC': 0.363289744763649, 'AUA': 0.273331091899568, 'AUU': 0.462925823433014, 'AUC': 0.263743084667417, 'UUG': 0.286319859527146, 'UUA': 0.275534472444779, 'CUG': 0.110440170850593, 'CUA': 0.141277445174148, 'CUU': 0.129115062940288, 'CUC': 0.0573129890630467, 'AAG': 0.423936637198697, 'AAA': 0.576063362801303, 'AUG': 1, 'UUU': 0.586126603840976, 'UUC': 0.413873396159024, 'CCG': 0.120626895854398, 'CCA': 0.417143753704543, 'CCU': 0.307740315888567, 'CCC': 0.154489034552491, 'AGU': 0.159245398699046, 'AGC': 0.109749229743856, 'UCG': 0.0963590866114069, 'UCA': 0.210157220085731, 'UCU': 0.264456618519558, 'UCC': 0.160032446340401, 'ACG': 0.135583991997041, 'ACA': 0.302413913478422, 'ACU': 0.345237040780705, 'ACC': 0.216765053743832, 'UGG': 1, 'UAU': 0.559573963633711, 'UAC': 0.440426036366289, 'GUG': 0.190897642582249, 'GUA': 0.208783185960798, 'GUU': 0.391481704636128, 'GUC': 0.208837466820824}} # Codon usage organized by organism, then amino acid CODON_FREQ_BY_AA = { 'sc': { 'A': {'GCG': 0.109972396541529, 'GCA': 0.288596474496094, 'GCU': 0.377014739102356, 'GCC': 0.224416389860021}, 'R': {'AGG': 0.208564104515562, 'AGA': 0.481137590939125, 'CGG': 0.0392677130215486, 'CGA': 0.0676728924436203, 'CGU': 0.144572019635586, 'CGC': 0.0587856794445578}, 'N': {'AAU': 0.589705127199784, 'AAC': 0.410294872800217}, 'D': {'GAU': 0.65037901553924, 'GAC': 0.34962098446076}, 'C': {'UGU': 0.629812614586062, 'UGC': 0.370187385413938}, '*': {'UGA': 0.303094329334787, 'UAG': 0.225736095965104, 'UAA': 0.471169574700109}, 'Q': {'CAG': 0.307418833439535, 'CAA': 0.692581166560465}, 'E': {'GAG': 0.296739610207218, 'GAA': 0.703260389792782}, 'G': {'GGG': 0.119057918187951, 'GGA': 0.215422869017838, 'GGU': 0.472217600813099, 'GGC': 0.193301611981112}, 'H': {'CAU': 0.636710255236351, 'CAC': 0.363289744763649}, 'I': {'AUA': 0.273331091899568, 'AUU': 0.462925823433014, 'AUC': 0.263743084667417}, 'L': {'UUG': 0.286319859527146, 'UUA': 0.275534472444779, 'CUG': 0.110440170850593, 'CUA': 0.141277445174148, 'CUU': 0.129115062940288, 'CUC': 0.0573129890630467}, 'K': {'AAG': 0.423936637198697, 'AAA': 0.576063362801303}, 'M': {'AUG': 1}, 'F': {'UUU': 0.586126603840976, 'UUC': 0.413873396159024}, 'P': {'CCG': 0.120626895854398, 'CCA': 0.417143753704543, 'CCU': 0.307740315888567, 'CCC': 0.154489034552491}, 'S': {'AGU': 0.159245398699046, 'AGC': 0.109749229743856, 'UCG': 0.0963590866114069, 'UCA': 0.210157220085731, 'UCU': 0.264456618519558, 'UCC': 0.160032446340401}, 'T': {'ACG': 0.135583991997041, 'ACA': 0.302413913478422, 'ACU': 0.345237040780705, 'ACC': 0.216765053743832}, 'W': {'UGG': 1}, 'Y': {'UAU': 0.559573963633711, 'UAC': 0.440426036366289}, 'V': {'GUG': 0.190897642582249, 'GUA': 0.208783185960798, 'GUU': 0.391481704636128, 'GUC': 0.208837466820824}}} # Complete list of codons. CODONS = {'AAA': 'K', 'AAC': 'N', 'AAG': 'K', 'AAU': 'N', 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACU': 'T', 'AGA': 'R', 'AGC': 'S', 'AGG': 'R', 'AGU': 'S', 'AUA': 'I', 'AUC': 'I', 'AUG': 'M', 'AUU': 'I', 'CAA': 'Q', 'CAC': 'H', 'CAG': 'Q', 'CAU': 'H', 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCU': 'P', 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGU': 'R', 'CUA': 'L', 'CUC': 'L', 'CUG': 'L', 'CUU': 'L', 'GAA': 'E', 'GAC': 'D', 'GAG': 'E', 'GAU': 'D', 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCU': 'A', 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGU': 'G', 'GUA': 'V', 'GUC': 'V', 'GUG': 'V', 'GUU': 'V', 'UAA': '*', 'UAC': 'Y', 'UAG': '*', 'UAU': 'Y', 'UCA': 'S', 'UCC': 'S', 'UCG': 'S', 'UCU': 'S', 'UGA': '*', 'UGC': 'C', 'UGG': 'W', 'UGU': 'C', 'UUA': 'L', 'UUC': 'F', 'UUG': 'L', 'UUU': 'F'}
# Created by MechAviv # White Heaven Sun Damage Skin | (2433828) if sm.addDamageSkin(2433828): sm.chat("'White Heaven Sun Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
def expose(board, x, y): if not board[y][x].flagged: board[y][x].exposed = True #debug print(x, y, sep='\t') if x == 0 or x == len(board[0]) - 1 or y == 0 or y == len(board) - 1 or board[y][x].mine: return 0 if board[y][x].neighbours == 0: if board[y-1][x-1].exposed is False: expose(board, x-1, y-1) if board[y-1][x].exposed is False: expose(board, x, y-1) if board[y-1][x+1].exposed is False: expose(board, x+1, y-1) if board[y][x-1].exposed is False: expose(board, x-1, y) if board[y][x+1].exposed is False: expose(board, x+1, y) if board[y+1][x-1].exposed is False: expose(board, x-1, y+1) if board[y+1][x].exposed is False: expose(board, x, y+1) if board[y+1][x+1].exposed is False: expose(board, x+1, y+1) return 0
number = 5 numbers = [1,2,3,4,5] # if statement if number == 5: print(number) if len(numbers) == 5: print(numbers[3]) if number in numbers: # if 3 in [1,2,3,4,5] print("3 is here") # elif and else statement if number == 3: print("is 3") elif number == 5: print("is 5") else: print("not 3 & 5")
memo = { 0: 0, 1: 1, 2: 1, } def fib(n): if n in memo: return memo[n] val = fib(n-1) + fib(n-2) memo[n] = val return val print(fib(35))
class Screen(object): """ Represents a display device or multiple display devices on a single system. """ def Equals(self,obj): """ Equals(self: Screen,obj: object) -> bool Gets or sets a value indicating whether the specified object is equal to this Screen. obj: The object to compare to this System.Windows.Forms.Screen. Returns: true if the specified object is equal to this System.Windows.Forms.Screen; otherwise,false. """ pass @staticmethod def FromControl(control): """ FromControl(control: Control) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the specified control. control: A System.Windows.Forms.Control for which to retrieve a System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the specified control. In multiple display environments where no display contains the control,the display closest to the specified control is returned. """ pass @staticmethod def FromHandle(hwnd): """ FromHandle(hwnd: IntPtr) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the object referred to by the specified handle. hwnd: The window handle for which to retrieve the System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the object. In multiple display environments where no display contains any portion of the specified window,the display closest to the object is returned. """ pass @staticmethod def FromPoint(point): """ FromPoint(point: Point) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the specified point. point: A System.Drawing.Point that specifies the location for which to retrieve a System.Windows.Forms.Screen. Returns: A System.Windows.Forms.Screen for the display that contains the point. In multiple display environments where no display contains the point,the display closest to the specified point is returned. """ pass @staticmethod def FromRectangle(rect): """ FromRectangle(rect: Rectangle) -> Screen Retrieves a System.Windows.Forms.Screen for the display that contains the largest portion of the rectangle. rect: A System.Drawing.Rectangle that specifies the area for which to retrieve the display. Returns: A System.Windows.Forms.Screen for the display that contains the largest region of the specified rectangle. In multiple display environments where no display contains the rectangle,the display closest to the rectangle is returned. """ pass @staticmethod def GetBounds(*__args): """ GetBounds(ctl: Control) -> Rectangle Retrieves the bounds of the display that contains the largest portion of the specified control. ctl: The System.Windows.Forms.Control for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified control. In multiple display environments where no display contains the specified control,the display closest to the control is returned. GetBounds(rect: Rectangle) -> Rectangle Retrieves the bounds of the display that contains the largest portion of the specified rectangle. rect: A System.Drawing.Rectangle that specifies the area for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified rectangle. In multiple display environments where no monitor contains the specified rectangle, the monitor closest to the rectangle is returned. GetBounds(pt: Point) -> Rectangle Retrieves the bounds of the display that contains the specified point. pt: A System.Drawing.Point that specifies the coordinates for which to retrieve the display bounds. Returns: A System.Drawing.Rectangle that specifies the bounds of the display that contains the specified point. In multiple display environments where no display contains the specified point,the display closest to the point is returned. """ pass def GetHashCode(self): """ GetHashCode(self: Screen) -> int Computes and retrieves a hash code for an object. Returns: A hash code for an object. """ pass @staticmethod def GetWorkingArea(*__args): """ GetWorkingArea(ctl: Control) -> Rectangle Retrieves the working area for the display that contains the largest region of the specified control. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. ctl: The System.Windows.Forms.Control for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified control,the display closest to the control is returned. GetWorkingArea(rect: Rectangle) -> Rectangle Retrieves the working area for the display that contains the largest portion of the specified rectangle. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. rect: The System.Drawing.Rectangle that specifies the area for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified rectangle,the display closest to the rectangle is returned. GetWorkingArea(pt: Point) -> Rectangle Retrieves the working area closest to the specified point. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. pt: A System.Drawing.Point that specifies the coordinates for which to retrieve the working area. Returns: A System.Drawing.Rectangle that specifies the working area. In multiple display environments where no display contains the specified point,the display closest to the point is returned. """ pass def ToString(self): """ ToString(self: Screen) -> str Retrieves a string representing this object. Returns: A string representation of the object. """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __ne__(self,*args): pass BitsPerPixel=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the number of bits of memory,associated with one pixel of data. Get: BitsPerPixel(self: Screen) -> int """ Bounds=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the bounds of the display. Get: Bounds(self: Screen) -> Rectangle """ DeviceName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the device name associated with a display. Get: DeviceName(self: Screen) -> str """ Primary=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether a particular display is the primary device. Get: Primary(self: Screen) -> bool """ WorkingArea=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the working area of the display. The working area is the desktop area of the display,excluding taskbars,docked windows,and docked tool bars. Get: WorkingArea(self: Screen) -> Rectangle """ AllScreens=None PrimaryScreen=None
# Esto es un comentario # enteros - int my_int = 42 # reales - float my_float = 3.14 # strings - str my_str = 'string con comilla simple' my_str_2 = "string con comilla doble" my_str_3 = """string multilinea""" """Los strings multilinea pueden servir para poner comentarios de varias líneas""" # booleans - bool my_bool_true = True my_bool_false = False # Imprimir por pantalla print('Imprime cualquier cosa entre los parentesis') # Operaciones aritméticas (int y floats) print(3 + 4) # Suma: 7 print(3 - 4) # Resta: -1 print(3 * 4) # Multiplicacion: 12 print(3 / 4) # Divison: 0.75 print(3 // 4) # Divion entera: 0 print(3 % 4) # Modulo: 3 print(3 ** 4) # Potenciacion: 81 print(-3) # Negativo: -3 print(+3) # Positivo: 3 # Los parentesis cambian la precedencia de los operadores print(3 / 4 * 5) # 3.75 print(3 / (4 * 5)) # 0.15 # La lista de precedencia de los operadores la podeis ver aqui: # https://docs.python.org/3/reference/expressions.html#operator-precedence # La lista esta ordenada de menor a mayor. Contiene muchas mas cosas de las que hemos visto # ahora, pero os puede servir si teneis dudas. # Operaciones ariméticas (str) print('Hello, ' + 'byteEpoch') # Hello, byteEpoch print('spam' * 3) # spamspamspam print('na' * 8 + ' Batman') # nananananananana Batman # print('Un string ' + 5) # ERROR: no se puede concatenar un str con algo que no sea un str # Cambio/Cast de tipos str(3) # int a str str(3.14) # float a str int('3') # str a int # int('3.14') # ERROR: no es un int float('3') # str a float float('3.14') # str a float bool(0) # False bool(42) # True bool(3.14) # True bool(0.0) # False bool('') # False bool(':)') # True # Declarar variables # Reglas para los nombres: # 1. Los nombres solo puedes contener caracteres alfanumericos y _ # 2. Las variables no pueden comenzar por numeros # 3. Las variables no pueden tener espacios # A parte de esto, las variables no pueden llamarse como algunas palabras # os dejo un link con las palabras prohibidas: # https://docs.python.org/3/reference/lexical_analysis.html#keywords # Por ultimo, las variables son case-senstive, no es lo mismo my_var que MY_VAR # Ejemplos de nombres de variables: my_var = 3 my_var_2 = 12 _my_other_var = 'papi' _12 = 'Arthur' MY_VAR = 'GREAT' # Ejemplos de variables con nombres invalidos # 12 = 'a' - Empieza por numero # dollar$ = '$' - Continen algo que no es un caracter alfanumerico o _ # my var = 12 - Contiene espacios # def = 2 - Palabra reservada # Leer por teclado my_value_from_keyboard = input() my_value_from_keyboard_2 = input('Este texto sale por pantalla como el print: ') # Longitud de un string print(len('hola')) # 4 """Primer programita en un string multilinea print('Hello, world!') print('What is your name?') my_name = input() print('It is good to meet you, ' + my_name) print('The length of your name is:') print(len(my_name)) print('What is your age?') my_age = input() print('You will be ' + str(int(my_age) + 1) + ' in a year.') """ # Operadores comparativos # Estos operadores devuelven un bool - True o False, 0 o 1 # Igual a my_num_1 = 7 my_num_2 = 7 print(my_num_1 == my_num_2) # True # Distinto de my_str1 = 'A' my_str2 = 'a' print(my_str1 != my_str2) # True # Mayor que print(5 > 3) # True # Menor que print(5 < 3) # False # Mayor o igual a print(5 >= 3) # True # Menor o igual a print(5 <= 3) # True # Operadores de asignacion # Asignan lo que haya a la derecha del operador a la variable de la izquierda # Asignacion normal my_number = 3 print(my_number) # 3 # Asignacion con suma # Suma lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number + 2 my_number += 2 print(my_number) # 5 # Asignacion con resta # Resta lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number - 2 my_number -= 2 print(my_number) # 3 # Asignacion con multiplicacion # Multiplica lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number * 2 my_number *= 2 print(my_number) # 6 # Asignacion con division # Divide lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number / 2 my_number /= 2 print(my_number) # 3 # Asignacion con potenciacion # Potencia lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number ** 2 my_number **= 2 print(my_number) # 9 # Asignacion con division entera # Divide y descarta la parte decimal de lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number // 2 my_number //= 2 print(my_number) # 4 # Asignacion con modulo # Obtiene el modulo de la division de lo que haya a la derecha a lo que ya hubiera a la izquierda # Seria equivalente a my_number = my_number % 2 my_number %= 2 print(my_number) # 0 # OR # Puerta logica que devuelve True si cualquiera de las dos partes es True. # En cualquier otro caso devuelve False. cobrar = False dejar = False print(cobrar or dejar) # 0 0 - False cobrar = False dejar = True print(cobrar or dejar) # 0 1 - True cobrar = True dejar = False print(cobrar or dejar) # 1 0 - True cobrar = True dejar = True print(cobrar or dejar) # 1 1 - True # AND # Puerta logica que devuelve True si, y solo si, ambas partes son True. # En cualquier otro caso devuelve False. cobramos = False soleado = False print(cobramos and soleado) # 0 0 - False cobramos = False soleado = True print(cobramos and soleado) # 0 1 - False cobramos = True soleado = False print(cobramos and soleado) # 1 0 - False cobramos = True soleado = True print(cobramos and soleado) # 1 1 - True # NOT # Puerta logica que devuelve la inversa, si es True, devuleve False, y si es False, devuleve True inversa = True print(not inversa) # False inversa = False print(not inversa) # True # Estructura de control condicional - if # Ejecuta el codigo que contiene si su condicion es True # Para indicar que el codigo esta dentro del if se hace indentando el codigo # Se puede indentar con cualquier numero de espacios o tabulador # aunque lo recomendable es con 4 espacios. # La mayoria de editores, sobre todo si son para python, transforman los # tabuladores en 4 espacios. # La sintaxis seria: # if CONDICION: # CODIGO if cobramos and soleado: print('Party hard!') # Si necesitamos tambien contemplar el caso contrario usamos else # La sintaxis seria: # if CONDICION: # CODIGO PARA CONDICION TRUE # else: # CODIGO PARA CONDICION FALSE if cobramos and soleado: print('Party hard!') else: print('Boooring!') # Happy Hacking! :)
num = int(input('\033[1;31mMe diga um número \033[m')) resultado = num % 2 par = (0) impar = (1) if resultado == impar: print('\033[1;32mO número\033[m \033[1;31m{}\033[m \033[1;34mé impar\033[m'.format(num)) else: print('\033[1;33mO número\033[m \033[1;31m{}\033[m \033[1;34mé par\033[m'.format(num))
# coding: utf-8 __version__ = '0.12.0'
# -*- coding: utf-8 -*- # Caching # https://docs.djangoproject.com/en/3.2/topics/cache/ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', }, 'staticfiles': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }
x, a, b = map(int, input().split()) if b <= a: print('delicious') elif b - a <= x: print('safe') else: print('dangerous')
class EvaluatorTestCases: expressions = [ ("1 2 + 2.5 * 2 5 SUM", 14.5, float, 3), ("1 2 3 SUM 4 5 SUM 6 7 SUM", sum(range(8)), int, 3), ("1 2 3 SUM 4 5 SUM 6 7 SUM 8.5 *", sum(range(8)) * 8.5, float, 4), ] not_ok = [ """ void test(){ int a; int b; a = int; b = int; int a /* scope violation*/ } """, """ void test(){ int a; int b; { int a; int b; { int c; int a; int q; int q; } } } """, """void a(){ }; void a(){ }""", """int i; i = str""", """int b; int b;""" ] ok = [ """ void test(){ int a; int b; a = int; b = int; } """, """ void test(){ int a; int b; a = int; b = int; { int a; int b; { int d; int e; } } } """, """str i; i = str""", """int b; int c;""" ]
class Args(object): def __init__(self): self.seed = 0 self.experiment = None self.network = None self.approach = None self.parameter = [] self.taskcla = None self.comment = None self.log_dir = None global args args = Args()
list1=[12,-7,5,64,-14] for num in list1: if num>=0: print(num,end=" ") list2=[12,14,-95,3] for num in list2: if num>=0: print(num,end=" ")
#Three character NHGIS codes to postal abbreviations state_codes = { '530':'WA', '100':'DE', '110':'DC', '550':'WI', '540':'WV', '150':'HI', '120':'FL', '560':'WY', '720':'PR', '340':'NJ', '350':'NM', '480':'TX', '220':'LA', '370':'NC', '380':'ND', '310':'NE', '470':'TN', '360':'NY', '420':'PA', '020':'AK', '320':'NV', '330':'NH', '510':'VA', '080':'CO', '060':'CA', '010':'AL', '050':'AR', '500':'VT', '170':'IL', '130':'GA', '180':'IN', '190':'IA', '250':'MA', '040':'AZ', '160':'ID', '090':'CT', '230':'ME', '240':'MD', '400':'OK', '390':'OH', '490':'UT', '290':'MO', '270':'MN', '260':'MI', '440':'RI', '200':'KS', '300':'MT', '280':'MS', '450':'SC', '210':'KY', '410':'OR', '460':'SD', '720':'PR' }
# função usada abaixo 'print()' é usada para exibir ou imprimir mensagens no console. # Iteiros | Int print(10) # Será exibido no console o numero 10 # Ponto Flutuante | Float print(9.5) # Cadeia de caracteres | Strings cadeia_de_caracter = "Olá Mundo!" print(cadeia_de_caracter) # Boleano | Boolean valor_verdadeiro = True valor_falso = False print("valor_verdadeiro: ", valor_verdadeiro) print("valor_falso: ", valor_falso) # Tipo de dado None, em Python não existe tipo de dados Null. valor_none = None print(valor_none) # Para verificar o tipo de dado armazenado em uma varivel usar a função type print("\n") print(type(valor_none)) print(type(valor_verdadeiro)) print(type(cadeia_de_caracter))
# Marcelo Campos de Medeiros # ADS UNIFIP # Exercicios Com Strings # https://wiki.python.org.br/ExerciciosComStrings ''' Leet spek generator. Leet é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras, como números por exemplo. A própria palavra leet admite muitas variações, como l33t ou 1337. O uso do leet reflete uma subcultura relacionada ao mundo dos jogos de computador e internet, sendo muito usada para confundir os iniciantes e afirmar-se como parte de um grupo. Pesquise sobre as principais formas de traduzir as letras. Depois, faça um programa que peça uma texto e transforme-o para a grafia leet speak. ''' print('='*30) print('{:*^30}'.format(' Leet spek generator ')) print('='*30) print() #primeiramente deve-se criar o dicióonario para cada letras do alfabeto e sua correspondente leet = { 'A': '4', 'B': '8', 'C': '<', 'D': '[)', 'E': '&', 'F': 'ph', 'G': '6', 'H': '#', 'I': '1', 'J': 'j', 'K': '|<', 'L': '|_', 'M': '|\/|', 'N': '/\/', 'O': '0', 'P': '|*', 'Q': '9', 'R': 'l2', 'S': '5', 'T': '7', 'U': 'v', 'V': 'V', 'W': 'vv', 'X': '><', 'Y': '`/', 'Z': '2' } texto = input('Informe um texto: ') print() # usando for passar por cada letrar do texto e for i in texto.upper(): # verificar se alfabetico o texto imprime seu correspondete valor if i.isalpha(): print(leet[i], end='') else: print (' ') print()
def uniquePaths(m: int, n: int) -> int: dp = [[0 for _ in range(m)] for _ in range(n)] for i in range(m): dp[0][i] = 1 for j in range(n): dp[j][0] = 1 for i in range(1, n): for j in range(1, m): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[-1][-1] if __name__ == "__main__": print(uniquePaths(3, 7)) print(uniquePaths(3, 2)) print(uniquePaths(7, 3)) print(uniquePaths(3, 3))
# -*- coding: utf-8 -*- """ Python Flight Mechanics Engine (PyFME). Copyright (c) AeroPython Development Team. Distributed under the terms of the MIT License. Constant variables ------------------ Sources: [1] - COESA standard - U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, D.C., 1976: http://hdl.handle.net/2060/19770009539 [2] - "Introducción a la Ingenería Aeroespacial". Sebastián Franchini, Óscar López García. UPM """ # AIR CONSTANTS # Adiabatic index or ratio of specific heats (dry air at 20º C) - [1] GAMMA_AIR = 1.4 # Specific gas constant for dry air (J/(Kg·K)) R_AIR = 287.05287 # Air at sea level conditions h=0 (m) RHO_0 = 1.225 # Density at sea level (kg/m3) - [1] P_0 = 101325 # Pressure at sea level (Pa) - [1] T_0 = 288.15 # Temperature at sea level (K) - [1] SOUND_VEL_0 = 340.293990543 # Sound speed at sea level (m/s) # EARTH CONSTANTS GRAVITY = 9.80665 # Gravity of Ethe Earth (m/s^2) - [1] # Standard Gravitational Parameter # product of the gravitational constant G and the mass M of the body (m³/s²) STD_GRAVITATIONAL_PARAMETER = 3.986004418e14 EARTH_MASS = 5.9722e24 # Mass of the Earth (kg) GRAVITATIONAL_CONSTANT = 6.67384e11 # Gravitational constant (N·m²/kg²) EARTH_MEAN_RADIUS = 6371000 # Mean radius of the Earth (m) - [2] # CONVERSIONS lbs2kg = 0.453592 # Pounds (lb) to kilograms (kg) ft2m = 0.3048 # Feet (ft) to meters (m) slug2kg = 14.5939 # Slug to kilograms (kg) slugft2_2_kgm2 = 1.35581795 # Slug*feet^2 to kilograms*meters^2 (kg*m^2)
a,b,c = input().split() #한번에 여러개의 입력을 받기 위해 .split() a = int(a) b = int(b) c = int(c) # 파이썬은 입력을 받을 때 문자열로 입력을 받기 때문에 int로 형변환 if a>b: print(">") elif a==b: print("==") else: print("<")
if __name__ == "__main__": base_path = "/data4/dheeraj/hashtag/all/Twitter/" f_tweets = open(base_path + "train_post.txt", "r") f_tags = open(base_path + "train_tag.txt", "r") tweets = f_tweets.readlines() tags = f_tags.readlines() f_tags.close() f_tweets.close() tweets = tweets[:100] tags = tags[:100] final_tweets = [] final_tags = [] for i, tag in enumerate(tags): all_tags = tag.split(';') for t in all_tags: final_tweets.append(tweets[i]) final_tags.append(t.strip()) for i, tweet in enumerate(final_tweets): tag = final_tags[i] with open(base_path + "data/" + str(i) + ".txt", "w") as f: f.write(tweet.strip()) f.write("\n") f.write(tag.strip())
# -*- coding: utf-8 -*- """Bandit directory containing multi-armed bandit implementations of BLA policies in python. **Files in this package** * :mod:`moe.bandit.bla.bla`: :class:`~moe.bandit.bla.bla.BLA` object for allocating bandit arms and choosing the winning arm based on BLA policy. """
# # PySNMP MIB module IPMROUTE-STD-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/IPMROUTE-STD-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:18:06 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( OctetString, Integer, ObjectIdentifier, ) = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection") ( IANAipMRouteProtocol, IANAipRouteProtocol, ) = mibBuilder.importSymbols("IANA-RTPROTO-MIB", "IANAipMRouteProtocol", "IANAipRouteProtocol") ( InterfaceIndexOrZero, InterfaceIndex, ) = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "InterfaceIndex") ( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ( ObjectGroup, ModuleCompliance, NotificationGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") ( mib_2, TimeTicks, ModuleIdentity, Integer32, Counter32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Unsigned32, MibIdentifier, Gauge32, Counter64, Bits, NotificationType, IpAddress, ) = mibBuilder.importSymbols("SNMPv2-SMI", "mib-2", "TimeTicks", "ModuleIdentity", "Integer32", "Counter32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Unsigned32", "MibIdentifier", "Gauge32", "Counter64", "Bits", "NotificationType", "IpAddress") ( RowStatus, DisplayString, TruthValue, TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention") ipMRouteStdMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 83)).setRevisions(("2000-09-22 00:00",)) if mibBuilder.loadTexts: ipMRouteStdMIB.setLastUpdated('200009220000Z') if mibBuilder.loadTexts: ipMRouteStdMIB.setOrganization('IETF IDMR Working Group') if mibBuilder.loadTexts: ipMRouteStdMIB.setContactInfo(' Dave Thaler\n Microsoft Corporation\n One Microsoft Way\n Redmond, WA 98052-6399\n US\n\n Phone: +1 425 703 8835\n EMail: dthaler@microsoft.com') if mibBuilder.loadTexts: ipMRouteStdMIB.setDescription('The MIB module for management of IP Multicast routing, but\n independent of the specific multicast routing protocol in\n use.') class LanguageTag(OctetString, TextualConvention): displayHint = '100a' subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1,100) ipMRouteMIBObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 83, 1)) ipMRoute = MibIdentifier((1, 3, 6, 1, 2, 1, 83, 1, 1)) ipMRouteEnable = MibScalar((1, 3, 6, 1, 2, 1, 83, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2),))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipMRouteEnable.setDescription('The enabled status of IP Multicast routing on this router.') ipMRouteEntryCount = MibScalar((1, 3, 6, 1, 2, 1, 83, 1, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteEntryCount.setDescription('The number of rows in the ipMRouteTable. This can be used\n to monitor the multicast routing table size.') ipMRouteTable = MibTable((1, 3, 6, 1, 2, 1, 83, 1, 1, 2), ) if mibBuilder.loadTexts: ipMRouteTable.setDescription('The (conceptual) table containing multicast routing\n information for IP datagrams sent by particular sources to\n the IP multicast groups known to this router.') ipMRouteEntry = MibTableRow((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteGroup"), (0, "IPMROUTE-STD-MIB", "ipMRouteSource"), (0, "IPMROUTE-STD-MIB", "ipMRouteSourceMask")) if mibBuilder.loadTexts: ipMRouteEntry.setDescription('An entry (conceptual row) containing the multicast routing\n information for IP datagrams from a particular source and\n addressed to a particular IP multicast group address.\n Discontinuities in counters in this entry can be detected by\n observing the value of ipMRouteUpTime.') ipMRouteGroup = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 1), IpAddress()) if mibBuilder.loadTexts: ipMRouteGroup.setDescription('The IP multicast group address for which this entry\n contains multicast routing information.') ipMRouteSource = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 2), IpAddress()) if mibBuilder.loadTexts: ipMRouteSource.setDescription('The network address which when combined with the\n corresponding value of ipMRouteSourceMask identifies the\n sources for which this entry contains multicast routing\n information.') ipMRouteSourceMask = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 3), IpAddress()) if mibBuilder.loadTexts: ipMRouteSourceMask.setDescription('The network mask which when combined with the corresponding\n value of ipMRouteSource identifies the sources for which\n this entry contains multicast routing information.') ipMRouteUpstreamNeighbor = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteUpstreamNeighbor.setDescription('The address of the upstream neighbor (e.g., RPF neighbor)\n from which IP datagrams from these sources to this multicast\n address are received, or 0.0.0.0 if the upstream neighbor is\n unknown (e.g., in CBT).') ipMRouteInIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 5), InterfaceIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInIfIndex.setDescription('The value of ifIndex for the interface on which IP\n datagrams sent by these sources to this multicast address\n are received. A value of 0 indicates that datagrams are not\n subject to an incoming interface check, but may be accepted\n on multiple interfaces (e.g., in CBT).') ipMRouteUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 6), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteUpTime.setDescription('The time since the multicast routing information\n represented by this entry was learned by the router.') ipMRouteExpiryTime = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 7), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteExpiryTime.setDescription('The minimum amount of time remaining before this entry will\n be aged out. The value 0 indicates that the entry is not\n subject to aging.') ipMRoutePkts = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRoutePkts.setDescription('The number of packets which this router has received from\n these sources and addressed to this multicast group\n address.') ipMRouteDifferentInIfPackets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteDifferentInIfPackets.setDescription('The number of packets which this router has received from\n these sources and addressed to this multicast group address,\n which were dropped because they were not received on the\n interface indicated by ipMRouteInIfIndex. Packets which are\n not subject to an incoming interface check (e.g., using CBT)\n are not counted.') ipMRouteOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteOctets.setDescription('The number of octets contained in IP datagrams which were\n received from these sources and addressed to this multicast\n group address, and which were forwarded by this router.') ipMRouteProtocol = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 11), IANAipMRouteProtocol()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteProtocol.setDescription('The multicast routing protocol via which this multicast\n forwarding entry was learned.') ipMRouteRtProto = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 12), IANAipRouteProtocol()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteRtProto.setDescription('The routing mechanism via which the route used to find the\n upstream or parent interface for this multicast forwarding\n entry was learned. Inclusion of values for routing\n protocols is not intended to imply that those protocols need\n be supported.') ipMRouteRtAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 13), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteRtAddress.setDescription('The address portion of the route used to find the upstream\n or parent interface for this multicast forwarding entry.') ipMRouteRtMask = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 14), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteRtMask.setDescription('The mask associated with the route used to find the upstream\n or parent interface for this multicast forwarding entry.') ipMRouteRtType = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("unicast", 1), ("multicast", 2),))).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteRtType.setDescription('The reason the given route was placed in the (logical)\n multicast Routing Information Base (RIB). A value of\n unicast means that the route would normally be placed only\n in the unicast RIB, but was placed in the multicast RIB\n (instead or in addition) due to local configuration, such as\n when running PIM over RIP. A value of multicast means that\n\n\n\n\n\n the route was explicitly added to the multicast RIB by the\n routing protocol, such as DVMRP or Multiprotocol BGP.') ipMRouteHCOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 2, 1, 16), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteHCOctets.setDescription('The number of octets contained in IP datagrams which were\n received from these sources and addressed to this multicast\n group address, and which were forwarded by this router.\n This object is a 64-bit version of ipMRouteOctets.') ipMRouteNextHopTable = MibTable((1, 3, 6, 1, 2, 1, 83, 1, 1, 3), ) if mibBuilder.loadTexts: ipMRouteNextHopTable.setDescription('The (conceptual) table containing information on the next-\n hops on outgoing interfaces for routing IP multicast\n datagrams. Each entry is one of a list of next-hops on\n outgoing interfaces for particular sources sending to a\n particular multicast group address.') ipMRouteNextHopEntry = MibTableRow((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteNextHopGroup"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopSource"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopSourceMask"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopIfIndex"), (0, "IPMROUTE-STD-MIB", "ipMRouteNextHopAddress")) if mibBuilder.loadTexts: ipMRouteNextHopEntry.setDescription('An entry (conceptual row) in the list of next-hops on\n outgoing interfaces to which IP multicast datagrams from\n particular sources to a IP multicast group address are\n routed. Discontinuities in counters in this entry can be\n detected by observing the value of ipMRouteUpTime.') ipMRouteNextHopGroup = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 1), IpAddress()) if mibBuilder.loadTexts: ipMRouteNextHopGroup.setDescription('The IP multicast group for which this entry specifies a\n next-hop on an outgoing interface.') ipMRouteNextHopSource = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 2), IpAddress()) if mibBuilder.loadTexts: ipMRouteNextHopSource.setDescription('The network address which when combined with the\n corresponding value of ipMRouteNextHopSourceMask identifies\n the sources for which this entry specifies a next-hop on an\n outgoing interface.') ipMRouteNextHopSourceMask = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 3), IpAddress()) if mibBuilder.loadTexts: ipMRouteNextHopSourceMask.setDescription('The network mask which when combined with the corresponding\n value of ipMRouteNextHopSource identifies the sources for\n which this entry specifies a next-hop on an outgoing\n interface.') ipMRouteNextHopIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 4), InterfaceIndex()) if mibBuilder.loadTexts: ipMRouteNextHopIfIndex.setDescription('The ifIndex value of the interface for the outgoing\n interface for this next-hop.') ipMRouteNextHopAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 5), IpAddress()) if mibBuilder.loadTexts: ipMRouteNextHopAddress.setDescription('The address of the next-hop specific to this entry. For\n most interfaces, this is identical to ipMRouteNextHopGroup.\n NBMA interfaces, however, may have multiple next-hop\n addresses out a single outgoing interface.') ipMRouteNextHopState = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("pruned", 1), ("forwarding", 2),))).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopState.setDescription("An indication of whether the outgoing interface and next-\n hop represented by this entry is currently being used to\n forward IP datagrams. The value 'forwarding' indicates it\n is currently being used; the value 'pruned' indicates it is\n not.") ipMRouteNextHopUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 7), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopUpTime.setDescription('The time since the multicast routing information\n represented by this entry was learned by the router.') ipMRouteNextHopExpiryTime = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 8), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopExpiryTime.setDescription('The minimum amount of time remaining before this entry will\n be aged out. If ipMRouteNextHopState is pruned(1), the\n remaining time until the prune expires and the state reverts\n to forwarding(2). Otherwise, the remaining time until this\n entry is removed from the table. The time remaining may be\n copied from ipMRouteExpiryTime if the protocol in use for\n this entry does not specify next-hop timers. The value 0\n\n\n\n\n\n indicates that the entry is not subject to aging.') ipMRouteNextHopClosestMemberHops = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopClosestMemberHops.setDescription('The minimum number of hops between this router and any\n member of this IP multicast group reached via this next-hop\n on this outgoing interface. Any IP multicast datagrams for\n the group which have a TTL less than this number of hops\n will not be forwarded to this next-hop.') ipMRouteNextHopProtocol = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 10), IANAipMRouteProtocol()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopProtocol.setDescription('The routing mechanism via which this next-hop was learned.') ipMRouteNextHopPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 3, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteNextHopPkts.setDescription('The number of packets which have been forwarded using this\n route.') ipMRouteInterfaceTable = MibTable((1, 3, 6, 1, 2, 1, 83, 1, 1, 4), ) if mibBuilder.loadTexts: ipMRouteInterfaceTable.setDescription('The (conceptual) table containing multicast routing\n information specific to interfaces.') ipMRouteInterfaceEntry = MibTableRow((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteInterfaceIfIndex")) if mibBuilder.loadTexts: ipMRouteInterfaceEntry.setDescription('An entry (conceptual row) containing the multicast routing\n information for a particular interface.') ipMRouteInterfaceIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: ipMRouteInterfaceIfIndex.setDescription('The ifIndex value of the interface for which this entry\n contains information.') ipMRouteInterfaceTtl = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipMRouteInterfaceTtl.setDescription('The datagram TTL threshold for the interface. Any IP\n multicast datagrams with a TTL less than this threshold will\n not be forwarded out the interface. The default value of 0\n means all multicast packets are forwarded out the\n interface.') ipMRouteInterfaceProtocol = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 3), IANAipMRouteProtocol()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInterfaceProtocol.setDescription('The routing protocol running on this interface.') ipMRouteInterfaceRateLimit = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipMRouteInterfaceRateLimit.setDescription('The rate-limit, in kilobits per second, of forwarded\n multicast traffic on the interface. A rate-limit of 0\n indicates that no rate limiting is done.') ipMRouteInterfaceInMcastOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInterfaceInMcastOctets.setDescription('The number of octets of multicast packets that have arrived\n on the interface, including framing characters. This object\n is similar to ifInOctets in the Interfaces MIB, except that\n only multicast packets are counted.') ipMRouteInterfaceOutMcastOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInterfaceOutMcastOctets.setDescription('The number of octets of multicast packets that have been\n sent on the interface.') ipMRouteInterfaceHCInMcastOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 7), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInterfaceHCInMcastOctets.setDescription('The number of octets of multicast packets that have arrived\n on the interface, including framing characters. This object\n is a 64-bit version of ipMRouteInterfaceInMcastOctets. It\n is similar to ifHCInOctets in the Interfaces MIB, except\n that only multicast packets are counted.') ipMRouteInterfaceHCOutMcastOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 4, 1, 8), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipMRouteInterfaceHCOutMcastOctets.setDescription('The number of octets of multicast packets that have been\n\n\n\n\n\n sent on the interface. This object is a 64-bit version of\n ipMRouteInterfaceOutMcastOctets.') ipMRouteBoundaryTable = MibTable((1, 3, 6, 1, 2, 1, 83, 1, 1, 5), ) if mibBuilder.loadTexts: ipMRouteBoundaryTable.setDescription("The (conceptual) table listing the router's scoped\n multicast address boundaries.") ipMRouteBoundaryEntry = MibTableRow((1, 3, 6, 1, 2, 1, 83, 1, 1, 5, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteBoundaryIfIndex"), (0, "IPMROUTE-STD-MIB", "ipMRouteBoundaryAddress"), (0, "IPMROUTE-STD-MIB", "ipMRouteBoundaryAddressMask")) if mibBuilder.loadTexts: ipMRouteBoundaryEntry.setDescription('An entry (conceptual row) in the ipMRouteBoundaryTable\n representing a scoped boundary.') ipMRouteBoundaryIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 5, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: ipMRouteBoundaryIfIndex.setDescription('The IfIndex value for the interface to which this boundary\n applies. Packets with a destination address in the\n associated address/mask range will not be forwarded out this\n interface.') ipMRouteBoundaryAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 5, 1, 2), IpAddress()) if mibBuilder.loadTexts: ipMRouteBoundaryAddress.setDescription('The group address which when combined with the\n corresponding value of ipMRouteBoundaryAddressMask\n identifies the group range for which the scoped boundary\n exists. Scoped addresses must come from the range 239.x.x.x\n as specified in RFC 2365.') ipMRouteBoundaryAddressMask = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 5, 1, 3), IpAddress()) if mibBuilder.loadTexts: ipMRouteBoundaryAddressMask.setDescription('The group address mask which when combined with the\n corresponding value of ipMRouteBoundaryAddress identifies\n the group range for which the scoped boundary exists.') ipMRouteBoundaryStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 5, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ipMRouteBoundaryStatus.setDescription('The status of this row, by which new entries may be\n created, or old entries deleted from this table.') ipMRouteScopeNameTable = MibTable((1, 3, 6, 1, 2, 1, 83, 1, 1, 6), ) if mibBuilder.loadTexts: ipMRouteScopeNameTable.setDescription('The (conceptual) table listing the multicast scope names.') ipMRouteScopeNameEntry = MibTableRow((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1), ).setIndexNames((0, "IPMROUTE-STD-MIB", "ipMRouteScopeNameAddress"), (0, "IPMROUTE-STD-MIB", "ipMRouteScopeNameAddressMask"), (1, "IPMROUTE-STD-MIB", "ipMRouteScopeNameLanguage")) if mibBuilder.loadTexts: ipMRouteScopeNameEntry.setDescription('An entry (conceptual row) in the ipMRouteScopeNameTable\n representing a multicast scope name.') ipMRouteScopeNameAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 1), IpAddress()) if mibBuilder.loadTexts: ipMRouteScopeNameAddress.setDescription('The group address which when combined with the\n corresponding value of ipMRouteScopeNameAddressMask\n identifies the group range associated with the multicast\n scope. Scoped addresses must come from the range\n 239.x.x.x.') ipMRouteScopeNameAddressMask = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 2), IpAddress()) if mibBuilder.loadTexts: ipMRouteScopeNameAddressMask.setDescription('The group address mask which when combined with the\n corresponding value of ipMRouteScopeNameAddress identifies\n the group range associated with the multicast scope.') ipMRouteScopeNameLanguage = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 3), LanguageTag()) if mibBuilder.loadTexts: ipMRouteScopeNameLanguage.setDescription('The RFC 1766-style language tag associated with the scope\n name.') ipMRouteScopeNameString = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ipMRouteScopeNameString.setDescription('The textual name associated with the multicast scope. The\n value of this object should be suitable for displaying to\n end-users, such as when allocating a multicast address in\n this scope. When no name is specified, the default value of\n this object should be the string 239.x.x.x/y with x and y\n replaced appropriately to describe the address and mask\n length associated with the scope.') ipMRouteScopeNameDefault = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 5), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: ipMRouteScopeNameDefault.setDescription('If true, indicates a preference that the name in the\n following language should be used by applications if no name\n is available in a desired language.') ipMRouteScopeNameStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 83, 1, 1, 6, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: ipMRouteScopeNameStatus.setDescription('The status of this row, by which new entries may be\n created, or old entries deleted from this table.') ipMRouteMIBConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 83, 2)) ipMRouteMIBCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 83, 2, 1)) ipMRouteMIBGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 83, 2, 2)) ipMRouteMIBCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 83, 2, 1, 1)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteMIBBasicGroup"), ("IPMROUTE-STD-MIB", "ipMRouteMIBRouteGroup"), ("IPMROUTE-STD-MIB", "ipMRouteMIBBoundaryGroup"), ("IPMROUTE-STD-MIB", "ipMRouteMIBHCInterfaceGroup"),)) if mibBuilder.loadTexts: ipMRouteMIBCompliance.setDescription('The compliance statement for the IP Multicast MIB.') ipMRouteMIBBasicGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 1)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteEnable"), ("IPMROUTE-STD-MIB", "ipMRouteEntryCount"), ("IPMROUTE-STD-MIB", "ipMRouteUpstreamNeighbor"), ("IPMROUTE-STD-MIB", "ipMRouteInIfIndex"), ("IPMROUTE-STD-MIB", "ipMRouteUpTime"), ("IPMROUTE-STD-MIB", "ipMRouteExpiryTime"), ("IPMROUTE-STD-MIB", "ipMRouteNextHopState"), ("IPMROUTE-STD-MIB", "ipMRouteNextHopUpTime"), ("IPMROUTE-STD-MIB", "ipMRouteNextHopExpiryTime"), ("IPMROUTE-STD-MIB", "ipMRouteNextHopProtocol"), ("IPMROUTE-STD-MIB", "ipMRouteNextHopPkts"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceTtl"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceProtocol"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceRateLimit"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceInMcastOctets"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceOutMcastOctets"), ("IPMROUTE-STD-MIB", "ipMRouteProtocol"),)) if mibBuilder.loadTexts: ipMRouteMIBBasicGroup.setDescription('A collection of objects to support basic management of IP\n Multicast routing.') ipMRouteMIBHopCountGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 2)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteNextHopClosestMemberHops"),)) if mibBuilder.loadTexts: ipMRouteMIBHopCountGroup.setDescription('A collection of objects to support management of the use of\n hop counts in IP Multicast routing.') ipMRouteMIBBoundaryGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 3)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteBoundaryStatus"), ("IPMROUTE-STD-MIB", "ipMRouteScopeNameString"), ("IPMROUTE-STD-MIB", "ipMRouteScopeNameDefault"), ("IPMROUTE-STD-MIB", "ipMRouteScopeNameStatus"),)) if mibBuilder.loadTexts: ipMRouteMIBBoundaryGroup.setDescription('A collection of objects to support management of scoped\n multicast address boundaries.') ipMRouteMIBPktsOutGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 4)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteNextHopPkts"),)) if mibBuilder.loadTexts: ipMRouteMIBPktsOutGroup.setDescription('A collection of objects to support management of packet\n counters for each outgoing interface entry of a route.') ipMRouteMIBHCInterfaceGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 5)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteInterfaceHCInMcastOctets"), ("IPMROUTE-STD-MIB", "ipMRouteInterfaceHCOutMcastOctets"), ("IPMROUTE-STD-MIB", "ipMRouteHCOctets"),)) if mibBuilder.loadTexts: ipMRouteMIBHCInterfaceGroup.setDescription('A collection of objects providing information specific to\n high speed (greater than 20,000,000 bits/second) network\n interfaces.') ipMRouteMIBRouteGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 6)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRouteRtProto"), ("IPMROUTE-STD-MIB", "ipMRouteRtAddress"), ("IPMROUTE-STD-MIB", "ipMRouteRtMask"), ("IPMROUTE-STD-MIB", "ipMRouteRtType"),)) if mibBuilder.loadTexts: ipMRouteMIBRouteGroup.setDescription('A collection of objects providing information on the\n relationship between multicast routing information, and the\n IP Forwarding Table.') ipMRouteMIBPktsGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 83, 2, 2, 7)).setObjects(*(("IPMROUTE-STD-MIB", "ipMRoutePkts"), ("IPMROUTE-STD-MIB", "ipMRouteDifferentInIfPackets"), ("IPMROUTE-STD-MIB", "ipMRouteOctets"),)) if mibBuilder.loadTexts: ipMRouteMIBPktsGroup.setDescription('A collection of objects to support management of packet\n counters for each forwarding entry.') mibBuilder.exportSymbols("IPMROUTE-STD-MIB", ipMRouteMIBConformance=ipMRouteMIBConformance, ipMRouteMIBPktsGroup=ipMRouteMIBPktsGroup, ipMRouteEntryCount=ipMRouteEntryCount, LanguageTag=LanguageTag, ipMRouteHCOctets=ipMRouteHCOctets, ipMRouteNextHopUpTime=ipMRouteNextHopUpTime, ipMRouteScopeNameTable=ipMRouteScopeNameTable, ipMRouteMIBBasicGroup=ipMRouteMIBBasicGroup, ipMRoutePkts=ipMRoutePkts, ipMRouteNextHopSource=ipMRouteNextHopSource, ipMRouteInterfaceRateLimit=ipMRouteInterfaceRateLimit, ipMRouteScopeNameDefault=ipMRouteScopeNameDefault, ipMRouteNextHopClosestMemberHops=ipMRouteNextHopClosestMemberHops, ipMRouteScopeNameAddress=ipMRouteScopeNameAddress, ipMRouteRtProto=ipMRouteRtProto, ipMRouteNextHopProtocol=ipMRouteNextHopProtocol, ipMRouteTable=ipMRouteTable, ipMRouteNextHopExpiryTime=ipMRouteNextHopExpiryTime, ipMRouteRtType=ipMRouteRtType, ipMRouteScopeNameEntry=ipMRouteScopeNameEntry, ipMRouteRtAddress=ipMRouteRtAddress, ipMRouteScopeNameString=ipMRouteScopeNameString, ipMRouteInterfaceProtocol=ipMRouteInterfaceProtocol, ipMRouteMIBCompliances=ipMRouteMIBCompliances, ipMRouteBoundaryTable=ipMRouteBoundaryTable, ipMRouteScopeNameStatus=ipMRouteScopeNameStatus, ipMRouteGroup=ipMRouteGroup, ipMRouteNextHopTable=ipMRouteNextHopTable, ipMRouteSource=ipMRouteSource, ipMRouteMIBHopCountGroup=ipMRouteMIBHopCountGroup, ipMRouteEntry=ipMRouteEntry, PYSNMP_MODULE_ID=ipMRouteStdMIB, ipMRouteExpiryTime=ipMRouteExpiryTime, ipMRouteBoundaryAddress=ipMRouteBoundaryAddress, ipMRouteMIBPktsOutGroup=ipMRouteMIBPktsOutGroup, ipMRouteSourceMask=ipMRouteSourceMask, ipMRouteNextHopSourceMask=ipMRouteNextHopSourceMask, ipMRouteInIfIndex=ipMRouteInIfIndex, ipMRouteScopeNameLanguage=ipMRouteScopeNameLanguage, ipMRouteOctets=ipMRouteOctets, ipMRouteNextHopPkts=ipMRouteNextHopPkts, ipMRouteNextHopAddress=ipMRouteNextHopAddress, ipMRouteNextHopState=ipMRouteNextHopState, ipMRouteMIBRouteGroup=ipMRouteMIBRouteGroup, ipMRouteBoundaryAddressMask=ipMRouteBoundaryAddressMask, ipMRouteRtMask=ipMRouteRtMask, ipMRouteInterfaceInMcastOctets=ipMRouteInterfaceInMcastOctets, ipMRouteBoundaryIfIndex=ipMRouteBoundaryIfIndex, ipMRouteProtocol=ipMRouteProtocol, ipMRouteNextHopIfIndex=ipMRouteNextHopIfIndex, ipMRouteMIBHCInterfaceGroup=ipMRouteMIBHCInterfaceGroup, ipMRouteDifferentInIfPackets=ipMRouteDifferentInIfPackets, ipMRouteInterfaceHCInMcastOctets=ipMRouteInterfaceHCInMcastOctets, ipMRouteNextHopEntry=ipMRouteNextHopEntry, ipMRouteInterfaceHCOutMcastOctets=ipMRouteInterfaceHCOutMcastOctets, ipMRouteBoundaryStatus=ipMRouteBoundaryStatus, ipMRouteEnable=ipMRouteEnable, ipMRouteMIBCompliance=ipMRouteMIBCompliance, ipMRouteInterfaceOutMcastOctets=ipMRouteInterfaceOutMcastOctets, ipMRouteNextHopGroup=ipMRouteNextHopGroup, ipMRouteInterfaceIfIndex=ipMRouteInterfaceIfIndex, ipMRouteInterfaceEntry=ipMRouteInterfaceEntry, ipMRouteStdMIB=ipMRouteStdMIB, ipMRouteInterfaceTable=ipMRouteInterfaceTable, ipMRouteUpstreamNeighbor=ipMRouteUpstreamNeighbor, ipMRouteUpTime=ipMRouteUpTime, ipMRouteScopeNameAddressMask=ipMRouteScopeNameAddressMask, ipMRoute=ipMRoute, ipMRouteInterfaceTtl=ipMRouteInterfaceTtl, ipMRouteMIBBoundaryGroup=ipMRouteMIBBoundaryGroup, ipMRouteMIBObjects=ipMRouteMIBObjects, ipMRouteBoundaryEntry=ipMRouteBoundaryEntry, ipMRouteMIBGroups=ipMRouteMIBGroups)
class Solution: def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ words = str.split(' ') if len(pattern) != len(words) or len(set(pattern)) != len(set(words)): return False d = dict() for index, value in enumerate(pattern): if value not in d: d[value] = words[index] else: if d[value] != words[index]: return False return True
# Problem 4: Dutch National Flag Problem def sort_zero_one_two(input_list): # We define 4 variables for the low, middle, high, and temporary values lo_end = 0 hi_end = len(input_list) - 1 mid = 0 tmp = None if len(input_list) <= 0 or input_list[mid] < 0: return "The list is either empty or invalid." while (mid <= hi_end): if input_list[mid] == 0: tmp = input_list[lo_end] input_list[lo_end] = input_list[mid] input_list[mid] = tmp lo_end += 1 mid += 1 elif input_list[mid] == 1: mid += 1 else: tmp = input_list[mid] input_list[mid] = input_list[hi_end] input_list[hi_end] = tmp hi_end -= 1 return input_list # Run some tests def test_function(test_case): sorted_array = sort_zero_one_two(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([1, 0, 2, 0, 1, 0, 2, 1, 0, 2, 2]) test_function([]) test_function([-1])
# -*- coding: utf-8 -*- """ equip.visitors.blocks ~~~~~~~~~~~~~~~~~~~~~ Callback the visit basic blocks in the program. :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ class BlockVisitor(object): """ A basic block visitor. It first receives the control-flow graph, and then the ``visit`` method is called with all basic blocks in the CFG. The blocks are not passed to the ``visit`` method with a particular order. """ def __init__(self): self._control_flow = None @property def control_flow(self): return self._control_flow @control_flow.setter def control_flow(self, value): self._control_flow = value def new_control_flow(self): pass def visit(self, block): pass
# coding=utf-8 BTC_BASED_COINS = { 'PIVX': { 'ip': '', 'port': 3000, 'url': '' } } ETHEREUM_BASED_COINS = ['ETH', 'BNB', 'SENT'] ADDRESS = ''.lower() PRIVATE_KEY = '' FEE_PERCENTAGE = 0.01 TOKENS = [ { 'address': ADDRESS, 'decimals': 18, 'logo_url': 'https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png', 'name': 'Ethereum', 'price_url': 'https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=SENT', 'symbol': 'ETH', 'coin_type': 'erc20' }, { 'address': '0xb8c77482e45f1f44de1745f52c74426c631bdd52', 'decimals': 18, 'logo_url': 'https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png', 'name': 'Binance Coin', 'price_url': 'https://api.coinmarketcap.com/v1/ticker/binance-coin/?convert=SENT', 'symbol': 'BNB', 'coin_type': 'erc20' }, { 'address': None, 'decimals': 0, 'logo_url': 'https://s2.coinmarketcap.com/static/img/coins/64x64/1169.png', 'name': 'PIVX', 'price_url': 'https://api.coinmarketcap.com/v1/ticker/pivx/?convert=SENT', 'symbol': 'PIVX', 'coin_type': 'btc_fork' }, { 'address': '0xa44e5137293e855b1b7bc7e2c6f8cd796ffcb037', 'decimals': 8, 'logo_url': 'https://s2.coinmarketcap.com/static/img/coins/64x64/2643.png', 'name': 'SENTinel', 'price_url': 'https://api.coinmarketcap.com/v1/ticker/sentinel/?convert=SENT', 'symbol': 'SENT', 'coin_type': 'erc20' } ]
def get_poisoned_worker_ids_from_log(log_path): # Unchanged from original work """ :param log_path: string """ with open(log_path, "r") as f: file_lines = [line.strip() for line in f.readlines() if "Poisoning data for workers:" in line] workers = file_lines[0].split("[")[1].split("]")[0] workers_list = workers.split(", ") return [int(worker) for worker in workers_list] def get_worker_num_from_model_file_name(model_file_name): # Unchanged from original work """ :param model_file_name: string """ return int(model_file_name.split("_")[1]) def get_epoch_num_from_model_file_name(model_file_name): # Unchanged from original work """ :param model_file_name: string """ return int(model_file_name.split("_")[2].split(".")[0]) def get_suffix_from_model_file_name(model_file_name): # Unchanged from original work """ :param model_file_name: string """ return model_file_name.split("_")[3].split(".")[0] def get_model_files_for_worker(model_files, worker_id): # Unchanged from original work """ :param model_files: list[string] :param worker_id: int """ worker_model_files = [] for model in model_files: worker_num = get_worker_num_from_model_file_name(model) if worker_num == worker_id: worker_model_files.append(model) return worker_model_files def get_model_files_for_epoch(model_files, epoch_num): # Unchanged from original work """ :param model_files: list[string] :param epoch_num: int """ epoch_model_files = [] for model in model_files: model_epoch_num = get_epoch_num_from_model_file_name(model) if model_epoch_num == epoch_num: epoch_model_files.append(model) return epoch_model_files def get_model_files_for_suffix(model_files, suffix): """ :param model_files: list[string] :param suffix: string """ suffix_only_model_files = [] for model in model_files: model_suffix = get_suffix_from_model_file_name(model) if model_suffix == suffix: suffix_only_model_files.append(model) return suffix_only_model_files
# It must be here to retrieve this information from the dummy core_universal_identifier = 'd9d94986-ea14-11e0-bd1d-00216a5807c8' core_universal_identifier_human = 'Consumer' db_database = "WebLabTests" weblab_db_username = 'weblab' weblab_db_password = 'weblab' debug_mode = True ######################### # General configuration # ######################### server_hostaddress = 'weblab.deusto.es' server_admin = 'weblab@deusto.es' ################################ # Admin Notifier configuration # ################################ mail_notification_enabled = False ########################## # Sessions configuration # ########################## session_mysql_username = 'weblab' session_mysql_password = 'weblab' session_locker_mysql_username = session_mysql_username session_locker_mysql_password = session_mysql_password
__author__ = "Shaban Hassan [shaban00]" """ Regiser all routes for flask socket io """ # SOCKET_EVENTS = [ # { # "event": "connect", # "func": "connect", # "namespace": "namespace" # } # ] SOCKET_EVENTS = []
if __name__ == '__main__': n, m = list(map(int, input().split(" "))) arr = list(map(int, input().split(" "))) set_a = set(map(int, input().split(" "))) set_b = set(map(int, input().split(' '))) print(sum([1 if e in set_a else -1 if e in set_b else 0 for e in arr]))
""" You are given an m x n 2D image matrix (List of Lists) where each integer represents a pixel. Flip it in-place along its horizontal axis. Example: Input image : 1 1 0 0 Modified to : 0 0 1 1 """ def flip_horizontal_axis(matrix): """ Returns a list of lists in reverse order. :param matrix: list of lists :return: list of lists reversed """ matrix.reverse()
# Given a binary tree, find a minimum path sum from root to a leaf. # For example, the minimum path in this tree is [10, 5, 1, -1], which has sum 15. # 10 # / \ # 5 5 # \ \ # 2 1 # / # -1 class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def min_path(node): path_values = [] def search_path(node, path=0): path += node.value if node.left is None and node.right is None: path_values.append(path) return if node.left: search_path(node.left, path) if node.right: search_path(node.right, path) search_path(node) return min(path_values) if __name__ == "__main__": tree = Node(10, Node(5, right=Node(2)), Node(5, right=Node(1, Node(-1)))) print(min_path(tree))
expected_output = { "interface": { "GigabitEthernet3.90": { "interface": "GigabitEthernet3.90", "neighbors": { "FE80::5C00:40FF:FEFF:209": { "age": "22", "ip": "FE80::5C00:40FF:FEFF:209", "link_layer_address": "5e00.40ff.0209", "neighbor_state": "STALE", } }, } } }
class Solution: def rob(self, nums: List[int]) -> int: dp = [num for num in nums] for i in range(2, len(nums)): dp[i] += max(dp[:i-1]) return max(dp)
print("Statements") print("Statement does something, while expression is something") 2*2 # this is an expression, it will not do anything if not using interactive interpreter. print(2*2) #this is an statement, it does print x=3 #this is also an statement, it has no values to print out, but x is already assigned.
# This problem was recently asked by Google: # Given a sorted list, create a height balanced binary search tree, # meaning the height differences of each node can only differ by at most 1. class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def __str__(self): answer = str(self.value) if self.left: answer += str(self.left) if self.right: answer += str(self.right) return answer def create_height_balanced_bst(nums): # Fill this in. if not nums: return None mid = int((len(nums)) / 2) root = Node(nums[mid]) root.left = create_height_balanced_bst(nums[:mid]) root.right = create_height_balanced_bst(nums[mid + 1 :]) return root tree = create_height_balanced_bst([1, 2, 3, 4, 5, 6, 7, 8]) print(tree) # 53214768 # (pre-order traversal) # 5 # / \ # 3 7 # / \ / \ # 2 4 6 8 # / # 1
# Copyright 2021 PaddleFSL Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['count_model_params'] def count_model_params(model): """ Calculate the number of parameters of the model. Args: model(paddle.nn.Layer): model to be counted. Returns: None. """ print(model) param_size = {} cnt = 0 for name, p in model.named_parameters(): k = name.split('.')[0] if k not in param_size: param_size[k] = 0 p_cnt = 1 # for j in p.size(): for j in p.shape: p_cnt *= j param_size[k] += p_cnt cnt += p_cnt for k, v in param_size.items(): print(f"Number of parameters for {k} = {round(v / 1024, 2)} k") print(f"Total parameters of model = {round(cnt / 1024, 2)} k")
#--------------------------------------------------------------------------------------------------- # Tiparoj #--------------------------------------------------------------------------------------------------- c.fonts.completion.category = "bold 8pt monospace" c.fonts.completion.entry = "8pt monospace" c.fonts.debug_console = "8pt monospace" c.fonts.downloads = "8pt monospace" c.fonts.hints = "bold 8pt monospace" c.fonts.keyhint = "8pt monospace" c.fonts.messages.error = "8pt monospace" c.fonts.messages.info = "8pt monospace" c.fonts.messages.warning = "8pt monospace" c.fonts.prompts = "8pt sans-serif" c.fonts.statusbar = "8pt monospace" c.fonts.tabs.selected = "8pt sans-serif" c.fonts.tabs.unselected = "8pt sans-serif" c.fonts.default_family = "Monospace, DejaVu Sans Mono"
class Account: """An account has a balance and a holder. >>> a = Account('John') >>> a.holder 'John' >>> a.deposit(100) 100 >>> a.withdraw(90) 10 >>> a.withdraw(90) 'Insufficient funds' >>> a.balance 10 >>> a.interest 0.02 """ interest = 0.02 # A class attribute def __init__(self, account_holder): self.holder = account_holder self.balance = 0 def deposit(self, amount): """Add amount to balance.""" self.balance = self.balance + amount return self.balance def withdraw(self, amount): """Subtract amount from balance if funds are available.""" if amount > self.balance: return 'Insufficient funds' self.balance = self.balance - amount return self.balance class CheckingAccount(Account): """A bank account that charges for withdrawals. >>> ch = CheckingAccount('Jack') >>> ch.balance = 20 >>> ch.withdraw(5) 14 >>> ch.interest 0.01 """ withdraw_fee = 1 interest = 0.01 def withdraw(self, amount): return Account.withdraw(self, amount + self.withdraw_fee) # Alternatively: return super().withdraw(amount + self.withdraw_fee) class Bank: """A bank has accounts and pays interest. >>> bank = Bank() >>> john = bank.open_account('John', 10) >>> jack = bank.open_account('Jack', 5, CheckingAccount) >>> jack.interest 0.01 >>> john.interest = 0.06 >>> bank.pay_interest() >>> john.balance 10.6 >>> jack.balance 5.05 """ def __init__(self): self.accounts = [] def open_account(self, holder, amount, account_type=Account): """Open an account_type for holder and deposit amount.""" account = account_type(holder) account.deposit(amount) self.accounts.append(account) return account def pay_interest(self): """Pay interest to all accounts.""" for account in self.accounts: account.deposit(account.balance * account.interest) # Inheritance Example class A: z = -1 def f(self, x): return B(x-1) class B(A): n = 4 def __init__(self, y): if y: self.z = self.f(y) else: self.z = C(y+1) class C(B): def f(self, x): return x def WWPD(): """What would Python Display? >>> a = A() >>> b = B(1) >>> b.n = 5 >>> C(2).n 4 >>> C(2).z 2 >>> a.z == C.z True >>> a.z == b.z False >>> b.z.z.z 1 """ # Multiple Inheritance class SavingsAccount(Account): """A bank account that charges for deposits.""" deposit_fee = 2 def deposit(self, amount): return Account.deposit(self, amount - self.deposit_fee) class AsSeenOnTVAccount(CheckingAccount, SavingsAccount): """A bank account that charges for everything.""" def __init__(self, account_holder): self.holder = account_holder self.balance = 1 # A free dollar! supers = [c.__name__ for c in AsSeenOnTVAccount.mro()]
_base_ = 'ranksort_cascade_rcnn_r50_fpn_1x_coco.py' model = dict(roi_head=dict(stage_loss_weights=[1, 0.50, 0.25]))
{ "targets": [ { "target_name": "pcap_binding", 'win_delay_load_hook': 'true', "sources": [ "npcap_binding.cpp","npcap_session.cpp"], "include_dirs": ["npcap/Include","<!@(node -p \"require('node-addon-api').include\")"], "libraries": [ "<(module_root_dir)/npcap/Lib/x64/Packet.lib", "<(module_root_dir)/npcap/Lib/x64/wpcap.lib", "Ws2_32.lib" ], 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS','NAPI_EXPERIMENTAL'], 'target_conditions': [ ['_win_delay_load_hook=="true"', { # If the addon specifies `'win_delay_load_hook': 'true'` in its # binding.gyp, link a delay-load hook into the DLL. This hook ensures # that the addon will work regardless of whether the node/iojs binary # is named node.exe, iojs.exe, or something else. 'conditions': [ [ 'OS=="win"', { 'defines': [ 'HOST_BINARY=\"<(node_host_binary)<(EXECUTABLE_SUFFIX)\"', ], 'sources': [ '<(node_gyp_dir)/src/win_delay_load_hook.cc', ], 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ '<(node_host_binary)<(EXECUTABLE_SUFFIX)','wpcap.dll' ], # Don't print a linker warning when no imports from either .exe # are used. 'AdditionalOptions': [ '/ignore:4199' ], }, }, }], ], }], ], } ] }
class Config(object): # game setting row_size = 6 column_size = 6 piece_in_line = 4 black_first = True max_num_round = 36 # mcts temperature = 1.0 playout_times = 100 # num of simulations for each move c_puct = 5. # data num_games_per_generation = 10 batch_size = 32 # mini-batch size for training buffer_size = 10000 data_buffer_size = 10000 # train epoch_per_dataset = 5 # num of train_steps for each update max_epochs = 1000 # learning_rate = 1e-3 # lr_multiplier = 1.0 # adaptively adjust the learning rate based on KL # saved model saved_dir = 'saved' def __init__(self, **kwargs): for k, v in kwargs: self.__setattr__(k, v)
class TooLarge(Exception): """The input was too long.""" def __init__(self): super(TooLarge, self).__init__("That number was too large.") class ImproperFormat(Exception): """Invalid Format was given.""" def __init__(self): super(ImproperFormat, self).__init__("An Invalid Format was given.") class NoTimeZone(Exception): """No Timezone was found.""" def __init__(self): super(NoTimeZone, self).__init__("The user did not have a timezone.")
""" Description Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings. Please implement encode and decode Example Example1 Input: ["lint","code","love","you"] Output: ["lint","code","love","you"] Explanation: One possible encode method is: "lint:;code:;love:;you" Example2 Input: ["we", "say", ":", "yes"] Output: ["we", "say", ":", "yes"] Explanation: One possible encode method is: "we:;say:;:::;yes" """ class Solution: def encode(self, strs): res = "" for s in strs: # encode the strings to one string by adding the length of the string and # before the string res += str(len(s)) + '#' + s return res def decode(self, str): # set i to be initially 0 res, i = [], 0 # while i is less than the length of the str while i < len(str): # we set j to be the current value of i j = i # while the char at j is not # while str[j] != '#': j += 1 # get lenth on the string length = int(str[i:j]) # we start at j+1 since we know the next character from # is where our string starts # we end at j+length+1 since we now have the total length of the string, we add 1 since we start at j+1 res.append(str[j+1: j+length+1]) # we reset i to be the start of the next word i = j+length+1 return res soln = Solution() print(soln.encode(['my', 'dad', 'is', 'coming'])) # output - 2#my3#dad2#is6#coming print(soln.decode('2#my3#dad2#is6#coming'))
# Demonstrate how to use dictionary comprehensions def main(): # define a list of temperature values ctemps = [0, 12, 34, 100] # Use a comprehension to build a dictionary tempDict = {t: (t * 9/5) + 32 for t in ctemps if t < 100} print(tempDict) print(tempDict[12]) # Merge two dictionaries with a comprehension team1 = {"Jones": 24, "Jameson": 18, "Smith": 58, "Burns": 7} team2 = {"White": 12, "Macke": 88, "Perce": 4} newTeam = {k: v for team in (team1, team2) for k, v in team.items()} print(newTeam) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """Collection of exceptions raised by requests-toolbelt.""" class StreamingError(Exception): """Used in :mod:`requests_toolbelt.downloadutils.stream`.""" pass class VersionMismatchError(Exception): """Used to indicate a version mismatch in the version of requests required. The feature in use requires a newer version of Requests to function appropriately but the version installed is not sufficient. """ pass class RequestsVersionTooOld(Warning): """Used to indicate that the Requests version is too old. If the version of Requests is too old to support a feature, we will issue this warning to the user. """ pass class IgnoringGAECertificateValidation(Warning): """Used to indicate that given GAE validation behavior will be ignored. If the user has tried to specify certificate validation when using the insecure AppEngine adapter, it will be ignored (certificate validation will remain off), so we will issue this warning to the user. In :class:`requests_toolbelt.adapters.appengine.InsecureAppEngineAdapter`. """ pass
class NaturalNumbers: def __init__(self): pass def get_first_n_for(self, n): # Ejemplo """ Obtener los primeros n naturales en una lista con for """ first_n = [] # Se declara una lista donde almacenaremos los numeros for i in range(n): # Se itera sobre range que genera un rango de 0 a n first_n.append(i) # Almacenamos la variable del ciclo en la lista con append print("FIRST n (n={}) FOR: {}".format(n, first_n)) return first_n # Regresamos la lista def get_first_n_while(self, n): # Ejemplo """ Obtener los primeros n naturales en una lista con while """ first_n = [] # Se declara una lista donde almacenaremos los numeros n_count = 0 # Inicializamos un contador para saber en que iteracion vamos dentro del ciclo while n_count < n: # Condición de terminación del ciclo first_n.append(n_count) # ALmacenamos el contador (contablizador del ciclo) en la lista n_count += 1 # Sumamos uno al contador puesto que termina ek ciclo, si no nunca n_count será mayor o igual que n y tendremos un loop infinito print(f"FIRST n (n={n}) WHILE: {first_n}") return first_n def get_first_n_pair_for(self, n): # Ejercicio """ Obtener los primeros n pares en una lista con for """ return [] def get_first_n_pair_while(self, n): # Ejercicio """ Obtener los primeros n pares en una lista con while """ return [] def get_factorial_for(self, n): # Ejercicio """ Obtener el factorial de n con for, regresa un int """ return 0 def get_factorial_while(self, n): # Ejercicio """ Obtener el factorial de n con while, regresa un int """ return 0 def get_factorial_recursive(self, n): #Ejemplo """ Obtener el factorial de n recursivamente, regresa un int """ if n <= 1: return 1 return n * self.get_factorial_recursive(n-1) def get_n_pow_2_for(self, n): # Ejemplo """ Obtener el cuadrado de los primeros n con for, regresa una lista """ n_pow_2 = [] for i in range(n): n_pow_2.append( i ** 2 ) print(f"FIRST n (n={n}) POW 2: {n_pow_2}") return n_pow_2 def get_n_pow_2_while(self, n): # Ejercicio """ Obtener el cuadrado de los primeros n con while, regresa una lista """ return [] def get_n_sum_recursive(self, n): #Ejemplo """ Obtener la suma de los primeros n recursivamente, regresa un int """ if n <= 0: return 0 return n + self.get_n_sum_recursive(n-1) def get_n_sum_for(self, n): # Ejercicio """ Obtener la suma de los primeros n con for, regresa un int """ return 0 def get_n_sum_while(self, n): # Ejercicio """ Obtener la suma de los primeros n con while, regresa un int """ return 0
class Config(): def __init__(self): self.type = "a2c" self.gamma = 0.99 self.learning_rate = 0.001 self.entropy_beta = 0.01 self.batch_size = 128
width = const(7) height = const(12) data = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x10\x10\x10\x10\x00\x00\x10\x00\x00\x00\x00lHH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x14(|(|(PP\x00\x00\x00\x108@@8Hp\x10\x10\x00\x00\x00 P \x0cp\x08\x14\x08\x00\x00\x00\x00\x00\x00\x18 TH4\x00\x00\x00\x00\x10\x10\x10\x10\x00\x00\x00\x00\x00\x00\x00\x00\x08\x08\x10\x10\x10\x10\x10\x10\x08\x08\x00\x00 \x10\x10\x10\x10\x10\x10 \x00\x00\x10|\x10((\x00\x00\x00\x00\x00\x00\x00\x00\x10\x10\x10\xfe\x10\x10\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x18\x100 \x00\x00\x00\x00\x00\x00|\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0000\x00\x00\x00\x00\x04\x04\x08\x08\x10\x10 @\x00\x00\x008DDDDDD8\x00\x00\x00\x000\x10\x10\x10\x10\x10\x10|\x00\x00\x00\x008D\x04\x08\x10 D|\x00\x00\x00\x008D\x04\x18\x04\x04D8\x00\x00\x00\x00\x0c\x14\x14$D~\x04\x0e\x00\x00\x00\x00< 8\x04\x04D8\x00\x00\x00\x00\x1c @xDDD8\x00\x00\x00\x00|D\x04\x08\x08\x08\x10\x10\x00\x00\x00\x008DD8DDD8\x00\x00\x00\x008DDD<\x04\x08p\x00\x00\x00\x00\x00\x0000\x00\x0000\x00\x00\x00\x00\x00\x00\x18\x18\x00\x00\x180 \x00\x00\x00\x00\x0c\x10`\x80`\x10\x0c\x00\x00\x00\x00\x00\x00\x00|\x00|\x00\x00\x00\x00\x00\x00\x00\xc0 \x18\x04\x18 \xc0\x00\x00\x00\x00\x00\x18$\x04\x08\x10\x000\x00\x00\x008DDLTTL@D8\x00\x00\x000\x10(((|D\xee\x00\x00\x00\x00\xf8DDxDDD\xf8\x00\x00\x00\x00<D@@@@D8\x00\x00\x00\x00\xf0HDDDDH\xf0\x00\x00\x00\x00\xfcDPpP@D\xfc\x00\x00\x00\x00~"(8( p\x00\x00\x00\x00<D@@NDD8\x00\x00\x00\x00\xeeDD|DDD\xee\x00\x00\x00\x00|\x10\x10\x10\x10\x10\x10|\x00\x00\x00\x00<\x08\x08\x08HHH0\x00\x00\x00\x00\xeeDHPpHD\xe6\x00\x00\x00\x00p $$|\x00\x00\x00\x00\xeellTTDD\xee\x00\x00\x00\x00\xeeddTTTL\xec\x00\x00\x00\x008DDDDDD8\x00\x00\x00\x00x$$$8 p\x00\x00\x00\x008DDDDDD8\x1c\x00\x00\x00\xf8DDDxHD\xe2\x00\x00\x00\x004L@8\x04\x04dX\x00\x00\x00\x00\xfe\x92\x10\x10\x10\x10\x108\x00\x00\x00\x00\xeeDDDDDD8\x00\x00\x00\x00\xeeDD(((\x10\x10\x00\x00\x00\x00\xeeDDTTTT(\x00\x00\x00\x00\xc6D(\x10\x10(D\xc6\x00\x00\x00\x00\xeeD((\x10\x10\x108\x00\x00\x00\x00|D\x08\x10\x10 D|\x00\x00\x00\x008 8\x00\x00@ \x10\x10\x08\x08\x08\x00\x00\x008\x08\x08\x08\x08\x08\x08\x08\x088\x00\x00\x10\x10(D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfe\x00\x10\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x008D<DD>\x00\x00\x00\x00\xc0@XdDDD\xf8\x00\x00\x00\x00\x00\x00<D@@D8\x00\x00\x00\x00\x0c\x044LDDD>\x00\x00\x00\x00\x00\x008D|@@<\x00\x00\x00\x00\x1c | |\x00\x00\x00\x00\x00\x006LDDD<\x048\x00\x00\xc0@XdDDD\xee\x00\x00\x00\x00\x10\x00p\x10\x10\x10\x10|\x00\x00\x00\x00\x10\x00x\x08\x08\x08\x08\x08\x08p\x00\x00\xc0@\\HpPH\xdc\x00\x00\x00\x000\x10\x10\x10\x10\x10\x10|\x00\x00\x00\x00\x00\x00\xe8TTTT\xfe\x00\x00\x00\x00\x00\x00\xd8dDDD\xee\x00\x00\x00\x00\x00\x008DDDD8\x00\x00\x00\x00\x00\x00\xd8dDDDx@\xe0\x00\x00\x00\x006LDDD<\x04\x0e\x00\x00\x00\x00l0 |\x00\x00\x00\x00\x00\x00<D8\x04Dx\x00\x00\x00\x00\x00 | "\x1c\x00\x00\x00\x00\x00\x00\xccDDDL6\x00\x00\x00\x00\x00\x00\xeeDD((\x10\x00\x00\x00\x00\x00\x00\xeeDTTT(\x00\x00\x00\x00\x00\x00\xccH00H\xcc\x00\x00\x00\x00\x00\x00\xeeD$(\x18\x10\x10x\x00\x00\x00\x00|H\x10 D|\x00\x00\x00\x00\x08\x10\x10\x10\x10 \x10\x10\x10\x08\x00\x00\x10\x10\x10\x10\x10\x10\x10\x10\x10\x00\x00\x00 \x10\x10\x10\x10\x08\x10\x10\x10 \x00\x00\x00\x00\x00\x00$X\x00\x00\x00\x00\x00'
# 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 binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: return [] result = [] if root.left or root.right: for path in self.binaryTreePaths(root.left): result.append(str(root.val) + "->" + path) for path in self.binaryTreePaths(root.right): result.append(str(root.val) + "->" + path) return result else: return [str(root.val)]
class Solution(object): def countComponents(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: int """ V = [[] for _ in range(n)] for e in edges: V[e[0]].append(e[1]) V[e[1]].append(e[0]) visited = [False for _ in range(n)] cnt = 0 for v in range(n): if not visited[v]: cnt += 1 self.dfs(V, v, visited) return cnt def dfs(self, V, v, visited): visited[v] = True for nbr in V[v]: if not visited[nbr]: self.dfs(V, nbr, visited)
class Solution: def calculate(self, s: str) -> int: inner, outer, result, opt = 0, 0, 0, '+' for c in s+'+': if c == ' ': continue if c.isdigit(): inner = 10*inner + int(c) continue if opt == '+': result += outer outer = inner elif opt == '-': result += outer outer = -inner elif opt == '*': outer = outer*inner elif opt == '/': outer = int(outer/inner) inner, opt = 0, c return result + outer
client_id="You need to fill this" client_secret="You need to fill this" user_agent="You need to fill this" username="You need to fill this" password="You need to fill this"
def by_independent_sets(independent_sets): """独立集合族Tにより与えられた集合が基拡大集合か否か判定する関数を返す関数 Args: independent_sets: 独立集合族T Returns: 与えられた集合Xが基拡大集合か否か判定する関数 True if |X| ≧ max{|I|: I ∈ T} False otherwise """ return lambda X: len(X) >= max(len(I) for I in independent_sets) def by_bases(bases): """基族Dにより与えられた集合が基拡大集合か否か判定する関数を返す関数 Args: bases: 基族D Returns: 与えられた集合Xが従属か否か判定する関数 True if ∃B ∈ D, B ⊊ X False otherwise """ return lambda X: any(B <= X for B in bases) def by_rank_function(rank_function, ground_set): """階数関数ρにより与えられた集合が基拡大集合か否か判定する関数を返す関数 Args: rank_function: 階数関数ρ ground_set: 台集合E Returns: 与えられた集合Xが従属か否か判定する関数 True if ρ(X) == ρ(E) False otherwise """ return lambda X: rank_function(X) == rank_function(ground_set)
targets = [int(target) for target in input().split()] command = input().split() while "End" not in command: index = int(command[1]) if "Shoot" in command: power = int(command[2]) if 0 <= index < len(targets): targets[index] -= power if targets[index] <= 0: targets.pop(index) elif "Add" in command: value = int(command[2]) if 0 <= index < len(targets): targets.insert(index, value) else: print("Invalid placement!") elif "Strike" in command: radius = int(command[2]) if (index - radius) >= 0 and (index + radius) < len(targets): for _ in range(radius): targets.pop(index+1) targets.pop(index) for _ in range(radius): targets.pop(index-1) else: print("Strike missed!") command = input().split() targets = [str(target) for target in targets] print("|".join(targets))
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def is_user_in_group(user, group): if user in group.users: return True if len(group.groups) == 0: return False else: for sub_group in group.groups: flag = is_user_in_group(user, sub_group) if flag: return True return False #%% Testing official # Testing preparation parent = Group("parent") child = Group("child") sub_child = Group("subchild") sub_child_user = "sub_child_user" sub_child.add_user(sub_child_user) child.add_group(sub_child) parent.add_group(child) # Normal Cases: print('Normal Cases:') print(is_user_in_group(user='parent_user', group=parent)) # False print(is_user_in_group(user='child_user', group=parent)) # False print(is_user_in_group(user='sub_child_user', group=parent), '\n') # True # Edge Cases: print('Edge Cases:') print(is_user_in_group(user='', group=parent)) # False print(is_user_in_group(user='', group=child)) # False
letter="Sai Teja"; for i in letter: print(i);
class Club: total = 140 start_address = 751472 size = 88 max_name_size = 48 max_tla_size = 3 def __init__(self, option_file, idx): self.option_file = option_file self.idx = idx self.set_addresses() self.set_name() self.set_tla() def set_addresses(self): """ Set the following club addresses: - Name - TLA - Name edited """ self.name_address = self.start_address + (self.idx * self.size) self.tla_address = self.start_address + 49 + (self.idx * self.size) self.name_edited_address = ( self.start_address + (self.idx * self.size) + 56 ) def set_name(self): """ Set club name from relevant OF data bytes. """ name_byte_array = self.option_file.data[ self.name_address : self.name_address + (self.max_name_size + 1) ] self.name = name_byte_array.partition(b"\0")[0].decode() def set_tla(self): """ Set club tla from relevant OF data bytes. """ tla_byte_array = self.option_file.data[ self.tla_address : self.tla_address + (self.max_tla_size + 1) ] self.tla = tla_byte_array.partition(b"\0")[0].decode() def update_name(self, name): """ Update club name with the supplied value. """ new_name = name[: self.max_name_size] club_name_bytes = [0] * (self.max_name_size + 1) new_name_bytes = str.encode(new_name) club_name_bytes[: len(new_name_bytes)] = new_name_bytes for i, byte in enumerate(club_name_bytes): self.option_file.data[self.name_address + i] = byte self.set_name_edited() self.name = new_name def update_tla(self, tla): """ Update club TLA with the supplied value. """ new_tla = tla[:3].upper() club_tla_bytes = [0] * (self.max_tla_size + 1) new_tla_bytes = str.encode(new_tla) club_tla_bytes[: len(new_tla_bytes)] = new_tla_bytes for i, byte in enumerate(club_tla_bytes): self.option_file.data[self.tla_address + i] = byte self.set_name_edited() self.tla = new_tla def set_name_edited(self): """ Set club name as being edited. """ self.option_file.data[self.name_edited_address] = 1
def add_one(num): return (-(~num)) print(add_one(3)) print(add_one(99))
#encode.py #ASCII print(ord('A')) print(ord('a')) print(chr(65)) #UTF-8 s = "世界,你好!" bs = s.encode("utf-8") print(bs) print(bs.decode("utf-8")) print(bs.encode("gbk"))
# Global constants that will be used all along the program # Port paths ODRIVE_USB_PORT_PATH = "" REHASTIM_USB_PORT_PATH = "" USB_DRIVE_PORT_PATH = ""
#!/usr/bin/env python3 class Solution: def xorOperation(self, n: int, start: int) -> int: res = start for i in range(1,n): res^=start+2*i return res ## Intuition: # # - As per the requirements of the problem, we don't need to return the array itself. # - So, we can free up any space that would have been otherwise allocated to the array # - And instead work with the elements of the array generated each iteration # without storing them in a temporary location # ## Time Complexity: # # O(n) # - We need to iterate through n elements to get our result # ## Space Complexity: # # O(1) # - Memory assigned does not depends upon the size of the list/array n, rather the value of the res variable
"""Faça um programa que leia um número Inteiro qualquer e mostre na tela a sua tabuada.""" n = int(input('Digite um número inteiro para ver sua tabuada: ')) #print(' {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {} \n {}'.format(n * 1, n * 2, n * 3, n * 4, n * 5, n * 6, n * 7, n * 8, n * 9, n * 10)) print('-'*12) print(f'{n} x {1:2} = {n*1:3}') print(f'{n} x {2:2} = {n*2:3}') print(f'{n} x {3:2} = {n*3:3}') print(f'{n} x {4:2} = {n*4:3}') print(f'{n} x {5:2} = {n*5:3}') print(f'{n} x {6:2} = {n*6:3}') print(f'{n} x {7:2} = {n*7:3}') print(f'{n} x {8:2} = {n*8:3}') print(f'{n} x {9:2} = {n*9:3}') print(f'{n} x {10:2} = {n*10:3}') print('-'*12)
# dude, this is a comment # some more hello def dude(): yes awesome; # Here we have a comment def realy_awesome(): # hi there in_more same_level def one_liner(): first; second # both inside one_liner back_down last_statement # dude, this is a comment # some more hello if 1: yes awesome; # Here we have a comment if ('hello'): # hi there in_more same_level if ['dude', 'dudess'].horsie(): first; second # both inside one_liner 1 back_down last_statement hello = 1.1(20); # subscription a[1] = b[2]; # simple slicing c[1:1] = d[2:2]; # simple slicing e[1:1, 2:2] = f[3:3, 4:4];
# https://open.kattis.com/problems/oddgnome n = int(input()) for _ in range(n): gnomes = list(map(int, input().split()))[1:] for i in range(1, len(gnomes) - 1): if gnomes[i + 1] > gnomes[i - 1]: if gnomes[i] < gnomes[i - 1] and gnomes[i] < gnomes[i + 1]: print(i + 1) break if gnomes[i] > gnomes[i - 1] and gnomes[i] > gnomes[i + 1]: print(i + 1) break
''' ## Questions ### 23. [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. **Example:** ``` Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 ''' ## Solutions # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: length = len(lists) a = [] for i in lists: temp_head = i while temp_head: a.append(temp_head.val) temp_head = temp_head.next a.sort() l = ListNode(None) head = l i = 0 j = len(a) while i < j: new_node = ListNode(a[i]) l.next = new_node l = l.next i += 1 l = head.next return l # Runtime: 100 ms # Memory Usage: 18 MB
# coding=utf-8 # # @lc app=leetcode id=144 lang=python # # [144] Binary Tree Preorder Traversal # # https://leetcode.com/problems/binary-tree-preorder-traversal/description/ # # algorithms # Medium (50.28%) # Total Accepted: 312.5K # Total Submissions: 618.9K # Testcase Example: '[1,null,2,3]' # # Given a binary tree, return the preorder traversal of its nodes' values. # # Example: # # # Input: [1,null,2,3] # ⁠ 1 # ⁠ \ # ⁠ 2 # ⁠ / # ⁠ 3 # # Output: [1,2,3] # # # Follow up: Recursive solution is trivial, could you do it iteratively? # # # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def _preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # 前序遍历 # 中左右 # 迭代 # 迭代用栈保存根节点 # DFS res = [] if root: res.append(root.val) res.extend(self._preorderTraversal(root.left)) res.extend(self._preorderTraversal(root.right)) return res def __preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # BFS res = [] nodes = [root] while nodes: node = nodes.pop() if node: res.append(node.val) nodes.append(node.right) nodes.append(node.left) return res def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # BFS # 用栈的另一种做法 result = [] stack = [] while root or stack: if root: result.append(root.val) stack.append(root) root = root.left else: root = stack.pop() root = root.right return result def ___preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # Morris Traversal res = [] current_node = pre_node = root while current_node: if not current_node.left: res.append(current_node.val) current_node = current_node.right else: pre_node = current_node.left while pre_node.right and pre_node.right != current_node: pre_node = pre_node.right if pre_node.right == current_node: pre_node.right = None current_node = current_node.right else: res.append(current_node.val) pre_node.right = current_node current_node = current_node.left return res def ____preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # An Other Morris Traversal res = [] current_node = pre_node = root while current_node: res.append(current_node.val) if not current_node.left: current_node = current_node.right else: pre_node = current_node.left while pre_node.right and pre_node.right != current_node: pre_node = pre_node.right if pre_node.right == current_node: res.pop() pre_node.right = None current_node = current_node.right else: pre_node.right = current_node current_node = current_node.left return res # if __name__ == "__main__": # s = Solution() # head = TreeNode(1) # head.left = TreeNode(5) # head.left.left = TreeNode(1) # head.left.right = TreeNode(2) # head.right = TreeNode(4) # head.right.left = TreeNode(1) # print s._preorderTraversal(head) # print s.preorderTraversal(head)
# Palace Oasis (2103000) | Ariant Castle (260000300) ariantCulture = 3900 if sm.hasQuest(ariantCulture): sm.setQRValue(ariantCulture, "5", False) sm.sendSayOkay("You used two hands to drink the clean water of the Oasis. " "Delicious! It quenched your thirst right on the spot.")
class Dino: @staticmethod def exe1(): print("al carajo 1") def exe2(self): print("al carajo 2") class Car(Dino): wheels = 0 def __init__(self, color, x, func): self.color = color self.f = func Car.wheels = x while (True): print("yey") Dino.exe1() din = Dino() din.exe2() f = lambda x: x+1 #print(f(2)) print(Car.wheels) car = Car("red", 5, f) print(Car.wheels) print(car.color) print(car.f(50))
#!/usr/bin/python # # Copyright 2007 Google Inc. All Rights Reserved. """CSS Lexical Grammar rules. CSS lexical grammar from http://www.w3.org/TR/CSS21/grammar.html """ __author__ = ['elsigh@google.com (Lindsey Simon)', 'msamuel@google.com (Mike Samuel)'] # public symbols __all__ = [ "NEWLINE", "HEX", "NON_ASCII", "UNICODE", "ESCAPE", "NMSTART", "NMCHAR", "STRING1", "STRING2", "IDENT", "NAME", "HASH", "NUM", "STRING", "URL", "SPACE", "WHITESPACE", "COMMENT", "QUANTITY", "PUNC" ] # The comments below are mostly copied verbatim from the grammar. # "@import" {return IMPORT_SYM;} # "@page" {return PAGE_SYM;} # "@media" {return MEDIA_SYM;} # "@charset" {return CHARSET_SYM;} KEYWORD = r'(?:\@(?:import|page|media|charset))' # nl \n|\r\n|\r|\f ; a newline NEWLINE = r'\n|\r\n|\r|\f' # h [0-9a-f] ; a hexadecimal digit HEX = r'[0-9a-f]' # nonascii [\200-\377] NON_ASCII = r'[\200-\377]' # unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])? UNICODE = r'(?:(?:\\' + HEX + r'{1,6})(?:\r\n|[ \t\r\n\f])?)' # escape {unicode}|\\[^\r\n\f0-9a-f] ESCAPE = r'(?:' + UNICODE + r'|\\[^\r\n\f0-9a-f])' # nmstart [_a-z]|{nonascii}|{escape} NMSTART = r'(?:[_a-z]|' + NON_ASCII + r'|' + ESCAPE + r')' # nmchar [_a-z0-9-]|{nonascii}|{escape} NMCHAR = r'(?:[_a-z0-9-]|' + NON_ASCII + r'|' + ESCAPE + r')' # ident -?{nmstart}{nmchar}* IDENT = r'-?' + NMSTART + NMCHAR + '*' # name {nmchar}+ NAME = NMCHAR + r'+' # hash HASH = r'#' + NAME # string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\" ; "string" STRING1 = r'"(?:[^\"\\]|\\.)*"' # string2 \'([^\n\r\f\\']|\\{nl}|{escape})*\' ; 'string' STRING2 = r"'(?:[^\'\\]|\\.)*'" # string {string1}|{string2} STRING = '(?:' + STRING1 + r'|' + STRING2 + ')' # num [0-9]+|[0-9]*"."[0-9]+ NUM = r'(?:[0-9]*\.[0-9]+|[0-9]+)' # s [ \t\r\n\f] SPACE = r'[ \t\r\n\f]' # w {s}* WHITESPACE = '(?:' + SPACE + r'*)' # url special chars URL_SPECIAL_CHARS = r'[!#$%&*-~]' # url chars ({url_special_chars}|{nonascii}|{escape})* URL_CHARS = r'(?:%s|%s|%s)*' % (URL_SPECIAL_CHARS, NON_ASCII, ESCAPE) # url URL = r'url\(%s(%s|%s)%s\)' % (WHITESPACE, STRING, URL_CHARS, WHITESPACE) # comments # see http://www.w3.org/TR/CSS21/grammar.html COMMENT = r'/\*[^*]*\*+([^/*][^*]*\*+)*/' # {E}{M} {return EMS;} # {E}{X} {return EXS;} # {P}{X} {return LENGTH;} # {C}{M} {return LENGTH;} # {M}{M} {return LENGTH;} # {I}{N} {return LENGTH;} # {P}{T} {return LENGTH;} # {P}{C} {return LENGTH;} # {D}{E}{G} {return ANGLE;} # {R}{A}{D} {return ANGLE;} # {G}{R}{A}{D} {return ANGLE;} # {M}{S} {return TIME;} # {S} {return TIME;} # {H}{Z} {return FREQ;} # {K}{H}{Z} {return FREQ;} # % {return PERCENTAGE;} UNIT = r'(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)' # {num}{UNIT|IDENT} {return NUMBER;} QUANTITY = '%s(?:%s%s|%s)?' % (NUM, WHITESPACE, UNIT, IDENT) # "<!--" {return CDO;} # "-->" {return CDC;} # "~=" {return INCLUDES;} # "|=" {return DASHMATCH;} # {w}"{" {return LBRACE;} # {w}"+" {return PLUS;} # {w}">" {return GREATER;} # {w}"," {return COMMA;} PUNC = r'<!--|-->|~=|\|=|[\{\+>,:;]'
# Copyright (c) 2018 - 2020 Institute for High Voltage Technology and Institute for High Voltage Equipment and Grids, Digitalization and Power Economics # RWTH Aachen University # Contact: Thomas Offergeld (t.offergeld@iaew.rwth-aachen.de) # # # This module is part of CIMPyORM. # # # CIMPyORM is licensed under the BSD-3-Clause license. # For further information see LICENSE in the project's root directory. # def test_parse_meta(acquire_db, dummy_source): _, session = acquire_db assert dummy_source.tree assert dummy_source.nsmap == {'cim': 'http://iec.ch/TC57/2013/CIM-schema-cim16#', 'entsoe': 'http://entsoe.eu/CIM/SchemaExtension/3/1#', 'md': 'http://iec.ch/TC57/61970-552/ModelDescription/1#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'} assert dummy_source.cim_version == "16"
""" Backported error classes for twisted. """ __docformat__ = 'epytext en' class VerifyError(Exception): """Could not verify something that was supposed to be signed. """ class PeerVerifyError(VerifyError): """The peer rejected our verify error. """ class CertificateError(Exception): """ We did not find a certificate where we expected to find one. """
alunos = {'aluno':str(input('Digite o nome do aluno: ')),'media':float(input(f'Média do aluno: '))} print(f'Nome: {alunos["aluno"]}.') print(f'Média: {alunos["media"]}.') if alunos['media'] > 7: print(f'O aluno {alunos["aluno"]} foi aprovado.') else: print(f'O aluno {alunos["aluno"]} foi reprovado.') #PODERIA TER USADO O for k, v in alunos.items() PARA MOSTRAR OS VALORES: #print(f' - {k} é igual a {v}.')
def test(): assert len(TRAINING_DATA) == 4, "Los datos de entrenamiento no concuerdan – esperaba 4 ejemplos." assert all( len(entry) == 2 and isinstance(entry[1], dict) for entry in TRAINING_DATA ), "Formato incorrecto de los datos de entrenamiento. Esperaba una lista de tuples dónde el segundo elemento es un dict." assert all( entry[1].get("entities") for entry in TRAINING_DATA ), "Todas las anotaciones en los datos de entrenamiento deberían incluir entidades." assert TRAINING_DATA[0][1]["entities"] == [ (10, 19, "GPE") ], "Vuelve a revisar las entidades en el primer ejemplo." assert TRAINING_DATA[1][1]["entities"] == [ (17, 22, "GPE") ], "Vuelve a revisar las entidades en el segundo ejemplo." assert TRAINING_DATA[2][1]["entities"] == [ (15, 20, "GPE"), (24, 32, "GPE"), ], "Vuelve a revisar las entidades en el tercer ejemplo." assert TRAINING_DATA[3][1]["entities"] == [ (0, 6, "GPE") ], "Vuelve a revisar las entidades en el cuarto ejemplo." __msg__.good( "¡Muy buen trabajo! Una vez el modelo logra buenos resultados detectando entidades GPE " "en los comentarios de los viajeros, podrías añadir un componente basado " "en reglas para determinar si la entidad es un destino turístico en " "este contexto. Por ejemplo, puedes resolver los tipos de entidades en relación con un knowledge base o " "buscarlas en un wiki de viajes." )
with open('inputs/input24.txt') as fin: raw = fin.read() def parse(raw): x = [x for x in raw.splitlines()] return x a = parse(raw) def part_1(data): dictionary = {} for a in data: e = a.count('ne') + a.count('se') w = a.count('nw') + a.count('sw') x = e + 2 * (a.count('e') - e) - (w + 2 * (a.count('w') - w)) y = a.count('n') - a.count('s') if (x, y) in dictionary: dictionary[(x, y)] = not dictionary[(x, y)] else: dictionary[(x, y)] = True return dictionary, sum(dictionary.values()) def part_2(data): result = {} print(data.items()) for x in range(10): for i in data.items(): count = 0 x = i[0] y = i[1] if data.get((x + 2, y)): if data.get((x + 2, y)) == 1: count += 1 else: result[(x + 2, y)] = -1 if data.get((x - 2, y)): if data.get((x - 2, y)) == 1: count += 1 else: result[(x - 2, y)] = -1 if data.get((x + 1, y + 1)): if data.get((x + 1, y + 1)) == 1: count += 1 else: result[(x + 1, y + 1)] = -1 if data.get((x - 1, y + 1)): if data.get((x - 1, y + 1)) == 1: count += 1 else: result[(x - 1, y + 1)] = -1 if data.get((x + 1, y - 1)): if data.get((x + 1, y - 1)) == 1: count += 1 else: result[(x + 1, y - 1)] = -1 if data.get((x - 1, y - 1)): if data.get((x - 1, y - 1)) == 1: count += 1 else: result[(x - 1, y - 1)] = -1 if data[i] == 1 and (count == 0 or count > 2): result[i] = -1 elif data[i] == -1 and count == 2: result[i] = 1 else: result[i] = data[i] data = result return list(result.values()) # print(a) print(part_1(a)[1]) print(part_2(part_1(a)[0]))
num = int(input('Digite um numero: ')) tot = 0 for c in range(1, num +1): if num% c == 0 : print('\033[33m', end='') tot += 1 else: print('\033[31m',end=' ') print('{}'.format(c) , end=' ') print('\n\033[mO numero {} foi divisivel {} vezes'.format(num, tot)) if tot == 2: print('E por isso ele e Primo') else: print('E por isso ele nao e Primo .')
__version__ = '0.3.7' __title__ = 'iam-docker-run' __description__ = 'Run Docker containers within the context of an AWS IAM Role, and other development workflow helpers.' __url__ = 'https://github.com/billtrust/iam-docker-run' __author__ = 'Doug Kerwin' __author_email__ = 'dwkerwin@gmail.com' __license__ = 'MIT' __keywords__ = ['aws', 'iam', 'iam-role', 'docker']
#!/bin/python3 # # Copyright (c) 2019 Paulo Vital # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # def fibonacci(n): if (n == 0) or (n == 1): yield 1 yield (fibonacci(n-1) + fibonacci(n-2)) # int main(int argc, char#*argv) # { # int i, limit; # # if (argc < 2) { # printf("Type a limit number: "); # scanf("%d", &limit); # } else { # limit = atoi(argv[1]); # } # # printf("The Fibonacci sequence for %d is: ", limit); # # for (i = 0; i < limit; i++) # printf ("%d ", fibonacci(i)); # # printf("\n"); # # return 0; # } if __name__ == '__main__': end = input("Type a limit number: ") print("The Fibonacci sequence for {0} is: ".format(end), list(fibonacci(int(end))))
""" Module: 'uasyncio.event' on esp32 1.13.0-103 """ # MCU: (sysname='esp32', nodename='esp32', release='1.13.0', version='v1.13-103-gb137d064e on 2020-10-09', machine='ESP32 module (spiram) with ESP32') # Stubber: 1.3.4 class Event: '' def clear(): pass def is_set(): pass def set(): pass wait = None core = None
NumbersBelow19 = ["One", "Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Ninteen"] multiplesOf10 = ["Twenty" , "Thirty" , "Fourty" , "Fifty" , "Sixty" , "Seventy" ,"Eighty" , "Ninety"] singleDigits = ["One", "Two","Three","Four","Five","Six","Seven","Eight","Nine"] def doHigh(anumber): if anumber < 20: result = NumbersBelow19[anumber-1] else: aPart = int(anumber / 10) bPart = anumber % 10 if bPart == 0: result = multiplesOf10[aPart - 2] else: result = "%s-%s"%(multiplesOf10[aPart - 2], singleDigits[bPart - 1] ) return result numberToBeConverted = int(input('Enter number: ')) print(doHigh(numberToBeConverted))
num = int(input()) first = [] second = [] for i in range(num): line = input().split(' ') name = line[0] t1 = float(line[1]) t2 = float(line[2]) first.append([name, t1]) second.append([name, t2]) first.sort(key=lambda x: x[1]) second.sort(key=lambda x: x[1]) total_time = 0 squad_list_of_lists = [] for i in first: name = i[0] squad = [] time = 0 for j in second: if len(squad) < 3: if j[0] != name: squad.append(j[0]) time += j[1] else: break squad.insert(0, name) time += i[1] squad_list_of_lists.append([squad, time]) squad_list_of_lists.sort(key=lambda x: x[1]) print(squad_list_of_lists[0][1]) for runner in squad_list_of_lists[0][0]: print(runner)
def remdup(a): return list(set(a)) l=[] for i in range(0,5): l.append(input()) print(l) rev = l[::-1] print(rev) print(remdup(l)) print([i for i in range(0,10) if i%2==0])
''' Created on 1.12.2016 @author: Darren '''''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array." '''
# This is Pessimistic Error Pruning. def prune(t): # If the node is a leaf node, stop pruning. if t.label != None: return L = t.leaf_sum N = t.N p = (t.RT + 0.5*L)/N # When the following condition is satisfied, # replace the subtree with a leaf node. if t.RT + 0.5 - (N*p*(1-p))**0.5 < t.RT + 0.5*L: # The label of the leaf node depends on the # majority label of the subtree. t.label = t.majority return # Prune the tree recursively. prune(t.left) prune(t.right)
__author__ = 'haukurk' def log_exception(sender, exception, **extra): """ Log an exception to our logging framework. @param sender: sender @param exception: exception triggered @**extra: other params. @return: void """ sender.logger.debug('Got exception during processing: %s', exception) def error_incorrect_version(version): """ Return a response when the client is using incorrect API version. @param version: version in use. @return: dict """ return {"status": "error", "message": "incorrect API version "+str(version)+" used."} def error_object_not_found(): """ Return an error response when something is not found, like a object in a database. @return: dict """ return {"status": "error", "message": "object not found"} def error_commit_error(ex): """ Return an error response when database commit fails somehow. Like when inserting into a database and you get a unique constraint violated. @return: dict """ return {"status": "error", "message": "error when committing object to database", "exception": ex.message}
"""Top-level package for trailscraper.""" __author__ = """Florian Sellmayr""" __email__ = 'florian.sellmayr@gmail.com' __version__ = '0.6.5'
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isCousins(self, root: 'TreeNode', x: 'int', y: 'int') -> 'bool': m = {} def traverse(node, parent=None, depth=0): if node: m[node.val] = (parent, depth) traverse(node.left, node.val, depth+1) traverse(node.right, node.val, depth + 1) traverse(root) return m[x][0] != m[y][0] and m[x][1] == m[y][1]
class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance # Taken from https://github.com/tomerghelber/singleton-factory class SingletonFactory(type): """ Singleton Factory - keeps one object with the same hash of the same cls. Returns: An existing instance. """ __instances = dict() def __call__(cls, *args, **kwargs): if cls not in cls.__instances: cls.__instances[cls] = dict() new_obj = super(SingletonFactory, cls).__call__(*args, **kwargs) if hash(new_obj) not in cls.__instances[cls]: cls.__instances[cls][hash(new_obj)] = new_obj return cls.__instances[cls][hash(new_obj)]
# Utilizando a função type, escreva uma função recursiva que imprima os elementos de uma lista # Cada elemento deve ser impresso separadamente, um por linha # Considere o caso de listas dentro de listas, como L = [1, [2, 3, 4, [5, 6, 7]]] # A cada nível, imprima a lista mais à direita, como fazemos para indentar blocos em Python # Dica: envie o nível atual como parâmetro e utilize-o para calcular a quantidade de espaços em branco à esquerda de cada elemento SPACES_BY_LEVEL = 4 def print_elements(lst, level=0): spaces = ' ' * SPACES_BY_LEVEL * level if type(lst) == list: print(spaces, '[') for e in lst: print_elements(e, level + 1) print(spaces, ']') else: print(spaces, lst) L = [1, [2, 3, 4, [5, 6, 7]]] print_elements(L)
#To find whether the number is +ve,-ve or 0 x=int(input("Enter a number")) def check_num(x): if x>0: print("The",x,"is positive") elif x<0: print("The",x,"is negative") else: print("The",x,"is zero") check_num(x)
"""Constants for propensity_matching library.""" MINIMUM_DF_COUNT = 4000 MINIMUM_POS_COUNT = 1000 UTIL_BOOST_THRESH_1 = MINIMUM_POS_COUNT UTIL_BOOST_THRESH_2 = MINIMUM_DF_COUNT UTIL_BOOST_THRESH_3 = 50000 SAMPLES_PER_FEATURE = 100 SMALL_MATCH_THRESHOLD = 3000**3
class RequestError(Exception): """The base class for all errors.""" def __init__(self, code, error, retry_after=None): pass class Unauthorized(RequestError): """Raised if your API Key is invalid or blocked.""" def __init__(self, url, code): self.code = code self.error = 'Your API Key is invalid or blocked.\nURL: ' + url super().__init__(self.code, self.error) class NotFoundError(RequestError): """Raised if an invalid player tag or club tag has been passed.""" def __init__(self, url, code): self.code = code self.error = 'An incorrect tag has been passed.\nURL: ' + url super().__init__(self.code, self.error) class RateLimitError(RequestError): """Raised when the rate limit is reached.""" def __init__(self, url, code, retry_after): self.code = code self.retry_after = retry_after self.error = 'The rate limit has been reached.\nURL: ' + url super().__init__(self.code, self.error, retry_after=self.retry_after) class UnexpectedError(RequestError): """Raised if an unknown error has occured.""" def __init__(self, url, code): self.code = code self.error = 'An unexpected error has occured.\nURL: ' + url super().__init__(self.code, self.error) class ServerError(RequestError): """Raised if the API is down.""" def __init__(self, url, code): self.code = code self.error = 'The API is down. Please be patient and try again later.\nURL: ' + url super().__init__(self.code, self.error)
#!/usr/bin/python3 ################################ # File Name: DocTestExample.py # Author: Chadd Williams # Date: 10/17/2014 # Class: CS 360 # Assignment: Lecture Examples # Purpose: Demonstrate PyTest ################################ # Run these test cases via: # chadd@bart:~> python3 -m doctest -v DocTestExample.py # Simple int example def testIntAddition(left: int, right: int)->"sum of left and right": """Test the + operator for ints Test a simple two in example >>> testIntAddition(1,2) 3 Use the same int twice, no problem >>> testIntAddition(2,2) 4 Try to add a list to a set! TypeError! Only show the first and last lines for the error message The ... is a wild card The ... is tabbed in TWICE >>> testIntAddition([2], {3}) Traceback (most recent call last): ... TypeError: can only concatenate list (not "set") to list """ return left + right # Simple List example def printFirstItemInList(theList: "list of items"): """ Retrieve the first item from the list and print it Test a list of ints >>> printFirstItemInList( [ 0, 1, 2] ) 0 Test a list of strings >>> printFirstItemInList( ["CS 360", "CS 150", "CS 300" ] ) CS 360 Generate a list comphrension >>> printFirstItemInList( [ x+1 for x in range(10) ] ) 1 Work with a list of tuples >>> printFirstItemInList( [ (x,x+1, x-1) for x in range(10) ] ) (0, 1, -1) """ item = theList[0] print(item) # Test Output of print and return value # that \ at the end of the line allows you to continue # the same statement on the next line! def printAndReturnSum(*args: "variadic param")\ ->"return sum of ints provided as parameters": """ Print and return the sum of the args that are ints >>> printAndReturnSum(1,2,3) 6 6 >>> printAndReturnSum("bob", 1) 1 1 """ total = 0 for x in args: # type check at run time! if type(x) is int : total += x print(total) return total