content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def fibo(n):
if n<3:
return n-1
else:
return fibo(n-1)+fibo(n-2)
| def fibo(n):
if n < 3:
return n - 1
else:
return fibo(n - 1) + fibo(n - 2) |
def doincre(delta, entity, cnt, RK, table, PK, tablesvc):
if cnt > 0:
item = {"PartitionKey": PK, "RowKey": RK, "value": int(entity.value) + delta, "etag": entity.etag}
try:
tablesvc.merge_entity(table, item)
except:
result = tablesvc.get_entity(table, PK, RK)
... | def doincre(delta, entity, cnt, RK, table, PK, tablesvc):
if cnt > 0:
item = {'PartitionKey': PK, 'RowKey': RK, 'value': int(entity.value) + delta, 'etag': entity.etag}
try:
tablesvc.merge_entity(table, item)
except:
result = tablesvc.get_entity(table, PK, RK)
... |
# Python - 3.4.3
test.describe('Example Tests')
InterlacedSpiralCipher = {'encode': encode, 'decode': decode }
example1A = 'Romani ite domum'
example1B = 'Rntodomiimuea m'
test.assert_equals(InterlacedSpiralCipher['encode'](example1A), example1B)
test.assert_equals(InterlacedSpiralCipher['decode'](example1B), exampl... | test.describe('Example Tests')
interlaced_spiral_cipher = {'encode': encode, 'decode': decode}
example1_a = 'Romani ite domum'
example1_b = 'Rntodomiimuea m'
test.assert_equals(InterlacedSpiralCipher['encode'](example1A), example1B)
test.assert_equals(InterlacedSpiralCipher['decode'](example1B), example1A)
example2_a ... |
RESOURCES = {
'accounts': {
'schema': {
'username': {
'type': 'string',
'required': True,
'unique': True
},
'password': {
'type': 'string',
'required': True
},
'roles':... | resources = {'accounts': {'schema': {'username': {'type': 'string', 'required': True, 'unique': True}, 'password': {'type': 'string', 'required': True}, 'roles': {'type': 'list', 'allowed': ['user', 'superuser'], 'required': True}, 'location': {'type': 'dict', 'schema': {'country': {'type': 'string'}, 'city': {'type': ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
t1_ptr = t1
t2_ptr = t2
t3_ptr = None
if t... | class Solution:
def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
t1_ptr = t1
t2_ptr = t2
t3_ptr = None
if t1_ptr and t2_ptr:
t3_ptr = tree_node(t1_ptr.val + t2_ptr.val)
t3_ptr.left = self.mergeTrees(t1_ptr.left, t2_ptr.left)
t3_ptr.r... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def isPalindrome(self, head):
if head == None:
return True
prev = None... | class Solution:
def is_palindrome(self, head):
if head == None:
return True
prev = None
slow = head
fast = head
while fast != None and fast.next != None:
prev = slow
slow = slow.next
fast = fast.next.next
mid = slow
... |
load("//third_party/py:python_configure.bzl", "python_configure")
load("@io_bazel_rules_python//python:pip.bzl", "pip_repositories")
load("@grpc_python_dependencies//:requirements.bzl", "pip_install")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
def grpc_python_deps():
# TODO(https... | load('//third_party/py:python_configure.bzl', 'python_configure')
load('@io_bazel_rules_python//python:pip.bzl', 'pip_repositories')
load('@grpc_python_dependencies//:requirements.bzl', 'pip_install')
load('@org_pubref_rules_protobuf//python:rules.bzl', 'py_proto_repositories')
def grpc_python_deps():
if hasattr(n... |
FONT_TITLE = 18
FONT_LEGEND = 16
FONT_LABEL = 14
FONT_STICK = 12
LEGEND_FRAMEALPHA = 0.5
########## h5py -- dod ############
wake_trim_min = None
period_length_sec = 30
h5_out_dir = './h5py/output'
ignore_class = None
kappa_weights='quadratic'
plot_hypnograms=True
plot_CMs=True
###### ablation #####... | font_title = 18
font_legend = 16
font_label = 14
font_stick = 12
legend_framealpha = 0.5
wake_trim_min = None
period_length_sec = 30
h5_out_dir = './h5py/output'
ignore_class = None
kappa_weights = 'quadratic'
plot_hypnograms = True
plot_c_ms = True
ablation_out_dir = './ablation/output' |
class CrabNavy:
def __init__(self, positions):
self.positions = positions
@classmethod
def from_str(cls, positions_str):
positions = [int(c) for c in positions_str.split(",")]
return cls(positions)
def calculate_consumption(self, alignment):
total = 0
for posi... | class Crabnavy:
def __init__(self, positions):
self.positions = positions
@classmethod
def from_str(cls, positions_str):
positions = [int(c) for c in positions_str.split(',')]
return cls(positions)
def calculate_consumption(self, alignment):
total = 0
for posit... |
# Exercise One
hash = "#"
for i in range(0, 7):
print(hash)
hash = hash + "#"
# Exercise two
for i in range(1, 101):
if i % 3 == 0:
if i % 5 == 0:
print("FizzBuzz")
else:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
# Exerci... | hash = '#'
for i in range(0, 7):
print(hash)
hash = hash + '#'
for i in range(1, 101):
if i % 3 == 0:
if i % 5 == 0:
print('FizzBuzz')
else:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
size = 8
chess_board = ''
for i in range(0,... |
'''https://adoptopenjdk.net/upstream.html
'''
load("//java:common/structs/KnownOpenJdkRepository.bzl", _KnownOpenJdkRepository = "KnownOpenJdkRepository")
def adoptopenjdk_upstream_repositories():
return _KNOWN_OPENJDK_REPOSITORIES
def _Repo(**kwargs):
kwargs['provider'] = "adoptopenjdk_upstream"
return ... | """https://adoptopenjdk.net/upstream.html
"""
load('//java:common/structs/KnownOpenJdkRepository.bzl', _KnownOpenJdkRepository='KnownOpenJdkRepository')
def adoptopenjdk_upstream_repositories():
return _KNOWN_OPENJDK_REPOSITORIES
def __repo(**kwargs):
kwargs['provider'] = 'adoptopenjdk_upstream'
return __... |
def map_wiimote_to_key(wiimote_index, wiimote_button, key):
# Check the global wiimote object's button state and set the global
# keyboard object's corresponding key.
if wiimote[wiimote_index].buttons.button_down(wiimote_button):
keyboard.setKeyDown(key)
else:
keyboard.setKeyUp(key)
def map_wiimote_to_vJoy(wii... | def map_wiimote_to_key(wiimote_index, wiimote_button, key):
if wiimote[wiimote_index].buttons.button_down(wiimote_button):
keyboard.setKeyDown(key)
else:
keyboard.setKeyUp(key)
def map_wiimote_to_v_joy(wiimote_index, wiimote_button, key):
if wiimote[wiimote_index].buttons.button_down(wiimot... |
# OpenWeatherMap API Key
weather_api_key = "reset"
# Google API Key
g_key = "reset"
| weather_api_key = 'reset'
g_key = 'reset' |
def merge_sorted_list(arr1, arr2):
# m = len(arr1), n = len(arr1)
# since we know arr1 is always greater or equal to (m+n)
# we compare arr2[i] with arr1[j] element and check if it
# should be placed there
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr2[j] == arr1[i] or arr2[... | def merge_sorted_list(arr1, arr2):
(i, j) = (0, 0)
while i < len(arr1) and j < len(arr2):
if arr2[j] == arr1[i] or arr2[j] <= arr1[i + 1]:
arr1.insert(i + 1, arr2[j])
arr1.pop()
i += 2
j += 1
elif arr2[j] > arr1[i]:
if arr1[i + 1] == 0:... |
data = open(0).readlines()
e = [i == "#" for i in data[0].strip()]
b = [line.strip() for line in data[2:]]
d = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,0),(0,1),(1,-1),(1,0),(1,1))
def neighbors(i, j):
for k, (di, dj) in enumerate(d):
yield 256 >> k, i+di, j+dj
def lookup(_s, i, j, bi, bj, flip=False):
if i ==... | data = open(0).readlines()
e = [i == '#' for i in data[0].strip()]
b = [line.strip() for line in data[2:]]
d = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1))
def neighbors(i, j):
for (k, (di, dj)) in enumerate(d):
yield (256 >> k, i + di, j + dj)
def lookup(_s, i, j, bi, bj... |
distance_success_response = {'destination_addresses': ['Brighton, UK'],
'origin_addresses': ['London, UK'], 'rows': [{'elements': [
{'distance': {'text': '64.6 mi', 'value': 103964},
... | distance_success_response = {'destination_addresses': ['Brighton, UK'], 'origin_addresses': ['London, UK'], 'rows': [{'elements': [{'distance': {'text': '64.6 mi', 'value': 103964}, 'duration': {'text': '1 hour 54 mins', 'value': 6854}, 'status': 'OK'}]}], 'status': 'OK'} |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getmerge(self,l1,l2):
head = ListNode(0)
tail = head
while l1 is not None and l2 is not None:
if l1.val > l2.val:
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getmerge(self, l1, l2):
head = list_node(0)
tail = head
while l1 is not None and l2 is not None:
if l1.val > l2.val:
(l1, l2) = (l2, l1... |
string = 'Monty Python'
print(string[0:4])
print(string[6:7])
print(string[6:20])
print(string[8:])
data = 'From robin.smorenburg@linkit.nl Sat Jan'
position = data.find('@')
print(position)
space_position = data.find(' ', position)
print(space_position)
host = data[position+1:space_position]
print(host)
| string = 'Monty Python'
print(string[0:4])
print(string[6:7])
print(string[6:20])
print(string[8:])
data = 'From robin.smorenburg@linkit.nl Sat Jan'
position = data.find('@')
print(position)
space_position = data.find(' ', position)
print(space_position)
host = data[position + 1:space_position]
print(host) |
def baz():
tmp = "!" # try to extract this assignment, either with or without this comment
baz()
def bar(self):
pass | def baz():
tmp = '!'
baz()
def bar(self):
pass |
# Find duplicates in an array in O(N) Time and O(1) space.
# The elements in the array can be only Between 1<=x<=len(array)
# Asked in Amazon,D-E-Shaw, Flipkart and many more
# Difficulty -> Medium (for O(N) time and O(1) space)
# Approaches:
# Naive Solution: Loop through all the values checking for multi... | def find_duplicates(arr):
size = len(arr)
for i in range(0, size):
idx = abs(arr[i]) - 1
if arr[idx] < 0:
print(abs(arr[i]))
arr[idx] = -arr[idx]
arr1 = [2, 1, 2, 1]
arr2 = [1, 2, 3, 1, 3, 6, 6]
find_duplicates(arr1)
print()
find_duplicates(arr2) |
'''
8-2. Favorite Book: Write a function called favorite_book() that accepts one parameter, title.
The function should print a message, such as One of my favorite books is Alice in Wonderland.
Call the function, making sure to include a book title as an argument in the function call.
'''
def favorite_book(title):
... | """
8-2. Favorite Book: Write a function called favorite_book() that accepts one parameter, title.
The function should print a message, such as One of my favorite books is Alice in Wonderland.
Call the function, making sure to include a book title as an argument in the function call.
"""
def favorite_book(title):
... |
yieldlyDB = {'FMBXOFAQCSAD4UWU4Q7IX5AV4FRV6AKURJQYGXLW3CTPTQ7XBX6MALMSPY' : 'Yieldly - YLDY-YLDY/ALGO',
'VUY44SYOFFJE3ZIDEMA6PT34J3FAZUAE6VVTOTUJ5LZ343V6WZ3ZJQTCD4' : 'Yieldly - YLDY-OPUL',
'U3RJ4NNSASBOIY25KAVVFV6CFDOS22L7YLZBENMIVVVFEWT5WE5GHXH5VQ' : 'Yieldly - GEMS-GEMS',
... | yieldly_db = {'FMBXOFAQCSAD4UWU4Q7IX5AV4FRV6AKURJQYGXLW3CTPTQ7XBX6MALMSPY': 'Yieldly - YLDY-YLDY/ALGO', 'VUY44SYOFFJE3ZIDEMA6PT34J3FAZUAE6VVTOTUJ5LZ343V6WZ3ZJQTCD4': 'Yieldly - YLDY-OPUL', 'U3RJ4NNSASBOIY25KAVVFV6CFDOS22L7YLZBENMIVVVFEWT5WE5GHXH5VQ': 'Yieldly - GEMS-GEMS', 'BXLXRYBOM7ZNYSCRLWG6THNMO6HASTIRMJGSNJANZFS6E... |
print ( True or False ) == True
print ( True or True ) == True
print ( False or False ) == False
print ( True and False ) == False
print ( True and True ) == True
print ( False and False ) == False
print ( not True ) == False
print ( not False ) == True
print ( not True or False ) == ( (not True) or False )
print ( ... | print(True or False) == True
print(True or True) == True
print(False or False) == False
print(True and False) == False
print(True and True) == True
print(False and False) == False
print(not True) == False
print(not False) == True
print(not True or False) == (not True or False)
print(not False or False) == (not False or... |
#
# PySNMP MIB module Wellfleet-PGM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-PGM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
points_str = input("Enter the lead in points: ")
points_remaining_int = int(points_str)
lead_calculation_float= float(points_remaining_int - 3)
has_ball_str = input("Does the lead team have the ball (Yes or No): ")
if has_ball_str == "Yes":
lead_calculation_float=lead_calculation_float + 0.5
else:
lead_calcula... | points_str = input('Enter the lead in points: ')
points_remaining_int = int(points_str)
lead_calculation_float = float(points_remaining_int - 3)
has_ball_str = input('Does the lead team have the ball (Yes or No): ')
if has_ball_str == 'Yes':
lead_calculation_float = lead_calculation_float + 0.5
else:
lead_calcu... |
alien_color = 'green'
if alien_color == 'green':
print("You get 5 points.")
else:
print("\nYou get 10 points.")
alien_color = 'yellow'
if alien_color == 'green':
print("You get 5 points.")
else:
print("\nYou get 10 points.") | alien_color = 'green'
if alien_color == 'green':
print('You get 5 points.')
else:
print('\nYou get 10 points.')
alien_color = 'yellow'
if alien_color == 'green':
print('You get 5 points.')
else:
print('\nYou get 10 points.') |
DATABASE_CONFIG = {
'uri': 'postgres://username:password@host/database'
}
JSREPORT_CONFIG = {
'uri': 'changeme',
'username': 'changeme',
'password': 'changeme',
'template': 'changeme'
}
ZIP_CONFIG = {
'name': 'flask_batch_download.zip'
}
| database_config = {'uri': 'postgres://username:password@host/database'}
jsreport_config = {'uri': 'changeme', 'username': 'changeme', 'password': 'changeme', 'template': 'changeme'}
zip_config = {'name': 'flask_batch_download.zip'} |
class Prop:
MAX_HOUSE = 4
def __init__(self, name, price, lien, house_price, class_count, klass, **taxes):
self.name = name
self.price = price
self.lien = lien
self.house_price = house_price
self.taxes = taxes
self.owner = None
self.n_house = 0
se... | class Prop:
max_house = 4
def __init__(self, name, price, lien, house_price, class_count, klass, **taxes):
self.name = name
self.price = price
self.lien = lien
self.house_price = house_price
self.taxes = taxes
self.owner = None
self.n_house = 0
se... |
#create file myaperture.dat needed for source optimization
f = open("myaperture.dat",'w')
f.write(" 50.0 -0.002 0.002 -0.002 0.002")
f.close()
print("File written to disk: myaperture.dat")
| f = open('myaperture.dat', 'w')
f.write(' 50.0 -0.002 0.002 -0.002 0.002')
f.close()
print('File written to disk: myaperture.dat') |
# -*- encoding:utf-8 -*-
# index rule:
# 3 ------6------- 2
#
# 7 ------ ------- 5
#
# 0 ------4------- 1
# Stores the triangle values
raw_trigs = [
[],
[(0,7,4)],
[(4,5,1)],
[(0,5,1),(0,7,5)],
[(5,6,2)],
[(0,7,4), (4,7,5), (7,6,5), (5,6,2)],
[(1,4,6), (1,6,2)],
[(1,0,7), (1,7,6), (1,6,2)],
[(7,3,6)],
[(0... | raw_trigs = [[], [(0, 7, 4)], [(4, 5, 1)], [(0, 5, 1), (0, 7, 5)], [(5, 6, 2)], [(0, 7, 4), (4, 7, 5), (7, 6, 5), (5, 6, 2)], [(1, 4, 6), (1, 6, 2)], [(1, 0, 7), (1, 7, 6), (1, 6, 2)], [(7, 3, 6)], [(0, 3, 4), (4, 3, 6)], [(1, 4, 5), (4, 7, 5), (5, 7, 6), (7, 3, 6)], [(0, 5, 1), (0, 6, 5), (0, 3, 6)], [(7, 3, 5), (5, 3... |
make = "Ford"
model = "Everest"
def start_engine():
print (f'{make} {model} engine started')
| make = 'Ford'
model = 'Everest'
def start_engine():
print(f'{make} {model} engine started') |
class Resource():
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(Resource(path))
def append(self, resource):
resource.number = len(self)
super().append(r... | class Resource:
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(resource(path))
def append(self, resource):
resource.number = len(self)
super().append(resou... |
# Python - 3.6.0
Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for name, age in zip(names, ages):
person = Person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}')
| Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for (name, age) in zip(names, ages):
person = person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}') |
#Floating loop
first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list)
| first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"win": "game.ipynb",
"lose": "game.ipynb"}
modules = ["game.py"]
doc_url = "https://thecharlieblake.github.io/solitairenet/"
git_url = "https://github.com/thecharlieblake/solitairenet/tree/master/... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'win': 'game.ipynb', 'lose': 'game.ipynb'}
modules = ['game.py']
doc_url = 'https://thecharlieblake.github.io/solitairenet/'
git_url = 'https://github.com/thecharlieblake/solitairenet/tree/master/'
def custom_doc_links(name):
return None |
def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [ItemWeight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for e... | def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [item_weight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for e... |
# O(nlogn) time | O(n) space
def mergeSort(array):
if len(array) <= 1:
return array
subarray = array[:]
mergeSortHelper(array, 0, len(array)-1)
return array
def mergeSortHelper(array, l, r):
if l == r:
return
m = (l + r) // 2
mergeSortHelper(array, l, m)
mergeSortHelper... | def merge_sort(array):
if len(array) <= 1:
return array
subarray = array[:]
merge_sort_helper(array, 0, len(array) - 1)
return array
def merge_sort_helper(array, l, r):
if l == r:
return
m = (l + r) // 2
merge_sort_helper(array, l, m)
merge_sort_helper(array, m + 1, r)
... |
# This is the custom function interface.
# You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
... | class Customfunction:
def f(self, x, y):
return x + y
class Solution:
def find_solution(self, customfunction, z: int):
ret = []
i = 1
while customfunction.f(i, 1) <= z:
j = 1
while True:
if customfunction.f(i, j) == z:
... |
class UndergroundSystem:
def __init__(self):
self.count = defaultdict(int)
self.time = defaultdict(int)
self.traveling = dict()
def checkIn(self, id: int, stationName: str, t: int) -> None:
self.traveling[id] = (stationName, t)
def checkOut(self, id: int, stationNa... | class Undergroundsystem:
def __init__(self):
self.count = defaultdict(int)
self.time = defaultdict(int)
self.traveling = dict()
def check_in(self, id: int, stationName: str, t: int) -> None:
self.traveling[id] = (stationName, t)
def check_out(self, id: int, stationName: st... |
def test_clear_images(client, seeder, app, utils):
user_id, admin_unit_id = seeder.setup_base()
image_id = seeder.upsert_default_image()
url = utils.get_image_url_for_id(image_id)
utils.get_ok(url)
runner = app.test_cli_runner()
result = runner.invoke(args=["cache", "clear-images"])
assert... | def test_clear_images(client, seeder, app, utils):
(user_id, admin_unit_id) = seeder.setup_base()
image_id = seeder.upsert_default_image()
url = utils.get_image_url_for_id(image_id)
utils.get_ok(url)
runner = app.test_cli_runner()
result = runner.invoke(args=['cache', 'clear-images'])
assert... |
def binary_slow(n):
assert n>=0
bits = []
while n:
bits.append('01'[n&1])
n >>= 1
bits.reverse()
return ''.join(bits) or '0'
| def binary_slow(n):
assert n >= 0
bits = []
while n:
bits.append('01'[n & 1])
n >>= 1
bits.reverse()
return ''.join(bits) or '0' |
# Containers for txid sequences start with this string.
CONTAINER_PREFIX = 'txids'
# Transaction ID sequence nodes start with this string.
COUNTER_NODE_PREFIX = 'tx'
# ZooKeeper stores the sequence counter as a signed 32-bit integer.
MAX_SEQUENCE_COUNTER = 2 ** 31 - 1
# The name of the node used for manually setting... | container_prefix = 'txids'
counter_node_prefix = 'tx'
max_sequence_counter = 2 ** 31 - 1
offset_node = 'txid_offset' |
# Solution 1 - recursion
# O(log(n)) time / O(log(n)) space
def binarySearch1(array, target):
return binarySearchHelper1(array, target, 0, len(array) - 1)
def binarySearchHelper1(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potentialMatch = array[middle... | def binary_search1(array, target):
return binary_search_helper1(array, target, 0, len(array) - 1)
def binary_search_helper1(array, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
potential_match = array[middle]
if target == potentialMatch:
return middle... |
# Uebungsblatt 2
# Uebung 1
i = 28
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 2
i = 28.0
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
# Uebung 3
s = "Hello"
s2 = s
print(s, id(s), s2, id(s2))
s += " World"
print(s, id(s), s2, id(s2))
# Uebung 4
m = ['a', 'b', 'd', 'e', 'f']
... | i = 28
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
i = 28.0
f = 28.0
print(i, id(i), type(i))
print(f, id(f), type(f))
s = 'Hello'
s2 = s
print(s, id(s), s2, id(s2))
s += ' World'
print(s, id(s), s2, id(s2))
m = ['a', 'b', 'd', 'e', 'f']
print(m, id(m))
m[0] = 'A'
print(m, id(m))
m2 = m
print(m, id(m), m... |
n, m = map(int, input().split())
f = list(int(i) for i in input().split())
f.sort()
# formula -> f[i+n-1] - f[i]
ans = 10**9
for i in range(m-n+1):
ans = min(ans, f[i+n-1] - f[i])
print(ans) | (n, m) = map(int, input().split())
f = list((int(i) for i in input().split()))
f.sort()
ans = 10 ** 9
for i in range(m - n + 1):
ans = min(ans, f[i + n - 1] - f[i])
print(ans) |
ENDPOINT_PATH = 'foobar'
BOOTSTRAP_SERVERS = 'localhost:9092'
TOPIC_RAW_REQUESTS = 'test.raw_requests'
TOPIC_PARSED_DATA = 'test.parsed_data'
USERNAME = None
PASSWORD = None
SASL_MECHANISM = None
SECURITY_PROTOCOL = 'PLAINTEXT'
# Use these when trying with FVH servers
# SASL_MECHANISM = "PLAIN"
# SECURITY_PROTOCOL = "... | endpoint_path = 'foobar'
bootstrap_servers = 'localhost:9092'
topic_raw_requests = 'test.raw_requests'
topic_parsed_data = 'test.parsed_data'
username = None
password = None
sasl_mechanism = None
security_protocol = 'PLAINTEXT' |
# input
print('What is my favourite food?')
input_guess = input("Guess? ")
# response
while input_guess != 'electricity':
print("Not even close.")
input_guess = input("Guess? ")
print("You guessed it! Buzzzz")
| print('What is my favourite food?')
input_guess = input('Guess? ')
while input_guess != 'electricity':
print('Not even close.')
input_guess = input('Guess? ')
print('You guessed it! Buzzzz') |
# Use enumerate() and other skills to return the count of the number of items in
# the list whose value equals its index.
def count_match_index(numbers):
return len([number for index, number in enumerate(numbers) if index == number])
result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10])
print(result)
| def count_match_index(numbers):
return len([number for (index, number) in enumerate(numbers) if index == number])
result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10])
print(result) |
__title__ = 'elasticsearch-cli'
__version__ = '0.0.1'
__author__ = 'nevercaution'
__license__ = 'Apache v2'
| __title__ = 'elasticsearch-cli'
__version__ = '0.0.1'
__author__ = 'nevercaution'
__license__ = 'Apache v2' |
## Largest 5 digit number in a series
## 7 kyu
## https://www.codewars.com/kata/51675d17e0c1bed195000001
def solution(digits):
biggest = 0
for index in range(len(digits) - 4):
if int(digits[index:index+5]) > biggest:
biggest = int(digits[index:index+5])
return biggest | def solution(digits):
biggest = 0
for index in range(len(digits) - 4):
if int(digits[index:index + 5]) > biggest:
biggest = int(digits[index:index + 5])
return biggest |
{
"targets": [
{
"target_name": "game",
"sources": [ "game.cpp" ]
}
]
} | {'targets': [{'target_name': 'game', 'sources': ['game.cpp']}]} |
class Stack:
def __init__(self,max_size=4):
self.max_size = max_size
self.stk = [None]*max_size
self.last_pos = -1
def pop(self):
if self.last_pos < 0:
raise IndexError()
temp = self.stk[self.last_pos]
self.stk[self.last_pos]=None
if self.last... | class Stack:
def __init__(self, max_size=4):
self.max_size = max_size
self.stk = [None] * max_size
self.last_pos = -1
def pop(self):
if self.last_pos < 0:
raise index_error()
temp = self.stk[self.last_pos]
self.stk[self.last_pos] = None
if se... |
DEFAULT_SERVER_HOST = "localhost"
DEFAULT_SERVER_PORT = 11211
DEFAULT_POOL_MINSIZE = 2
DEFAULT_POOL_MAXSIZE = 5
DEFAULT_TIMEOUT = 1
DEFAULT_MAX_KEY_LENGTH = 250
DEFAULT_MAX_VALUE_LENGTH = 1024 * 1024 # 1 megabyte
STORED = b"STORED\r\n"
NOT_STORED = b"NOT_STORED\r\n"
EXISTS = b"EXISTS\r\n"
NOT_FOUND = b"NOT_FOUND\r\n"... | default_server_host = 'localhost'
default_server_port = 11211
default_pool_minsize = 2
default_pool_maxsize = 5
default_timeout = 1
default_max_key_length = 250
default_max_value_length = 1024 * 1024
stored = b'STORED\r\n'
not_stored = b'NOT_STORED\r\n'
exists = b'EXISTS\r\n'
not_found = b'NOT_FOUND\r\n'
deleted = b'DE... |
def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return int(copy[int((size-1) / 2)])
else:
return (int(copy[int((size) / 2)-1]) + int(copy[int(size / 2)])) / 2
| def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return int(copy[int((size - 1) / 2)])
else:
return (int(copy[int(size / 2) - 1]) + int(copy[int(size / 2)])) / 2 |
# Python program to calculate C(n, k)
# Returns value of Binomial Coefficient
# C(n, k)
def binomialCoefficient(n, k):
# since C(n, k) = C(n, n - k)
if(k > n - k):
k = n - k
# initialize result
res = 1
# Calculate value of
# [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]... | def binomial_coefficient(n, k):
if k > n - k:
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
(n, k) = map(int, input().split())
res = binomial_coefficient(n, k)
print('Value of C(% d, % d) is % d' % (n, k, res))
'\nTEST CASES\n\nInput =\n5... |
#does array have duplicate entries
a=[1,2,3,4,5,1,7]
i=1
j=1
for num in a:
for ab in range(len(a)):
if num==a[i]:
print("duplicate found! ",num,"is = a[",i,"]")
else:
print(num,"is not = a[",i,"]" )
if i>4:
break
else:
i=i+1
i=0
... | a = [1, 2, 3, 4, 5, 1, 7]
i = 1
j = 1
for num in a:
for ab in range(len(a)):
if num == a[i]:
print('duplicate found! ', num, 'is = a[', i, ']')
else:
print(num, 'is not = a[', i, ']')
if i > 4:
break
else:
i = i + 1
i = 0 |
{
'name': 'To-Do Kanban board',
'description': 'Kanban board to manage to-do tasks.',
'author': 'Daniel Reis',
'depends': ['todo_ui'],
'data': ['views/todo_view.xml'],
}
| {'name': 'To-Do Kanban board', 'description': 'Kanban board to manage to-do tasks.', 'author': 'Daniel Reis', 'depends': ['todo_ui'], 'data': ['views/todo_view.xml']} |
# play sound
file = "HappyBirthday.mp3"
print('playing sound using native player')
os.system("afplay " + file) | file = 'HappyBirthday.mp3'
print('playing sound using native player')
os.system('afplay ' + file) |
v = 18
_v = 56
def f():
pass
def _f():
pass
class MyClass(object):
pass
class _MyClass(object):
pass
| v = 18
_v = 56
def f():
pass
def _f():
pass
class Myclass(object):
pass
class _Myclass(object):
pass |
def solve_single_lin(opt_x_s):
'''
solve one opt_x[s]
'''
opt_x_s.solve(solver='MOSEK', verbose = True)
return opt_x_s | def solve_single_lin(opt_x_s):
"""
solve one opt_x[s]
"""
opt_x_s.solve(solver='MOSEK', verbose=True)
return opt_x_s |
pkgname = "xsetroot"
pkgver = "1.1.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = [
"xbitmaps", "libxmu-devel", "libxrender-devel",
"libxfixes-devel", "libxcursor-devel"
]
pkgdesc = "X root window parameter setting utility"
maintainer = "q66 <q66@chimera-linux.org>"
lice... | pkgname = 'xsetroot'
pkgver = '1.1.2'
pkgrel = 0
build_style = 'gnu_configure'
hostmakedepends = ['pkgconf']
makedepends = ['xbitmaps', 'libxmu-devel', 'libxrender-devel', 'libxfixes-devel', 'libxcursor-devel']
pkgdesc = 'X root window parameter setting utility'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT... |
class Item:
def __init__(self, block_id, count, damage, data):
self.block_id = block_id
self.count = count
self.damage = damage
self.data = data
def __str__(self):
return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage)
| class Item:
def __init__(self, block_id, count, damage, data):
self.block_id = block_id
self.count = count
self.damage = damage
self.data = data
def __str__(self):
return 'block: {:3d}, count: {:2d}, damage: {}'.format(self.block_id, self.count, self.damage) |
BAZEL_VERSION_SHA256S = {
"0.14.1": "7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376",
"0.15.0": "7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b",
"0.15.2": "13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241",
"0.16.1": "17ab70344645359fd4178002f367885e9... | bazel_version_sha256_s = {'0.14.1': '7b14e4fc76bf85c4abf805833e99f560f124a3b96d56e0712c693e94e19d1376', '0.15.0': '7f6748b48a7ea6bdf00b0e1967909ce2181ebe6f377638aa454a7d09a0e3ea7b', '0.15.2': '13eae0f09565cf17fc1c9ce1053b9eac14c11e726a2215a79ebaf5bdbf435241', '0.16.1': '17ab70344645359fd4178002f367885e9019ae7507c9c1ade... |
def censor(text, word):
bigstring = text.split()
print (bigstring)
words = ""
" ".join(bigstring)
return bigstring
print (censor("hello hi hey", "hi")) | def censor(text, word):
bigstring = text.split()
print(bigstring)
words = ''
' '.join(bigstring)
return bigstring
print(censor('hello hi hey', 'hi')) |
config = {
'api_root': 'https://library.cca.edu/api/v1',
'client_id': 'abcedfg-123445678',
'client_secret': 'abcedfg-123445678',
}
| config = {'api_root': 'https://library.cca.edu/api/v1', 'client_id': 'abcedfg-123445678', 'client_secret': 'abcedfg-123445678'} |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... | response.logo = a(b('Placement portal'), _class='brand', _id='web2py-logo')
response.title = request.application.replace('_', ' ').title()
response.subtitle = ''
response.meta.author = 'Your Name <you@example.com>'
response.meta.description = 'a cool new app'
response.meta.keywords = 'web2py, python, framework'
respons... |
# game model list base class for all object collections in game
class GameModelList():
def __init__(
self,
game,
game_models=[],
collidable=False,
block_color=None
):
self.game = game
self.game_models = game_models
self.collidable = collidable
self.block_color = block_color
for model in self.g... | class Gamemodellist:
def __init__(self, game, game_models=[], collidable=False, block_color=None):
self.game = game
self.game_models = game_models
self.collidable = collidable
self.block_color = block_color
for model in self.game_models:
model.set_collidable(self... |
# Author: Ian Burke
# Module: Emerging Technologies
# Date: September, 2017
# Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html
# create a function to reverse a string
def reverse():
word = input("Enter a string: ") #user enters a string and store it in word
word = word[... | def reverse():
word = input('Enter a string: ')
word = word[::-1]
print(word)
reverse() |
# GENERATED VERSION FILE
# TIME: Tue Oct 26 14:07:11 2021
__version__ = '0.3.0+dc45206'
short_version = '0.3.0'
| __version__ = '0.3.0+dc45206'
short_version = '0.3.0' |
class Cuenta:
def __init__(self, nombre, numero, saldo):
self.nombre = nombre
self.numero= numero
self.saldo = saldo
def depositar(self, a):
self.saldo=self.saldo+a
return self.saldo
def retirar(self, a):
self.saldo=self.saldo-a
return self... | class Cuenta:
def __init__(self, nombre, numero, saldo):
self.nombre = nombre
self.numero = numero
self.saldo = saldo
def depositar(self, a):
self.saldo = self.saldo + a
return self.saldo
def retirar(self, a):
self.saldo = self.saldo - a
return self... |
temp=n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print(f"natural numbers in series {sum1}+{n}")
print(f"The sum of first {temp} natural numbers is: {sum1}") | temp = n = int(input('Enter a number: '))
sum1 = 0
while n > 0:
sum1 = sum1 + n
n = n - 1
print(f'natural numbers in series {sum1}+{n}')
print(f'The sum of first {temp} natural numbers is: {sum1}') |
def get_max_profit(stock_prices):
# initialize the lowest_price to the first stock price
lowest_price = stock_prices[0]
# initialize the max_profit to the
# difference between the first and the second stock price
max_profit = stock_prices[1] - stock_prices[0]
# loop through every price in stock... | def get_max_profit(stock_prices):
lowest_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
for index in range(1, len(stock_prices)):
if stock_prices[index] - lowest_price > max_profit:
max_profit = stock_prices[index] - lowest_price
if stock_prices[index] < l... |
class EventMongoRepository:
database_address = "localhost"
def __init__(self):
self.client = "Opens a connection with mongo"
def add_event(self, event):
pass
def remove_event(self, event):
pass
def update_event(self, event):
pass
| class Eventmongorepository:
database_address = 'localhost'
def __init__(self):
self.client = 'Opens a connection with mongo'
def add_event(self, event):
pass
def remove_event(self, event):
pass
def update_event(self, event):
pass |
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(list, object)) | class Superlist(list):
def __len__(self):
return 1000
super_list1 = super_list()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(list, object)) |
class Finding:
def __init__(self, filename, secret_type, secret_value, line_number=None, link=None):
self._filename = filename
self._secret_type = secret_type
self._secret_value = secret_value
self._line_number = line_number
self._link = link
@property
def filename(s... | class Finding:
def __init__(self, filename, secret_type, secret_value, line_number=None, link=None):
self._filename = filename
self._secret_type = secret_type
self._secret_value = secret_value
self._line_number = line_number
self._link = link
@property
def filename(... |
PATH_ROOT = "/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/"
def read_srx_list(file):
srxs = set()
with open(file, "r") as fh:
next(fh)
for line in fh:
if line.startswith("SRX"):
srxs.add(line.rstrip())
return list(srxs)
def read_srr_file(srr_file):
srr_d... | path_root = '/sra/sra-instant/reads/ByExp/sra/SRX/SRX{}/{}/'
def read_srx_list(file):
srxs = set()
with open(file, 'r') as fh:
next(fh)
for line in fh:
if line.startswith('SRX'):
srxs.add(line.rstrip())
return list(srxs)
def read_srr_file(srr_file):
srr_data... |
styles = {
"alignment": {
"color": "black",
"linestyle": "-",
"linewidth": 1.0,
"alpha": 0.2,
"label": "raw alignment"
},
"despiked": {
"color": "blue",
"linestyle": "-",
"linewidth": 1.4,
"alpha": 1.0,
"label": "de-spiked align... | styles = {'alignment': {'color': 'black', 'linestyle': '-', 'linewidth': 1.0, 'alpha': 0.2, 'label': 'raw alignment'}, 'despiked': {'color': 'blue', 'linestyle': '-', 'linewidth': 1.4, 'alpha': 1.0, 'label': 'de-spiked alignment'}, 'line1': {'color': 'black', 'linestyle': '-', 'linewidth': 1.2, 'alpha': 0.3, 'label': '... |
'''
'''
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return length
left = 0
cur = 0
while cur < length - 1:
sums = 1
while cur < length - 1 and nums[cur] == nums[cur + 1]:
... | """
"""
class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
length = len(nums)
if length <= 2:
return length
left = 0
cur = 0
while cur < length - 1:
sums = 1
while cur < length - 1 and nums[cur] == nums[cur + 1]:
... |
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
def make_change(money, coins):
if money < 0:
return 0
elif money == 0:
return 1
elif not coins:
return 0
else:
return make_change(money - coins[-1], coins) + make_change(money, coi... | def make_change(money, coins):
if money < 0:
return 0
elif money == 0:
return 1
elif not coins:
return 0
else:
return make_change(money - coins[-1], coins) + make_change(money, coins[:-1])
coins = [1, 2, 3]
money = 4
make_change(money, coins) |
_notes_dict_array_hz = {
'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0],
'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],
'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8],... | _notes_dict_array_hz = {'C': [8.176, 16.352, 32.703, 65.406, 130.81, 261.63, 523.25, 1046.5, 2093.0, 4186.0, 8372.0], 'C#': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'Df': [8.662, 17.324, 34.648, 69.296, 138.59, 277.18, 554.37, 1108.7, 2217.5, 4434.9, 8869.8], 'D': [9.177,... |
def funct(l1, l2):
s = len(set(l1+l2))
return s
for t in range(int(input())):
n = int(input())
l = input().split()
a = {}
for i in l:
p = i[1:]
if p in a:
a[p].append(i[0])
else:
a[p] = [i[0]]
b = list(a.keys())
s = 0
for i in range(l... | def funct(l1, l2):
s = len(set(l1 + l2))
return s
for t in range(int(input())):
n = int(input())
l = input().split()
a = {}
for i in l:
p = i[1:]
if p in a:
a[p].append(i[0])
else:
a[p] = [i[0]]
b = list(a.keys())
s = 0
for i in range(l... |
class ConfigSVM:
# matrix_size = 1727
# matrix_size = 1219
# matrix_size = 1027
matrix_size = 798
# matrix_size = 3 | class Configsvm:
matrix_size = 798 |
print('\033[1;93m-=-\033[m' * 15)
print(f'\033[1;31m{"LARGEST AND SMALLEST ON THE LIST":^45}\033[m', )
print('\033[1;93m-=-\033[m' * 15)
numbers = list()
largest = 0
big_position = list()
small_position = list()
numbers.append(int(input(f'Type a number for the position {0}: ')))
smallest = numbers[0]
for i in range(... | print('\x1b[1;93m-=-\x1b[m' * 15)
print(f"\x1b[1;31m{'LARGEST AND SMALLEST ON THE LIST':^45}\x1b[m")
print('\x1b[1;93m-=-\x1b[m' * 15)
numbers = list()
largest = 0
big_position = list()
small_position = list()
numbers.append(int(input(f'Type a number for the position {0}: ')))
smallest = numbers[0]
for i in range(1, 5)... |
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... | {'includes': ['../build/common.gypi'], 'conditions': [['OS=="ios"', {'targets': [{'target_name': 'rtc_api_objc', 'type': 'static_library', 'dependencies': ['<(webrtc_root)/base/base.gyp:rtc_base_objc'], 'sources': ['objc/RTCIceServer+Private.h', 'objc/RTCIceServer.h', 'objc/RTCIceServer.mm'], 'xcode_settings': {'CLANG_... |
getObject = {
'primaryRouter': {
'datacenter': {'id': 1234, 'longName': 'TestDC'},
'fullyQualifiedDomainName': 'fcr01.TestDC'
},
'id': 1234,
'vlanNumber': 4444,
'firewallInterfaces': None
}
| get_object = {'primaryRouter': {'datacenter': {'id': 1234, 'longName': 'TestDC'}, 'fullyQualifiedDomainName': 'fcr01.TestDC'}, 'id': 1234, 'vlanNumber': 4444, 'firewallInterfaces': None} |
class Car:
def wheels(self):
print('Car.wheels')
return 4
class Bike(Car):
def wheels(self):
return 2
class Truck(Car):
def wheels(self):
print('Truck.wheels: start')
super().wheels()
print('Truck.wheels: end')
return 6
car = Bike()
print(car.wh... | class Car:
def wheels(self):
print('Car.wheels')
return 4
class Bike(Car):
def wheels(self):
return 2
class Truck(Car):
def wheels(self):
print('Truck.wheels: start')
super().wheels()
print('Truck.wheels: end')
return 6
car = bike()
print(car.whee... |
class NodeEndpoint:
protocol = ''
host = ''
port = ''
@staticmethod
def from_parameters(protocol, host, port):
endpoint = NodeEndpoint()
endpoint.protocol = protocol
endpoint.host = host
endpoint.port = port
return endpoint
@staticmethod
def from_jso... | class Nodeendpoint:
protocol = ''
host = ''
port = ''
@staticmethod
def from_parameters(protocol, host, port):
endpoint = node_endpoint()
endpoint.protocol = protocol
endpoint.host = host
endpoint.port = port
return endpoint
@staticmethod
def from_js... |
class SchemaConstructionException(Exception):
def __init__(self, claz):
self.cls = claz
class SchemaParseException(Exception):
def __init__(self, errors):
self.errors = errors
class ParseError(object):
def __init__(self, path, inner):
self.path = path
self.inner = inner... | class Schemaconstructionexception(Exception):
def __init__(self, claz):
self.cls = claz
class Schemaparseexception(Exception):
def __init__(self, errors):
self.errors = errors
class Parseerror(object):
def __init__(self, path, inner):
self.path = path
self.inner = inner
... |
class Solution:
def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
modulo = 10 ** 9 + 7
# build tuples of (efficiency, speed)
candidates = zip(efficiency, speed)
# sort the candidates by their efficiencies
candidates = sorted(candidates... | class Solution:
def max_performance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
modulo = 10 ** 9 + 7
candidates = zip(efficiency, speed)
candidates = sorted(candidates, key=lambda t: t[0], reverse=True)
speed_heap = []
(speed_sum, perf) = (0, 0)
... |
# Minimum Size Subarray Sum
class Solution:
def minSubArrayLen(self, target, nums):
length = len(nums)
Invalid = length + 1
left, right = 0, 0
added = nums[left]
if added >= target:
return 1
ans = Invalid
while True:
if left + 1 <= r... | class Solution:
def min_sub_array_len(self, target, nums):
length = len(nums)
invalid = length + 1
(left, right) = (0, 0)
added = nums[left]
if added >= target:
return 1
ans = Invalid
while True:
if left + 1 <= right and added - nums[l... |
# http://codingbat.com/prob/p165321
def near_ten(num):
return (num % 10 <= 2) or (num % 10 >= 8)
| def near_ten(num):
return num % 10 <= 2 or num % 10 >= 8 |
class WorkerNode(object):
def __init__(self, ip, k8s_name, k8s_is_ready):
self.ip = ip
self.k8s_name = k8s_name
self.k8s_is_ready = k8s_is_ready
self.k8s_pod_num = 0
self.vc = None
self.to_turn_on = False
self.to_turn_off = False
class Pod(object):
d... | class Workernode(object):
def __init__(self, ip, k8s_name, k8s_is_ready):
self.ip = ip
self.k8s_name = k8s_name
self.k8s_is_ready = k8s_is_ready
self.k8s_pod_num = 0
self.vc = None
self.to_turn_on = False
self.to_turn_off = False
class Pod(object):
def ... |
class Solution:
def countAndSay(self, n):
numb = 1
w = 1
while n > 1:
w = Solution.CountSay(numb)
numb = w
n -= 1
return str(w)
def CountSay(no):
tnumb = str(no)
x = tnumb[0]
count = 1
strr = ""
... | class Solution:
def count_and_say(self, n):
numb = 1
w = 1
while n > 1:
w = Solution.CountSay(numb)
numb = w
n -= 1
return str(w)
def count_say(no):
tnumb = str(no)
x = tnumb[0]
count = 1
strr = ''
for ... |
# domoticz configuration
DOMOTICZ_SERVER_IP = "xxx.xxx.x.xxx"
DOMOTICZ_SERVER_PORT = "xxxx"
DOMOTICZ_USERNAME = ""
DOMOTICZ_PASSWORD = ""
# sensor dictionary to add own sensors
# if you don't want to use the raw voltage option, just write -1 in the VOLTAGE_IDX value field
sensors = { 1: {"MAC": "xx:xx:xx:xx:xx... | domoticz_server_ip = 'xxx.xxx.x.xxx'
domoticz_server_port = 'xxxx'
domoticz_username = ''
domoticz_password = ''
sensors = {1: {'MAC': 'xx:xx:xx:xx:xx:xx', 'TH_IDX': 1, 'VOLTAGE_IDX': -1, 'UPDATED': False}, 2: {'MAC': 'xx:xx:xx:xx:xx:xx', 'TH_IDX': 2, 'VOLTAGE_IDX': -1, 'UPDATED': False}, 3: {'MAC': 'xx:xx:xx:xx:xx:xx'... |
del_items(0x8009E2A0)
SetType(0x8009E2A0, "char StrDate[12]")
del_items(0x8009E2AC)
SetType(0x8009E2AC, "char StrTime[9]")
del_items(0x8009E2B8)
SetType(0x8009E2B8, "char *Words[117]")
del_items(0x8009E48C)
SetType(0x8009E48C, "struct MONTH_DAYS MonDays[12]")
| del_items(2148131488)
set_type(2148131488, 'char StrDate[12]')
del_items(2148131500)
set_type(2148131500, 'char StrTime[9]')
del_items(2148131512)
set_type(2148131512, 'char *Words[117]')
del_items(2148131980)
set_type(2148131980, 'struct MONTH_DAYS MonDays[12]') |
class FunctionLink:
def __init__(self, linked_function):
self.__linked_function = linked_function
@property
def linked_function(self):
return self.__linked_function
| class Functionlink:
def __init__(self, linked_function):
self.__linked_function = linked_function
@property
def linked_function(self):
return self.__linked_function |
workers = 2
timeout = 120
reload = True
limit_request_field_size = 0
limit_request_line = 0
| workers = 2
timeout = 120
reload = True
limit_request_field_size = 0
limit_request_line = 0 |
GITHUB_TOKENS = ['GH_TOKEN']
GITHUB_URL_FILE = 'rawGitUrls.txt'
GITHUB_API_URL = 'https://api.github.com/search/code?q='
GITHUB_API_COMMIT_URL = 'https://api.github.com/repos/'
GITHUB_SEARCH_PARAMS = '&sort=indexed&o=desc'
GITHUB_BASE_URL = 'https://github.com'
GITHUB_MAX_RETRY = 10
XDISCORD_WEBHOOKURL = 'https://disco... | github_tokens = ['GH_TOKEN']
github_url_file = 'rawGitUrls.txt'
github_api_url = 'https://api.github.com/search/code?q='
github_api_commit_url = 'https://api.github.com/repos/'
github_search_params = '&sort=indexed&o=desc'
github_base_url = 'https://github.com'
github_max_retry = 10
xdiscord_webhookurl = 'https://disco... |
class QuickSort(object):
"In Place Quick Sort"
def __init__(self, arr):
self.arr = arr
def sort(self, left_i, right_i):
if right_i - left_i < 1:
return
pivot_i = self.partition(left_i, right_i)
self.sort(left_i, pivot_i - 1)
self.sort(pivot_i + 1, right_... | class Quicksort(object):
"""In Place Quick Sort"""
def __init__(self, arr):
self.arr = arr
def sort(self, left_i, right_i):
if right_i - left_i < 1:
return
pivot_i = self.partition(left_i, right_i)
self.sort(left_i, pivot_i - 1)
self.sort(pivot_i + 1, ri... |
a = []
for i in range(100):
a.append(i)
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)") | a = []
for i in range(100):
a.append(i)
if (n := len(a)) > 10:
print(f'List is too long ({n} elements, expected <= 10)') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.