content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\autonomy\parameterized_autonomy_request_info.py
# Compiled at: 2016-09-08 21:38:24
# Size of source ... | class Parameterizedautonomyrequestinfo:
def __init__(self, commodities, static_commodities, objects, retain_priority, retain_carry_target=True, objects_to_ignore=None, affordances=None, randomization_override=None, radius_to_consider=0, consider_scores_of_zero=False, test_connectivity_to_target=True, retain_contex... |
def nswp(n):
if n < 2: return 1
a, b = 1, 1
for i in range(2, n + 1):
c = 2 * b + a
a = b
b = c
return b
n = 3
print(nswp(n))
| def nswp(n):
if n < 2:
return 1
(a, b) = (1, 1)
for i in range(2, n + 1):
c = 2 * b + a
a = b
b = c
return b
n = 3
print(nswp(n)) |
##def txt2BRAM2(CFile):
## """
## FUNCTION: txt2BRAM2(a str)
## a: text file name string
##
## - Initalizing a VHDL array with the contentes of a text file.
## """
##
# Python's variable declerations
#-------------------------------------------------------------------... | txt_file = ''
txt_file_name = ''
x = ''
s = ''
msg = ''
vhd_file_temp1 = ''
vhd_file_temp2 = ''
mem_file = ''
mem_filearr = []
bram0 = []
bram1 = []
bram2 = []
bram3 = []
bram4 = []
bram5 = []
bram6 = []
bram7 = []
bram8 = []
bram9 = []
bram10 = []
bram11 = []
bram12 = []
bram13 = []
bram14 = []
bram15 = []
bram16 = []... |
description = "Lowtemperature setup for SPHERES" \
"Contains: SIS, doppler, shutter, sps and cct6"
group = 'basic'
includes = ['spheres',
'cct6']
startupcode = """
cct6_c_temperature.samplestick = 'lt'\n
cct6_c_temperature.userlimits = (0, 350)
""" | description = 'Lowtemperature setup for SPHERESContains: SIS, doppler, shutter, sps and cct6'
group = 'basic'
includes = ['spheres', 'cct6']
startupcode = "\ncct6_c_temperature.samplestick = 'lt'\n\ncct6_c_temperature.userlimits = (0, 350)\n" |
def user_input():
'''
this function to get input from user
return to_currency, from_currency, date
'''
to_currency = input("what is your to currency code ? \n")
from_currency = input("what is your from currency code? \n")
date = input("what is your date? \n")
return to_cur... | def user_input():
"""
this function to get input from user
return to_currency, from_currency, date
"""
to_currency = input('what is your to currency code ? \n')
from_currency = input('what is your from currency code? \n')
date = input('what is your date? \n')
return (to_currency... |
def foo(arg1, *, kwarg1):
pass
def bar():
pass | def foo(arg1, *, kwarg1):
pass
def bar():
pass |
#
# PySNMP MIB module DECserver-Accounting-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DECserver-Accounting-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:22:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
def point_in_region(lower_left_corner, upper_right_corner, x, y):
return (
x >= lower_left_corner.x
and x <= upper_right_corner.x
and y >= lower_left_corner.y
and y <= upper_right_corner.y) | def point_in_region(lower_left_corner, upper_right_corner, x, y):
return x >= lower_left_corner.x and x <= upper_right_corner.x and (y >= lower_left_corner.y) and (y <= upper_right_corner.y) |
"""Programming support libraries.
The modules in this package
Module Summary
--------------
motleydatetime
Makes datetime manipulation easy and reliable. Potentially useful to any Python program
which uses the standard "datetime" module, especially when dealing with timezones or UTC datetimes.
... | """Programming support libraries.
The modules in this package
Module Summary
--------------
motleydatetime
Makes datetime manipulation easy and reliable. Potentially useful to any Python program
which uses the standard "datetime" module, especially when dealing with timezones or UTC datetimes.
... |
def duplicate_zeros(arr):
if 0 not in arr:
return arr
else:
array = []
for a in arr:
if a == 0:
array.extend([0, 0])
else:
array.append(a)
for i in range(len(arr)):
arr[i] = array[i] | def duplicate_zeros(arr):
if 0 not in arr:
return arr
else:
array = []
for a in arr:
if a == 0:
array.extend([0, 0])
else:
array.append(a)
for i in range(len(arr)):
arr[i] = array[i] |
class MinStack(object):
def __init__(self):
self.s = []
self.min_s = []
def push(self, x):
self.s.append(x)
if self.min_s:
if self.min_s[-1] > x:
self.min_s.append(x)
else:
self.min_s.append(self.min_s[-1])
else:
... | class Minstack(object):
def __init__(self):
self.s = []
self.min_s = []
def push(self, x):
self.s.append(x)
if self.min_s:
if self.min_s[-1] > x:
self.min_s.append(x)
else:
self.min_s.append(self.min_s[-1])
else:
... |
# Guest & items
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
# function: get amount of a item(allGuests, item)
def totalBrought(guests, item):
# initiate a counter
numBrought = 0
# traverse va... | all_guests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}}
def total_brought(guests, item):
num_brought = 0
for v in guests.values():
num_brought += v.get(item, 0)
return numBrought
food_set = set()
for v in allGuests.valu... |
# This problem was asked by Yahoo.
# Write an algorithm that computes the reversal of a directed graph.
# For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
####
graph1 = {}
graph1['A'] = ['B', 'C', 'D']
graph1['B'] = ['C', 'D']
graph1['C'] = ['D']
####
def reversegraph(gr):
ret = {}
... | graph1 = {}
graph1['A'] = ['B', 'C', 'D']
graph1['B'] = ['C', 'D']
graph1['C'] = ['D']
def reversegraph(gr):
ret = {}
for (beg, v) in gr.items():
for end in v:
ret[end] = ret.get(end, []) + [beg]
return ret
print(graph1)
print(reversegraph(graph1)) |
class Stack:
sizeof = 0
def __init__(self,list = None):
if list == None:
self.item =[]
else :
self.item = list
def push(self,i):
self.item.append(i)
def size(self):
return len(self.item)
def isEmpty(self):
if self.size()==0:
... | class Stack:
sizeof = 0
def __init__(self, list=None):
if list == None:
self.item = []
else:
self.item = list
def push(self, i):
self.item.append(i)
def size(self):
return len(self.item)
def is_empty(self):
if self.size() == 0:
... |
if __name__ == '__main__':
# This is a line printing Hello World
# This is a second line comment
'''
This is a line printing Hello World
This is a second line comment
'''
print("Hello World") # This is a comment
| if __name__ == '__main__':
'\n This is a line printing Hello World\n This is a second line comment\n '
print('Hello World') |
def mutate_string(string, position, character):
stringlist = list(string)
stringlist[position] = character
string = ''.join(stringlist)
return string
| def mutate_string(string, position, character):
stringlist = list(string)
stringlist[position] = character
string = ''.join(stringlist)
return string |
__all__ = [
'NoDestinationError',
'DocDoesNotExist'
]
class NoDestinationError(BaseException):
"""There is no destination Git Repo configured for this Document"""
class DocDoesNotExist(BaseException):
"""The PaperDoc being requested does not exist"""
| __all__ = ['NoDestinationError', 'DocDoesNotExist']
class Nodestinationerror(BaseException):
"""There is no destination Git Repo configured for this Document"""
class Docdoesnotexist(BaseException):
"""The PaperDoc being requested does not exist""" |
flowers = input()
amount_flowers = int(input())
budget = int(input())
final_price = 0
one_rose_price = 5
one_Dahlias_price = 3.80
one_Tulips_price = 2.80
one_Narcissus_price = 3
one_Gladiolus_price = 2.50
if flowers == "Roses":
final_price = amount_flowers * one_rose_price
if amount_flowers > 80:
fin... | flowers = input()
amount_flowers = int(input())
budget = int(input())
final_price = 0
one_rose_price = 5
one__dahlias_price = 3.8
one__tulips_price = 2.8
one__narcissus_price = 3
one__gladiolus_price = 2.5
if flowers == 'Roses':
final_price = amount_flowers * one_rose_price
if amount_flowers > 80:
final... |
def main():
dic = {
'wide': [
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_5.mscluster41.144549.out',
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_4.mscluster40.144548.out',
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_3.mscluster18.144536.out',
'logs/pipelines/all_pcgrl/... | def main():
dic = {'wide': ['logs/pipelines/all_pcgrl/pcgrl_smb_wide_5.mscluster41.144549.out', 'logs/pipelines/all_pcgrl/pcgrl_smb_wide_4.mscluster40.144548.out', 'logs/pipelines/all_pcgrl/pcgrl_smb_wide_3.mscluster18.144536.out', 'logs/pipelines/all_pcgrl/pcgrl_smb_wide_2.mscluster39.144547.out', 'logs/pipelines/... |
class ArXivAuthorNames:
def __init__(self, names_string):
self.names_string = self.__required(names_string)
def names(self):
"""
Converts name into a simple form suitable for the CrossRef search
"""
names = self.names_string.split(';')
out = list(map(self.__par... | class Arxivauthornames:
def __init__(self, names_string):
self.names_string = self.__required(names_string)
def names(self):
"""
Converts name into a simple form suitable for the CrossRef search
"""
names = self.names_string.split(';')
out = list(map(self.__pars... |
a=[5,20,15,20,25,50,20]
b=set(a)
b.remove(20)
print(b)
| a = [5, 20, 15, 20, 25, 50, 20]
b = set(a)
b.remove(20)
print(b) |
FEATKEY_NR_IMAGES = "nr_images"
FEATKEY_IMAGE_HEIGHT = "height"
FEATKEY_IMAGE_WIDTH = "width"
FEATKEY_ORIGINAL_HEIGHT = "original_height"
FEATKEY_ORIGINAL_WIDTH = "original_width"
FEATKEY_PATIENT_ID = "patient_id"
FEATKEY_LATERALITY = "laterality"
FEATKEY_VIEW = "view"
FEATKEY_IMAGE = "pixel_arr"
FEATKEY_IMAGE_ORIG = "... | featkey_nr_images = 'nr_images'
featkey_image_height = 'height'
featkey_image_width = 'width'
featkey_original_height = 'original_height'
featkey_original_width = 'original_width'
featkey_patient_id = 'patient_id'
featkey_laterality = 'laterality'
featkey_view = 'view'
featkey_image = 'pixel_arr'
featkey_image_orig = '... |
# DDA Algorithm
def draw_line(x0, y0, x1, y1):
dy = y1 - y0
dx = x1 - x0
m = dy / dx
current_y = y0
print(f'dy = {dy}')
print(f'dx = {dx}')
print(f'm = {m}')
for index in range (x0, x1 + 1):
print(f'x = {index}, y = {round(current_y)}')
current_y = curren... | def draw_line(x0, y0, x1, y1):
dy = y1 - y0
dx = x1 - x0
m = dy / dx
current_y = y0
print(f'dy = {dy}')
print(f'dx = {dx}')
print(f'm = {m}')
for index in range(x0, x1 + 1):
print(f'x = {index}, y = {round(current_y)}')
current_y = current_y + m
draw_line(2, 1, 7, 3) |
"""String constants.
Once defined, it becomes immutable.
"""
class _const:
class ConstError(TypeError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise... | """String constants.
Once defined, it becomes immutable.
"""
class _Const:
class Consterror(TypeError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError
self.__dict__[name] = value
def __delattr__(self, name):
if name in... |
""" Distributor init file
Distributors: you can add custom code here to support particular distributions
of numpy_demo.
For example, this is a good place to put any checks for hardware requirements.
The numpy_demo standard source distribution will not put code in this file, so you
can safely replace this file with y... | """ Distributor init file
Distributors: you can add custom code here to support particular distributions
of numpy_demo.
For example, this is a good place to put any checks for hardware requirements.
The numpy_demo standard source distribution will not put code in this file, so you
can safely replace this file with y... |
class Strategy:
moneymanagement = None
def __init__(self, moneymanagement):
self.moneymanagement = moneymanagement
def can_find_pattern(self, data):
if self.moneymanagement.checkDrawdown() < - float(self.moneymanagement.algorithm.Portfolio.Cash) * 0.1:
return False
r... | class Strategy:
moneymanagement = None
def __init__(self, moneymanagement):
self.moneymanagement = moneymanagement
def can_find_pattern(self, data):
if self.moneymanagement.checkDrawdown() < -float(self.moneymanagement.algorithm.Portfolio.Cash) * 0.1:
return False
retur... |
# Attribute types
STRING = 1
NUMBER = 2
DATETIME = 3
# Analysis Types
SENTIMENT_ANALYSIS = 1
DOCUMENT_CLUSTERING = 2
CONCEPT_EXTRACTION = 3
DOCUMENT_CLASSIFICATION = 4
# Analysis Status
NOT_EXECUTED = 1
IN_PROGRESS = 2
EXECUTED = 3
# Creation Status
DRAFT = 1
COMPLETED = 2
# Visibilities
PUBLIC = 1
PRIVATE = 2
TEAM... | string = 1
number = 2
datetime = 3
sentiment_analysis = 1
document_clustering = 2
concept_extraction = 3
document_classification = 4
not_executed = 1
in_progress = 2
executed = 3
draft = 1
completed = 2
public = 1
private = 2
team = 3 |
#!/usr/bin/env python3
# coding:utf-8
f = open("yankeedoodle.csv")
nums = [num.strip() for num in f.read().split(',')]
f.close()
res = [int(x[0][5] + x[1][5] + x[2][6]) for x in zip(nums[0::3], nums[1::3], nums[2::3])]
print(''.join([chr(e) for e in res]))
| f = open('yankeedoodle.csv')
nums = [num.strip() for num in f.read().split(',')]
f.close()
res = [int(x[0][5] + x[1][5] + x[2][6]) for x in zip(nums[0::3], nums[1::3], nums[2::3])]
print(''.join([chr(e) for e in res])) |
hex_colors = {
"COLOR_1": "#d9811e",
"TEXT_BUTTON_LIGHT": "#000000",
"BUTTON_1": "#dfdfdf",
"BACKGROUND": "#dfdfdf",
"LABEL_TEXT_COLOR_LIGHT": "black",
"FRAME_1_DARK": "#2b2b42",
"TEXT_BUTTON_DARK": "white",
"BUTTON_DARK": "#292929",
"BACKGROUND_DARK": "#292929",
"LABEL_TEXT_CO... | hex_colors = {'COLOR_1': '#d9811e', 'TEXT_BUTTON_LIGHT': '#000000', 'BUTTON_1': '#dfdfdf', 'BACKGROUND': '#dfdfdf', 'LABEL_TEXT_COLOR_LIGHT': 'black', 'FRAME_1_DARK': '#2b2b42', 'TEXT_BUTTON_DARK': 'white', 'BUTTON_DARK': '#292929', 'BACKGROUND_DARK': '#292929', 'LABEL_TEXT_COLOR_DARK': 'white'}
custom_size = {'init_wi... |
## Mel-filterbank
mel_window_length = 25 # In milliseconds
mel_window_step = 10 # In milliseconds
mel_n_channels = 40
## Audio
sampling_rate = 16000
# Number of spectrogram frames in a partial utterance
partials_n_frames = 160 # 1600 ms
## Voice Activation Detection
vad_window_length = 30 # In millisecond... | mel_window_length = 25
mel_window_step = 10
mel_n_channels = 40
sampling_rate = 16000
partials_n_frames = 160
vad_window_length = 30
vad_moving_average_width = 8
vad_max_silence_length = 6
audio_norm_target_d_bfs = -30
model_hidden_size = 256
model_embedding_size = 256
model_num_layers = 3 |
#python3
for t in range(int(input())):
count = 0
s,w1,w2,w3 = map(int,input().split())
if((w1+w2+w3)<=s):
count = 1
elif((w1+w2)<=s):
if(w3 <= s):
count = 2
else:
count = 1
elif((w2+w3)<=s):
if(w3 <= s):
count = 2
else:... | for t in range(int(input())):
count = 0
(s, w1, w2, w3) = map(int, input().split())
if w1 + w2 + w3 <= s:
count = 1
elif w1 + w2 <= s:
if w3 <= s:
count = 2
else:
count = 1
elif w2 + w3 <= s:
if w3 <= s:
count = 2
else:
... |
# ================================================= #
# Trash Guy Animation #
# (> ^_^)> #
# Made by Zac (trashguy@zac.cy) #
# Version 4.1.0+20201210 #
# Donate: ... | _lut = ((0, 7), (0, 7), (0, 7), (0, 7), (0, 7), (0, 7), (0, 7), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (1, 9), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (2, 11), (3, 13), (3, 13), (3, 13), (3, 13), (3, 13), (3, 13), (3, 13), (3, 13), (3, 13), (3, ... |
with open('F_T_W copy/ada_fund.json') as f:
data = json.load(f)
print(data)
| with open('F_T_W copy/ada_fund.json') as f:
data = json.load(f)
print(data) |
class Dice(object):
__slots__ = ['sides']
def __init__(self, sides):
self.sides = sides
class DiceStack(object):
__slots__ = ['amount', 'dice']
def __init__(self, amount, dice):
self.amount = amount
self.dice = dice | class Dice(object):
__slots__ = ['sides']
def __init__(self, sides):
self.sides = sides
class Dicestack(object):
__slots__ = ['amount', 'dice']
def __init__(self, amount, dice):
self.amount = amount
self.dice = dice |
_cmds_registry = {}
def register(cmd:str, alias:str) -> bool:
if alias in _cmds_registry:
return False
else:
_cmds_registry[alias] = cmd
return True
def get_cmd(alias:str) -> str:
if alias in _cmds_registry:
return _cmds_registry[alias]
else:
return ''
| _cmds_registry = {}
def register(cmd: str, alias: str) -> bool:
if alias in _cmds_registry:
return False
else:
_cmds_registry[alias] = cmd
return True
def get_cmd(alias: str) -> str:
if alias in _cmds_registry:
return _cmds_registry[alias]
else:
return '' |
def word_form(number):
ones = ('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine')
tens = ('', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety')
teens = ('ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
... | def word_form(number):
ones = ('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine')
tens = ('', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')
teens = ('ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', ... |
""" Settings default definition for Nine CMS """
__author__ = 'George Karakostas'
__copyright__ = 'Copyright 2015, George Karakostas'
__licence__ = 'BSD-3'
__email__ = 'gkarak@9-dev.com'
""" Default recommended settings """
# INSTALLED_APPS = (
# 'admin_bootstrapped_plus',
# # 'bootstrap3',
# 'django_admin... | """ Settings default definition for Nine CMS """
__author__ = 'George Karakostas'
__copyright__ = 'Copyright 2015, George Karakostas'
__licence__ = 'BSD-3'
__email__ = 'gkarak@9-dev.com'
' Default recommended settings '
' Test '
' Live '
' CMS '
site_name = '9cms'
site_author = '9cms'
site_keywords = ''
image_styles = ... |
__author__ = 'Ladeinde Oluwaseun'
__copyright__ = 'Copyright 2018, Ladeinde Oluwaseun'
__credits__ = ['Ladeinde Oluwaseun, amordigital']
__license__ = 'BSD'
__version__ = '1.5.1'
__maintainer__ = 'Ladeinde Oluwaseun'
__email__ = 'oluwaseun.ladeinde@gmail.com'
__status__ = 'Development'
| __author__ = 'Ladeinde Oluwaseun'
__copyright__ = 'Copyright 2018, Ladeinde Oluwaseun'
__credits__ = ['Ladeinde Oluwaseun, amordigital']
__license__ = 'BSD'
__version__ = '1.5.1'
__maintainer__ = 'Ladeinde Oluwaseun'
__email__ = 'oluwaseun.ladeinde@gmail.com'
__status__ = 'Development' |
a=10
b=5
print('Addition:', a+b)
print('Substraction: ', a-b)
print('Multiplication:', a*b)
print('Division: ', a/b)
print('Remainder: ', a%b)
print('Exponential:', a ** b) | a = 10
b = 5
print('Addition:', a + b)
print('Substraction: ', a - b)
print('Multiplication:', a * b)
print('Division: ', a / b)
print('Remainder: ', a % b)
print('Exponential:', a ** b) |
CHUNK_SIZE = (1024**2) * 50
file_number = 1
with open('encoder-5-3000.pkl', 'rb') as f:
chunk = f.read(CHUNK_SIZE)
while chunk:
with open('encoder-5-3000_part_' + str(file_number), 'wb') as chunk_file:
chunk_file.write(chunk)
file_number += 1
chunk = f.read(CHUNK_SIZE)
| chunk_size = 1024 ** 2 * 50
file_number = 1
with open('encoder-5-3000.pkl', 'rb') as f:
chunk = f.read(CHUNK_SIZE)
while chunk:
with open('encoder-5-3000_part_' + str(file_number), 'wb') as chunk_file:
chunk_file.write(chunk)
file_number += 1
chunk = f.read(CHUNK_SIZE) |
def app(amb , start_response):
arq=open('index.html','rb')
data = arq.read()
status = "200 OK"
headers = [('Content-type',"text/html")]
start_response(status,headers)
return [data] | def app(amb, start_response):
arq = open('index.html', 'rb')
data = arq.read()
status = '200 OK'
headers = [('Content-type', 'text/html')]
start_response(status, headers)
return [data] |
#!/usr/bin/env python3
SIZE = 100
with open('03-output.pbm', 'wb') as f:
f.write(b'P4\n100 100\n')
for i in range(SIZE):
counter = 0
xs = b''
for j in range(SIZE):
counter += 1
if (i + j) % 2 == 0:
xs += b'1'
else:
xs ... | size = 100
with open('03-output.pbm', 'wb') as f:
f.write(b'P4\n100 100\n')
for i in range(SIZE):
counter = 0
xs = b''
for j in range(SIZE):
counter += 1
if (i + j) % 2 == 0:
xs += b'1'
else:
xs += b'0'
if co... |
#
# PySNMP MIB module RSTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RSTP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:50:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
class Payment:
"""Class for handling payments
"""
def __init__(self):
self.flag_1 = 1
def payment_process(self, dist, delivery_charge, bill, time_avg, delivery_time):
"""Print final invoice generated with details
Args:
dist (float): Distance b/w user and... | class Payment:
"""Class for handling payments
"""
def __init__(self):
self.flag_1 = 1
def payment_process(self, dist, delivery_charge, bill, time_avg, delivery_time):
"""Print final invoice generated with details
Args:
dist (float): Distance b/w user and restaurant... |
"""
File: settings.py
------------------------
This file holds all the constant variables
so that they can be globally called upon
and accessed by all of the other programs
"""
LEXICON_FILE = "Lexicon.txt" # File to read word list from
SCORE_FILE = 'highscores.txt' # File that stores all the scores
GRID_DIMENSIO... | """
File: settings.py
------------------------
This file holds all the constant variables
so that they can be globally called upon
and accessed by all of the other programs
"""
lexicon_file = 'Lexicon.txt'
score_file = 'highscores.txt'
grid_dimension = 10
time_limit = 90
window_width = 1000
window_height = 600
vertica... |
#Done by Carlos Amaral in 16/07/2020
"""
Write a function that accepts two parameters: a city name
and a country name. The function should return a single string of the form
City, Country , such as Santiago, Chile . Store the function in a module called
city _functions.py.
Create a file called test_cities.py that test... | """
Write a function that accepts two parameters: a city name
and a country name. The function should return a single string of the form
City, Country , such as Santiago, Chile . Store the function in a module called
city _functions.py.
Create a file called test_cities.py that tests the function you just wrote
(remembe... |
#..............example 1 combine................
# s = "ABC"
# s2 = "123"
# L = [x+y for x in s for y in s2]
# print(L)
#..............example 2 remove duplicates................
# L = [1, 3, 2, 1, 6, 4, 2, 98, 82]
# L2 = []
# for x in L:
# if x not in L2:
# L2.append(x)
# print(L2)
#.......... | l = [1, 1]
while len(L) < 40:
L.append(L[-1] + L[-2])
print(L) |
""" var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls, name):
"fetch var with given name"
return cls.list(name=name)[0]
@classmethod
def next(cls, name, advance=True):
"give (and, if advance, then increment) a counter variable"... | """ var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls, name):
"""fetch var with given name"""
return cls.list(name=name)[0]
@classmethod
def next(cls, name, advance=True):
"""give (and, if advance, then increment) a counter var... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# __doc__ string
# _
__doc__ = """test of ocs_common"""
# +
# function: test_ocs_common() to keep py.test happy
# -
def test_ocs_common():
assert True
| __doc__ = 'test of ocs_common'
def test_ocs_common():
assert True |
def main(request, response):
headers = []
if "cors" in request.GET:
headers.append(("Access-Control-Allow-Origin", "*"))
headers.append(("Access-Control-Allow-Credentials", "true"))
headers.append(("Access-Control-Allow-Methods", "GET, POST, PUT, FOO"))
headers.append(("Access-Co... | def main(request, response):
headers = []
if 'cors' in request.GET:
headers.append(('Access-Control-Allow-Origin', '*'))
headers.append(('Access-Control-Allow-Credentials', 'true'))
headers.append(('Access-Control-Allow-Methods', 'GET, POST, PUT, FOO'))
headers.append(('Access-Co... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_jar")
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazelrio//:deps_utils.bzl", "cc_library_headers", "cc_library_shared", "cc_library_sourc... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive', 'http_jar')
load('@bazel_tools//tools/build_defs/repo:jvm.bzl', 'jvm_maven_import_external')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazelrio//:deps_utils.bzl', 'cc_library_headers', 'cc_library_shared', 'cc_library_sourc... |
class Display(object):
@classmethod
def getColumns(cls):
raise NotImplementedError
@classmethod
def getRows(cls):
raise NotImplementedError
@classmethod
def getRowText(cls, row):
raise NotImplementedError
def show(self):
for i in range(int(self.getRows())):... | class Display(object):
@classmethod
def get_columns(cls):
raise NotImplementedError
@classmethod
def get_rows(cls):
raise NotImplementedError
@classmethod
def get_row_text(cls, row):
raise NotImplementedError
def show(self):
for i in range(int(self.getRows... |
def fact(a):
if a<=1:
return 1
return a*fact(a-1)
a = int(input())
for i in range(a):
n=int(input())
print(fact(n))
| def fact(a):
if a <= 1:
return 1
return a * fact(a - 1)
a = int(input())
for i in range(a):
n = int(input())
print(fact(n)) |
#!/usr/bin/env python
# coding: utf-8
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return 0
prod = nums[0]
head, tail = 0, 0
count = 0
w... | class Solution:
def num_subarray_product_less_than_k(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return 0
prod = nums[0]
(head, tail) = (0, 0)
count = 0
while tail < len(nums):
... |
""" Binary Search Algortihm
--------------------------------------------------
"""
#iterative implementation of binary search in Python def binary_search(a+list, item):
""" Performs iterative bonary search to find the position of an integer in a given, sorted, list.
a_list -- sorted list of integers
item -- integer yo... | """ Binary Search Algortihm
--------------------------------------------------
"""
' Performs iterative bonary search to find the position of an integer in a given, sorted, list.\n a_list -- sorted list of integers\nitem -- integer you are searching for the position of\n'
first = 0
last = len(a_list) - 1
while first <=... |
'''
package fitnesse.slim;
import java.util.List;
import fitnesse.util.ListUtility;
'''
'''
Packs up a list into a serialized string using a special format. The list items must be strings, or lists.
They will be recursively serialized.
Format: [iiiiii:llllll:item...]
All lists (including lists within lists) ... | """
package fitnesse.slim;
import java.util.List;
import fitnesse.util.ListUtility;
"""
'\n Packs up a list into a serialized string using a special format. The list items must be strings, or lists.\n They will be recursively serialized.\n \n Format: [iiiiii:llllll:item...]\n All lists (including lists within lists... |
def selection_sort(array):
N = len(array)
for i in range(N):
# Find the min element in the unsorted a[i .. N - 1]
# Assume the min is the first element.
minimum_element_index = i
for j in range(i + 1, N):
if (array[j] < array[minimum_element_index]):
... | def selection_sort(array):
n = len(array)
for i in range(N):
minimum_element_index = i
for j in range(i + 1, N):
if array[j] < array[minimum_element_index]:
minimum_element_index = j
if minimum_element_index != i:
(array[i], array[minimum_element_i... |
width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"
rf"result: {value:{width}.{precision}}"
foo(f'this SHOULD be a multi-line string because it is '
f'very long and does not fit on one line. And {value} is the value.')
foo('this SHOULD be a multi-line string, but no... | width = 10
precision = 4
value = decimal.Decimal('12.34567')
f'result: {value:{width}.{precision}}'
f'result: {value:{width}.{precision}}'
foo(f'this SHOULD be a multi-line string because it is very long and does not fit on one line. And {value} is the value.')
foo(f'this SHOULD be a multi-line string, but not reflowed... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: May 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate string concatenation
noun = input("Enter a singular noun: ")
print("The plural of "+noun+" is "+noun+"s")
| noun = input('Enter a singular noun: ')
print('The plural of ' + noun + ' is ' + noun + 's') |
elements = {
0: {
"element": 0,
"description": "",
"dynamic": False,
"bitmap": False,
"len": 0,
"format": "",
"start_position": 0,
"end_position": 0
},
1: {
"element": 1,
"description": "Bitmap Secondary",
"dynamic": Fal... | elements = {0: {'element': 0, 'description': '', 'dynamic': False, 'bitmap': False, 'len': 0, 'format': '', 'start_position': 0, 'end_position': 0}, 1: {'element': 1, 'description': 'Bitmap Secondary', 'dynamic': False, 'bitmap': True, 'len': 16, 'format': 'AN', 'start_position': 0, 'end_position': 16}, 3: {'element': ... |
def write_html(messages):
file = open("messages.html","w")
html = []
html.append('<html>\n<head>\n\t<meta http-equiv="Content-Type" content = "text/html" charset=UTF-8 >\n')
html.append('\t<link rel="stylesheet" href="body.css">\n')
html.append('\t<base href="../../"/>\n')
html.append('\t<title>... | def write_html(messages):
file = open('messages.html', 'w')
html = []
html.append('<html>\n<head>\n\t<meta http-equiv="Content-Type" content = "text/html" charset=UTF-8 >\n')
html.append('\t<link rel="stylesheet" href="body.css">\n')
html.append('\t<base href="../../"/>\n')
html.append('\t<title... |
class ViradaCulturalSpider(CrawlSpider):
name = "virada_cultural"
start_urls = ["http://conteudo.icmc.usp.br/Portal/conteudo/484/243/alunos-especiais"]
def parse(self, response):
self.logger.info('A response from %s just arrived!', response.url)
| class Viradaculturalspider(CrawlSpider):
name = 'virada_cultural'
start_urls = ['http://conteudo.icmc.usp.br/Portal/conteudo/484/243/alunos-especiais']
def parse(self, response):
self.logger.info('A response from %s just arrived!', response.url) |
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
darkBlue = (0,0,128)
white = (255,255,255)
black = (0,0,0)
pink = (255,200,200)
| red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
dark_blue = (0, 0, 128)
white = (255, 255, 255)
black = (0, 0, 0)
pink = (255, 200, 200) |
def createWordList(filename):
text_file= open(filename,"r")
temp = text_file.read().split("\n")
text_file.close()
temp.pop() #remove the last new line
return temp
def canWeMakeIt(myWord, myLetters):
listLetters=[]
for letter in myLetters:
listLetters.append (letter)
for x in m... | def create_word_list(filename):
text_file = open(filename, 'r')
temp = text_file.read().split('\n')
text_file.close()
temp.pop()
return temp
def can_we_make_it(myWord, myLetters):
list_letters = []
for letter in myLetters:
listLetters.append(letter)
for x in myWord:
if x... |
expected_output = {
"BDI3147": {
"interface": "BDI3147",
"redirects_disable": False,
"address_family": {
"ipv4": {
"version": {
1: {
"groups": {
31: {
"group_nu... | expected_output = {'BDI3147': {'interface': 'BDI3147', 'redirects_disable': False, 'address_family': {'ipv4': {'version': {1: {'groups': {31: {'group_number': 31, 'hsrp_router_state': 'active', 'statistics': {'num_state_changes': 17}, 'last_state_change': '12w6d', 'primary_ipv4_address': {'address': '10.190.99.49'}, 'v... |
# User Configuration variable settings for pitimolo
# Purpose - Motion Detection Security Cam
# Created - 20-Jul-2015 pi-timolo ver 2.94 compatible or greater
# Done by - Claude Pageau
configTitle = "pi-timolo default config motion"
configName = "pi-timolo-default-config"
# These settings should both be False if thi... | config_title = 'pi-timolo default config motion'
config_name = 'pi-timolo-default-config'
verbose = True
log_data_to_file = True
debug = False
image_test_print = False
image_name_prefix = 'cam1-'
image_width = 1024
image_height = 768
image_v_flip = False
image_h_flip = False
image_rotation = 0
image_preview = False
no_... |
# This problem was asked by Facebook.
# Given a binary tree, return all paths from the root to leaves.
# For example, given the tree:
# 1
# / \
# 2 3
# / \
# 4 5
# Return [[1, 2], [1, 3, 4], [1, 3, 5]].
def getPaths(tree, path):
left = None
if tree.left:
left = getPaths(tree.left, path + [tree... | def get_paths(tree, path):
left = None
if tree.left:
left = get_paths(tree.left, path + [tree.value])
right = None
if tree.right:
right = get_paths(tree.right, path + [tree.value])
merged_list = []
if left:
merged_list = mergedList + left
if right:
merged_list... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : __init__.py
# Author : yang <mightyang@hotmail.com>
# Date : 10.03.2019
# Last Modified Date: 11.03.2019
# Last Modified By : yang <mightyang@hotmail.com>
__all__ = ['pkgProj']
# from . import *
| __all__ = ['pkgProj'] |
# Sum square difference
# Answer: 25164150
def sum_of_the_squares(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
total += i ** 2
return total
def square_of_the_sum(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
t... | def sum_of_the_squares(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
total += i ** 2
return total
def square_of_the_sum(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
total += i
return total ** 2
def sum_square_difference... |
# import pytest
def test_query_no_join(connection):
query = connection.get_sql_query(metrics=["total_item_revenue"], dimensions=["channel"])
correct = (
"SELECT order_lines.sales_channel as order_lines_channel,"
"SUM(order_lines.revenue) as order_lines_total_item_revenue "
"FROM anal... | def test_query_no_join(connection):
query = connection.get_sql_query(metrics=['total_item_revenue'], dimensions=['channel'])
correct = 'SELECT order_lines.sales_channel as order_lines_channel,SUM(order_lines.revenue) as order_lines_total_item_revenue FROM analytics.order_line_items order_lines GROUP BY order_li... |
#%%
def validate_velocity_derivative():
pass
#%%
trial = 's1x2i7x5'
subject = 'AB01'
joint = 'jointangles_shank_x'
filename = '../local-storage/test/dataport_flattened_partial_{}.parquet'.format(subject)
df = pd.read_parquet(filename)
trial_df = df[df['trial'] == trial]
... | def validate_velocity_derivative():
pass
trial = 's1x2i7x5'
subject = 'AB01'
joint = 'jointangles_shank_x'
filename = '../local-storage/test/dataport_flattened_partial_{}.parquet'.format(subject)
df = pd.read_parquet(filename)
trial_df = df[df['trial'] == trial]
model_foot_dot = model_lo... |
# Inheritance in coding is when one "child" class receives
# all of the methods and attributes of another "parent" class
class Test:
def __init__(self):
self.x = 0
# class Derived_Test inherits from class Test
class Derived_Test(Test):
def __init__(self):
Test.__init__(self) # do Test's __i... | class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1
b = derived__test()
print(b.x, b.y) |
DEFAULT_NUM_IMAGES = 40
LOWER_LIMIT = 0
UPPER_LIMIT = 100
class MissingConfigException(Exception):
pass
class ImageLimitException(Exception):
pass
def init(config):
if (config is None):
raise MissingConfigException()
raise NotImplementedError
def download(num_images):
images_to_down... | default_num_images = 40
lower_limit = 0
upper_limit = 100
class Missingconfigexception(Exception):
pass
class Imagelimitexception(Exception):
pass
def init(config):
if config is None:
raise missing_config_exception()
raise NotImplementedError
def download(num_images):
images_to_download ... |
#new file as required
print ('ne1')
print ('ne2')
#C:\Users\kpmis\OneDrive\Documents\GitHub\wowmeter\new1.py
| print('ne1')
print('ne2') |
"""Convert Big-5 to UTF-8 and fix some trailing commas"""
with open("data/tetfp.csv", "rb") as f:
with open("data/tetfp_fixed.csv", "wb") as f2:
for line in f.readlines():
line = line.decode("big5").strip()
if line.endswith(","):
f2.write((line[:-1] + "\n").encode("ut... | """Convert Big-5 to UTF-8 and fix some trailing commas"""
with open('data/tetfp.csv', 'rb') as f:
with open('data/tetfp_fixed.csv', 'wb') as f2:
for line in f.readlines():
line = line.decode('big5').strip()
if line.endswith(','):
f2.write((line[:-1] + '\n').encode('ut... |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=0)
config.add_route('home', '/')
config.add_route('auth', '/auth')
config.add_route('add-stock', '/add-stock')
config.add_route('logout', '/logout')
config.add_route('portfolio', '/portfolio')
config.add_route('s... | def includeme(config):
config.add_static_view('static', 'static', cache_max_age=0)
config.add_route('home', '/')
config.add_route('auth', '/auth')
config.add_route('add-stock', '/add-stock')
config.add_route('logout', '/logout')
config.add_route('portfolio', '/portfolio')
config.add_route('s... |
######################################################################
#
# File: b2sdk/transfer/transfer_manager.py
#
# Copyright 2022 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
class TransferMan... | class Transfermanager:
"""
Base class for manager classes (copy, upload, download)
"""
def __init__(self, services, **kwargs):
self.services = services
super().__init__(**kwargs) |
#! python3
# -*- coding: utf-8 -*-
class OdoleniumError(Exception):
def __init__(self, msg):
super().__init__(msg)
| class Odoleniumerror(Exception):
def __init__(self, msg):
super().__init__(msg) |
def oeis_transform(seq: list):
"""
This function will receive an OEIS sequence, you should return the sequence after applying your transformation
"""
return seq
def input_transform(seq: list):
"""
This function will receive the input sequence, you should return the sequence after applying yo... | def oeis_transform(seq: list):
"""
This function will receive an OEIS sequence, you should return the sequence after applying your transformation
"""
return seq
def input_transform(seq: list):
"""
This function will receive the input sequence, you should return the sequence after applying your ... |
"""
This package is the central point to find nice utilities in Matils.
Check out the code documentation it is very rich and provides informations and
valuable examples to start playing with Matils.
"""
| """
This package is the central point to find nice utilities in Matils.
Check out the code documentation it is very rich and provides informations and
valuable examples to start playing with Matils.
""" |
"""
Given an integer (signed 32 bits), write a function to check whether it is
a power of 4.
Example:
Input: 16
Output: true
Follow up: Could you solve it without loops/recursion?
"""
#Difficulty: Easy
#1060 / 1060 test cases passed.
#Runtime: 28 ms
#Memory Usage: 13.6 MB
#Runtime: 28 ms, fa... | """
Given an integer (signed 32 bits), write a function to check whether it is
a power of 4.
Example:
Input: 16
Output: true
Follow up: Could you solve it without loops/recursion?
"""
class Solution:
def is_power_of_four(self, num: int) -> bool:
if num != 0:
return (... |
while True:
print('-' * 50)
num = int(input('Quer ver a tabuada de qual valor? '))
print('-'*50)
if num < 0:
break
for i in range(1,11):
print(f'{num} x {i} = {num*i}')
print('Programa finalizado. \nObrigado e volte sempre!') | while True:
print('-' * 50)
num = int(input('Quer ver a tabuada de qual valor? '))
print('-' * 50)
if num < 0:
break
for i in range(1, 11):
print(f'{num} x {i} = {num * i}')
print('Programa finalizado. \nObrigado e volte sempre!') |
def get_code_langs():
return [[164, 'MPASM', True],
[165, 'MXML', True],
[166, 'MySQL', True],
[167, 'Nagios', True],
[160, 'MIX Assembler', True],
[161, 'Modula 2', True],
[162, 'Modula 3', True],
[163, 'Motorola 68000 HiSoft Dev',... | def get_code_langs():
return [[164, 'MPASM', True], [165, 'MXML', True], [166, 'MySQL', True], [167, 'Nagios', True], [160, 'MIX Assembler', True], [161, 'Modula 2', True], [162, 'Modula 3', True], [163, 'Motorola 68000 HiSoft Dev', True], [173, 'NullSoft Installer', True], [174, 'Oberon 2', True], [175, 'Objeck Pr... |
'''
TODO:
def get_wrapper
def get_optimizer
''' | """
TODO:
def get_wrapper
def get_optimizer
""" |
"""
day1ab - https://adventofcode.com/2020/day/1
Part 1 - 1019571
Part 2 - 100655544
"""
def load_data():
numbers = []
datafile = 'input-day1'
with open(datafile, 'r') as input:
for line in input:
num = line.strip()
numbers.append(int(num))
return numbers
def par... | """
day1ab - https://adventofcode.com/2020/day/1
Part 1 - 1019571
Part 2 - 100655544
"""
def load_data():
numbers = []
datafile = 'input-day1'
with open(datafile, 'r') as input:
for line in input:
num = line.strip()
numbers.append(int(num))
return numbers
def part1(num... |
"""
File: caesar.py
Name: Yujing Wei
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic... | """
File: caesar.py
Name: Yujing Wei
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
... |
_base_ = 'fcos_r50_caffe_fpn_gn-head_1x_coco.py'
model = dict(
pretrained='open-mmlab://detectron2/resnet50_caffe',
backbone=dict(
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True)),
bbox_head=dict(
norm_on_bbox=True,
... | _base_ = 'fcos_r50_caffe_fpn_gn-head_1x_coco.py'
model = dict(pretrained='open-mmlab://detectron2/resnet50_caffe', backbone=dict(dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True)), bbox_head=dict(norm_on_bbox=True, centerness_on_reg=True, dcn_on_last_conv=True, ... |
#!/usr/bin/env python3
bank = [0, 2, 7, 0]
bank = [0, 5, 10, 0, 11, 14, 13, 4, 11, 8, 8, 7, 1, 4, 12, 11]
visited = {}
steps = 0
l = len(bank)
while tuple(bank) not in visited:
visited[tuple(bank)] = steps
m = max(bank)
i = bank.index(m)
bank[i] = 0 # Set the item to 0
quotient = m // l
bank ... | bank = [0, 2, 7, 0]
bank = [0, 5, 10, 0, 11, 14, 13, 4, 11, 8, 8, 7, 1, 4, 12, 11]
visited = {}
steps = 0
l = len(bank)
while tuple(bank) not in visited:
visited[tuple(bank)] = steps
m = max(bank)
i = bank.index(m)
bank[i] = 0
quotient = m // l
bank = [x + quotient for x in bank]
remainder =... |
def reorder_boxes(boxes):
boxes.sort()
ans = list()
for i in range(len(boxes) - 1, -1, -2):
if i - 1 >= 0:
ans.append(boxes[i] + boxes[i - 1])
else:
ans.append(boxes[i])
return ans
print(reorder_boxes([1, 2, 3, 4, 5, 6, 7]))
| def reorder_boxes(boxes):
boxes.sort()
ans = list()
for i in range(len(boxes) - 1, -1, -2):
if i - 1 >= 0:
ans.append(boxes[i] + boxes[i - 1])
else:
ans.append(boxes[i])
return ans
print(reorder_boxes([1, 2, 3, 4, 5, 6, 7])) |
def sleep(seconds: float):
pass
def sleep_ms(millis: int):
pass
def sleep_us(micros: int):
pass | def sleep(seconds: float):
pass
def sleep_ms(millis: int):
pass
def sleep_us(micros: int):
pass |
class IEntry:
"""
* Entry interface - this will be shared across the projects
"""
SOURCE_CLI = 'cli'
SOURCE_GET = 'get'
SOURCE_POST = 'post'
SOURCE_FILES = 'files'
SOURCE_COOKIE = 'cookie'
SOURCE_SESSION = 'session'
SOURCE_SERVER = 'server'
SOURCE_ENV = 'environment'
S... | class Ientry:
"""
* Entry interface - this will be shared across the projects
"""
source_cli = 'cli'
source_get = 'get'
source_post = 'post'
source_files = 'files'
source_cookie = 'cookie'
source_session = 'session'
source_server = 'server'
source_env = 'environment'
sou... |
for i in range(1, 11):
for j in range(1, 11):
a = i * j
if a < 10:
a = " " + str(a)
elif a < 100:
a = " " + str(a)
else:
a = str(a)
print(a, end=" ")
print()
| for i in range(1, 11):
for j in range(1, 11):
a = i * j
if a < 10:
a = ' ' + str(a)
elif a < 100:
a = ' ' + str(a)
else:
a = str(a)
print(a, end=' ')
print() |
class GaiaUtils:
@staticmethod
def convert_positive_int(param):
param = int(param)
if param < 1:
raise ValueError
return param | class Gaiautils:
@staticmethod
def convert_positive_int(param):
param = int(param)
if param < 1:
raise ValueError
return param |
class Attachment:
_SUPPORTED_MIME_TYPES = [
"application/vnd.google-apps.audio",
"application/vnd.google-apps.document", # Google Docs
"application/vnd.google-apps.drawing", # Google Drawing
"application/vnd.google-apps.file", # Google Drive file
"application/vnd.google-ap... | class Attachment:
_supported_mime_types = ['application/vnd.google-apps.audio', 'application/vnd.google-apps.document', 'application/vnd.google-apps.drawing', 'application/vnd.google-apps.file', 'application/vnd.google-apps.folder', 'application/vnd.google-apps.form', 'application/vnd.google-apps.fusiontable', 'app... |
A_CONSTANT = 45
def a_sum_function(a: int, b: int) -> int:
return a + b
def a_mult_function(a: int, b: int) -> int:
return a * b
class ACarClass:
def __init__(self, color: str, speed: int):
self.color = color
self.speed = speed
def describe(self) -> str:
return f'I am a {s... | a_constant = 45
def a_sum_function(a: int, b: int) -> int:
return a + b
def a_mult_function(a: int, b: int) -> int:
return a * b
class Acarclass:
def __init__(self, color: str, speed: int):
self.color = color
self.speed = speed
def describe(self) -> str:
return f'I am a {sel... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
ha, hb = headA, headB
while ha != hb:
ha = ha.next if ha else headB
... | class Solution(object):
def get_intersection_node(self, headA, headB):
(ha, hb) = (headA, headB)
while ha != hb:
ha = ha.next if ha else headB
hb = hb.next if hb else headA
return ha |
AUTHOR = 'Sage Bionetworks'
SITENAME = 'Sage Bionetworks Developer Handbook'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
# FEED_ALL_ATOM = None
# CATEGORY_FEED_ATOM = None
# TRANSLATION_FEED_ATOM = None
# AUTHOR_FEED_ATO... | author = 'Sage Bionetworks'
sitename = 'Sage Bionetworks Developer Handbook'
siteurl = ''
path = 'content'
timezone = 'America/Los_Angeles'
default_lang = 'en'
default_pagination = False |
'''
URL: https://leetcode.com/problems/diagonal-traverse
Time complexity: O(mn)
Space complexity: O(1)
'''
class Solution:
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
m = len... | """
URL: https://leetcode.com/problems/diagonal-traverse
Time complexity: O(mn)
Space complexity: O(1)
"""
class Solution:
def find_diagonal_order(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
m = l... |
'''
Author: jianzhnie
Date: 2022-01-24 11:36:20
LastEditTime: 2022-01-24 11:36:21
LastEditors: jianzhnie
Description:
'''
| """
Author: jianzhnie
Date: 2022-01-24 11:36:20
LastEditTime: 2022-01-24 11:36:21
LastEditors: jianzhnie
Description:
""" |
"""
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load
load("@bazel_tools//too... | """
@generated
cargo-raze generated Bazel file.
DO NOT EDIT! Replaced on runs of cargo-raze
"""
load('@bazel_tools//tools/build_defs/repo:git.bzl', 'new_git_repository')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
def zexe_fetch_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.