content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# elasticmodels/tests/test_settings.py # author: andrew young # email: ayoung@thewulf.org DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } } ROOT_URLCONF = ["elasticmodels.urls"] INSTALLED_APPS = ["elasticmodels"]
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} root_urlconf = ['elasticmodels.urls'] installed_apps = ['elasticmodels']
# Python - 2.7.6 Test.describe('Basic Tests') data = [2] Test.assert_equals(print_array(data), '2') data = [2, 4, 5, 2] Test.assert_equals(print_array(data), '2,4,5,2') data = [2, 4, 5, 2] Test.assert_equals(print_array(data), '2,4,5,2') data = [2.0, 4.2, 5.1, 2.2] Test.assert_equals(print_array(data), '2.0,4.2,5.1...
Test.describe('Basic Tests') data = [2] Test.assert_equals(print_array(data), '2') data = [2, 4, 5, 2] Test.assert_equals(print_array(data), '2,4,5,2') data = [2, 4, 5, 2] Test.assert_equals(print_array(data), '2,4,5,2') data = [2.0, 4.2, 5.1, 2.2] Test.assert_equals(print_array(data), '2.0,4.2,5.1,2.2') data = ['2', '...
def result(score): min = max = score[0] min_count = max_count = 0 for i in score[1:]: if i > max: max_count += 1 max = i if i < min: min_count += 1 min = i return max_count, min_count n = input() score = list(map(int, input().split())) p...
def result(score): min = max = score[0] min_count = max_count = 0 for i in score[1:]: if i > max: max_count += 1 max = i if i < min: min_count += 1 min = i return (max_count, min_count) n = input() score = list(map(int, input().split())) pr...
DEFAULT_PRAGMAS = ( "akamai-x-get-request-id", "akamai-x-get-cache-key", "akamai-x-get-true-cache-key", "akamai-x-get-extracted-values", "akamai-x-cache-on", "akamai-x-cache-remote-on", "akamai-x-check-cacheable", "akamai-x-get-ssl-client-session-id", "akamai-x-serial-no", )
default_pragmas = ('akamai-x-get-request-id', 'akamai-x-get-cache-key', 'akamai-x-get-true-cache-key', 'akamai-x-get-extracted-values', 'akamai-x-cache-on', 'akamai-x-cache-remote-on', 'akamai-x-check-cacheable', 'akamai-x-get-ssl-client-session-id', 'akamai-x-serial-no')
n1 = int(input("digite o valor em metros ")) n2 = int(input("digite o valor em metros ")) n3 = int(input("digite o valor em metros ")) r= (n1**2)+(n2**2)+(n3**2) print(r)
n1 = int(input('digite o valor em metros ')) n2 = int(input('digite o valor em metros ')) n3 = int(input('digite o valor em metros ')) r = n1 ** 2 + n2 ** 2 + n3 ** 2 print(r)
__author__ = 'ipetrash' if __name__ == '__main__': def getprint(str="hello world!"): print(str) def decor(func): def wrapper(*args, **kwargs): print("1 begin: " + func.__name__) print("Args={} kwargs={}".format(args, kwargs)) f = func(*args, **kwargs) ...
__author__ = 'ipetrash' if __name__ == '__main__': def getprint(str='hello world!'): print(str) def decor(func): def wrapper(*args, **kwargs): print('1 begin: ' + func.__name__) print('Args={} kwargs={}'.format(args, kwargs)) f = func(*args, **kwargs) ...
''' https://youtu.be/-xRKazHGtjU Smarter Approach: https://youtu.be/J7S3CHFBZJA Dynamic Programming: https://youtu.be/VQeFcG9pjJU '''
""" https://youtu.be/-xRKazHGtjU Smarter Approach: https://youtu.be/J7S3CHFBZJA Dynamic Programming: https://youtu.be/VQeFcG9pjJU """
def fit_index(dataset, list_variables): """ Mapping between index and category, for categorical variables For each (categorical) variable, create 2 dictionaries: - index_to_categorical: from the index to the category - categorical_to_index: from the category to the index Parameters -...
def fit_index(dataset, list_variables): """ Mapping between index and category, for categorical variables For each (categorical) variable, create 2 dictionaries: - index_to_categorical: from the index to the category - categorical_to_index: from the category to the index Parameters ---...
def model(outcome, player1, player2, game_matrix): """ outcome [N, 1] where N is games and extra dimension is just 1 or zero depending on whether player 1 or player 2 wins player1 is one-hot vector encoding of player id player2 "" game_matrix has entries [G,P] (use sparse multiplication COO...
def model(outcome, player1, player2, game_matrix): """ outcome [N, 1] where N is games and extra dimension is just 1 or zero depending on whether player 1 or player 2 wins player1 is one-hot vector encoding of player id player2 "" game_matrix has entries [G,P] (use sparse multiplication COO) ...
# inspired from spacy def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWi...
def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class Errorswithcodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return errors_with_codes() @add_code...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def Insertion_sort(_list): list_length = len(_list) i = 1 while i < list_length: key = _list[i] j = i - 1 while j >= 0 and _list[j] > key: _list[j+1] = _list[j] j -= 1 _list[j+1] = key i += 1 ...
def insertion_sort(_list): list_length = len(_list) i = 1 while i < list_length: key = _list[i] j = i - 1 while j >= 0 and _list[j] > key: _list[j + 1] = _list[j] j -= 1 _list[j + 1] = key i += 1 return _list
duzina = 5 sirina = 2 povrsina = duzina * sirina print('Povrsina je ', povrsina) print('Obim je ', 2 * (duzina + sirina))
duzina = 5 sirina = 2 povrsina = duzina * sirina print('Povrsina je ', povrsina) print('Obim je ', 2 * (duzina + sirina))
""" Constants for event handling in Eris. """ PRIO_HIGH = 0 PRIO_MEDIUM = 1 PRIO_LOW = 2
""" Constants for event handling in Eris. """ prio_high = 0 prio_medium = 1 prio_low = 2
class Contact: def __init__(self, fname=None, sname=None, lname=None, address=None, email=None, tel=None): self.fname = fname self.sname = sname self.lname = lname self.address = address self.email = email self.tel = tel
class Contact: def __init__(self, fname=None, sname=None, lname=None, address=None, email=None, tel=None): self.fname = fname self.sname = sname self.lname = lname self.address = address self.email = email self.tel = tel
def response(number): if number % 4 == 0: return "Multiple of four" elif number % 2 == 0: return "Even" else: return "Odd" def divisible(num, check): if check % num == 0: return "Yes, it's evenly divisible" return "No, it's not evenly divisible" if __name__ == "__...
def response(number): if number % 4 == 0: return 'Multiple of four' elif number % 2 == 0: return 'Even' else: return 'Odd' def divisible(num, check): if check % num == 0: return "Yes, it's evenly divisible" return "No, it's not evenly divisible" if __name__ == '__mai...
class PipelineError(Exception): pass class PipelineParallelError(Exception): pass
class Pipelineerror(Exception): pass class Pipelineparallelerror(Exception): pass
# print statement, function definition name = "Anurag" age = 30 print(name, age, "python", 2020) print(name, age, "python", 2020, sep=", ", end=" $$ ")
name = 'Anurag' age = 30 print(name, age, 'python', 2020) print(name, age, 'python', 2020, sep=', ', end=' $$ ')
def isPermutation(string_1, string_2): string_1 = list(string_1) string_2 = list(string_2) for i in range(0, len(string_1)): for j in range(0, len(string_2)): if string_1[i] == string_2[j]: del string_2[j] break if len(string_2) == 0: retu...
def is_permutation(string_1, string_2): string_1 = list(string_1) string_2 = list(string_2) for i in range(0, len(string_1)): for j in range(0, len(string_2)): if string_1[i] == string_2[j]: del string_2[j] break if len(string_2) == 0: return T...
""" Regular expressions """ def match(pattern, string, flags=0): return _compile(pattern, flags).match(string) def _compile(pattern, flags): p = sre_compile.compile(pattern, flags) return p
""" Regular expressions """ def match(pattern, string, flags=0): return _compile(pattern, flags).match(string) def _compile(pattern, flags): p = sre_compile.compile(pattern, flags) return p
class Observer(object): """docstring for Observer""" def __init__(self): super(Observer, self).__init__() self.signalFunc = None def onReceive(self, signal, emitter): if self.signalFunc != None and signal in self.signalFunc: self.signalFunc[signal](emitter)
class Observer(object): """docstring for Observer""" def __init__(self): super(Observer, self).__init__() self.signalFunc = None def on_receive(self, signal, emitter): if self.signalFunc != None and signal in self.signalFunc: self.signalFunc[signal](emitter)
class _SCon: esc : str = '\u001B' bra : str = '[' eb : str = esc + bra bRed : str = eb + '41m' white : str = eb + '37m' bold : str = eb + '1m' right : str = 'C' left : str = 'D' down : str = 'B' up : str = 'A' reset : str = eb + '0m' cy...
class _Scon: esc: str = '\x1b' bra: str = '[' eb: str = esc + bra b_red: str = eb + '41m' white: str = eb + '37m' bold: str = eb + '1m' right: str = 'C' left: str = 'D' down: str = 'B' up: str = 'A' reset: str = eb + '0m' cyan: str = eb + '36m' del_char: str = eb + 'X...
# tree structure in decoder side # divide sub-node by brackets "()" class Tree(): def __init__(self): self.parent = None self.num_children = 0 self.children = [] def __str__(self, level = 0): ret = "" for child in self.children: if isinstance(child,type(...
class Tree: def __init__(self): self.parent = None self.num_children = 0 self.children = [] def __str__(self, level=0): ret = '' for child in self.children: if isinstance(child, type(self)): ret += child.__str__(level + 1) else: ...
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): N = len(A) l_sum = A[0] r_sum = sum(A) - l_sum diff = abs(l_sum - r_sum) for i in range(1, N -1): l_sum += A[i] r_sum -= A[i] c_diff = abs(l_sum - r_sum) if di...
def solution(A): n = len(A) l_sum = A[0] r_sum = sum(A) - l_sum diff = abs(l_sum - r_sum) for i in range(1, N - 1): l_sum += A[i] r_sum -= A[i] c_diff = abs(l_sum - r_sum) if diff > c_diff: diff = c_diff return diff
#!/usr/bin/python3 def uppercase(str): for c in str: if (ord(c) >= ord('a')) and (ord(c) <= ord('z')): c = chr(ord(c)-ord('a')+ord('A')) print("{}".format(c), end='') print()
def uppercase(str): for c in str: if ord(c) >= ord('a') and ord(c) <= ord('z'): c = chr(ord(c) - ord('a') + ord('A')) print('{}'.format(c), end='') print()
# Copyright 2018 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...
"""BUILD rules used to provide a Swift toolchain provided by Xcode on macOS. The rules defined in this file are not intended to be used outside of the Swift toolchain package. If you are looking for rules to build Swift code using this toolchain, see `swift.bzl`. """ load(':providers.bzl', 'SwiftToolchainInfo') load('...
#In PowerShell """ function Get-Something { param ( [string[]]$thing ) foreach ($t in $things){ Write-Host $t } } """ #region functions def powershell_python(): print('This is a function') #return is key for returning values return #positional arguments mandatory, def powers...
""" function Get-Something { param ( [string[]]$thing ) foreach ($t in $things){ Write-Host $t } } """ def powershell_python(): print('This is a function') return def powershell_python(name, optional=yes): if optional == 'yes': print('This uses an optional arguments...
def calcula_diferenca(A: int, B: int, C: int, D: int): if (not isinstance(A, int) or not isinstance(B, int) or not isinstance(C, int) or not isinstance(D, int)): raise(TypeError) D = A * B - C * D return f'DIFERENCA = {D}'
def calcula_diferenca(A: int, B: int, C: int, D: int): if not isinstance(A, int) or not isinstance(B, int) or (not isinstance(C, int)) or (not isinstance(D, int)): raise TypeError d = A * B - C * D return f'DIFERENCA = {D}'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ################################################### #........../\./\...___......|\.|..../...\.........# #........./..|..\/\.|.|_|._.|.\|....|.c.|.........# #......../....../--\|.|.|.|i|..|....\.../.........# # Mathtin (c) # #############...
__author__ = 'Mathtin' class Invalidconfigexception(Exception): def __init__(self, msg: str, var_name: str): super().__init__(f'{msg}, check {var_name} value') class Notcoroutineexception(TypeError): def __init__(self, func): super().__init__(f'{str(func)} is not a coroutine function') clas...
# # LeetCode # Algorithm 104 Maximum depth of binary tree # # See LICENSE # # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def traverse(self, root, depth): """...
class Solution(object): def traverse(self, root, depth): """ :type root: TreeNode :type depth: int :rtype: int """ if root == None: return depth else: return max(self.traverse(root.left, depth + 1), self.traverse(root.right, depth + 1)...
#Question link #https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x/0 def window(arr,n, k): left=0 right=0 ans=n sum1=0 while left<n and right<n+1: if sum1>k: if left==right: ans=1 break ...
def window(arr, n, k): left = 0 right = 0 ans = n sum1 = 0 while left < n and right < n + 1: if sum1 > k: if left == right: ans = 1 break ans = min(ans, right - left) sum1 -= arr[left] left += 1 elif righ...
s = input() # s = ' name1' list_stop = [' ', '@', '$', '%'] list_num = '0123456789' # flag_true = 0 flag_false = 0 for i in list_num: if s[0] == i: flag_false += 1 break for j in s: for k in list_stop: if j == k: flag_false += 1 break else: # f...
s = input() list_stop = [' ', '@', '$', '%'] list_num = '0123456789' flag_false = 0 for i in list_num: if s[0] == i: flag_false += 1 break for j in s: for k in list_stop: if j == k: flag_false += 1 break else: break if flag_false >= 1: prin...
# # @lc app=leetcode id=1232 lang=python3 # # [1232] Check If It Is a Straight Line # # @lc code=start class Solution: def checkStraightLine(self, coordinates): if len(coordinates) <= 2: return True x1, x2, y1, y2 = coordinates[0][0], coordinates[1][0], coordinates[0][1], coordinates[1]...
class Solution: def check_straight_line(self, coordinates): if len(coordinates) <= 2: return True (x1, x2, y1, y2) = (coordinates[0][0], coordinates[1][0], coordinates[0][1], coordinates[1][1]) if x1 == x2: k = 0 else: k = (y1 - y2) / (x1 - x2) ...
class YggException(Exception): pass class LoginFailed(Exception): pass class TooManyFailedLogins(Exception): pass
class Yggexception(Exception): pass class Loginfailed(Exception): pass class Toomanyfailedlogins(Exception): pass
class TriggerBase: def __init__(self, q, events): self.q = q self.events = events def trigger(self, name): self.q.put( {'req': 'trigger_animation', 'data': name, 'sender': 'Trigger'})
class Triggerbase: def __init__(self, q, events): self.q = q self.events = events def trigger(self, name): self.q.put({'req': 'trigger_animation', 'data': name, 'sender': 'Trigger'})
favcolor = { "Jacob": "Magenta", "Jason": "Red", "Anais": "Purple" } for name, color in favcolor.items(): print("%s's favorite color is %s" %(name, color))
favcolor = {'Jacob': 'Magenta', 'Jason': 'Red', 'Anais': 'Purple'} for (name, color) in favcolor.items(): print("%s's favorite color is %s" % (name, color))
"""Constants for the Vivint integration.""" DOMAIN = "vivint" EVENT_TYPE = f"{DOMAIN}_event" RTSP_STREAM_DIRECT = 0 RTSP_STREAM_INTERNAL = 1 RTSP_STREAM_EXTERNAL = 2 RTSP_STREAM_TYPES = { RTSP_STREAM_DIRECT: "Direct (falls back to internal if direct access is not available)", RTSP_STREAM_INTERNAL: "Internal", ...
"""Constants for the Vivint integration.""" domain = 'vivint' event_type = f'{DOMAIN}_event' rtsp_stream_direct = 0 rtsp_stream_internal = 1 rtsp_stream_external = 2 rtsp_stream_types = {RTSP_STREAM_DIRECT: 'Direct (falls back to internal if direct access is not available)', RTSP_STREAM_INTERNAL: 'Internal', RTSP_STREA...
''' 5. Write a Python program to check whether a specified value is contained in a group of values. Test Data : 3 -> [1, 5, 8, 3] : True -1 -> [1, 5, 8, 3] : False ''' def check_value(group_data, n): for x in group_data: if n == x: return True else: return False print(check_value([1,...
""" 5. Write a Python program to check whether a specified value is contained in a group of values. Test Data : 3 -> [1, 5, 8, 3] : True -1 -> [1, 5, 8, 3] : False """ def check_value(group_data, n): for x in group_data: if n == x: return True else: return False print(check_value([1...
# Program corresponding to flowchart in this site https://automatetheboringstuff.com/2e/images/000039.jpg print('Is raining? (Y)es or (N)o') answer = input() if answer == 'N': print('Go outside.') elif answer == 'Y': print('Have umbrella? (Y)es or (N)o') answer2 = input() if answer2 == 'Y': print('Go out...
print('Is raining? (Y)es or (N)o') answer = input() if answer == 'N': print('Go outside.') elif answer == 'Y': print('Have umbrella? (Y)es or (N)o') answer2 = input() if answer2 == 'Y': print('Go outside.') elif answer2 == 'N': print('Wait a while.') print('Is raining? (Y)es ...
__all__ = ["TreeDict"] class TreeDict: """Converts a nested dict to an object. Items in the dict are set to object attributes. ARTIQ python does not support dict type. Inherit this class to convert the dict to an object. self.value_parser() can be inherited to parse non-dict values. Args: ...
__all__ = ['TreeDict'] class Treedict: """Converts a nested dict to an object. Items in the dict are set to object attributes. ARTIQ python does not support dict type. Inherit this class to convert the dict to an object. self.value_parser() can be inherited to parse non-dict values. Args: ...
first_name = input() second_name = input() delimeter = input() print(f"{first_name}{delimeter}{second_name}")
first_name = input() second_name = input() delimeter = input() print(f'{first_name}{delimeter}{second_name}')
# # PySNMP MIB module CISCO-ITP-RT-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-RT-CAPABILITY # Produced by pysmi-0.3.4 at Wed May 1 12:03:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) ...
# -*- coding: utf-8 -*- qntCaso = int(input()) for caso in range(qntCaso): listStrTamanhoStr = list() listStr = list(map(str, input().split())) for indiceStr in range(len(listStr)): listStrTamanhoStr.append([listStr[indiceStr], len(listStr[indiceStr])]) strSequenciaOrdenadaTamanho = "" for ch...
qnt_caso = int(input()) for caso in range(qntCaso): list_str_tamanho_str = list() list_str = list(map(str, input().split())) for indice_str in range(len(listStr)): listStrTamanhoStr.append([listStr[indiceStr], len(listStr[indiceStr])]) str_sequencia_ordenada_tamanho = '' for (chave, valor) i...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Chirstoph Reimers' __email__ = 'creimers@byteyard.de' __version__ = '0.1.0.b6'
__author__ = 'Chirstoph Reimers' __email__ = 'creimers@byteyard.de' __version__ = '0.1.0.b6'
#square pattern ''' Print the following pattern for the given N number of rows. Pattern for N = 4 4444 4444 4444 4444 ''' rows=int(input()) for i in range(rows): for j in range(rows): print(rows,end="") print()
""" Print the following pattern for the given N number of rows. Pattern for N = 4 4444 4444 4444 4444 """ rows = int(input()) for i in range(rows): for j in range(rows): print(rows, end='') print()
expected_output = { "vrf": { "default": { "address_family": { "ipv4": { "instance": { "10000": { "summary_traffic_statistics": { "ospf_packets_received_sent": { ...
expected_output = {'vrf': {'default': {'address_family': {'ipv4': {'instance': {'10000': {'summary_traffic_statistics': {'ospf_packets_received_sent': {'type': {'rx_invalid': {'packets': 0, 'bytes': 0}, 'rx_hello': {'packets': 0, 'bytes': 0}, 'rx_db_des': {'packets': 0, 'bytes': 0}, 'rx_ls_req': {'packets': 0, 'bytes':...
# Write your solutions for 1.5 here! class superheroes: def __int__(self, name, superpower, strength): self.name=name self.superpower=superpower self.strength=strength def print_me(self): print(self.name +str( self.strength)) superhero = superheroes("tamara","fly", 10) superhero.print_me()
class Superheroes: def __int__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def print_me(self): print(self.name + str(self.strength)) superhero = superheroes('tamara', 'fly', 10) superhero.print_me()
''' There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give?...
""" There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give?...
N = int(input()) A, B, C = input(), input(), input() ans = 0 for i in range(N): abc = A[i], B[i], C[i] ans += len(set(abc)) - 1 print(ans)
n = int(input()) (a, b, c) = (input(), input(), input()) ans = 0 for i in range(N): abc = (A[i], B[i], C[i]) ans += len(set(abc)) - 1 print(ans)
contador = 0 print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador)) contador = 1 print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador)) contador = 2 print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador)) contador = 3 print("2 elevado a " + str(contado...
contador = 0 print('2 elevado a ' + str(contador) + ' es igual a: ' + str(2 ** contador)) contador = 1 print('2 elevado a ' + str(contador) + ' es igual a: ' + str(2 ** contador)) contador = 2 print('2 elevado a ' + str(contador) + ' es igual a: ' + str(2 ** contador)) contador = 3 print('2 elevado a ' + str(contador) ...
class Number: def __init__(self): self.num = 0 def setNum(self, x): self.num = x # na= Number() # na.setNum(3) # print(hasattr(na, 'id')) a = ABCDEFGHIJKLMNOPQRSTUVWXYZ b = BLUESKYACDFGHIJMNOPQRTVWXZ class Point: def __init__(self, x=0, y=0): self.x = x ...
class Number: def __init__(self): self.num = 0 def set_num(self, x): self.num = x a = ABCDEFGHIJKLMNOPQRSTUVWXYZ b = BLUESKYACDFGHIJMNOPQRTVWXZ class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return (self.x, self.y) de...
n = int(input()) ans = 0 for i in range(n): a, b = map(int, input().split()) ans += (a + b) * (b - a + 1) // 2 print(ans)
n = int(input()) ans = 0 for i in range(n): (a, b) = map(int, input().split()) ans += (a + b) * (b - a + 1) // 2 print(ans)
def is_leap(year): leap = False # Write your logic here if (year%400) == 0: leap = True elif (year%100) == 0: leap = False elif (year%4) == 0: leap = True return leap
def is_leap(year): leap = False if year % 400 == 0: leap = True elif year % 100 == 0: leap = False elif year % 4 == 0: leap = True return leap
__version__ = '2.0.0' print("*"*35) print(f'SpotifyToVKStatus. Version: {__version__}') print("*"*35)
__version__ = '2.0.0' print('*' * 35) print(f'SpotifyToVKStatus. Version: {__version__}') print('*' * 35)
file_name = input('Enter file name: ') if file_name == 'na na boo boo': print("NA NA BOO BOO TO YOU - You have been punk'd!") exit() else: try: file = open(file_name) except: print('File cannot be opened') exit() count = 0 numbers = 0 average = 0 for line in file: if line.startswith('X-DSPAM-Confidence'): ...
file_name = input('Enter file name: ') if file_name == 'na na boo boo': print("NA NA BOO BOO TO YOU - You have been punk'd!") exit() else: try: file = open(file_name) except: print('File cannot be opened') exit() count = 0 numbers = 0 average = 0 for line in file: if line.sta...
""" Module docstring """ def _write_file_impl(ctx): f = ctx.actions.declare_file("out.txt") ctx.actions.write(f, "contents") def _source_list_rule_impl(ctx): if len(ctx.attr.srcs) != 2: fail("Expected two sources") first = ctx.attr.srcs[0].short_path.replace("\\", "/") second = ctx.attr.sr...
""" Module docstring """ def _write_file_impl(ctx): f = ctx.actions.declare_file('out.txt') ctx.actions.write(f, 'contents') def _source_list_rule_impl(ctx): if len(ctx.attr.srcs) != 2: fail('Expected two sources') first = ctx.attr.srcs[0].short_path.replace('\\', '/') second = ctx.attr.sr...
class Solution(object): def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ cnt = 1 prod = 9 for i in range(min(n, 10)): cnt += prod prod *= 9 - i return cnt
class Solution(object): def count_numbers_with_unique_digits(self, n): """ :type n: int :rtype: int """ cnt = 1 prod = 9 for i in range(min(n, 10)): cnt += prod prod *= 9 - i return cnt
# # @lc app=leetcode id=46 lang=python3 # # [46] Permutations # # @lc code=start class Solution: def permute(self, nums: List[int]) -> List[List[int]]: results = [] prev_elements = [] def dfs(elements): if len(elements) == 0: results.append(prev_elements[:]) ...
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: results = [] prev_elements = [] def dfs(elements): if len(elements) == 0: results.append(prev_elements[:]) for e in elements: next_elements = elements[:] ...
def count_up(start, stop): """Print all numbers from start up to and including stop. For example: count_up(5, 7) should print: 5 6 7 """ # YOUR CODE HERE # print(start) # start += 1 # print(start) # parameters can be modified while start <= sto...
def count_up(start, stop): """Print all numbers from start up to and including stop. For example: count_up(5, 7) should print: 5 6 7 """ while start <= stop: print(start) start += 1 count_up(5, 7) count_up(3, 8)
def user(*args): blank=[] for num in args: blank+=1 return arg user()
def user(*args): blank = [] for num in args: blank += 1 return arg user()
class basedriver (object): def __init__(self, ctx, model): self._ctx = ctx self._model = model def check_update(self, current): if current is None: return True if current.version is None: return True if current.version != self._model.version: ...
class Basedriver(object): def __init__(self, ctx, model): self._ctx = ctx self._model = model def check_update(self, current): if current is None: return True if current.version is None: return True if current.version != self._model.version: ...
def get(key): return None def set(key, value): pass
def get(key): return None def set(key, value): pass
""" [2017-09-29] Challenge #333 [Hard] Build a Web API-driven Data Site https://www.reddit.com/r/dailyprogrammer/comments/739j8c/20170929_challenge_333_hard_build_a_web_apidriven/ # Description A common theme in present-day programming are web APIs. We've had a previous challenge where you had to _consume_ an API, to...
""" [2017-09-29] Challenge #333 [Hard] Build a Web API-driven Data Site https://www.reddit.com/r/dailyprogrammer/comments/739j8c/20170929_challenge_333_hard_build_a_web_apidriven/ # Description A common theme in present-day programming are web APIs. We've had a previous challenge where you had to _consume_ an API, to...
# Problem Statement: https://leetcode.com/problems/longest-increasing-subsequence/ class Solution: def lengthOfLIS(self, nums: List[int]) -> int: arr = nums if not arr: return 0 lens = [1 for num in arr] seqs = [None for num in arr] for i, num in enumerate(arr):...
class Solution: def length_of_lis(self, nums: List[int]) -> int: arr = nums if not arr: return 0 lens = [1 for num in arr] seqs = [None for num in arr] for (i, num) in enumerate(arr): curr_num = num for j in range(0, i): ot...
print('load # extractor diagram V1 essential') # Essential version for the final summary automation in the main notebook. #It contains only the winning prefilter and feature extraction from the development process. class extdia_v1_essential(extractor_diagram): def ini_diagram(self): # custom ...
print('load # extractor diagram V1 essential') class Extdia_V1_Essential(extractor_diagram): def ini_diagram(self): self.name = 'EDiaV1' if self.fHP: self.name += 'HP' if self.augment > -1: self.name += 'aug' + str(self.augment) if self.DeviceType == 1: ...
class Solution(object): def kidsWithCandies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ max_candies = max(candies) # out_l = [] # for i in candies: # if(i + extraCandies >= max_c...
class Solution(object): def kids_with_candies(self, candies, extraCandies): """ :type candies: List[int] :type extraCandies: int :rtype: List[bool] """ max_candies = max(candies) return [True if i + extraCandies >= max_candies else False for i in candies]
n = int(input()) sticks = list(map(int, input().split())) uniq = sorted(set(sticks)) for i in uniq: print(len([x for x in sticks if x >= i]))
n = int(input()) sticks = list(map(int, input().split())) uniq = sorted(set(sticks)) for i in uniq: print(len([x for x in sticks if x >= i]))
x = 1 y = 10 if(x == 1): print("x equals 1") if(y != 1): print("y doesn't equal 1") if(x < y): print("x is less than y") elif(x > y): print("x is greater than y") else: print("x equals y") if (x == 1 and y == 10): print("Both values true") if(x < 10): if (y > 5): print("x is less th...
x = 1 y = 10 if x == 1: print('x equals 1') if y != 1: print("y doesn't equal 1") if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x equals y') if x == 1 and y == 10: print('Both values true') if x < 10: if y > 5: print('x is less than 10, y i...
class BackgroundClip( Property, ): BorderBox = "border-box" PaddingBox = "padding-box" ContentBox = "content-box"
class Backgroundclip(Property): border_box = 'border-box' padding_box = 'padding-box' content_box = 'content-box'
''' config file ''' n_one_hot_slot = 6 # 0 - user_id, 1 - movie_id, 2 - gender, 3 - age, 4 - occ, 5 - release year n_mul_hot_slot = 2 # 6 - title (mul-hot), 7 - genres (mul-hot) max_len_per_slot = 5 # max num of fts in one mul-hot slot num_csv_col_warm = 17 num_csv_col_w_ngb = 17 + 160 # num of cols in the csv file (...
""" config file """ n_one_hot_slot = 6 n_mul_hot_slot = 2 max_len_per_slot = 5 num_csv_col_warm = 17 num_csv_col_w_ngb = 17 + 160 layer_dim = [256, 128, 1] n_one_hot_slot_ngb = 6 n_mul_hot_slot_ngb = 2 max_len_per_slot_ngb = 5 max_n_ngb_ori = 10 max_n_ngb = 10 pre = './data/' suf = '.tfrecord' train_file_name_a = [pre ...
first_num_elements, second_num_elements2 = [int(num) for num in input().split()] first_set = {input() for _ in range(first_num_elements)} second_set = {input() for _ in range(second_num_elements2)} print(*first_set.intersection(second_set), sep='\n') # 4 3 # 1 # 3 # 5 # 7 # 3 # 4 # 5
(first_num_elements, second_num_elements2) = [int(num) for num in input().split()] first_set = {input() for _ in range(first_num_elements)} second_set = {input() for _ in range(second_num_elements2)} print(*first_set.intersection(second_set), sep='\n')
def decode_index(index: int) -> str: return {0: "ham", 1: "spam"}[index] def probability_to_index(prediction: list) -> int: return 0 if prediction[0] > prediction[1] else 1
def decode_index(index: int) -> str: return {0: 'ham', 1: 'spam'}[index] def probability_to_index(prediction: list) -> int: return 0 if prediction[0] > prediction[1] else 1
a = [] impar = [] par = [] while True: n1 = int(input("Digite um valor: ")) a.append(n1) if n1 % 2 == 0: par.append(n1) elif n1 % 2 != 0: impar.append(n1) s = str(input("Deseja continuar? [S/N]")) if s in 'Nn': break print(f"Lista geral {a}") print(f"Lista dos pares {par}...
a = [] impar = [] par = [] while True: n1 = int(input('Digite um valor: ')) a.append(n1) if n1 % 2 == 0: par.append(n1) elif n1 % 2 != 0: impar.append(n1) s = str(input('Deseja continuar? [S/N]')) if s in 'Nn': break print(f'Lista geral {a}') print(f'Lista dos pares {par}...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTilt(self, root): def travel(node, tiles): if node is None: return 0 ...
class Solution(object): def find_tilt(self, root): def travel(node, tiles): if node is None: return 0 sum_left = travel(node.left, tiles) sum_right = travel(node.right, tiles) diff = abs(sum_left - sum_right) tiles.append(diff) ...
class Triangle: def __init__(self,a,b,c): self.a=a self.b=b self.c=c def is_valid(self): if (self.a+self.b>self.c) and (self.a+self.c>self.b) and (self.b+self.c>self.a): return 'Valid' else: return 'Invalid' def Side_Classification(sel...
class Triangle: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def is_valid(self): if self.a + self.b > self.c and self.a + self.c > self.b and (self.b + self.c > self.a): return 'Valid' else: return 'Invalid' def side__classi...
def main(app_config=None, q1=0, q2=2): some_var = {'key': 'value'} if q1 > 9: return { "dict_return": 1, } return some_var if __name__ == "__main__": main()
def main(app_config=None, q1=0, q2=2): some_var = {'key': 'value'} if q1 > 9: return {'dict_return': 1} return some_var if __name__ == '__main__': main()
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2018 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
class Structure(list): def __init__(self, capacity, signature): self.capacity = capacity self.signature = signature def __repr__(self): return repr(tuple(iter(self))) def __eq__(self, other): return list(self) == list(other) def __ne__(self, other): return not...
#Implemnting queue ADT using singly linked list class LinkedQueue: """FIFO queue implementation using a singly linked list for storage""" class Empty(Exception): """Error attempting to access an element from an empty container""" pass class _Node: """Lightweight, nonpublic class...
class Linkedqueue: """FIFO queue implementation using a singly linked list for storage""" class Empty(Exception): """Error attempting to access an element from an empty container""" pass class _Node: """Lightweight, nonpublic class for storing singly linked node """ __slots...
# -*- coding: utf-8 -*- """ Created on Fri May 29 10:48:30 2020 @author: Tim """ n = 1000 count = 0 for i in range(n): for j in range(n): for k in range(n): if i < j and j < k: count += 1 print(count)
""" Created on Fri May 29 10:48:30 2020 @author: Tim """ n = 1000 count = 0 for i in range(n): for j in range(n): for k in range(n): if i < j and j < k: count += 1 print(count)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def isSymmetric(self, root: TreeNode) -> bool: """ function to determine if the provided TreeNode is the root of a symmetric binary tree """ ...
def is_symmetric(self, root: TreeNode) -> bool: """ function to determine if the provided TreeNode is the root of a symmetric binary tree """ def is_mirror(left: TreeNode, right: TreeNode) -> bool: """ Utility function to determine if two trees mirror each other. If the root and ...
# Python3 program to find the numbers # of non negative integral solutions # return number of non negative # integral solutions def countSolutions(n, val,indent): print(indent+"countSolutions(",n,val,")") # initialize total = 0 total = 0 # Base Case if n = 1 and val >= 0 # then it shoul...
def count_solutions(n, val, indent): print(indent + 'countSolutions(', n, val, ')') total = 0 if n == 1 and val >= 0: return 1 for i in range(val + 1): total += count_solutions(n - 1, val - i, indent + ' ') return total n = 4 val = 2 print(count_solutions(n, val, ''))
# -*- coding: utf-8 -*- DATABASE_MAPPING = { 'database_list': { 'resource': 'database/', 'docs': '', 'methods': ['GET'], }, 'database_get': { 'resource': 'database/{id}/', 'docs': '', 'methods': ['GET'], }, 'database_create': { 'resource': 'da...
database_mapping = {'database_list': {'resource': 'database/', 'docs': '', 'methods': ['GET']}, 'database_get': {'resource': 'database/{id}/', 'docs': '', 'methods': ['GET']}, 'database_create': {'resource': 'database/', 'docs': '', 'methods': ['POST']}, 'database_update': {'resource': 'database/{id}/', 'docs': '', 'me...
def is_abundant(number): mysum = 1 # Can always divide by 1, so start looking at divisor 2 for divisor in range(2, int(round(number / 2 + 1))): if number % divisor == 0: mysum += divisor if mysum > number: return True else: return False
def is_abundant(number): mysum = 1 for divisor in range(2, int(round(number / 2 + 1))): if number % divisor == 0: mysum += divisor if mysum > number: return True else: return False
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - Muhammad Aditya Hilmy...
class Didnotavailableexception(BaseException): def __init__(self): super().__init__('DID is not yet available.') class Multipleitemdid(list): def __init__(self, items, did_available=True): super(MultipleItemDID, self).__init__(items) self.items = items self.did_available = did...
class OAuthError(Exception): """Base class for OAuth errors""" pass class OAuthStateMismatchError(OAuthError): pass class OAuthCannotDisconnectError(OAuthError): pass class OAuthUserAlreadyExistsError(OAuthError): pass
class Oautherror(Exception): """Base class for OAuth errors""" pass class Oauthstatemismatcherror(OAuthError): pass class Oauthcannotdisconnecterror(OAuthError): pass class Oauthuseralreadyexistserror(OAuthError): pass
def ispow2(n): ''' True if n is a power of 2, False otherwise >>> ispow2(5) False >>> ispow2(4) True ''' return (n & (n-1)) == 0 def nextpow2(n): ''' Given n, return the nearest power of two that is >= n >>> nextpow2(1) 1 >>> nextpow2(2) 2 >>> nextpow2(5) ...
def ispow2(n): """ True if n is a power of 2, False otherwise >>> ispow2(5) False >>> ispow2(4) True """ return n & n - 1 == 0 def nextpow2(n): """ Given n, return the nearest power of two that is >= n >>> nextpow2(1) 1 >>> nextpow2(2) 2 >>> nextpow2(5) ...
# Complete the fibonacciModified function below. def fibonacciModified(t1, t2, n): term = 3 while term <= n: actual_number = t1 + t2**2 t1 = t2 t2 = actual_number term += 1 return actual_number
def fibonacci_modified(t1, t2, n): term = 3 while term <= n: actual_number = t1 + t2 ** 2 t1 = t2 t2 = actual_number term += 1 return actual_number
a=1; b=2; c=a+b; print("hello world") 121213
a = 1 b = 2 c = a + b print('hello world') 121213
name = input() age = int(input()) while name != 'Anton': print(name) name = input() age = input() print(f'I am Anton')
name = input() age = int(input()) while name != 'Anton': print(name) name = input() age = input() print(f'I am Anton')
class Task(object): def __init__(self, name, description="", task_id=None): self.id = task_id self.name = name self.description = description def serialize(self): return { "id": self.id, "name": self.name, "description": self.d...
class Task(object): def __init__(self, name, description='', task_id=None): self.id = task_id self.name = name self.description = description def serialize(self): return {'id': self.id, 'name': self.name, 'description': self.description} @staticmethod def serialize_mul...
# -*- coding: utf-8 -*- _available_examples = ["ex_001_Molecule_Hamiltonian.py", "ex_002_Molecule_Aggregate.py", "ex_003_CorrFcnSpectDens.py", "ex_004_SpectDensDatabase.py", "ex_005_UnitsManagementHamiltonian.py", ...
_available_examples = ['ex_001_Molecule_Hamiltonian.py', 'ex_002_Molecule_Aggregate.py', 'ex_003_CorrFcnSpectDens.py', 'ex_004_SpectDensDatabase.py', 'ex_005_UnitsManagementHamiltonian.py', 'ex_006_Absorption_1.py', 'ex_010_RedfieldTheory_1.py', 'ex_011_LindbladForm_1.py', 'ex_012_Integrodiff.py', 'ex_013_HEOM.py', 'ex...
def recursive_multiply(x, y): if (x < y): return recursive_multiply(y, x) elif (y != 0): return (x + recursive_multiply(x, y-1)) else: return 0 x = int(input("Enter x")) y = int(input("Enter y")) print(recursive_multiply(x, y))
def recursive_multiply(x, y): if x < y: return recursive_multiply(y, x) elif y != 0: return x + recursive_multiply(x, y - 1) else: return 0 x = int(input('Enter x')) y = int(input('Enter y')) print(recursive_multiply(x, y))
DEFAULT_STACK_SIZE = 8 class PcStack(object): def __init__(self, programCounter, size: int=DEFAULT_STACK_SIZE): self._programCounter = programCounter self._size = size self._stack = [0]*size self._stackPointer = 0 @property def programCounter(self): return self._p...
default_stack_size = 8 class Pcstack(object): def __init__(self, programCounter, size: int=DEFAULT_STACK_SIZE): self._programCounter = programCounter self._size = size self._stack = [0] * size self._stackPointer = 0 @property def program_counter(self): return self....
# -*- coding: utf-8 -*- user_schema = { 'username': { 'type': 'string', 'minlength': 1, 'maxlength': 64, 'required': True, 'unique': True }, 'email': { 'type': 'string', 'regex': '^\S+@\S+.\S+', 'required': True, 'unique': True }, ...
user_schema = {'username': {'type': 'string', 'minlength': 1, 'maxlength': 64, 'required': True, 'unique': True}, 'email': {'type': 'string', 'regex': '^\\S+@\\S+.\\S+', 'required': True, 'unique': True}, 'password': {'type': 'string', 'minlength': 1, 'maxlength': 64, 'required': True}} user = {'item_title': 'user', 'a...
''' https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/ Given a 2-Dimensional character array and a string, we need to find the given string in 2-dimensional character array such that individual characters can be present left to right, right to left, top to down or down to top. Exa...
""" https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/ Given a 2-Dimensional character array and a string, we need to find the given string in 2-dimensional character array such that individual characters can be present left to right, right to left, top to down or down to top. Exa...
# # PHASE: jvm flags # # DOCUMENT THIS # def phase_jvm_flags(ctx, p): if ctx.attr.tests_from: archives = _get_test_archive_jars(ctx, ctx.attr.tests_from) else: archives = p.compile.merged_provider.runtime_output_jars serialized_archives = _serialize_archives_short_path(archives) test_su...
def phase_jvm_flags(ctx, p): if ctx.attr.tests_from: archives = _get_test_archive_jars(ctx, ctx.attr.tests_from) else: archives = p.compile.merged_provider.runtime_output_jars serialized_archives = _serialize_archives_short_path(archives) test_suite = _gen_test_suite_flags_based_on_prefi...
METADATA = 'metadata' CONTENT = 'content' FILENAME = 'filename' PARAM_CREATION_DATE = '_audit_creation_date' PARAM_R1 = '_diffrn_reflns_av_R_equivalents' PARAM_SIGMI_NETI = '_diffrn_reflns_av_sigmaI/netI' PARAM_COMPLETENESS = '_reflns_odcompleteness_completeness' PARAM_SPACEGROUP = '_space_group_name_H-M_alt' PARAM_SP...
metadata = 'metadata' content = 'content' filename = 'filename' param_creation_date = '_audit_creation_date' param_r1 = '_diffrn_reflns_av_R_equivalents' param_sigmi_neti = '_diffrn_reflns_av_sigmaI/netI' param_completeness = '_reflns_odcompleteness_completeness' param_spacegroup = '_space_group_name_H-M_alt' param_spa...
class cves(): cve_url = "https://services.nvd.nist.gov/rest/json/cves/1.0?pubStartDate=2021-09-01T00:00:00:000+UTC-00:00&resultsPerPage=100&keyword=" keywords = ["RHCS", "RHEL", "Thales", "nShield", "Certificate+Authority&isExactMatch=true", "NSS", "tomcat", "TLS"]
class Cves: cve_url = 'https://services.nvd.nist.gov/rest/json/cves/1.0?pubStartDate=2021-09-01T00:00:00:000+UTC-00:00&resultsPerPage=100&keyword=' keywords = ['RHCS', 'RHEL', 'Thales', 'nShield', 'Certificate+Authority&isExactMatch=true', 'NSS', 'tomcat', 'TLS']
class SingleMethods: def __init__(self, finished_reports_dictionary, single_reports_dictionary, sample_data, latex_header_and_sample_list_dictionary, loq_dictionary ): self.finished_reports_dictionary = fi...
class Singlemethods: def __init__(self, finished_reports_dictionary, single_reports_dictionary, sample_data, latex_header_and_sample_list_dictionary, loq_dictionary): self.finished_reports_dictionary = finished_reports_dictionary self.single_reports_dictionary = single_reports_dictionary se...
#!/usr/local/bin/python3 class Object(object): def __init__(self, id): self.id = id self.children = [] root = Object("COM") objects = {"COM": root} def get_object(id): if id not in objects: objects[id] = Object(id) return objects[id] with open("input.txt") as f: for line in f...
class Object(object): def __init__(self, id): self.id = id self.children = [] root = object('COM') objects = {'COM': root} def get_object(id): if id not in objects: objects[id] = object(id) return objects[id] with open('input.txt') as f: for line in f.readlines(): (pare...
begin_unit comment|'# Copyright (c) 2013 Intel, Inc.' nl|'\n' comment|'# Copyright (c) 2012 OpenStack Foundation' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in ...
begin_unit comment | '# Copyright (c) 2013 Intel, Inc.' nl | '\n' comment | '# Copyright (c) 2012 OpenStack Foundation' nl | '\n' comment | '# All Rights Reserved.' nl | '\n' comment | '#' nl | '\n' comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl | '\n' comment | '# not us...