content
stringlengths
7
1.05M
class Calculadora: def soma(self, valor_a, valor_b): return valor_a + valor_b def subtracao(self, valor_a, valor_b): return valor_a - valor_b def multiplacacao(self, valor_a, valor_b): return valor_a * valor_b def divisao(self, valor_a, valor_b): return valor_a / valo...
#!/usr/bin/python #Excercise 1 from Chapter 4 spam = ['apples','bananas','tofu','cats'] def structlist(lists): sstring = "" for i in range(len(lists)): if i == len(lists)-1: sstring +="and "+lists[i] print(sstring) break else: sstring += lists[i]...
# -*- coding: utf-8 -*- # 基础异常 class BaseError(Exception): def __init__(self, data=None): super().__init__() self._data = data @property def data(self): return self._data def __repr__(self): return repr(self._data) # 数据库只读限制异常 class MySQLReadOnlyError(BaseError...
#crie um programa que leia um número real qualquer e mostre sua porção inteira #ex: 6.127 --> 6 '''from math import trunc num = float(input('Digite um valor: ')) print('O valor digitado foi {} e sua porção inteira é {}'.format(num, trunc(num)))''' num = float(input('Digite um número: ')) print('O valor digitado foi {...
# 源程序文件名 SOURCE_FILE = "{filename}.py_" # 输出程序文件名 OUTPUT_FILE = "{filename}.py" # 编译命令行 COMPILE = "cp {source} {output} {extra}" # 运行命令行 RUN = 'sh -c "python2.7 {program} {redirect}"' # 显示名 DISPLAY = "Python 2.7" # 版本 VERSION = "CPython 2.7" # Ace.js模式 ACE_MODE = "python"
# Configuration file for ipcontroller. c = get_config() #------------------------------------------------------------------------------ # IPControllerApp configuration #------------------------------------------------------------------------------ # IPControllerApp will inherit config from: BaseParallelApplication, ...
# Package Constants # Meraki dashboard API key, set either at instantiation or as an environment variable API_KEY_ENVIRONMENT_VARIABLE = 'MERAKI_DASHBOARD_API_KEY' # Base URL preceding all endpoint resources DEFAULT_BASE_URL = 'https://api.meraki.com/api/v1' # Maximum number of seconds for each API call SINGLE_REQUE...
class Solution: # @param word1 & word2: Two string. # @return: The minimum number of steps. def minDistance(self, word1, word2): # write your code here dp = [] for i in range(len(word1) + 1): dp.append([]) for j in range(len(word2) + 1): if (i ...
fp = open("assets/virus2.csv", "r", encoding="utf-8") lines = fp.readlines() fp.close() n = len(lines) if lines[n-1][0:10] == lines[n-2][0:10]: lines.pop(n-2) pass with open("assets/virus2.csv", "w", encoding="utf-8") as fp: start = 10 stop = 26 id = 0 for line in lines: if id !=0: ...
# # PySNMP MIB module ZHONE-COM-IP-FILTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-FILTER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:40:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
class Solution(object): def findDuplicate(self, paths): """ :type paths: List[str] :rtype: List[List[str]] """ ret = [] hm = dict() self.buildHashMap(paths, hm) return [v for v in hm.itervalues() if len(v)>1] def buildHashMap(self, paths,...
user = "" password = "" host = "127.0.0.1" database = "" raise_on_warnings = True config = { "user": user, "password": password, "host": host, "database": database, "raise_on_warnings": raise_on_warnings, } def set_configs(user=None, password=None, database=None): config["user"] = user co...
dic = { 'color':'red', 'typw':'car', 'price': 1250 }
""" Return text based on the tab number passed """ def descriptions(index): if index == 0: # Machine Tab return text_0 elif index == 1: # Display Tab return text_1 elif index == 2: # Axis Tab return text_2 elif index == 3: # Spindle Tab return text_3 elif index == 4: # Inputs Tab return text_4 elif i...
# Store the RSS feed IDs for each of the topics in the CNBC client. cnbc_rss_feeds_id = { 'top_news': 100003114, 'world_news': 100727362, 'us_news': 15837362, 'asia_news': 19832390, 'europe_news': 19794221, 'business': 10001147, 'earnings': 15839135, 'commentary': 100370673, ...
# START PROBLEM SET 01 print('PROBLEM SET 01 \n') # PROBLEM 01A (25 points) # Uncomment the variable name and assigned value that adheres to the styling # convention described in PEP 08 for function and variable names # (see https://www.python.org/dev/peps/pep-0008/#function-and-variable-names) # Choose wisely or you ...
##함수 def isQueueFull(): global SIZE, front, rear if (rear != SIZE - 1) and (front == -1): return False else: for i in range(front+1,SIZE): queue[i-1] = queue[i] queue[i] = None front -= 1 rear -= 1 return False def enQueue(data): global SIZ...
class BasicCalculator: def __init__(self): return def sum(self, num1, num2): return num1 + num2 def sub(self, num1, num2): return num1 - num2 def mul(self, num1, num2): return num1 * num2 def div(self, num1, num2): return num1 / num2 class AdvancedCalculator(BasicCalculator): def __...
#!/usr/bin/env python3 # Print out all the unique pairwise amino acid combinations # AC is the same as CA # Skip AA, CC etc. # Also print out how many combinations there are amino = 'ACDEFGHIKLMNPQRSTVWY' k = 1 i = -1 for i in range(i, len(amino)): i += 1 for i2 in range(i+1, len(amino)): print(amino[i], amino[i2...
#!/usr/bin/env python3 def harmasosztas(szam): if szam in range(0, 10): return "00" + str(szam) elif szam in range(10, 100): return "0" + str(szam) elif szam in range(100, 1000): return szam else: return str(harmasosztas(szam // 1000)) + " " + str(harmasosztas(szam % 1000)) def main(): prin...
keywords = ["asm","else","new","this","auto","enum","operator","throw","bool","explicit","private","true","break","export","protected","try","case","extern","public","typedef","catch","false","register","typeid","char","float","reinterpret_cast","typename","class","for","return","union","const","friend","short","unsign...
EventRandomDialogue = 1 EventRandomEffects = 2 EventEstateGravity = 3 EventGlobalGravity = 4 EventSirMaxBirthday = 5 RandomCheesyList = [ 1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 11, 11] RandomCheesyMinTime = 3 RandomCheesyMaxTime = 60
area_code_filename = 'area_code.json' hunters_file = 'hunters.xlsx' # get方法请求头 get_headers = { 'Host': 'www.51jingying.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'Cookie': '' } # post方法请求头 post_headers = { 'X-R...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/1/2 14:55' _ooOoo_ o8888888o 88" . "88 (| -_- |) ...
mylist = [[1,2,3],[4,5,6],[4,3,8]] print("Multi-Dimensional List",mylist) mylist[1].reverse() mylist[0].reverse() print("Multi-Dimensional After Sublist-List",mylist)
N = 10**3 count = 0 for i in range(1, N+1): # 1 ~ N まで for j in range(i, N+1, i): # N以下の i の倍数 count += 1 print(count)
print('{:=^50}'.format('Aono informática')) valor = float(input('Digite o valor das compras? R$')) print('''FORMA DE PAGAMENTO [ 1 ] á Vista dinheiro/cheque com 10% de desconto [ 2 ] 2x no cartão [ 3 ] 3x ou mais no cartão com 20% de juros''') aperte = int(input('Digite a opção desejada')) print('-=-'*20) print('Valor ...
class Pessoa: nome = 'Nome Padrão' p1 = Pessoa() p2 = Pessoa() p1.nome = "Marcelo" print(p1.nome) print(p1.__dict__) # {'nome': 'Marcelo'} # Quando eu tento mudar um atributo da classe através de uma instância, ela não altera o valor do atributo da classe, e sim cria um atributo diretamente na instância print(...
def print_metrics(counter, metrics, summary_writer=None, prefix=None, model_name=""): if 'cls_report' in metrics.keys(): metrics = metrics.copy() del metrics['cls_report'] # print(prefix + "\t" + "\t".join([f"{key}:{valu...
class AudioFile: def __init__(self, filename): if not filename.endswith(self.ext): raise Exception ('Formato Inválido!') self.filename = filename pass class MP3File(AudioFile): ext = 'mp3' f = MP3File('flamingos.wav')
# Argument that are used to create simulation objects. # # They are resolved as follows: # # 1. Numeric values are inlined. # 2. List and Tuples are iterated over, creating a # separate simulation object for each value. # 3. Strings are evaluated as previous keys of ARGS. # If it fails to find a key, ...
def entrada(): p,n = map(int,input().split()) x = input().split() for i in range(len(x)): x[i] = int(x[i]) return p,n,x def verifica(a,b,p): if abs(a-b) > p: return True else: return False def main(): p,n,x = entrada() a = False ...
''' *** A program for the cryptanalysis of Caesar cipher and identify the plaintext *** ''' #All albhabet Frequencies in Known and meaningful English words al_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00...
def main(): usernameStr = input("Enter username:") passwordStr = input("Enter password:") browser = webdriver.Chrome() browser.get(('http://192.168.100.100:8090/')) # fill in username and hit the next button username = browser.find_element_by_id('username') username.send_keys(usernameStr) ...
class LinearSchedule(object): r"""A linear scheduling from an initial to a final value over a certain timesteps, then the final value is fixed constantly afterwards. .. note:: This could be useful for following use cases: * Decay of epsilon-greedy: initialized with :math:`1.0` an...
""" There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the poi...
class DkuApplication(object): def __init__(self, name, label, source, model_func, preprocessing, weights, input_shape=None): self.name = name self.label = label self.source = source self.model_func = model_func self.preprocessing = preprocessing self.input_shape = inp...
# Use for, .split(), and if to create a Statement that will print out words that start with 's': print("Challenge 1 : ") st = 'Print only the words that start with s in this sentence' for word in st.split(): if word[0]=='s' or word[0]=='S': print(word) # Use range() to print all the even numbers from 0 t...
eUnit = { 0: "Academy, Disabled", 1: "Gator, disabled", 3: "Archer, D", 4: "Archer", 5: "Hand Cannoneer", 6: "Elite Skirmisher", 7: "Skirmisher", 8: "Longbowman", 9: "Arrow", 10: "Archery Range 3", 11: "Mangudai", 12: "Barracks", 13: "Fishing Ship", 14: "Archery R...
#Return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. def get_middle(s): if len(s) % 2 == 0: return s[int(len(s) / 2) - 1] + s[int((len(s) / 2))] else: return s[int(len(s) / 2)] #Alterna...
# codeforces round 600 div 2 - A # solved in time # https://codeforces.com/contest/1253/problem/A?locale=en t = int(input()) for i in range(t): n = int(input()) a_list = input().split(' ') b_list = input().split(' ') prev_diff = 0 current_diff = 0 diff_found = 0 result = '' if n == 1...
""" From Medium post "Google Interview Questions Deconstructed: The Knight’s Dialer" by Alex Golec: https://hackernoon.com/google-interview-questions-deconstructed-the-knights-dialer-f780d516f029 Imagine you place a knight chess piece on a phone dial pad. This chess piece moves in an uppercase “L” shape: two steps hor...
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': '', 'USER': '', 'PASSWORD': '...
def add_native_methods(clazz): def __java_init______(a0): raise NotImplementedError() def selectAlternatives__com_sun_xml_internal_ws_policy_EffectivePolicyModifier__com_sun_xml_internal_ws_policy_AssertionValidationProcessor__(a0, a1): raise NotImplementedError() clazz.__java_init______ =...
# -*- coding: utf-8 -*- print('%2d-%02d' % (3, 1)) print('%.2f' % 3.1415926) print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)) s1 = 72 s2 = 85 r = '{0} 成绩提升了 {1:.1f} %' s3 = (s2-s1)%s1 print(r.format('小明',s3)) print('%s 成绩提升了 %.1f %%'%('小明', s3)) ch = '中文' chencode = ch.encode('utf-8') print(chencode) chd...
############### Configuration file for Bayesian ############### n_epochs = 10000 lr_start = 0.0001 num_workers = 16 valid_size = 0.1 batch_size = 1024 train_ens = 1 valid_ens = 1 record_mean_var = True recording_freq_per_epoch = 8 record_layers = ['fc5'] # Cross-module global variables mean_var_dir = No...
''' Solve the problem of skyscrapers game github: https://github.com/VictoriyaRoy/skyscrapers ''' def read_input(path: str) -> list: """ Read game board file from path. Return list of str. """ with open(path, mode = 'r', encoding = 'utf-8') as file: board = file.read().split('\n') retur...
# Copyright (c) 2012-2021 Esri R&D Center Zurich # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law o...
class ClassPropertyDescriptor(object): """Based on https://stackoverflow.com/questions/5189699/how-to-make-a-class-property""" def __init__(self, fget): self.fget = fget def __get__(self, obj, klass): if klass is None: klass = type(obj) return self.fget.__get__(obj, kla...
idade = 20 if idade >=18: print("maior de idade") elif idade < 18: print("menor de idade") else: print("valor inválido ")
# Exceptions indicating the reaction completer has an error # __author__ = 'Haoyan Huo' __maintainer__ = 'Haoyan Huo' __email__ = 'haoyan.huo@lbl.gov' class FormulaException(Exception): """ A chemical formula cannot be parsed. """ pass class CannotBalance(Exception): """ A general exception ...
''' Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M). More formally check if there exists two indices i and j such that : i != j 0 <= i, j < arr.length arr[i] == 2 * arr[j] Example 1: Input: arr = [10,2,5,3] Output: true Explanation: N = 1...
# Author: btjanaka (Bryon Tjanaka) # Problem: (HackerRank) summing-the-n-series # Title: Summing the N series # Link: https://www.hackerrank.com/challenges/summing-the-n-series/problem # Idea: The terms cancel out such that the sum is just n^2. # Difficulty: easy # Tags: math t = int(input()) MOD = 10**9 + 7 for i in r...
def classify(entries): for entry in entries: entry['category_id'] = 1 entry['event_id'] = 1 return entries
# __***__ are especial functions and attributes def dynamic_function(): print('dynamic_function') class MyClass: """A simple example class""" # default: __doc__=... i: int # it is a instance attribute att = 'static' # it is a static attribute def __init__(self, name): # constructor: __init_...
# Given list of values. We play a game against the opponent and we always grab # one value from either left or right side of our list of values. Our opponent # does the same move. What is the maximum value we can grab if our opponent # plays optimally, just like us. def optimal_values(V): T = [[0]*(len(V)+1) for ...
""" x + y sum of x and y x - y difference of x and y x * y product of x and y x / y quotient of x and y x // y floored quotient of x and y x % y remainder of x / y -x x negated +x x unchanged abs(x) absolute value or magnitude of x int(x) x converted to integer float(x) x converted t...
a = int(input('Digite o primeiro número:')) b = int(input('Digite o segundo número:')) c = int(input('Digite o terceiro número:')) menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c maior = a if b > a and b > c: maior = b if c > a and c > b: maior = c print('O maior valor foi {} e ...
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.6 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # %% [markdown] ...
""" 如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。 只有给定的树是单值二叉树时,才返回 true;否则返回 false。 示例 1: 输入:[1,1,1,1,1,null,1] 输出:true 示例 2: 输入:[2,2,2,5,2] 输出:false 提示: 给定树的节点数范围是 [1, 100]。 每个节点的值都是整数,范围为 [0, 99] 。 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # se...
stars = "" for i in range(0, 5, 1): for j in range(0, i, 1): stars += "*" print(stars)
# -*- coding: utf-8 -*- class TestClient(object): """ fake_client will call the wrapped api function, going through all middlewares """ def __init__(self, app): self.app = app def __getattr__(self, item): api = self.app.api_map.get(item) if api is None: ra...
''' Configuration for the style, size, and elements of the GUI will be configured here ''' class window: scale_height = 0.5 scale_width = 0.5
linestyles = {'wind_speed': '-', 'wind_gust': '--', 'pressure': '-'} fig, axes = plt.subplots(1, len(plot_variables), sharex=True, figsize=(18, 6)) for ax, var_names in zip(axes, plot_variables): for var_name in var_names: # Grab the color from our dictionary and pass it to plot() color = colors[...
n =str( input('Digite um valor: ')) # mostra se o valor é numerico, verdadeiro ou falso print('é numero? ') print(n.isnumeric()) # mostra se o valor é letra, verdadeiro ou falso print('é letra? ') print(n.isalpha()) # mostra se o valor é alfanumerico, verdadeiro ou falso print('é alfanumérico? ') print(n.isalnum()) ...
#! /usr/bin/env python3 REQUEST = 'Request' PRE_PREPARE = 'PrePrepare' PREPARE = 'Prepare' COMMIT = 'Commit' RESULT = 'Result' VIEW_CHANGE = 'ViewChange' NEW_VIEW = 'NewView' # Decouple actual message from preprepare message is highly recommended for optimization (etc. choice of protocol for small and...
{ "targets": [{ "target_name": "picosat", "include_dirs": [ "<!(node -e \"require('napi-macros')\")" ], "sources": [ "index.c", "lib/picosat.c" ] }] }
################################# FINAL SETTING! # model settings voxel_size = [0.05, 0.05, 0.1] point_cloud_range = [0, -40, -3, 70.4, 40, 1] # MOCO Model model = dict( # type='Inter_Intro_moco', type='Inter_Intro_moco_better', img_backbone=dict( type='ResNet', depth=50, num_stag...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 最小公倍数の計算 def gcd(n1:int, n2:int): if n2 == 0: return n1 else: return gcd(n2, n1%n2) if __name__ == "__main__": print(gcd(120, 180))
class ScoreCard: def __init__(self, score_text: str): score_texts = score_text.split('|') self.normal_turns = [score_texts[i] for i in range(10)] if len(score_texts) == 12: self.additional_turns = [score_texts[11]] self.all_turns = self.normal_turns + self.additional_tur...
class RefreshIPOperation(object): def __init__(self, vm_service, resource_id_parser): """ :param vm_service: cloudshell.cp.azure.domain.services.virtual_machine_service.VirtualMachineService :param resource_id_parser: cloudshell.cp.azure.common.parsers.azure_model_parser.AzureModelsParser ...
## Copyright 2018 The Chromium Authors. All rights reserved. ## Use of this source code is governed by a BSD-style license that can be ## found in the LICENSE file. ProtocolCompatibilityInfo = provider() def _check_protocol_compatibility_impl(ctx): stamp = ctx.actions.declare_file("{}.stamp".format(ctx.attr.name)...
bot_token = "" users = [ ] website_links =[ "https://www.google.com", ]
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
test = { 'name': 'q3_b', 'points': 5, 'suites': [ { 'cases': [ { 'code': '>>> no_match in ' "list(['professor', 'engineer', " "'scientist', 'cat'])\n" 'True', ...
class CookieContainer(object): """ Provides a container for a collection of System.Net.CookieCollection objects. CookieContainer() CookieContainer(capacity: int) CookieContainer(capacity: int,perDomainCapacity: int,maxCookieSize: int) """ def ZZZ(self): """hardcoded/mock instance of the class"""...
#I, Andy Le, student number 000805099, certify that all code submitted is my own work; # that i have not copied it from any other source. I also certify that I have not allowed my work to be copied by others. color = input("What is your favourite color? ") print("You said " + color) #This is a comment, Python wil...
# variables 2 x = 5 y = "John" print(x) print(y) # variables in py dont need to be specified as a boolean int char string etc
def format_timestamp(timestamp): localtime = timestamp.timetuple() result = unicode(int(time.strftime(u'%I', localtime))) result += time.strftime(u':%M %p, %A %B ', localtime) result += unicode(int(time.strftime(u'%d', localtime))) result += time.strftime(u', %Y') return result
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): idx = 0 while my_list and idx < x: try: print("{:d}".format(my_list[idx]), end="") idx += 1 except IndexError: break print() return idx
#9TH PROGRAM # THIS PROGRAM WILL HELP IN ACCESSING DICTIONARY ITEMS AND PERFROM CERTAIN OPERATIONS WITH DICTIONARY ages = {} #EMPTY DICTIONARY ages["Micky"] = 24 ages["Lucky"] = 25 print(ages) keys = ages.keys # .keys prints all the keys avaialble in Dictionary print(keys) values = ages.values # .values prints a...
# coding=utf-8 """ @Time: 2020/11/14 2:15 下午 @Author: Aopolin @File: MolweniConfig.py @Contact: aopolin.ii@gmail.com @Description: """ class Config(object): def __init__(self): self.SQUAD_DIR = "../../Dataset/squad2.0" self.MOLWENI_DIR = "../../Dataset/Molweni" ...
# # PySNMP MIB module A3COM-HUAWEI-LswIGSP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LswIGSP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:51:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
#!/usr/bin/env python # encoding: utf-8 def build_log_urls(node, path): url = node.web_url_for( 'addon_view_or_download_file', path=path, provider='osfstorage' ) return { 'view': url, 'download': url + '?action=download' } class OsfStorageNodeLogger(object): ...
T = input() hh, mm = map(int, T.split(':')) mm += 5 if mm > 59: hh += 1 mm %= 60 if hh > 23: hh %= 24 print('%02d:%02d' % (hh, mm))
class NodeSocketInterfaceIntUnsigned: default_value = None max_value = None min_value = None
''' # TASK 5 - Write a function that takes a string and a shift integer and returns the string with each letter shifted - you can iterate over the letters in a string - for letter in str: ''' def get_shifted_string(string, shift): ''' return the input string with each letter shifted shift steps ''' raise ...
mytuple = (9,8,7,5,4,1,2,3) num = len(mytuple) print("# of element:", num) min_value = min(mytuple) max_value = max(mytuple) print("Min value:", min_value) print("Max value:", max_value)
class CalcController: def __init__(self, model, view): self.model = model self.model.OnResult = self.OnResult self.model.OnError = self.OnError self.view = view self.model.AllClear() # interface for view def command(self, command): if command in ['0','1','2'...
# Delete all keys that start with 'foo'. for k in hiera.keys(): if k.startswith('foo'): hiera.pop(k)
# -*- coding: utf-8 -*- # # Copyright 2012 James Thornton (http://jamesthornton.com) # BSD License (see LICENSE for details) # """ Bulbs is a Python persistence framework for graph databases. Bulbs is a Python client library for Neo4j Server and Rexster, Rexster is a REST server that provides access t...
length = float(input()) width = float(input()) height = float(input()) perc_full = float(input()) aquarium_volume = length*width*height total_liters = aquarium_volume*0.001 perc = perc_full*0.01 needed_liters = total_liters*(1-perc) print(needed_liters)
"""Part 2: Write a Python program to add two given lists using lambda. Hint : Map nums1 = [1, 4, 5, 6, 5] nums2 = [3, 5, 7, 2, 5] Expected Input Output Result: after adding two list [4, 9, 12, 8, 10] Update code in script_2/lambda_2.py""" nums1 = [1, 4, 5, 6, 5] nums2 = [3, 5, 7, 2, 5] result = map(lambda x, y: x + ...
def maximum_subarray(nums): current_sum = max_sum = nums[0] for num in nums[1:]: current_sum = max(num, current_sum + num) max_sum = max(max_sum, current_sum) return max_sum if __name__ == '__main__': print(maximum_subarray([-2,1,-3,4,-1,2,1,-5,4]))
class MocNode: def __init__(self): self.name = '' self.parent = '' self.refmoc = [] def setName(self, name): self.name = name def setParent(self, parent): self.parent = parent def setRefmoc(self, refmoc): self.refmoc = refmoc
print("| U0 | U1 | U2 | Element |") print("|--|--|--|--------|") stack = [] for a in (0, 1, 2): for b in (0, 1, 2): for c in (0, 1, 2): stack.append(str(a) if a != 0 else '') stack.append(((str(b) if b > 1 else '') + 'x') if b != 0 else '') sta...
print(" ADIN EGIAZTAKETA\n") adina=int(input("Sartu zure adina: ")) while adina<0: print(f"{adina} zenbaki negatibo bat da eta ezin dezu adin negatiborik eduki.") adina=int(input("Sartu zure adina: ")) while adina>130: print(f"{adina} adin haundiegi bat da, ez det sinisten adin hoi dezunik.") adin...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"show_binmask": "00_core.ipynb", "BinaryMasksBlock": "00_core.ipynb", "TensorBinMasks": "00_core.ipynb", "TensorBinMasks2TensorMask": "00_core.ipynb", "CocoData": "01_datas...
#Banar for Em-Bomber def logo(): return ("""\033[1;92m ___ ___ _ | __>._ _ _ ___ | . > ___ ._ _ _ | |_ ___ _ _ | _> | ' ' ||___|| . \/ . \| ' ' || . \/ ._>| '_> |___>|_|_|_| |___/\___/|_|_|_||___/\___.|_| \033[0;0...
DEFAULT_TIMEOUT = 120 def test_upgrade_simple(context, client): _run_upgrade(context, client, 1, 1, finalScale=2, intervalMillis=100) def test_upgrade_odd_numbers(context, client): _run_upgrade(context, client, 5, 2, batchSize=100, finalScale=3, intervalMillis=100) def test_upgrade_to_too_high(context, client): _run...