content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
micropy.utils.decorators
~~~~~~~~~~~~~~
This module contains generic decorators
used by MicropyCli
"""
__all__ = ['lazy_property']
def lazy_property(fn):
attr = '_lazy__' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr):
setat... | """
micropy.utils.decorators
~~~~~~~~~~~~~~
This module contains generic decorators
used by MicropyCli
"""
__all__ = ['lazy_property']
def lazy_property(fn):
attr = '_lazy__' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr):
setattr(self, attr, fn(self))
... |
"""
Un obrero necesita calcular su salario semanal, el cual se obtiene de la
siguiente manera:
Si trabaja 40 horas o menos se le paga 16 euros por hora
Si trabaja mas de 40 horas se le paga 16 euros por cada una de
las primeras 40 horas y 20 euros por cada hora extra.
"""
print("============SALARIO SEMANAL OBRERO===... | """
Un obrero necesita calcular su salario semanal, el cual se obtiene de la
siguiente manera:
Si trabaja 40 horas o menos se le paga 16 euros por hora
Si trabaja mas de 40 horas se le paga 16 euros por cada una de
las primeras 40 horas y 20 euros por cada hora extra.
"""
print('============SALARIO SEMANAL OBRERO====... |
palavras = ('APRENDER', 'ESTUDAR', 'PROGRAMAR', 'AUTOMATIZAR', 'ANALISTA DE TESTES', 'PYTHON', 'ROBOT FRAMEWORK')
for c in palavras:
print(f'\nNa palavra {c.upper()} temos ',end='')
for vogal in c:
if vogal.lower() in 'aeiou':
print(vogal.lower(), end='') | palavras = ('APRENDER', 'ESTUDAR', 'PROGRAMAR', 'AUTOMATIZAR', 'ANALISTA DE TESTES', 'PYTHON', 'ROBOT FRAMEWORK')
for c in palavras:
print(f'\nNa palavra {c.upper()} temos ', end='')
for vogal in c:
if vogal.lower() in 'aeiou':
print(vogal.lower(), end='') |
russian_word_list = []
abkhazian_word_list = []
outputfile = 'ab-ru-probability.dic'
output = open(outputfile,"w+")
cyrillic_encoding="utf-8"
probability = 0.9
#read the russian word into the list
with open('../draft/dictionary_prescript.ru', 'r+',encoding=cyrillic_encoding) as f:
russian_word_list = f.read().spl... | russian_word_list = []
abkhazian_word_list = []
outputfile = 'ab-ru-probability.dic'
output = open(outputfile, 'w+')
cyrillic_encoding = 'utf-8'
probability = 0.9
with open('../draft/dictionary_prescript.ru', 'r+', encoding=cyrillic_encoding) as f:
russian_word_list = f.read().splitlines()
with open('../draft/dicti... |
num1 = 10
num2 = 3
result = num1 / num2
print(result)
# 10//3 # ==> 3
print(10//3); | num1 = 10
num2 = 3
result = num1 / num2
print(result)
print(10 // 3) |
ipDDN = "192.168.0.1"
octets = ipDDN.split(".")
#convert ddn to int
ip = int(octets[0]) << 24
ip += int(octets[1]) << 16
ip += int(octets[2]) << 8
ip += int(octets[3])
print(ip) | ip_ddn = '192.168.0.1'
octets = ipDDN.split('.')
ip = int(octets[0]) << 24
ip += int(octets[1]) << 16
ip += int(octets[2]) << 8
ip += int(octets[3])
print(ip) |
# Write a program to turn a number into its English name
# Assume that the number is positive below 1000
# for more info on this quiz, go to this url: http://www.programmr.com/word-representation-number
ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "... | ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
decade = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def first(num... |
# https://www.codewars.com/kata/exclamation-marks-series-number-17-put-the-exclamation-marks-and-question-marks-to-the-balance-are-they-balanced/train/python
leftString = '!!'
rightString = '??'
def balance(left, right):
if ((left.count('!') * 2) + (left.count('?') * 3)) == ((right.count('!') * 2) + (right.count('... | left_string = '!!'
right_string = '??'
def balance(left, right):
if left.count('!') * 2 + left.count('?') * 3 == right.count('!') * 2 + right.count('?') * 3:
return 'Balance'
elif left.count('!') * 2 + left.count('?') * 3 > right.count('!') * 2 + right.count('?') * 3:
return 'Left'
elif lef... |
input_file = "" #file location
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kid of like a tape.... | input_file = ''
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kid of like a tape.")
rewind(current_fi... |
#!/usr/bin/env python3
# add one level of indentation to code
def indent(code):
return [ " " + l for l in code ]
# remove one level of indentation from code
def unindent(code):
cs = []
for l in code:
if l != "" and l[0:4] != " ":
print("Malformed conditional code '" + l[0:4] +"'"... | def indent(code):
return [' ' + l for l in code]
def unindent(code):
cs = []
for l in code:
if l != '' and l[0:4] != ' ':
print("Malformed conditional code '" + l[0:4] + "'")
assert False
cs.append(l[4:])
return cs
def demangle_execute_asl(code):
tops ... |
BATCH_SIZE = 64
EPOCHS = 100
IMG_WIDTH = 1801
IMG_HEIGHT = 32
NUM_CHANNELS = 3
NUM_CLASSES = 2
NUM_REGRESSION_OUTPUTS = 24
K_NEGATIVE_SAMPLE_RATIO_WEIGHT = 4
INPUT_SHAPE = (IMG_HEIGHT, IMG_WIDTH, NUM_CHANNELS)
PREDICTION_FILE_NAME = 'objects_obs1_lidar_predictions.csv'
PREDICTION_MD_FILE_NAME = 'objects_obs1_metadata.... | batch_size = 64
epochs = 100
img_width = 1801
img_height = 32
num_channels = 3
num_classes = 2
num_regression_outputs = 24
k_negative_sample_ratio_weight = 4
input_shape = (IMG_HEIGHT, IMG_WIDTH, NUM_CHANNELS)
prediction_file_name = 'objects_obs1_lidar_predictions.csv'
prediction_md_file_name = 'objects_obs1_metadata.c... |
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = self.buildHeap(array)
def buildHeap(self, array):
# Write your code here.
pass
def siftDown(self):
# Write your code here.
pass
def siftUp(self):
# Write your co... | class Minheap:
def __init__(self, array):
self.heap = self.buildHeap(array)
def build_heap(self, array):
pass
def sift_down(self):
pass
def sift_up(self):
pass
def peek(self):
pass
def remove(self):
pass
def insert(self, value):
... |
NAMES = ["Bill", "Richie", "Ben", "Eddie", "Mike", "Beverly"]
while True:
searched_name = input("Give a member of The Losers' Club: ")
if searched_name is "":
break
elif (searched_name in NAMES) is True:
print("Correct!")
else:
print("Wrong!")
| names = ['Bill', 'Richie', 'Ben', 'Eddie', 'Mike', 'Beverly']
while True:
searched_name = input("Give a member of The Losers' Club: ")
if searched_name is '':
break
elif (searched_name in NAMES) is True:
print('Correct!')
else:
print('Wrong!') |
# -*- coding: utf-8 -*-
# @Author: Mujib
# @Date: 2017-07-15 15:05:13
# @Last Modified by: Mujib
# @Last Modified time: 2017-07-15 15:20:03
actualString = 'Monster truck rally. 4pm. Monday'
print( 'This is upperCase >>> ' + actualString.upper() )
print( '---------------------------------------------' )
print( 'T... | actual_string = 'Monster truck rally. 4pm. Monday'
print('This is upperCase >>> ' + actualString.upper())
print('---------------------------------------------')
print('This is lowerCase >>> ' + actualString.lower())
print('---------------------------------------------')
print('Is string ends with ".jpg" >>> ')
print(ac... |
cffi_template = '''from cffi import FFI
def link_clib(block_cell_name):
ffi = FFI()
ffi.cdef(r\'\'\'{{headers}}\'\'\')
C = ffi.dlopen('{{dynlib_file}}')
return ffi, C
''' | cffi_template = "from cffi import FFI\ndef link_clib(block_cell_name):\n ffi = FFI()\n ffi.cdef(r'''{{headers}}''')\n C = ffi.dlopen('{{dynlib_file}}')\n return ffi, C\n" |
class Store:
def __init__(self, name, categories):
self.name = name
self.categories = categories
def __str__(self):
output = f"{self.name}\n"
for idx, category in enumerate(self.categories):
output += " " + str(idx+1) + ", " + category + "\n"
return ... | class Store:
def __init__(self, name, categories):
self.name = name
self.categories = categories
def __str__(self):
output = f'{self.name}\n'
for (idx, category) in enumerate(self.categories):
output += ' ' + str(idx + 1) + ', ' + category + '\n'
return outp... |
'''
Gui/Views/Dialogs
_________________
Subset of views that are specifically for QDialog and QMessageBox
classes.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
__all__ = [
'base',
'export',
'f... | """
Gui/Views/Dialogs
_________________
Subset of views that are specifically for QDialog and QMessageBox
classes.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
"""
__all__ = ['base', 'export', 'findreplace', '... |
_base_ = [
'../../_base_/models/tanet_r50.py', '../../_base_/default_runtime.py'
]
# dataset settings
dataset_type = 'VideoDataset'
data_root = '/home/petros/Datasets/hmdb51/videos'
data_root_val = '/home/petros/Datasets/hmdb51/videos'
ann_file_train = '/home/petros/Datasets/hmdb51/hmdb51_train_split_1_videos.txt'... | _base_ = ['../../_base_/models/tanet_r50.py', '../../_base_/default_runtime.py']
dataset_type = 'VideoDataset'
data_root = '/home/petros/Datasets/hmdb51/videos'
data_root_val = '/home/petros/Datasets/hmdb51/videos'
ann_file_train = '/home/petros/Datasets/hmdb51/hmdb51_train_split_1_videos.txt'
ann_file_val = '/home/pet... |
# https://leetcode.com/problems/kth-smallest-element-in-a-bst/
class Solution(object):
result = []
def getSmallest(self, root, k):
global y
if root != None:
left = self.getSmallest(root.left)
if left != None:
self.re... | class Solution(object):
result = []
def get_smallest(self, root, k):
global y
if root != None:
left = self.getSmallest(root.left)
if left != None:
self.result.append(left.val)
y -= 1
if y == 0:
self.result.append(ro... |
class Solution:
def search(self, nums, target):
low , high = 0 , len(nums)-1
while low <= high:
mid = low + (high-low) // 2 # if high is greater than low
if nums[mid] == target:
return mid
if nums[mid] > target: # if target is smaller ignore righ... | class Solution:
def search(self, nums, target):
(low, high) = (0, len(nums) - 1)
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
return mid
if nums[mid] > target:
high = mid - 1
else:
... |
"""
Auxilliary list of HEX colors for graphic purposes.
Recommended usage, if wanted:
`from pylabutils._tools._colors import color_dict [as <name>]`
"""
__all__ = ['color_dict']
color_dict = {
"""
Auxilliary list of HEX colors for graphic purposes.
"""
'light_blue' : '#60A0FF',
'blue' : '#3... | """
Auxilliary list of HEX colors for graphic purposes.
Recommended usage, if wanted:
`from pylabutils._tools._colors import color_dict [as <name>]`
"""
__all__ = ['color_dict']
color_dict = {'\n Auxilliary list of HEX colors for graphic purposes.\n light_blue': '#60A0FF', 'blue': '#3385FF', 'dark_blue': '#0A4A... |
# empt_dict = {'01': '31', '02': '29', '03': '31', '04': '30', '05': '31', '06': '30', '07': '31', '08': '31', '09': '30', '10': '31', '11': '30', '12': '31'}
# date = '06_04'
def get_last_seven(date_input):
dict_input = {'01': '31', '02': '29', '03': '31', '04': '30', '05': '31', '06': '30', '07': '31', '08': ... | def get_last_seven(date_input):
dict_input = {'01': '31', '02': '29', '03': '31', '04': '30', '05': '31', '06': '30', '07': '31', '08': '31', '09': '30', '10': '31', '11': '30', '12': '31'}
dates_to_grab = []
current_date = date_input.split('_')
month = current_date[0]
day = current_date[1]
mont... |
class Point():
def __init__(self, input1, input2):
self.x = input1
self.y = input2
p = Point(2, 8)
# PRINT THE X&Y-VALUES OF THE POINT
print(p.x)
print(p.y)
# CREATED A CLASS (Flight which takes capacity as input)
class FLight():
# FUNCTION FOR CAPACITY
def __init__(self, capacity):
... | class Point:
def __init__(self, input1, input2):
self.x = input1
self.y = input2
p = point(2, 8)
print(p.x)
print(p.y)
class Flight:
def __init__(self, capacity):
self.capacity = capacity
self.passengers = []
def add_passenger(self, name):
if not self.open_seats()... |
fact = 1
n = int(input('Enter the no you want to factorial \t'))
for i in range(1,n+1):
fact = fact*i
print('FACTORIAL Of ',n,"is",fact)
| fact = 1
n = int(input('Enter the no you want to factorial \t'))
for i in range(1, n + 1):
fact = fact * i
print('FACTORIAL Of ', n, 'is', fact) |
entries = [
{
'env-title': 'mujoco-half-cheetah',
'score': 1668.58,
},
{
'env-title': 'mujoco-hopper',
'score': 2316.16,
},
{
'env-title': 'mujoco-inverted-pendulum',
'score': 809.43,
},
{
'env-title': 'mujoco-swimmer',
'score':... | entries = [{'env-title': 'mujoco-half-cheetah', 'score': 1668.58}, {'env-title': 'mujoco-hopper', 'score': 2316.16}, {'env-title': 'mujoco-inverted-pendulum', 'score': 809.43}, {'env-title': 'mujoco-swimmer', 'score': 111.19}, {'env-title': 'mujoco-inverted-double-pendulum', 'score': 7102.91}, {'env-title': 'mujoco-rea... |
class Solution:
def isStable(self, board, numRows, numCols):
positions = set()
for row in range(numRows):
for col in range(numCols):
if board[row][col]:
if col > 1 and (board[row][col] == board[row][col-1] == board[row][col-2]):
... | class Solution:
def is_stable(self, board, numRows, numCols):
positions = set()
for row in range(numRows):
for col in range(numCols):
if board[row][col]:
if col > 1 and board[row][col] == board[row][col - 1] == board[row][col - 2]:
... |
def sp_cls_count(sp_cls, n_seg_cls=8):
"""
Get the count (number of superpixels) for each segmentation class
Args:
sp_cls (dict): the key is the superpixel ID, and the value is the
class ID for the corresponding superpixel. There are n elements
in the sp_cls. Here, we ... | def sp_cls_count(sp_cls, n_seg_cls=8):
"""
Get the count (number of superpixels) for each segmentation class
Args:
sp_cls (dict): the key is the superpixel ID, and the value is the
class ID for the corresponding superpixel. There are n elements
in the sp_cls. Here, we us... |
s = 0
for x in range(1, 10+1):
s = s+x
print("x:", x, "sum:", s)
| s = 0
for x in range(1, 10 + 1):
s = s + x
print('x:', x, 'sum:', s) |
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
'''
T: O(len(strs) * m * n) and S: (m * n)
'''
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for s in strs:
count = collections.Counter(s)
for i in range(m, co... | class Solution:
def find_max_form(self, strs: List[str], m: int, n: int) -> int:
"""
T: O(len(strs) * m * n) and S: (m * n)
"""
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for s in strs:
count = collections.Counter(s)
for i in range(m, coun... |
def roman_nums():
"""Generator for roman numerals."""
mapping = [
(1, 'i'), (4, 'iv'), (5, 'v'), (9, 'ix'),
(10, 'x'), (40, 'xl'), (50, 'l'), (90, 'xc'),
(100, 'c'), (400, 'cd'), (500, 'd'), (900, 'cm'),
(1000, 'm')
]
i = 1
while True:
next_str = ''
... | def roman_nums():
"""Generator for roman numerals."""
mapping = [(1, 'i'), (4, 'iv'), (5, 'v'), (9, 'ix'), (10, 'x'), (40, 'xl'), (50, 'l'), (90, 'xc'), (100, 'c'), (400, 'cd'), (500, 'd'), (900, 'cm'), (1000, 'm')]
i = 1
while True:
next_str = ''
remaining_int = i
remaining_mapp... |
expected_output={
'interfaces': {
'HundredGigE1/0/21': {
'neighbors': {
'3.3.3.3': {
'priority': 0,
'state': 'FULL/ -',
'dead_time': '00:00:35',
'interface_id': 23
}
}
}
}
}
| expected_output = {'interfaces': {'HundredGigE1/0/21': {'neighbors': {'3.3.3.3': {'priority': 0, 'state': 'FULL/ -', 'dead_time': '00:00:35', 'interface_id': 23}}}}} |
config = {
"cmip6": {
"base_dir": "/badc/cmip6/data/CMIP6",
"facets": "mip_era activity_id institution_id source_id experiment_id member_id table_id variable_id grid_label version".split(),
"scan_depth": 5,
"mappings": {"variable": "variable_id", "project": "mip_era"}
},
"cmi... | config = {'cmip6': {'base_dir': '/badc/cmip6/data/CMIP6', 'facets': 'mip_era activity_id institution_id source_id experiment_id member_id table_id variable_id grid_label version'.split(), 'scan_depth': 5, 'mappings': {'variable': 'variable_id', 'project': 'mip_era'}}, 'cmip5': {'base_dir': '/badc/cmip5/data/cmip5', 'fa... |
'''
Created on May 12, 2022
@author: mballance
'''
class PoolSize(object):
def __init__(self, sz):
self._sz = sz
def __int__(self):
return self._sz | """
Created on May 12, 2022
@author: mballance
"""
class Poolsize(object):
def __init__(self, sz):
self._sz = sz
def __int__(self):
return self._sz |
""" base on http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/index.html demo-5
"""
class DummyResource:
def __init__(self, tag):
self.tag = tag
print('Resource [%s]' % tag)
def __enter__(self):
print('[Enter %s]: Allocate resource.' % self.tag)
return self # c... | """ base on http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/index.html demo-5
"""
class Dummyresource:
def __init__(self, tag):
self.tag = tag
print('Resource [%s]' % tag)
def __enter__(self):
print('[Enter %s]: Allocate resource.' % self.tag)
return self
... |
n = int(input())
for i in range (97 , 97 + n ):
for m in range (97, 97 + n):
for k in range (97, 97 + n):
print(chr(i) + chr(m) + chr(k)) | n = int(input())
for i in range(97, 97 + n):
for m in range(97, 97 + n):
for k in range(97, 97 + n):
print(chr(i) + chr(m) + chr(k)) |
def trainer(model, data):
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
(x, y) = data('train')
def result(epochs, batch_size):
model.fit(x, y, batch_size=batch_size, epochs=epochs, validation_split=0.1)
return model
return result
| def trainer(model, data):
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
(x, y) = data('train')
def result(epochs, batch_size):
model.fit(x, y, batch_size=batch_size, epochs=epochs, validation_split=0.1)
return model
return result |
# print([callable(getattr(__builtins__, attr)) for attr in dir(__builtins__)])
print([(attr,type(getattr(__builtins__, attr))) for attr in dir(__builtins__)])
# print 'hello'*100
| print([(attr, type(getattr(__builtins__, attr))) for attr in dir(__builtins__)]) |
# https://leetcode.com/problems/count-univalue-subtrees/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def countUnivalSubtrees(self, root):
"""
:type root: TreeNode
... | class Solution:
def count_unival_subtrees(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def search(root):
(lu, lv) = (True, root.val)
(ru, rv) = (True, root.val)
if root.left:
(lu, lv) = search(root.left)
... |
#criar um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros.
m = float(input('Digite um valor em metros: '))
km = m/1000
hm = m/100
dam= m/10
dm = m*10
cm = m*100
mm = m*1000
print("A medida de {} metros corresponde a {:.0f} dm, {:.0f} cm e {:.0f} mm".format(m, dm, cm, mm))
print... | m = float(input('Digite um valor em metros: '))
km = m / 1000
hm = m / 100
dam = m / 10
dm = m * 10
cm = m * 100
mm = m * 1000
print('A medida de {} metros corresponde a {:.0f} dm, {:.0f} cm e {:.0f} mm'.format(m, dm, cm, mm))
print('A medida de {} metros corresponde a {} km, {} hm e {} dam'.format(m, km, hm, dam)) |
#! /usr/bin/python
# Copyright Notice:
# Copyright 2019-2020 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Tacklebox/blob/master/LICENSE.md
"""
Resets Module
File : resets.py
Brief : This file contains the common definitions and functionalities fo... | """
Resets Module
File : resets.py
Brief : This file contains the common definitions and functionalities for
reset operations
"""
reset_types = ['On', 'ForceOff', 'GracefulShutdown', 'GracefulRestart', 'ForceRestart', 'Nmi', 'ForceOn', 'PushPowerButton', 'PowerCycle'] |
_base_ = './cascade_rcnn_r50_fpn_20e_coco.py'
# The new config inherits a base config to highlight the necessary modification
_base_ = 'mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py'
# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
roi_head=dict(
... | _base_ = './cascade_rcnn_r50_fpn_20e_coco.py'
_base_ = 'mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_coco.py'
model = dict(roi_head=dict(bbox_head=dict(num_classes=6), mask_head=dict(num_classes=6)))
dataset_type = 'COCODataset'
classes = ('badge', 'person', 'glove', 'wrongglove', 'operatingbar', 'powerchecker')
d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 08:24:01 2020
@author: krishan
"""
class Student:
collegeName = 'KITS'
def __init__(self, name):
self.name = name
# Aggregation[No need for object]
print(Student.collegeName)
s = Student('Arjun')
# Composition[Wit... | """
Created on Tue Aug 11 08:24:01 2020
@author: krishan
"""
class Student:
college_name = 'KITS'
def __init__(self, name):
self.name = name
print(Student.collegeName)
s = student('Arjun')
print(s.name) |
class DateTimeExtensions(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DateTimeExtensions()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
@staticmethod
def AddWorkday(date):
""" AddWorkday(date: DateTime) -> DateTime """
pass
@staticmethod
def IsSam... | class Datetimeextensions(object):
def zzz(self):
"""hardcoded/mock instance of the class"""
return date_time_extensions()
instance = zzz()
'hardcoded/returns an instance of the class'
@staticmethod
def add_workday(date):
""" AddWorkday(date: DateTime) -> DateTime """
... |
"""
The snake ladder board game is represented as one-dimensional array
where value in the array are the destination id cell for the snakes (lower
numbers) and ladders higher number.
"""
board = [1,15,3,4,7,6,7,8,27,10,11,12,13,14,15,16,4,29,19,21,22,23,16,
35,26,27,28,29,30,31,30,33,12,35,36]
def find_mi... | """
The snake ladder board game is represented as one-dimensional array
where value in the array are the destination id cell for the snakes (lower
numbers) and ladders higher number.
"""
board = [1, 15, 3, 4, 7, 6, 7, 8, 27, 10, 11, 12, 13, 14, 15, 16, 4, 29, 19, 21, 22, 23, 16, 35, 26, 27, 28, 29, 30, 31, 30, 33, 12, ... |
BASE_URL = 'http://api.statbank.dk/v1'
DELIMITER = ';'
DEFAULT_LANGUAGE = 'da'
LOCALES = {'da': 'en_DK.UTF-8',
'en': 'en_US.UTF-8'}
| base_url = 'http://api.statbank.dk/v1'
delimiter = ';'
default_language = 'da'
locales = {'da': 'en_DK.UTF-8', 'en': 'en_US.UTF-8'} |
class TaxNotKnown(Exception):
"""
Exception for when a tax-inclusive price is requested but we don't know
what the tax applicable is (yet).
"""
class Price(object):
is_tax_known = False
def __init__(self, currency, excl_tax, incl_tax=None, tax=None):
"""
You can either pass th... | class Taxnotknown(Exception):
"""
Exception for when a tax-inclusive price is requested but we don't know
what the tax applicable is (yet).
"""
class Price(object):
is_tax_known = False
def __init__(self, currency, excl_tax, incl_tax=None, tax=None):
"""
You can either pass the... |
def fibo(n):
if n<3:
return n-1
else:
return fibo(n-1)+fibo(n-2)
| def fibo(n):
if n < 3:
return n - 1
else:
return fibo(n - 1) + fibo(n - 2) |
"""
Number of Islands
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["... | """
Number of Islands
Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
["... |
"""."""
class HashBrowns:
"""Makes a hash table."""
def __init__(self):
self.size = 753
self.slots = [None] * self.size
self.data = [None] * self.size
def hashingtons(self, key, size):
return key % size
def hashemagain(self, oldcountrystylehash, size):
return ... | """."""
class Hashbrowns:
"""Makes a hash table."""
def __init__(self):
self.size = 753
self.slots = [None] * self.size
self.data = [None] * self.size
def hashingtons(self, key, size):
return key % size
def hashemagain(self, oldcountrystylehash, size):
return ... |
"""
Copyright 2021 Robert MacGregor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d... | """
Copyright 2021 Robert MacGregor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d... |
def doincre(delta, entity, cnt, RK, table, PK, tablesvc):
if cnt > 0:
item = {"PartitionKey": PK, "RowKey": RK, "value": int(entity.value) + delta, "etag": entity.etag}
try:
tablesvc.merge_entity(table, item)
except:
result = tablesvc.get_entity(table, PK, RK)
... | def doincre(delta, entity, cnt, RK, table, PK, tablesvc):
if cnt > 0:
item = {'PartitionKey': PK, 'RowKey': RK, 'value': int(entity.value) + delta, 'etag': entity.etag}
try:
tablesvc.merge_entity(table, item)
except:
result = tablesvc.get_entity(table, PK, RK)
... |
# Python - 3.4.3
test.describe('Example Tests')
InterlacedSpiralCipher = {'encode': encode, 'decode': decode }
example1A = 'Romani ite domum'
example1B = 'Rntodomiimuea m'
test.assert_equals(InterlacedSpiralCipher['encode'](example1A), example1B)
test.assert_equals(InterlacedSpiralCipher['decode'](example1B), exampl... | test.describe('Example Tests')
interlaced_spiral_cipher = {'encode': encode, 'decode': decode}
example1_a = 'Romani ite domum'
example1_b = 'Rntodomiimuea m'
test.assert_equals(InterlacedSpiralCipher['encode'](example1A), example1B)
test.assert_equals(InterlacedSpiralCipher['decode'](example1B), example1A)
example2_a ... |
RESOURCES = {
'accounts': {
'schema': {
'username': {
'type': 'string',
'required': True,
'unique': True
},
'password': {
'type': 'string',
'required': True
},
'roles':... | resources = {'accounts': {'schema': {'username': {'type': 'string', 'required': True, 'unique': True}, 'password': {'type': 'string', 'required': True}, 'roles': {'type': 'list', 'allowed': ['user', 'superuser'], 'required': True}, 'location': {'type': 'dict', 'schema': {'country': {'type': 'string'}, 'city': {'type': ... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n, k = map(int, input().strip().split())
s ... | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
(n, k) = map(int, input().strip().split())
s = input()
mx = 0
ans =... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
t1_ptr = t1
t2_ptr = t2
t3_ptr = None
if t... | class Solution:
def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
t1_ptr = t1
t2_ptr = t2
t3_ptr = None
if t1_ptr and t2_ptr:
t3_ptr = tree_node(t1_ptr.val + t2_ptr.val)
t3_ptr.left = self.mergeTrees(t1_ptr.left, t2_ptr.left)
t3_ptr.r... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def isPalindrome(self, head):
if head == None:
return True
prev = None... | class Solution:
def is_palindrome(self, head):
if head == None:
return True
prev = None
slow = head
fast = head
while fast != None and fast.next != None:
prev = slow
slow = slow.next
fast = fast.next.next
mid = slow
... |
load("//third_party/py:python_configure.bzl", "python_configure")
load("@io_bazel_rules_python//python:pip.bzl", "pip_repositories")
load("@grpc_python_dependencies//:requirements.bzl", "pip_install")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
def grpc_python_deps():
# TODO(https... | load('//third_party/py:python_configure.bzl', 'python_configure')
load('@io_bazel_rules_python//python:pip.bzl', 'pip_repositories')
load('@grpc_python_dependencies//:requirements.bzl', 'pip_install')
load('@org_pubref_rules_protobuf//python:rules.bzl', 'py_proto_repositories')
def grpc_python_deps():
if hasattr(n... |
FONT_TITLE = 18
FONT_LEGEND = 16
FONT_LABEL = 14
FONT_STICK = 12
LEGEND_FRAMEALPHA = 0.5
########## h5py -- dod ############
wake_trim_min = None
period_length_sec = 30
h5_out_dir = './h5py/output'
ignore_class = None
kappa_weights='quadratic'
plot_hypnograms=True
plot_CMs=True
###### ablation #####... | font_title = 18
font_legend = 16
font_label = 14
font_stick = 12
legend_framealpha = 0.5
wake_trim_min = None
period_length_sec = 30
h5_out_dir = './h5py/output'
ignore_class = None
kappa_weights = 'quadratic'
plot_hypnograms = True
plot_c_ms = True
ablation_out_dir = './ablation/output' |
class CrabNavy:
def __init__(self, positions):
self.positions = positions
@classmethod
def from_str(cls, positions_str):
positions = [int(c) for c in positions_str.split(",")]
return cls(positions)
def calculate_consumption(self, alignment):
total = 0
for posi... | class Crabnavy:
def __init__(self, positions):
self.positions = positions
@classmethod
def from_str(cls, positions_str):
positions = [int(c) for c in positions_str.split(',')]
return cls(positions)
def calculate_consumption(self, alignment):
total = 0
for posit... |
class Human:
pass
class Man(Human):
pass
class Woman(Human):
pass
def God():
""" god == PEP8 (forced to capitalize by CodeWars) """
return [Man(), Woman()]
| class Human:
pass
class Man(Human):
pass
class Woman(Human):
pass
def god():
""" god == PEP8 (forced to capitalize by CodeWars) """
return [man(), woman()] |
# Exercise One
hash = "#"
for i in range(0, 7):
print(hash)
hash = hash + "#"
# Exercise two
for i in range(1, 101):
if i % 3 == 0:
if i % 5 == 0:
print("FizzBuzz")
else:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
# Exerci... | hash = '#'
for i in range(0, 7):
print(hash)
hash = hash + '#'
for i in range(1, 101):
if i % 3 == 0:
if i % 5 == 0:
print('FizzBuzz')
else:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
size = 8
chess_board = ''
for i in range(0,... |
'''https://adoptopenjdk.net/upstream.html
'''
load("//java:common/structs/KnownOpenJdkRepository.bzl", _KnownOpenJdkRepository = "KnownOpenJdkRepository")
def adoptopenjdk_upstream_repositories():
return _KNOWN_OPENJDK_REPOSITORIES
def _Repo(**kwargs):
kwargs['provider'] = "adoptopenjdk_upstream"
return ... | """https://adoptopenjdk.net/upstream.html
"""
load('//java:common/structs/KnownOpenJdkRepository.bzl', _KnownOpenJdkRepository='KnownOpenJdkRepository')
def adoptopenjdk_upstream_repositories():
return _KNOWN_OPENJDK_REPOSITORIES
def __repo(**kwargs):
kwargs['provider'] = 'adoptopenjdk_upstream'
return __... |
def map_wiimote_to_key(wiimote_index, wiimote_button, key):
# Check the global wiimote object's button state and set the global
# keyboard object's corresponding key.
if wiimote[wiimote_index].buttons.button_down(wiimote_button):
keyboard.setKeyDown(key)
else:
keyboard.setKeyUp(key)
def map_wiimote_to_vJoy(wii... | def map_wiimote_to_key(wiimote_index, wiimote_button, key):
if wiimote[wiimote_index].buttons.button_down(wiimote_button):
keyboard.setKeyDown(key)
else:
keyboard.setKeyUp(key)
def map_wiimote_to_v_joy(wiimote_index, wiimote_button, key):
if wiimote[wiimote_index].buttons.button_down(wiimot... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 12 09:23:59 2016
@author: andre
"""
num = int(input("Choose a number to convert: "))
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num%2) + result
num = num // 2
i... | """
Created on Mon Sep 12 09:23:59 2016
@author: andre
"""
num = int(input('Choose a number to convert: '))
if num < 0:
is_neg = True
num = abs(num)
else:
is_neg = False
result = ''
if num == 0:
result = '0'
while num > 0:
result = str(num % 2) + result
num = num // 2
if isNeg:
result = '-'... |
# OpenWeatherMap API Key
weather_api_key = "reset"
# Google API Key
g_key = "reset"
| weather_api_key = 'reset'
g_key = 'reset' |
def merge_sorted_list(arr1, arr2):
# m = len(arr1), n = len(arr1)
# since we know arr1 is always greater or equal to (m+n)
# we compare arr2[i] with arr1[j] element and check if it
# should be placed there
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr2[j] == arr1[i] or arr2[... | def merge_sorted_list(arr1, arr2):
(i, j) = (0, 0)
while i < len(arr1) and j < len(arr2):
if arr2[j] == arr1[i] or arr2[j] <= arr1[i + 1]:
arr1.insert(i + 1, arr2[j])
arr1.pop()
i += 2
j += 1
elif arr2[j] > arr1[i]:
if arr1[i + 1] == 0:... |
data = open(0).readlines()
e = [i == "#" for i in data[0].strip()]
b = [line.strip() for line in data[2:]]
d = ((-1,-1),(-1,0),(-1,1),(0,-1),(0,0),(0,1),(1,-1),(1,0),(1,1))
def neighbors(i, j):
for k, (di, dj) in enumerate(d):
yield 256 >> k, i+di, j+dj
def lookup(_s, i, j, bi, bj, flip=False):
if i ==... | data = open(0).readlines()
e = [i == '#' for i in data[0].strip()]
b = [line.strip() for line in data[2:]]
d = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1))
def neighbors(i, j):
for (k, (di, dj)) in enumerate(d):
yield (256 >> k, i + di, j + dj)
def lookup(_s, i, j, bi, bj... |
distance_success_response = {'destination_addresses': ['Brighton, UK'],
'origin_addresses': ['London, UK'], 'rows': [{'elements': [
{'distance': {'text': '64.6 mi', 'value': 103964},
... | distance_success_response = {'destination_addresses': ['Brighton, UK'], 'origin_addresses': ['London, UK'], 'rows': [{'elements': [{'distance': {'text': '64.6 mi', 'value': 103964}, 'duration': {'text': '1 hour 54 mins', 'value': 6854}, 'status': 'OK'}]}], 'status': 'OK'} |
"""Bazel rule for making a zip file."""
def zip_dir(name, srcs, zipname, **kwargs):
"""Zips up an entire directory or Fileset.
Args:
name: The name of the target
srcs: A single-item list with a directory or fileset
zipname: The name of the output zip file
**kwargs: Further generic argu... | """Bazel rule for making a zip file."""
def zip_dir(name, srcs, zipname, **kwargs):
"""Zips up an entire directory or Fileset.
Args:
name: The name of the target
srcs: A single-item list with a directory or fileset
zipname: The name of the output zip file
**kwargs: Further generic argu... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getmerge(self,l1,l2):
head = ListNode(0)
tail = head
while l1 is not None and l2 is not None:
if l1.val > l2.val:
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getmerge(self, l1, l2):
head = list_node(0)
tail = head
while l1 is not None and l2 is not None:
if l1.val > l2.val:
(l1, l2) = (l2, l1... |
string = 'Monty Python'
print(string[0:4])
print(string[6:7])
print(string[6:20])
print(string[8:])
data = 'From robin.smorenburg@linkit.nl Sat Jan'
position = data.find('@')
print(position)
space_position = data.find(' ', position)
print(space_position)
host = data[position+1:space_position]
print(host)
| string = 'Monty Python'
print(string[0:4])
print(string[6:7])
print(string[6:20])
print(string[8:])
data = 'From robin.smorenburg@linkit.nl Sat Jan'
position = data.find('@')
print(position)
space_position = data.find(' ', position)
print(space_position)
host = data[position + 1:space_position]
print(host) |
def baz():
tmp = "!" # try to extract this assignment, either with or without this comment
baz()
def bar(self):
pass | def baz():
tmp = '!'
baz()
def bar(self):
pass |
# Find duplicates in an array in O(N) Time and O(1) space.
# The elements in the array can be only Between 1<=x<=len(array)
# Asked in Amazon,D-E-Shaw, Flipkart and many more
# Difficulty -> Medium (for O(N) time and O(1) space)
# Approaches:
# Naive Solution: Loop through all the values checking for multi... | def find_duplicates(arr):
size = len(arr)
for i in range(0, size):
idx = abs(arr[i]) - 1
if arr[idx] < 0:
print(abs(arr[i]))
arr[idx] = -arr[idx]
arr1 = [2, 1, 2, 1]
arr2 = [1, 2, 3, 1, 3, 6, 6]
find_duplicates(arr1)
print()
find_duplicates(arr2) |
# Description: Extract just the intensities for a give Miller array and print ten rows of them.
# Source: NA
"""
Iobs = miller_arrays[${1:0}]
iobsdata = Iobs.data()
list(iobsdata[${1:100:110}])
"""
Iobs = miller_arrays[0]
iobsdata = Iobs.data()
list(iobsdata[100:110])
| """
Iobs = miller_arrays[${1:0}]
iobsdata = Iobs.data()
list(iobsdata[${1:100:110}])
"""
iobs = miller_arrays[0]
iobsdata = Iobs.data()
list(iobsdata[100:110]) |
'''
8-2. Favorite Book: Write a function called favorite_book() that accepts one parameter, title.
The function should print a message, such as One of my favorite books is Alice in Wonderland.
Call the function, making sure to include a book title as an argument in the function call.
'''
def favorite_book(title):
... | """
8-2. Favorite Book: Write a function called favorite_book() that accepts one parameter, title.
The function should print a message, such as One of my favorite books is Alice in Wonderland.
Call the function, making sure to include a book title as an argument in the function call.
"""
def favorite_book(title):
... |
yieldlyDB = {'FMBXOFAQCSAD4UWU4Q7IX5AV4FRV6AKURJQYGXLW3CTPTQ7XBX6MALMSPY' : 'Yieldly - YLDY-YLDY/ALGO',
'VUY44SYOFFJE3ZIDEMA6PT34J3FAZUAE6VVTOTUJ5LZ343V6WZ3ZJQTCD4' : 'Yieldly - YLDY-OPUL',
'U3RJ4NNSASBOIY25KAVVFV6CFDOS22L7YLZBENMIVVVFEWT5WE5GHXH5VQ' : 'Yieldly - GEMS-GEMS',
... | yieldly_db = {'FMBXOFAQCSAD4UWU4Q7IX5AV4FRV6AKURJQYGXLW3CTPTQ7XBX6MALMSPY': 'Yieldly - YLDY-YLDY/ALGO', 'VUY44SYOFFJE3ZIDEMA6PT34J3FAZUAE6VVTOTUJ5LZ343V6WZ3ZJQTCD4': 'Yieldly - YLDY-OPUL', 'U3RJ4NNSASBOIY25KAVVFV6CFDOS22L7YLZBENMIVVVFEWT5WE5GHXH5VQ': 'Yieldly - GEMS-GEMS', 'BXLXRYBOM7ZNYSCRLWG6THNMO6HASTIRMJGSNJANZFS6E... |
print ( True or False ) == True
print ( True or True ) == True
print ( False or False ) == False
print ( True and False ) == False
print ( True and True ) == True
print ( False and False ) == False
print ( not True ) == False
print ( not False ) == True
print ( not True or False ) == ( (not True) or False )
print ( ... | print(True or False) == True
print(True or True) == True
print(False or False) == False
print(True and False) == False
print(True and True) == True
print(False and False) == False
print(not True) == False
print(not False) == True
print(not True or False) == (not True or False)
print(not False or False) == (not False or... |
#
# PySNMP MIB module Wellfleet-PGM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-PGM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) ... |
points_str = input("Enter the lead in points: ")
points_remaining_int = int(points_str)
lead_calculation_float= float(points_remaining_int - 3)
has_ball_str = input("Does the lead team have the ball (Yes or No): ")
if has_ball_str == "Yes":
lead_calculation_float=lead_calculation_float + 0.5
else:
lead_calcula... | points_str = input('Enter the lead in points: ')
points_remaining_int = int(points_str)
lead_calculation_float = float(points_remaining_int - 3)
has_ball_str = input('Does the lead team have the ball (Yes or No): ')
if has_ball_str == 'Yes':
lead_calculation_float = lead_calculation_float + 0.5
else:
lead_calcu... |
alien_color = 'green'
if alien_color == 'green':
print("You get 5 points.")
else:
print("\nYou get 10 points.")
alien_color = 'yellow'
if alien_color == 'green':
print("You get 5 points.")
else:
print("\nYou get 10 points.") | alien_color = 'green'
if alien_color == 'green':
print('You get 5 points.')
else:
print('\nYou get 10 points.')
alien_color = 'yellow'
if alien_color == 'green':
print('You get 5 points.')
else:
print('\nYou get 10 points.') |
class School:
def __init__(self):
"""Initiates database for the school."""
self._db = {}
def add_student(self, name, grade):
"""Add student to the school databsase."""
self._db.setdefault(grade, []).append(name)
self._db[grade].sort()
def roster(self):
"""Cr... | class School:
def __init__(self):
"""Initiates database for the school."""
self._db = {}
def add_student(self, name, grade):
"""Add student to the school databsase."""
self._db.setdefault(grade, []).append(name)
self._db[grade].sort()
def roster(self):
"""C... |
DATABASE_CONFIG = {
'uri': 'postgres://username:password@host/database'
}
JSREPORT_CONFIG = {
'uri': 'changeme',
'username': 'changeme',
'password': 'changeme',
'template': 'changeme'
}
ZIP_CONFIG = {
'name': 'flask_batch_download.zip'
}
| database_config = {'uri': 'postgres://username:password@host/database'}
jsreport_config = {'uri': 'changeme', 'username': 'changeme', 'password': 'changeme', 'template': 'changeme'}
zip_config = {'name': 'flask_batch_download.zip'} |
class Prop:
MAX_HOUSE = 4
def __init__(self, name, price, lien, house_price, class_count, klass, **taxes):
self.name = name
self.price = price
self.lien = lien
self.house_price = house_price
self.taxes = taxes
self.owner = None
self.n_house = 0
se... | class Prop:
max_house = 4
def __init__(self, name, price, lien, house_price, class_count, klass, **taxes):
self.name = name
self.price = price
self.lien = lien
self.house_price = house_price
self.taxes = taxes
self.owner = None
self.n_house = 0
se... |
#create file myaperture.dat needed for source optimization
f = open("myaperture.dat",'w')
f.write(" 50.0 -0.002 0.002 -0.002 0.002")
f.close()
print("File written to disk: myaperture.dat")
| f = open('myaperture.dat', 'w')
f.write(' 50.0 -0.002 0.002 -0.002 0.002')
f.close()
print('File written to disk: myaperture.dat') |
"""Module containing expected string output to be used in test_game.py."""
leader_board_string = expected_string = """\n-------- LEADERBOARD --------
Clive Felix 1
Adis 0
-----------------------------"""
rules_string = """\n\x1b[92mPig is a simple dice game first describe... | """Module containing expected string output to be used in test_game.py."""
leader_board_string = expected_string = '\n-------- LEADERBOARD --------\nClive Felix 1\nAdis 0\n\n \n-----------------------------'
rules_string = '\n\x1b[92mPig is a simple dice game first described ... |
# -*- encoding:utf-8 -*-
# index rule:
# 3 ------6------- 2
#
# 7 ------ ------- 5
#
# 0 ------4------- 1
# Stores the triangle values
raw_trigs = [
[],
[(0,7,4)],
[(4,5,1)],
[(0,5,1),(0,7,5)],
[(5,6,2)],
[(0,7,4), (4,7,5), (7,6,5), (5,6,2)],
[(1,4,6), (1,6,2)],
[(1,0,7), (1,7,6), (1,6,2)],
[(7,3,6)],
[(0... | raw_trigs = [[], [(0, 7, 4)], [(4, 5, 1)], [(0, 5, 1), (0, 7, 5)], [(5, 6, 2)], [(0, 7, 4), (4, 7, 5), (7, 6, 5), (5, 6, 2)], [(1, 4, 6), (1, 6, 2)], [(1, 0, 7), (1, 7, 6), (1, 6, 2)], [(7, 3, 6)], [(0, 3, 4), (4, 3, 6)], [(1, 4, 5), (4, 7, 5), (5, 7, 6), (7, 3, 6)], [(0, 5, 1), (0, 6, 5), (0, 3, 6)], [(7, 3, 5), (5, 3... |
"""
Python package to help with daily work on heusler materials.
"""
name = "heuslertools"
| """
Python package to help with daily work on heusler materials.
"""
name = 'heuslertools' |
make = "Ford"
model = "Everest"
def start_engine():
print (f'{make} {model} engine started')
| make = 'Ford'
model = 'Everest'
def start_engine():
print(f'{make} {model} engine started') |
class Resource():
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(Resource(path))
def append(self, resource):
resource.number = len(self)
super().append(r... | class Resource:
def __init__(self, path):
self.path = path
def __str__(self):
return '-i {}'.format(self.path)
class Resources(list):
def add(self, path):
self.append(resource(path))
def append(self, resource):
resource.number = len(self)
super().append(resou... |
# Python - 3.6.0
Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for name, age in zip(names, ages):
person = Person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}')
| Test.describe('Basic tests')
names = ['john', 'matt', 'alex', 'cam']
ages = [16, 25, 57, 39]
for (name, age) in zip(names, ages):
person = person(name, age)
Test.it(f'Testing for {name} and {age}')
Test.assert_equals(person.info, f'{name}s age is {age}') |
#Floating loop
first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list)
| first_list = list(range(10))
for i in first_list:
first_list[i] = float(first_list[i])
print(first_list) |
def read_file(filename):
"""
Read input file and save the lines into a list.
:param filename: input file
:return: grid of octopuses
"""
grid = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
grid.append([int(s) for s in list(line.strip())])
re... | def read_file(filename):
"""
Read input file and save the lines into a list.
:param filename: input file
:return: grid of octopuses
"""
grid = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
grid.append([int(s) for s in list(line.strip())])
re... |
# compat3.py
# Copyright (c) 2013-2019 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,W0122,W0613
###
# Functions
###
def _readlines(fname, fpointer1=open, fpointer2=open):
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try: # pragma: no cover
... | def _readlines(fname, fpointer1=open, fpointer2=open):
"""Read all lines from file."""
try:
with fpointer1(fname, 'r') as fobj:
return fobj.readlines()
except UnicodeDecodeError:
with fpointer2(fname, 'r', encoding='utf-8') as fobj:
return fobj.readlines()
def _unico... |
class Fibonacci:
"""Implementations of the Fibonacci number."""
@staticmethod
def fib_iterative(index):
"""
Iterative algorithm for calculating the Fibonacci number.
:param index: Index of a number in the Fibonacci sequence.
:return: Fibonacci number.
"""
lower = 0
higher = 1
for i in range(1, index... | class Fibonacci:
"""Implementations of the Fibonacci number."""
@staticmethod
def fib_iterative(index):
"""
Iterative algorithm for calculating the Fibonacci number.
:param index: Index of a number in the Fibonacci sequence.
:return: Fibonacci number.
"""
lower = 0
higher = ... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"win": "game.ipynb",
"lose": "game.ipynb"}
modules = ["game.py"]
doc_url = "https://thecharlieblake.github.io/solitairenet/"
git_url = "https://github.com/thecharlieblake/solitairenet/tree/master/... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'win': 'game.ipynb', 'lose': 'game.ipynb'}
modules = ['game.py']
doc_url = 'https://thecharlieblake.github.io/solitairenet/'
git_url = 'https://github.com/thecharlieblake/solitairenet/tree/master/'
def custom_doc_links(name):
return None |
""" Helper routines for generating gpu kernels for nvcc.
"""
def nvcc_kernel(name, params, body):
"""Return the c code of a kernel function.
:param params: the parameters to the function as one or more strings
:param body: the [nested] list of statements for the body of the function. These will be
se... | """ Helper routines for generating gpu kernels for nvcc.
"""
def nvcc_kernel(name, params, body):
"""Return the c code of a kernel function.
:param params: the parameters to the function as one or more strings
:param body: the [nested] list of statements for the body of the function. These will be
s... |
def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [ItemWeight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for e... | def smooth(dataset):
dataset_length = len(dataset)
dataset_extra_weights = [item_weight(*x) for x in dataset]
def get_next():
if dataset_length == 0:
return None
if dataset_length == 1:
return dataset[0][0]
total_weight = 0
result = None
for e... |
# O(nlogn) time | O(n) space
def mergeSort(array):
if len(array) <= 1:
return array
subarray = array[:]
mergeSortHelper(array, 0, len(array)-1)
return array
def mergeSortHelper(array, l, r):
if l == r:
return
m = (l + r) // 2
mergeSortHelper(array, l, m)
mergeSortHelper... | def merge_sort(array):
if len(array) <= 1:
return array
subarray = array[:]
merge_sort_helper(array, 0, len(array) - 1)
return array
def merge_sort_helper(array, l, r):
if l == r:
return
m = (l + r) // 2
merge_sort_helper(array, l, m)
merge_sort_helper(array, m + 1, r)
... |
# This is the custom function interface.
# You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
... | class Customfunction:
def f(self, x, y):
return x + y
class Solution:
def find_solution(self, customfunction, z: int):
ret = []
i = 1
while customfunction.f(i, 1) <= z:
j = 1
while True:
if customfunction.f(i, j) == z:
... |
#!/usr/bin/env python
class SulException(Exception):
"""
"""
class ConfigurationException(SulException):
pass
class ServerException(SulException):
pass
class DirectoryNotFoundException(SulException):
pass
class IntegrityException(SulException):
pass
| class Sulexception(Exception):
"""
"""
class Configurationexception(SulException):
pass
class Serverexception(SulException):
pass
class Directorynotfoundexception(SulException):
pass
class Integrityexception(SulException):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.