content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
This program turns a string into all capital or all lowercase letters.
"""
first_string = "hello"
second_string = first_string.upper()
third_string = second_string.lower()
print(first_string)
print(second_string)
print(third_string) | """
This program turns a string into all capital or all lowercase letters.
"""
first_string = 'hello'
second_string = first_string.upper()
third_string = second_string.lower()
print(first_string)
print(second_string)
print(third_string) |
name = input("please enter name: ")
'''
count = 0
for i in name:
if i == ",":
count +=1
print("you entered " + str(count + 1) + " names")
'''
a = name.count(",")
b = a + 1
print (b)
| name = input('please enter name: ')
'\ncount = 0\nfor i in name:\n if i == ",":\n count +=1\n\nprint("you entered " + str(count + 1) + " names")\n\n'
a = name.count(',')
b = a + 1
print(b) |
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes,
as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table
for the 26 letters of the English alphabet is given below:
[
".-","-...","-.-.","-.... | """
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes,
as follows: "a" maps to ".-", "b" maps to "-...", "c" maps to "-.-.", and so on. For convenience, the full table
for the 26 letters of the English alphabet is given below:
[
".-","-...","-.-.","-.... |
class AgeError(Exception):
def __init__(self,message):
Exception.__init__(self,message)
try: # Write the code whose exceptions need handling
d = {1:"One"}
print(d[1])
age= int(input("Enter Age: "))
if age < 0:
raise AgeError('Age is Negative')# Throw your own exception
f = 100/2... | class Ageerror(Exception):
def __init__(self, message):
Exception.__init__(self, message)
try:
d = {1: 'One'}
print(d[1])
age = int(input('Enter Age: '))
if age < 0:
raise age_error('Age is Negative')
f = 100 / 2
except KeyError as e:
print('Key Error ' + str(e))
except Valu... |
# pyinfra
# File: pyinfra/api/exceptions.py
# Desc: pyinfra's exceptions!
class PyinfraError(Exception):
'''
Generic pyinfra exception.
'''
class OperationError(PyinfraError):
'''
Exception raised during fact gathering staging if an operation is unable to
generate output/change state.
''... | class Pyinfraerror(Exception):
"""
Generic pyinfra exception.
"""
class Operationerror(PyinfraError):
"""
Exception raised during fact gathering staging if an operation is unable to
generate output/change state.
"""
class Deployerror(PyinfraError):
"""
User exception for raising in... |
__project__ = 'checkio'
__version__ = '0.72.0'
VERSION = "{0} v{1}".format(__project__, __version__)
| __project__ = 'checkio'
__version__ = '0.72.0'
version = '{0} v{1}'.format(__project__, __version__) |
class MinPQ():
def __init__(self):
self.a = [None]
self.n = 0
self.size = 0
def insert(self, item):
if self.n == self.size:
self._resize(max(1, self.n) * 2)
self.n += 1
self.a[self.n] = item
self._swim(self.n)
return None
def del_... | class Minpq:
def __init__(self):
self.a = [None]
self.n = 0
self.size = 0
def insert(self, item):
if self.n == self.size:
self._resize(max(1, self.n) * 2)
self.n += 1
self.a[self.n] = item
self._swim(self.n)
return None
def del_m... |
with open("input.txt") as f:
data = f.read().splitlines()
horizontal, vertical, aim = 0, 0, 0
for command in data:
direction, amount = command.split()
match direction:
case "forward":
horizontal += int(amount)
vertical += int(amount) * aim
case "down":
... | with open('input.txt') as f:
data = f.read().splitlines()
(horizontal, vertical, aim) = (0, 0, 0)
for command in data:
(direction, amount) = command.split()
match direction:
case 'forward':
horizontal += int(amount)
vertical += int(amount) * aim
case 'down':
... |
APP_PATH = '/var/www/Capstone/'
LANDS_PATH = APP_PATH + 'var/landmarks/face_landmarks_68.dat'
RATIOS_PATH = APP_PATH + 'var/data/ratios.json'
RATIOS_AVG_PATH = APP_PATH + 'var/data/ratios_avg.json'
RATIOS_STDS_PATH = APP_PATH + 'var/data/ratios_stdevs.json'
ANGLES_PATH = APP_PATH + 'var/data/angles.json'
ANGLES_AVG_P... | app_path = '/var/www/Capstone/'
lands_path = APP_PATH + 'var/landmarks/face_landmarks_68.dat'
ratios_path = APP_PATH + 'var/data/ratios.json'
ratios_avg_path = APP_PATH + 'var/data/ratios_avg.json'
ratios_stds_path = APP_PATH + 'var/data/ratios_stdevs.json'
angles_path = APP_PATH + 'var/data/angles.json'
angles_avg_pat... |
class MethodDoc():
def __init__(self, namespace, method_sig):
self.__namespace = namespace
self.__method_sig = method_sig
self.__description = ''
self.__signature = ''
self.__parameters = {}
self.__return_type = ''
self.__return_description = ''
self._... | class Methoddoc:
def __init__(self, namespace, method_sig):
self.__namespace = namespace
self.__method_sig = method_sig
self.__description = ''
self.__signature = ''
self.__parameters = {}
self.__return_type = ''
self.__return_description = ''
self.__... |
# Inteiro para Romano
def int_to_roman(num):
"""
https://www.w3resource.com/python-exercises/class-exercises/python-class-exercise-1.php
:param num:
:return:
"""
lookup = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),... | def int_to_roman(num):
"""
https://www.w3resource.com/python-exercises/class-exercises/python-class-exercise-1.php
:param num:
:return:
"""
lookup = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, ... |
# Python Program To Create A New Object Inside The Function Does Not Modify Outside Object
'''
Function Name : Create New Object Inside Function Does Not Modify Outside Object.
Function Date : 6 Sep 2020
Function Author : Prasad Dangare
Input : Integer
Output : Integer
'''
... | """
Function Name : Create New Object Inside Function Does Not Modify Outside Object.
Function Date : 6 Sep 2020
Function Author : Prasad Dangare
Input : Integer
Output : Integer
"""
def modify(lst):
""" To Create A New List """
lst = [10, 11, 12]
print(lst, id(lst))
lst ... |
#
# PySNMP MIB module LSF-SNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LSF-SNMP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:08:56 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,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
class BeaconDBException(Exception):
"""
Base class for exceptions raised by this package.
"""
pass
class HeadStateSlotNotFound(BeaconDBException):
"""
Exception raised if head state slot does not exist.
"""
pass
class StateNotFound(BeaconDBException):
"""
Exception raised i... | class Beacondbexception(Exception):
"""
Base class for exceptions raised by this package.
"""
pass
class Headstateslotnotfound(BeaconDBException):
"""
Exception raised if head state slot does not exist.
"""
pass
class Statenotfound(BeaconDBException):
"""
Exception raised if st... |
class TopVotedCandidate:
def __init__(self, persons, times):
votes = collections.defaultdict(int)
winner = 0
self.winners = [None] * len(times)
self.times = times
for i, person in enumerate(persons):
votes[person] += 1
if votes[person] >= votes[winne... | class Topvotedcandidate:
def __init__(self, persons, times):
votes = collections.defaultdict(int)
winner = 0
self.winners = [None] * len(times)
self.times = times
for (i, person) in enumerate(persons):
votes[person] += 1
if votes[person] >= votes[winn... |
def get_shortest_path(graph: dict, start, goal) -> str:
# keep track of visited nodes
visited = []
# keep track of all the paths to be checked
queue = [[start]]
# return path if start is goal
if start == goal:
return start
# keeps looping until all possible paths have been checked
... | def get_shortest_path(graph: dict, start, goal) -> str:
visited = []
queue = [[start]]
if start == goal:
return start
while queue:
path = queue.pop(0)
node = path[-1]
if node not in visited:
neighbours = graph[node]
for neighbour in neighbours:
... |
"""
Madau, P., & Dickinson, M. 2014, ARA&A, 52, 415
"""
pars_ml = \
{
'a': 0.015,
'b': 2.7,
'c': 2.9,
'd': 5.6,
}
#pars_err = \
#{
# 'a': 0.001,
# 'b': 0.21,
# 'c': 0.14,
# 'd': 0.19,
#}
def _SFRD(z, a=None, b=None, c=None, d=None):
return a * (1. + z)**b / (1 + ((1 + z) / c)**d)
def SFRD(z):
return _SF... | """
Madau, P., & Dickinson, M. 2014, ARA&A, 52, 415
"""
pars_ml = {'a': 0.015, 'b': 2.7, 'c': 2.9, 'd': 5.6}
def _sfrd(z, a=None, b=None, c=None, d=None):
return a * (1.0 + z) ** b / (1 + ((1 + z) / c) ** d)
def sfrd(z):
return _sfrd(z, **pars_ml)
info = {'Lmin': '0.03 * Lstar'} |
expected_output = {
'vrf': {
'vrf_104': {
'address_family': {
'ipv4': {
'no_group_ranges': 5,
'no_g_routes': 1,
'no_s_g_routes': 100,
'no_route_x_interfaces': 100,
'total_no_inte... | expected_output = {'vrf': {'vrf_104': {'address_family': {'ipv4': {'no_group_ranges': 5, 'no_g_routes': 1, 'no_s_g_routes': 100, 'no_route_x_interfaces': 100, 'total_no_interfaces': 202}}}}} |
# Specify output formats. At least one must = True
STL = True # [True, False]
WEB = False # [True, False]
STEP = False # [True, False]
# Set Standard Dimensions
std_d = 40.0 # Diameter of the base [5.0 to 100.0] (mm)
std_h = 48.0 # Height of the neck [10.0 to 200.0 ] (mm) NOTE: this is the height of the bisho... | stl = True
web = False
step = False
std_d = 40.0
std_h = 48.0
std_top = 22.0
pawn = {'base': {'diameter': std_d, 'height': std_h / 4.0}, 'neck': {'bottom_d': std_d * 0.925, 'top_d': std_d * 0.4, 'height': std_h * 0.65}, 'top': {'diameter': std_top * 0.95, 'piece': 'pawn'}}
rook = {'base': {'diameter': std_d, 'height': ... |
# def find_similar_in_3_arrays(a, b, c):
# ii, jj, kk = 0, 0, 0
# result = []
# while (ii <= len(a)) and (jj <= len(b)) and (kk <= len(c)):
# ii
# if a[ii] > b[jj] and a[ii] > c[kk]:
# print("a i ", a[ii])
# jj += 1
# kk += 1
# elif b[jj] > a[ii] ... | def find_common(a, b, c):
(ii, jj, kk) = (0, 0, 0)
results = []
while ii < len(a):
if a[ii] > b[jj] and a[ii] > c[kk]:
while jj < len(b) and b[jj] < a[ii]:
jj += 1
while kk < len(c) and c[kk] < a[ii]:
kk += 1
if jj < len(b) and kk < len... |
class ComboBoxData(RibbonItemData):
"""
This class contains information necessary to construct a combo box in the Ribbon.
ComboBoxData(name: str)
"""
@staticmethod
def __new__(self,name):
""" __new__(cls: type,name: str) """
pass
Image=property(lambda self: object(),lambda self,v: None,lambda... | class Comboboxdata(RibbonItemData):
"""
This class contains information necessary to construct a combo box in the Ribbon.
ComboBoxData(name: str)
"""
@staticmethod
def __new__(self, name):
""" __new__(cls: type,name: str) """
pass
image = property(lambda self: object(), lambda se... |
"""
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should
become 1 -> 2 -> 4 after calling your function.
"""
__author__ = 'Daniel'
class ListNode:... | """
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should
become 1 -> 2 -> 4 after calling your function.
"""
__author__ = 'Daniel'
class Listnode:
... |
# A function is a block of code which only runs when it is called. In Python,
# we do not use parentheses and curly brackets, we use indentation with tabs or spaces
# Create function
def sayHello(name = 'Sam'):
"""
Prints Hello and then name.
"""
print('Hello ' + name)
# Return value
def getSum(num1, num2):
... | def say_hello(name='Sam'):
"""
Prints Hello and then name.
"""
print('Hello ' + name)
def get_sum(num1, num2):
total = num1 + num2
return total
num_sum = get_sum(2, 3)
def add_one_to_num(num):
num += 1
return num
num = 5
new_num = add_one_to_num(num)
print(new_num)
get_sum = lambda num1, n... |
# increment i by one
i += 1
def sentence_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
# Tokenize and tag
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
# Get the synsets for the tagged words
synsets1 = [ta... | i += 1
def sentence_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
synsets1 = [tagged_to_synset(*tagged_word) for tagged_word in sentence1]
synsets2 = [tagged_to_syns... |
class IStorageOption:
@staticmethod
def config_has_api(request) -> bool:
"""check if the api exists"""
pass
# Create new redis key
@staticmethod
def config_load_headers(cache_key, val, exp):
"""Creates the header object from storage"""
pass
# Get value of key
... | class Istorageoption:
@staticmethod
def config_has_api(request) -> bool:
"""check if the api exists"""
pass
@staticmethod
def config_load_headers(cache_key, val, exp):
"""Creates the header object from storage"""
pass
@staticmethod
def config_is_scoped(cache_ke... |
#
# PySNMP MIB module BAY-STACK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:35:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint, constraints_union) ... |
def filter_noncruising(trip_list, keep_only_driving=True,
keep_all_fhv=False, silent=True):
# keep_list = np.repeat(0, len(trip_list))
# for i in range(len(trip_list)):
if keep_all_fhv == True:
# if trip_list[i]['label'] == 'cruising' or \
# trip_list[i]['fhv'] == True:
trip... | def filter_noncruising(trip_list, keep_only_driving=True, keep_all_fhv=False, silent=True):
if keep_all_fhv == True:
trip_list = list(filter(lambda x: x['label'] == 'cruising' or x['fhv'] == True, trip_list))
else:
trip_list = list(filter(lambda x: x['label'] == 'cruising', trip_list))
if ke... |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Reverses a string obtained from user. #
# Program ... | def obtain_user_data(input_mess: str) -> str:
(user_data, valid) = ('', False)
while not valid:
try:
user_data = input(input_mess).strip()
if len(user_data) == 0:
raise value_error(f'Oops! word needed')
valid = True
except ValueError as ve:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 7 12:26:07 2021
@author: aymer
"""
data | """
Created on Wed Jul 7 12:26:07 2021
@author: aymer
"""
data |
"""
Given a string, find the first non-repeating character in it and return its
index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
"""
#Difficulty: Easy
#104 / ... | """
Given a string, find the first non-repeating character in it and return its
index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
"""
class Solution:
def... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 15:47:06 2020
@author: Christopher Cheng
"""
# Define an object type via class
# parenthesis of object means your class is going to be a python object
class Circle (object):
# Must initialize parameters of a class afterwards
# this is aka method
# self i... | """
Created on Sat May 23 15:47:06 2020
@author: Christopher Cheng
"""
class Circle(object):
def __init__(self):
self.radius = 0
def change_radius(self, radius):
self.radius = radius
def get_radius(self):
return self.radius |
class CoffeeMachine:
# Constructor that initializes a CoffeeMachine with default values.
def __init__(self):
self.water = 400
self.milk = 540
self.coffee_beans = 120
self.cups = 9
self.money = 550
self.state = 'await_command'
# Determines if the coffee machin... | class Coffeemachine:
def __init__(self):
self.water = 400
self.milk = 540
self.coffee_beans = 120
self.cups = 9
self.money = 550
self.state = 'await_command'
def buy(self, choice):
self.state = 'await_command'
if choice == 'back':
ret... |
class options():
mitm = True
sniffer = True
srv_ = "192.168.0.100"
port = 5777
gui = False | class Options:
mitm = True
sniffer = True
srv_ = '192.168.0.100'
port = 5777
gui = False |
def find_subarray(A, i):
k = A[i]
solutions = [A.pop(i)]
for n in range(i - 1, -1, -1): # search left
if k >= A[n]:
solutions.insert(0, A.pop(n))
else:
break
for n in range(-(len(A) - i - 1), 0): # search right
if k >= A[n]:
solutions.append(A... | def find_subarray(A, i):
k = A[i]
solutions = [A.pop(i)]
for n in range(i - 1, -1, -1):
if k >= A[n]:
solutions.insert(0, A.pop(n))
else:
break
for n in range(-(len(A) - i - 1), 0):
if k >= A[n]:
solutions.append(A.pop(n))
else:
... |
class abstractstatic(staticmethod):
__slots__ = ()
def __init__(self, function):
super(abstractstatic, self).__init__(function)
function.__isabstractmethod__ = True
__isabstractmethod__ = True
| class Abstractstatic(staticmethod):
__slots__ = ()
def __init__(self, function):
super(abstractstatic, self).__init__(function)
function.__isabstractmethod__ = True
__isabstractmethod__ = True |
ACCOUNTS = [
{
'email': 'grrr',
'password': 'grrr',
},
]
| accounts = [{'email': 'grrr', 'password': 'grrr'}] |
class Heap:
"""Base class for heap object."""
def __init__(self):
"""Initialize constructor for heap object."""
self.heap = []
def parent(self, index: int) -> int:
return (index - 1) // 2
def left_child(self, index: int) -> int:
return (2 * index) + 1 # pragma: no cove... | class Heap:
"""Base class for heap object."""
def __init__(self):
"""Initialize constructor for heap object."""
self.heap = []
def parent(self, index: int) -> int:
return (index - 1) // 2
def left_child(self, index: int) -> int:
return 2 * index + 1
def right_chil... |
######## Return Statement ########
def cube(num):
return num*num*num
print(cube(3))
result = cube(4)
print(result) | def cube(num):
return num * num * num
print(cube(3))
result = cube(4)
print(result) |
def bubbleSort(lst):
for i in range(len(lst)-1):
for j in range(len(lst)-1, i, -1):
if lst[j] < lst[j-1]:
lst[j-1], lst[j] = lst[j], lst[j-1]
return lst
if __name__ == '__main__':
lst = [8, 11, 2, 1, 4, 19, 9, 14, 13, 5, 6, 22]
lst = bubbleSort(lst)
print(lst) | def bubble_sort(lst):
for i in range(len(lst) - 1):
for j in range(len(lst) - 1, i, -1):
if lst[j] < lst[j - 1]:
(lst[j - 1], lst[j]) = (lst[j], lst[j - 1])
return lst
if __name__ == '__main__':
lst = [8, 11, 2, 1, 4, 19, 9, 14, 13, 5, 6, 22]
lst = bubble_sort(lst)
... |
#program to perform ceaser cipher
ch='y'
while ch=='y' or ch=='Y':
print("Menu:") #menu for asking choice
print("1.Cipher a message")
print("2.Decipher a message")
choice=int(input("Enter your choice: "))
if choice==1:
string=input("Enter the string: ")
k=i... | ch = 'y'
while ch == 'y' or ch == 'Y':
print('Menu:')
print('1.Cipher a message')
print('2.Decipher a message')
choice = int(input('Enter your choice: '))
if choice == 1:
string = input('Enter the string: ')
k = int(input('Enter the key for ciphering: '))
print('Creating ciph... |
#!/usr/bin/env python3
# Add two link-lists of integers, this time in python
#
# found here:
# https://leetcode.com/problems/add-two-numbers/
#
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: Lis... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode:
result_node = list_node(0)
head_node = resultNode
carry_over = 0
while l1 or l2 or carryOver... |
class MixTapeError(Exception):
"""Mixtape exception base clase"""
class PlayerNotConfigured(MixTapeError):
"""Player setup not completed"""
class PlayerAlreadyConfigured(MixTapeError):
"""Player has already been setup"""
class PlayerSetStateError(MixTapeError):
"""Setting the pipeline state has fa... | class Mixtapeerror(Exception):
"""Mixtape exception base clase"""
class Playernotconfigured(MixTapeError):
"""Player setup not completed"""
class Playeralreadyconfigured(MixTapeError):
"""Player has already been setup"""
class Playersetstateerror(MixTapeError):
"""Setting the pipeline state has faile... |
class DisplayFilter:
def __init__(self):
self.log_level_set = set()
def Update_Filter(self, log_level_set):
self.log_level_set = log_level_set
def IsValidForFilter(self, log_message):
if log_message.level in self.log_level_set:
return True
return False
| class Displayfilter:
def __init__(self):
self.log_level_set = set()
def update__filter(self, log_level_set):
self.log_level_set = log_level_set
def is_valid_for_filter(self, log_message):
if log_message.level in self.log_level_set:
return True
return False |
def two_sum_hastable(nums, target):
hashtable = {}
for i, num in enumerate(nums):
remaining = target - num
if remaining not in hashtable:
hashtable[num] = i
else:
return [hashtable[remaining], i]
| def two_sum_hastable(nums, target):
hashtable = {}
for (i, num) in enumerate(nums):
remaining = target - num
if remaining not in hashtable:
hashtable[num] = i
else:
return [hashtable[remaining], i] |
#-------------------------------------------------------------------------------
# elftools: elf/constants.py
#
# Constants and flags, placed into classes for namespacing
#
# Eli Bendersky (eliben@gmail.com)
# This code is in the public domain
#---------------------------------------------------------------------------... | class Shn_Indices(object):
""" Special section indices
"""
shn_undef = 0
shn_loreserve = 65280
shn_loproc = 65280
shn_hiproc = 65311
shn_abs = 65521
shn_common = 65522
shn_hireserve = 65535
class Sh_Flags(object):
""" Flag values for the sh_flags field of section headers
"""... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"
'''
| """
Created on 1.12.2016
@author: Darren
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
"
""" |
class Vector:
size = 0
capacity = 0
data = []
def _init__(self, size=0):
self.size = size
if size:
self.data = [None] * size
print('Vector initialized!!')
def __str__(self):
return "Size = {} \nCapacity = {} \nData = {}\n".format(
self.size, ... | class Vector:
size = 0
capacity = 0
data = []
def _init__(self, size=0):
self.size = size
if size:
self.data = [None] * size
print('Vector initialized!!')
def __str__(self):
return 'Size = {} \nCapacity = {} \nData = {}\n'.format(self.size, self.capacity... |
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count = 0
for char in S:
if char in J:
count +=1
return count
if __name__ == '__main__':
J = "aA"
S = "aAAbbbb"
instance = Solution()
solution = instance.numJewelsInStones(J,S)
... | class Solution:
def num_jewels_in_stones(self, J: str, S: str) -> int:
count = 0
for char in S:
if char in J:
count += 1
return count
if __name__ == '__main__':
j = 'aA'
s = 'aAAbbbb'
instance = solution()
solution = instance.numJewelsInStones(J, ... |
class Account():
def __init__(self,ownername,balance):
self.ownername=ownername
self.balance=balance
def _str_(self):
return 'Account owner:{ownername}\nAccount balance:${balance}'.format(ownername=self.owner,balance=self.balance)
def deposit(self,dp_money):
self.balan... | class Account:
def __init__(self, ownername, balance):
self.ownername = ownername
self.balance = balance
def _str_(self):
return 'Account owner:{ownername}\nAccount balance:${balance}'.format(ownername=self.owner, balance=self.balance)
def deposit(self, dp_money):
self.bal... |
#MP03 by Jake Hayes
def rail4Encrypt(plainText):
firstChars=""
secondChars=""
thirdChars=""
fourthChars=""
for i in range(len(plainText)):
if i%4==0:
fourthChars=fourthChars+plainText[i]
elif (i-1)%4==0:
thirdChars=thirdChars+plainText[i]
elif i%2==0:
... | def rail4_encrypt(plainText):
first_chars = ''
second_chars = ''
third_chars = ''
fourth_chars = ''
for i in range(len(plainText)):
if i % 4 == 0:
fourth_chars = fourthChars + plainText[i]
elif (i - 1) % 4 == 0:
third_chars = thirdChars + plainText[i]
... |
# Python - 3.6.0
test.assert_equals(warn_the_sheep(['sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'wolf', 'sheep', 'sheep']), 'Oi! Sheep number 2! You are about to be eaten by a wolf!')
test.assert_equals(warn_the_sheep(['sheep', 'wolf', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep']), 'Oi! Sheep number 5! You are about ... | test.assert_equals(warn_the_sheep(['sheep', 'sheep', 'sheep', 'sheep', 'sheep', 'wolf', 'sheep', 'sheep']), 'Oi! Sheep number 2! You are about to be eaten by a wolf!')
test.assert_equals(warn_the_sheep(['sheep', 'wolf', 'sheep', 'sheep', 'sheep', 'sheep', 'sheep']), 'Oi! Sheep number 5! You are about to be eaten by a w... |
def _sum_compose(losses):
loss = sum(v[0] for v in losses)
loss_value = sum(v[1] for v in losses)
loss_dict = {}
[loss_dict.update(v[2]) for v in losses]
return loss, loss_value, loss_dict
class MultiScaleLossComposer:
def __init__(self, compose_fn, single_scale_loss_composers):
self.s... | def _sum_compose(losses):
loss = sum((v[0] for v in losses))
loss_value = sum((v[1] for v in losses))
loss_dict = {}
[loss_dict.update(v[2]) for v in losses]
return (loss, loss_value, loss_dict)
class Multiscalelosscomposer:
def __init__(self, compose_fn, single_scale_loss_composers):
... |
#!/usr/bin/python3
""" All constants for Jupyter Notebook testing """
DEFAULT_WAIT_PERIOD = 10
START_SERVER_WAIT_PERIOD = 60
DATAHUB_DEV_URL = "http://datahub-dev.berkeley.edu"
NBPULLER_ROUTE = "/interact"
JPY_USER_ROUTE = "/user/peterkangveerman"
TEST_1_PARAMS = "repo=data8assets&path=materials/sp17/lab/lab02"
TEST_1... | """ All constants for Jupyter Notebook testing """
default_wait_period = 10
start_server_wait_period = 60
datahub_dev_url = 'http://datahub-dev.berkeley.edu'
nbpuller_route = '/interact'
jpy_user_route = '/user/peterkangveerman'
test_1_params = 'repo=data8assets&path=materials/sp17/lab/lab02'
test_1_files = ['tests', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# def build_column_names_from_list_of_column_name_with_type(list_of_column_name_with_type):
# column_names = []
#
# for column_name_with_type in list_of_column_name_with_type:
# # if the column is a geometry, so transform the geom to text
# if "geo... | def get_subquery_feature(f_table_name, feature_id, columns_of_table):
conditions_of_where = []
if feature_id is not None:
conditions_of_where.append('id = {0}'.format(feature_id))
where_clause = ''
if conditions_of_where:
where_clause = 'WHERE ' + ' AND '.join(conditions_of_where)
su... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class SqlOptionsEnum(object):
"""Implementation of the 'SqlOptions' enum.
Specifies the sql options to update the Restore Task with.
Specifies the action type of multi stage SQL restore.
'kCreate' specifies the create action for a restore.
'k... | class Sqloptionsenum(object):
"""Implementation of the 'SqlOptions' enum.
Specifies the sql options to update the Restore Task with.
Specifies the action type of multi stage SQL restore.
'kCreate' specifies the create action for a restore.
'kUpdate' specifies the user action to update an ongoing re... |
wid = 0
hei = 0
dots = []
folds = []
grid = []
def loadFile():
global wid
global hei
#load dots
f = open("Day13\\Input.txt", "r")
for x in f:
if x=="\n":
break
x = x.strip()
dot = [int(y) for y in x.split(',')]
if(dot[0]>=wid):
... | wid = 0
hei = 0
dots = []
folds = []
grid = []
def load_file():
global wid
global hei
f = open('Day13\\Input.txt', 'r')
for x in f:
if x == '\n':
break
x = x.strip()
dot = [int(y) for y in x.split(',')]
if dot[0] >= wid:
wid = dot[0] + 1
i... |
class NullBotAPIException(Exception):
def __init__(
self,
error: int,
description: str = ""
):
self.error = error
self.description = description
def __repr__(self):
return f"<NullBotAPIException:code={self.error}, msg={self.description}>"
... | class Nullbotapiexception(Exception):
def __init__(self, error: int, description: str=''):
self.error = error
self.description = description
def __repr__(self):
return f'<NullBotAPIException:code={self.error}, msg={self.description}>'
def __str__(self):
return f'[{self.err... |
q_001 = '''
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX mds: <http://www.angelocarbone.com/ontologies/MoDelS#>
... | q_001 = '\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n PREFIX owl: <http://www.w3.org/2002/07/owl#>\n PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n PREFIX mds: <http://www.angelocarbone.com/ontologies/MoDelS#>... |
# 1492. The kth Factor of n
# User Accepted:4524
# User Tried:4554
# Total Accepted:4600
# Total Submissions:6166
# Difficulty:Medium
# Given two positive integers n and k.
# A factor of an integer n is defined as an integer i where n % i == 0.
# Consider a list of all factors of n sorted in ascending order,
# return ... | class Solution:
def kth_factor(self, n: int, k: int) -> int:
res = []
for i in range(1, n + 1):
if n % i == 0:
res.append(i)
if k > len(res):
return -1
return res[k - 1] |
# -*- coding: utf-8 -*-
day1 = int(input().split()[1])
hour1, minute1, second1 = map(int, input().split(" : "))
day2 = int(input().split()[1])
hour2, minute2, second2 = map(int, input().split(" : "))
totalSeconds1 = hour1 * 3600 + minute1 * 60 + second1
totalSeconds2 = hour2 * 3600 + minute2 * 60 + second2
days = d... | day1 = int(input().split()[1])
(hour1, minute1, second1) = map(int, input().split(' : '))
day2 = int(input().split()[1])
(hour2, minute2, second2) = map(int, input().split(' : '))
total_seconds1 = hour1 * 3600 + minute1 * 60 + second1
total_seconds2 = hour2 * 3600 + minute2 * 60 + second2
days = day2 - day1
if totalSec... |
# complex expressions
# from
def renderBanner(self):
if (
(self.platform.toUpperCase().indexOf("MAC") > -1)
and (self.browser.toUpperCase().indexOf("IE") > -1)
and self.wasInitialized()
and (self.resize > 0)
):
# do something
pass
# to
def renderBanner(self):
... | def render_banner(self):
if self.platform.toUpperCase().indexOf('MAC') > -1 and self.browser.toUpperCase().indexOf('IE') > -1 and self.wasInitialized() and (self.resize > 0):
pass
def render_banner(self):
is_mac_os = self.platform.toUpperCase().indexOf('MAC') > -1
is_ie = self.browser.toUpperCase()... |
def userInput(): # takes user input for number of sides and lenght of sides
year = int(input('Please enter the 4 digit year: '))
month = int(input('Please enter the month: '))
return year, month
def leapYear(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
... | def user_input():
year = int(input('Please enter the 4 digit year: '))
month = int(input('Please enter the month: '))
return (year, month)
def leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
ret... |
class ClimateMonitor:
def __init__(self, get_climate_data, low_to_high_threshold, high_to_low_threshold, low_is_normal=True):
self.low_is_normal = low_is_normal
# Assume that climate data is in its normal state at first
if self.low_is_normal:
self.climate_data_is_high = False
... | class Climatemonitor:
def __init__(self, get_climate_data, low_to_high_threshold, high_to_low_threshold, low_is_normal=True):
self.low_is_normal = low_is_normal
if self.low_is_normal:
self.climate_data_is_high = False
else:
self.climate_data_is_high = True
se... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2015 ARM Limited
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 o... | """
mbed CMSIS-DAP debugger
Copyright (c) 2015 ARM Limited
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 o... |
def ccw(A, B, C):
"""Tests whether the line formed by A, B, and C is ccw"""
return (B.x - A.x) * (C.y - A.y) < (B.y - A.y) * (C.x - A.x)
class PathFinder:
def __init__(self):
pass
'''
Implementation of the funnel algorithm for path finding
'''
def find_path_funnel(self, point_dict ... | def ccw(A, B, C):
"""Tests whether the line formed by A, B, and C is ccw"""
return (B.x - A.x) * (C.y - A.y) < (B.y - A.y) * (C.x - A.x)
class Pathfinder:
def __init__(self):
pass
'\n Implementation of the funnel algorithm for path finding\n '
def find_path_funnel(self, point_dict, ... |
def climbingLeaderboard(scores, alice):
unique_scores = list(reversed(sorted(set(scores))))
i = len(alice)-1
j = 0
ans = []
while i >= 0:
if j >= len(unique_scores) or unique_scores[j] <= alice[i]:
ans.append(j+1)
i -= 1
else:
j += 1
return ... | def climbing_leaderboard(scores, alice):
unique_scores = list(reversed(sorted(set(scores))))
i = len(alice) - 1
j = 0
ans = []
while i >= 0:
if j >= len(unique_scores) or unique_scores[j] <= alice[i]:
ans.append(j + 1)
i -= 1
else:
j += 1
retur... |
def numPointsInSpans(spans):
"""
ARC112B
>>> numPointsInSpans([(1, 3)])
3
>>> numPointsInSpans([(1, 3), (5, 7)])
6
>>> numPointsInSpans([(1, 3), (3, 5)])
5
>>> numPointsInSpans([(1, 3), (2, 5)])
5
"""
timeline = []
for start, end in spans:
assert start <= end
... | def num_points_in_spans(spans):
"""
ARC112B
>>> numPointsInSpans([(1, 3)])
3
>>> numPointsInSpans([(1, 3), (5, 7)])
6
>>> numPointsInSpans([(1, 3), (3, 5)])
5
>>> numPointsInSpans([(1, 3), (2, 5)])
5
"""
timeline = []
for (start, end) in spans:
assert start <=... |
# @dependency 001-main/002-createrepository.py
with repository.workcopy() as work:
review = Review(work, "alice", "200-json/008-batches")
review.addFile(first="200-json/008-batches/first.txt",
second="200-json/008-batches/second.txt",
third="200-json/008-batches/third.txt"... | with repository.workcopy() as work:
review = review(work, 'alice', '200-json/008-batches')
review.addFile(first='200-json/008-batches/first.txt', second='200-json/008-batches/second.txt', third='200-json/008-batches/third.txt')
review.commit('Reference commit', reference=True, first=['First', '=====', 'Init... |
# *
# * *
# * * *
# * * * *
for row in range(0,4):
for column in (0,row+1): # range is not there hence weired output
print(column,end=' ')
print("")
#end is very important, by default it is \n which is new line,
# it needs to remove for pattern programs and can be replace woth
#empty string or sp... | for row in range(0, 4):
for column in (0, row + 1):
print(column, end=' ')
print('')
for row in range(0, 4):
for column in range(0, row + 1):
print('*', end=' ')
print('') |
# material definition table: artdeco
#
artdeco = [\
[ # 0
[[0.0706087, 0.0212897, 0.0336154, 1.0]], # ambient
[[0.282435, 0.0851587, 0.134462, 1.0]], # diffuse
[[0.0, 0.0, 0.0, 1.0]], # emission
[[0.276305, 0.11431, 0.139857, 1.0]], # specular
[0.127273], # shini... | artdeco = [[[[0.0706087, 0.0212897, 0.0336154, 1.0]], [[0.282435, 0.0851587, 0.134462, 1.0]], [[0.0, 0.0, 0.0, 1.0]], [[0.276305, 0.11431, 0.139857, 1.0]], [0.127273], [1.0]], [[[0.174575, 0.0343131, 0.084684, 1.0]], [[0.685208, 0.134679, 0.332385, 1.0]], [[0.0, 0.0, 0.0, 1.0]], [[0.122449, 0.0500352, 0.0500352, 1.0]],... |
# 126. Word Ladder II
# ttungl@gmail.com
# Given two words (beginWord and endWord), and a dictionary's word list,
# find all shortest transformation sequence(s) from beginWord to endWord, such that:
# Only one letter can be changed at a time
# Each transformed word must exist in the word list. Note that beginWord is
... | class Solution(object):
def find_ladders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
def recurse(wordList, cur, d=collections.defaultdict(list)):
if not cu... |
th_prime_number_being_searched = 10001
arbitrary_size = 1000000
prime_numbers = [True] * arbitrary_size
prime_numbers[1] = False
counter_prime_numbers = 0
i = 1
continue_search = True
while (i < arbitrary_size - 1 and continue_search):
i += 1
if (prime_numbers[i]):
counter_prime_numbers += 1
if... | th_prime_number_being_searched = 10001
arbitrary_size = 1000000
prime_numbers = [True] * arbitrary_size
prime_numbers[1] = False
counter_prime_numbers = 0
i = 1
continue_search = True
while i < arbitrary_size - 1 and continue_search:
i += 1
if prime_numbers[i]:
counter_prime_numbers += 1
if coun... |
class EditorBrowsableState(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the browsable state of a property or method from within an editor.
enum EditorBrowsableState,values: Advanced (2),Always (0),Never (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__... | class Editorbrowsablestate(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies the browsable state of a property or method from within an editor.
enum EditorBrowsableState,values: Advanced (2),Always (0),Never (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x... |
def my_handler(event, context):
return 'new hello world'
| def my_handler(event, context):
return 'new hello world' |
# -*- coding: utf-8 -*-
__author__ = 'Andrew Stretton'
__email__ = 'andrew.stretton@sgc.ox.ac.uk'
__version__ = '0.1.0' | __author__ = 'Andrew Stretton'
__email__ = 'andrew.stretton@sgc.ox.ac.uk'
__version__ = '0.1.0' |
# built-int list1.sort() sorted(list1) can be used
def partition(arr, i, j, p):
left = i
right = j
while(left < right):
while(arr[left] < p):
left += 1
while(arr[right] > p):
right -= 1
if left < right:
arr[left], arr[right] = arr[righ... | def partition(arr, i, j, p):
left = i
right = j
while left < right:
while arr[left] < p:
left += 1
while arr[right] > p:
right -= 1
if left < right:
(arr[left], arr[right]) = (arr[right], arr[left])
return left
def _quick_sort(arr: 'list', i: ... |
a = "I am not tainted"
while b:
send_mail_jinja(a)
a = ContactMailForm() + get_query_string()
execute(a) | a = 'I am not tainted'
while b:
send_mail_jinja(a)
a = contact_mail_form() + get_query_string()
execute(a) |
"""
upload data related constants
"""
INSTRUCTIONS_1 = """You can upload your data using an ```Excel file (.xlsx)``` which should at
least have the following columns:
* **Date.** it is advised to use reversed order (**YYYY/MM/DD**).
* **Amount.** the values for **incomes** should be **positive** while **expenses*... | """
upload data related constants
"""
instructions_1 = 'You can upload your data using an ```Excel file (.xlsx)``` which should at\n least have the following columns:\n* **Date.** it is advised to use reversed order (**YYYY/MM/DD**).\n* **Amount.** the values for **incomes** should be **positive** while **expenses*... |
class Penalty:
def __init__(self, stats):
self.player_penalty = stats.playing_players
self.cpu_penalty = 1.05 ** (100 * stats.system_load) * 10 - 10
self.null_frame_penalty = 0
self.deficit_frame_penalty = 0
if stats.frames_nulled is not -1:
self.null_frame_penal... | class Penalty:
def __init__(self, stats):
self.player_penalty = stats.playing_players
self.cpu_penalty = 1.05 ** (100 * stats.system_load) * 10 - 10
self.null_frame_penalty = 0
self.deficit_frame_penalty = 0
if stats.frames_nulled is not -1:
self.null_frame_penal... |
class Solution:
def countArrangement(self, N: int) -> int:
def getValid(i, usedValues):
if i > N:
return 1
count = 0
for val in range(1, N+1):
if not usedValues[val] and (val%i==0 or i%val == 0):
usedValues[... | class Solution:
def count_arrangement(self, N: int) -> int:
def get_valid(i, usedValues):
if i > N:
return 1
count = 0
for val in range(1, N + 1):
if not usedValues[val] and (val % i == 0 or i % val == 0):
usedValues[v... |
class Solution:
def longestPalindrome(self, s: str) -> str:
dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)]
for i in range(len(s)):
dp[i][i] = 1
for i in range(len(s) - 1, -1, -1):
for j in range(i + 1, len(s)):
if(s... | class Solution:
def longest_palindrome(self, s: str) -> str:
dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)]
for i in range(len(s)):
dp[i][i] = 1
for i in range(len(s) - 1, -1, -1):
for j in range(i + 1, len(s)):
if s[i] == s[j]:
... |
class Node:
def __init__(self, key, val, left=None, right=None, n=0):
self.key = key
self.val = val
self.left = left
self.right = right
self.n = n
class BinarySearchTree:
def __init__(self):
self.root = None
def size(self, node):
if not node:
... | class Node:
def __init__(self, key, val, left=None, right=None, n=0):
self.key = key
self.val = val
self.left = left
self.right = right
self.n = n
class Binarysearchtree:
def __init__(self):
self.root = None
def size(self, node):
if not node:
... |
counter = {chr(val): 0 for val in range(97, 124)}
str1 = input("enter the string: ")
for char in str1:
if not char == " ":
counter[char] += 1
for char in str1:
if not char == " ":
print(char, counter[char], end=",") | counter = {chr(val): 0 for val in range(97, 124)}
str1 = input('enter the string: ')
for char in str1:
if not char == ' ':
counter[char] += 1
for char in str1:
if not char == ' ':
print(char, counter[char], end=',') |
# Question: https://projecteuler.net/problem=44
N = 10000
pentagon_nums = [i*(3*i-1) for i in range(1, N+1)]
pentagon_num_set = set(pentagon_nums)
best_diff = N * (3*N - 1)
for i, a in enumerate(pentagon_nums):
for b in pentagon_nums[i:]:
if b - a > best_diff:
break
if (b - a) in pe... | n = 10000
pentagon_nums = [i * (3 * i - 1) for i in range(1, N + 1)]
pentagon_num_set = set(pentagon_nums)
best_diff = N * (3 * N - 1)
for (i, a) in enumerate(pentagon_nums):
for b in pentagon_nums[i:]:
if b - a > best_diff:
break
if b - a in pentagon_num_set and b + a in pentagon_num_se... |
def findsd(n):
d = n - 1
s = 0
while d % 2 == 0:
d >>= 1
s += 1
return (s, d)
# Is composite?
def MillerRabin(n, a, s, d):
if pow(a, d, n) == 1:
return False #might be prime
for r in range(0, s, 1):
if pow(a, 2**r*d, n) == n-1:
return False #might be prime
return True #definitely not prime
# Is n ... | def findsd(n):
d = n - 1
s = 0
while d % 2 == 0:
d >>= 1
s += 1
return (s, d)
def miller_rabin(n, a, s, d):
if pow(a, d, n) == 1:
return False
for r in range(0, s, 1):
if pow(a, 2 ** r * d, n) == n - 1:
return False
return True
def is_prime(n):
... |
x=input()
count=0
m=x.split(".")
print(len(m))
| x = input()
count = 0
m = x.split('.')
print(len(m)) |
a = [int(i) for i in input().split()]
b = 0
for i in range(1, len(a) - 1):
if a[i - 1] < a[i] > a[i + 1]:
b += 1
print(b) | a = [int(i) for i in input().split()]
b = 0
for i in range(1, len(a) - 1):
if a[i - 1] < a[i] > a[i + 1]:
b += 1
print(b) |
session_numbers = []
lower_bound = 0.0
upper_bound = 0.0
while True: # Set the minimum and maximum values
try:
lower_bound = float(input("Please enter the minimum value allowed for this instance of the program: "))
upper_bound = float(input("Please enter the maximum value allowed: "))
if ... | session_numbers = []
lower_bound = 0.0
upper_bound = 0.0
while True:
try:
lower_bound = float(input('Please enter the minimum value allowed for this instance of the program: '))
upper_bound = float(input('Please enter the maximum value allowed: '))
if upper_bound < lower_bound:
p... |
@app.errorhandler(403) # Trying to access without permission
@login_required
def page_not_allowed(e):
return render_template('403.html'), 403
@app.errorhandler(404) # Trying to access page that does not exist.
@login_required
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500... | @app.errorhandler(403)
@login_required
def page_not_allowed(e):
return (render_template('403.html'), 403)
@app.errorhandler(404)
@login_required
def page_not_found(e):
return (render_template('404.html'), 404)
@app.errorhandler(500)
@login_required
def internal_server_error(e):
return (render_template('50... |
def numpaths(m , n):
if m == 1 or n == 1:
return 1
return numpaths(m -1 , n) + numpaths(m, n-1)
m = int(input("M: "))
n = int(input("N: "))
print(numpaths(m , n))
| def numpaths(m, n):
if m == 1 or n == 1:
return 1
return numpaths(m - 1, n) + numpaths(m, n - 1)
m = int(input('M: '))
n = int(input('N: '))
print(numpaths(m, n)) |
class Logger:
"""
Class that provides methods to log warnings and errors.
"""
@staticmethod
def warning(message):
print("[Warning] {}".format(message))
@staticmethod
def error(message):
print("[Error] {}".format(message))
| class Logger:
"""
Class that provides methods to log warnings and errors.
"""
@staticmethod
def warning(message):
print('[Warning] {}'.format(message))
@staticmethod
def error(message):
print('[Error] {}'.format(message)) |
# Given some integer, find the maximal number you can obtain by deleting exactly one digit of the given number.
#
# Example
#
# For n = 152, the output should be
# deleteDigit(n) = 52;
# For n = 1001, the output should be
# deleteDigit(n) = 101.
def deleteDigit(n):
num = 0
s = str(n)
for i in range(len(s... | def delete_digit(n):
num = 0
s = str(n)
for i in range(len(s)):
if int(s[:i] + s[i + 1:]) > num:
num = int(s[:i] + s[i + 1:])
return num
print(delete_digit(1001))
print(delete_digit(152)) |
print("Hello!, Welcome to Python")
print("*" * 40)
print("Please Enter your name ")
name = input()
print("Your name is, " + name)
# Hello!,Welcome to Python
# ****************************************
# Please Enter your name
# Leo
# Your name is, Leo
| print('Hello!, Welcome to Python')
print('*' * 40)
print('Please Enter your name ')
name = input()
print('Your name is, ' + name) |
#
# Copyright (C) 2019 The Android Open Source Project
#
# 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... | input0 = input('input0', 'TENSOR_FLOAT32', '{3}')
multipliers = input('multipliers', 'TENSOR_INT32', '{1}')
output0 = output('output0', 'TENSOR_FLOAT32', '{6}')
model = model().Operation('TILE', input0, multipliers).To(output0)
input_values = [1.2, -3.4, 5.6]
multiplier_values = [2]
output_values = input_values + input... |
def dataset(state, event):
del state, event # unused
return "the_fabulous_cifar10_dataset"
def register(mf):
mf.register_helpers({
"num_data": 24
})
mf.register_event("dataset", dataset, unique=True)
| def dataset(state, event):
del state, event
return 'the_fabulous_cifar10_dataset'
def register(mf):
mf.register_helpers({'num_data': 24})
mf.register_event('dataset', dataset, unique=True) |
# -*- coding: utf-8 -*-
# Scrapy settings for europython project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'europython'
SPIDER_MODULES = ['europython.spide... | bot_name = 'europython'
spider_modules = ['europython.spiders']
newspider_module = 'europython.spiders'
item_pipelines = {'europython.pipelines.EuropythonJsonExport': 100, 'europython.pipelines.EuropythonXmlExport': 200, 'europython.pipelines.EuropythonCSVExport': 300}
downloader_middlewares = {'scrapy.downloadermiddle... |
def find_substring(string, substring, count_start=0, count_stop=0):
""" find substring with unknown start/finish index
and return metadata of said string
:param string: full string (str)
:param substring: str
:param count_start: starting index for the search after substring
:param count_stop: ... | def find_substring(string, substring, count_start=0, count_stop=0):
""" find substring with unknown start/finish index
and return metadata of said string
:param string: full string (str)
:param substring: str
:param count_start: starting index for the search after substring
:param count_stop: ... |
name = "Kalob"
def myfunc(name):
# name = "New name"
return name
print(myfunc())
print(name)
| name = 'Kalob'
def myfunc(name):
return name
print(myfunc())
print(name) |
n = int(input())
a, b = [], []
for i in range(n):
a.append(input())
for i in range(n):
b.append(input())
count = 0
for i in range(n):
if a[i] == b[i]:
count += 1
print(count)
| n = int(input())
(a, b) = ([], [])
for i in range(n):
a.append(input())
for i in range(n):
b.append(input())
count = 0
for i in range(n):
if a[i] == b[i]:
count += 1
print(count) |
def binary_search(input_array, value):
"""Your code goes here."""
# mid = len(input_array)//2
# if input_array[mid] < value:
# return binary_search(input_array[mid+1:],value)
# elif input_array[mid] > value:
# return binary_search(input_array[:mid],value)
# elif input_array[mid] == ... | def binary_search(input_array, value):
"""Your code goes here."""
low = 0
high = len(input_array)
while low <= high:
mid = (low + high) // 2
if input_array[mid] < value:
low = mid + 1
elif input_array[mid] > value:
high = mid - 1
elif input_array[m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.