content
stringlengths
7
1.05M
# Python program to learn about control flow number = 23 guess = int(input('Enter an integer : ')) if guess == number: # New block starts here print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') # New block ends here elif guess < number: # Another block print('No, it is a little higher than that') # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guessed > number to reach here print('Done') number = 23 running = True #You can have an else cause for a while loop while running: guess = int(input('Enter an integer : ')) if guess == number: # New block starts here print('Congratulations, you guessed it.') print('(but you do not win any prizes!)') running = False # New block ends here elif guess < number: # Another block print('No, it is a little higher than that') # You can do whatever you want in a block ... else: print('No, it is a little lower than that') # you must have guessed > number to reach here else: print('the while loop is over') print('Done') #for loop for i in range (1,5): print(i) else: print('the for loop is over') print(list(range(5))) while True: s = input('Ente somting: ') if s == 'quit': break print('Length of the string is', len(s)) print('Done') print() while True: s = input('Enter something : ') if s == 'quit': break if len(s) < 3: print('too small') continue print('Input is of sufficent length')
#takes data from the Game() class and... #1. populates the score board with the runs scored and balls used by batsman #2. changes the player position if the run hit is 1,3 or 5 #3. removes the player from the activePlayers list and the playing list if he gets out class Runs(): def __init__(self,run,playing,remaining,scoreBoard,total,currentScore,target): self.run = run self.playing = playing self.remaining = remaining self.scoreBoard = scoreBoard self.total = total self.currentScore = currentScore self.target = target self.scoreBoard[self.playing[0]][1] += 1 if self.run in [1,2,3,4,5,6]: self.scoreBoard[self.playing[0]][0] += self.run self.total += self.run self.currentScore -= self.run if self.run in [1,3,5]: self.playing = self.playing[::-1] if self.run == "Out": if len(self.remaining) != 0: self.scoreBoard[self.playing[0]][1] -= 1 self.playing.pop(0) self.playing.insert(0, self.remaining[0]) self.remaining.pop(0) else: self.playing.pop(0)
class Arrayerrortype(basestring): """ ARRAY_INCONSISTENT_ADDRESSING_METHOD|ARRAY_DEVTYPE_ERROR Possible values: <ul> <li> "array_inconsistent_addressing_method" - Array is using inconsistent LUN addressing schemes., <li> "array_devtype_error" - Array has encountered a device class error. </ul> """ @staticmethod def get_api_name(): return "arrayerrortype"
#!/usr/bin/env python3 # Author:: Justin Flannery (mailto:juftin@juftin.com) """ Project Configuration for Yellowstone Variables """ class SearchConfig: """ File Path Storage Class """ POLLING_INTERVAL_MINIMUM: int = 5 # 5 MINUTES RECOMMENDED_POLLING_INTERVAL: int = 10 # 10 MINUTES ERROR_MESSAGE: str = "No search days configured. Exiting" MINIMUM_CAMPSITES_FIRST_NOTIFY: int = 5
__author__ = 'cosmin' class CommandError(Exception): def __init__(self, arg): self.msg = arg class InvalidParameters(Exception): def __init__(self, arg): self.msg = arg
if __name__ == '__main__': N = int(input()) nested_list = [] for _ in range(N): name = input() score = float(input()) nested_list.append([name,score]) score_list = [] for i in nested_list: score_list.append(i[1]) mini = min(score_list) score_list = sorted(score_list) nun_mini = score_list.count(mini) score_list = score_list[nun_mini:] second_lowest = min(score_list) second_lowest_list = [] for i in range(len(nested_list)): if nested_list[i][1] == second_lowest: second_lowest_list.append(nested_list[i][0]) sorted_list = sorted(second_lowest_list) for name in sorted_list: print(name)
colors = {"Red", "Green", "Blue"} # add(): adds item to the set. colors.add("Magenta") print(colors) # discard(): removes item from set without error if not present. colors.discard("Blue") colors.discard("Blue") print(colors) # remove(): removes item from set with KeyError if not present. colors.remove("Red") # colors.remove("Red") # KeyError: 'Red' numbers = {1, 2, 3, 4} # update(): adds items from a sequence into a set. colors.update(numbers) print(colors) # Below is a string, which will be stored as A, n, d, y colors.update("Andy") print(colors)
"""Presets for end-to-end model training for special tasks.""" __all__ = [ 'tabular_gpu_presets' ]
class ProcessoSimulado: idProcesso = 0 contadorPrograma = 0 tempoInicio = 0 idProcessoPai = 0 estado = 0 # Bloqueado:0, Pronto:1, Em execução:2 prioridade = 0 # 0,1,2,3 sendo que 3 é a mais baixa e 0 a mais alta tempoCPU = 0 instrucoes = [] def __init__(self, idProcesso, contadorPrograma, tempoInicio, idPai=0, estado=0, prioridade=0): self.idProcesso = idProcesso self.contadorPrograma = contadorPrograma self.tempoInicio = tempoInicio self.idProcessoPai = idPai self.estado = estado self.prioridade = prioridade self.tempoCPU = 0 self.instrucoes = [] # * Método relacionado a manipulação do estado do processo def retornaEstado(self): if self.estado == 0: return "Bloqueado" elif self.estado == 1: return "Pronto" elif self.estado == 2: return "Em Execução" # * Métodos relacionados a manipulação das prioridades dos processos def incrementarPrioridade(self): if self.prioridade < 3: self.prioridade+=1 def decrementarPrioridade(self): if self.prioridade > 0: self.prioridade-=1 # * Métodos relacionados a execução do processo def adicionarInstrucao(self, instrucao:str): self.instrucoes.append(instrucao) def executarProcesso(self): self.tempoCPU += 1 # * Métodos relacionados a impressão do processo def imprimeProcessoDetalhado(self): dadosDoProcesso = [] dadosDoProcesso.append(self.idProcesso) dadosDoProcesso.append(self.idProcessoPai) dadosDoProcesso.append(self.prioridade) dadosDoProcesso.append(self.retornaEstado()) dadosDoProcesso.append(self.tempoInicio) dadosDoProcesso.append(self.tempoCPU) return dadosDoProcesso def imprimeProcessoSimplificado(self): dadosDoProcesso = [] dadosDoProcesso.append(self.idProcesso) dadosDoProcesso.append(self.prioridade) dadosDoProcesso.append(self.retornaEstado()) return dadosDoProcesso
# -*- coding: utf-8 -*- def main(): n, m, x, y = map(int, input().split()) xs = list(map(int, input().split())) + [x] ys = list(map(int, input().split())) + [y] x_max = max(xs) y_min = min(ys) if x_max < y_min: print('No War') else: print('War') if __name__ == '__main__': main()
description_short = "linux signal file descriptor for python" keywords = [ "signalfd", "python3", "linux", ]
a, n = map(int, input().split()) ans = 0 for i in range(n): ans = ans + (n - i) * a * (10 ** i) print(ans)
def parse_comment(comment, data): comment.etag = data["etag"] comment.id = data["string"] # snippet snippet_data = data.get("snippet", False) if snippet_data: comment.author_display_name = author_display_name_data["snippet"][ "authorDisplayName" ] comment.author_profile_image_url = author_profile_image_url_data[ "snippet" ]["authorProfileImageUrl"] comment.author_channel_url = author_channel_url_data["snippet"][ "authorChannelUrl" ] comment.channel_id = channel_id_data["snippet"]["channelId"] comment.video_id = video_id_data["snippet"]["videoId"] comment.text_display = text_display_data["snippet"]["textDisplay"] comment.text_original = text_original_data["snippet"]["textOriginal"] comment.parent_id = parent_id_data["snippet"]["parentId"] comment.can_rate = can_rate_data["snippet"]["canRate"] comment.viewer_rating = viewer_rating_data["snippet"]["viewerRating"] comment.like_count = like_count_data["snippet"]["likeCount"] comment.moderation_status = moderation_status_data["snippet"][ "moderationStatus" ] comment.published_at = published_at_data["snippet"]["publishedAt"] comment.updated_at = updated_at_data["snippet"]["updatedAt"] return comment
def isPalindrome(strn): for i in range(0, len(strn)//2): if strn[i] != strn[len(strn)-i-1]: return False return True x=input() if isPalindrome(x)==1: print("Yes, '{}' is a palindrome".format(x)) else: print("No, '{}' is NOT a palindrome".format(x))
# Faça um programa que tenha uma função chamada escreva(), que receba um texto # qualquer como parâmetro e mostre uma mensagem com tamanho adaptável. def escreva(msg): a = len(msg) + 4 print('~' * a) print(f'{msg.center(a)}') # Centralizando a formatação de uma string print('~' * a) escreva("RENATO PEREIRA") escreva("Curso de Python no Youtube") escreva("CeV")
""" You can't call grok.context multiple times on module level: >>> import grokcore.component.tests.adapter.modulecontextmultiple_fixture Traceback (most recent call last): ... GrokImportError: The 'context' directive can only be called once per class or module. """
# @Title: 提莫攻击 (Teemo Attacking) # @Author: KivenC # @Date: 2018-07-24 13:50:50 # @Runtime: 116 ms # @Memory: N/A class Solution(object): def findPoisonedDuration(self, timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ if timeSeries == []: return 0 count = 0 for i in range(len(timeSeries)-1): if timeSeries[i] + duration <= timeSeries[i+1]: count += duration else: count += timeSeries[i+1] - timeSeries[i] return count + duration
if __name__ == "__main__": # Read integer input from stdin t = int(input()) for t_itr in range(t): # Read string input from stdin n, k = list(map(int, input().split())) # Compute bitwise and max value print(k-1 if ((k-1) | k) <= n else k-2)
# -*- coding: utf-8 -*- """ This file is covered by the LICENSING file in the root of this project. """ __author__ = 'ZGQ'
# https://app.terra.bio/#workspaces/broad-dsp-hca-processing-prod4/Bone-Marrow-Myeloma-copy/workflows/broad-dsp-hca-processing-prod4/CreateSS2AdapterMetadata BAM_INPUT = { "file_path": "/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam", "sha256": "1d7038c19c5961ee8f956330af0dd24ecd0407eb14aa21e4c1c9bbad47468500", "input_uuid": "0244354d-cf37-4483-8db3-425b7e504ca6", "workspace_version": "2021-10-19T17:43:52.000000Z", "creation_time": "2021-10-14T18:47:57Z", "pipeline_type": "SS2", "crc32c": "2a3433fb", "size": 791383592, } BAI_INPUT = { "file_path": "/cromwell_root/localized-path/call-HISAT2PairedEnd/cacheCopy/0244354d-cf37-4483-8db3-425b7e504ca6_qc.bam.bai", "sha256": "9474e18a0e86baac1f3b6bd017c781738f7cadafe21862beb1841abc070f32fe", "input_uuid": "0244354d-cf37-4483-8db3-425b7e504ca6", "workspace_version": "2021-10-19T17:43:52.000000Z", "creation_time": "2021-10-14T18:47:57Z", "pipeline_type": "SS2", "crc32c": "dbd6cf34", "size": 2295024, }
#! /usr/bin/env python3 a = 1 b = 0 x = 1 limit = 1000 while len("%d"%a) < limit: print("F(%d) %d: %d " % (x,len("%d"%a),a)) c = a a = a+b b = c x+=1
# 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 FindElements: def __init__(self, root: TreeNode): self.root = root self.recover(self.root, 0) def recover(self, root: TreeNode, val: int) -> None: root.val = val if root.left: self.recover(root.left, 2 * val + 1) if root.right: self.recover(root.right, 2 * val + 2) def find(self, target: int) -> bool: return self.lookup(self.root, target) def lookup(self, root: TreeNode, target: int) -> bool: if not root: return False if root.val > target: return self.lookup(root.left, target) if root.val == target: return True return self.lookup(root.right, target) or self.lookup(root.left, target) # Your FindElements object will be instantiated and called as such: # obj = FindElements(root) # param_1 = obj.find(target)
# Given two strings str1 and str2 and below operations that can performed on str1. # Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. # Insert # Remove # Replace # All of the above operations are of equal cost. def editDistance(s,t): m = len(s) n = len(t) dp = [[0 for j in range(n+1)] for i in range(m+1)] for i in range(m+1): for j in range(n+1): if i==0: dp[i][j] = j elif j == 0: dp[i][j] = i elif s[i-1] == t[j-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) return dp[m][n] s = input() t = input() print(editDistance(s,t))
a = 10 if 0 <= a < 5: print('[0, 5)') elif 5 <= a < 8: print('[5, 8)') else: print('[8, +Infinity)')
for T in range(1,int(input())+1): t,c=input().split() t=list(t) c=int(c) ans=0 for i in range(len(t)-c+1): if t[i]=='-': ans+=1 for j in range(i,i+c): t[j]='+' if t[j]=='-' else '-' if not '-' in t: print('Case #%d:'%T,ans) else: print('Case #%d: IMPOSSIBLE'%T)
# Time: O(n) # Space: O(1) class Solution: def missingNumber(self, nums): n = len(nums) sum = n * (n + 1) / 2 sum2 = 0 for i in nums: sum2 += i return int(sum - sum2) if __name__ == "__main__": nums = [9, 6, 4, 2, 3, 5, 7, 0, 1] s = Solution() print(s.missingNumber(nums))
# Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite. vel = float(input('Digite a velocidade do carro: ')) if vel > 80.0: multa = (vel - 80.0) * 7 print('Voce foi multado em R$ {:.2f} por excesso de velocidade. '.format(multa)) else: print('Parabéns, você digite muito bem !')
class Solution: def uniquePaths(self, m, n): dp = [[0] * n for i in xrange(m)] dp[m - 1][n - 1] = 1 process = collections.deque([(m - 1, n - 1)]) while process: i, j = process.popleft() if j < n - 1: a = dp[i][j + 1] else: a = 0 if i < m - 1: b = dp[i + 1][j] else: b = 0 dp[i][j] = max(a + b, 1) if i > 0 and dp[i - 1][j] != -1: dp[i - 1][j] = -1 process.append((i - 1, j)) if j > 0 and dp[i][j - 1] != -1: dp[i][j - 1] = -1 process.append((i, j - 1)) return dp[0][0]
# Adapted from a Java code in the "Refactoring" book by Martin Fowler. # Replace temp with query # Code snippet. Not runnable. def get_price(): base_price = quantity * item_price discount_factor = 0 if base_price > 1000: discount_factor = 0.95 else: discount_factor = 0.98 return base_price * discount_factor
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/30 10:38 # @Author : Leishichi # @File : 12.py # @Software: PyCharm # @Tag: class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """ symbols = {1: "I", 5: "V", 10: "X", 50: "L", 100: "C", 500: "D", 1000: "M"} position = 1 romans = [] while num > 0: digit = num % 10 if digit < 4: for _ in range(digit): romans.append(symbols[position]) elif digit == 4 or digit == 9: romans.append(symbols[(digit + 1) * position]); romans.append(symbols[position]) elif digit == 5: romans.append(symbols[digit * position]) else: for _ in range(digit - 5): romans.append(symbols[position]) romans.append(symbols[5 * position]) position *= 10 num = num // 10 return "".join(romans[::-1])
# Esto es un comentario # Input siempre regresa una string(palabra) # Nombre nombre = "Cristian" print("Mi nombre es " + nombre) # Apellidos apellidoPaterno = "Flores" apellidoMaterno = "Bernal" apellidos = apellidoPaterno + ' ' + apellidoMaterno print("Mis Apellidos son: " + apellidos) # Edad edad = 0 print("Edad:", edad) edad = int(input("Cual es tu edad? ")) # "21" -> 21 print("Edad:", edad) print("Edad + 5:", edad + 5)
""" encoders.py ----------- Convert GraphData to texts. """ def encode_edgelist(graph, delimiter=' ', attr=False, header=False): text = '' if header: text += delimiter.join([str(a) for a in graph.edge_attr[:2]]) if attr: text += delimiter text += delimiter.join([str(a) for a in graph.edge_attr[2:]]) text += '\n' for ((node1, node2), *attrs) in graph.edges: text += '{}{}{}'.format( graph.nodes[node1][0], delimiter, graph.nodes[node2][0]) if attr: text += delimiter + delimiter.join([str(d) for d in attrs]) text += '\n' return text def write(text, out, close=True): file = open(out) if isinstance(out, str) else out file.write(text) if close: file.close()
# Largest palindrome product def checkPalindrome(x): if str(x) == str(x)[::-1]: return True return False maxPalindrome = 0 for x in range(999,99,-1): for y in range(999,99,-1): if checkPalindrome(x*y): print(x,y) print(x*y) if x*y > maxPalindrome: maxPalindrome = x*y print(maxPalindrome)
class Animal: name = "Lion" noise = "Rrrrr" color = "Gray" def make_noise(self): print(f"{self.noise}") def get_noise(self): return self.noise def set_noise(self, new_noise): self.noise = new_noise def show_name(self): print(f"{self.name}") def get_name(self): return self.name def set_name(self, new_name): self.name = new_name def show_color(self): print(f"{self.color}") def get_name(self): return self.color def set_noise(self, new_color): self.color = new_color class Wolf(Animal): noise = "GRrrrrrr"
# Time complexity: O(n*2^n) # Approach: For each subset, iterate from 0 to n-1 and for each number in binary, take elements corresponding to 1s. class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums = sorted(nums) n = len(nums) ans = [] for i in range(2**n): tmp = [] for j in range(n): if i & (1<<j): tmp.append(nums[j]) if tmp not in ans: ans.append(tmp) return ans
class rawDataError(Exception): def __init__(self): self.message = 'Please choose a valid raw data file!' super().__init__(self.message) class ratioError(Exception): def __init__(self): self.message = 'Could not read Active:Carbon:Binder ratio input.' super().__init__(self.message) class tablePermissionError(Exception): def __init__(self): self.message = 'Cannot save data table because the file is currently in use by another program.' super().__init__(self.message) class figurePermissionError(Exception): def __init__(self): self.message = 'Cannot save figure because the file is currently in use by another program.' super().__init__(self.message)
class Reservations: def __init__(self, client): self.client = client def list(self, params={}): return self.client.request('GET', self._url(params), params) def create(self, params={}): return self.client.request('POST', self._url(params), params) def show(self, id): url = '/reservations/{0}'.format(id) return self.client.request('GET', url, {}) def update(self, id, params={}): url = '/reservations/{0}'.format(id) update_params = {'reservation': params} return self.client.request('PUT', url, update_params) def destroy(self, id): url = '/reservations/{0}'.format(id) return self.client.request('DELETE', url, {}) def bulk_create(self, reservations=[], webhook=None): url = '/reservations/bulk_create' params = {'reservations': reservations} if webhook: params['webhook'] = webhook return self.client.request('POST', url, params) def _url(self, params={}): if 'property_id' in params: property_id = params['property_id'] return '/properties/{id}/reservations'.format(id=property_id) else: return '/reservations'
""" time complexity = O(n) space complexity = O(1) set MAX and MIN value to be 32 bits maximun and minimun integar strip to delete whitespace remain sign as 1 or -1 check each char should be in '0'~ '9' plus the ret as each bit check MAX//10 and ret to make sure result will not out of range return ret*sign """ class Solution: def myAtoi(self, s: str) -> int: ls = s.strip() if len(ls) == 0 : return 0 i=0 ret = 0 sign = 1 MAX = 2147483647 MIN = -2147483648 if ls[i] =='+' or ls[i] == '-': sign = 1-2*(ls[i] == '-') i+=1 while i<len(ls) and ls[i]>='0'and ls[i]<='9': if ret > MAX//10 or (ret == MAX//10 and ord(ls[i])-ord('0') > MAX%10): return MAX if sign ==1 else MIN ret = ret*10+ (ord(ls[i])-ord('0')) i+=1 return ret*sign A = Solution() s = "2147483648" print(A.myAtoi(s))
def english_full_name(first=None, last=None, middle=None, prefix=None, suffix=None): fullname = None if first is None or last is None: raise ValueError("first and last must be specified") if middle: fullname = first + " " + middle + " " + last else: fullname = "{} {}".format(first, last) if prefix: fullname = prefix + " " + fullname if suffix: fullname = fullname + " " + suffix return fullname
del_items(0x80122C20) SetType(0x80122C20, "struct THEME_LOC themeLoc[50]") del_items(0x80123368) SetType(0x80123368, "int OldBlock[4]") del_items(0x80123378) SetType(0x80123378, "unsigned char L5dungeon[80][80]") del_items(0x80123008) SetType(0x80123008, "struct ShadowStruct SPATS[37]") del_items(0x8012310C) SetType(0x8012310C, "unsigned char BSTYPES[206]") del_items(0x801231DC) SetType(0x801231DC, "unsigned char L5BTYPES[206]") del_items(0x801232AC) SetType(0x801232AC, "unsigned char STAIRSUP[34]") del_items(0x801232D0) SetType(0x801232D0, "unsigned char L5STAIRSUP[34]") del_items(0x801232F4) SetType(0x801232F4, "unsigned char STAIRSDOWN[26]") del_items(0x80123310) SetType(0x80123310, "unsigned char LAMPS[10]") del_items(0x8012331C) SetType(0x8012331C, "unsigned char PWATERIN[74]") del_items(0x80122C10) SetType(0x80122C10, "unsigned char L5ConvTbl[16]") del_items(0x8012B5A8) SetType(0x8012B5A8, "struct ROOMNODE RoomList[81]") del_items(0x8012BBFC) SetType(0x8012BBFC, "unsigned char predungeon[40][40]") del_items(0x80129D38) SetType(0x80129D38, "int Dir_Xadd[5]") del_items(0x80129D4C) SetType(0x80129D4C, "int Dir_Yadd[5]") del_items(0x80129D60) SetType(0x80129D60, "struct ShadowStruct SPATSL2[2]") del_items(0x80129D70) SetType(0x80129D70, "unsigned char BTYPESL2[161]") del_items(0x80129E14) SetType(0x80129E14, "unsigned char BSTYPESL2[161]") del_items(0x80129EB8) SetType(0x80129EB8, "unsigned char VARCH1[18]") del_items(0x80129ECC) SetType(0x80129ECC, "unsigned char VARCH2[18]") del_items(0x80129EE0) SetType(0x80129EE0, "unsigned char VARCH3[18]") del_items(0x80129EF4) SetType(0x80129EF4, "unsigned char VARCH4[18]") del_items(0x80129F08) SetType(0x80129F08, "unsigned char VARCH5[18]") del_items(0x80129F1C) SetType(0x80129F1C, "unsigned char VARCH6[18]") del_items(0x80129F30) SetType(0x80129F30, "unsigned char VARCH7[18]") del_items(0x80129F44) SetType(0x80129F44, "unsigned char VARCH8[18]") del_items(0x80129F58) SetType(0x80129F58, "unsigned char VARCH9[18]") del_items(0x80129F6C) SetType(0x80129F6C, "unsigned char VARCH10[18]") del_items(0x80129F80) SetType(0x80129F80, "unsigned char VARCH11[18]") del_items(0x80129F94) SetType(0x80129F94, "unsigned char VARCH12[18]") del_items(0x80129FA8) SetType(0x80129FA8, "unsigned char VARCH13[18]") del_items(0x80129FBC) SetType(0x80129FBC, "unsigned char VARCH14[18]") del_items(0x80129FD0) SetType(0x80129FD0, "unsigned char VARCH15[18]") del_items(0x80129FE4) SetType(0x80129FE4, "unsigned char VARCH16[18]") del_items(0x80129FF8) SetType(0x80129FF8, "unsigned char VARCH17[14]") del_items(0x8012A008) SetType(0x8012A008, "unsigned char VARCH18[14]") del_items(0x8012A018) SetType(0x8012A018, "unsigned char VARCH19[14]") del_items(0x8012A028) SetType(0x8012A028, "unsigned char VARCH20[14]") del_items(0x8012A038) SetType(0x8012A038, "unsigned char VARCH21[14]") del_items(0x8012A048) SetType(0x8012A048, "unsigned char VARCH22[14]") del_items(0x8012A058) SetType(0x8012A058, "unsigned char VARCH23[14]") del_items(0x8012A068) SetType(0x8012A068, "unsigned char VARCH24[14]") del_items(0x8012A078) SetType(0x8012A078, "unsigned char VARCH25[18]") del_items(0x8012A08C) SetType(0x8012A08C, "unsigned char VARCH26[18]") del_items(0x8012A0A0) SetType(0x8012A0A0, "unsigned char VARCH27[18]") del_items(0x8012A0B4) SetType(0x8012A0B4, "unsigned char VARCH28[18]") del_items(0x8012A0C8) SetType(0x8012A0C8, "unsigned char VARCH29[18]") del_items(0x8012A0DC) SetType(0x8012A0DC, "unsigned char VARCH30[18]") del_items(0x8012A0F0) SetType(0x8012A0F0, "unsigned char VARCH31[18]") del_items(0x8012A104) SetType(0x8012A104, "unsigned char VARCH32[18]") del_items(0x8012A118) SetType(0x8012A118, "unsigned char VARCH33[18]") del_items(0x8012A12C) SetType(0x8012A12C, "unsigned char VARCH34[18]") del_items(0x8012A140) SetType(0x8012A140, "unsigned char VARCH35[18]") del_items(0x8012A154) SetType(0x8012A154, "unsigned char VARCH36[18]") del_items(0x8012A168) SetType(0x8012A168, "unsigned char VARCH37[18]") del_items(0x8012A17C) SetType(0x8012A17C, "unsigned char VARCH38[18]") del_items(0x8012A190) SetType(0x8012A190, "unsigned char VARCH39[18]") del_items(0x8012A1A4) SetType(0x8012A1A4, "unsigned char VARCH40[18]") del_items(0x8012A1B8) SetType(0x8012A1B8, "unsigned char HARCH1[14]") del_items(0x8012A1C8) SetType(0x8012A1C8, "unsigned char HARCH2[14]") del_items(0x8012A1D8) SetType(0x8012A1D8, "unsigned char HARCH3[14]") del_items(0x8012A1E8) SetType(0x8012A1E8, "unsigned char HARCH4[14]") del_items(0x8012A1F8) SetType(0x8012A1F8, "unsigned char HARCH5[14]") del_items(0x8012A208) SetType(0x8012A208, "unsigned char HARCH6[14]") del_items(0x8012A218) SetType(0x8012A218, "unsigned char HARCH7[14]") del_items(0x8012A228) SetType(0x8012A228, "unsigned char HARCH8[14]") del_items(0x8012A238) SetType(0x8012A238, "unsigned char HARCH9[14]") del_items(0x8012A248) SetType(0x8012A248, "unsigned char HARCH10[14]") del_items(0x8012A258) SetType(0x8012A258, "unsigned char HARCH11[14]") del_items(0x8012A268) SetType(0x8012A268, "unsigned char HARCH12[14]") del_items(0x8012A278) SetType(0x8012A278, "unsigned char HARCH13[14]") del_items(0x8012A288) SetType(0x8012A288, "unsigned char HARCH14[14]") del_items(0x8012A298) SetType(0x8012A298, "unsigned char HARCH15[14]") del_items(0x8012A2A8) SetType(0x8012A2A8, "unsigned char HARCH16[14]") del_items(0x8012A2B8) SetType(0x8012A2B8, "unsigned char HARCH17[14]") del_items(0x8012A2C8) SetType(0x8012A2C8, "unsigned char HARCH18[14]") del_items(0x8012A2D8) SetType(0x8012A2D8, "unsigned char HARCH19[14]") del_items(0x8012A2E8) SetType(0x8012A2E8, "unsigned char HARCH20[14]") del_items(0x8012A2F8) SetType(0x8012A2F8, "unsigned char HARCH21[14]") del_items(0x8012A308) SetType(0x8012A308, "unsigned char HARCH22[14]") del_items(0x8012A318) SetType(0x8012A318, "unsigned char HARCH23[14]") del_items(0x8012A328) SetType(0x8012A328, "unsigned char HARCH24[14]") del_items(0x8012A338) SetType(0x8012A338, "unsigned char HARCH25[14]") del_items(0x8012A348) SetType(0x8012A348, "unsigned char HARCH26[14]") del_items(0x8012A358) SetType(0x8012A358, "unsigned char HARCH27[14]") del_items(0x8012A368) SetType(0x8012A368, "unsigned char HARCH28[14]") del_items(0x8012A378) SetType(0x8012A378, "unsigned char HARCH29[14]") del_items(0x8012A388) SetType(0x8012A388, "unsigned char HARCH30[14]") del_items(0x8012A398) SetType(0x8012A398, "unsigned char HARCH31[14]") del_items(0x8012A3A8) SetType(0x8012A3A8, "unsigned char HARCH32[14]") del_items(0x8012A3B8) SetType(0x8012A3B8, "unsigned char HARCH33[14]") del_items(0x8012A3C8) SetType(0x8012A3C8, "unsigned char HARCH34[14]") del_items(0x8012A3D8) SetType(0x8012A3D8, "unsigned char HARCH35[14]") del_items(0x8012A3E8) SetType(0x8012A3E8, "unsigned char HARCH36[14]") del_items(0x8012A3F8) SetType(0x8012A3F8, "unsigned char HARCH37[14]") del_items(0x8012A408) SetType(0x8012A408, "unsigned char HARCH38[14]") del_items(0x8012A418) SetType(0x8012A418, "unsigned char HARCH39[14]") del_items(0x8012A428) SetType(0x8012A428, "unsigned char HARCH40[14]") del_items(0x8012A438) SetType(0x8012A438, "unsigned char USTAIRS[34]") del_items(0x8012A45C) SetType(0x8012A45C, "unsigned char DSTAIRS[34]") del_items(0x8012A480) SetType(0x8012A480, "unsigned char WARPSTAIRS[34]") del_items(0x8012A4A4) SetType(0x8012A4A4, "unsigned char CRUSHCOL[20]") del_items(0x8012A4B8) SetType(0x8012A4B8, "unsigned char BIG1[10]") del_items(0x8012A4C4) SetType(0x8012A4C4, "unsigned char BIG2[10]") del_items(0x8012A4D0) SetType(0x8012A4D0, "unsigned char BIG5[10]") del_items(0x8012A4DC) SetType(0x8012A4DC, "unsigned char BIG8[10]") del_items(0x8012A4E8) SetType(0x8012A4E8, "unsigned char BIG9[10]") del_items(0x8012A4F4) SetType(0x8012A4F4, "unsigned char BIG10[10]") del_items(0x8012A500) SetType(0x8012A500, "unsigned char PANCREAS1[32]") del_items(0x8012A520) SetType(0x8012A520, "unsigned char PANCREAS2[32]") del_items(0x8012A540) SetType(0x8012A540, "unsigned char CTRDOOR1[20]") del_items(0x8012A554) SetType(0x8012A554, "unsigned char CTRDOOR2[20]") del_items(0x8012A568) SetType(0x8012A568, "unsigned char CTRDOOR3[20]") del_items(0x8012A57C) SetType(0x8012A57C, "unsigned char CTRDOOR4[20]") del_items(0x8012A590) SetType(0x8012A590, "unsigned char CTRDOOR5[20]") del_items(0x8012A5A4) SetType(0x8012A5A4, "unsigned char CTRDOOR6[20]") del_items(0x8012A5B8) SetType(0x8012A5B8, "unsigned char CTRDOOR7[20]") del_items(0x8012A5CC) SetType(0x8012A5CC, "unsigned char CTRDOOR8[20]") del_items(0x8012A5E0) SetType(0x8012A5E0, "int Patterns[10][100]") del_items(0x801315F0) SetType(0x801315F0, "unsigned char lockout[40][40]") del_items(0x80131350) SetType(0x80131350, "unsigned char L3ConvTbl[16]") del_items(0x80131360) SetType(0x80131360, "unsigned char L3UP[20]") del_items(0x80131374) SetType(0x80131374, "unsigned char L3DOWN[20]") del_items(0x80131388) SetType(0x80131388, "unsigned char L3HOLDWARP[20]") del_items(0x8013139C) SetType(0x8013139C, "unsigned char L3TITE1[34]") del_items(0x801313C0) SetType(0x801313C0, "unsigned char L3TITE2[34]") del_items(0x801313E4) SetType(0x801313E4, "unsigned char L3TITE3[34]") del_items(0x80131408) SetType(0x80131408, "unsigned char L3TITE6[42]") del_items(0x80131434) SetType(0x80131434, "unsigned char L3TITE7[42]") del_items(0x80131460) SetType(0x80131460, "unsigned char L3TITE8[20]") del_items(0x80131474) SetType(0x80131474, "unsigned char L3TITE9[20]") del_items(0x80131488) SetType(0x80131488, "unsigned char L3TITE10[20]") del_items(0x8013149C) SetType(0x8013149C, "unsigned char L3TITE11[20]") del_items(0x801314B0) SetType(0x801314B0, "unsigned char L3ISLE1[14]") del_items(0x801314C0) SetType(0x801314C0, "unsigned char L3ISLE2[14]") del_items(0x801314D0) SetType(0x801314D0, "unsigned char L3ISLE3[14]") del_items(0x801314E0) SetType(0x801314E0, "unsigned char L3ISLE4[14]") del_items(0x801314F0) SetType(0x801314F0, "unsigned char L3ISLE5[10]") del_items(0x801314FC) SetType(0x801314FC, "unsigned char L3ANVIL[244]") del_items(0x8013640C) SetType(0x8013640C, "unsigned char dung[20][20]") del_items(0x8013659C) SetType(0x8013659C, "unsigned char hallok[20]") del_items(0x801365B0) SetType(0x801365B0, "unsigned char L4dungeon[80][80]") del_items(0x80137EB0) SetType(0x80137EB0, "unsigned char L4ConvTbl[16]") del_items(0x80137EC0) SetType(0x80137EC0, "unsigned char L4USTAIRS[42]") del_items(0x80137EEC) SetType(0x80137EEC, "unsigned char L4TWARP[42]") del_items(0x80137F18) SetType(0x80137F18, "unsigned char L4DSTAIRS[52]") del_items(0x80137F4C) SetType(0x80137F4C, "unsigned char L4PENTA[52]") del_items(0x80137F80) SetType(0x80137F80, "unsigned char L4PENTA2[52]") del_items(0x80137FB4) SetType(0x80137FB4, "unsigned char L4BTYPES[140]")
# -*- coding: utf-8 -*- def pytest_addoption(parser): group = parser.getgroup("portion") group.addoption( "--portion", action="store", help='Select a part of all the collected tests in the form "i/n" or "start:end"' ) def slice_fraction(sequence, i, n): """ Split a sequence in `n` slices and then return the i-th (1-indexed). The last slice will be longer if the sequence can't be splitted even-sized or n is greater than the sequence's size. """ total = len(sequence) per_slice = total // n if not per_slice: return sequence if i == n else type(sequence)() ranges = [[n, n + per_slice] for n in range(0, total, per_slice)] # fix last if total % n != 0: ranges = ranges[:-1] ranges[-1][1] = None portion = dict(enumerate(ranges, 1))[i] return sequence[slice(*portion)] def slice_percentage_range(sequence, start, end): """ return the slice range between coefficient `start` and `end` where start and end represents fractions between 0 and 1. Corner elements may be repeated in consecutive slices. """ total = len(sequence) return slice(int(round(total * start)), int(total * end) + 1) def pytest_collection_modifyitems(config, items): try: portion = config.getoption("portion") or config.getini("portion") except ValueError: portion = None deselected = [] if not portion: return elif "/" in portion: i, n = [int(n) for n in portion.split("/")] selected = slice_fraction(items, i, n) for range_number in range(1, n + 1): if range_number == i: continue deselected.extend(slice_fraction(items, range_number, n)) elif ":" in portion: start, end = [float(n) for n in portion.split(":")] slice_selected = slice_percentage_range(items, start, end) selected = items[slice_selected] deselected.extend(items[:slice_selected.start]) deselected.extend(items[slice_selected.stop:]) items[:] = selected config.hook.pytest_deselected(items=deselected)
def normalize_bbox(bbox, size): return [ int(1000 * bbox[0] / size[0]), int(1000 * bbox[1] / size[1]), int(1000 * bbox[2] / size[0]), int(1000 * bbox[3] / size[1]), ]
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: nums.sort() result = set() l = len(nums) for a in range(l - 3): if a > 0 and nums[a] == nums[a - 1]: continue if nums[a] + nums[a + 1] + nums[a + 2] + nums[a + 3] > target: break if nums[a] + nums[l - 3] + nums[l - 2] + nums[l - 1] < target: continue for b in range(a + 1, l - 2): if b > a + 1 and nums[b] == nums[b - 1]: continue if nums[a] + nums[b] + nums[b + 1] + nums[b + 2] > target: break if nums[a] + nums[b] + nums[l - 2] + nums[l - 1] < target: continue c, d = b + 1, l - 1 rem_target = target - (nums[a] + nums[b]) while c < d: if nums[c] + nums[d] > rem_target: d -= 1 elif nums[c] + nums[d] < rem_target: c += 1 else: result.add((nums[a], nums[b], nums[c], nums[d])) c += 1 d -= 1 return result
a = int(input()) b = int(input()) for i in range(a,b+1): if i%2==0: print(i)
''' BFS is a tree traversal method. We search the graph level by level. - The concept is a layered traversal. - This means we start at the root of the node and we begin a "levelled" traversal. Let's define the **level or depth of a given node the amount of edges between that node and the root**. Let's look at the following tree as an example: ``` 1 / \ 2 3 / \ 4 5 ``` **Level 0** All nodes at distance 0 from root. `{1}` **Level 1** All nodes at distance 1 from root. `{2, 3}` **Level 2** All nodes at distance 2 from root. `{4, 5}` **Traversal Example** Like mentioned above a valid BFS traversal could visit the nodes in the graph in the following order: `1->2->3->4->5` Another valid BFS traversal could be: `1->3->2->5->4` Let's look at an iterative and recursive BFS implmentation. ''' class TreeNode: def __init__(self, val, left, right): self.val = val self.left = left self.right = right def visitNode(node): if node: print(node.val) def bfsIterative(root): if not root: return q = [root] while q: current = q.pop(0) if not current: return visitNode(current) if current.left: q.append(current.left) if current.right: q.append(current.right) def recursiveBfs(root): if not root: return def helper(q): if not q: return current = q.pop(0) if not current: return visitNode(current) if current.left: q.append(current.left) if current.right: q.append(current.right) helper(q) q = [root] helper(q)
defs = { 'season': { 'type': 'numeric', 'options': { 'min_length': 1, 'max_length': 2 } }, 'episode': { 'type': 'numeric', 'options': { 'min_length': 1, 'max_length': 2 } }, 'shot': { 'type': 'numeric', 'options': { 'min_length': 1, 'max_length': 4 } }, 'version': { 'type': 'numeric', 'options': { 'min_length': 1, 'max_length': 4 } } } motion_template = { 'name': 'motion', 'template': 'S${season}_EP${episode}_MOTION_SH${shot}_V${version}', 'definitions': defs }
def main(): h,w = map(int,input().split()) maze = [] for _ in range(h): maze.append(list(input())) dx = [1,0,-1,0] dy = [0,1,0,-1] que = [] que.append([0,0]) d = [[-1 for _ in range(w)] for _ in range(h)] d[0][0] = 0 while len(que)!=0: qx,qy = que.pop() for i in range(4): nx = qx + dx[i] ny = qy + dy[i] if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] == "." and d[nx][ny] == -1: d[nx][ny] = d[qx][qy] + 1 que.append([nx,ny]) if d[h-1][w-1] == -1: print(-1) return cnt = 0 for i in range(h): for j in range(w): if maze[i][j] == ".": cnt += 1 print(cnt-d[h-1][w-1]-1) if __name__ == "__main__": main()
class RuleCollection(object): def __init__(self, name, ruleset_list, result_on_match): self.name = name self.ruleset_list = ruleset_list self.result_on_match = result_on_match def check(self, data): results = [] for ruleset in self.ruleset_list: results.append(ruleset.check(data)) if True in results and False not in results: return self.result_on_match else: return None
class A: def __init__(self): self.nr=int(input()) self.nc=int(input()) self.matrix=[] for i in range(self.nr): self.col=[] for j in range(self.nc): self.element=int(input()) self.col.append(self.element) self.matrix.append(self.col) def printMatrix(self): for i in range(0,self.nr): for j in range(0,self.nc): print(self.matrix[i][j],end=" ") print() #def sumMat(self,A,B): a=A() b=A() #a.printMatrix()
poesia = list() poesia = input().split(" ") while "*" not in poesia[0]: aux = poesia[0] aux = aux[0].lower() tam = 0 for i in poesia: if i[0].lower() == aux: tam+=1 if tam == len(poesia): print("Y") else: print("N") poesia.clear() poesia = input().split(" ")
# Time: O(n^2) # Space: O(n^2) # On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j). # # Now rain starts to fall. At time t, the depth of the water everywhere is t. # You can swim from a square to another 4-directionally adjacent square # if and only if the elevation of both squares individually are at most t. # You can swim infinite distance in zero time. Of course, # you must stay within the boundaries of the grid during your swim. # # You start at the top left square (0, 0). # What is the least time until you can reach the bottom right square (N-1, N-1)? # # Example 1: # Input: [[0,2],[1,3]] # Output: 3 # Explanation: # At time 0, you are in grid location (0, 0). # You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. # # You cannot reach point (1, 1) until time 3. # When the depth of water is 3, we can swim anywhere inside the grid. # Example 2: # # Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] # Output: 16 # Explanation: # 0 1 2 3 4 # 24 23 22 21 5 # 12 13 14 15 16 # 11 17 18 19 20 # 10 9 8 7 6 # # The final route is marked in bold. # We need to wait until time 16 so that (0, 0) and (4, 4) are connected. # # Note: # - 2 <= N <= 50. # - grid[i][j] is a permutation of [0, ..., N*N - 1]. class UnionFind(object): def __init__(self, n): self.set = range(n) def find_set(self, x): if self.set[x] != x: self.set[x] = self.find_set(self.set[x]) # path compression. return self.set[x] def union_set(self, x, y): x_root, y_root = map(self.find_set, (x, y)) if x_root == y_root: return False self.set[min(x_root, y_root)] = max(x_root, y_root) return True class Solution(object): def swimInWater(self, grid): """ :type grid: List[List[int]] :rtype: int """ n = len(grid) positions = [None] * (n**2) for i in xrange(n): for j in xrange(n): positions[grid[i][j]] = (i, j) directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) union_find = UnionFind(n**2) for elevation in xrange(n**2): i, j = positions[elevation] for direction in directions: x, y = i+direction[0], j+direction[1] if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation: union_find.union_set(i*n+j, x*n+y) if union_find.find_set(0) == union_find.find_set(n**2-1): return elevation return n**2-1
class CommonWriter: """ Writer interface """ def write(self, dictionary): raise Exception("unimplemented")
# # PySNMP MIB module ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH # Produced by pysmi-0.3.4 at Wed May 1 13:06:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint") ecExperimental, = mibBuilder.importSymbols("ESSENTIAL-COMMUNICATIONS-GLOBAL-REG", "ecExperimental") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, enterprises, Bits, iso, Integer32, ObjectIdentity, MibIdentifier, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, NotificationType, Counter64, TimeTicks, IpAddress, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "enterprises", "Bits", "iso", "Integer32", "ObjectIdentity", "MibIdentifier", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "NotificationType", "Counter64", "TimeTicks", "IpAddress", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") essentialCommunications = MibIdentifier((1, 3, 6, 1, 4, 1, 2159)) ecRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1)) ecProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3)) ecExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 6)) hippiSwitchMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 6, 1)) hippiSwitchMIBv103 = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1)) switchObjs = MibIdentifier((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1)) switchDescription = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: switchDescription.setStatus('mandatory') if mibBuilder.loadTexts: switchDescription.setDescription('Returns the description, vendor, and version numbers of the switch.') switchNumOfPorts = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: switchNumOfPorts.setStatus('mandatory') if mibBuilder.loadTexts: switchNumOfPorts.setDescription('The number of slots in this switch. (Max number of media access cards).') sccDescription = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sccDescription.setStatus('mandatory') if mibBuilder.loadTexts: sccDescription.setDescription('The model, vendor, and version number of the switch control card.') sccDateTime = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sccDateTime.setStatus('mandatory') if mibBuilder.loadTexts: sccDateTime.setDescription('The date/time in the real time clock. Format: yyyymmddhhmmss.') sccAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("reset", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sccAdminStatus.setStatus('mandatory') if mibBuilder.loadTexts: sccAdminStatus.setDescription('The desired state of the switch.') sccOperStatus = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("up", 1), ("reseting", 2), ("busy", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sccOperStatus.setStatus('mandatory') if mibBuilder.loadTexts: sccOperStatus.setDescription('The current state of the switch. SNMP operations can not occur when the switch is busy. SNMP operations can not occur when the switch is resetting.') backPlaneTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7), ) if mibBuilder.loadTexts: backPlaneTable.setStatus('mandatory') if mibBuilder.loadTexts: backPlaneTable.setDescription('This table represent all of the slots in a HIPPI switch. None of the rows can be added to or deleted by the user.') backPlaneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "backPlaneIndex")) if mibBuilder.loadTexts: backPlaneEntry.setStatus('mandatory') if mibBuilder.loadTexts: backPlaneEntry.setDescription('A row in the table describing one slot in the switch backplane. ') backPlaneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 1), Gauge32()) if mibBuilder.loadTexts: backPlaneIndex.setStatus('mandatory') if mibBuilder.loadTexts: backPlaneIndex.setDescription('The table index for this slot on the backplane.') backPlaneNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: backPlaneNumber.setStatus('mandatory') if mibBuilder.loadTexts: backPlaneNumber.setDescription('The slot number as seen printed on the switch (backPlaneIndex + 1)') backPlaneCard = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("none", 0), ("unknown", 1), ("parallel", 2), ("serial", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: backPlaneCard.setStatus('mandatory') if mibBuilder.loadTexts: backPlaneCard.setDescription('The type of MIC present in this slot of the backplane on the switch') mICPowerUpInitError = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICPowerUpInitError.setStatus('mandatory') if mibBuilder.loadTexts: mICPowerUpInitError.setDescription('True if error detected by MIC on start-up.') mICHippiParityBurstError = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICHippiParityBurstError.setStatus('mandatory') if mibBuilder.loadTexts: mICHippiParityBurstError.setDescription('Valid the SMIC only. Type of parity error.') mICLinkReady = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICLinkReady.setStatus('mandatory') if mibBuilder.loadTexts: mICLinkReady.setDescription('Valid the SMIC only. True if link ready asserted.') mICSourceInterconnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICSourceInterconnect.setStatus('mandatory') if mibBuilder.loadTexts: mICSourceInterconnect.setDescription('Source interconnect is valid for the PMIC only.') mICSourceRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICSourceRequest.setStatus('mandatory') if mibBuilder.loadTexts: mICSourceRequest.setDescription('True if source request is asserted.') mICSourceConnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICSourceConnect.setStatus('mandatory') if mibBuilder.loadTexts: mICSourceConnect.setDescription('True if source connect is asserted.') mICSourceLastConnectAttempt = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICSourceLastConnectAttempt.setStatus('mandatory') if mibBuilder.loadTexts: mICSourceLastConnectAttempt.setDescription('True if last source request was successful.') mICDestinationInterconnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICDestinationInterconnect.setStatus('mandatory') if mibBuilder.loadTexts: mICDestinationInterconnect.setDescription('True if destination interconnect is asserted.') mICDestinationRequest = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 12), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICDestinationRequest.setStatus('mandatory') if mibBuilder.loadTexts: mICDestinationRequest.setDescription('True if destination request is asserted.') mICDestinationConnect = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 13), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICDestinationConnect.setStatus('mandatory') if mibBuilder.loadTexts: mICDestinationConnect.setDescription('True if destination connect is asserted.') mICByteCounterOverflow = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 14), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICByteCounterOverflow.setStatus('mandatory') if mibBuilder.loadTexts: mICByteCounterOverflow.setDescription('The number of times the byte counter has over-flowed.') mICNumberOfBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 15), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICNumberOfBytes.setStatus('mandatory') if mibBuilder.loadTexts: mICNumberOfBytes.setDescription('The number of bytes that have passed through the MIC.') mICNumberOfPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 16), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICNumberOfPackets.setStatus('mandatory') if mibBuilder.loadTexts: mICNumberOfPackets.setDescription('The number of times packets has been asserted.') mICConnectsSuccessful = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 7, 1, 17), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mICConnectsSuccessful.setStatus('mandatory') if mibBuilder.loadTexts: mICConnectsSuccessful.setDescription('The number of times this MIC has connected since reset.') sourceRouteTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8), ) if mibBuilder.loadTexts: sourceRouteTable.setStatus('mandatory') if mibBuilder.loadTexts: sourceRouteTable.setDescription('This table holds all of the source routes for this switch. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)') sourceRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "srcIndex")) if mibBuilder.loadTexts: sourceRouteEntry.setStatus('mandatory') if mibBuilder.loadTexts: sourceRouteEntry.setDescription('One row in the source route table.') srcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: srcIndex.setStatus('mandatory') if mibBuilder.loadTexts: srcIndex.setDescription('The row number for this row of the table.') srcRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 8, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: srcRoute.setStatus('mandatory') if mibBuilder.loadTexts: srcRoute.setDescription('One source route. FORMAT: OutputPort InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)') srcWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 9), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: srcWriteRow.setStatus('mandatory') if mibBuilder.loadTexts: srcWriteRow.setDescription('Setting this variable alters source routes. FORMAT: OutputPortList InputPortList Status. Output port is 0 to 15 Input port is 0 to 15 List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2. Status is 0 (disabled) or 1 (enabled)') destRouteTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10), ) if mibBuilder.loadTexts: destRouteTable.setStatus('mandatory') if mibBuilder.loadTexts: destRouteTable.setDescription('This table holds all of destination routes (logical address routes) for this switch. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15 Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.') destRouteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "destIndex")) if mibBuilder.loadTexts: destRouteEntry.setStatus('mandatory') if mibBuilder.loadTexts: destRouteEntry.setDescription('A row in the destination route table.') destIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: destIndex.setStatus('mandatory') if mibBuilder.loadTexts: destIndex.setDescription('The index for this row of the table.') destRoute = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 10, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: destRoute.setStatus('mandatory') if mibBuilder.loadTexts: destRoute.setDescription('One Destination Route. FORMAT: LogicalAddress InputPortList Huntgroup. LogicalAddress is 0 to 4095. Input port is 0 to 15. Huntgroup is 0 to 31. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.') destWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 11), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: destWriteRow.setStatus('mandatory') if mibBuilder.loadTexts: destWriteRow.setDescription('Setting this variable will alter the desitination routes. FORMAT: LogicalAddressList Huntgroup InputPortList. LogicalAddress is 0 to 4095. Huntgroup is 0 to 31. 31 will disable this route. Input port is 0 to 15. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.') huntGroupTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12), ) if mibBuilder.loadTexts: huntGroupTable.setStatus('mandatory') if mibBuilder.loadTexts: huntGroupTable.setDescription('This table holds all of the huntgroups for this switch. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.') huntGroupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "hg")) if mibBuilder.loadTexts: huntGroupEntry.setStatus('mandatory') if mibBuilder.loadTexts: huntGroupEntry.setDescription('A row in the huntgroup table.') hg = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hg.setStatus('mandatory') if mibBuilder.loadTexts: hg.setDescription('The huntgroup number.') hgOutPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 12, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: hgOutPortList.setStatus('mandatory') if mibBuilder.loadTexts: hgOutPortList.setDescription('The definition of one Huntgroup. FORMAT: Huntgroup ( OutportList ) Huntgroup is 0 to 31. OutportList is an orderd list of output ports in Huntgroup.') hgLWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 13), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hgLWriteRow.setStatus('mandatory') if mibBuilder.loadTexts: hgLWriteRow.setDescription('Setting this variable will alter the huntgroup table by setting every huntgroup in list to include outPortList. FORMAT: HuntgroupList OutportList Huntgroup is 0 to 31. Outport is 0 to 15 and 16. 16 will clear the huntgroup. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.') huntGroupOrderTable = MibTable((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14), ) if mibBuilder.loadTexts: huntGroupOrderTable.setStatus('mandatory') if mibBuilder.loadTexts: huntGroupOrderTable.setDescription('This table holds all of the huntgroup order information for this switch. i.e. The order huntgroups are processed in when more than one huntgroup contends for the same output port. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.') huntGroupOrderEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1), ).setIndexNames((0, "ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", "hg")) if mibBuilder.loadTexts: huntGroupOrderEntry.setStatus('mandatory') if mibBuilder.loadTexts: huntGroupOrderEntry.setDescription("One record on an output port's huntgroup priority.") hgOrderIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 1), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hgOrderIndex.setStatus('mandatory') if mibBuilder.loadTexts: hgOrderIndex.setDescription('The backplane slot number containing output port.') hgOrderList = MibTableColumn((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 14, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: hgOrderList.setStatus('mandatory') if mibBuilder.loadTexts: hgOrderList.setDescription("An ordered list of an output port's huntgroup priority. FORMAT: OutputPort HuntGroupList OutputPort is 0 to 15. Huntgroup is 0 to 31. List is an ordered list of huntgroups.") hgOWriteRow = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 15), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hgOWriteRow.setStatus('mandatory') if mibBuilder.loadTexts: hgOWriteRow.setDescription('Setting this variable will alter the huntgroup order table. FORMAT: OutputPort HuntGroupList Output port is 0 to 15. Huntgroup is 0 to 31. Huntgroup must contain output port in its output port list. List is NUMBER or NUMBER1-NUMBER2 where NUMBER1 < NUMBER2.') hgSaveRestore = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("save", 1), ("restore", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hgSaveRestore.setStatus('mandatory') if mibBuilder.loadTexts: hgSaveRestore.setDescription(' Writting a 1 saves all hunt group information on the switch. Writting a 2 restores all hunt group information on the switch.') routesSaveRestore = MibScalar((1, 3, 6, 1, 4, 1, 2159, 1, 3, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("save", 1), ("restore", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: routesSaveRestore.setStatus('mandatory') if mibBuilder.loadTexts: routesSaveRestore.setDescription(' Writting a 1 saves all source/destination routes on the switch. Writting a 2 restores all source/destination routes on the switch.') mibBuilder.exportSymbols("ESSENTIAL-COMMUNICATIONS-HIPPI-SWITCH", srcWriteRow=srcWriteRow, hg=hg, hippiSwitchMIBv103=hippiSwitchMIBv103, switchDescription=switchDescription, backPlaneTable=backPlaneTable, mICNumberOfPackets=mICNumberOfPackets, backPlaneNumber=backPlaneNumber, hgLWriteRow=hgLWriteRow, mICPowerUpInitError=mICPowerUpInitError, sccAdminStatus=sccAdminStatus, huntGroupOrderEntry=huntGroupOrderEntry, sccDescription=sccDescription, backPlaneCard=backPlaneCard, huntGroupTable=huntGroupTable, ecProducts=ecProducts, mICHippiParityBurstError=mICHippiParityBurstError, srcRoute=srcRoute, destWriteRow=destWriteRow, switchNumOfPorts=switchNumOfPorts, destRoute=destRoute, sourceRouteTable=sourceRouteTable, destIndex=destIndex, hgOWriteRow=hgOWriteRow, mICSourceRequest=mICSourceRequest, mICDestinationInterconnect=mICDestinationInterconnect, hgOrderIndex=hgOrderIndex, ecRoot=ecRoot, destRouteTable=destRouteTable, hgSaveRestore=hgSaveRestore, sccOperStatus=sccOperStatus, ecExperimental=ecExperimental, mICSourceLastConnectAttempt=mICSourceLastConnectAttempt, backPlaneIndex=backPlaneIndex, sccDateTime=sccDateTime, hgOutPortList=hgOutPortList, mICSourceConnect=mICSourceConnect, mICDestinationConnect=mICDestinationConnect, mICByteCounterOverflow=mICByteCounterOverflow, srcIndex=srcIndex, mICLinkReady=mICLinkReady, switchObjs=switchObjs, mICSourceInterconnect=mICSourceInterconnect, backPlaneEntry=backPlaneEntry, huntGroupEntry=huntGroupEntry, routesSaveRestore=routesSaveRestore, sourceRouteEntry=sourceRouteEntry, hgOrderList=hgOrderList, mICDestinationRequest=mICDestinationRequest, huntGroupOrderTable=huntGroupOrderTable, hippiSwitchMIB=hippiSwitchMIB, mICConnectsSuccessful=mICConnectsSuccessful, mICNumberOfBytes=mICNumberOfBytes, essentialCommunications=essentialCommunications, destRouteEntry=destRouteEntry)
def ordenada(lista): ordem = True for index in range(len(lista)-1): if lista[index] > lista[index + 1]: ordem = False return ordem
def credits(): print('\nObrigado por jogar !\n') print('-' * 20) print('CRÉDITOS FINAIS \nDiretor Geral - Álef Ádonis\nProgramador - Álef Ádonis\nRoteirista - Álef Ádonis\nEditor Chefe - Álef Ádonis\n\nUM PEQUENO GESTO PARA DEMOSTRAR MEU AMOR') print('-' *20)
DATA = '../data/articles/' BUILDINGS = "../data/buildings/" OUTPUT = '../output/' PHOTO_LOC = '/Users/elisabethsilver/Box/SIB/photos/' DATA_FNAME = f"{DATA}uni_data.xlsx" FMTD_DATA_FNAME = f"{DATA}uni_data_year_formatted.xlsx" LINK_FNAME = f"{DATA}uni_links.csv" YEAR_LINK_FNAME = f"{DATA}uni_links_year.csv" GDRIVE = "/Users/elisabethsilver/Google Drive/Seeing is believing/News article study/2019 Data/"
def generate(env): env.Replace( MODE='Release' ) env.Append( CPPDEFINES={'RELEASE': None}, CCFLAGS=[ '-O3', ], ) def exists(env): return 1
def binomial( k, n ): if n < k or n < 0 or k < 0: raise ValueError("n > k > 0") if k == 1 or k == (n-1): return n elif k == 0 or k == n: return 1 return binomial( k, n - 1 ) + binomial( k-1, n-1) print("( a nad b )") a = int(input("A = ")) b = int(input("B = ")) print( binomial( b, a ) )
__all__ = ['merge_lists'] # HELPER FUNCTION FOR MERGING LISTS def merge_lists(*args, **kwargs): merged = [] for seq in args: for element in seq: merged.append(element) return merged
def tablefy(data, column=None, gutter=1, width=79): """ Convert a list of strings into being a table, displaying in a left-to-right and top-to-bottom pattern. This does not sort the values. :param data: list of strings :param column: width of column, if None, detected :param gutter: width of gutter :param width: width of entire table to fill :returns: newline separated string """ if not data: return "" lines = [] if column is None: column = max([len(s) for s in data]) per_line = max(int(width / column), 1) gutter_chars = " " * gutter items = [] for entry in data: items.append(entry.ljust(column)) if len(items) == per_line: lines.append(gutter_chars.join(items)) items = [] if items: lines.append(gutter_chars.join(items)) return "\n".join(lines)
def sockMerchant(n, ar): ar_no_duplicates = dict.fromkeys(ar) pairs = 0 for sock in ar_no_duplicates: ocurrences = ar.count(sock) print("ocurrences of {} in {} -> {}".format(sock, ar, ocurrences)) if ocurrences % 2 == 0: pairs += ocurrences / 2 elif ocurrences % 2 == 1 and ocurrences > 2: pairs += (ocurrences - 1) / 2 return int(pairs) n = 9 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20] print(sockMerchant(n, ar))
nome = input() salfixo = float(input()) qtdvendas = float(input()) bonus = float(qtdvendas * (15/100)) total = salfixo + bonus print ('TOTAL = R$ %0.2f' %total)
""" The ``density`` module contains functions to calculate the density and temperature at hub height of a wind turbine. SPDX-FileCopyrightText: 2019 oemof developer group <contact@oemof.org> SPDX-License-Identifier: MIT """ def barometric(pressure, pressure_height, hub_height, temperature_hub_height): r""" Calculates the density of air at hub height using the barometric height equation. This function is carried out when the parameter `density_model` of an instance of the :class:`~.modelchain.ModelChain` class is 'barometric'. Parameters ---------- pressure : :pandas:`pandas.Series<series>` or numpy.array Air pressure in Pa. pressure_height : float Height in m for which the parameter `pressure` applies. hub_height : float Hub height of wind turbine in m. temperature_hub_height : :pandas:`pandas.Series<series>` or numpy.array Air temperature at hub height in K. Returns ------- :pandas:`pandas.Series<series>` or numpy.array Density of air at hub height in kg/m³. Returns a pandas.Series if one of the input parameters is a pandas.Series. Notes ----- The following equation is used [1]_ [2]_ : .. math:: \rho_{hub}=\left(p/100-\left(h_{hub}-h_{p,data}\right) \cdot\frac{1}{8}\right)\cdot \frac{\rho_0 T_0\cdot 100}{p_0 T_{hub}} with: T: temperature [K], h: height [m], :math:`\rho`: density [kg/m³], p: pressure [Pa] :math:`h_{p,data}` is the height of the measurement or model data for pressure, :math:`p_0` the ambient air pressure, :math:`\rho_0` the ambient density of air, :math:`T_0` the ambient temperature and :math:`T_{hub}` the temperature at hub height :math:`h_{hub}`. Assumptions: * Pressure gradient of -1/8 hPa/m References ---------- .. [1] Hau, E.: "Windkraftanlagen - Grundlagen, Technik, Einsatz, Wirtschaftlichkeit". 4. Auflage, Springer-Verlag, 2008, p. 560 .. [2] Deutscher Wetterdienst: http://www.dwd.de/DE/service/lexikon/begriffe/D/Druckgradient_pdf.pdf?__blob=publicationFile&v=4 """ return ( (pressure / 100 - (hub_height - pressure_height) * 1 / 8) * 1.225 * 288.15 * 100 / (101330 * temperature_hub_height) ) def ideal_gas(pressure, pressure_height, hub_height, temperature_hub_height): r""" Calculates the density of air at hub height using the ideal gas equation. This function is carried out when the parameter `density_model` of an instance of the :class:`~.modelchain.ModelChain` class is 'ideal_gas'. Parameters ---------- pressure : :pandas:`pandas.Series<series>` or numpy.array Air pressure in Pa. pressure_height : float Height in m for which the parameter `pressure` applies. hub_height : float Hub height of wind turbine in m. temperature_hub_height : :pandas:`pandas.Series<series>` or numpy.array Air temperature at hub height in K. Returns ------- :pandas:`pandas.Series<series>` or numpy.array Density of air at hub height in kg/m³. Returns a pandas.Series if one of the input parameters is a pandas.Series. Notes ----- The following equations are used [1]_ [2]_ [3]_: .. math:: \rho_{hub}=p_{hub}/ (R_s T_{hub}) and [4]_: .. math:: p_{hub}=\left(p/100-\left(h_{hub}-h_{p,data}\right)\cdot \frac{1}{8}\right)\cdot 100 with: T: temperature [K], :math:`\rho`: density [kg/m³], p: pressure [Pa] :math:`h_{p,data}` is the height of the measurement or model data for pressure, :math:`R_s` is the specific gas constant of dry air (287.058 J/(kg*K)) and :math:`p_{hub}` is the pressure at hub height :math:`h_{hub}`. References ---------- .. [1] Ahrendts J., Kabelac S.: "Das Ingenieurwissen - Technische Thermodynamik". 34. Auflage, Springer-Verlag, 2014, p. 23 .. [2] Biank, M.: "Methodology, Implementation and Validation of a Variable Scale Simulation Model for Windpower based on the Georeferenced Installation Register of Germany". Master's Thesis at RLI, 2014, p. 57 .. [3] Knorr, K.: "Modellierung von raum-zeitlichen Eigenschaften der Windenergieeinspeisung für wetterdatenbasierte Windleistungssimulationen". Universität Kassel, Diss., 2016, p. 97 .. [4] Deutscher Wetterdienst: http://www.dwd.de/DE/service/lexikon/begriffe/D/Druckgradient_pdf.pdf?__blob=publicationFile&v=4 """ return ( (pressure / 100 - (hub_height - pressure_height) * 1 / 8) * 100 / (287.058 * temperature_hub_height) )
def gcd(a,b): if b==0: return a return gcd(b,a%b) print(gcd(5,20))
#!/usr/bin/env python if __name__== '__main__': #set help message help = """ Usage: help TOOLS: === Help === ./help.py [[this file]] === Generate results and plot === ./run_1.py [[Do 1 run. Input conf file. Output rundir w/ csv and dbs.]] ./plot_1.py [[Plot results from 1 run. Input csv. Output pngs.]] ./showstats.py [[Show performance statistics for a run]] Example flow: see bottom === Running tests === pytest [[run all tests]] pytest engine/ [[run all tests in engine/ directory]] pytest tests/test_foo.py [[run a single pytest-based test file]] pytest tests/test_foo.py::test_foobar [[run a single pytest-based test]] === Config files, with params to change === -System parameters: ~/tokenspice.conf -Logging: ./logging.conf == Example flow == rm -rf outdir_csv; ./run_1.py 10 outdir_csv 1>out.txt 2>&1 & tail -f out.txt rm -rf outdir_png; ./plot_1.py outdir_csv outdir_png eog outdir_png """ print(help)
class Lift: def __init__(self, name, lift_type, status, sector): self.name = name self.lift_type = lift_type self.status = status self.sector = sector def __str__(self): return self.name + " " + self.lift_type + " " + self.status + " " + self.sector
class Constants: j_title_list = [ 'Journal of Academy of Marketing Science', 'Journal of Marketing', 'Journal of Marketing Research', 'Marketing Science', 'Management Science', 'Administrative Science Quarterly', 'Academy of Management Journal', 'Academy of Management Review'] journal_keys = [ '-JAMS-', '-JM-', '-JMR-', '-MKTSC-', '-MGMTSC-', '-ASQ-', '-AOMJ-', '-AOMR-'] journal_abbrv_list = [ 'jams', 'jm', 'jmr', 'mktsc', 'mgmtsc', 'asq', 'aomj', 'aomr'] j_title_dict = { # marketing journals 'jams': 'Journal of Academy of Marketing Science', 'jm': 'Journal of Marketing', 'jmr': 'Journal of Marketing Research', 'mktsc': 'Marketing Science', 'mgmtsc': 'Management Science', # management journals 'asq':'Administrative Science Quarterly', 'aomj':'Academy of Management Journal', 'aomr':'Academy of Management Review'} base_url_dict = { # marketing journals 'jm': 'https://journals.sagepub.com/action/doSearch?&publication=jmxa', 'jmr': 'https://journals.sagepub.com/action/doSearch?&publication=mrja', 'mktsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mksc', 'mgmtsc': 'https://pubsonline.informs.org/action/doSearch?&publication[]=mnsc', 'jams': 'https://link.springer.com/search?search-within=Journal&facet-journal-id=11747', # management journals 'aomj': 'https://journals.aom.org/action/doSearch?&publication[]=amj', 'aomr': 'https://journals.aom.org/action/doSearch?&publication[]=amr', 'asq': 'https://journals.sagepub.com/action/doSearch?&publication=asqa'}
def factorial(n): if n==1 or n==0: return 1 return n*factorial(n-1)
# Code listing #10 """ Module A (a.py) - Implement functions that operate on series of numbers """ # Note this is version 1 of a.py so called a1.py def squares(narray): """ Return array of squares of numbers """ return pow_n(narray, 2) def cubes(narray): """ Return array of cubes of numbers """ return pow_n(narray, 3) def pow_n(narray, n): """ Return array of numbers raised to arbitrary power n each """ return [pow(x, n) for x in narray] def frequency(string, word): """ Find the frequency of occurrences of word in string as percentage """ word_l = word.lower() string_l = string.lower() # Words in string count = string_l.count(word_l) # Return frequency as percentage return 100.0*count/len(string_l)
app = Flask(__name__) api = Api(app) index = RetrievalIndex() class BuildIndex(Resource): def post(self): request_body = json.loads(request.data) user_id = request_body["user_id"] image_hashes = request_body["image_hashes"] image_embeddings = request_body["image_embeddings"] index.build_index_for_user(user_id, image_hashes, image_embeddings) return jsonify({"status": True, "index_size": index.indices[user_id].ntotal}) class SearchIndex(Resource): def post(self): try: request_body = json.loads(request.data) user_id = request_body["user_id"] image_embedding = request_body["image_embedding"] if "n" in request_body.keys(): n = int(request_body["n"]) else: n = 100 res = index.search_similar(user_id, image_embedding, n) return jsonify({"status": True, "result": res}) except BaseException as e: logger.error(str(e)) return jsonify({"status": False, "result": []}, status=500) api.add_resource(BuildIndex, "/build/") api.add_resource(SearchIndex, "/search/") if __name__ == "__main__": logger.info("starting server") server = WSGIServer(("0.0.0.0", 8002), app) server_thread = gevent.spawn(server.serve_forever) gevent.joinall([server_thread])
# ########################################################### # ## generate menu # ########################################################### _a = request.application _c = request.controller _f = request.function response.title = '%s %s' % (_f, '/'.join(request.args)) response.subtitle = 'admin' response.menu = [(T('Site'), _f == 'site', URL(_a, 'default', 'site'))] if request.vars.app or request.args: _t = request.vars.app or request.args[0] response.menu.append((T('Edit'), _c == 'default' and _f == 'design', URL(_a, 'default', 'design', args=_t))) response.menu.append((T('About'), _c == 'default' and _f == 'about', URL(_a, 'default', 'about', args=_t, ))) response.menu.append((T('Errors'), _c == 'default' and _f == 'errors', URL(_a, 'default', 'errors', args=_t))) response.menu.append((T('Versioning'), _c == 'mercurial' and _f == 'commit', URL(_a, 'mercurial', 'commit', args=_t))) if os.path.exists('applications/examples'): response.menu.append( (T('Help'), False, URL('examples', 'default', 'documentation'))) else: response.menu.append((T('Help'), False, 'http://web2py.com/examples/default/documentation')) if not session.authorized: response.menu = [(T('Login'), True, URL('site'))] else: response.menu.append((T('Logout'), False, URL(_a, 'default', f='logout'))) response.menu.append((T('Debug'), False, URL(_a, 'debug', 'interact')))
BASE = r"""Export of Github issues for [{repo_name}]({repo_url}).{datestring} {issues} """ ISSUE = r"""# [\#{number}]({url}) `{state}`: {title} {labels} #### [{author}]({author_url}) opened issue at [{date}]({url}): {body} {comments} <div style="page-break-after: always;"></div> """ COMMENT = r"""#### [{author}]({author_url}) commented at [{date}]({url}): {body} """ ISSUE_FILE_FOOTNOTE = r""" [Export of Github issue for [{repo_name}]({repo_url}).{datestring}] """
"""Base Base Package more description """
class ReverseProxied(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): print(environ) script_name = environ.get('HTTP_X_SCRIPT_NAME', '') if script_name: environ['SCRIPT_NAME'] = script_name path_info = environ['PATH_INFO'] if path_info.startswith(script_name): environ['PATH_INFO'] = path_info[len(script_name):] scheme = environ.get('HTTP_X_SCHEME', '') if scheme: environ['wsgi.url_scheme'] = scheme return self.app(environ, start_response)
""" Package for the application. """ #from .graficoLinhaTempo import PlotGraphTimeLineBar #from .DataFrameUtil import SumRows #from .DataFrameUtil import RenameCols
print("first string" + ", " + "second string") print(str(1) + "2" + "3" + "4") print("spam" * 3) print(4 * "2") print("Love" * 0) print("7" * 3) # 1 + "2" + 3 -- TypeError # "4" * "2" -- TypeError # "Python is fun" * 7.0 -- TypeError
f = open("all.txt") s = f.readlines(); f.close() fout = open("allout1.txt", 'w') o = [] outPath = 'S:\\BACKUP!!!\\WD\\L\\Canon\\All\\' quote = "\"" for x in s: #x.replace('\\', '\\\\') #print(x) #if x.rfind('MVI') > -1: ix = x.rindex('MVI'); x = x.strip(); if x.rfind('MVI') > -1: ix = x.rindex('MVI'); else: ix = -1 if x.rfind('THM') > -1: ix = -1 fn = x[ix:] #if ix != None: fn = x[ix:] #else: fn = "NONE" #if (x.rfind("avi")): o = o + ["VirtualDub.Open(" + x + "); " + "VirtualDub.SaveAVI(" + outPath + fn + ");\n" ] if ix != -1: #if (x.rfind("avi")): so = "VirtualDub.Open(\"" + x + "\"" + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");" if (x.rfind("avi")): so = "VirtualDub.Open(" + quote + x + quote + "); VirtualDub.SaveAVI(" + quote + outPath + fn + quote + ");" + "\r\n"; print(so) fout.write(so) fout.close(); #print(o)
class Solution: def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ if k < 0: return 0 count = 0 n = len(nums) d = {} for i in range(n): d[nums[i]] = i for i in range(n): if nums[i] + k in d.keys() and d[nums[i] + k] != i: count += 1 d.pop(nums[i] + k, 0) return count if __name__ == '__main__': solution = Solution() print(solution.findPairs([3, 1, 4, 1, 5], 2)) print(solution.findPairs([2, 3, 4, 5, 1], 1)) print(solution.findPairs([1, 3, 1, 5, 4], 0)) print(solution.findPairs([1, 1, 1, 2, 1], 1)) print(solution.findPairs([1, 1, 1, 2, 2], 0)) print(solution.findPairs([-1, -2, -3], 1)) else: pass
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you 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. class weakdict(dict): # noqa: D101 __slots__ = ("__weakref__",) def optional_square(number: int = 5) -> int: # noqa """ Square `number`. The function from Modin. Parameters ---------- number : int Some number. Notes ----- The `optional_square` Modin function from modin/scripts/examples.py. """ return number ** 2 def optional_square_empty_parameters(number: int = 5) -> int: """ Parameters ---------- """ return number ** 2 def square_summary(number: int) -> int: # noqa: D103, GL08 """ Square `number`. Examples -------- The function that will never be used in modin.pandas.DataFrame same as in Pandas or Numpy. """ return number ** 2
class _FieldInfo: """ Exposes the public members of the System.Reflection.FieldInfo class to unmanaged code. """ def Equals(self,other): """ Equals(self: _FieldInfo,other: object) -> bool Provides COM objects with version-independent access to the System.Object.Equals(System.Object) method. other: The System.Object to compare with the current System.Object. Returns: true if the specified System.Object is equal to the current System.Object; otherwise,false. """ pass def GetCustomAttributes(self,*__args): """ GetCustomAttributes(self: _FieldInfo,inherit: bool) -> Array[object] Provides COM objects with version-independent access to the System.Reflection.MemberInfo.GetCustomAttributes(System.Boolean) method. inherit: Specifies whether to search this member's inheritance chain to find the attributes. Returns: An array that contains all the custom attributes,or an array with zero elements if no attributes are defined. GetCustomAttributes(self: _FieldInfo,attributeType: Type,inherit: bool) -> Array[object] Provides COM objects with version-independent access to the System.Reflection.MemberInfo.GetCustomAttributes(System.Type,System.Boolean) method. attributeType: The type of attribute to search for. Only attributes that are assignable to this type are returned. inherit: Specifies whether to search this member's inheritance chain to find the attributes. Returns: An array of custom attributes applied to this member,or an array with zero (0) elements if no attributes have been applied. """ pass def GetHashCode(self): """ GetHashCode(self: _FieldInfo) -> int Provides COM objects with version-independent access to the System.Object.GetHashCode method. Returns: The hash code for the current instance. """ pass def GetIDsOfNames(self,riid,rgszNames,cNames,lcid,rgDispId): """ GetIDsOfNames(self: _FieldInfo,riid: Guid,rgszNames: IntPtr,cNames: UInt32,lcid: UInt32,rgDispId: IntPtr) -> Guid Maps a set of names to a corresponding set of dispatch identifiers. riid: Reserved for future use. Must be IID_NULL. rgszNames: Passed-in array of names to be mapped. cNames: Count of the names to be mapped. lcid: The locale context in which to interpret the names. rgDispId: Caller-allocated array that receives the IDs corresponding to the names. """ pass def GetType(self): """ GetType(self: _FieldInfo) -> Type Provides COM objects with version-independent access to the System.Object.GetType method. Returns: A System.Type object. """ pass def GetTypeInfo(self,iTInfo,lcid,ppTInfo): """ GetTypeInfo(self: _FieldInfo,iTInfo: UInt32,lcid: UInt32,ppTInfo: IntPtr) Retrieves the type information for an object,which can then be used to get the type information for an interface. iTInfo: The type information to return. lcid: The locale identifier for the type information. ppTInfo: Receives a pointer to the requested type information object. """ pass def GetTypeInfoCount(self,pcTInfo): """ GetTypeInfoCount(self: _FieldInfo) -> UInt32 Retrieves the number of type information interfaces that an object provides (either 0 or 1). """ pass def GetValue(self,obj): """ GetValue(self: _FieldInfo,obj: object) -> object Provides COM objects with version-independent access to the System.Reflection.FieldInfo.GetValue(System.Object) method. obj: The object whose field value will be returned. Returns: An object containing the value of the field reflected by this instance. """ pass def GetValueDirect(self,obj): """ GetValueDirect(self: _FieldInfo,obj: TypedReference) -> object Provides COM objects with version-independent access to the System.Reflection.FieldInfo.GetValueDirect(System.TypedReference) method. obj: A System.TypedReference structure that encapsulates a managed pointer to a location and a runtime representation of the type that might be stored at that location. Returns: An System.Object containing a field value. """ pass def Invoke(self,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr): """ Invoke(self: _FieldInfo,dispIdMember: UInt32,riid: Guid,lcid: UInt32,wFlags: Int16,pDispParams: IntPtr,pVarResult: IntPtr,pExcepInfo: IntPtr,puArgErr: IntPtr) -> Guid Provides access to properties and methods exposed by an object. dispIdMember: Identifies the member. riid: Reserved for future use. Must be IID_NULL. lcid: The locale context in which to interpret arguments. wFlags: Flags describing the context of the call. pDispParams: Pointer to a structure containing an array of arguments,an array of argument DISPIDs for named arguments,and counts for the number of elements in the arrays. pVarResult: Pointer to the location where the result is to be stored. pExcepInfo: Pointer to a structure that contains exception information. puArgErr: The index of the first argument that has an error. """ pass def IsDefined(self,attributeType,inherit): """ IsDefined(self: _FieldInfo,attributeType: Type,inherit: bool) -> bool Provides COM objects with version-independent access to the System.Reflection.MemberInfo.IsDefined(System.Type,System.Boolean) method. attributeType: The System.Type object to which the custom attributes are applied. inherit: Specifies whether to search this member's inheritance chain to find the attributes. Returns: true if one or more instance of attributeType is applied to this member; otherwise,false. """ pass def SetValue(self,obj,value,invokeAttr=None,binder=None,culture=None): """ SetValue(self: _FieldInfo,obj: object,value: object) Provides COM objects with version-independent access to the System.Reflection.FieldInfo.SetValue(System.Object,System.Object) method. obj: The object whose field value will be set. value: The value to assign to the field. SetValue(self: _FieldInfo,obj: object,value: object,invokeAttr: BindingFlags,binder: Binder,culture: CultureInfo) Provides COM objects with version-independent access to the System.Reflection.PropertyInfo.SetValue(System.Object,System.Object,System.Reflection.BindingFlag s,System.Reflection.Binder,System.Object[],System.Globalization.CultureInfo) method. obj: The object whose field value will be set. value: The value to assign to the field. invokeAttr: A field of System.Reflection.Binder that specifies the type of binding that is desired (for example,Binder.CreateInstance or Binder.ExactBinding). binder: A set of properties that enables the binding,coercion of argument types,and invocation of members through reflection. If binder is null,then Binder.DefaultBinding is used. culture: The software preferences of a particular culture. """ pass def SetValueDirect(self,obj,value): """ SetValueDirect(self: _FieldInfo,obj: TypedReference,value: object) Provides COM objects with version-independent access to the System.Reflection.FieldInfo.SetValueDirect(System.TypedReference,System.Object) method. obj: The object whose field value will be set. value: The value to assign to the field. """ pass def ToString(self): """ ToString(self: _FieldInfo) -> str Provides COM objects with version-independent access to the System.Object.ToString method. Returns: A string that represents the current System.Object. """ pass def __eq__(self,*args): """ x.__eq__(y) <==> x==y """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __str__(self,*args): pass Attributes=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.Attributes property. Get: Attributes(self: _FieldInfo) -> FieldAttributes """ DeclaringType=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.MemberInfo.DeclaringType property. Get: DeclaringType(self: _FieldInfo) -> Type """ FieldHandle=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldHandle property. Get: FieldHandle(self: _FieldInfo) -> RuntimeFieldHandle """ FieldType=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.FieldType property. Get: FieldType(self: _FieldInfo) -> Type """ IsAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsAssembly property. Get: IsAssembly(self: _FieldInfo) -> bool """ IsFamily=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamily property. Get: IsFamily(self: _FieldInfo) -> bool """ IsFamilyAndAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyAndAssembly property. Get: IsFamilyAndAssembly(self: _FieldInfo) -> bool """ IsFamilyOrAssembly=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsFamilyOrAssembly property. Get: IsFamilyOrAssembly(self: _FieldInfo) -> bool """ IsInitOnly=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsInitOnly property. Get: IsInitOnly(self: _FieldInfo) -> bool """ IsLiteral=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsLiteral property. Get: IsLiteral(self: _FieldInfo) -> bool """ IsNotSerialized=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsNotSerialized property. Get: IsNotSerialized(self: _FieldInfo) -> bool """ IsPinvokeImpl=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPinvokeImpl property. Get: IsPinvokeImpl(self: _FieldInfo) -> bool """ IsPrivate=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPrivate property. Get: IsPrivate(self: _FieldInfo) -> bool """ IsPublic=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsPublic property. Get: IsPublic(self: _FieldInfo) -> bool """ IsSpecialName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsSpecialName property. Get: IsSpecialName(self: _FieldInfo) -> bool """ IsStatic=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.IsStatic property. Get: IsStatic(self: _FieldInfo) -> bool """ MemberType=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.FieldInfo.MemberType property. Get: MemberType(self: _FieldInfo) -> MemberTypes """ Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.MemberInfo.Name property. Get: Name(self: _FieldInfo) -> str """ ReflectedType=property(lambda self: object(),lambda self,v: None,lambda self: None) """Provides COM objects with version-independent access to the System.Reflection.MemberInfo.ReflectedType property. Get: ReflectedType(self: _FieldInfo) -> Type """
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ Simple calculator that determines the price of a meal after tax and tip Author: Alexander A. Laurence Last modified: January 2019 Website: www.celestial.tokyo """ # pricing meal = 44.5 tax = 6.75/100 tip = 15.0/100 # logic meal = meal + (meal*tax) total = meal+(meal*tip) # print print(total)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"ROOT_DIR": "00_core.ipynb", "DOWNLOAD_DIR_BASE": "00_core.ipynb", "PROCESSED_DIR_BASE": "00_core.ipynb", "DATASET_DIR": "00_core.ipynb", "create_country_dirs": "00_core.ipynb", "gen_weekdates": "00_core.ipynb", "STANDARD_WEEK": "00_core.ipynb", "STANDARD_WEEK.columns": "00_core.ipynb", "LAST_MODIFIED": "020_Netherlands.ipynb", "COUNTRIES": "03_collect.ipynb", "SUMMARY": "03_collect.ipynb"} modules = ["core.py", "countries/uk.py", "countries/netherlands.py", "collect.py"] doc_url = "https://kk1694.github.io/weekly_mort/" git_url = "https://github.com/kk1694/weekly_mort/tree/master/" def custom_doc_links(name): return None
class Quark: """ An :class:`src.ops.ElementalOperator` is a product of quark fields and other commuting objects. :param barred: Specifies if quark or anti-quark :type barred: bool :param flavor: Quark flavor :type flavor: char :param spin: Quark spin :type spin: str :param color: Quark color :type color: str :param time: Quark time :type time: str :param position: Quark position :type position: str """ def __init__(self, barred, flavor, spin, color, time, position): """Constructor """ self.barred=barred self.flavor=flavor self.spin=spin self.color=color self.time=time self.position=position def __str__(self): """Printer to string """ if self.barred: return "\\bar{" + str(self.flavor) + "}" + "_{" + self.spin + " " \ + self.color + "}(" + self.position + ", " + self.time + ")" else: return str(self.flavor) + "_{" + self.spin + " " + self.color \ + "}(" + self.position + ", " + self.time + ")" def __eq__(self, other): """Check if two quarks are equal :param other: Another quark :type other: :class:`src.ops.Quark` """ return (self.barred==other.barred) and (self.flavor==other.flavor) and \ (self.spin==other.spin) and (self.color==other.color) and \ (self.time==other.time) and (self.position==other.position) #TODO Implement this for the wick_contraction part. class ShortQuark: """ A more efficient implementation of :class:`src.ops.Quark` for use within LINK_TO_WICK_CONTRACTION. :param barred: Quark or anti-quark :type barred: bool :param flavor: Quark flavor :type flavor: char :param label: Single label for the quark :type lavel: str """ def __init__(self, barred, flavor, label): """Constructor """ self.barred=barred self.flavor=flavor self.label=label def __str__(self): """Printer to string """ if(self.barred): return "\\bar{" + str(self.flavor) + "}_{" + self.label + "}" else: return str(self.flavor) + "_{" + self.label + "}" def __eq__(self, other): """Check if two short quarks are equal :param other: Another short quark :type other: :class:`src.ops.ShortQuark` """ return (self.barred==other.barred) and (self.flavor==other.flavor) \ and (self.label==other.label)
server='tcp:mkgsupport.database.windows.net' database='mkgsupport' username='mkguser' password='Usersqlmkg123!' driver='/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.6.so.1.1'
# _create_empty_dict.py __module_name__ = "_create_empty_dict.py" __author__ = ", ".join(["Michael E. Vinyard"]) __email__ = ", ".join(["vinyard@g.harvard.edu",]) def _create_empty_dict(keys): """ Create an empty python Dictionary given a set of keys. Parameters: ----------- keys Returns: -------- Dict """ Dict = {} for key in keys: Dict[key] = {} return Dict
""" faça um programa que leia um numeo de 0 a 9999 e mostre na tela cada um dos seus digitos separados""" numero = int(input('Digite um numero entre 0 e 9999 para exibir seus valores: ')) u = numero // 1 % 10 # nesse caso eu estou dividino inteiro e pego o resto da divisão d = numero // 10 % 10 c = numero // 100 % 10 m = numero // 1000 % 10 print(f'unidade.......: {u}') print(f'dezena........: {d}') print(f'Centena.......: {c}') print(f'Milhar........: {m}')
seq_emoji_map = { 'A': ':apple:', # avocado? differnet colours? 'C': ':corn:', 'T': ':tomato:', 'G': ':grapes:', 'N': ':question:' } all_qualities = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" #From https://en.wikipedia.org/wiki/FASTQ_format # note order not exact here fastq_emoji_map = { '!': ':no_entry_sign:', '\"': ':x:', '#': ':japanese_goblin:', '$': ':broken_heart:', '%': ':no_good:', '&': ':space_invader:', '\'': ':imp:', '(': ':skull:', ')': ':ghost:', '': ':pouting_cat:', '*': ':see_no_evil:', '+': ':hear_no_evil:', ',': ':speak_no_evil:', '/': ':pouting_cat:', '-': ':monkey_face:', '.': ':crying_cat_face:', '0': ':scream_cat:', '1': ':bomb:', '2': ':fire:', '3': ':rage:', '4': ':poop:', '5': ':warning:', '6': ':grinning:', '7': ':sweat_smile:', '8': ':smirk:', '9': ':blush:', ':': ':kissing_smiling_eyes:', ';': ':kissing:', '<': ':kissing_closed_eyes:', '>': ':kissing_heart:', '@': ':smile:', '=': ':smiley:', '?': ':laughing:', 'A': ':yum:', 'B': ':relaxed:', 'D': ':stuck_out_tongue:', 'C': ':stuck_out_tongue_closed_eyes:', 'E': ':stuck_out_tongue_winking_eye:', 'G': ':grin:', 'H': ':smile:', 'I': ':sunglasses:', 'J': ':heart_eyes:', 'F': ':wink:' } # only use 0 to 50 use same emoji # binning - i.e https://www.illumina.com/documents/products/technotes/technote_understanding_quality_scores.pdf fastq_emoji_map_binned= { #N (no call) N (no call) '!': ':no_entry_sign:', '"': ':no_entry_sign:', #2–9 6 '#': ':skull:', '$': ':skull:', '%': ':skull:', '&': ':skull:', '\'': ':skull:', '(': ':skull:', ')': ':skull:', '*': ':skull:', #10–19 15 '+': ':poop:' , ',': ':poop:' , '-': ':poop:' , '.': ':poop:' , '/': ':poop:' , '0': ':poop:' , '1': ':poop:' , '2': ':poop:' , '3': ':poop:' , '4': ':poop:' , #20–24 22 '5': ':warning:', '6': ':warning:', '7': ':warning:', '8': ':warning:', '9': ':warning:', #25–29 27 ':': ':smile:', ';': ':smile:', '<': ':smile:', '=': ':smile:', '>': ':smile:', #30–34 33 '?': ':laughing:', '@': ':laughing:', 'A': ':laughing:', 'B': ':laughing:', 'C': ':laughing:', #35–39 37 'D': ':sunglasses:', 'E': ':sunglasses:', 'F': ':sunglasses:', 'G': ':sunglasses:', 'H': ':sunglasses:', #≥ 40 40 'I': ':heart_eyes:', 'J': ':heart_eyes:', } # binning - i.e https://www.illumina.com/documents/products/technotes/technote_understanding_quality_scores.pdf fastq_noemoji_map = { #N (no call) N (no call) '!': '▁', '"': '▁', #2–9 6 '#': '▂', '$': '▂', '%': '▂', '&': '▂', '\'': '▂', '(': '▂', ')': '▂', '*': '▂', #10–19 15 '+': '▃' , ',': '▃' , '-': '▃' , '.': '▃' , '/': '▃' , '0': '▃' , '1': '▃' , '2': '▃' , '3': '▃' , '4': '▃' , #20–24 22 '5': '▄', '6': '▄', '7': '▄', '8': '▄', '9': '▄', #25–29 27 ':': '▅', ';': '▅', '<': '▅', '=': '▅', '>': '▅', #30–34 33 '?': '▆', '@': '▆', 'A': '▆', 'B': '▆', 'C': '▆', #35–39 37 'D': '▇', 'E': '▇', 'F': '▇', 'G': '▇', 'H': '▇', #≥ 40 40 'I': '█', 'J': '█', }
""" ======================================================================== Bits.py ======================================================================== Pure-Python implementation of fixed-bitwidth data type. Author : Shunning Jiang Date : Oct 31, 2017 """ class Bits: __slots__ = ( "nbits", "value" ) def __init__( self, nbits=32, value=0 ): self.nbits = nbits self.value = int(value) & ((1 << nbits) - 1) def __ilshift__( self, x ): try: assert x.nbits == self.nbits, "Bitwidth mismatch during <<=" except AttributeError: raise TypeError(f"Assign {type(x)} to Bits") self._next = x.value return self def _flip( self ): self.value = self._next def __call__( self ): return Bits( self.nbits ) # Arithmetics def __getitem__( self, idx ): sv = int(self.value) if isinstance( idx, slice ): start, stop = int(idx.start), int(idx.stop) assert not idx.step and start < stop and start >= 0 and stop <= self.nbits, \ "Invalid access: [{}:{}] in a Bits{} instance".format( start, stop, self.nbits ) return Bits( stop-start, (sv & ((1 << stop) - 1)) >> start ) i = int(idx) assert 0 <= i < self.nbits return Bits( 1, (sv >> i) & 1 ) def __setitem__( self, idx, v ): sv = int(self.value) if isinstance( idx, slice ): start, stop = int(idx.start), int(idx.stop) assert not idx.step and start < stop and start >= 0 and stop <= self.nbits, \ "Invalid access: [{}:{}] in a Bits{} instance".format( start, stop, self.nbits ) self.value = (sv & (~((1 << stop) - (1 << start)))) | \ ((int(v) & ((1 << (stop - start)) - 1)) << start) return i = int(idx) assert 0 <= i < self.nbits self.value = (sv & ~(1 << i)) | ((int(v) & 1) << i) def __add__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) + int(other) ) except: return Bits( self.nbits, int(self.value) + int(other) ) def __radd__( self, other ): return self.__add__( other ) def __sub__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) - int(other) ) except: return Bits( self.nbits, int(self.value) - int(other) ) def __rsub__( self, other ): return Bits( self.nbits, other ) - self def __mul__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) * int(other) ) except: return Bits( self.nbits, int(self.value) * int(other) ) def __rmul__( self, other ): return self.__mul__( other ) def __and__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) & int(other) ) except: return Bits( self.nbits, int(self.value) & int(other) ) def __rand__( self, other ): return self.__and__( other ) def __or__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) | int(other) ) except: return Bits( self.nbits, int(self.value) | int(other) ) def __ror__( self, other ): return self.__or__( other ) def __xor__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) ^ int(other) ) except: return Bits( self.nbits, int(self.value) ^ int(other) ) def __rxor__( self, other ): return self.__xor__( other ) def __div__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) / int(other) ) except: return Bits( self.nbits, int(self.value) / int(other) ) def __floordiv__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) / int(other) ) except: return Bits( self.nbits, int(self.value) / int(other) ) def __mod__( self, other ): try: return Bits( max(self.nbits, other.nbits), int(self.value) % int(other) ) except: return Bits( self.nbits, int(self.value) % int(other) ) def __invert__( self ): return Bits( self.nbits, ~int(self.value) ) def __lshift__( self, other ): nb = int(self.nbits) # TODO this doesn't work perfectly. We need a really smart # optimization that avoids the guard totally if int(other) >= nb: return Bits( nb ) return Bits( nb, int(self.value) << int(other) ) def __rshift__( self, other ): return Bits( self.nbits, int(self.value) >> int(other) ) def __eq__( self, other ): try: other = int(other) except ValueError: return False return Bits( 1, int(self.value) == other ) def __hash__( self ): return hash((self.nbits, self.value)) def __ne__( self, other ): try: other = int(other) except ValueError: return True return Bits( 1, int(self.value) != other ) def __lt__( self, other ): return Bits( 1, int(self.value) < int(other) ) def __le__( self, other ): return Bits( 1, int(self.value) <= int(other) ) def __gt__( self, other ): return Bits( 1, int(self.value) > int(other) ) def __ge__( self, other ): return Bits( 1, int(self.value) >= int(other) ) def __bool__( self ): return int(self.value) != 0 def __int__( self ): return int(self.value) def int( self ): if self.value >> (self.nbits - 1): return -int(~self + 1) return int(self.value) def uint( self ): return int(self.value) def __index__( self ): return int(self.value) # Print def __repr__(self): return "Bits{}( {} )".format( self.nbits, self.hex() ) def __str__(self): str = "{:x}".format(int(self.value)).zfill(((self.nbits-1)>>2)+1) return str def __oct__( self ): # print("DEPRECATED: Please use .oct()!") return self.oct() def __hex__( self ): # print("DEPRECATED: Please use .hex()!") return self.hex() def bin(self): str = "{:b}".format(int(self.value)).zfill(self.nbits) return "0b"+str def oct( self ): str = "{:o}".format(int(self.value)).zfill(((self.nbits-1)>>1)+1) return "0o"+str def hex( self ): str = "{:x}".format(int(self.value)).zfill(((self.nbits-1)>>2)+1) return "0x"+str
# -*- coding: utf-8 -*- ''' File name: code\combined_volume_of_cuboids\sol_212.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #212 :: Combined Volume of Cuboids # # For more information see: # https://projecteuler.net/problem=212 # Problem Statement ''' An axis-aligned cuboid, specified by parameters { (x0,y0,z0), (dx,dy,dz) }, consists of all points (X,Y,Z) such that x0 ≤ X ≤ x0+dx, y0 ≤ Y ≤ y0+dy and z0 ≤ Z ≤ z0+dz. The volume of the cuboid is the product, dx × dy × dz. The combined volume of a collection of cuboids is the volume of their union and will be less than the sum of the individual volumes if any cuboids overlap. Let C1,...,C50000 be a collection of 50000 axis-aligned cuboids such that Cn has parameters x0 = S6n-5 modulo 10000y0 = S6n-4 modulo 10000z0 = S6n-3 modulo 10000dx = 1 + (S6n-2 modulo 399)dy = 1 + (S6n-1 modulo 399)dz = 1 + (S6n modulo 399) where S1,...,S300000 come from the "Lagged Fibonacci Generator": For 1 ≤ k ≤ 55, Sk = [100003 - 200003k + 300007k3]   (modulo 1000000)For 56 ≤ k, Sk = [Sk-24 + Sk-55]   (modulo 1000000) Thus, C1 has parameters {(7,53,183),(94,369,56)}, C2 has parameters {(2383,3563,5079),(42,212,344)}, and so on. The combined volume of the first 100 cuboids, C1,...,C100, is 723581599. What is the combined volume of all 50000 cuboids, C1,...,C50000 ? ''' # Solution # Solution Approach ''' '''
"""This module contains exceptions that power Injectify.""" class ClassFoundException(Exception): pass
a = 1 b = 0 c = 128 d = 0 f = 836 + c #964 if a == 1: c = 10550400 f = f + c #10551364 a = 0 for b in range(1, f+1): if (f % b) == 0: a += b print(a)
class GoodreadsClientException(Exception): pass class NetworkError(GoodreadsClientException): pass
def show_words(**kwargs): print(kwargs['pies'], kwargs['kot']) for key, value in kwargs.items(): print(key + "->" + value) show_words(pies="Dog", kot="Cat", sowa="Owl", mysz="Mouse")
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Shashi Bhushan (sbhushan1 @ outlook dot com)' class GameObject(object): pass
n1 = int(input('Digite um número para ver sua tabuada: ')) print('-'*12) print(f'{n1} X 1 = {n1 * 1} \n{n1} X 2 = {n1 * 2} \n{n1} X 3 = {n1 * 3} \n{n1} x 4 = {n1 * 4} ') print(f'{n1} X 5 = {n1 * 5} \n{n1} X 6 = {n1 * 6} \n{n1} X 7 = {n1 * 7} \n{n1} X 8 = {n1 * 8}') print(f'{n1} X 9 = {n1 * 9} \n{n1} X 10 = {n1 * 10}') print('-'*12)
debian_os = ['debian', 'ubuntu'] rhel_os = ['redhat', 'centos'] def test_distribution(host): assert host.system_info.distribution.lower() in debian_os + rhel_os def test_conf_dir(host): f = host.file('/etc/pgbouncer_exporter') assert f.exists assert f.is_directory def test_log_dir(host): f = host.file('/var/log/pgbouncer_exporter') assert f.exists assert f.is_directory def test_service(host): s = host.service('pgbouncer_exporter') assert s.is_enabled assert s.is_running def test_user(host): u = host.user('postgres') assert u.exists def test_group(host): g = host.group('postgres') assert g.exists def test_socket(host): s = host.socket("tcp://127.0.0.1:9127") assert s.is_listening def test_version(host): g = host.pip_package.get_packages(pip_path='pip3') for k, v in g.items(): if k == "prometheus-pgbouncer-exporter": version = v['version'] break assert version == "2.0.1"
#!/usr/bin/env python3 """ linear_search.py - Linear Search Implementation Author: Hoanh An (hoanhan@bennington.edu) Date: 10/18/2017 """ def linear_search(arr, x): for i in arr: if i == x: return True return False if __name__ == '__main__': test_array = [1, 2, 3] if linear_search(test_array, 3): print("PASSED test_item_in_list") if linear_search(test_array, 5) == False: print("PASSED test_item_NOT_in_list")
a = 1 b = 2 c = 3 d = 4 e = 5 f = 6
# --- Day 15: Rambunctious Recitation --- # You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it. # While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're playing a memory game and are ever so excited to explain the rules! # In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number: # If that was the first time the number has been spoken, the current player says 0. # Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. # So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat). # For example, suppose the starting numbers are 0,3,6: # Turn 1: The 1st number spoken is a starting number, 0. # Turn 2: The 2nd number spoken is a starting number, 3. # Turn 3: The 3rd number spoken is a starting number, 6. # Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0. # Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3. # Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3. # Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1. # Turn 8: Since 1 is new, the 8th number spoken is 0. # Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4. # Turn 10: 4 is new, so the 10th number spoken is 0. # (The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.) # Their question for you is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436. # Here are a few more examples: # Given the starting numbers 1,3,2, the 2020th number spoken is 1. # Given the starting numbers 2,1,3, the 2020th number spoken is 10. # Given the starting numbers 1,2,3, the 2020th number spoken is 27. # Given the starting numbers 2,3,1, the 2020th number spoken is 78. # Given the starting numbers 3,2,1, the 2020th number spoken is 438. # Given the starting numbers 3,1,2, the 2020th number spoken is 1836. # Given your starting numbers, what will be the 2020th number spoken? def fileInput(): f = open(inputFile, 'r') with open(inputFile) as f: read_data = f.read().split(',') f.close() return read_data def dictTransform(data): turn_count = 0 dict_data = {} for num in data: turn_count += 1 #turn starts on count 1, so do it before and add extra count at the end dict_data.update({int(num):[0,turn_count]}) prev_num = num dict_data.update({int(prev_num):[turn_count]}) return dict_data,turn_count def memGameTurn(dict_data,prev_num,turn_count): # print('-----------') # print('#',turn_count,prev_num, '->',dict_data,end=" ") if dict_data.get(prev_num) is None: dict_data.update({prev_num:[turn_count]}) prev_num = 0 elif len(dict_data.get(prev_num)) == 1: dict_data.update({prev_num:[dict_data.get(prev_num)[0],turn_count]}) prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0] else: dict_data.update({prev_num:[dict_data.get(prev_num)[1],turn_count]}) prev_num = dict_data.get(prev_num)[1]-dict_data.get(prev_num)[0] return dict_data,prev_num def memGame(data): turn_end = 2020 prev_num = 0 #first turn after data is always new number dict_data,turn_start = dictTransform(data) for i in range(turn_start+1,turn_end): dict_data,prev_num = memGameTurn(dict_data,prev_num,i) return prev_num #/////////////////////////////////////////////////// inputFile = 'day15-input.txt' if __name__ == "__main__": data = fileInput() print(memGame(data))
# -*- coding: utf-8 -*- # in VTK, the header file is the same as the classname def get_include_file(classname,filename): incfile = '#include "{0}"'.format(filename) #print "including class {0} from file {1}".format(classname,incfile) if classname.startswith("itk::DefaultConvertPixelTraits"): incfile = '#include "itkMatrix.h"\n'+incfile if classname.startswith("std::set"): incfile = '#include <set>\n'+incfile return incfile #return "{0}.h".format(classname) def get_var_filter(): return "(itk::|vnl_|itkAmi|gdcm::|std::).*" def wrap_public_fields(classname): return False def deleter_includefile(): return "" def implement_deleter(classname): # no deleter for the moment unless for smart pointers? # or only in case of protected deleter? return ", smartpointer_nodeleter<{0} >()".format(classname)