content
stringlengths
7
1.05M
class Except(Exception): def __init__(*args, **kwargs): Exception.__init__(*args, **kwargs) def CheckExceptions(data): raise Except(data)
# -*- coding: utf-8 -*- """ Created on Sat Aug 22 19:49:17 2020 @author: matth """ def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='highs', callback=None, maxiter=None, disp=False, presolve=True, time_limit...
"""Devstack environment variables unique to the instructor plugin.""" def plugin_settings(settings): """Settings for the instructor plugin.""" # Set this to the dashboard URL in order to display the link from the # dashboard to the Analytics Dashboard. settings.ANALYTICS_DASHBOARD_URL = None
__version__ = '0.54' class LandDegradationError(Exception): """Base class for exceptions in this module.""" def __init__(self, msg=None): if msg is None: msg = "An error occurred in the landdegradation module" super(LandDegradationError, self).__init__(msg) class GEEError(LandDe...
del_items(0x80145350) SetType(0x80145350, "void _cd_seek(int sec)") del_items(0x801453BC) SetType(0x801453BC, "void init_cdstream(int chunksize, unsigned char *buf, int bufsize)") del_items(0x801453E4) SetType(0x801453E4, "void flush_cdstream()") del_items(0x80145438) SetType(0x80145438, "void reset_cdstream()") del_it...
# Sets an error rate of %0.025 (1 in 4,000) with a capacity of 5MM items. # See https://hur.st/bloomfilter/?n=5000000&p=0.00025&m=& for more information # 5MM was chosen for being a whole number roughly 2x the size of our most dense sparse plugin output in late July 2020. DEFAULT_ERROR_RATE = 0.00025 DEFAULT_CAPACITY ...
fp = open("./packet.csv", "r") vals = fp.readlines() count = 1 pre_val = 0 current = 0 sampling_rate = 31 val_bins = [] for i in range(len(vals)): pre_val = current current = int(vals[i]) if current == pre_val: count = count + 1 else: count = 1 if count == sampling_rate: ...
''' Specifies the username and password required to log into the iNaturalist website. These variables are imported into the 'inaturalist_scraper.py' script ''' username = 'your_iNaturalist_username_here' password = 'your_iNaturalist_password_here'
FRONT_LEFT_WHEEL_TOPIC = "/capo_front_left_wheel_controller/command" FRONT_RIGHT_WHEEL_TOPIC = "/capo_front_right_wheel_controller/command" # BACK_RIGHT_WHEEL_TOPIC = "/capo_rear_left_wheel_controller/command", # BACK_LEFT_WHEEL_TOPIC = "/capo_rear_right_wheel_controller/command" HEAD_JOINT_TOPIC = "/capo_head_rotatio...
class BasicEnvironment: """Object to pass containing data used for solve. Individuals are mapped to this data upon evaluation. Environments also hold additional evaluation data.""" def __init__(self, df, _dict=None): self.df = df self._dict = _dict
# -*- coding:utf-8 -*- pizzas = ['fruit', 'buff', 'milk', 'zhishi', 'little'] # for pizza in pizzas: # print(pizza) # print(pizza.title() + ", I like eat !") # print("I like eat pizza!") pizzas_bak = pizzas[:] pizzas.append('chicken') pizzas_bak.append('dog') print(pizzas_bak) print(pizzas)
class Solution: def reformatDate(self, date: str) -> str: pattern = re.compile(r'[0-9]+') dateList=date.split(' ') day=pattern.findall(dateList[0])[0] monthList=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] month=monthList.index(da...
inp = open('input_d24.txt').read().strip().split('\n') graph = dict() n = 0 yn = len(inp) xn = len(inp[0]) poss = '01234567' def find_n(ton): for y in range(len(inp)): for x in range(len(inp[y])): if inp[y][x] == str(ton): return (x,y) def exists(n, found): for ele in lis...
array = [] for i in range (16): # array.append([i,0]) array.append([i,5]) print(array)
# # PySNMP MIB module Juniper-PPPOE-PROFILE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-PPPOE-PROFILE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:03:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
class Solution(object): def isValidSudoku(self, board): return (self.is_row_valid(board) and self.is_col_valid(board) and self.is_square_valid(board)) def is_row_valid(self, board): for row in board: if not self.is_unit_valid(row): ...
n = int(input()) D = [list(map(int,input().split())) for i in range(n)] D.sort(key = lambda t: t[0]) S = 0 for i in D: S += i[1] S = (S+1)//2 S2 = 0 for i in D: S2 += i[1] if S2 >= S: print(i[0]) break
#!/usr/local/bin/python3 # Copyright 2019 NineFx Inc. # Justin Baum # 20 May 2019 # Precis Code-Generator ReasonML # https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt fp = open('unicodedata.txt', 'r') ranges = [] line = fp.readline() prev = "" start = 0 while line: if len(line) < 2: break...
# Public Attributes class Employee: def __init__(self, ID, salary): # all properties are public self.ID = ID self.salary = salary def displayID(self): print("ID:", self.ID) Steve = Employee(3789, 2500) Steve.displayID() print(Steve.salary)
m: int; n: int; j: int; i: int m = int(input("Quantas linhas vai ter cada matriz? ")) n = int(input("Quantas colunas vai ter cada matriz? ")) A: [[int]] = [[0 for x in range(n)] for x in range(m)] B: [[int]] = [[0 for x in range(n)] for x in range(m)] C: [[int]] = [[0 for x in range(n)] for x in range(m)] print("Dig...
''' POO - O método super() O método super() se refere á super classe. ''' class Animal: def __init__(self, nome, especie): self.__nome = nome self.__especie = especie def faz_som(self, som): print(f'O {self.__nome} fala {som}') class Gato(Animal): def __init__(self, nome, e...
""" Python列表解析式 https://codingpy.com/article/python-list-comprehensions-explained-visually/ """ numbers = [1, 2, 3, 4, 5] # 如果你熟悉函数式编程(functional programming),你可以把列表解析式看作为结合了filter函数与map函数功能的语法糖: a_list = list(map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))) b_list = [n * 2 for n in numbers if n % 2 == 1] ...
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def solve(self, root): stack = [] stack.append(root) level = -1 min_sum = float('inf') l = 0 ...
""" 1. Clarification 2. Possible solutions - Backtracking 3. Coding 4. Tests """ # T=O(sum(feasible solutions' len)), S=O(target) class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: if not candidates or target < 1: return [] ans, tmp = [], [] ...
def ack ( m, n ): ''' ack: Evaluates Ackermann function with the given arguments m: Positive integer value n: Positive integer value ''' # Guard against error from incorrect input if n < 0 or (not isinstance(n, int)): return "Error: n is either negative or not an integer" if...
# Copyright (c) 2021 Ben Maddison. All rights reserved. # """aspa.as_path Module.""" AS_SEQUENCE = 0x0 AS_SET = 0x1 class AsPathSegment(object): def __init__(self, segment_type, values): if segment_type not in (AS_SEQUENCE, AS_SET): raise ValueError(int) self.type = segment_type ...
def love(): lover = 'sure' lover
""" Parses a Markdown file in the Task.md format. :params doc: :returns: a dictionary containing the main fields of the task. """ def remove_obsidian_syntax(string): "Removes Obsidian syntax from a string, namely []'s, [[]]'s and #'s" pass def parse_md(filename): "Parses a markdown file in the Ta...
# class OtsUtil(object): STEP_THRESHOLD = 408 step = 0 @staticmethod def log(msg): if OtsUtil.step >= OtsUtil.STEP_THRESHOLD: print(msg)
#Program to Remove Punctuations From a String string="Wow! What a beautiful nature!" new_string=string.replace("!","") print(new_string)
def condensate_to_gas_equivalence(api, stb): "Derivation from real gas equation" Tsc = 519.57 # standard temp in Rankine psc = 14.7 # standard pressure in psi R = 10.732 rho_w = 350.16 # water density in lbm/STB so = 141.5 / (api + 131.5) # so: specific gravity of oil (dimensionless) Mo = 5854 / (api - 8...
def fibonacci(): number = 0 previous_number = 1 while True: if number == 0: yield number number += previous_number if number == 1: yield number number += previous_number if number == 2: yield previous_number if numbe...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __repr__(self): return str(self.data) def count_unival_trees(root): if not root: return 0 elif not root.left and not root.right: return 1 elif not root....
""" A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there d...
# List Operations and Functions # '+' Operator print('-----------+ Operator------------') a = [1,2,3] b = [4,5,6] c = a + b print(c) print('----------* Operator--------------') # '*' Operator a1 = a * 2 print(a1) print('--------len function----------------') print(len(a)) print('--------max function----------------') ...
{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9de928d7", "metadata": {}, "outputs": [], "source": [ "import os\n", "import csv\n", "import pandas as pd" ] }, { "cell_type": "code", "execution_count": 2, "id": "8f1478f8", "metadata": {}, "outputs"...
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? ![...
text = input().split(' ') new_text = '' for word in text: if len(word) > 4: if word[:2] in word[2:]: word = word[2:] new_text += ' ' + word print(new_text[1:])
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if len(strs) == 0: return "" resLen = 0 while True: if len(strs[0]) == resLen: return strs[0] curChar = strs[0][resLen] for i in range(1, len(strs)): ...
#!python3 # -*- coding:utf-8 -*- ''' this code is a sample of code for learn how to use python test modules. ''' def aaa(): ''' printing tree ! mark. ''' print("!!!") def bbb(): ''' printing tree chars. ''' print("BBB") def ccc(): ''' printing number with loop. '...
# Project Framework default is 1 (Model/View/Provider) # src is source where is the lib folder located def startmain(src="flutterproject/myapp/lib", pkg="Provider", file="app_widget", home="", project_framework=1, autoconfigfile=True): maindart = open(src + "/main.dart", "w") if project_f...
def max_consecutive_ones(x): # e.g. x= 95 (1101111) """ Steps 1. x & x<<1 --> 1101111 & 1011110 == 1001110 2. x & x<<1 --> 1001110 & 0011100 == 0001100 3. x & x<<1 --> 0001100 & 0011000 == 0001000 4. x & x<<1 --> 0001000 & 0010000 == 0000000 :param x: :return: """...
# Avg week temperature print("Enter temperatures of 7 days:") a = float(input()) b = float(input()) c = float(input()) d = float(input()) e = float(input()) f = float(input()) g = float(input()) print("Average temperature:", (a+b+c+d+e+f+g)/7)
def digitSum(n,step): res=0 while(n>0): res+=n%10 n=n//10 step+=1 if(res<=9): return (res,step) else: return digitSum(res,step) t=int(input()) for _ in range(t): minstep=[99999999 for i in range(10)] #cache hitratio=[0 for i in range(10)] maxhit=0 n,d=[int(x) for x in input().strip().split()] if(n...
###################################################### # # # author # # Parth Lathiya # # https://www.cse.iitb.ac.in/~parthiitb/ # # # ###################################################### at =...
# 15/15 num_of_flicks = int(input()) art = [] for _ in range(num_of_flicks): coords = input().split(",") art.append((int(coords[0]), int(coords[1]))) lowest_x = min(art, key=lambda x: x[0])[0] - 1 lowest_y = min(art, key=lambda x: x[1])[1] - 1 highest_x = max(art, key=lambda x: x[0])[0] + 1 highest_y = max...
print("Leap Year Range Calculator: ") year1=int(input("Enter First Year: ")) year2 = int(input("Enter Last Year: ")) while year1<=year2: if year1 % 4 == 0 : print(year1,"is a leap year") year1= year1 + 1
# Given an array nums of n integers, # are there elements a, b, c in nums such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. # Note: # The solution set must not contain duplicate triplets. # Example: # Given array nums = [-1, 0, 1, 2, -1, -4], # A solution set is: # [ # ...
I = lambda : int(input()) LI = lambda : [int(x) for x in input().split()] MI = lambda : map(int, input().split()) SI = lambda : input() """ #Leer de archivo for line in sys.stdin: ... """ """ def fastio(): import sys from io import StringIO from atexit import register global input sys.stdin = ...
""" Generator with a finite loop can be used with for """ def count(): n = 1 while n < 1000: yield n n *= 2 gen = count() for number in gen: print(number)
""" Constants to be used in the module """ __author__ = 'Santiago Flores Kanter (sfloresk@cisco.com)' QUERY_TARGET_CHILDREN = 'children' QUERY_TARGET_SELF = 'self' QUERY_TARGET_SUBTREE = 'subtree' API_URL = 'api/' MQ_API2_URL = 'mqapi2/'
# Escreva um programa que leia duas strings e gere uma terceira, na qual os caracteres da segunda foram retirados da primeira # 1ª string: AATTGGAA # 2ª string: TG # 3ª string: AAAA # str1 = 'AATTGGAA' # str2 = 'TG' # # print(f'\nPrimeira string: {str1}') # print(f'Segunda string: {str2}') str1 = str(input('\nPrimeir...
#!/usr/bin/env python """ File: pentagon_p_solution-garid.py Find the perimeter of pentagon. """ __author__ = "Ochirgarid Chinzorig (Ochirgarid)" __version__ = "1.0" # Open file on read mode inp = open("../test/test1.txt", "r") # read input lines one by one # and convert them to integer a = int(inp.readline...
# # PySNMP MIB module MITEL-IPVIRTUAL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-IPVIRTUAL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:03:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
def Reverse(Dna): tt = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', } ans = '' for a in Dna: ans += tt[a] return ans[::-1] def main(infile, outfile): # Read the input, but do something non-trivial instead of count the lines in the file inp = lines =...
# configuracoes pessoais PERSONAL_NAME = 'YOU' # configuracoes de email EMAIL = 'your gmail account' PASSWORD = 'your gmail PASSWORD' RECEIVER_EMAIL = 'email to forward the contact messages' # configuracoes do Google ReCaptha SECRET_KEY = "Google ReCaptha's Secret key" SITE_KEY = "Google ReCaptha's Site key" APP_SEC...
"""Data set for text records. A Dataset maintains the collection of data instances and metadata associated with the dataset. """ class Dataset(object): """Data set for text records. A Dataset maintains the collection of data instances and metadata associated with the dataset. Parameters -------...
OCTICON_PAPER_AIRPLANE = """ <svg class="octicon octicon-paper-airplane" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M1.592 2.712L2.38 7.25h4.87a.75.75 0 110 1.5H2.38l-.788 4.538L13.929 8 1.592 2.712zM.989 8L.064 2.68a1.341 1.341 0 011.85-1.462l13.402 5.74...
def test(): a = 10 fun1 = lambda: a fun1() print(a) a += 1 fun1() print(a) return fun1 fun = test() print(f"Fun: {fun()}")
# Author: OMKAR PATHAK # In this example, we will see how to implement graphs in Python class Vertex(object): ''' This class helps to create a Vertex for our graph ''' def __init__(self, key): self.key = key self.edges = {} def addNeighbour(self, neighbour, weight = 0): self.edges[...
# -*- coding: utf-8 -*- """ neutrino_api This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ). """ class Blacklist(object): """Implementation of the 'Blacklist' model. TODO: type model description here. Attributes: is_listed (b...
class DmpIo(): def __init__(self): # inputs self.event = None self.username = None self.password = None
''' Inhalte Arbeit: - Werte einlesen mit try except block - if - Verzweigungen - for - Schleifen (for in ....) for i in lst: for i in range(10): - list - anhängen, sortieren, löschen, ist etwas in einer Liste - dict - keys zugreifen - values zugreifen und auf beide zugreifen - files - lesen und schreiben Übungsprogra...
#!/usr/bin/env python3 """ This prints out my node IPs. nodes-005.py is used to print out..... al;jsdflkajsdf l;ajdsl;faj a;ljsdklfj -------------------------------------------------- """ print('10.10.10.5') print('10.10.10.4') print('10.10.10.3') print('10.10.10.2') print('10.10.10.1')
""" Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string. """ def computegrade(score): if score >= 0.9: return 'A' elif score >= 0.8: return 'B' elif score >= 0.7: ret...
# Desenvolva um programa que pergunte a distancia de uma viagem em Km. #Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 # para viagens mais longas. #minha resposta #dist = float(input('Qual a distancia da sua viagem? ')) #print('Voce está prestes a começar uma viagem de {:.1f}Km'...
name = input("Как вас зовут?:") age = input("Сколько вам лет?:") livePlace = input("Где вы живете?:") age = int(age) print("Это ", name) print("Ему/ей ", age, " лет") print("Он/она живет ", livePlace)
# # PySNMP MIB module CISCO-STACK-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-STACK-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 12:12:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
description = 'system setup' group = 'lowlevel' sysconfig = dict( cache='localhost', instrument='ESTIA', experiment='Exp', datasinks=['conssink', 'filesink', 'daemonsink'], ) modules = ['nicos.commands.standard'] includes = ['temp'] devices = dict( ESTIA=device('nicos.devices.instrument.Instrum...
#!/usr/bin/python # -*- coding: utf-8 -*- #Script by: Jesús Redondo García #Date: 28-10-2014 #Script to process the user metadata about the catalog. #Get all the fields from fields.conf fields_conf_file = open('fields.conf','r') fields_lines = fields_conf_file.readlines() fields_conf_file.close() for line in fields...
a = float(input()) b = float(input()) c = float(input()) media = (a * 2 + b * 3 + c * 5) / (2 + 3 + 5) print("MEDIA = {:.1f}".format(media))
#Aula 7 #Dicionarios lista = [] # dicionario = {'Nome':'Matheus', 'Sobrenome': 'Schuetz' } # print(dicionario) # print(dicionario['Sobrenome']) nome = 'Maria' lista_notas = [10,20,50,70] media = sum(lista_notas)/len(lista_notas) situacao = 'Reprovado' if media >=7: situacao = 'Aprovado' dicionario_alunos = {'No...
TEACHER_AUTHORITIES = [ 'VIEW_PROFILE', 'JUDGE_TASK', 'SHARE_TASK', 'VIEW_ABSENT', 'SUBMIT_LESSON', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'EDIT_PROFILE', 'GIVE_TASK', 'VIEW_TASK', 'ADD_ABSENT' ] STUDENT_AUTHORITIES = [ 'VIEW_PROFILE', 'VIEW_LESSON', 'VIEW_ACTIVITY', 'VIEW_TASK_FRAGMENT', 'DOING_TASK', 'VIEW...
def _init(): global _global_dict _global_dict = {} def set_value(key, value): _global_dict[key] = value def get_value(key): return _global_dict.get(key) _init()
palavra = input('Digite uma palavra para ser advinhada: ') digitadas =[] chances = int(len(palavra)/2) print('\n'*50) while True: if chances <= 0: print(f'Voce perdeu! A palavra era {palavra}') break letra = input('Digite uma letra: ') if len(letra) > 1: print ('Favor, digitar so...
# # PySNMP MIB module CISCO-VLAN-GROUP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-GROUP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
def hello_world(): print("hello world") # [REQ-002] def hello_world_2(): print("hello world") # [/REQ-002]
class Solution: def solve(self, s, pairs): letters = set(ascii_lowercase) leaders = {letter:letter for letter in letters} followers = {letter:[letter] for letter in letters} for a,b in pairs: if leaders[a] == leaders[b]: continue if len(followers...
prompt = "How old are you?" message = "" while message != 'quit': message = input(prompt) if message != 'quit': age = int(message) if age < 3: print("Free") elif age < 12: print("The fare is 10 dollar") else: print("The fare is 15 dollar")
# Variables first_name = "Ada" # print function followed by variable name. print("Hello,", first_name) print(first_name, "is learning Python") # print takes multiple arguments. print("These", "will be", "joined together by spaces") # input statement. first_name = input("What is your first name? ") print("Hello,", fi...
def extractThehlifestyleCom(item): ''' Parser for 'thehlifestyle.com' ''' tstr = str(item['tags']).lower() if 'review' in tstr: return None if 'actors' in tstr: return None if 'game' in tstr: return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "...
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0 # which is available at https://www.volatilityfoundation.org/license/vsl-v1.0 # """Volatility 3 Linux Constants. Windows-specific values that aren't found in debug symbols """ KERNEL_MODULE_NAMES = ["ntkrnlmp", ...
""" This subpackage is intented for low-level extension developers and compiler developers. Regular user SHOULD NOT use code in this module. This contains compilable utility functions that can interact directly with the compiler to implement low-level internal code. """
''' Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). """ Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is n...
# list - список, послідовність елементів # Ініціалізація змінних типу list names = ["john", "rob", "bill"] chars = list("hello") new_chars = ["h", "e", "l", "l", "o"] new_users = [] numbers = list(range(1, 11)) # Перевірка типу print(type(names)) # Перевірка змінної типу list print("rob" in names) print(chars == new_...
""" Definitions used to parse DTED files. """ # Definitions of DTED Record lengths. UHL_SIZE = 80 DSI_SIZE = 648 ACC_SIZE = 2700 # Definitions of the value DTED uses for void data. VOID_DATA_VALUE = (-1 << 15) + 1 _UTF8 = "utf-8"
#Input tamanhoArquivo = float(input("Digite o tamanho do arquivo(em MB): ")) velocidadeInternet = float(input("Digite a velocidade de download ou upload (em Mbps): ")) #Algoritmo velocidadeInternet *= 1024 / 8000 tempoEstimadoInteiro = (tamanhoArquivo / velocidadeInternet) // 60 tempoEstimadoDecimal = (tamanhoA...
ATTACK = '-' SUPPORT = '+' NEUTRAL = '0' CRITICAL_SUPPORT = '+!' CRITICAL_ATTACK = '-!' WEAK_SUPPORT = '+*' WEAK_ATTACK = '-*' NON_SUPPORT = '+~' NON_ATTACK = '-~' TRIPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL] QUADPOLAR_RELATIONS = [ATTACK, SUPPORT, NEUTRAL, CRITICAL_SUPPORT] def get_type(val): if val > 0: ...
# repeating strings s = "?" for i in range(4): print(s, end="") print() print(s * 4) # looping strings text = "This is an example." count = 0 for char in text: # isalpha() returns true if the character is a-z if char.isalpha(): count += 1
CREDENTIALS = { 'username': 'Replace with your WA username', 'password': 'Replace with your WA password (b64)' } DEFAULT_RECIPIENTS = ('single-user@s.whatsapp.net', 'group-chat@g.us',) HOST_NOTIFICATION = '%(emoji)s %(type)s HOST ALERT %(emoji)s\n\n' + \ 'Host %(host)s, %(address)s is %(st...
'''9. Write a Python program to get the difference between the two lists. ''' def difference_twoLists(lst1, lst2): lst1 = set(lst1) lst2 = set(lst2) return list(lst1 - lst2) print(difference_twoLists([1, 2, 3, 4], [4, 5, 6, 7])) print(difference_twoLists([1, 2, 3, 4], [0, 5, 6, 7])) print(difference_twoLis...
''' module for implementation of cycle sort ''' def cycle_sort(arr: list): writes = 0 for cycleStart in range(0, len(arr) - 1): item = arr[cycleStart] pos = cycleStart for i in range(cycleStart + 1, len(arr)): if (arr[i] < item): pos += 1 if (p...
class Error(Exception): """Base class for BMI exceptions""" pass class VarNameError(Error): """Exception to indicate a bad input/output variable name""" def __init__(self, name): self.name = name def __str__(self): return self.name class BMI(object): def initialize(self, f...
class Script: @staticmethod def main(): cities = ["Albuquerque", "Anaheim", "Anchorage", "Arlington", "Atlanta", "Aurora", "Austin", "Bakersfield", "Baltimore", "Boston", "Buffalo", "Charlotte-Mecklenburg", "Cincinnati", "Cleveland", "Colorado Springs", "Corpus Christi", "Dallas", "Denver", "Detroit", "El Paso", "...
class VendingMachine: def __init__(self): self.change = 0 def run(self, raw): tokens = raw.split(" ") cmd, params = tokens[0], tokens[1:] if cmd == "잔돈": return "잔돈은 %d 원입니다" %self.change elif cmd == "동전": coin = params[0] self.change...
""" Some of the options of the protocol specification LINE 1-8 PAGE A-Z (remapped to 0-25) LEADING A/a = Immediate (Image will be immediately disappeared) B/b = Xopen (Image will be disappeared from center and extend to 4 side) C/c = Curtain UP (Image will be disappeared one ...
fig, ax = create_map_background() # Contour 1 - Temperature, dotted cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2), colors='grey', linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabelte...
#Ejercicio 01 def binarySearch(arr, valor): #Dado un arreglo y un elemento #Busca el elemento dado en el arreglo inicio = 0 final = len(arr) - 1 while inicio <= final: medio = (inicio + final) // 2 if arr[medio] == valor: return True elif arr[medio...
# William Thompson (wtt53) # Software Testing and QA # Assignment 1: Test Driven Development # Retirement: Takes current age (int), annual salary (float), # percent of annual salary saved (float), and savings goal (float) # and outputs what age savings goal will be met def calc_retirement(age, salary, percent, goal):...
""" this module provides encryption and decryption of strings """ _eng_alphabet = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)] _rus_alphabet = [chr(i) for i in range(1072, 1104)] + [chr(i) for i in range(1040, 1072)] _alphabets = {'en': _eng_alphabet, 'rus': _rus_alphabet} def _add_encrypted_...