content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class LastPassError(Exception): def __init__(self, output): self.output = output class CliNotInstalledException(Exception): pass
class Lastpasserror(Exception): def __init__(self, output): self.output = output class Clinotinstalledexception(Exception): pass
n=int(input()) arr=[int(x) for x in input().split()] brr=[int(x) for x in input().split()] my_list=[] for i in arr[1:]: my_list.append(i) for i in brr[1:]: my_list.append(i) for i in range(1,n+1): if i in my_list: if i == n: print("I become the guy.") break else: ...
n = int(input()) arr = [int(x) for x in input().split()] brr = [int(x) for x in input().split()] my_list = [] for i in arr[1:]: my_list.append(i) for i in brr[1:]: my_list.append(i) for i in range(1, n + 1): if i in my_list: if i == n: print('I become the guy.') break ...
class APICONTROLLERNAMEController(apicontrollersbase.APIOperationBase): def __init__(self, apirequest): super(APICONTROLLERNAMEController, self).__init__(apirequest) return def validaterequest(self): logging.debug('performing custom validation..') #validate required ...
class Apicontrollernamecontroller(apicontrollersbase.APIOperationBase): def __init__(self, apirequest): super(APICONTROLLERNAMEController, self).__init__(apirequest) return def validaterequest(self): logging.debug('performing custom validation..') return def getrequesttype...
# Leo colorizer control file for c mode. # This file is in the public domain. # Properties for c mode. properties = { "commentEnd": "*/", "commentStart": "/*", "doubleBracketIndent": "false", "indentCloseBrackets": "}", "indentNextLine": "\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|...
properties = {'commentEnd': '*/', 'commentStart': '/*', 'doubleBracketIndent': 'false', 'indentCloseBrackets': '}', 'indentNextLine': '\\s*(((if|while)\\s*\\(|else\\s*|else\\s+if\\s*\\(|for\\s*\\(.*\\))[^{;]*)', 'indentOpenBrackets': '{', 'lineComment': '//', 'lineUpClosingBracket': 'true', 'wordBreakChars': ',+-=<>/?^...
class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort(key = lambda interval : interval[1]) res = 0 prev = intervals[0][1] for i in range(1, len(intervals)): if intervals[i][0] < prev: res +=1 else: prev = intervals[i][1...
class Solution: def erase_overlap_intervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort(key=lambda interval: interval[1]) res = 0 prev = intervals[0][1] for i in range(1, len(intervals)): if intervals[i][0] < pr...
#https://www.interviewbit.com/problems/max-distance/ def maximumGap(A): left = [A[0]] right = [A[-1]] n = len(A) for i in range(1,n): left.append(min(left[-1], A[i])) for i in range(n-2, -1, -1): right.insert(0, max(right[0], A[i])) i,j,gap = 0, 0, -1 while (i < n and j < n):...
def maximum_gap(A): left = [A[0]] right = [A[-1]] n = len(A) for i in range(1, n): left.append(min(left[-1], A[i])) for i in range(n - 2, -1, -1): right.insert(0, max(right[0], A[i])) (i, j, gap) = (0, 0, -1) while i < n and j < n: if left[i] < right[j]: g...
''' Created on May 24, 2012 @author: newatv2user ''' PIANO_RPC_HOST = "tuner.pandora.com" PIANO_ONE_HOST = "internal-tuner.pandora.com" PIANO_RPC_PATH = "/services/json/?" class PianoUserInfo: def __init__(self): self.listenerId = '' self.authToken = '' class PianoStation: def __init...
""" Created on May 24, 2012 @author: newatv2user """ piano_rpc_host = 'tuner.pandora.com' piano_one_host = 'internal-tuner.pandora.com' piano_rpc_path = '/services/json/?' class Pianouserinfo: def __init__(self): self.listenerId = '' self.authToken = '' class Pianostation: def __init__(self...
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
class Error(object): @staticmethod def exceeded_maximum_metric_capacity(): return 'ErrorExceededMaximumMetricCapacity' @staticmethod def missing_attribute(): return 'ErrorMissingAttributes' @staticmethod def is_not_lower(): return 'ErrorNotLowerCase' @staticmethod...
class Singleton(type): def __new__(meta, name, bases, attrs): attrs["_instance"] = None return super().__new__(meta, name, bases, attrs) def __call__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__call__(*args, **kwargs) return cls._instance
class Singleton(type): def __new__(meta, name, bases, attrs): attrs['_instance'] = None return super().__new__(meta, name, bases, attrs) def __call__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__call__(*args, **kwargs) return cls._instance
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/gaogaotiantian/pygictower/blob/master/NOTICE __version__ = "0.0.1"
__version__ = '0.0.1'
def countBits(n: int) -> list[int]: result = [0] for i in range(1,n+1): count = 0 test = ~(i - 1) while test & 1 == 0: test >>= 1 count += 1 result.append(result[i-1] - count + 1) return result
def count_bits(n: int) -> list[int]: result = [0] for i in range(1, n + 1): count = 0 test = ~(i - 1) while test & 1 == 0: test >>= 1 count += 1 result.append(result[i - 1] - count + 1) return result
# Solution to Advent of Code 2020 day 6 # Read data with open("input.txt") as inFile: groups = inFile.read().split("\n\n") # Part 1 yesAnswers = sum([len(set(group.replace("\n", ""))) for group in groups]) print("Solution for part 1:", yesAnswers) # Part 2 yesAnswers = 0 for group in groups: persons = group....
with open('input.txt') as in_file: groups = inFile.read().split('\n\n') yes_answers = sum([len(set(group.replace('\n', ''))) for group in groups]) print('Solution for part 1:', yesAnswers) yes_answers = 0 for group in groups: persons = group.split('\n') same_answers = set(persons[0]) for person in perso...
DOCARRAY_PULL_NAME = "fashion-product-images-clip-all" DATA_DIR = "../data/images" # Where are the files? CSV_FILE = "../data/styles.csv" # Where's the metadata? WORKSPACE_DIR = "../embeddings" DIMS = 512 # This should be same shape as vector embedding
docarray_pull_name = 'fashion-product-images-clip-all' data_dir = '../data/images' csv_file = '../data/styles.csv' workspace_dir = '../embeddings' dims = 512
def Instagram_scroller(driver,command): print('In scroller function') while True: while True: l0 = ["scroll up","call down","call don","scroll down","up","down","exit","roll down","croll down","roll up","croll up"] if len([i for i in l0 if i in command]) != 0: ...
def instagram_scroller(driver, command): print('In scroller function') while True: while True: l0 = ['scroll up', 'call down', 'call don', 'scroll down', 'up', 'down', 'exit', 'roll down', 'croll down', 'roll up', 'croll up'] if len([i for i in l0 if i in command]) != 0: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- def _is_tensor(x): return hasattr(x, "__len__")
def _is_tensor(x): return hasattr(x, '__len__')
#Collaborators: None def rerun(): #Function is here to rerun the program for total of two times y = 0 while y<2: yogurtshack() y += 1 def yogurtshack(): print("Welcome to Yogurt Shack! Please type your order below. ") #Introducing the store and asking for order print("\n") fla...
def rerun(): y = 0 while y < 2: yogurtshack() y += 1 def yogurtshack(): print('Welcome to Yogurt Shack! Please type your order below. ') print('\n') flavor = input('What would you like your yogurt flavor to be? ') topping1 = input('Topping 1? ') topping2 = input('Topping 2? ...
def print_fun(): print("Heloo") class bala: Name = "This is Shifat" def shit(self): print("Say my name !") print("I'm in a class") def __str__(self): return self.Name
def print_fun(): print('Heloo') class Bala: name = 'This is Shifat' def shit(self): print('Say my name !') print("I'm in a class") def __str__(self): return self.Name
''' This module represents the time stamp when Arelle was last built @author: Mark V Systems Limited (c) Copyright 2013 Mark V Systems Limited, All rights reserved. ''' version = '2013-10-08 05:43 UTC'
""" This module represents the time stamp when Arelle was last built @author: Mark V Systems Limited (c) Copyright 2013 Mark V Systems Limited, All rights reserved. """ version = '2013-10-08 05:43 UTC'
pedidos = [] def adicionaPedidos(nome, sabor, observacao='None'): pedido = {} pedido['nome'] = nome pedido['sabor'] = sabor pedido['observacao'] = observacao return (pedido) pedidos.append(adicionaPedidos('mario', 'pepperoni')) pedidos.append(adicionaPedidos('marco', 'portuguesa', 'dobro de presu...
pedidos = [] def adiciona_pedidos(nome, sabor, observacao='None'): pedido = {} pedido['nome'] = nome pedido['sabor'] = sabor pedido['observacao'] = observacao return pedido pedidos.append(adiciona_pedidos('mario', 'pepperoni')) pedidos.append(adiciona_pedidos('marco', 'portuguesa', 'dobro de presun...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPAR_ABREPAR_CIERRArightIGUALleftORleftANDleftNO_IGUALnonassocMAYORMENORMAYOR_IGUALMENOR_IGUALleftMASMENOSleftASTERISCODIVISIONMODULOleftPOTENCIArightNOTleftLLAVE_AB...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftPAR_ABREPAR_CIERRArightIGUALleftORleftANDleftNO_IGUALnonassocMAYORMENORMAYOR_IGUALMENOR_IGUALleftMASMENOSleftASTERISCODIVISIONMODULOleftPOTENCIArightNOTleftLLAVE_ABRELLAVE_CIERRAABS ADD ALL ALTER AND AS ASC ASTERISCO AVG BETWEEN BIGINT BOOLEAN BY CADENA CASE...
#pangram - sentence with all alphabets #example - The quick brown fox jumps over the lazy dog #read the input myStr = input("Enter a sentence: ").lower() #eliminating all the spaces myStr = myStr.replace(" ", "") #eliminating all commonly used special characters myStr = myStr.replace("," , "") myStr = myStr.replace("...
my_str = input('Enter a sentence: ').lower() my_str = myStr.replace(' ', '') my_str = myStr.replace(',', '') my_str = myStr.replace('.', '') my_str = myStr.replace('!', '') my_set = set(myStr) if len(mySet) == 26: print('Entered string is a Pangram String') else: print('Not a Pangram String')
__all__ = ["Roll"] class Roll: pass
__all__ = ['Roll'] class Roll: pass
class ApiHttpRequest: GET_METHOD = 'GET' POST_METHOD = 'POST' HTTP_METHODS = [GET_METHOD, POST_METHOD] def __init__(self, api_http_request_method: str, api_url: str, api_http_request_headers: dict = None, api_http_request_body: str = None) -> None: self._method = api_http_requ...
class Apihttprequest: get_method = 'GET' post_method = 'POST' http_methods = [GET_METHOD, POST_METHOD] def __init__(self, api_http_request_method: str, api_url: str, api_http_request_headers: dict=None, api_http_request_body: str=None) -> None: self._method = api_http_request_method sel...
# This code reads a text file from user input, finds words and sorts them by unique count then alphabetically. # C++ version is named "sortwords.cpp" and uses no built-in maps. # Dict is like std::map in C++ result = dict() # Count total number of words totalWords = 0 for line in open(input("Enter the filename:...
result = dict() total_words = 0 for line in open(input('Enter the filename: '), encoding='utf8'): for word in ''.join((c for c in line.rstrip().lower() if c == ' ' or c.isalpha())).split(' '): if word != '': result[word] = result[word] + 1 if word in result else 1 total_words += 1 re...
# https://www.hackerrank.com/challenges/crush/problem?isFullScreen=true def reduce_x(a, b, c): mod = 1000000007 return a % mod, b % mod, c % mod # Main Method if __name__ == '__main__': n, m = map(int, input().split()) arr = [0] * (n + 2) for _ in range(m): a, b, k = map(int...
def reduce_x(a, b, c): mod = 1000000007 return (a % mod, b % mod, c % mod) if __name__ == '__main__': (n, m) = map(int, input().split()) arr = [0] * (n + 2) for _ in range(m): (a, b, k) = map(int, input().split()) (a, b, k) = reduce_x(a, b, k) arr[a] += k arr[b + 1] -...
def calcManhattanDist(x1, y1, x2, y2) -> float: return abs(x1 - x2) + abs(y1 - y2) def main(): print(calcManhattanDist(2, 5, 10, 14)) if __name__ == "__main__": main()
def calc_manhattan_dist(x1, y1, x2, y2) -> float: return abs(x1 - x2) + abs(y1 - y2) def main(): print(calc_manhattan_dist(2, 5, 10, 14)) if __name__ == '__main__': main()
def collatz(n): seq = [n] while n != 1: if n % 2 == 0: n = n / 2 seq.append(int(n)) else: n = 3 * n + 1 seq.append(int(n)) return len(seq) i = 1 seqs = [] dictich = {} while i < 1000000: length = collatz(i) dictich[le...
def collatz(n): seq = [n] while n != 1: if n % 2 == 0: n = n / 2 seq.append(int(n)) else: n = 3 * n + 1 seq.append(int(n)) return len(seq) i = 1 seqs = [] dictich = {} while i < 1000000: length = collatz(i) dictich[length] = i seqs....
# DEVELOPER NOTES: # Copy this file and rename it to config.py # Replace your client/secret/callback url for each environment below with your specific app details # (Note: local is mainly for BB2 internal developers) ConfigType = { 'production' : { 'bb2BaseUrl' : 'https://api.bluebutton.cms.gov', '...
config_type = {'production': {'bb2BaseUrl': 'https://api.bluebutton.cms.gov', 'bb2ClientId': '<client-id>', 'bb2ClientSecret': '<client-secret>', 'bb2CallbackUrl': '<only https is supported in prod>', 'port': 3001, 'host': 'Unk'}, 'sandbox': {'bb2BaseUrl': 'https://sandbox.bluebutton.cms.gov', 'bb2ClientId': '<client-i...
class prm: std = dict( field_color="mediumseagreen", field_markings_color="White", title_color="White", ) pc = dict( field_color="White", field_markings_color="black", title_color="black" ) field_width = 1000 field_height = 700 field_dim = (106.0, 68.0) ...
class Prm: std = dict(field_color='mediumseagreen', field_markings_color='White', title_color='White') pc = dict(field_color='White', field_markings_color='black', title_color='black') field_width = 1000 field_height = 700 field_dim = (106.0, 68.0) marker_border_color = 'white' marker_border...
assert gradiente('rojo', 'azul') == gradiente('rojo', 'azul') assert gradiente('rojo', 'azul', inicio='centro') == gradiente('rojo', 'azul') assert gradiente('rojo', 'azul', inicio='izquierda') == gradiente('rojo', 'azul', inicio='izquierda') assert gradiente('rojo', 'azul') != gradiente('rojo', 'azul', inicio='izquie...
assert gradiente('rojo', 'azul') == gradiente('rojo', 'azul') assert gradiente('rojo', 'azul', inicio='centro') == gradiente('rojo', 'azul') assert gradiente('rojo', 'azul', inicio='izquierda') == gradiente('rojo', 'azul', inicio='izquierda') assert gradiente('rojo', 'azul') != gradiente('rojo', 'azul', inicio='izquier...
def foo(y): x = 5 x / y def bar(): foo(0) bar()
def foo(y): x = 5 x / y def bar(): foo(0) bar()
class Error(Exception): def __init__(self, message, error): self.message = message self.error = error @property def code(self): return 503 @property def name(self): return self.__class__.__name__ @property def description(self): return self.message ...
class Error(Exception): def __init__(self, message, error): self.message = message self.error = error @property def code(self): return 503 @property def name(self): return self.__class__.__name__ @property def description(self): return self.message...
def sixIntegers(): print("Please enter 6 integers:") i = 0 even = 0 odd = 0 while i < 6: try: six = input(">") six = int(six) i += 1 if (six % 2) == 0: even = even + six elif (six % 2) == 1: odd = od...
def six_integers(): print('Please enter 6 integers:') i = 0 even = 0 odd = 0 while i < 6: try: six = input('>') six = int(six) i += 1 if six % 2 == 0: even = even + six elif six % 2 == 1: odd = odd + ...
class YLBaseServer(object): def name(self): pass def handle(self, args): pass def startup(self, *args): pass def stop(self, *args): pass
class Ylbaseserver(object): def name(self): pass def handle(self, args): pass def startup(self, *args): pass def stop(self, *args): pass
#!/usr/local/bin/python3 def checkDriverAge(age=0): # if not age: # age = int(input('What is your age?: ')) if int(age) < 18: print('Sorry, you are too young to drive this car ' 'Powering off!') elif int(age) > 18: print('Powering On. Enjoy the ride!') elif int(ag...
def check_driver_age(age=0): if int(age) < 18: print('Sorry, you are too young to drive this car Powering off!') elif int(age) > 18: print('Powering On. Enjoy the ride!') elif int(age) == 18: print('Congratulations on your first year ofdriving. Enjoy the ride') return age if __na...
#!/usr/bin/env python3 #encoding=utf-8 #--------------------------------------- # Usage: python3 5-tracer1.py # Description: Recall from Chapter 30 that the __call__ operator overloading # method implements a function-call interface for class instances. # The following code uses this to def...
class Tracer: def __init__(self, func): self.calls = 0 self.func = func def __call__(self, *args): self.calls += 1 print('call %s to %s' % (self.calls, self.func.__name__)) return self.func(*args) if __name__ == '__main__': '\n Because the spam function is run th...
class Artist: def __init__(self, name = 'None', birthYear = 0, deathYear = 0): self.name = name self.BirthYear = birthYear self.deathYear = deathYear def printInfo(self): if self.deathYear == str('alive'): print('Artist: {}, born {}'.format(self.name, self.BirthYear))...
class Artist: def __init__(self, name='None', birthYear=0, deathYear=0): self.name = name self.BirthYear = birthYear self.deathYear = deathYear def print_info(self): if self.deathYear == str('alive'): print('Artist: {}, born {}'.format(self.name, self.BirthYear)) ...
alert_failure_count = 0 MAX_TEMP_ALLOWED_IN_CELCIUS = 200 def network_alert_stub(celcius): print(f'ALERT: Temperature is {celcius} celcius') if(celcius <= MAX_TEMP_ALLOWED_IN_CELCIUS): # Return 200 for ok return 200 else: # Return 500 for not-ok return 500 def network_a...
alert_failure_count = 0 max_temp_allowed_in_celcius = 200 def network_alert_stub(celcius): print(f'ALERT: Temperature is {celcius} celcius') if celcius <= MAX_TEMP_ALLOWED_IN_CELCIUS: return 200 else: return 500 def network_alert_real(celcius): return 200 def farenheit2celcius(farenhe...
class Spam(object): def __init__(self, count): self.count = count def __eq__(self, other): return self.count == other.count
class Spam(object): def __init__(self, count): self.count = count def __eq__(self, other): return self.count == other.count
class Node: def __init__(self, data=None, pointer=None): self.data = data self.pointer = pointer def set_data(self, data): self.data = data def get_data(self): return self.data def set_pointer(self, pointer): self.pointer = pointer def get_pointer(self): ...
class Node: def __init__(self, data=None, pointer=None): self.data = data self.pointer = pointer def set_data(self, data): self.data = data def get_data(self): return self.data def set_pointer(self, pointer): self.pointer = pointer def get_pointer(self): ...
def test_message_create_list(test_client, version_header): payload = {"subject": "heyhey", "message": "testing"} create_response = test_client.post( "/messages", json=payload, headers=version_header ) assert create_response.status_code == 201 response = test_client.get("/me...
def test_message_create_list(test_client, version_header): payload = {'subject': 'heyhey', 'message': 'testing'} create_response = test_client.post('/messages', json=payload, headers=version_header) assert create_response.status_code == 201 response = test_client.get('/messages', headers=version_header)...
# 11. Write a program that asks the user to enter a word that contains the letter a. The program # should then print the following two lines: On the first line should be the part of the string up # to and including the the first a, and on the second line should be the rest of the string. Sample # output is shown below:...
word = input('Enter a word: ') idx = word.find('a') print(word[:idx + 1]) print(word[idx + 1:])
''' The floor number we can check given m moves and k eggs. dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1 ''' class Solution: def superEggDrop(self, K: int, N: int) -> int: dp = [0] * (K + 1) m = 0 while dp[K] < N: for k in range(K, 0, -1): dp[k] = dp[k - 1] + d...
""" The floor number we can check given m moves and k eggs. dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1 """ class Solution: def super_egg_drop(self, K: int, N: int) -> int: dp = [0] * (K + 1) m = 0 while dp[K] < N: for k in range(K, 0, -1): dp[k] = dp[k - 1] ...
def dfs(node,parent,ptaken): if dp[node][ptaken]!=-1: return dp[node][ptaken] taking,nottaking=1,0 total=0 tways for neig in graph[node]: if neig!=parent: taking+=dfs(neig,node,1) nottaking+=dfs(neig,node,0) if ptaken: dp[node][ptaken]=min(taking,nottaking) else: dp[node][ptaken]=taking return dp...
def dfs(node, parent, ptaken): if dp[node][ptaken] != -1: return dp[node][ptaken] (taking, nottaking) = (1, 0) total = 0 tways for neig in graph[node]: if neig != parent: taking += dfs(neig, node, 1) nottaking += dfs(neig, node, 0) if ptaken: dp[no...
# Vicfred # https://atcoder.jp/contests/abc154/tasks/abc154_a # simulation s, t = input().split() a, b = list(map(int, input().split())) u = input() balls = {} balls[s] = a balls[t] = b balls[u] = balls[u] - 1 print(balls[s], balls[t])
(s, t) = input().split() (a, b) = list(map(int, input().split())) u = input() balls = {} balls[s] = a balls[t] = b balls[u] = balls[u] - 1 print(balls[s], balls[t])
class Solution: def longestPalindrome(self, s: str) -> str: def expand(left:int, right:int) -> str: while left >= 0 and right <= len(s) and s[left] == s[right-1]: left -= 1 right += 1 return s[left+1 : right-1] if len(s) < 2 or s == s[...
class Solution: def longest_palindrome(self, s: str) -> str: def expand(left: int, right: int) -> str: while left >= 0 and right <= len(s) and (s[left] == s[right - 1]): left -= 1 right += 1 return s[left + 1:right - 1] if len(s) < 2 or s == ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "David S. Batista" __email__ = "dsbatista@inesc-id.pt" class Seed(object): def __init__(self, _e1, _e2): self.e1 = _e1 self.e2 = _e2 def __hash__(self): return hash(self.e1) ^ hash(self.e2) def __eq__(self, other): ...
__author__ = 'David S. Batista' __email__ = 'dsbatista@inesc-id.pt' class Seed(object): def __init__(self, _e1, _e2): self.e1 = _e1 self.e2 = _e2 def __hash__(self): return hash(self.e1) ^ hash(self.e2) def __eq__(self, other): return self.e1 == other.e1 and self.e2 == ot...
CONFIG = { 'file_gdb': 'curb_geocoder.gdb', 'input': { 'address_pt': 'ADDRESS_CURB_20141105', 'address_fields': { 'address_id': 'OBJECTID', 'address_full': 'ADDRESS_ID', 'poly_id': 'OBJECTID_1', }, 'streets_lin': 'STREETS_LIN', 'streets_fields': { 'street_name': 'STNAME', 'left_from': 'L_F_...
config = {'file_gdb': 'curb_geocoder.gdb', 'input': {'address_pt': 'ADDRESS_CURB_20141105', 'address_fields': {'address_id': 'OBJECTID', 'address_full': 'ADDRESS_ID', 'poly_id': 'OBJECTID_1'}, 'streets_lin': 'STREETS_LIN', 'streets_fields': {'street_name': 'STNAME', 'left_from': 'L_F_ADD', 'left_to': 'L_T_ADD', 'right_...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: bottomleft=root.val stack=[(...
class Solution: def find_bottom_left_value(self, root: Optional[TreeNode]) -> int: bottomleft = root.val stack = [(root, 0)] prev_depth = 0 while stack: (cur, depth) = stack.pop(0) if depth != prev_depth: bottomleft = cur.val if cu...
# # PySNMP MIB module AISPY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AISPY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:00:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) ...
class OrangeRicky(): def __init__(self, rotation): self.colour = "O" self.rotation = rotation if rotation == 0: self.coords = [[8, 0], [8, 1], [7, 1], [6, 1]] elif rotation == 1: self.coords = [[8, 2], [7, 2], [7, 1], [7, 0]] elif rotat...
class Orangericky: def __init__(self, rotation): self.colour = 'O' self.rotation = rotation if rotation == 0: self.coords = [[8, 0], [8, 1], [7, 1], [6, 1]] elif rotation == 1: self.coords = [[8, 2], [7, 2], [7, 1], [7, 0]] elif rotation == 2: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 queue=...
class Solution: def width_of_binary_tree(self, root: TreeNode) -> int: if not root: return 0 queue = [[root, 0]] max_width = 1 while queue: new_queue = [] for (node, node_id) in queue: if node.left: new_queue.ap...
class AppMetricsError(Exception): pass class InvalidMetricsBackend(AppMetricsError): pass class MetricError(AppMetricsError): pass class TimerError(AppMetricsError): pass
class Appmetricserror(Exception): pass class Invalidmetricsbackend(AppMetricsError): pass class Metricerror(AppMetricsError): pass class Timererror(AppMetricsError): pass
def get_tensor_shape(tensor): shape = [] for s in tensor.shape: if s is None: shape.append(s) else: shape.append(s.value) return tuple(shape)
def get_tensor_shape(tensor): shape = [] for s in tensor.shape: if s is None: shape.append(s) else: shape.append(s.value) return tuple(shape)
#!/usr/bin/python3 f = open("day8-input.txt", "r") finput = f.read().split("\n") finput.pop() def get_instruction_set(): instruction_set = [] for i in finput: instruction_set.append({ "instruction" : i.split(' ')[0], "value": int(i.split(' ')[1]), "order": [] ...
f = open('day8-input.txt', 'r') finput = f.read().split('\n') finput.pop() def get_instruction_set(): instruction_set = [] for i in finput: instruction_set.append({'instruction': i.split(' ')[0], 'value': int(i.split(' ')[1]), 'order': []}) return instruction_set def run_instruction_set(change, ch...
num = [] par = [] impar = [] for i in range(20): num.append(float(input())) print(num) for i in num: if i % 2 == 0: par.append(i) else: impar.append(i) print(par) print(impar)
num = [] par = [] impar = [] for i in range(20): num.append(float(input())) print(num) for i in num: if i % 2 == 0: par.append(i) else: impar.append(i) print(par) print(impar)
data = '/home/tong.wang001/data/TS/textsimp.train.pt' save_model = 'textsimp' train_from_state_dict = '' train_from = '' curriculum = True extra_shuffle = True batch_size = 64 gpus = [0] layers = 2 rnn_size = 500 word_vec_size = 500 input_feed = 1 brnn_merge = 'concat' max_generator_batches = 32 epochs = 13 start_epoch...
data = '/home/tong.wang001/data/TS/textsimp.train.pt' save_model = 'textsimp' train_from_state_dict = '' train_from = '' curriculum = True extra_shuffle = True batch_size = 64 gpus = [0] layers = 2 rnn_size = 500 word_vec_size = 500 input_feed = 1 brnn_merge = 'concat' max_generator_batches = 32 epochs = 13 start_epoch...
#!/usr/bin/python3 count = 0 with open('./input.txt', 'r') as input: list_lines = input.read().split('\n\n') for line in list_lines: count += len({i:line.replace("\n", "").count(i) for i in line.replace("\n", "")}) print(count) input.close()
count = 0 with open('./input.txt', 'r') as input: list_lines = input.read().split('\n\n') for line in list_lines: count += len({i: line.replace('\n', '').count(i) for i in line.replace('\n', '')}) print(count) input.close()
h, n = map(int, input().split()) a = [] b = [] for _ in range(n): ai, bi = map(int, input().split()) a.append(ai) b.append(bi) dp = [float("inf")] * (h + 1) dp[0] = 0 for i in range(h): for j in range(n): index = min(i + a[j], h) dp[index] = min(dp[index], dp[i] + b[j]) print(dp[h])
(h, n) = map(int, input().split()) a = [] b = [] for _ in range(n): (ai, bi) = map(int, input().split()) a.append(ai) b.append(bi) dp = [float('inf')] * (h + 1) dp[0] = 0 for i in range(h): for j in range(n): index = min(i + a[j], h) dp[index] = min(dp[index], dp[i] + b[j]) print(dp[h])
test = { 'name': 'q5', 'points': 3, 'suites': [ { 'cases': [ {'code': '>>> abs(kg_to_newtons(100) - 980) < 0.000001\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> abs(kg_to_newtons(3) - 29.4) < 0.000001\nTrue', 'hidden': False, 'locked': False}, ...
test = {'name': 'q5', 'points': 3, 'suites': [{'cases': [{'code': '>>> abs(kg_to_newtons(100) - 980) < 0.000001\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> abs(kg_to_newtons(3) - 29.4) < 0.000001\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> abs(kg_to_newtons(47) - 460.6) < 0.000001\nTrue', 'hid...
PROCESS_NAME_SET = None PROCESS_DATA = None SERVICE_NAME_SET = None SYSPATH_STR = None SYSPATH_FILE_SET = None SYSTEMROOT_STR = None SYSTEMROOT_FILE_SET = None DRIVERPATH_STR = None DRIVERPATH_FILE_SET = None DRIVERPATH_DATA = None PROFILE_PATH = None USER_DIRS_LIST = None HKEY_USERS_DATA = None PROGRAM_FILES_STR = No...
process_name_set = None process_data = None service_name_set = None syspath_str = None syspath_file_set = None systemroot_str = None systemroot_file_set = None driverpath_str = None driverpath_file_set = None driverpath_data = None profile_path = None user_dirs_list = None hkey_users_data = None program_files_str = Non...
class ShoppingCartItem: def __init__(self, id, name, price, quantity): self.id = id self.name = name self.price = price self.quantity = quantity @property def total_price(self): return self.price * self.quantity
class Shoppingcartitem: def __init__(self, id, name, price, quantity): self.id = id self.name = name self.price = price self.quantity = quantity @property def total_price(self): return self.price * self.quantity
def sort_(arr, temporary=False, reverse=False): # Making copy of array if temporary is true if temporary: ar = arr[:] else: ar = arr # To blend every element # in correct position # length of total array is required length = len(ar) # After each iteration ...
def sort_(arr, temporary=False, reverse=False): if temporary: ar = arr[:] else: ar = arr length = len(ar) while length > 0: for i in range(0, length - 1): if reverse: if ar[i] < ar[i + 1]: tmp = ar[i] ar[i] = ar[...
def tagWithMostP(dom, tagMaxP=None): for child in dom.findChildren(recursive=False): if child and not child.get('name') == 'p': numMaxP = 0 if tagMaxP: numMaxP = len(tagMaxP.find_all('p', recursive=False)) numCurrentP = len(child.find_all('p', recursive=Fa...
def tag_with_most_p(dom, tagMaxP=None): for child in dom.findChildren(recursive=False): if child and (not child.get('name') == 'p'): num_max_p = 0 if tagMaxP: num_max_p = len(tagMaxP.find_all('p', recursive=False)) num_current_p = len(child.find_all('p', r...
a = [3, 8, 5, 1, 8, 9, 4, 9, 6, 4, 3, 7] b = list (set (a)) for i in range (len(b)): for j in range (i+1,len (b)): if b[i]>b[j]: b[i] , b[j] = b[j], b[i] print (b)
a = [3, 8, 5, 1, 8, 9, 4, 9, 6, 4, 3, 7] b = list(set(a)) for i in range(len(b)): for j in range(i + 1, len(b)): if b[i] > b[j]: (b[i], b[j]) = (b[j], b[i]) print(b)
def get_input(path): with open(path, 'r') as fh: return fh.read().splitlines() def isValid_part1(rule, password): (r, c) = rule.split(" ") (mini, maxi) = r.split("-") num_of_occur = password.count(c) if num_of_occur < int(mini) or num_of_occur > int(maxi): return False return T...
def get_input(path): with open(path, 'r') as fh: return fh.read().splitlines() def is_valid_part1(rule, password): (r, c) = rule.split(' ') (mini, maxi) = r.split('-') num_of_occur = password.count(c) if num_of_occur < int(mini) or num_of_occur > int(maxi): return False return T...
def default(): return { 'columns': [ {'name': 'id', 'type': 'string'}, {'name': 'sku', 'type': 'object'}, {'name': 'name', 'type': 'string'}, {'name': 'type', 'type': 'string'}, {'name': 'kind', 'type': 'string'}, {'name': 'plan', 'type...
def default(): return {'columns': [{'name': 'id', 'type': 'string'}, {'name': 'sku', 'type': 'object'}, {'name': 'name', 'type': 'string'}, {'name': 'type', 'type': 'string'}, {'name': 'kind', 'type': 'string'}, {'name': 'plan', 'type': 'object'}, {'name': 'tags', 'type': 'object'}, {'name': 'location', 'type': 'st...
numbers=[] while True: number=input("Enter a number:") if number=="done": break else: number=float(number) numbers.append(number) continue print("Maximum:",max(numbers)) print("Minimum:",min(numbers))
numbers = [] while True: number = input('Enter a number:') if number == 'done': break else: number = float(number) numbers.append(number) continue print('Maximum:', max(numbers)) print('Minimum:', min(numbers))
def g_load(file): print("file {} loaded as BMP v2".format(file)) return None if __name__ == "__main__": print("Test Bmp.py") print(g_load("test.bmp"))
def g_load(file): print('file {} loaded as BMP v2'.format(file)) return None if __name__ == '__main__': print('Test Bmp.py') print(g_load('test.bmp'))
## Shorty ## Copyright 2009 Joshua Roesslein ## See LICENSE ## @url budurl.com class Budurl(Service): def __init__(self, apikey=None): self.apikey = apikey def _test(self): #prompt for apikey self.apikey = raw_input('budurl apikey: ') Service._test(self) def shrink(self, ...
class Budurl(Service): def __init__(self, apikey=None): self.apikey = apikey def _test(self): self.apikey = raw_input('budurl apikey: ') Service._test(self) def shrink(self, bigurl, notes=None): if self.apikey is None: raise shorty_error('Must set an apikey') ...
def validate_genome(genome, *args, **kwargs): if len(set(e.innov for e in genome.edges)) != len(genome.edges): raise ValueError('Non-unique edge in genome edges.') if len(set(n.innov for n in genome.nodes)) != len(genome.nodes): raise ValueError('Non-unique node in genome node.') for e in ...
def validate_genome(genome, *args, **kwargs): if len(set((e.innov for e in genome.edges))) != len(genome.edges): raise value_error('Non-unique edge in genome edges.') if len(set((n.innov for n in genome.nodes))) != len(genome.nodes): raise value_error('Non-unique node in genome node.') for e...
print("enter the two number") n1,n2=map(int,input().split()) print("press + for add") print("press - for subb") print("press * for mul") print("press / for div") e=input() if e == "+": print(n1+n2) elif e == "-": print(n1-n2) elif e == "*": print(n1*n2) elif e == "/": print(n1/n2) else: print("you e...
print('enter the two number') (n1, n2) = map(int, input().split()) print('press + for add') print('press - for subb') print('press * for mul') print('press / for div') e = input() if e == '+': print(n1 + n2) elif e == '-': print(n1 - n2) elif e == '*': print(n1 * n2) elif e == '/': print(n1 / n2) else: ...
recipes,available = {'flour': 500, 'sugar': 200, 'eggs': 1}, {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200} print(min([available.get(k,0) // recipes[k] for k in recipes]))
(recipes, available) = ({'flour': 500, 'sugar': 200, 'eggs': 1}, {'flour': 1200, 'sugar': 1200, 'eggs': 5, 'milk': 200}) print(min([available.get(k, 0) // recipes[k] for k in recipes]))
# Program to calculate the gross pay of a worker hours_worked = input("Enter the hours worked:\n") rate = input("Enter the payment rate:\n ") pay = int(hours_worked)*float(rate) print(pay)
hours_worked = input('Enter the hours worked:\n') rate = input('Enter the payment rate:\n ') pay = int(hours_worked) * float(rate) print(pay)
# # PySNMP MIB module A3COM-HUAWEI-QINQ-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-QINQ-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:52:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(h3c_common,) = mibBuilder.importSymbols('A3COM-HUAWEI-OID-MIB', 'h3cCommon') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constrain...
def handle_request(): print("hello world!") return "hello world!" if __name__ == '__main__': handle_request()
def handle_request(): print('hello world!') return 'hello world!' if __name__ == '__main__': handle_request()
# ShortTk DownlaodRealeses shell lib Copyright (c) Boubajoker 2021. All right reserved. Project under MIT License. __version__ = "0.0.1 Alpha A-1" __all__ = [ "librairy", "shell", "librairy shell", "downlaod shell lib" ]
__version__ = '0.0.1 Alpha A-1' __all__ = ['librairy', 'shell', 'librairy shell', 'downlaod shell lib']
string = "Emir Nazira Zarina Aijana Sultan Danil Adis" string = string.replace('Emir', 'Baizak') string = string.replace('Nazira', 'l') print(string)
string = 'Emir Nazira Zarina Aijana Sultan Danil Adis' string = string.replace('Emir', 'Baizak') string = string.replace('Nazira', 'l') print(string)
A, B, C = map(int, input().split()) if A == B: print(C) elif A == C: print(B) else: print(A)
(a, b, c) = map(int, input().split()) if A == B: print(C) elif A == C: print(B) else: print(A)
###### Birthday Cake Candles def birthdayCakeCandles(ar): blown_candle=0 maxi=max(ar) for i in ar: if i==maxi: blown_candle+=1 print(blown_candle) birthdayCakeCandles([3,2,1,3])
def birthday_cake_candles(ar): blown_candle = 0 maxi = max(ar) for i in ar: if i == maxi: blown_candle += 1 print(blown_candle) birthday_cake_candles([3, 2, 1, 3])
i = 1 j = 7 while(i<10): for x in range(3): print("I=%d J=%d" %(i,j)) j += -1 i += 2 j = i + 6
i = 1 j = 7 while i < 10: for x in range(3): print('I=%d J=%d' % (i, j)) j += -1 i += 2 j = i + 6
def check_matrix(mat): O_win = 0 X_win = 0 if mat[:3].count('O') == 3: O_win += 1 if mat[:3].count('X') == 3: X_win += 1 if mat[3:6].count('O') == 3: O_win += 1 if mat[3:6].count('X') == 3: X_win += 1 if mat[6:].count('O') == 3: O_win += 1 if mat[6...
def check_matrix(mat): o_win = 0 x_win = 0 if mat[:3].count('O') == 3: o_win += 1 if mat[:3].count('X') == 3: x_win += 1 if mat[3:6].count('O') == 3: o_win += 1 if mat[3:6].count('X') == 3: x_win += 1 if mat[6:].count('O') == 3: o_win += 1 if mat[6...
#!/usr/bin/env python3 class Error(Exception): '''Base class for exceptions''' def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) def __repr__(self): return self.message class InterpolationError(Error): '''Base class for interpolation-related excep...
class Error(Exception): """Base class for exceptions""" def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) def __repr__(self): return self.message class Interpolationerror(Error): """Base class for interpolation-related exceptions""" def __init__...
class ActionListener: def __init__(self, function): self.function = function def execute(self): if self.function is not None: self.function()
class Actionlistener: def __init__(self, function): self.function = function def execute(self): if self.function is not None: self.function()
class Ansvar: def __init__(self, id, name, strength, beskrivelse): self.id = id self.name = name self.strength = strength self.description = beskrivelse
class Ansvar: def __init__(self, id, name, strength, beskrivelse): self.id = id self.name = name self.strength = strength self.description = beskrivelse
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Register class RegisterStatus(object): Success = 0 FailUnknown = 1 FailUserNameConflicted = 2
class Registerstatus(object): success = 0 fail_unknown = 1 fail_user_name_conflicted = 2
word1 = input() word2 = txt = input()[::-1] if(word1 == word2): print("YES") else: print("NO")
word1 = input() word2 = txt = input()[::-1] if word1 == word2: print('YES') else: print('NO')
# MIT License # Copyright (C) Michael Tao-Yi Lee (taoyil AT UCI EDU) # A descriptor class class PositiveAttr(object): def __init__(self, name): self.name = name self.parent = None def __get__(self, instance, cls): print("get called", instance, cls) return instance.__dict__[sel...
class Positiveattr(object): def __init__(self, name): self.name = name self.parent = None def __get__(self, instance, cls): print('get called', instance, cls) return instance.__dict__[self.name] def __set__(self, instance, value): print('set called', instance, valu...
class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: s = s.replace('-', '').upper()[::-1] return '-'.join(s[i:i + k] for i in range(0, len(s), k))[::-1]
class Solution: def license_key_formatting(self, s: str, k: int) -> str: s = s.replace('-', '').upper()[::-1] return '-'.join((s[i:i + k] for i in range(0, len(s), k)))[::-1]
class Solution: def rotate(self, nums: List[int], k: int) -> None: if not nums: return step = k % len(nums) self.swap(nums, 0, len(nums) - step - 1) self.swap(nums, len(nums)-step, len(nums) - 1) self.swap(nums, 0, len(nums) - 1) def swap(self, nums, left, ri...
class Solution: def rotate(self, nums: List[int], k: int) -> None: if not nums: return step = k % len(nums) self.swap(nums, 0, len(nums) - step - 1) self.swap(nums, len(nums) - step, len(nums) - 1) self.swap(nums, 0, len(nums) - 1) def swap(self, nums, left,...
#!/usr/bin/env python #------------------------------------------------------------------------------- # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: #--------------------------------...
class Solution: def min_depth(self, root): if root == None: return 0 if root.left == None or root.right == None: return self.minDepth(root.left) + self.minDepth(root.right) + 1 return min(self.minDepth(root.right), self.minDepth(root.left)) + 1 def min_depth2(se...
# reads from the console two numbers a and b, calculates and prints the face of a rectangle with sides a and b a = int(input()) b = int(input()) print(a * b)
a = int(input()) b = int(input()) print(a * b)
a = [] a.append(2) for i in range(1,36): sum,dem,cnt = 0,0,9; for j in range(i): cnt = 9*(10**(j//2)) sum += cnt a.append(a[i-1]+sum) t = int(input()) for i in range(t): n = int(input()) print(a[n])
a = [] a.append(2) for i in range(1, 36): (sum, dem, cnt) = (0, 0, 9) for j in range(i): cnt = 9 * 10 ** (j // 2) sum += cnt a.append(a[i - 1] + sum) t = int(input()) for i in range(t): n = int(input()) print(a[n])
c_num = int(input()) a_num = 1 b_num = 1 # O(n**2) while a_num < c_num: while b_num < c_num: if (a_num**2 + b_num**2) == c_num**2: print(a_num, b_num) b_num += 1 b_num = 1 a_num += 1 # Bisa pakai yang atas atau yang bawah # O(n**2) # for a in range(1, c_num): # for b in ra...
c_num = int(input()) a_num = 1 b_num = 1 while a_num < c_num: while b_num < c_num: if a_num ** 2 + b_num ** 2 == c_num ** 2: print(a_num, b_num) b_num += 1 b_num = 1 a_num += 1
num = int(input("Enter a number: \t")) pow = int(input("Enter Power: \t")) sum = 1 i = 1 while(i<=pow): sum=sum*num i+=1 print(num,"to the power",pow,"is",sum)
num = int(input('Enter a number: \t')) pow = int(input('Enter Power: \t')) sum = 1 i = 1 while i <= pow: sum = sum * num i += 1 print(num, 'to the power', pow, 'is', sum)
items = [] def enqueue(item): items.append(item) def dequeue(): if len(items) > 0: items.pop(0) enqueue(5) enqueue(11) enqueue('Jones') enqueue(45) print(items) dequeue() print(items) dequeue() print(items)
items = [] def enqueue(item): items.append(item) def dequeue(): if len(items) > 0: items.pop(0) enqueue(5) enqueue(11) enqueue('Jones') enqueue(45) print(items) dequeue() print(items) dequeue() print(items)
class Sampling_InfinteLoopWrapper: def __init__(self, sampling_algo): self.sampling_algo = sampling_algo def get(self): return self.sampling_algo.current() def move_next(self): if not self.sampling_algo.move_next(): self.sampling_algo.reset() assert self.sam...
class Sampling_Infinteloopwrapper: def __init__(self, sampling_algo): self.sampling_algo = sampling_algo def get(self): return self.sampling_algo.current() def move_next(self): if not self.sampling_algo.move_next(): self.sampling_algo.reset() assert self.sa...
##################################### # Installation module for autorecon ##################################### # XXX: Expects seclists to be in /usr/share/seclists # AUTHOR OF MODULE NAME AUTHOR="ypcrts" # DESCRIPTION OF THE MODULE DESCRIPTION="This module will install/update autorecon - a multi-threaded network re...
author = 'ypcrts' description = 'This module will install/update autorecon - a multi-threaded network reconnaissance tool' install_type = 'GIT' repository_location = 'https://github.com/Tib3rius/AutoRecon.git' install_location = 'autorecon' debian = 'python3,python3-pip' fedora = 'git' after_commands = 'cd {INSTALL_LOC...
# -*- coding: UTF-8 -*- lan = 15 for a in range(5): lan *= 10 print(lan)
lan = 15 for a in range(5): lan *= 10 print(lan)
def almost_equal(obj1, obj2, exclude_paths=[]): def almost_equal_helper(x, y, path): if isinstance(x, dict): if not isinstance(y, dict): print(f"At path {path}, obj1 was of type dict while obj2 was not") return False if not set(x.keys()) == set(y.key...
def almost_equal(obj1, obj2, exclude_paths=[]): def almost_equal_helper(x, y, path): if isinstance(x, dict): if not isinstance(y, dict): print(f'At path {path}, obj1 was of type dict while obj2 was not') return False if not set(x.keys()) == set(y.keys...