content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Employee: # class variables num_of_employees = 0 raise_amount = 1.04 def __init__(self, first, last, pay): # instance variables self.first = first self.last = last self.pay = pay self.email = f"{first}.{last}@company.com" Employee.num_of_employees +...
class Employee: num_of_employees = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = f'{first}.{last}@company.com' Employee.num_of_employees += 1 def fullname(self): return f'{self...
""" Hacker Rank Problem found here: https://www.hackerrank.com/challenges/electronics-shop/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign 1. Clarifying Questions - are the prices on positive integers? - will the prices alwas be unique within one array? - is the a...
""" Hacker Rank Problem found here: https://www.hackerrank.com/challenges/electronics-shop/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign 1. Clarifying Questions - are the prices on positive integers? - will the prices alwas be unique within one array? - is the a...
# Constants for browser located in this file. # CONFIG DIRECTORY NAMES DIRECTORY_CONFIGURATIONS = 'configurations' DIRECTORY_TOPICS = 'topics' DIRECTORY_AVRO_SCHEMAS = 'avro_schemas' DIRECTORY_DEPLOYMENT_SCRIPTS = 'deployment_scripts' # CONFIG FILENAMES FILE_MAIN_CONFIG = 'main_config.yml' FILE_LOGGER_CONFIG = 'logge...
directory_configurations = 'configurations' directory_topics = 'topics' directory_avro_schemas = 'avro_schemas' directory_deployment_scripts = 'deployment_scripts' file_main_config = 'main_config.yml' file_logger_config = 'logger_config.yml' file_avro_topics = 'avro_topics.yml' file_ui = 'splash.html' request_search_st...
""" For your information: class Node(object): def __init__(self, data=None): self.data = data self.next = None """ def front_back_split(source, front, back): if not source or not front or not back or not source.next: raise Exception() length=0 temp=source while source: ...
""" For your information: class Node(object): def __init__(self, data=None): self.data = data self.next = None """ def front_back_split(source, front, back): if not source or not front or (not back) or (not source.next): raise exception() length = 0 temp = source while sourc...
# # PySNMP MIB module SYMMSYNCE (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMSYNCE # Produced by pysmi-0.3.4 at Tue Jul 30 11:35:09 2019 # On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt # Using Python version 3.7.4 (default, Jul 9 20...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ...
def get_head(line, releases, **kwargs): for release in releases: if "Django {} release notes".format(release) in line: return release return False def get_urls(releases, **kwargs): urls = [] for release in releases: urls.append("https://raw.githubusercontent.com/django/djan...
def get_head(line, releases, **kwargs): for release in releases: if 'Django {} release notes'.format(release) in line: return release return False def get_urls(releases, **kwargs): urls = [] for release in releases: urls.append('https://raw.githubusercontent.com/django/djang...
# Copyright - see copyright.txt class Predicate: """Predicate is one specific ``if'' encountered during the program execution. """ def __init__(self, st, result): self.symtype = st self.result = result def getVars(self): return self.symtype.getVars() def __eq__(self, other): if isinstance(other, Pred...
class Predicate: """Predicate is one specific ``if'' encountered during the program execution. """ def __init__(self, st, result): self.symtype = st self.result = result def get_vars(self): return self.symtype.getVars() def __eq__(self, other): if isinstance(other,...
# Scrapy settings for news project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/topics/settings.html # BOT_NAME = 'news' BOT_VERSION = '1.0' SPIDER_MODULES = ['news.spiders'] NEWSPIDER_MODULE = 'news.spi...
bot_name = 'news' bot_version = '1.0' spider_modules = ['news.spiders'] newspider_module = 'news.spiders' user_agent = '%s/%s' % (BOT_NAME, BOT_VERSION)
# Challenge name: Fun with an interview question # Challenge link: https://danielbmarkham.com/fun-with-an-interview-question/ # Completed by Zack Sargent on: Feb. 6th, 2021 # this was done after I did it in JavaScript. # see ./StringToArray.js for the Javascript version. """ Prompt: Input: "aaaabbbcca" Output: [("...
""" Prompt: Input: "aaaabbbcca" Output: [("a", 4), ("b", 3), ("c", 2), ("a", 1)] Write a function that converts the input to the output. """ def make_array(chars: str): current_char = chars[0] times = 1 output = [] for char in chars[1:]: if char == currentChar: times += 1 ...
class Mapper(object): @staticmethod def map(enum, value): result = None for enum_value in enum: if Mapper._normalize(value) == Mapper._normalize(enum_value.value): result = enum_value return result @staticmethod def _normalize(value: str): ret...
class Mapper(object): @staticmethod def map(enum, value): result = None for enum_value in enum: if Mapper._normalize(value) == Mapper._normalize(enum_value.value): result = enum_value return result @staticmethod def _normalize(value: str): re...
def city_country(city, country): return(city.title() + ", " + country.title()) city = city_country('santiago', 'chile') print(city) city = city_country('ushuaia', 'argentina') print(city) city = city_country('longyearbyen', 'svalbard') print(city)
def city_country(city, country): return city.title() + ', ' + country.title() city = city_country('santiago', 'chile') print(city) city = city_country('ushuaia', 'argentina') print(city) city = city_country('longyearbyen', 'svalbard') print(city)
# -*- coding: utf-8 -*- description = 'setup for Beckhoff PLC mtt devices on PANDA' group = 'lowlevel' devices = dict( mtt = device('nicos.devices.generic.Axis', description = 'Virtual MTT axis that exchanges block automatically ' '(must be used in "automatic" mode).', motor...
description = 'setup for Beckhoff PLC mtt devices on PANDA' group = 'lowlevel' devices = dict(mtt=device('nicos.devices.generic.Axis', description='Virtual MTT axis that exchanges block automatically (must be used in "automatic" mode).', motor=device('nicos.devices.generic.VirtualMotor', abslimits=(-122, -25), unit='de...
def pstrip(s, prefix): """Prefix strip >>> pstrip('foo_oof', 'foo_') 'oof' >>> pstrip('baroof', 'foo_') 'baroof' """ i = len(prefix) if s[:i] == prefix: return s[i:] return s def sstrip(s, suffix): """Suffix strip >>> sstrip('foo.oof', '.oof') 'foo' >>> ss...
def pstrip(s, prefix): """Prefix strip >>> pstrip('foo_oof', 'foo_') 'oof' >>> pstrip('baroof', 'foo_') 'baroof' """ i = len(prefix) if s[:i] == prefix: return s[i:] return s def sstrip(s, suffix): """Suffix strip >>> sstrip('foo.oof', '.oof') 'foo' >>> sst...
""" A list of particle properties. """ c = 3*10**8 # m/sec pion_tau = 2.6*(10**-8) # sec muon_tau = 2.2*(10**-6) # sec pion_mass = 139.6 # MeV muon_mass = 105.7 # MeV electron_mass = 0.5 # MeV electron_ratio = 10**4
""" A list of particle properties. """ c = 3 * 10 ** 8 pion_tau = 2.6 * 10 ** (-8) muon_tau = 2.2 * 10 ** (-6) pion_mass = 139.6 muon_mass = 105.7 electron_mass = 0.5 electron_ratio = 10 ** 4
class Name: def __init__(self, name, age): self.name = name self.age = age def age_next(self): return self.age + 10 def name_len(self): return 'Length of name is {}'.format(len(self.name)) class Education(Name): def __init__(self, name, age, school, btech, ms): ...
class Name: def __init__(self, name, age): self.name = name self.age = age def age_next(self): return self.age + 10 def name_len(self): return 'Length of name is {}'.format(len(self.name)) class Education(Name): def __init__(self, name, age, school, btech, ms): ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 12 13:32:50 2018 @author: afilbrun """ # Problem 4 palindrome = []; for first in range (100,1000): for second in range (100,1000): num = first * second; if str(num) == str(num)[::-1]: palindrome.append(num) print (max(palindrome));
""" Created on Thu Jul 12 13:32:50 2018 @author: afilbrun """ palindrome = [] for first in range(100, 1000): for second in range(100, 1000): num = first * second if str(num) == str(num)[::-1]: palindrome.append(num) print(max(palindrome))
def batch( qs, batch_size=1000 ): """ Returns a ( start, end, total, queryset ) tuple for each batch in the given queryset. Usage: # Make sure to order your querset article_qs = Article.objects.order_by('id') for start, end, total, qs in batch_qs(article_qs): print "...
def batch(qs, batch_size=1000): """ Returns a ( start, end, total, queryset ) tuple for each batch in the given queryset. Usage: # Make sure to order your querset article_qs = Article.objects.order_by('id') for start, end, total, qs in batch_qs(article_qs): print "No...
class Constants: default_config_folder = "config" default_modules_folder = "modules" default_deployment_template_file = "deployment.template.json" default_deployment_debug_template_file = "deployment.debug.template.json" default_platform = "amd64" deployment_template_suffix = ".template.json" ...
class Constants: default_config_folder = 'config' default_modules_folder = 'modules' default_deployment_template_file = 'deployment.template.json' default_deployment_debug_template_file = 'deployment.debug.template.json' default_platform = 'amd64' deployment_template_suffix = '.template.json' ...
# -*- coding: utf-8 -*- def ten_sum_exists(matrix): """Calculate if the numbers provided can sum to 10. :Parameter: matrix: list :Returns: boolean, dict """ if not isinstance(matrix, list): return length = len(matrix) count = 0 pointer = 0 ten_sum_count = ...
def ten_sum_exists(matrix): """Calculate if the numbers provided can sum to 10. :Parameter: matrix: list :Returns: boolean, dict """ if not isinstance(matrix, list): return length = len(matrix) count = 0 pointer = 0 ten_sum_count = 0 calculated_sums = set(...
class PIDController: def __init__(self, kp, ki, kd, goal): self.kp = kp self.ki = ki self.kd = kd self.goal = goal self.error = 0 self.lX = 0 self.dError = 0 self.iError = 0 def correction(self): return (self.error * self.kp + self.iErr...
class Pidcontroller: def __init__(self, kp, ki, kd, goal): self.kp = kp self.ki = ki self.kd = kd self.goal = goal self.error = 0 self.lX = 0 self.dError = 0 self.iError = 0 def correction(self): return self.error * self.kp + self.iError ...
class HWPDecryptor(): def __init__(self, filepath, key): self.data = '' self.key = key with open(filepath, 'rb') as f: data = f.read() self.data = bytearray(data) def decryption(self): r = list() for i in range(0, len(self.data)): ...
class Hwpdecryptor: def __init__(self, filepath, key): self.data = '' self.key = key with open(filepath, 'rb') as f: data = f.read() self.data = bytearray(data) def decryption(self): r = list() for i in range(0, len(self.data)): a = s...
class Solution(object): def divisorGame(self, N): """ :type N: int :rtype: bool """ return True if N % 2 == 0 else False
class Solution(object): def divisor_game(self, N): """ :type N: int :rtype: bool """ return True if N % 2 == 0 else False
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) n = int(input("Please enter your number")) values = [str(fibonacci(x)) for x in range(0, n+1)] print(",".join(values))
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) n = int(input('Please enter your number')) values = [str(fibonacci(x)) for x in range(0, n + 1)] print(','.join(values))
RANDOM_SEED = 7 # constant for reproducability # for training TRAINING_CONFIG = { 'TYPE': 'single_country', # single_country or country_held_out 'COUNTRY': 'malawi_2016', # malawi_2016, ethiopia_2015 'METRIC': 'est_monthly_phone_cost_pc' # house_has_cellphone or est_monthly_phone_cost_pc } # for predicti...
random_seed = 7 training_config = {'TYPE': 'single_country', 'COUNTRY': 'malawi_2016', 'METRIC': 'est_monthly_phone_cost_pc'} vis_config = {'COUNTRY_NAME': 'Ethiopia', 'COUNTRY_ABBRV': 'MWI', 'TYPE': 'single_country', 'COUNTRY': 'ethiopia_2015', 'METRIC': 'est_monthly_phone_cost_pc'}
# Copyright 2019 Zadara Storage, Inc. # Originally authored by Jeremy Brown - https://github.com/jwbrown77 # # 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...
def get_antivirus_status(session, return_type=None, **kwargs): """ Enables the antivirus engine. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type return_type: str :param return_type: If this is set to the string 'json', this func...
""" Utility module to manipulate CSV files. """ __author__ = "Jenson Jose" __email__ = "jensonjose@live.in" __status__ = "Alpha" class CsvUtils: """ Utility class containing methods for manipulating CSV files. """ def __init__(self): pass
""" Utility module to manipulate CSV files. """ __author__ = 'Jenson Jose' __email__ = 'jensonjose@live.in' __status__ = 'Alpha' class Csvutils: """ Utility class containing methods for manipulating CSV files. """ def __init__(self): pass
""" Cutting Ribbons You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all. For example, if you have a ribbon of length 4, you can: Keep the r...
""" Cutting Ribbons You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all. For example, if you have a ribbon of length 4, you can: Keep the r...
class LetterSpacingKeyword: Normal = "normal" class LetterSpacing( LetterSpacingKeyword, Length, ): pass
class Letterspacingkeyword: normal = 'normal' class Letterspacing(LetterSpacingKeyword, Length): pass
""" Dataframes constants """ TRANS = "trans_m" LIQUID = "liquid_m" CATEG = "trans_categ" INVEST = "invest_m" WORTH = "worth_m" ALL_FROM_DATA = [CATEG, LIQUID, INVEST, WORTH] ALL = [TRANS] + ALL_FROM_DATA
""" Dataframes constants """ trans = 'trans_m' liquid = 'liquid_m' categ = 'trans_categ' invest = 'invest_m' worth = 'worth_m' all_from_data = [CATEG, LIQUID, INVEST, WORTH] all = [TRANS] + ALL_FROM_DATA
"""Top-level package for purepython_flagser.""" __author__ = """Nicolas Ninin""" __email__ = 'nicolas.ninin@gmail.com' __version__ = '0.1.0'
"""Top-level package for purepython_flagser.""" __author__ = 'Nicolas Ninin' __email__ = 'nicolas.ninin@gmail.com' __version__ = '0.1.0'
# problem description: https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid/problem def getBiggestRegion(grid): n_row = len(grid) n_col = len(grid[0]) region_sizes = [] for row in range(n_row): for col in range(n_col): region_size = measure_region(grid, row, col) ...
def get_biggest_region(grid): n_row = len(grid) n_col = len(grid[0]) region_sizes = [] for row in range(n_row): for col in range(n_col): region_size = measure_region(grid, row, col) region_sizes.append(region_size) return max(region_sizes) def measure_region(grid, ro...
# -*- coding: utf-8 -*- """ History of past trials ====================== Maintain the history of past trials used by an algorithm. """ # pylint:disable=protected-access,too-few-public-methods class TrialsHistory: """Maintain a list of all the last seen trials that are on different dependency paths""" def ...
""" History of past trials ====================== Maintain the history of past trials used by an algorithm. """ class Trialshistory: """Maintain a list of all the last seen trials that are on different dependency paths""" def __init__(self): """Create empty trials history""" self.children = ...
expected_output = { "my_state": "13 -ACTIVE", "peer_state": "1 -DISABLED", "mode": "Simplex", "unit": "Primary", "unit_id": 48, "redundancy_mode_operational": "Non-redundant", "redundancy_mode_configured": "Non-redundant", "redundancy_state": "Non Redundant", "maintenance_mode": "Di...
expected_output = {'my_state': '13 -ACTIVE', 'peer_state': '1 -DISABLED', 'mode': 'Simplex', 'unit': 'Primary', 'unit_id': 48, 'redundancy_mode_operational': 'Non-redundant', 'redundancy_mode_configured': 'Non-redundant', 'redundancy_state': 'Non Redundant', 'maintenance_mode': 'Disabled', 'manual_swact': 'disabled', ...
class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: int """ self.nums = nums self.reset = lambda: self.nums def shuffle(self): """ Returns a random shuffling of the array. :rtype:...
class Solution(object): def __init__(self, nums): """ :type nums: List[int] :type size: int """ self.nums = nums self.reset = lambda : self.nums def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] ...
t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] a.sort() n *= 2 if n == 2: print(abs(a[-1]-a[0])) else: print(a[n//2]-a[n//2-1])
t = int(input()) for _ in range(t): n = int(input()) a = [int(x) for x in input().split()] a.sort() n *= 2 if n == 2: print(abs(a[-1] - a[0])) else: print(a[n // 2] - a[n // 2 - 1])
# https://wiki.python.org/moin/BitManipulation # testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one. def testBit(int_type, offset): mask = 1 << offset return(int_type & mask) # setBit() returns an integer with the bit at 'offset' set to 1. def setBit(int_type, offset): mask = 1...
def test_bit(int_type, offset): mask = 1 << offset return int_type & mask def set_bit(int_type, offset): mask = 1 << offset return int_type | mask def clear_bit(int_type, offset): print('{0:b}'.format(int_type)) mask = ~(1 << offset) print('{0:b}'.format(mask)) return int_type & mask ...
# Django settings for unit test project. DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sqlite', }, } SITE_ID = 1 ROOT_URLCONF = 'parler_example.urls' SECRET_KEY = 'secret' # Absolute path to the directory that holds media. # Example: "/ho...
debug = True databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'database.sqlite'}} site_id = 1 root_urlconf = 'parler_example.urls' secret_key = 'secret' media_root = '' media_url = '' static_root = '/home/static/' static_url = '/static/' templates = [{'BACKEND': 'django.template.backends.django....
""" File-based help entries. These complements command-based help and help entries added in the database using the `sethelp` command in-game. Control where Evennia reads these entries with `settings.FILE_HELP_ENTRY_MODULES`, which is a list of python-paths to modules to read. A module like this should hold a global `...
""" File-based help entries. These complements command-based help and help entries added in the database using the `sethelp` command in-game. Control where Evennia reads these entries with `settings.FILE_HELP_ENTRY_MODULES`, which is a list of python-paths to modules to read. A module like this should hold a global `...
SCHEDULE_MODE = { 'SECONDS': 1, 'MINUTS': 2, 'HOUR': 3, 'DAY': 4 } SCHEDULE_STATUS = { 'RUNNING': 1, 'STOPPED': 2 } SCHEDULE_ACTIVE = { 'ACTIVE': 1, 'DEACTIVE': 2 } def getDictKeyByName(dictObject, value): for (key, itemValue) in dictObject.items(): if (value == itemValue): return key retu...
schedule_mode = {'SECONDS': 1, 'MINUTS': 2, 'HOUR': 3, 'DAY': 4} schedule_status = {'RUNNING': 1, 'STOPPED': 2} schedule_active = {'ACTIVE': 1, 'DEACTIVE': 2} def get_dict_key_by_name(dictObject, value): for (key, item_value) in dictObject.items(): if value == itemValue: return key return N...
# -------------- class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 new_class.append("Peter Warden") print(new_class) new_class.remove("Carla Gentry") print(new_class) courses = { "Math":65,"English":70,...
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English': 70, 'History':...
# # @lc app=leetcode id=20 lang=python3 # # [20] Valid Parentheses # # @lc code=start class Solution: def isValid(self, s: str) -> bool: # if s == "" if len(s) == 0: return True d = { ')': '(', '}' : '{', ']' : '[' } temp = [] ...
class Solution: def is_valid(self, s: str) -> bool: if len(s) == 0: return True d = {')': '(', '}': '{', ']': '['} temp = [] for item in s: if item not in d: temp.append(item) else: if temp == []: ...
""" Overview ======== This module implements the NORMAL mode that is the mode in which most editing keycommands are implemented. Key-Commands ============ Namespace: normal-mode Mode: -1 Event: <Escape> Description: Get the focused AreaVi instance in NORMAL mode. Mode: -1 Event: <Alt-n> Description: Get the focuse...
""" Overview ======== This module implements the NORMAL mode that is the mode in which most editing keycommands are implemented. Key-Commands ============ Namespace: normal-mode Mode: -1 Event: <Escape> Description: Get the focused AreaVi instance in NORMAL mode. Mode: -1 Event: <Alt-n> Description: Get the focuse...
total_umur_dalam_hari = 75 jumlah_hari_dalam_sebulan = 30 bulan = total_umur_dalam_hari/jumlah_hari_dalam_sebulan hari = total_umur_dalam_hari % jumlah_hari_dalam_sebulan print('umur bayi sekarang {} bulan dan {} hari'.format(bulan,hari)) print('umur bayi sekarang {1} bulan dan {0} hari'.format(hari,bulan)) print('um...
total_umur_dalam_hari = 75 jumlah_hari_dalam_sebulan = 30 bulan = total_umur_dalam_hari / jumlah_hari_dalam_sebulan hari = total_umur_dalam_hari % jumlah_hari_dalam_sebulan print('umur bayi sekarang {} bulan dan {} hari'.format(bulan, hari)) print('umur bayi sekarang {1} bulan dan {0} hari'.format(hari, bulan)) print('...
# Copyright 2018 Road-Support - Roel Adriaans # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Github Connector - OCA extension", "summary": "Add OCA specific information to Odoo modules", "version": "13.0.1.0.0", "category": "Connector", "license": "AGPL-3", "author": ...
{'name': 'Github Connector - OCA extension', 'summary': 'Add OCA specific information to Odoo modules', 'version': '13.0.1.0.0', 'category': 'Connector', 'license': 'AGPL-3', 'author': 'Odoo Community Association (OCA), Road-Support', 'website': 'https://github.com/OCA/interface-github', 'depends': ['github_connector_o...
def initialize(): return 'initialize' def computeTile(x, y, array): spend_some_time() return 'computeTile-' + str(x) + ',' + str(y) def dispose(): return 'dispose' def spend_some_time(): l = list(range(10000)) for i in range(10000): l.reverse()
def initialize(): return 'initialize' def compute_tile(x, y, array): spend_some_time() return 'computeTile-' + str(x) + ',' + str(y) def dispose(): return 'dispose' def spend_some_time(): l = list(range(10000)) for i in range(10000): l.reverse()
# Exibindo valores da lista com for comidas = ['Cebola', 'Tomate', 'Cenoura', 'Ovo', 'Queijo', 'Cerveja'] print("indice - elemento") for indice, elemento in enumerate(comidas): print (f"{indice:<5}{elemento}") print(1 + 1)
comidas = ['Cebola', 'Tomate', 'Cenoura', 'Ovo', 'Queijo', 'Cerveja'] print('indice - elemento') for (indice, elemento) in enumerate(comidas): print(f'{indice:<5}{elemento}') print(1 + 1)
pkgname = "bsded" pkgver = "0.99.0" pkgrel = 0 build_style = "makefile" pkgdesc = "FreeBSD ed(1) utility" maintainer = "q66 <q66@chimera-linux.org>" license = "BSD-2-Clause" url = "https://github.com/chimera-linux/bsded" source = f"https://github.com/chimera-linux/bsded/archive/refs/tags/v{pkgver}.tar.gz" sha256 = "ae3...
pkgname = 'bsded' pkgver = '0.99.0' pkgrel = 0 build_style = 'makefile' pkgdesc = 'FreeBSD ed(1) utility' maintainer = 'q66 <q66@chimera-linux.org>' license = 'BSD-2-Clause' url = 'https://github.com/chimera-linux/bsded' source = f'https://github.com/chimera-linux/bsded/archive/refs/tags/v{pkgver}.tar.gz' sha256 = 'ae3...
def load(): with open("input") as f: yield next(f).strip() next(f) img = {} for y, row in enumerate(f): img.update({(x, y): v for x, v in enumerate(row.strip())}) yield img def get_square(x, y, image, void_value): for i in range(y - 1, y + 2): for j ...
def load(): with open('input') as f: yield next(f).strip() next(f) img = {} for (y, row) in enumerate(f): img.update({(x, y): v for (x, v) in enumerate(row.strip())}) yield img def get_square(x, y, image, void_value): for i in range(y - 1, y + 2): for...
#a function which formats a duration, given as a number of seconds, in a human-friendly way. def format_duration(seconds): if seconds is 0: return 'now' times = ['years', 'days', 'hours', 'minutes', 'seconds'] times_to_seconds = {'years':31536000, 'days':86400, 'hours':3600, 'minutes':60, 'seconds...
def format_duration(seconds): if seconds is 0: return 'now' times = ['years', 'days', 'hours', 'minutes', 'seconds'] times_to_seconds = {'years': 31536000, 'days': 86400, 'hours': 3600, 'minutes': 60, 'seconds': 1} times_to_templates = {'years': '{} year{}', 'days': '{} day{}', 'hours': '{} hour...
# # Bounce constant investigation # Y_BASE = 210 Y_TOP = 88 Y_MAX = 65 # maximum allowed height TIME = 113 # time to bounce # simulates given arc with starting VY and gravity AY # returns (peak,time length) def arc(vy,ay,trace=False): p = 0 y = 0 t = 0 if (trace): print("arc(%5d,%5d)" % (vy,...
y_base = 210 y_top = 88 y_max = 65 time = 113 def arc(vy, ay, trace=False): p = 0 y = 0 t = 0 if trace: print('arc(%5d,%5d)' % (vy, ay)) while y >= 0: if trace: print('%3d: %6d %3d' % (t, vy, Y_BASE - y // 256)) y += vy p = max(p, y) vy -= ay ...
ca, na = map(int, input().split()) fila = [] caixas = [] lim = 0 tempo = 0 for cliente in range(na): chegada, tempo_atendimento = map(int, input().split()) fila.append([chegada, tempo_atendimento]) while fila: try: while (tempo >= fila[0][0]) and (len(caixas) < ca): pessoa = fila[0] caixas.append(pessoa[1]...
(ca, na) = map(int, input().split()) fila = [] caixas = [] lim = 0 tempo = 0 for cliente in range(na): (chegada, tempo_atendimento) = map(int, input().split()) fila.append([chegada, tempo_atendimento]) while fila: try: while tempo >= fila[0][0] and len(caixas) < ca: pessoa = fila[0] ...
class Solution: def isValid(self, s: str) -> bool: if s[0] == ')': return False openClose = {'(':')', '{':'}', '[':']'} stack = [] for i in range(len(s)): if s[i] in '({[': stack.append(s[i]) else: if not stack...
class Solution: def is_valid(self, s: str) -> bool: if s[0] == ')': return False open_close = {'(': ')', '{': '}', '[': ']'} stack = [] for i in range(len(s)): if s[i] in '({[': stack.append(s[i]) else: if not stack...
"""Provides an abstraction around the database.""" def get_repo_list(cnx, branch): # pick all repos with status of 0 cur = cnx.cursor() cur.execute("SELECT `repo` FROM `github_deploy_repo` WHERE `status` = 0") repos = [repo.split('/', 2) for (repo,) in cur] cur.close() repos = [tuple(repo) for repo in rep...
"""Provides an abstraction around the database.""" def get_repo_list(cnx, branch): cur = cnx.cursor() cur.execute('SELECT `repo` FROM `github_deploy_repo` WHERE `status` = 0') repos = [repo.split('/', 2) for (repo,) in cur] cur.close() repos = [tuple(repo) for repo in repos if repo[2] == branch] ...
class ListNode: def __init__(self, x): self.val = x self.next = None def __str__(self): return "Node:%d" % self.val class Solution: # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): dummy = Lis...
class Listnode: def __init__(self, x): self.val = x self.next = None def __str__(self): return 'Node:%d' % self.val class Solution: def remove_elements(self, head, val): dummy = list_node(0) dummy.next = head current = dummy while current and curre...
""" :mod:`disco` -- API Reference ============================= .. toctree:: :titlesonly: :glob: * worker/index worker/classic """
""" :mod:`disco` -- API Reference ============================= .. toctree:: :titlesonly: :glob: * worker/index worker/classic """
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_spark_session": "00_00_core.ipynb", "get_directory_size": "00_00_core.ipynb", "get_size_format": "00_00_core.ipynb"} modules = ["core.py"] doc_url = "https://HansjoergW.github.io/bfh_...
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'get_spark_session': '00_00_core.ipynb', 'get_directory_size': '00_00_core.ipynb', 'get_size_format': '00_00_core.ipynb'} modules = ['core.py'] doc_url = 'https://HansjoergW.github.io/bfh_cas_bgd_fs2020_sa/' git_url = 'https://github.com/HansjoergW/...
def count(word): return f'{word} has {len(word)} characters.' if __name__ == '__main__': print(count(input('What is the input string?')))
def count(word): return f'{word} has {len(word)} characters.' if __name__ == '__main__': print(count(input('What is the input string?')))
#!/usr/bin/python3 for n1 in range(1,11): print("Tabla del " + str(n1)) print("-----------") for n2 in range(1,11): print(str(n1) + " por " + str(n2) + " es " + str(n1*n2))
for n1 in range(1, 11): print('Tabla del ' + str(n1)) print('-----------') for n2 in range(1, 11): print(str(n1) + ' por ' + str(n2) + ' es ' + str(n1 * n2))
#!/usr/bin/env python """wxPython GUI for VAMP project TODO: create (or copy?) a wx.Frame subclass for holding a matplotlib plot with navigation toolbar. """ #import uimain, tension, debug, geometry
"""wxPython GUI for VAMP project TODO: create (or copy?) a wx.Frame subclass for holding a matplotlib plot with navigation toolbar. """
class Solution: def candy(self, ratings: List[int]) -> int: ratingsLength = len(ratings) if ratingsLength == 0: return 0 candies = [1] * ratingsLength for i in range(1, ratingsLength): if ratings[i] > ratings[i - 1]: candies[i] = candies[i - 1]...
class Solution: def candy(self, ratings: List[int]) -> int: ratings_length = len(ratings) if ratingsLength == 0: return 0 candies = [1] * ratingsLength for i in range(1, ratingsLength): if ratings[i] > ratings[i - 1]: candies[i] = candies[i - ...
# Python 3.2 Bug from abc.py # Make sure we handle: # LOAD_FAST '__locals__' # STORE_LOCALS '' # Note this is similar to 05_abc_class.py but not the same: # object -> classmethod class abstractclassmethod(object): """A Python 3.2 STORE_LOCALS bug """ def __init__(self, callable): ...
class Abstractclassmethod(object): """A Python 3.2 STORE_LOCALS bug """ def __init__(self, callable): callable.__isabstractmethod__ = True
""" https://leetcode.com/problems/kth-missing-positive-number/ Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive int...
""" https://leetcode.com/problems/kth-missing-positive-number/ Given an array arr of positive integers sorted in a strictly increasing order, and an integer k. Find the kth positive integer that is missing from this array. Example 1: Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive int...
expected_output = { 'cores': { 1: { 'virtual_service': 'guestshell+', 'process_name': 'sleep', 'pid': 266, 'date': '2019-05-30 19:53:28', }, } }
expected_output = {'cores': {1: {'virtual_service': 'guestshell+', 'process_name': 'sleep', 'pid': 266, 'date': '2019-05-30 19:53:28'}}}
# Copyright 2009 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ '../../../../../build/common.gypi', ], 'targets': [ { 'target_name': 'service_runtime_x86_32', 'type': 'static...
{'includes': ['../../../../../build/common.gypi'], 'targets': [{'target_name': 'service_runtime_x86_32', 'type': 'static_library', 'sources': ['nacl_app_32.c', 'nacl_switch_32.S', 'nacl_switch_all_regs_32.c', 'nacl_switch_all_regs_asm_32.S', 'nacl_switch_to_app_32.c', 'nacl_syscall_32.S', 'nacl_tls_32.c', 'sel_addrspac...
n=int(input()) x=[0]+[*map(int,input().split())] dp=[0]*(n+5) dp[1]=x[1] ans=dp[1] for i in range(2,n+1): dp[i]=x[i] for j in range(1,i): if x[j]>x[i]: dp[i]=max(dp[i],dp[j]+x[i]) ans=max(ans,dp[i]) print(ans)
n = int(input()) x = [0] + [*map(int, input().split())] dp = [0] * (n + 5) dp[1] = x[1] ans = dp[1] for i in range(2, n + 1): dp[i] = x[i] for j in range(1, i): if x[j] > x[i]: dp[i] = max(dp[i], dp[j] + x[i]) ans = max(ans, dp[i]) print(ans)
n = int(input()) slist = [] for i in range(2,n): iss = False for ii in range(2,i): if i%ii == 0: iss = True break; if not iss: slist.append(i) print(slist)
n = int(input()) slist = [] for i in range(2, n): iss = False for ii in range(2, i): if i % ii == 0: iss = True break if not iss: slist.append(i) print(slist)
def binary_classification_metrics(prediction, ground_truth): ''' Computes metrics for binary classification Arguments: prediction, np array of bool (num_samples) - model predictions ground_truth, np array of bool (num_samples) - true labels Returns: precision, recall, f1, accuracy - classi...
def binary_classification_metrics(prediction, ground_truth): """ Computes metrics for binary classification Arguments: prediction, np array of bool (num_samples) - model predictions ground_truth, np array of bool (num_samples) - true labels Returns: precision, recall, f1, accuracy - classi...
global driver def infect(driver_): global driver driver = driver_ class Widget: selector = None def __init__(self, driver): self.driver = driver def setup_class(self): if self.selector is None: raise Exception('You need to assign me a selector: %s' % self) se...
global driver def infect(driver_): global driver driver = driver_ class Widget: selector = None def __init__(self, driver): self.driver = driver def setup_class(self): if self.selector is None: raise exception('You need to assign me a selector: %s' % self) sel...
# # PySNMP MIB module LIEBERT-GP-AGENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIEBERT-GP-AGENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:06:38 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (defau...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ...
class ParsingError(Exception): pass class UnexpectedToken(ParsingError): def __init__(self, index): super().__init__() self.index = index
class Parsingerror(Exception): pass class Unexpectedtoken(ParsingError): def __init__(self, index): super().__init__() self.index = index
the_list = [1,2,3,4,5,6,7,8,9,10] def filter_evens(li): even_numbers = [items for items in the_list if items % 2 ==0] print(even_numbers) filter_evens(the_list)
the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def filter_evens(li): even_numbers = [items for items in the_list if items % 2 == 0] print(even_numbers) filter_evens(the_list)
# dictionaries fruit = { "orange": "a sweet, orange, citrus frtui", "apple": "good for making cider", "lemon": "a sour, yellow citrus fruit", "grape": "a small, sweet fruit growing in bunches", "lime": " a sour, green citruis fruit" } # print(fruit) # print(fruit["lemon"]) fruit["pear"] = "an odd s...
fruit = {'orange': 'a sweet, orange, citrus frtui', 'apple': 'good for making cider', 'lemon': 'a sour, yellow citrus fruit', 'grape': 'a small, sweet fruit growing in bunches', 'lime': ' a sour, green citruis fruit'} fruit['pear'] = 'an odd shaped apple' fruit['lime'] = 'great with tequila' while True: dict_key = ...
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: n = len(nums) l = [] for i, j in enumerate(nums): l.append((j, i)) l.sort(key = lambda x: x[0]) #print(l) i = 0 j = 1 while j < n...
class Solution: def contains_nearby_almost_duplicate(self, nums: List[int], k: int, t: int) -> bool: n = len(nums) l = [] for (i, j) in enumerate(nums): l.append((j, i)) l.sort(key=lambda x: x[0]) i = 0 j = 1 while j < n: if abs(l[j][0...
exp_token = "dns" exp_dir = "./exp_diversity_noise" q_ratio = "0.2" test_ratio = "0.5" maj_ratio = 0.755558 prepare_data = False submit = True split_size = 1000 n_test = 100 n_test_maj = 100 * maj_ratio n_test_min = 100 - n_test_maj k_maj = 5 * maj_ratio k_min = 5. - k_maj alpha = "0.1" n_runs = 100 n_runs_test = 1000 ...
exp_token = 'dns' exp_dir = './exp_diversity_noise' q_ratio = '0.2' test_ratio = '0.5' maj_ratio = 0.755558 prepare_data = False submit = True split_size = 1000 n_test = 100 n_test_maj = 100 * maj_ratio n_test_min = 100 - n_test_maj k_maj = 5 * maj_ratio k_min = 5.0 - k_maj alpha = '0.1' n_runs = 100 n_runs_test = 1000...
class ConsensusModule(torch.nn.Module): """docstring for ConsensusModule""" def __init__(self, consensus_type, dim = 1): super(ConsensusModule, self).__init__() self.consensus_type = consensus_type if consensus_type != 'rnn' else 'identity' self.dim = dim
class Consensusmodule(torch.nn.Module): """docstring for ConsensusModule""" def __init__(self, consensus_type, dim=1): super(ConsensusModule, self).__init__() self.consensus_type = consensus_type if consensus_type != 'rnn' else 'identity' self.dim = dim
n = int(input()) for i in range(n): alg = str(input()) e = str(input()).split() r = int(e[0]) g = int(e[1]) b = int(e[2]) if alg == 'eye' : p = int(0.3 * r + 0.59 * g + 0.11 * b) elif alg == 'mean': p = int((r + g + b) / 3) elif alg == 'max' : p = sorted([r, g, b])[2] elif alg == '...
n = int(input()) for i in range(n): alg = str(input()) e = str(input()).split() r = int(e[0]) g = int(e[1]) b = int(e[2]) if alg == 'eye': p = int(0.3 * r + 0.59 * g + 0.11 * b) elif alg == 'mean': p = int((r + g + b) / 3) elif alg == 'max': p = sorted([r, g, b])[...
class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f"Pizza({self.ingredients!r})" print(Pizza(["cheese", "tomatoes"]))
class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients!r})' print(pizza(['cheese', 'tomatoes']))
class GridViewColumn(DependencyObject, INotifyPropertyChanged): """ Represents a column that displays data. GridViewColumn() """ def OnHeaderStringFormatChanged(self, *args): """ OnHeaderStringFormatChanged(self: GridViewColumn,oldHeaderStringFormat: str,newHeaderStringFormat: str) ...
class Gridviewcolumn(DependencyObject, INotifyPropertyChanged): """ Represents a column that displays data. GridViewColumn() """ def on_header_string_format_changed(self, *args): """ OnHeaderStringFormatChanged(self: GridViewColumn,oldHeaderStringFormat: str,newHeaderStringFormat: str) Occ...
#setting RPPpath = r"D:\document\python projects\Autolipsync\scripttest2.rpp" TEMPLATEPath = r"D:\document\python projects\Autolipsync\template.exo" LIPPath = r"D:\document\python projects\Autolipsync\*.avi" ExportPath = "RPPtoEXO(Lyric).exo" FPS = 60
rp_ppath = 'D:\\document\\python projects\\Autolipsync\\scripttest2.rpp' template_path = 'D:\\document\\python projects\\Autolipsync\\template.exo' lip_path = 'D:\\document\\python projects\\Autolipsync\\*.avi' export_path = 'RPPtoEXO(Lyric).exo' fps = 60
# %% def isprime(n): if n == 1: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True def solution(n, k): enc = [] while n != 0: enc.append(n % k) n = n // k curr = enc[-1] answer = 0 for v in enc[-2::-...
def isprime(n): if n == 1: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True def solution(n, k): enc = [] while n != 0: enc.append(n % k) n = n // k curr = enc[-1] answer = 0 for v in enc[-2::-1]: ...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftANDleftGLOBALUNTILleftNEGleftLPARENRPARENATOMICLBRACKRBRACKNUMBER COMMA LPAREN RPAREN LBRACK RBRACK AND NEG ATOMIC GLOBAL UNTIL\n\texpression \t: expression AND expression\n\t\t\t\t| NEG e...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftANDleftGLOBALUNTILleftNEGleftLPARENRPARENATOMICLBRACKRBRACKNUMBER COMMA LPAREN RPAREN LBRACK RBRACK AND NEG ATOMIC GLOBAL UNTIL\n\texpression \t: expression AND expression\n\t\t\t\t| NEG expression\n\t\t\t\t| GLOBAL LBRACK NUMBER RBRACK expression\n\t\t\t\t|...
""" Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = Non...
""" Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5 """ class Solution: def sort_list(self, head: ListNode) -> ListNode: def sort_list(head): if head is None: ...
''' Polynomials are given as a list i.e. 2x^3 - 6x^2 + 2x - 1 = [2, -6, 2, -1] ''' def polynomial(): coefficients = [] n = int(input("Enter number of coefficients: \n")) print("Enter coefficients: \n") for i in range(0, n): element = int(input()) coefficients.append(element) x = float(input("Value to eval...
""" Polynomials are given as a list i.e. 2x^3 - 6x^2 + 2x - 1 = [2, -6, 2, -1] """ def polynomial(): coefficients = [] n = int(input('Enter number of coefficients: \n')) print('Enter coefficients: \n') for i in range(0, n): element = int(input()) coefficients.append(element) x = fl...
""" Propagate the generated Swift header from a swift_library target This exists to work around https://github.com/bazelbuild/rules_swift/issues/291 """ def _swift_header_collector(ctx): headers = [ DefaultInfo( files = ctx.attr.library[CcInfo].compilation_context.headers, ), ] ...
""" Propagate the generated Swift header from a swift_library target This exists to work around https://github.com/bazelbuild/rules_swift/issues/291 """ def _swift_header_collector(ctx): headers = [default_info(files=ctx.attr.library[CcInfo].compilation_context.headers)] if len(headers[0].files.to_list()) != 1...
class Router(object): def db_for_read(self, model, **hints): return 'read' def db_for_write(self, model, **hints): return 'default'
class Router(object): def db_for_read(self, model, **hints): return 'read' def db_for_write(self, model, **hints): return 'default'
state_data = [{'id': 'AL', 'name': 'Alabama', 'code': 'AL', 'electoral_votes': 9, 'campaign_cost': 18, 'popular_vote': 2.1, 'groups': ['AA', 'OS']}, {'id': 'AK', 'name': 'Alaska', 'code'...
state_data = [{'id': 'AL', 'name': 'Alabama', 'code': 'AL', 'electoral_votes': 9, 'campaign_cost': 18, 'popular_vote': 2.1, 'groups': ['AA', 'OS']}, {'id': 'AK', 'name': 'Alaska', 'code': 'AK', 'electoral_votes': 3, 'campaign_cost': 10, 'popular_vote': 0.3, 'groups': ['OG']}, {'id': 'AZ', 'name': 'Arizona', 'code': 'AZ...
#!/usr/bin/python # function def my_function(): print("Hello world!") # call function def call_function(): print("Hello world!") call_function() # output: # Hello world! # parameters def pa_function(param): print("Hello", param) pa_function("Emily") pa_function("John") # output: # Hello Emily # Hello Jo...
def my_function(): print('Hello world!') def call_function(): print('Hello world!') call_function() def pa_function(param): print('Hello', param) pa_function('Emily') pa_function('John') def de_function(name='Cat'): print('Hello' + name) de_function() de_function('Dog') def ret_function(x): retu...
words=['Wednesday', 'a lot', 'absence', 'accept', 'acceptable', 'accessible', 'accidentally', 'accommodate', 'accompanied', 'accomplish', 'accumulate', 'accuracy', 'achievement', 'acknowledgment', 'acquaintance', 'acquire', 'acquitted', 'across', 'actually', 'address', 'admission', 'adolescent', 'advice', 'advise', 'ad...
words = ['Wednesday', 'a lot', 'absence', 'accept', 'acceptable', 'accessible', 'accidentally', 'accommodate', 'accompanied', 'accomplish', 'accumulate', 'accuracy', 'achievement', 'acknowledgment', 'acquaintance', 'acquire', 'acquitted', 'across', 'actually', 'address', 'admission', 'adolescent', 'advice', 'advise', '...
# -*- coding: iso-8859-1 -*- """ MoinMoin - Datasets Datasets are used by the DataBrowserWidget, and with the statistics code. @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ class Column: """ Meta-data for a column. """ _SLOTS = [ ...
""" MoinMoin - Datasets Datasets are used by the DataBrowserWidget, and with the statistics code. @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ class Column: """ Meta-data for a column. """ _slots = [('label', ''), ('sortable', 0), ('hidd...
def total_parity(n): """ Checks the binary parity of the value `n`. 01001 is even parity, 011001 is odd parity. :param n: any positive integer :returns: 1 for odd parity, 0 for even parity. """ if n == 0: return 0 N = int(np.ceil(np.log2(n))) if 2 ** N == n: N += 1 ...
def total_parity(n): """ Checks the binary parity of the value `n`. 01001 is even parity, 011001 is odd parity. :param n: any positive integer :returns: 1 for odd parity, 0 for even parity. """ if n == 0: return 0 n = int(np.ceil(np.log2(n))) if 2 ** N == n: n += 1 ...
#-*- coding:utf-8 class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name.title() + "'s cuisine type is " + self.cuisine_type + ".") def...
class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name.title() + "'s cuisine type is " + self.cuisine_type + '.') def open_restaurant(sel...
# -*- coding: utf-8 -*- # @Time : 2021/1/3 # @Author : handsomezhou #start:setting table_setting="setting" INDEX_ID=int(0) INDEX_KEY=int(1) INDEX_VALUE=int(2) INDEX_CREATE_TIME=int(3) INDEX_UPDATE_TIME=int(4) id = "id" key = "key" value = "value" create_time = "create_time" update_time = "update_time" CREATE_TABL...
table_setting = 'setting' index_id = int(0) index_key = int(1) index_value = int(2) index_create_time = int(3) index_update_time = int(4) id = 'id' key = 'key' value = 'value' create_time = 'create_time' update_time = 'update_time' create_table_setting = 'CREATE TABLE IF NOT EXISTS ' + table_setting + '(' + id + ' INTE...
def convert(num): num = int(num) new = bin(num)[2:] new = ((32 - len(new)) * '0') + new return new def maping_one(num, indexs): for i in range(len(num)): if (i not in indexs): indexs[i] = [0, []] if (num[i] == '1'): indexs[i][0] += 1 indexs[i][1]....
def convert(num): num = int(num) new = bin(num)[2:] new = (32 - len(new)) * '0' + new return new def maping_one(num, indexs): for i in range(len(num)): if i not in indexs: indexs[i] = [0, []] if num[i] == '1': indexs[i][0] += 1 indexs[i][1].append...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Author : windpro E-mail : windprog@gmail.com Date : 15/8/26 Desc : """
""" Author : windpro E-mail : windprog@gmail.com Date : 15/8/26 Desc : """
# -*- coding: utf-8 -*- """ @author: Francis Franklin """
""" @author: Francis Franklin """
""" PASSENGERS """ numPassengers = 19157 passenger_arriving = ( (14, 8, 6, 8, 8, 0, 0, 1, 4, 0, 0, 2, 0, 7, 3, 3, 4, 3, 2, 0, 1, 0, 2, 2, 0, 0), # 0 (5, 5, 6, 5, 3, 2, 5, 2, 3, 5, 1, 1, 0, 7, 6, 5, 3, 8, 5, 1, 2, 2, 1, 0, 0, 0), # 1 (5, 9, 4, 2, 7, 4, 2, 1, 2, 0, 0, 0, 0, 10, 3, 5, 1, 6, 3, 3, 2, 3, 1, 0, 0, 0)...
""" PASSENGERS """ num_passengers = 19157 passenger_arriving = ((14, 8, 6, 8, 8, 0, 0, 1, 4, 0, 0, 2, 0, 7, 3, 3, 4, 3, 2, 0, 1, 0, 2, 2, 0, 0), (5, 5, 6, 5, 3, 2, 5, 2, 3, 5, 1, 1, 0, 7, 6, 5, 3, 8, 5, 1, 2, 2, 1, 0, 0, 0), (5, 9, 4, 2, 7, 4, 2, 1, 2, 0, 0, 0, 0, 10, 3, 5, 1, 6, 3, 3, 2, 3, 1, 0, 0, 0), (9, 3, 5, 2, 7...
def add_up(a, b): return a + b def test_add_up_succeed(): assert add_up(1, 2) == 3 def test_add_up_fail(): assert add_up(1, 2) == 4 def ignore_me(): assert "I will be" == "completely ignored"
def add_up(a, b): return a + b def test_add_up_succeed(): assert add_up(1, 2) == 3 def test_add_up_fail(): assert add_up(1, 2) == 4 def ignore_me(): assert 'I will be' == 'completely ignored'
destination = input() while destination != "End": needed_money = float(input()) saved_money = 0 while saved_money < needed_money: saved_money += float(input()) print(f"Going to {destination}!") destination = input()
destination = input() while destination != 'End': needed_money = float(input()) saved_money = 0 while saved_money < needed_money: saved_money += float(input()) print(f'Going to {destination}!') destination = input()
while True: try: # get an integer for age age = int(input('What is your age? ')) 10/age print('You are',age, 'years old.') except ValueError as err: #if anything accept an int is enter print following error print(f''' please enter a number for your age. Error 10001 {err} '''...
while True: try: age = int(input('What is your age? ')) 10 / age print('You are', age, 'years old.') except ValueError as err: print(f'\n please enter a number for your age.\n Error 10001\n {err}\n ') continue except ArithmeticError as err: print(f...
# Return the remainder def remainder(x: int, y: int) -> int: return x % y # remainder_lambda = lambda x, y: x % y if __name__ == "__main__": print(remainder(1, 3))
def remainder(x: int, y: int) -> int: return x % y if __name__ == '__main__': print(remainder(1, 3))