content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Range Sum of BST
'''
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
... | """
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Constraints:
The nu... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
if not self.next:
return str(self.val)
return f'{self.val}->{self.next}'
# TODO: This one took a while... come back and take another look
cl... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
if not self.next:
return str(self.val)
return f'{self.val}->{self.next}'
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l... |
def func(self):
self.info(self.rid, "get store")
users = []
for row in self.datastore.all():
email = row.data.get('email', None)
if not email:
continue
if not row.data['email'] in users:
users.append(email)
return users | def func(self):
self.info(self.rid, 'get store')
users = []
for row in self.datastore.all():
email = row.data.get('email', None)
if not email:
continue
if not row.data['email'] in users:
users.append(email)
return users |
def main() -> None:
s = input()
print("0" + s[:3])
if __name__ == "__main__":
main()
| def main() -> None:
s = input()
print('0' + s[:3])
if __name__ == '__main__':
main() |
#Author:
#Dilpreet Singh Chawla
#Indian Institute of Information Technology Kalyani.
#Newton's Method to find square root of a positive number
def square_root(n):
if n<0:
raise RuntimeError("Please enter a positive number!")
else:
root=n/2 #initial_guess
for k in range(20):
... | def square_root(n):
if n < 0:
raise runtime_error('Please enter a positive number!')
else:
root = n / 2
for k in range(20):
root = 1 / 2 * (root + n / root)
return root
n = float(input('Enter a number: '))
sqrt = square_root(n)
print('The square root of the number is ... |
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A, ncnt = sorted(A), sum([1 for a in A if a < 0])
cnt1, cnt2 = min(K, ncnt), K - ncnt if K > ncnt else 0
for i in range(cnt1): A[i] = -A[i]
return sum(A) - min(A) * 2 * (cnt2 % 2) if cnt2 else sum(A)
| class Solution:
def largest_sum_after_k_negations(self, A: List[int], K: int) -> int:
(a, ncnt) = (sorted(A), sum([1 for a in A if a < 0]))
(cnt1, cnt2) = (min(K, ncnt), K - ncnt if K > ncnt else 0)
for i in range(cnt1):
A[i] = -A[i]
return sum(A) - min(A) * 2 * (cnt2 % ... |
#unexpected results, can use try statement to make trial statement
try:
print(a) #have not defined a, will return exception
except:
print("a is not defined!")
#these are specific errors
try:
print(a) # a still not defined
except NameError:
print("a is still not defined")
except:
print("something else went wrong... | try:
print(a)
except:
print('a is not defined!')
try:
print(a)
except NameError:
print('a is still not defined')
except:
print('something else went wrong')
print(a) |
MHP = open('numeros.txt','w')
for linha in range(1,101):
arquivo.write('%d\n'%linha)
arquivo.close()
| mhp = open('numeros.txt', 'w')
for linha in range(1, 101):
arquivo.write('%d\n' % linha)
arquivo.close() |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
invalid_open = []
invalid_close = []
for i,char in enumerate(s):
if char == '(':
invalid_open.append(i)
elif char == ')':
if not invalid_open:
... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
invalid_open = []
invalid_close = []
for (i, char) in enumerate(s):
if char == '(':
invalid_open.append(i)
elif char == ')':
if not invalid_open:
in... |
class BBAWriter:
def __init__(self, f):
self.f = f
def pre(self, s):
print("pre {}".format(s), file=self.f)
def post(self, s):
print("post {}".format(s), file=self.f)
def push(self, s):
print("push {}".format(s), file=self.f)
def offset32(self):
print("offset32", file=self.f)
def ref(self, r, comment=""... | class Bbawriter:
def __init__(self, f):
self.f = f
def pre(self, s):
print('pre {}'.format(s), file=self.f)
def post(self, s):
print('post {}'.format(s), file=self.f)
def push(self, s):
print('push {}'.format(s), file=self.f)
def offset32(self):
print('of... |
del_items(0x80079E14)
SetType(0x80079E14, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80079E30)
SetType(0x80079E30, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80079E3C)
SetType(0x80079E3C, "void Remove96__Fv()")
del_items(0x80079E74)
SetType(0x80079E74, "void AppMain()")
del_items(0x80079F14)
SetType... | del_items(2147982868)
set_type(2147982868, 'int GetTpY__FUs(unsigned short tpage)')
del_items(2147982896)
set_type(2147982896, 'int GetTpX__FUs(unsigned short tpage)')
del_items(2147982908)
set_type(2147982908, 'void Remove96__Fv()')
del_items(2147982964)
set_type(2147982964, 'void AppMain()')
del_items(2147983124)
set... |
x = 10
y = 'Hi'
z = 'Hello'
print(y)
# breakpoint() is introduced in Python 3.7
breakpoint()
print(z)
# Execution Steps
# Default:
# $python3.7 python_breakpoint_examples.py
# Disable Breakpoint:
# $PYTHONBREAKPOINT=0 python3.7 python_breakpoint_examples.py
# Using Other Debugger (for example web-pdb):
# $PYTHONB... | x = 10
y = 'Hi'
z = 'Hello'
print(y)
breakpoint()
print(z) |
# Test if list is Palindrome
# Using list slicing
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# Reversing the list
reverse = test_list[::-1]
# checking if palindrome
res = test_list == reverse
# printing result
print("Is list Palindrome... | test_list = [1, 4, 5, 4, 1]
print('The original list is : ' + str(test_list))
reverse = test_list[::-1]
res = test_list == reverse
print('Is list Palindrome : ' + str(res)) |
def _file_name(filePathName):
if "/" in filePathName:
return filePathName.rsplit("/", -1)[1]
else:
return filePathName
def _base_name(fileName):
return fileName.split(".")[0]
def qt_cc_library(name, src, hdr, uis = [], res = [], normal_hdrs = [], deps = None, **kwargs):
srcs = src
... | def _file_name(filePathName):
if '/' in filePathName:
return filePathName.rsplit('/', -1)[1]
else:
return filePathName
def _base_name(fileName):
return fileName.split('.')[0]
def qt_cc_library(name, src, hdr, uis=[], res=[], normal_hdrs=[], deps=None, **kwargs):
srcs = src
for h_it... |
def winning_move(board, piece):
# Check horizontal locations for win
# every possibility horizontal 4 in the board
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece\
and board[r][c+2] == piece and b... | def winning_move(board, piece):
for c in range(COLUMN_COUNT - 3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c + 1] == piece and (board[r][c + 2] == piece) and (board[r][c + 3] == piece):
return True
for c in range(COLUMN_COUNT):
for r in range(RO... |
count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
count = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count += 1
| count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
count = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count += 1 |
#
# Virtual Block Device (VBD) Xen API Configuration
#
# Note: There is a non-API field here called "image" which is a backwards
# compat addition so you can mount to old images.
#
VDI = ''
device = 'sda1'
mode = 'RW'
driver = 'paravirtualised'
image = 'file:/root/gentoo.amd64.img'
| vdi = ''
device = 'sda1'
mode = 'RW'
driver = 'paravirtualised'
image = 'file:/root/gentoo.amd64.img' |
# Use this playground to experiment with list methods, using Test Run
list_method = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
list_method.append(5, )
print(list_method)
list_method.extend([5, 5, 5, 5])
print(list_method)
list_method.insert(3, 2)
print(list_method)
list_method.remove(2)
print(list_method)
print(list_method.count... | list_method = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
list_method.append(5)
print(list_method)
list_method.extend([5, 5, 5, 5])
print(list_method)
list_method.insert(3, 2)
print(list_method)
list_method.remove(2)
print(list_method)
print(list_method.count(5))
print(list_method.pop(10))
print(list_method)
list_method.reverse()
p... |
min3 = 100
max3 = 999
mul = 0
mx = 0 # max palindrome
for i in range(max3, min3-1, -1):
for j in range(i, min3-1, -1):
mul = i*j
rev = int(str(mul)[::-1]) # reversed
if (mul <= mx):
break
if (mul == rev):
mx = mul
print(mx)
| min3 = 100
max3 = 999
mul = 0
mx = 0
for i in range(max3, min3 - 1, -1):
for j in range(i, min3 - 1, -1):
mul = i * j
rev = int(str(mul)[::-1])
if mul <= mx:
break
if mul == rev:
mx = mul
print(mx) |
###
# Created on Apr 13,2020
# @author: Jordon Malcolm
# jordonm1@umbc.edu
###
class Events:
def __init__(self, arg1=" ", arg2=" ", arg3=" ", arg4=" ", arg5=" ", arg6=" ", arg7=0):
self.subject = arg1
self.courseNum = arg2
self.version = arg3
self.section = arg4
self.instruct... | class Events:
def __init__(self, arg1=' ', arg2=' ', arg3=' ', arg4=' ', arg5=' ', arg6=' ', arg7=0):
self.subject = arg1
self.courseNum = arg2
self.version = arg3
self.section = arg4
self.instructor = arg5
self.time = arg6
self.capacity = arg7
def get_s... |
countries = input().split(", ")
capitals = input().split(", ")
my_dict = {country: capital for country, capital in tuple(zip(countries, capitals))}
[print (f"{country} -> {capital}") for country, capital in my_dict.items()] | countries = input().split(', ')
capitals = input().split(', ')
my_dict = {country: capital for (country, capital) in tuple(zip(countries, capitals))}
[print(f'{country} -> {capital}') for (country, capital) in my_dict.items()] |
class Interface:
QUERY_SCHEDULE = "0"
QUERY_TEAM_STATS = "1"
# add new query type above this line
RESP_SCHEDULE = "0"
RESP_TEAM_STATS = "1"
# add new response type above this line
| class Interface:
query_schedule = '0'
query_team_stats = '1'
resp_schedule = '0'
resp_team_stats = '1' |
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
remaining = numBottles%numExchange
numBottles = numBottles // numExchange
ans += numBottles
numBottles += remaining
... | class Solution:
def num_water_bottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
remaining = numBottles % numExchange
num_bottles = numBottles // numExchange
ans += numBottles
num_bottles += rema... |
def get_matrix():
return [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
| def get_matrix():
return [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
'''
This is Day 2 of 100 Days of Python
Today, we are going to build a tip calculator
The knowledge that we need are basic school mathematics and the usage of the different operators in Python
In python the different operators used are +, - , *, /, // , **, and the % operators.
Each has its own function, which we shal... | """
This is Day 2 of 100 Days of Python
Today, we are going to build a tip calculator
The knowledge that we need are basic school mathematics and the usage of the different operators in Python
In python the different operators used are +, - , *, /, // , **, and the % operators.
Each has its own function, which we shal... |
GENERAL_EXCEPTION = "internal_server_error"
LOGIN_EXCEPTION = "login_error"
REGISTER_EXCEPTION = "register_error"
NOT_AUTHORIZED = "not_authorized"
QUERY_PARAM_EXCEPTION = "query_param_error"
NOT_FOUND = "resource_not_found"
BAD_REQUEST_EXCEPTION = "bad_request_error"
| general_exception = 'internal_server_error'
login_exception = 'login_error'
register_exception = 'register_error'
not_authorized = 'not_authorized'
query_param_exception = 'query_param_error'
not_found = 'resource_not_found'
bad_request_exception = 'bad_request_error' |
lista = [2, 4, 2, 2, 3, 3, 1]
def soma_elementos(lista):
soma = 0
for element in lista:
soma += element
return soma
print(soma_elementos(lista)) | lista = [2, 4, 2, 2, 3, 3, 1]
def soma_elementos(lista):
soma = 0
for element in lista:
soma += element
return soma
print(soma_elementos(lista)) |
def get_strob_numbers(num_digits):
if not num_digits:
return [""]
elif num_digits == 1:
return ["0", "1", "8"]
smaller_strob_numbers = get_strob_numbers(num_digits - 2)
strob_numbers = list()
for x in smaller_strob_numbers:
strob_numbers.extend([
"1" + x + "1",
... | def get_strob_numbers(num_digits):
if not num_digits:
return ['']
elif num_digits == 1:
return ['0', '1', '8']
smaller_strob_numbers = get_strob_numbers(num_digits - 2)
strob_numbers = list()
for x in smaller_strob_numbers:
strob_numbers.extend(['1' + x + '1', '6' + x + '9', ... |
PAIRSAM_FORMAT_VERSION = '1.0.0'
PAIRSAM_SEP = '\t'
PAIRSAM_SEP_ESCAPE = r'\t'
SAM_SEP = '\031'
SAM_SEP_ESCAPE = r'\031'
INTER_SAM_SEP = '\031NEXT_SAM\031'
COL_READID = 0
COL_C1 = 1
COL_P1 = 2
COL_C2 = 3
COL_P2 = 4
COL_S1 = 5
COL_S2 = 6
COL_PTYPE = 7
COL_SAM1 = 8
COL_SAM2 = 9
COLUMNS = ['readID', 'chrom1', 'pos1', '... | pairsam_format_version = '1.0.0'
pairsam_sep = '\t'
pairsam_sep_escape = '\\t'
sam_sep = '\x19'
sam_sep_escape = '\\031'
inter_sam_sep = '\x19NEXT_SAM\x19'
col_readid = 0
col_c1 = 1
col_p1 = 2
col_c2 = 3
col_p2 = 4
col_s1 = 5
col_s2 = 6
col_ptype = 7
col_sam1 = 8
col_sam2 = 9
columns = ['readID', 'chrom1', 'pos1', 'chr... |
def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
convert_integer = int(number_string)
return convert_integer
answer = sum("1... | def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
convert_integer = int(number_string)
return convert_integer
answer = sum('1', '2'... |
def Bin(L,start,end,x,k):
if end > start:
mid = (start+end)//2
if (x==L[mid]):
j = mid
i = mid
while(i>-1 and L[i]==x):
i-=1
while(j<k and L[j]==x):
j+=1
return(i,j)
elif x<L[mid]:
... | def bin(L, start, end, x, k):
if end > start:
mid = (start + end) // 2
if x == L[mid]:
j = mid
i = mid
while i > -1 and L[i] == x:
i -= 1
while j < k and L[j] == x:
j += 1
return (i, j)
elif x < L[mid... |
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
degree = 0
freqs = {}
for num in nums:
if num not in freqs:
freqs[num] = 0
freqs[num] += 1
for key, value in freqs.items():
... | class Solution:
def find_shortest_sub_array(self, nums: List[int]) -> int:
if not nums:
return 0
degree = 0
freqs = {}
for num in nums:
if num not in freqs:
freqs[num] = 0
freqs[num] += 1
for (key, value) in freqs.items():
... |
'''Utilities for generating graphs
This provides a set of utilities that will allow us to geenrate a
girected graph. This assumes that configuration files for all the
modules are present in the ``config/modules/`` folder. The files
should be JSON files with the folliwing specifications:
.. code-block:: JSON
{
... | """Utilities for generating graphs
This provides a set of utilities that will allow us to geenrate a
girected graph. This assumes that configuration files for all the
modules are present in the ``config/modules/`` folder. The files
should be JSON files with the folliwing specifications:
.. code-block:: JSON
{
... |
expected_regimen_to_treatment = [
{
"id": "1",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "1"
},
{
"id": "2",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "2"
},
{
"id": "3",
"regimen_ontology_term_... | expected_regimen_to_treatment = [{'id': '1', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '1'}, {'id': '2', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '2'}, {'id': '3', 'regimen_ontology_term_id': '1', 'treatment_ontology_term_id': '3'}, {'id': '4', 'regimen_ontology_term_id': '1',... |
def test_java_version(host):
ansible_vars = host.ansible.get_variables()
java_version = ansible_vars.get('java__version')
java_output = host.run('java -version')
assert str(java_version) + '.' in java_output.stderr
| def test_java_version(host):
ansible_vars = host.ansible.get_variables()
java_version = ansible_vars.get('java__version')
java_output = host.run('java -version')
assert str(java_version) + '.' in java_output.stderr |
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
class SecretStoreMock:
args = None
id_to_document = dict()
def __init__(self, secret_store_url, keeper_url, account):
self.args = (secret_store_url, keeper_url, account)
def set_secret_store_url(self, url):
... | class Secretstoremock:
args = None
id_to_document = dict()
def __init__(self, secret_store_url, keeper_url, account):
self.args = (secret_store_url, keeper_url, account)
def set_secret_store_url(self, url):
return
def encrypt_document(self, document_id, document, threshold=0):
... |
m1 = 0; m2 = 0; n = int(input())
while n:
n -= 1
a, b = map(int, input().split())
m1 = max(m1, a*b)
m = int(input())
while m:
m -= 1
a, b = map(int, input().split())
m2 = max(m2, a*b)
if m1 == m2:
print("Tie")
elif m1 > m2:
print("Casper")
else:
print("Natalie") | m1 = 0
m2 = 0
n = int(input())
while n:
n -= 1
(a, b) = map(int, input().split())
m1 = max(m1, a * b)
m = int(input())
while m:
m -= 1
(a, b) = map(int, input().split())
m2 = max(m2, a * b)
if m1 == m2:
print('Tie')
elif m1 > m2:
print('Casper')
else:
print('Natalie') |
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def getIntersectionNode(self,headA, headB):
if headA is None or headB is None:
return None
pa = headA # 2 pointers
pb = headB
LinkedLi... | class Listnode:
def __init__(self, val, next=None):
self.val = val
self.next = next
class Linkedlist:
def __init__(self):
self.head = None
def get_intersection_node(self, headA, headB):
if headA is None or headB is None:
return None
pa = headA
... |
class Credential:
'''
class that generates new instance for credentials
'''
credential_list=[]
def __init__(self,account_name,password):
'''
__init__ method that helps us define properties for our objects.
Args:
account_name: New credential account name.
... | class Credential:
"""
class that generates new instance for credentials
"""
credential_list = []
def __init__(self, account_name, password):
"""
__init__ method that helps us define properties for our objects.
Args:
account_name: New credential account name.
... |
times = input("How many times do I have to tell you? ")
times = int(times)
for time in range(times):
print("CLEAN UP YOUR ROOM")
| times = input('How many times do I have to tell you? ')
times = int(times)
for time in range(times):
print('CLEAN UP YOUR ROOM') |
touched_files = danger.git.modified_files + danger.git.created_files
has_source_changes = any(map(lambda f: f.startswith("danger_python"), touched_files))
has_changelog_entry = "CHANGELOG.md" in touched_files
is_trivial = "#trivial" in danger.github.pr.title
if has_source_changes and not has_changelog_entry and not is... | touched_files = danger.git.modified_files + danger.git.created_files
has_source_changes = any(map(lambda f: f.startswith('danger_python'), touched_files))
has_changelog_entry = 'CHANGELOG.md' in touched_files
is_trivial = '#trivial' in danger.github.pr.title
if has_source_changes and (not has_changelog_entry) and (not ... |
def facerecognizer():
i01.opencv.capture()
i01.opencv.addFilter("PyramidDown")
i01.opencv.setDisplayFilter("FaceRecognizer")
fr=i01.opencv.addFilter("FaceRecognizer")
fr.train()# it takes some time to train and be able to recognize face
#if((lastName+"-inmoovWebKit" not in inmoovWebKit.getSessionNames())):
#... | def facerecognizer():
i01.opencv.capture()
i01.opencv.addFilter('PyramidDown')
i01.opencv.setDisplayFilter('FaceRecognizer')
fr = i01.opencv.addFilter('FaceRecognizer')
fr.train() |
class ARGA ( object ) :
def __init__( self ) :
pass
def __len__( self ) :
return 0
def build_primitive_dispatch( self ) :
return ''
class ARG( ARGA ) :
def __init__( self, *pattern ) :
self.pattern = pattern
CORE.register_pattern( self )
def __repr__( self ) :
return 'ARG[ ' ... | class Arga(object):
def __init__(self):
pass
def __len__(self):
return 0
def build_primitive_dispatch(self):
return ''
class Arg(ARGA):
def __init__(self, *pattern):
self.pattern = pattern
CORE.register_pattern(self)
def __repr__(self):
return 'A... |
def setup ():
strokeWeight(140)
size (500, 500)
smooth ()
noLoop ()
noStroke()
def draw ():
background (50)
fill (94, 206, 40, 250)
ellipse (100, 100, 150, 150)
fill (94, 206, 40, 150)
ellipse (100, 200, 150, 150)
fill (94, 206, 40, 100)
ellipse (100, 300... | def setup():
stroke_weight(140)
size(500, 500)
smooth()
no_loop()
no_stroke()
def draw():
background(50)
fill(94, 206, 40, 250)
ellipse(100, 100, 150, 150)
fill(94, 206, 40, 150)
ellipse(100, 200, 150, 150)
fill(94, 206, 40, 100)
ellipse(100, 300, 150, 150)
fill(94, ... |
{
'targets': [
{
'target_name': 'serialport',
'sources': [
'src/serialport.cpp',
'src/serialport_unix.cpp',
],
'conditions': [
['OS=="win"',
{
'sources': [
"src/serialport_win.cpp",
'src/win/disphelper.c',
... | {'targets': [{'target_name': 'serialport', 'sources': ['src/serialport.cpp', 'src/serialport_unix.cpp'], 'conditions': [['OS=="win"', {'sources': ['src/serialport_win.cpp', 'src/win/disphelper.c', 'src/win/enumser.cpp']}], ['OS!="win"', {'sources': ['src/serialport_unix.cpp']}]]}]} |
# Create a file phonebook.det that stores the details in following format:
# Name Phone
# Jiving 8666000
# Kriti 1010101
# Obtain the details from the user.
fileObj = open("phonebook.det","w")
fileObj.write("Name \t")
fileObj.write("Phone \t")
fileObj.write("\n")
while True :
name = input("Ente... | file_obj = open('phonebook.det', 'w')
fileObj.write('Name \t')
fileObj.write('Phone \t')
fileObj.write('\n')
while True:
name = input('Enter Name: ')
fileObj.write(name + '\t')
phone = input('Enter Phone: ')
fileObj.write(phone + '\t')
fileObj.write('\n')
user = input("Enter 'Q' or 'q' to quit (... |
def readBinaryDataSet(metaFilePath,binaryFilePath):
dfmeta = pd.read_csv(metaFilePath)
binaryFile = open(binaryFilePath,'rb')
# print binaryFile.seek()
FileVars={}
for ind in dfmeta.index:
binaryFile.seek(dfmeta.loc[ind,'startBytePosition'])
typenum = None
if dfmeta.loc[ind,'internalVartype'] == 'int':
... | def read_binary_data_set(metaFilePath, binaryFilePath):
dfmeta = pd.read_csv(metaFilePath)
binary_file = open(binaryFilePath, 'rb')
file_vars = {}
for ind in dfmeta.index:
binaryFile.seek(dfmeta.loc[ind, 'startBytePosition'])
typenum = None
if dfmeta.loc[ind, 'internalVartype'] =... |
def hello_world(event):
return f"Hello, World!"
def hello_bucket(event, context):
return f"A new file was uploaded to the bucket" | def hello_world(event):
return f'Hello, World!'
def hello_bucket(event, context):
return f'A new file was uploaded to the bucket' |
def solve():
for n in range(1, 1001):
for m in range(n + 1, 1001):
a, b, c = (m**2 - n**2, 2 * m * n, m**2 + n**2)
if a + b + c == 1000:
return a * b * c
if __name__ == "__main__":
print(solve()) | def solve():
for n in range(1, 1001):
for m in range(n + 1, 1001):
(a, b, c) = (m ** 2 - n ** 2, 2 * m * n, m ** 2 + n ** 2)
if a + b + c == 1000:
return a * b * c
if __name__ == '__main__':
print(solve()) |
def matrixElementsSum(matrix):
sum = 0
for i in range(0,len(matrix)-1):
for j in range(0,len(matrix[i])):
if matrix[i][j] == 0:
matrix[i+1][j] = 0
for row in matrix:
for element in row:
sum = sum + element
return sum
| def matrix_elements_sum(matrix):
sum = 0
for i in range(0, len(matrix) - 1):
for j in range(0, len(matrix[i])):
if matrix[i][j] == 0:
matrix[i + 1][j] = 0
for row in matrix:
for element in row:
sum = sum + element
return sum |
class MapPiece(object):
name = ""
tiles = ""
symbolic_links = {}
spawn_ratios = tuple()
spawners = tuple()
connectors = {}
@classmethod
def write_tiles_level(cls, level, left_x, top_y):
local_x = 0
local_y = 0
for line in cls.tiles:
for char in line:
... | class Mappiece(object):
name = ''
tiles = ''
symbolic_links = {}
spawn_ratios = tuple()
spawners = tuple()
connectors = {}
@classmethod
def write_tiles_level(cls, level, left_x, top_y):
local_x = 0
local_y = 0
for line in cls.tiles:
for char in line:
... |
# Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | {'targets': [{'target_name': 'ios_engine_main', 'type': 'executable', 'sources': ['ios_engine_main.cc'], 'dependencies': ['ios_engine']}, {'target_name': 'ios_engine', 'type': 'static_library', 'sources': ['ios_engine.cc', 'ios_engine.h'], 'dependencies': ['../base/absl.gyp:absl_synchronization', '../base/base.gyp:base... |
class Solution:
def __init__(self, w: List[int]):
self.length = sum(w)
self.n = len(w)
self.w_pool = [0]
for i in range(self.n):
self.w_pool.append(self.w_pool[-1] + w[i])
def pickIndex(self) -> int:
picked_val = random.uniform(0, self.length)
i = 0
... | class Solution:
def __init__(self, w: List[int]):
self.length = sum(w)
self.n = len(w)
self.w_pool = [0]
for i in range(self.n):
self.w_pool.append(self.w_pool[-1] + w[i])
def pick_index(self) -> int:
picked_val = random.uniform(0, self.length)
i = 0... |
class TrainTaskConfig(object):
use_gpu = False
# the epoch number to train.
pass_num = 2
# the number of sequences contained in a mini-batch.
batch_size = 64
# the hyper parameters for Adam optimizer.
learning_rate = 0.001
beta1 = 0.9
beta2 = 0.98
eps = 1e-9
# the paramete... | class Traintaskconfig(object):
use_gpu = False
pass_num = 2
batch_size = 64
learning_rate = 0.001
beta1 = 0.9
beta2 = 0.98
eps = 1e-09
warmup_steps = 4000
use_avg_cost = False
model_dir = 'trained_models'
class Infertaskconfig(object):
use_gpu = False
batch_size = 10
... |
INSTALLED_APPS = [
"django_event_sourcing",
"django.contrib.auth",
"django.contrib.contenttypes",
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
SECRET_KEY = "This is a SECRET_KEY"
EVENT_TYPES = [
"tests.event_types.DummyEventType"... | installed_apps = ['django_event_sourcing', 'django.contrib.auth', 'django.contrib.contenttypes']
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
secret_key = 'This is a SECRET_KEY'
event_types = ['tests.event_types.DummyEventType'] |
#! python2.7
## -*- coding: utf-8 -*-
## kun for Apk View Tracing
## TreeType.py
#===============================================================================
# # data structures
#===============================================================================
class CRect(object):
mLeft = 0
mRigh... | class Crect(object):
m_left = 0
m_right = 0
m_top = 0
m_bottom = 0
class Cpoint:
x = 0
y = 0
class Ctreenode(object):
m_class_name = 'mClassName'
m_hash_code = 'fffff'
m_id = 'mId'
m_text = 'mText'
m_absolute_rect = c_rect()
m_rect = c_rect()
m_location = c_point()
... |
grades = {
"English": 97,
"Math": 93,
"Art": 74,
"Music": 86
}
grades.setdefault("Art", 87) # Art key exists. No change.
print("Art grade:", grades["Art"])
grades.setdefault("Gym", 97) # Gym key is new. Added and set.
print("Gym grade:", grades["Gym"]) | grades = {'English': 97, 'Math': 93, 'Art': 74, 'Music': 86}
grades.setdefault('Art', 87)
print('Art grade:', grades['Art'])
grades.setdefault('Gym', 97)
print('Gym grade:', grades['Gym']) |
strategy_type = "learning"
config = {
"strategy_id": "svm",
"name": "Support Vector Machine Classifier",
"parameters": [
{
"parameter_id": "C",
"label": "C - Error term weight",
"type": "float",
"default_value": 2.6,
},
{
"p... | strategy_type = 'learning'
config = {'strategy_id': 'svm', 'name': 'Support Vector Machine Classifier', 'parameters': [{'parameter_id': 'C', 'label': 'C - Error term weight', 'type': 'float', 'default_value': 2.6}, {'parameter_id': 'kernel', 'label': 'SVM kernel', 'selection_values': ['linear', 'poly', 'sigmoid', 'rbf'... |
# is_learning = True
# while is_learning:
# print('Learning...')
# ask = input('Are you still learning? ')
# is_learning = ask == 'yes'
# if not is_learning:
# print('You finally mastered it')
people = ['Alice', 'Bob', 'Charlie']
for person in people:
print(person)
indices = [0, 1, 2, 3, 4]
for _ i... | people = ['Alice', 'Bob', 'Charlie']
for person in people:
print(person)
indices = [0, 1, 2, 3, 4]
for _ in indices:
print('I will repeat 5 times')
for _ in range(5):
print('I will repeat 5 times again')
start = 2
stop = 20
step = 3
for index in range(start, stop, step):
print(index)
students = [{'name'... |
def height(root):
if root is None:
return -1
left_height = height(root.left)
right_height = height(root.right)
return 1 + max(left_height, right_height) | def height(root):
if root is None:
return -1
left_height = height(root.left)
right_height = height(root.right)
return 1 + max(left_height, right_height) |
#
# PySNMP MIB module LIEBERT-GP-REGISTRATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIEBERT-GP-REGISTRATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
class BadRequest(Exception):
pass
class ParamError(BadRequest):
pass
class Unauthorized(Exception):
pass
class Forbidden(Exception):
pass
class NotFound(Exception):
pass
class IDNotFoundError(NotFound):
pass
class Conflict(Exception):
pass
class ParamConflict(Conflict):
pass
cla... | class Badrequest(Exception):
pass
class Paramerror(BadRequest):
pass
class Unauthorized(Exception):
pass
class Forbidden(Exception):
pass
class Notfound(Exception):
pass
class Idnotfounderror(NotFound):
pass
class Conflict(Exception):
pass
class Paramconflict(Conflict):
pass
clas... |
# Copyright (c) 2017 Mark D. Hill and David A. Wood
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditio... | class Result:
enums = '\n NotRun\n Skipped\n Passed\n Failed\n Errored\n '.split()
for (idx, enum) in enumerate(enums):
locals()[enum] = idx
@classmethod
def name(cls, enum):
return cls.enums[enum]
def __init__(self, value, reason=None):
... |
a= "goat"
def animal():
global a
b = "pakka"
a = a * 6
print(a)
print(b)
animal()
| a = 'goat'
def animal():
global a
b = 'pakka'
a = a * 6
print(a)
print(b)
animal() |
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()... | def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
(alist[i], alist[smallest]) = (alist[smallest], alist[i])
alist = input('Enter the list of numbers: ').split()... |
# Idenpotant
# Closure
def outer_function(tag):
pass
def add(x, y):
return x + y
def deco(orig_func):
def wrapper(*args, **kwargs):
print("That is to know that I ran the deco func")
return orig_func(*args, **kwargs)
return wrapper
add = deco(add)
print(add(3, 5))
| def outer_function(tag):
pass
def add(x, y):
return x + y
def deco(orig_func):
def wrapper(*args, **kwargs):
print('That is to know that I ran the deco func')
return orig_func(*args, **kwargs)
return wrapper
add = deco(add)
print(add(3, 5)) |
skills = [
{
"id" : "0001",
"name" : "Liver of Steel",
"type" : "Passive",
"isPermable" : False,
"effects" :
{
"maximumInebriety" : "+5",
},
},
{
"id" : "0002",
"name" : "Chronic Indigestion",
"type" : "Combat",
... | skills = [{'id': '0001', 'name': 'Liver of Steel', 'type': 'Passive', 'isPermable': False, 'effects': {'maximumInebriety': '+5'}}, {'id': '0002', 'name': 'Chronic Indigestion', 'type': 'Combat', 'mpCost': 5}, {'id': '0003', 'name': 'The Smile of Mr. A.', 'type': 'Buff', 'mpCost': 5, 'isPermable': False}, {'id': '0004',... |
for cat1 in range(1, 21):
for cat2 in range(1, 21):
hypo = (cat1 ** 2 + cat2 ** 2) ** 0.5
if hypo.is_integer():
print(cat1, cat2, hypo)
| for cat1 in range(1, 21):
for cat2 in range(1, 21):
hypo = (cat1 ** 2 + cat2 ** 2) ** 0.5
if hypo.is_integer():
print(cat1, cat2, hypo) |
#
# Copyright 2018-2019 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | debug = False
restplus_mask_swagger = False
api_title = 'MAX Weather Forecaster'
api_desc = 'An API for serving models'
api_version = '1.1.0'
model_name = 'lstm_weather_forecaster'
default_model_path = 'assets/models'
model_license = 'Apache 2'
models = ['univariate', 'multistep', 'multivariate']
default_model = MODELS... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
h = set()
while head and head not in h:
h.add(head)
head = head.next
retu... | class Solution:
def has_cycle(self, head: ListNode) -> bool:
h = set()
while head and head not in h:
h.add(head)
head = head.next
return head |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"main": "00_beproductive.ipynb",
"parse_arguments": "00_beproductive.ipynb",
"in_notebook": "00_beproductive.ipynb",
"APP_NAME": "01_blocker.ipynb",
"REDIRECT": "01... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'main': '00_beproductive.ipynb', 'parse_arguments': '00_beproductive.ipynb', 'in_notebook': '00_beproductive.ipynb', 'APP_NAME': '01_blocker.ipynb', 'REDIRECT': '01_blocker.ipynb', 'WIN_PATH': '01_blocker.ipynb', 'LINUX_PATH': '01_blocker.ipynb', 'N... |
def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicador(a, b):
return a * b
def dividir(numerador, denominador):
return float(numerador)/denominador | def sumar(a, b):
return a + b
def restar(a, b):
return a - b
def multiplicador(a, b):
return a * b
def dividir(numerador, denominador):
return float(numerador) / denominador |
class MockOpenedFile(object):
def __init__(self, value='value'):
self.seek_values = []
self.buf_values = []
self.value = value
def seek(self, offset):
self.seek_values.append(offset)
def read(self, buf):
self.buf_values.append(buf)
return self.value
def... | class Mockopenedfile(object):
def __init__(self, value='value'):
self.seek_values = []
self.buf_values = []
self.value = value
def seek(self, offset):
self.seek_values.append(offset)
def read(self, buf):
self.buf_values.append(buf)
return self.value
de... |
# CountFirstCharaters
# --------------------------------------
# It counts how many times a character appears at the beginning of a line
def CountFirstCharacters (Line, Character):
n = 0
for letter in Line:
if letter == Character:
n = n + 1
else:
return n
# Remove all the Character characters from the li... | def count_first_characters(Line, Character):
n = 0
for letter in Line:
if letter == Character:
n = n + 1
else:
return n
def remove_first_characters(Line, Character):
n = count_firstcharacters(Line, Character)
return Line[n:] |
print ("hola mundo/jhon")
a=45
b=5
print("Suma:",a+b)
print("Resta:",a-b)
print("Division:",a/b)
print("Multiplicacion:",a*b) | print('hola mundo/jhon')
a = 45
b = 5
print('Suma:', a + b)
print('Resta:', a - b)
print('Division:', a / b)
print('Multiplicacion:', a * b) |
class Interfaces:
def __init__(self, interface: dict):
self.screen = interface['screen']
self.account_linking = interface['account_linking']
class MetaData:
def __init__(self, meta: dict):
self.locale = meta['locale']
self.timezone = meta['timezone']
self.interfaces = I... | class Interfaces:
def __init__(self, interface: dict):
self.screen = interface['screen']
self.account_linking = interface['account_linking']
class Metadata:
def __init__(self, meta: dict):
self.locale = meta['locale']
self.timezone = meta['timezone']
self.interfaces = ... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/4/A
n = int(input())
print('YES' if (n>2 and n%2==0) else 'NO')
| n = int(input())
print('YES' if n > 2 and n % 2 == 0 else 'NO') |
class Submissions:
def __init__(self, client):
self.client = client
def list(self, groupId, assignmentId):
url = self.client.api_url + '/groups/' + groupId + '/assignments/' + assignmentId + '/submissions'
method = 'get'
return self.client.api_handler(url=url, method=method)
... | class Submissions:
def __init__(self, client):
self.client = client
def list(self, groupId, assignmentId):
url = self.client.api_url + '/groups/' + groupId + '/assignments/' + assignmentId + '/submissions'
method = 'get'
return self.client.api_handler(url=url, method=method)
... |
class NQ:
def __init__(self, size):
self.n = size
self.board = self.generateBoard()
def solve(self):
if self.__util(0) == False:
print("Solution does not exist")
self.printBoard()
def __util(self, col):
if col >= self.n:
return ... | class Nq:
def __init__(self, size):
self.n = size
self.board = self.generateBoard()
def solve(self):
if self.__util(0) == False:
print('Solution does not exist')
self.printBoard()
def __util(self, col):
if col >= self.n:
return False
... |
# %% [139. Word Break](https://leetcode.com/problems/word-break/)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@functools.lru_cache(None)
def check(s):
if not s:
return True
for word in wordDict:
if s.startswith(wor... | class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
@functools.lru_cache(None)
def check(s):
if not s:
return True
for word in wordDict:
if s.startswith(word) and check(s[len(word):]):
return True
... |
def wrapper(f):
def fun(l):
decorated_numbers = []
for number in l:
decorated_numbers.append("+91 " + number[-10:-5] + " " + number[-5:])
return f(decorated_numbers)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l =... | def wrapper(f):
def fun(l):
decorated_numbers = []
for number in l:
decorated_numbers.append('+91 ' + number[-10:-5] + ' ' + number[-5:])
return f(decorated_numbers)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l = [i... |
def reverse_text(string):
return (x for x in string[::-1])
# for x in string[::-1]:
# yield x
# idx = len(string) - 1
# while idx >= 0:
# yield string[idx]
# idx -= 1
for char in reverse_text("step"):
print(char, end='')
| def reverse_text(string):
return (x for x in string[::-1])
for char in reverse_text('step'):
print(char, end='') |
class Ticket:
def __init__(self, payload, yt_api, gh_api, users_dict):
self.payload = payload
self.action = payload["action"]
self.yt_api = yt_api
self.gh_api = gh_api
self.users_dict = users_dict
self.pr = payload["pull_request"]
self.url = self.pr["html_ur... | class Ticket:
def __init__(self, payload, yt_api, gh_api, users_dict):
self.payload = payload
self.action = payload['action']
self.yt_api = yt_api
self.gh_api = gh_api
self.users_dict = users_dict
self.pr = payload['pull_request']
self.url = self.pr['html_url... |
dna_seq1 = 'ACCTGATC'
gc_count = 0
for nucl in dna_seq1:
if nucl == 'G' or nucl == 'C':
gc_count += 1
print(gc_count / len(dna_seq1))
| dna_seq1 = 'ACCTGATC'
gc_count = 0
for nucl in dna_seq1:
if nucl == 'G' or nucl == 'C':
gc_count += 1
print(gc_count / len(dna_seq1)) |
class BaseLoadTester(object):
def __init__(self, config):
self.config = config
def before(self):
raise NotImplementedError()
def on_result(self):
raise NotImplementedError()
| class Baseloadtester(object):
def __init__(self, config):
self.config = config
def before(self):
raise not_implemented_error()
def on_result(self):
raise not_implemented_error() |
description = 'POLI monochromator devices'
group = 'lowlevel'
tango_base = 'tango://phys.poli.frm2:10000/poli/'
s7_motor = tango_base + 's7_motor/'
devices = dict(
chi_m = device('nicos.devices.tango.Motor',
description = 'monochromator tilt (chi axis)',
tangodevice = s7_motor + 'chi_m',
... | description = 'POLI monochromator devices'
group = 'lowlevel'
tango_base = 'tango://phys.poli.frm2:10000/poli/'
s7_motor = tango_base + 's7_motor/'
devices = dict(chi_m=device('nicos.devices.tango.Motor', description='monochromator tilt (chi axis)', tangodevice=s7_motor + 'chi_m', fmtstr='%.2f', abslimits=(0, 12.7), pr... |
# Advent of code 2021 : Day 1 | Part 1
# Author = Abhinav
# Date = 1st of December 2021
# Source = [Advent Of Code](https://adventofcode.com/2021/day/1)
# Solution :
inputs = open("input.txt", "rt")
inputs = list(map(int, inputs.read().splitlines()))
print(sum([1 for _ in range(1, len(inputs)) if inputs[_-1] < in... | inputs = open('input.txt', 'rt')
inputs = list(map(int, inputs.read().splitlines()))
print(sum([1 for _ in range(1, len(inputs)) if inputs[_ - 1] < inputs[_]])) |
class Charge:
def __init__(self, vehicle):
self._vehicle = vehicle
self._api_client = vehicle._api_client
async def get_state(self):
return await self._api_client.get(
"vehicles/{}/data_request/charge_state".format(self._vehicle.id))
async def start_charging(self):
... | class Charge:
def __init__(self, vehicle):
self._vehicle = vehicle
self._api_client = vehicle._api_client
async def get_state(self):
return await self._api_client.get('vehicles/{}/data_request/charge_state'.format(self._vehicle.id))
async def start_charging(self):
return a... |
test = { 'name': 'q3_1_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': ">>> #It looks like you didn't give anything the name;\n"
">>> # seconds_in_a_decade. Maybe there's a typo, or maybe you ;\n"
'>>> # ... | test = {'name': 'q3_1_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> #It looks like you didn\'t give anything the name;\n>>> # seconds_in_a_decade. Maybe there\'s a typo, or maybe you ;\n>>> # just need to run the cell below Question 3.2 where you defined ;\n>>> # seconds_in_a_decade. Click that cell and then cli... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/eigen3".split(';') if "/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/eigen3'.split(';') if '/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/e... |
if __name__ == '__main__':
n = int(input())
answer = ''
for i in range(n):
answer += str(i + 1)
print(answer)
| if __name__ == '__main__':
n = int(input())
answer = ''
for i in range(n):
answer += str(i + 1)
print(answer) |
def reset_io(buff):
buff.seek(0)
buff.truncate(0)
return buff
def truncate_io(buff, size):
# get the remainder value
buff.seek(size)
leftover = buff.read()
# remove the remainder
buff.seek(0)
buff.truncate(size)
return leftover
# def diesattheend(pool):
# import atexit
# ... | def reset_io(buff):
buff.seek(0)
buff.truncate(0)
return buff
def truncate_io(buff, size):
buff.seek(size)
leftover = buff.read()
buff.seek(0)
buff.truncate(size)
return leftover
class Fakepool:
def __init__(self, max_workers=None):
pass
def submit(self, func, *a, **k... |
'''
APDT: Ploting
--------------------------
Provide useful data visualizaton tools.
Check https://github.com/Zhiyuan-Wu/apdt for more information.
''' | """
APDT: Ploting
--------------------------
Provide useful data visualizaton tools.
Check https://github.com/Zhiyuan-Wu/apdt for more information.
""" |
dead_emcal = [128, 129, 131, 134, 139, 140, 182, 184, 188, 189, 385, 394, 397, 398, 399, 432, 434, 436, 440, 442, 5024, 5025, 5026, 5027, 5028, 5030, 5032, 5033, 5035, 5036, 5037, 5038, 5039, 5121, 5122, 5123, 5124, 5125, 5126, 5128, 5129, 5130, 5132, 5133, 5134, 5135, 5170, 5172, 5173, 5174, 5178, 5181, 6641, 6647, 66... | dead_emcal = [128, 129, 131, 134, 139, 140, 182, 184, 188, 189, 385, 394, 397, 398, 399, 432, 434, 436, 440, 442, 5024, 5025, 5026, 5027, 5028, 5030, 5032, 5033, 5035, 5036, 5037, 5038, 5039, 5121, 5122, 5123, 5124, 5125, 5126, 5128, 5129, 5130, 5132, 5133, 5134, 5135, 5170, 5172, 5173, 5174, 5178, 5181, 6641, 6647, 66... |
#!/usr/bin/python3
#---------------------- Begin Serializer Boilerplate for GAPS ------------------------
HHEAD='''#ifndef GMA_HEADER_FILE
#define GMA_HEADER_FILE
#pragma pack(1)
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <arpa/in... | hhead = '#ifndef GMA_HEADER_FILE\n#define GMA_HEADER_FILE\n#pragma pack(1)\n\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <arpa/inet.h>\n#include <float.h>\n\n#include "float754.h"\n\n#define id(X) (X)\n\ntypedef struct _trailer... |
#!/usr/bin/env python
def add_multiply(x, y, z=1):
return (x + y) * z
add_multiply(1, 2) # x=1, y=2, z=1
| def add_multiply(x, y, z=1):
return (x + y) * z
add_multiply(1, 2) |
'''
Write a function called my_func that takes two arguments---a list and a
substring---and returns a new list, containing only words that start with the
chosen substring. Make sure that your function is not case sensitive: meaning
that if you want to filter by words that start with 'a', both 'apple' and
'Apple' wo... | """
Write a function called my_func that takes two arguments---a list and a
substring---and returns a new list, containing only words that start with the
chosen substring. Make sure that your function is not case sensitive: meaning
that if you want to filter by words that start with 'a', both 'apple' and
'Apple' wo... |
font = CurrentFont()
for glyph in font.selection:
glyph = font[name]
glyph.prepareUndo()
glyph.rotate(-5)
glyph.skew(5)
glyph.performUndo()
| font = current_font()
for glyph in font.selection:
glyph = font[name]
glyph.prepareUndo()
glyph.rotate(-5)
glyph.skew(5)
glyph.performUndo() |
load("//elm/private:test.bzl", _elm_test = "elm_test")
elm_test = _elm_test
def _elm_make_impl(ctx):
elm_compiler = ctx.toolchains["@rules_elm//elm:toolchain"].elm
output_file = ctx.actions.declare_file(ctx.attr.output)
env = {}
inputs = [elm_compiler, ctx.file.elm_json] + ctx.files.srcs
if ctx.f... | load('//elm/private:test.bzl', _elm_test='elm_test')
elm_test = _elm_test
def _elm_make_impl(ctx):
elm_compiler = ctx.toolchains['@rules_elm//elm:toolchain'].elm
output_file = ctx.actions.declare_file(ctx.attr.output)
env = {}
inputs = [elm_compiler, ctx.file.elm_json] + ctx.files.srcs
if ctx.file.... |
x = [2,3,5,6,8]
y = [1,6,22,33,61]
x_2 = list()
x_3 = list()
x_4 = list()
x_carpi_y = list()
x_2_carpi_y = list()
for i in x:
x_2.append(int(pow(i,2)))
x_3.append(int(pow(i,3)))
x_4.append(int(pow(i,4)))
print("xi : ", x, sum(x))
print("xi^2 : ", x_2, sum(x_2))
print("xi^3 : ", x_3, sum(x_3))
print("xi^... | x = [2, 3, 5, 6, 8]
y = [1, 6, 22, 33, 61]
x_2 = list()
x_3 = list()
x_4 = list()
x_carpi_y = list()
x_2_carpi_y = list()
for i in x:
x_2.append(int(pow(i, 2)))
x_3.append(int(pow(i, 3)))
x_4.append(int(pow(i, 4)))
print('xi : ', x, sum(x))
print('xi^2 : ', x_2, sum(x_2))
print('xi^3 : ', x_3, sum(x_3))
pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.