content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# (regname, regsize, is_big_endian, arch_name, branches)
# PowerPC CPU REGS
PPCREGS = [[], 4, True, "ppc", ["bl "]]
for i in range(32):
PPCREGS[0].append("r"+str(i))
for i in range(32):
PPCREGS[0].append(None)
PPCREGS[0].append("lr")
PPCREGS[0].append("ctr")
for i in range(8):
PPCREGS[0].append("cr"+str(i))
# A... | ppcregs = [[], 4, True, 'ppc', ['bl ']]
for i in range(32):
PPCREGS[0].append('r' + str(i))
for i in range(32):
PPCREGS[0].append(None)
PPCREGS[0].append('lr')
PPCREGS[0].append('ctr')
for i in range(8):
PPCREGS[0].append('cr' + str(i))
aarch64_regs = [[], 8, False, 'aarch64', ['bl ', 'blx ']]
for i in rang... |
""" Swagger documentation for comment resources """
class CommentResourceDoc:
""" Comment resources swagger documentation """
@staticmethod
def get_by_id_docs():
""" Get by id endpoint documentation """
return {
'tags': ['comment'],
'description': 'Returns json',
... | """ Swagger documentation for comment resources """
class Commentresourcedoc:
""" Comment resources swagger documentation """
@staticmethod
def get_by_id_docs():
""" Get by id endpoint documentation """
return {'tags': ['comment'], 'description': 'Returns json', 'parameters': [{'name': 'Co... |
# -*- coding: utf8 -*
'''
A Simple Extractor Key Note for SPED Fiscal
created by Matheus Tavares
'''
# Abrindo arquivo Sped para ler e Criando arquivo com notas separadas
sped = open("sped.txt", "r")
noteLine =[]
# Encontrando linhas C100 e salvando em Lista
for line in sped:
if line[0:6] == '|C... | """
A Simple Extractor Key Note for SPED Fiscal
created by Matheus Tavares
"""
sped = open('sped.txt', 'r')
note_line = []
for line in sped:
if line[0:6] == '|C100|':
noteLine.append(line)
sep_note = []
for line in noteLine:
sepNote.append(line.split('|'))
key_notes = open('./keys.txt', 'w')
for i in ... |
DATA_FOLDER = 'data'
DATA_INPUT_ZIP = 'stanford-dogs-dataset.zip'
DATA_OUTPUT_ZIP = 'dataset_unzipped'
DATASET_FOLDER = 'dataset'
IMAGES_LIST_FILE_NAME = 'images.txt'
INDEX_FILE_NAME = 'index.nmslib'
INPUT_IMAGE_FILE_NAME = 'input_image.jpg'
OUTPUT_IMAGE_FILE_NAME = 'output_image.jpg'
DEFAULT_IMAGES_PER_RACE = 1
IMAG... | data_folder = 'data'
data_input_zip = 'stanford-dogs-dataset.zip'
data_output_zip = 'dataset_unzipped'
dataset_folder = 'dataset'
images_list_file_name = 'images.txt'
index_file_name = 'index.nmslib'
input_image_file_name = 'input_image.jpg'
output_image_file_name = 'output_image.jpg'
default_images_per_race = 1
image_... |
class Solution:
def threeSumClosest(self, nums: [int], target: int) -> int:
nums = sorted(nums)
visited = []
difference = float('inf')
result = 0
for i, num_1 in enumerate(nums):
if num_1 in visited:
continue
else:
visi... | class Solution:
def three_sum_closest(self, nums: [int], target: int) -> int:
nums = sorted(nums)
visited = []
difference = float('inf')
result = 0
for (i, num_1) in enumerate(nums):
if num_1 in visited:
continue
else:
... |
class Note(object):
def __init__(self, content = None):
self.content = content
def write_content(self, content):
self.content = content
def remove_all(self):
self.content=""
def __str__(self):
return self.content
class NoteBook(object):
def __init__(self, title):
... | class Note(object):
def __init__(self, content=None):
self.content = content
def write_content(self, content):
self.content = content
def remove_all(self):
self.content = ''
def __str__(self):
return self.content
class Notebook(object):
def __init__(self, title)... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio search errors."""
class IndexAlreadyExistsError(Exception):
"""Raised whe... | """Invenio search errors."""
class Indexalreadyexistserror(Exception):
"""Raised when an index or alias already exists during index creation.""" |
USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS"
USER_SIGNUP_SUCCESSFUL = "USER_SIGNUP_SUCCESSFUL"
CREDENTIALS_INCORRECT = "CREDENTIALS_INCORRECT"
USER_UNREGISTERED = "USER_UNREGISTERED"
ROLL_NUMBER_REQUIRED = "ROLL_NUMBER_REQUIRED"
PASSWORD_REQUIRED = "PASSWORD_REQUIRED"
| user_already_exists = 'USER_ALREADY_EXISTS'
user_signup_successful = 'USER_SIGNUP_SUCCESSFUL'
credentials_incorrect = 'CREDENTIALS_INCORRECT'
user_unregistered = 'USER_UNREGISTERED'
roll_number_required = 'ROLL_NUMBER_REQUIRED'
password_required = 'PASSWORD_REQUIRED' |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def has_path(root, stack, x):
if not root:
return False
stack.append(root.val)
if root.val == x:
return True
if has_path(root.left, stack, x) or has_path(root.right, s... | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def has_path(root, stack, x):
if not root:
return False
stack.append(root.val)
if root.val == x:
return True
if has_path(root.left, stack, x) or has_path(root.right, stack... |
def add(x, y):
return x + y
def sub(x, y):
return x - y
# as we implemented new multiply method is started showing error
# crashing our python project
# so testing in python is important
def multiply(x, y):
"""Function to perform multiply"""
return x * (-1 * y)
# return x * y
def division(x, y... | def add(x, y):
return x + y
def sub(x, y):
return x - y
def multiply(x, y):
"""Function to perform multiply"""
return x * (-1 * y)
def division(x, y):
"""Function to perform division"""
if y == 0:
raise value_error('Can;t divide by zero')
return x / y
def eq(x, y):
"""Functio... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(h) time | O(h) space - where h is the height of tree
def deleteNode(self, root: Optional[TreeNode], ... | class Solution:
def delete_node(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root is None:
return root
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.nodes_sorted = []
self.index = -1
... | class Bstiterator:
def __init__(self, root: Optional[TreeNode]):
self.nodes_sorted = []
self.index = -1
self._inorder(root)
def _inorder(self, root):
if not root:
return
self._inorder(root.left)
self.nodes_sorted.append(root.val)
self._inorde... |
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
if len(arr) == 1:
return root and root.val == arr[0] and not root.left and not root.right
if not root or root.val != arr[0]:
return False
return self.isValidSequence(root.left, arr[1:])... | class Solution:
def is_valid_sequence(self, root: TreeNode, arr: List[int]) -> bool:
if len(arr) == 1:
return root and root.val == arr[0] and (not root.left) and (not root.right)
if not root or root.val != arr[0]:
return False
return self.isValidSequence(root.left, a... |
#import osgeo._gdal
#import osgeo._gdalconst
#import osgeo._ogr
#import osgeo._osr
#import osgeo
#import gdal
#import gdalconst
#import ogr
#import osr
#
#cnt = ogr.GetDriverCount()
#for i in xrange(cnt):
# print ogr.GetDriver(i).GetName()
#
#import os1_hw
pass
| pass |
class Solution:
def numberOfSteps(self, ans: int) -> int:
steps = 0
while ans != 0:
if ans % 2 == 0:
ans = ans / 2
steps += 1
else:
ans -= 1
steps += 1
return steps
| class Solution:
def number_of_steps(self, ans: int) -> int:
steps = 0
while ans != 0:
if ans % 2 == 0:
ans = ans / 2
steps += 1
else:
ans -= 1
steps += 1
return steps |
class MaxStack:
def __init__(self):
# do intialization if necessary
self.St = []
self.maxSt = []
"""
@param: number: An integer
@return: nothing
"""
def push(self, x):
# write your code here
self.St.append(x)
if not self.maxSt or x >= sel... | class Maxstack:
def __init__(self):
self.St = []
self.maxSt = []
'\n @param: number: An integer\n @return: nothing\n '
def push(self, x):
self.St.append(x)
if not self.maxSt or x >= self.maxSt[-1]:
self.maxSt.append(x)
'\n @return: An integer\n ... |
"""
This state module is used to manage Wordpress installations
:depends: wp binary from http://wp-cli.org/
"""
def __virtual__():
if "wordpress.show_plugin" in __salt__:
return True
return (False, "wordpress module could not be loaded")
def installed(name, user, admin_user, admin_password, admin_e... | """
This state module is used to manage Wordpress installations
:depends: wp binary from http://wp-cli.org/
"""
def __virtual__():
if 'wordpress.show_plugin' in __salt__:
return True
return (False, 'wordpress module could not be loaded')
def installed(name, user, admin_user, admin_password, admin_ema... |
SEQUENCE = [
'webhooktarget_extra_state',
'webhooktarget_extra_data_null',
'manytomanyfield_rm_null',
]
| sequence = ['webhooktarget_extra_state', 'webhooktarget_extra_data_null', 'manytomanyfield_rm_null'] |
# https://www.codewars.com/kata/5868b2de442e3fb2bb000119
def closest(strng):
if not strng:
return []
arr = [i for i in strng.split()]
arr_num = []
for i in arr:
sum_num = 0
for j in i:
sum_num += int(j)
arr_num.append(sum_num)
arr = [int(i) for i in arr]
... | def closest(strng):
if not strng:
return []
arr = [i for i in strng.split()]
arr_num = []
for i in arr:
sum_num = 0
for j in i:
sum_num += int(j)
arr_num.append(sum_num)
arr = [int(i) for i in arr]
n = len(arr)
new_arr = sorted(list(zip(arr_num, ra... |
#
# PySNMP MIB module PCSYSTEMSMIF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PCSYSTEMSMIF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:37:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) ... |
# output: ok
count = 0
total = 0
last = 0
for i in (1, 2, 3):
count += 1
total += i
last = i
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0
last = 0
i = 1
while i <= 3:
count += 1
total += i
last = i
i += 1
assert count == 3
assert total == 6
assert last == 3
cou... | count = 0
total = 0
last = 0
for i in (1, 2, 3):
count += 1
total += i
last = i
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0
last = 0
i = 1
while i <= 3:
count += 1
total += i
last = i
i += 1
assert count == 3
assert total == 6
assert last == 3
count = 0
total = 0... |
"""
A module implementing package-specific exceptions
"""
class OutputValidationError(Exception):
""" This exception is raised whenever there is something wrong with the submitted output
""" | """
A module implementing package-specific exceptions
"""
class Outputvalidationerror(Exception):
""" This exception is raised whenever there is something wrong with the submitted output
""" |
"""
Tower of Hanoi
Problem:
Given three rods and disks
The objective of the puzzle is to move the
entire stack of disks to another rod.
The following rules needs to be followed:
*Only one disk can be moved at a time.
*Each move consists of taking the upper disk from one of the stacks and placing it on top
... | """
Tower of Hanoi
Problem:
Given three rods and disks
The objective of the puzzle is to move the
entire stack of disks to another rod.
The following rules needs to be followed:
*Only one disk can be moved at a time.
*Each move consists of taking the upper disk from one of the stacks and placing it on top
... |
ix.enable_command_history()
ix.api.SdkHelpers.create_shading_layer_for_items_selected(ix.application, 3)
ix.disable_command_history() | ix.enable_command_history()
ix.api.SdkHelpers.create_shading_layer_for_items_selected(ix.application, 3)
ix.disable_command_history() |
# If we list all the natural numbers below 10 that are multiples
# of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
if __name__ == "__main__":
numbers = [ n for n in range(1,1000) if n % 3 == 0 or n % 5 == 0 ]
print(sum(numbers))
| if __name__ == '__main__':
numbers = [n for n in range(1, 1000) if n % 3 == 0 or n % 5 == 0]
print(sum(numbers)) |
class Solver:
def __init__(self, cells):
self.cells = cells
def determine_cell_possibilities(self):
for cell in self.cells:
candidates = list(range(1, 10))
for association in cell.get_unique_associations():
if association.number is not None:
if association.number in candidates... | class Solver:
def __init__(self, cells):
self.cells = cells
def determine_cell_possibilities(self):
for cell in self.cells:
candidates = list(range(1, 10))
for association in cell.get_unique_associations():
if association.number is not None:
... |
n = int(input())
arr = []
i = list(map(int, input().split()))
arr = list(range(i[0], i[1]+1))
for each in range(n - 1):
i = list(map(int, input().split()))
for c,every in enumerate(arr):
if every < i[0]:
arr[c] = -1
elif every > i[1]:
arr[c] = -1
if sum(arr) == (-1*len(ar... | n = int(input())
arr = []
i = list(map(int, input().split()))
arr = list(range(i[0], i[1] + 1))
for each in range(n - 1):
i = list(map(int, input().split()))
for (c, every) in enumerate(arr):
if every < i[0]:
arr[c] = -1
elif every > i[1]:
arr[c] = -1
if sum(arr) == -1 * ... |
# __author__ = 'tusharmakkar08'
class Wallet:
def __init__(self):
self.amount = 0 # TODO: get init amount on the basis of user name from db
def load_money(self, amount):
self.amount += amount
def deduct_money(self, amount):
self.amount -= amount
def get_money(self):
... | class Wallet:
def __init__(self):
self.amount = 0
def load_money(self, amount):
self.amount += amount
def deduct_money(self, amount):
self.amount -= amount
def get_money(self):
return self.amount |
r_TPC = 0.664
r_FSWires = 0.668
r_FSGuards = 0.680
path_main = '/dali/lgrandi/peres/efieldsim/'
path_cache = path_main + 'cache/'
path_root_files = path_main + '/solved_outputs/EField_SR0/' | r_tpc = 0.664
r_fs_wires = 0.668
r_fs_guards = 0.68
path_main = '/dali/lgrandi/peres/efieldsim/'
path_cache = path_main + 'cache/'
path_root_files = path_main + '/solved_outputs/EField_SR0/' |
# The following is used as a global constant to represent
# the contribution rate.
CONTRIBUTION_RATE = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
# The show_pay_contrib f... | contribution_rate = 0.05
def main():
gross_pay = float(input('Enter the gross pay: '))
bonus = float(input('Enter the amount of bonuses: '))
show_pay_contrib(gross_pay)
show_bonus_contrib(bonus)
def show_pay_contrib(gross):
contrib = gross * CONTRIBUTION_RATE
print('Contribution for gross pay:... |
'''
Created on 1.12.2016
@author: Darren
''''''
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,... | """
Created on 1.12.2016
@author: Darren
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
... |
def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass
| def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass |
books = int(input("How many books do you want to buy? "))
amount = int(input("How much do you have? "))
amount_required = 100
if books == amount_required > amount:
print("you can purchase the books")
else:
print("You donot have sufficient funds to buy the books")
print(f"You will need {amount} to buy the book... | books = int(input('How many books do you want to buy? '))
amount = int(input('How much do you have? '))
amount_required = 100
if books == amount_required > amount:
print('you can purchase the books')
else:
print('You donot have sufficient funds to buy the books')
print(f'You will need {amount} to buy the b... |
class i18n(object):
def __init__(self):
# Default domain
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {
# Month
'Januari': 'January',
'Februari': 'Febru... | class I18N(object):
def __init__(self):
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {'Januari': 'January', 'Februari': 'February', 'Maret': 'March', 'April': 'April', 'Mei': 'May', 'Juni': 'June'... |
#
# @lc app=leetcode.cn id=1700 lang=python3
#
# [1700] minimum-deletion-cost-to-avoid-repeating-letters
#
None
# @lc code=end | None |
"""Rules to load archives for Bazel plugins."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def rules_docker_archives(version, sha256):
http_archive(
name = "io_bazel_rules_docker",
sha256 = sha256,
strip_prefix = "rules_docker-%s" % version,
urls = ["https... | """Rules to load archives for Bazel plugins."""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def rules_docker_archives(version, sha256):
http_archive(name='io_bazel_rules_docker', sha256=sha256, strip_prefix='rules_docker-%s' % version, urls=['https://github.com/bazelbuild/rules_docker/rele... |
'''
Created on 2009-09-16
@author: beaudoin
A Python version of the C++ Observable class found in Utils
'''
class Observable(object):
def __init__(self):
self._observers = []
self._hasChanged = False
self._batchChangeDepth = 0
def setChanged(self):
"""Protected.... | """
Created on 2009-09-16
@author: beaudoin
A Python version of the C++ Observable class found in Utils
"""
class Observable(object):
def __init__(self):
self._observers = []
self._hasChanged = False
self._batchChangeDepth = 0
def set_changed(self):
"""Protected. Indicate t... |
#
# Code property of Jared Scarito
#
testCases = int(input())
outCases = []
for i in range(testCases):
weights = []
dataSet = str(input())
case = dataSet.split(" ")[0]
maxWeight = int(dataSet.split(" ")[1])
for weightIndex in range(len(dataSet.split(" "))):
if int(weightIndex) > 1:
... | test_cases = int(input())
out_cases = []
for i in range(testCases):
weights = []
data_set = str(input())
case = dataSet.split(' ')[0]
max_weight = int(dataSet.split(' ')[1])
for weight_index in range(len(dataSet.split(' '))):
if int(weightIndex) > 1:
weight = dataSet.split(' ')[i... |
SMS_setting = {
'secretId':'',
'secretKey':'',
'req_Appid':'',
'req_Sign':'',
'req_SessionContext':'',
'req_NumberSet':[],
'req_TemplateID':'',
'req_TemplateParmSet':[],
}
| sms_setting = {'secretId': '', 'secretKey': '', 'req_Appid': '', 'req_Sign': '', 'req_SessionContext': '', 'req_NumberSet': [], 'req_TemplateID': '', 'req_TemplateParmSet': []} |
LEFT = 0
UP = 1
RIGHT = 2
DOWN = 3
vectors = [(-1, 0), (0, 1), (1, 0), (0, -1)]
class Laser:
def __init__(self, board, x, y):
self.board = board
class Board:
def __init__(self, size):
self.size = size
self.real = [[False for _ in range(size)] for _ in range(size)]
def set_mirro... | left = 0
up = 1
right = 2
down = 3
vectors = [(-1, 0), (0, 1), (1, 0), (0, -1)]
class Laser:
def __init__(self, board, x, y):
self.board = board
class Board:
def __init__(self, size):
self.size = size
self.real = [[False for _ in range(size)] for _ in range(size)]
def set_mirror... |
#!/usr/bin/env python3
# Based on the code in
# https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
# by Rob Pike.
def match(regexp, text):
if regexp and regexp[0] == '^':
return match_here(regexp[1:], text)
while text:
print('\nmatch({!r}, {!r})'.format(regexp, text))
... | def match(regexp, text):
if regexp and regexp[0] == '^':
return match_here(regexp[1:], text)
while text:
print('\nmatch({!r}, {!r})'.format(regexp, text))
if match_here(regexp, text):
return True
text = text[1:]
return False
def match_here(regexp, text):
prin... |
expected_output = {
'socket_connections': {
'total_socket_connections': 4,
'sockets_in_listen_state': ['Tunnel1-head-0', 'Tunnel2-head-0', 'Tunnel3-head-0', 'Tunnel20-head-0'],
'Tu1': {
'peers': {
'remote_ip': '10.0.0.2',
'local_ip': '85... | expected_output = {'socket_connections': {'total_socket_connections': 4, 'sockets_in_listen_state': ['Tunnel1-head-0', 'Tunnel2-head-0', 'Tunnel3-head-0', 'Tunnel20-head-0'], 'Tu1': {'peers': {'remote_ip': '10.0.0.2', 'local_ip': '85.45.1.1'}, 'local_ident': {'protocol': 47, 'mask': '255.255.255.255', 'port': 0, 'addre... |
def list_function(x):
return x
n = [3, 5, 7]
print(list_function(n))
| def list_function(x):
return x
n = [3, 5, 7]
print(list_function(n)) |
t = int(input())
for i in range(t):
n = int(input())
m = n-1
arr = []
# print(arr)
uparr = list(range(1,n)) + list(range(n-1,0,-1))
down = 2
up = 0
# print(uparr)
start = 1
for j in range(n):
if j>0:
start += down
down += 1
temp = []
... | t = int(input())
for i in range(t):
n = int(input())
m = n - 1
arr = []
uparr = list(range(1, n)) + list(range(n - 1, 0, -1))
down = 2
up = 0
start = 1
for j in range(n):
if j > 0:
start += down
down += 1
temp = []
temp2 = start
for... |
def sum(a , b):
return a + b
def getAllData():
listOfCategory = [
{
'id': 1,
'cat_name': 'Cell phone',
'products': [
{
'product_id': 1,
'product_name': 'iPhone 12 Pro Max'
},
{
... | def sum(a, b):
return a + b
def get_all_data():
list_of_category = [{'id': 1, 'cat_name': 'Cell phone', 'products': [{'product_id': 1, 'product_name': 'iPhone 12 Pro Max'}, {'product_id': 2, 'product_name': 'iPhone 11 Pro'}, {'product_id': 3, 'product_name': 'iPhone XS'}]}, {'id': 2, 'cate_name': 'Tablet'}]
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 14:42:54 2016
@author: ktritz
"""
def currentshot(self):
return self._connections[0].get('current_shot("nstx")').value
| """
Created on Thu Jun 23 14:42:54 2016
@author: ktritz
"""
def currentshot(self):
return self._connections[0].get('current_shot("nstx")').value |
if __name__ == "__main__":
"""
('f', 'f', 'f')
('l', 'l', 'l')
('o', 'o', 'i')
('w', 'w', 'g')
"""
nums = ['flower','flow','flight'] # each string is regarded as a tuple
for i in zip(*nums):
print(i)
"""
The list elements are connected in sequence
"""
l = ['a', '... | if __name__ == '__main__':
"\n ('f', 'f', 'f')\n ('l', 'l', 'l')\n ('o', 'o', 'i')\n ('w', 'w', 'g')\n "
nums = ['flower', 'flow', 'flight']
for i in zip(*nums):
print(i)
'\n The list elements are connected in sequence\n '
l = ['a', 'b', 'c', 'd', 'e', 'f']
print(l)
... |
class MULT18X18():
def __init__(self, clk=True, site=None, **kwargs):
self.inst = inst("MULT18X18SIO", site, **kwargs)
self.setcfgs({
"AREG": "0",
"BREG": "0",
"B_INPUT": "DIRECT",
"CEAINV": "CEA",
"CEBINV": "CEB",
"CEPINV": "... | class Mult18X18:
def __init__(self, clk=True, site=None, **kwargs):
self.inst = inst('MULT18X18SIO', site, **kwargs)
self.setcfgs({'AREG': '0', 'BREG': '0', 'B_INPUT': 'DIRECT', 'CEAINV': 'CEA', 'CEBINV': 'CEB', 'CEPINV': 'CEP', 'CLKINV': 'CLK', 'PREG': '0', 'PREG_CLKINVERSION': '0', 'RSTAINV': 'RS... |
# NBA Game Predictor
# File: baseline.py
# Authors: Tarmily Wen & Andrew Petrosky
#
# A baseline predictor based purely of winning percentage
def model(train_x, train_y, test_x, test_y):
# Train test
print("Testing on training data...")
correct = 0.0
total = 0.0
for i in range(len(train_x)):
... | def model(train_x, train_y, test_x, test_y):
print('Testing on training data...')
correct = 0.0
total = 0.0
for i in range(len(train_x)):
t = 0 if train_x[i][-2] < train_x[i][-1] else 1
if t == train_y[i]:
correct += 1.0
total += 1.0
acc = correct / total
prin... |
def name_file(fmt, nbr, start):
if not isinstance(nbr, int) or not isinstance(start, int) or nbr <= 0:
return []
filename = fmt.replace('<index_no>', '{0}').format
return [filename(a) for a in xrange(start, start + nbr)]
| def name_file(fmt, nbr, start):
if not isinstance(nbr, int) or not isinstance(start, int) or nbr <= 0:
return []
filename = fmt.replace('<index_no>', '{0}').format
return [filename(a) for a in xrange(start, start + nbr)] |
# import numpy as np
def add(x, y):
"""
This function sums up two numbers.
Parameters
----------
x : float
The first number to be added.
y : float
The second number to be added.
Returns
-------
sum : float
The sum of x and y.
"""
sum = x + y
ret... | def add(x, y):
"""
This function sums up two numbers.
Parameters
----------
x : float
The first number to be added.
y : float
The second number to be added.
Returns
-------
sum : float
The sum of x and y.
"""
sum = x + y
return sum |
SHARD_COUNT = 2**10 # 1024
EPOCH_LENGTH = 2**6 # 64 slots, 6.4 minutes
TARGET_COMMITTEE_SIZE = 2**8 # 256 validators
| shard_count = 2 ** 10
epoch_length = 2 ** 6
target_committee_size = 2 ** 8 |
class Stack:
'''Visual FX Stack'''
def __init__(self, layers=[]):
self.layers = layers
def apply(self, frame):
'''Return the frame with the fx layers applied.'''
output = frame.copy()
for layer in self.layers:
if layer.active:
output = layer.app... | class Stack:
"""Visual FX Stack"""
def __init__(self, layers=[]):
self.layers = layers
def apply(self, frame):
"""Return the frame with the fx layers applied."""
output = frame.copy()
for layer in self.layers:
if layer.active:
output = layer.appl... |
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
first,last = -1,-1
def search(lo,hi):
nonlocal first,last
if nums[lo]<=target<=nums[hi]:
mid = (lo+hi)//2
if nums[mid]==target:
if fi... | class Solution:
def search_range(self, nums: list[int], target: int) -> list[int]:
(first, last) = (-1, -1)
def search(lo, hi):
nonlocal first, last
if nums[lo] <= target <= nums[hi]:
mid = (lo + hi) // 2
if nums[mid] == target:
... |
regions = {'jp': 'amazon.co.jp',
'uk': 'amazon.co.uk',
'de': 'amazon.de',
'eu': 'amazon.co.uk',
'us': 'amazon.com',
'na': 'amazon.com'}
| regions = {'jp': 'amazon.co.jp', 'uk': 'amazon.co.uk', 'de': 'amazon.de', 'eu': 'amazon.co.uk', 'us': 'amazon.com', 'na': 'amazon.com'} |
""" Exception classes for panzer """
class PanzerError(Exception):
""" base class for all panzer exceptions """
pass
class SetupError(PanzerError):
""" error in the setup phase """
pass
class BadASTError(PanzerError):
""" malformatted AST encountered (e.g. C or T fields missing) """
pass
cla... | """ Exception classes for panzer """
class Panzererror(Exception):
""" base class for all panzer exceptions """
pass
class Setuperror(PanzerError):
""" error in the setup phase """
pass
class Badasterror(PanzerError):
""" malformatted AST encountered (e.g. C or T fields missing) """
pass
cla... |
# coding: utf-8
n, m = [int(i) for i in input().split()]
d = {}
for i in range(m):
tmp = input().split()
d[tmp[0]] = tmp[1]
s = input().split()
for i in range(n):
if len(s[i])>len(d[s[i]]):
s[i] = d[s[i]]
print(' '.join(s))
| (n, m) = [int(i) for i in input().split()]
d = {}
for i in range(m):
tmp = input().split()
d[tmp[0]] = tmp[1]
s = input().split()
for i in range(n):
if len(s[i]) > len(d[s[i]]):
s[i] = d[s[i]]
print(' '.join(s)) |
#MergeSort.py
# 20 Oct 2017
#written by Amin dehghan
#DS & Algorithms With Python
def merge(seq,start,mid,stop):
lst=[]
i=start
j=mid
while i<mid and j<stop:
if seq[i]<seq[j]:
lst.append(seq[i])
i+=1
else:
lst.append(seq[j])
j+=1
... | def merge(seq, start, mid, stop):
lst = []
i = start
j = mid
while i < mid and j < stop:
if seq[i] < seq[j]:
lst.append(seq[i])
i += 1
else:
lst.append(seq[j])
j += 1
while i < mid:
lst.append(seq[i])
i += 1
for i in... |
class ReactionZone:
"""
Store a block of 9 reactions.
"""
def __init__(self, indexes, reactions_array):
self.reactions_array = reactions_array
self.contained_indexes = indexes
def getFields(self):
list_of_fields = []
for index in self.contained_indexes:... | class Reactionzone:
"""
Store a block of 9 reactions.
"""
def __init__(self, indexes, reactions_array):
self.reactions_array = reactions_array
self.contained_indexes = indexes
def get_fields(self):
list_of_fields = []
for index in self.contained_indexes:
... |
"""Student data in a dictionary"""
student = {}
for i in range(3):
name = input("Enter name: ")
age = input("Enter age: ")
reg = input("Enter registration number: ")
student[name] = f"{age}, {reg}"
dict(student)
print(student) | """Student data in a dictionary"""
student = {}
for i in range(3):
name = input('Enter name: ')
age = input('Enter age: ')
reg = input('Enter registration number: ')
student[name] = f'{age}, {reg}'
dict(student)
print(student) |
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j flo... | int_max = 32767
def egg_drop(n, k):
egg_floor = [[0 for x in range(k + 1)] for x in range(n + 1)]
for i in range(1, n + 1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
for j in range(1, k + 1):
eggFloor[1][j] = j
for i in range(2, n + 1):
for j in range(2, k + 1):
... |
def my_map(transformation_function, sequence):
for elt in sequence:
yield transformation_function(elt)
powers_of_two = my_map(lambda x: x**2, range(1,11))
print(powers_of_two)
print(next(powers_of_two))
print(list(powers_of_two)) | def my_map(transformation_function, sequence):
for elt in sequence:
yield transformation_function(elt)
powers_of_two = my_map(lambda x: x ** 2, range(1, 11))
print(powers_of_two)
print(next(powers_of_two))
print(list(powers_of_two)) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def isEmpty(self):
return self.top == Non... | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return f'{self.value}'
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def is_empty(self):
return self.top == No... |
#
# PySNMP MIB module HPN-ICF-LswQos-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LswQos-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:27:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.bt(nums, [], res)
return res
def bt(self, nums, tempList, res):
if len(tempList) == len(nums):
res.append(tempList)
return
for i in range(len(nums)):
... | class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
self.bt(nums, [], res)
return res
def bt(self, nums, tempList, res):
if len(tempList) == len(nums):
res.append(tempList)
return
for i in range(len(nums)):
... |
"""Learners"""
NAME = "Model"
DESCRIPTION = "Prediction."
BACKGROUND = "#FAC1D9"
ICON = "icons/Category-Model.svg"
PRIORITY = 4
| """Learners"""
name = 'Model'
description = 'Prediction.'
background = '#FAC1D9'
icon = 'icons/Category-Model.svg'
priority = 4 |
"""
Specification of canopies
"""
class Canopy(object):
def __init__(self, **kwargs):
self.d = kwargs.get('d', None)
self._check()
def _check(self):
assert self.d is not None, 'Vegetation height needs to be given'
class OneLayer(Canopy):
"""
define a homogeneous one layer ca... | """
Specification of canopies
"""
class Canopy(object):
def __init__(self, **kwargs):
self.d = kwargs.get('d', None)
self._check()
def _check(self):
assert self.d is not None, 'Vegetation height needs to be given'
class Onelayer(Canopy):
"""
define a homogeneous one layer can... |
def bubble_sort(alist):
for _ in range(len(alist)-1,0,-1):
for i in range(_):
if alist[i] > alist[i+1]:
alist[i+1],alist[i] = alist[i],alist[i+1]
return alist
print(bubble_sort([1,4,2,3,9,0]))
| def bubble_sort(alist):
for _ in range(len(alist) - 1, 0, -1):
for i in range(_):
if alist[i] > alist[i + 1]:
(alist[i + 1], alist[i]) = (alist[i], alist[i + 1])
return alist
print(bubble_sort([1, 4, 2, 3, 9, 0])) |
(n, k) = map(int, input().split())
cnt = 0
arr = [0 for _ in range(0, n + 1)]
for i in range(2, n + 1):
for j in range(i, n + 1, i):
if arr[j] != 0:
continue
arr[j] = 1
cnt += 1
if cnt == k:
print(j)
exit(0) | (n, k) = map(int, input().split())
cnt = 0
arr = [0 for _ in range(0, n + 1)]
for i in range(2, n + 1):
for j in range(i, n + 1, i):
if arr[j] != 0:
continue
arr[j] = 1
cnt += 1
if cnt == k:
print(j)
exit(0) |
def strangeCounter(t):
initial = 3
j = 3 + 1
time = 0
while True:
time += 1
j -= 1
if t > time -1 + initial:
time += initial -1
initial = initial * 2
j = initial + 1
continue
return j - (t - time)
if __name__ =... | def strange_counter(t):
initial = 3
j = 3 + 1
time = 0
while True:
time += 1
j -= 1
if t > time - 1 + initial:
time += initial - 1
initial = initial * 2
j = initial + 1
continue
return j - (t - time)
if __name__ == '__main__... |
'''
Description: exercise: day old bread
Version: 1.0.1.20210114
Author: Arvin Zhao
Date: 2021-01-13 06:12:15
Last Editors: Arvin Zhao
LastEditTime: 2021-01-14 03:49:47
'''
def print_receipt(loaf_num: int, regular_per_price: float, discount_rate: float) -> None:
'''
Calculate and print the regular price for lo... | """
Description: exercise: day old bread
Version: 1.0.1.20210114
Author: Arvin Zhao
Date: 2021-01-13 06:12:15
Last Editors: Arvin Zhao
LastEditTime: 2021-01-14 03:49:47
"""
def print_receipt(loaf_num: int, regular_per_price: float, discount_rate: float) -> None:
"""
Calculate and print the regular price for lo... |
{
"includes": [
"../../common.gypi"
],
'target_defaults': {
'default_configuration': 'Release',
'cflags':[
'-std=c99'
],
'configurations': {
'Debug': {
'defines': [ 'DEBUG', '_DEBUG' ],
},
'Release': {
'defines': [ 'NDEBUG' ],
}
},
'conditions'... | {'includes': ['../../common.gypi'], 'target_defaults': {'default_configuration': 'Release', 'cflags': ['-std=c99'], 'configurations': {'Debug': {'defines': ['DEBUG', '_DEBUG']}, 'Release': {'defines': ['NDEBUG']}}, 'conditions': [['OS == "win"', {'defines': ['WIN32']}]]}, 'targets': [{'target_name': 'libsqlite', 'type'... |
#!/usr/bin/python3
""" This challenge is as follows:
Given an int n, return the absolute difference
between n and 21, except return double the
absolute difference if n is over 21.
Expected Results:
19 -> 2
10 -> 11
21 -> 0 """
def diff21(n):
# This part is where the challen... | """ This challenge is as follows:
Given an int n, return the absolute difference
between n and 21, except return double the
absolute difference if n is over 21.
Expected Results:
19 -> 2
10 -> 11
21 -> 0 """
def diff21(n):
return (n - 21) * 2 if n > 21 else 21 - n
if __name... |
data = [
["Total Bill","Tip","Payer Gender","Payer Smoker","Day of Week","Meal","Party Size"],
[16.99,1.01,"Female","Non-Smoker","Sunday","Dinner",2],
[10.34,1.66,"Male","Non-Smoker","Sunday","Dinner",3],
[21.01,3.5,"Male","Non-Smoker","Sunday","Dinner",3],
[23.68,3.31,"Male","Non-Smoker","Sunday","Dinner",2],
[24.59,3... | data = [['Total Bill', 'Tip', 'Payer Gender', 'Payer Smoker', 'Day of Week', 'Meal', 'Party Size'], [16.99, 1.01, 'Female', 'Non-Smoker', 'Sunday', 'Dinner', 2], [10.34, 1.66, 'Male', 'Non-Smoker', 'Sunday', 'Dinner', 3], [21.01, 3.5, 'Male', 'Non-Smoker', 'Sunday', 'Dinner', 3], [23.68, 3.31, 'Male', 'Non-Smoker', 'Su... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def find_bottom_left_value(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return []
a ... |
discord_token = 'NDQyNTQ3OTY0MDI0NzE3MzEy.DdAacQ._iDLpBSxzKb8T5rZDh4De9A1sXc'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'
goat_url = 'https://2fwotdvm2o-dsn.algolia.net/1/indexes/ProductTemplateSearch/query'
stockx_url = 'https://xw7sbct9v6-dsn.algolia.net/1/inde... | discord_token = 'NDQyNTQ3OTY0MDI0NzE3MzEy.DdAacQ._iDLpBSxzKb8T5rZDh4De9A1sXc'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'
goat_url = 'https://2fwotdvm2o-dsn.algolia.net/1/indexes/ProductTemplateSearch/query'
stockx_url = 'https://xw7sbct9v6-dsn.algolia.net/1/indexes/pro... |
lista=[]
for i in range(1,101):
if(i%7!=0):
lista.append(i)
print(lista)
| lista = []
for i in range(1, 101):
if i % 7 != 0:
lista.append(i)
print(lista) |
def fizz_buzz(fizz, buzz, highest):
result = []
for i in range(1, highest + 1):
letter = ''
# If divisible by fizz or buzz, add F or B appropriately.
if i % fizz == 0:
letter += 'F'
if i % buzz == 0:
letter += 'B'
# If neither F or B has been la... | def fizz_buzz(fizz, buzz, highest):
result = []
for i in range(1, highest + 1):
letter = ''
if i % fizz == 0:
letter += 'F'
if i % buzz == 0:
letter += 'B'
if letter == '':
letter = str(i)
result.append(letter)
return ' '.join(resul... |
""" Implements some convenience logic for specifying item embedding dependencies.
In the context of invalidation scope, it is imperative that we embed all fields used in
default embeds (display_title). The hope is DependencyEmbedder will make it easy to do so, allowing
one to specify the dependencies in onl... | """ Implements some convenience logic for specifying item embedding dependencies.
In the context of invalidation scope, it is imperative that we embed all fields used in
default embeds (display_title). The hope is DependencyEmbedder will make it easy to do so, allowing
one to specify the dependencies in onl... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxProfit = 0
minValue = 10**5
for price in prices:
minValue = min(price, minValue)
maxProfit = max(price - minValue, maxProfit)
return maxProfit | class Solution:
def max_profit(self, prices: List[int]) -> int:
max_profit = 0
min_value = 10 ** 5
for price in prices:
min_value = min(price, minValue)
max_profit = max(price - minValue, maxProfit)
return maxProfit |
steps = []
def do_action(name):
steps.append(name)
WAREHOUSE_PHONE = '<phone number here e.g. +44712345678>'
SECRET_CODE = '<paste here>'
def handle_purchase():
"""
Here are the actions you can trigger:
calculate_price - Calculates total cost of the order
check_inventory - Checks that th... | steps = []
def do_action(name):
steps.append(name)
warehouse_phone = '<phone number here e.g. +44712345678>'
secret_code = '<paste here>'
def handle_purchase():
"""
Here are the actions you can trigger:
calculate_price - Calculates total cost of the order
check_inventory - Checks that the pro... |
class Node:
def __init__(self, element):
self.item = element
self.next_link = None
self.prev_link = None
class DoubleLinkedList:
def __init__(self):
self.first_node = None
def is_empty(self):
if self.first_node is None:
print("Error! The list is empty!"... | class Node:
def __init__(self, element):
self.item = element
self.next_link = None
self.prev_link = None
class Doublelinkedlist:
def __init__(self):
self.first_node = None
def is_empty(self):
if self.first_node is None:
print('Error! The list is empty!... |
"""
Pops the gear onto the peg. Uses solenoids.
"""
class GearSol(object):
def __init__(self, sol):
self.sol = sol
def run(self, trigger):
if (trigger == True):
self.sol.set(self.sol.Value.kForward)
else:
self.sol.set(self.sol.Value.kReverse)
| """
Pops the gear onto the peg. Uses solenoids.
"""
class Gearsol(object):
def __init__(self, sol):
self.sol = sol
def run(self, trigger):
if trigger == True:
self.sol.set(self.sol.Value.kForward)
else:
self.sol.set(self.sol.Value.kReverse) |
# Import the library that makes it easier to write context managers
# Implement a context manager that writes to a text file
# using a class:
class MyContextManager:
pass
# Implement a context manager using a method with a decorator
def my_context_manager():
raise Exception("Method not implemented")
def c... | class Mycontextmanager:
pass
def my_context_manager():
raise exception('Method not implemented')
def call_class_context_manager(file_name='class_hi.txt', text='hello', access_mode='w'):
with my_context_manager(file_name, access_mode) as f:
f.write(text)
def call_function_context_manager(file_name... |
# items implementation
class Item:
def __init__(self, item_name, item_description):
self.item_name = item_name
self.item_description = item_description
def __str__(self):
return '%s, %s' % (self.item_name, self.item_description)
| class Item:
def __init__(self, item_name, item_description):
self.item_name = item_name
self.item_description = item_description
def __str__(self):
return '%s, %s' % (self.item_name, self.item_description) |
# tiles
ONE_MAN = 0
TWO_MAN = 1
THREE_MAN = 2
FOUR_MAN = 3
FIVE_MAN = 4
SIX_MAN = 5
SEVEN_MAN = 6
EIGHT_MAN = 7
NINE_MAN = 8
ONE_PIN = 9
TWO_PIN = 10
THREE_PIN = 11
FOUR_PIN = 12
FIVE_PIN = 13
SIX_PIN = 14
SEVEN_PIN = 15
EIGHT_PIN = 16
NINE_PIN = 17
ONE_SOU = 18
TWO_SOU = 19
THREE_SOU = 20
FOUR_SOU = 21
FIVE_SOU = 22
S... | one_man = 0
two_man = 1
three_man = 2
four_man = 3
five_man = 4
six_man = 5
seven_man = 6
eight_man = 7
nine_man = 8
one_pin = 9
two_pin = 10
three_pin = 11
four_pin = 12
five_pin = 13
six_pin = 14
seven_pin = 15
eight_pin = 16
nine_pin = 17
one_sou = 18
two_sou = 19
three_sou = 20
four_sou = 21
five_sou = 22
six_sou =... |
garden_waitlist = ["Jiho", "Adam", "Sonny", "Alisha"]
garden_waitlist[1] = "Calla"
garden_waitlist[-1] = "Alex"
print(garden_waitlist)
| garden_waitlist = ['Jiho', 'Adam', 'Sonny', 'Alisha']
garden_waitlist[1] = 'Calla'
garden_waitlist[-1] = 'Alex'
print(garden_waitlist) |
#!/usr/bin/env python
# coding: utf-8
# p676
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self._words = dict() # type: dict[int, list[str]]
def buildDict(self, dict):
"""
Build a dictionary through a list of words
... | class Magicdictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self._words = dict()
def build_dict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
for wor... |
def one2two(digit):
if len(digit) == 1:
return "0" + digit
else:
return digit
def result(pt, st):
rt = ""
second, minute, hour = 0, 0, 0
sc, mc = 0, 0
if st[2] - pt[2] >= 0:
second = st[2] - pt[2]
else:
second = st[2] - pt[2] + 60
sc = 1
if st[... | def one2two(digit):
if len(digit) == 1:
return '0' + digit
else:
return digit
def result(pt, st):
rt = ''
(second, minute, hour) = (0, 0, 0)
(sc, mc) = (0, 0)
if st[2] - pt[2] >= 0:
second = st[2] - pt[2]
else:
second = st[2] - pt[2] + 60
sc = 1
i... |
n, m = map(int, input().split())
trees = list(map(int, input().split()))
minH = 0
maxH = max(trees)
ans = 0
while minH <= maxH:
cutH = (minH+maxH)//2
cutMount = 0
for tree in trees:
cutMount += (tree - cutH if tree >= cutH else 0)
if cutMount >= m:
ans = cutH
minH = cutH + 1
... | (n, m) = map(int, input().split())
trees = list(map(int, input().split()))
min_h = 0
max_h = max(trees)
ans = 0
while minH <= maxH:
cut_h = (minH + maxH) // 2
cut_mount = 0
for tree in trees:
cut_mount += tree - cutH if tree >= cutH else 0
if cutMount >= m:
ans = cutH
min_h = cut... |
class BaseInferer:
""" Base inferer class
"""
def infer(self, *args, **kwargs):
""" Perform an inference on test data.
"""
raise NotImplementedError
def fusion(self, submissions_dir, preds):
""" Ensamble predictions.
"""
raise NotImplementedError ... | class Baseinferer:
""" Base inferer class
"""
def infer(self, *args, **kwargs):
""" Perform an inference on test data.
"""
raise NotImplementedError
def fusion(self, submissions_dir, preds):
""" Ensamble predictions.
"""
raise NotImplementedError
... |
# Python - 2.7.6
def logical_calc(array, op):
logic = {
'AND': all,
'OR': any,
'XOR': lambda arr: bool(arr.count(True) & 1)
}
if op in logic:
return logic[op](array)
return False
| def logical_calc(array, op):
logic = {'AND': all, 'OR': any, 'XOR': lambda arr: bool(arr.count(True) & 1)}
if op in logic:
return logic[op](array)
return False |
# bluetooth device attributes
DEVICE_NAME = "TT Camera Slider"
MIN_POS = 0
MAX_POS = 0.9
MIN_DURATION = 0
MAX_DURATION = 500
MIN_SPEED = 0.002
MAX_SPEED = 0.25
# motor attributes
STEP_ANGLE = 1.8
VEL_TO_RPS = 9.88319028614 * 2 # 1/(2pi(r))
DIST_TO_STEPS = 1976.63805723 # (360)/(1.8*2pi(r)) ONLY for ms=0
RADIUS = 0.01... | device_name = 'TT Camera Slider'
min_pos = 0
max_pos = 0.9
min_duration = 0
max_duration = 500
min_speed = 0.002
max_speed = 0.25
step_angle = 1.8
vel_to_rps = 9.88319028614 * 2
dist_to_steps = 1976.63805723
radius = 0.0161036
default_velocity = 0.1
sleep_between_move = 2
dist_to_steps_e = 2.58064516129
vel_to_rps_e = ... |
"""
Hangman.
Authors: Nasser Hegar and YOUR_PARTNERS_NAME_HERE.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
# TODO: 2. Implement Hangman using your Iterative Enhancement Plan.
####### Do NOT attempt this assignment before class! #######
| """
Hangman.
Authors: Nasser Hegar and YOUR_PARTNERS_NAME_HERE.
""" |
def combinations_fixed_sum(fixed_sum, length_of_list, lst=[]):
if length_of_list == 1:
lst += [fixed_sum]
yield lst
else:
for i in range(fixed_sum+1):
yield from combinations_fixed_sum(i, length_of_list-1, lst + [fixed_sum-i])
def combinations_fixed_sum_limits(fixed_sum, length_of_list, minimum,... | def combinations_fixed_sum(fixed_sum, length_of_list, lst=[]):
if length_of_list == 1:
lst += [fixed_sum]
yield lst
else:
for i in range(fixed_sum + 1):
yield from combinations_fixed_sum(i, length_of_list - 1, lst + [fixed_sum - i])
def combinations_fixed_sum_limits(fixed_su... |
class LoginProviders:
google = "google"
facebook = "facebook"
github = "github"
twitter = "twitter"
login_providers = LoginProviders()
| class Loginproviders:
google = 'google'
facebook = 'facebook'
github = 'github'
twitter = 'twitter'
login_providers = login_providers() |
def startRightHand():
##############
i01.startRightHand(rightPort)
i01.rightHand.thumb.setMinMax(0,115)
i01.rightHand.index.setMinMax(35,130)
i01.rightHand.majeure.setMinMax(35,130)
i01.rightHand.ringFinger.setMinMax(35,130)
i01.rightHand.pinky.setMinMax(35,130)
i01.rightHand.wrist.map(90,90,90,... | def start_right_hand():
i01.startRightHand(rightPort)
i01.rightHand.thumb.setMinMax(0, 115)
i01.rightHand.index.setMinMax(35, 130)
i01.rightHand.majeure.setMinMax(35, 130)
i01.rightHand.ringFinger.setMinMax(35, 130)
i01.rightHand.pinky.setMinMax(35, 130)
i01.rightHand.wrist.map(90, 90, 90, 9... |
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
def to_bits(value):
return value * 1048576.0
def to_kilobits(value):
return value * 1048.58
def to_megabits(value):
return value * 1.04858
def to_gigabit... | def to_bits(value):
return value * 1048576.0
def to_kilobits(value):
return value * 1048.58
def to_megabits(value):
return value * 1.04858
def to_gigabits(value):
return value / 953.67431640625
def to_terabits(value):
return value / 953674.0
def to_kilobytes(value):
return value / 0.0076293... |
async def m001_initial(db):
"""
Creates an improved withdraw table and migrates the existing data.
"""
await db.execute(
"""
CREATE TABLE IF NOT EXISTS withdraw_links (
id TEXT PRIMARY KEY,
wallet TEXT,
title TEXT,
min_withdrawable INTEGER ... | async def m001_initial(db):
"""
Creates an improved withdraw table and migrates the existing data.
"""
await db.execute('\n CREATE TABLE IF NOT EXISTS withdraw_links (\n id TEXT PRIMARY KEY,\n wallet TEXT,\n title TEXT,\n min_withdrawable INTEGER DEFAUL... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | repo_root = 'io_bazel_rules_kotlin'
kotlin_repo_root = 'com_github_jetbrains_kotlin'
kotlin_info = provider(fields={'src': 'the source files. [intelij-aspect]', 'outputs': 'output jars produced by this rule. [intelij-aspect]'}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.