content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if (self.x < other.x):
return True
elif (self.x > other.x):
return False
elif (self.x == other.x):
return (self.y < other.y)
... | class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if self.x < other.x:
return True
elif self.x > other.x:
return False
elif self.x == other.x:
return self.y < other.y |
#
# CAMP
#
# Copyright (C) 2017 -- 2019 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
class About:
PROGRAM = "CAMP"
VERSION = "0.7.0"
COMMIT_HASH = None
LICENSE = "MIT"
COPYRIG... | class About:
program = 'CAMP'
version = '0.7.0'
commit_hash = None
license = 'MIT'
copyright = 'Copyright (C) 2017 -- 2019 SINTEF Digital'
description = 'Amplify your configuration tests!'
@staticmethod
def full_version():
if About.COMMIT_HASH:
return '%s-git.%s' % (... |
# SIMPLE FORMULA
# __________________________________________________________________________________________
# VARIABLE
# - Localize language: ID
textOpen=(
'Solve it! #1',
'Diketahui W=((X+YxZ)/(XxY))^Z'
)
textInX='Nilai X:'
textInY='Nilai Y:'
textInZ='Nilai Z:'
textOut='Nilai W adalah'
# ____________________... | text_open = ('Solve it! #1', 'Diketahui W=((X+YxZ)/(XxY))^Z')
text_in_x = 'Nilai X:'
text_in_y = 'Nilai Y:'
text_in_z = 'Nilai Z:'
text_out = 'Nilai W adalah'
print(f'\n{textOpen[0]}\n\n{textOpen[1]}\n')
x = int(input(f'{textInX} '))
y = int(input(f'{textInY} '))
z = int(input(f'{textInZ} '))
w = ((x + y * z) / (x * y)... |
# I have used sieve of erato algorithm to solve this problem
def seive(Max):
primes = []
isprime = [False] * (Max)
maxN = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if (isprime[i] is False):
for j in range... | def seive(Max):
primes = []
isprime = [False] * Max
max_n = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if isprime[i] is False:
for j in range(i * i, maxN, i):
isprime[j] = True
for i in r... |
class FilterError(RuntimeError):
"""
This error is raised when a filter can never match on a given model class
"""
pass
class MultipleResultsError(RuntimeError):
"""
This filter is raised when multiple results are returned while a single
one was expected
"""
| class Filtererror(RuntimeError):
"""
This error is raised when a filter can never match on a given model class
"""
pass
class Multipleresultserror(RuntimeError):
"""
This filter is raised when multiple results are returned while a single
one was expected
""" |
class Solution():
def isUnique(self, string: str):
'''Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
... | class Solution:
def is_unique(self, string: str):
"""Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
... |
class Page():
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent
| class Page:
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent |
class Multiplication:
def __init__(self,matrix1,matrix2):
self.matrix1 = matrix1
self.matrix2 = matrix2
self.result = []
def ismultiplyable(self):
"""
INPUT: No Input
OUTPUT: ismultiplyable : bool
DESC: Can matrices be multiplied?
"""
... | class Multiplication:
def __init__(self, matrix1, matrix2):
self.matrix1 = matrix1
self.matrix2 = matrix2
self.result = []
def ismultiplyable(self):
"""
INPUT: No Input
OUTPUT: ismultiplyable : bool
DESC: Can matrices be multiplied?
"""
... |
# from astra import models
#
# class UserObject(models.Model):
# def
#
#
#
class MetaDemo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = Demo()
print(d.__class__.__metaclass__)
| class Metademo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = demo()
print(d.__class__.__metaclass__) |
#!/usr/bin/env prey
async def main():
count = int(await x("ls -1 | wc -l"))
print(f"Files count: {count}")
| async def main():
count = int(await x('ls -1 | wc -l'))
print(f'Files count: {count}') |
g = int(input())
if g%2 == 0:
print("no. even")
else:
print("no. is odd")
| g = int(input())
if g % 2 == 0:
print('no. even')
else:
print('no. is odd') |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 12:25:06 2019
@author: abhij
"""
def circle_intersection(f1 = 0, f2 = 0, o1 = 0, o2 = 0, l1 = 0, l2 = 0):
R = (f1**2 + f2**2)**(0.5)
x_cor = f1 - o1
y_cor = f2 - o2
rot1 = (l1**2 - l2**2 + R**2)/(2*R)
print("\n l is", ... | """
Created on Fri Dec 20 12:25:06 2019
@author: abhij
"""
def circle_intersection(f1=0, f2=0, o1=0, o2=0, l1=0, l2=0):
r = (f1 ** 2 + f2 ** 2) ** 0.5
x_cor = f1 - o1
y_cor = f2 - o2
rot1 = (l1 ** 2 - l2 ** 2 + R ** 2) / (2 * R)
print('\n l is', rot1)
rot2 = (l1 ** 2 - rot1 ** 2) ** 0.5
pr... |
def soma_elementos(lista):
soma = 0
for i in lista:
soma = soma + i
return soma
lista = [1,2,3,4,5,6]
print(soma_elementos(lista))
| def soma_elementos(lista):
soma = 0
for i in lista:
soma = soma + i
return soma
lista = [1, 2, 3, 4, 5, 6]
print(soma_elementos(lista)) |
class str(object):
def __new__(self, *args):
if ___delta("num=", args.__len__(), 0):
return ""
else:
first_arg = ___delta("tuple-getitem", args, 0)
return first_arg.__str__()
def __init__(self, *args):
pass
def __len__(self):
int = ___id("%int")
return ___delta("strlen", se... | class Str(object):
def __new__(self, *args):
if ___delta('num=', args.__len__(), 0):
return ''
else:
first_arg = ___delta('tuple-getitem', args, 0)
return first_arg.__str__()
def __init__(self, *args):
pass
def __len__(self):
int = ___id... |
# 9.2.2 Implementation with an Unsorted List
class PriorityQueueBase:
"""Abstract base class for a priority queue."""
class _Item:
"""Lightweight composite to store priority queue items."""
__slots__ = '_key','_value'
def __init__(self,k,v):
self._key = k
self.... | class Priorityqueuebase:
"""Abstract base class for a priority queue."""
class _Item:
"""Lightweight composite to store priority queue items."""
__slots__ = ('_key', '_value')
def __init__(self, k, v):
self._key = k
self._value = v
def ___it__(self, oth... |
#!/usr/bin/python35
fp = open('hello.txt')
print('fp.tell = %s' % (fp.tell()))
fp.seek(10, SEEK_SET)
print('fp.seek(10), fp.tell() = %s' % (fp.tell()))
# only do zero cur-relative seeks
fp.seek(0, SEEK_CUR)
print('fp.seek(0, 1), fp.tell() = %s' % (fp.tell()))
fp.seek(0, SEEK_END)
print('fp.seek(0, 2), fp.tell() = ... | fp = open('hello.txt')
print('fp.tell = %s' % fp.tell())
fp.seek(10, SEEK_SET)
print('fp.seek(10), fp.tell() = %s' % fp.tell())
fp.seek(0, SEEK_CUR)
print('fp.seek(0, 1), fp.tell() = %s' % fp.tell())
fp.seek(0, SEEK_END)
print('fp.seek(0, 2), fp.tell() = %s' % fp.tell()) |
'''
Created on 02-06-2011
@author: Piotr
'''
class GeneratorInterval(object):
'''
Describes the interval in for generating the image.
@attention: DTO
'''
def __init__(self, start, stop, step=0):
'''
Constructor.
@param start: starting point of the interval
... | """
Created on 02-06-2011
@author: Piotr
"""
class Generatorinterval(object):
"""
Describes the interval in for generating the image.
@attention: DTO
"""
def __init__(self, start, stop, step=0):
"""
Constructor.
@param start: starting point of the interval
@param s... |
with open('8.input') as inputFile:
data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]]
result = 0
for d in data:
for e in d:
if len(e) in [2,3,4,7]:
result += 1
print(result)
| with open('8.input') as input_file:
data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]]
result = 0
for d in data:
for e in d:
if len(e) in [2, 3, 4, 7]:
result += 1
print(result) |
def main():
message = input("Introducir Mensaje: ")
key = int(input("Key [1-26]: "))
mode = input("Cifrar o Descifrar [c/d]: ")
if mode.lower().startswith('c'):
mode = "cifrar"
elif mode.lower().startswith('d'):
mode = "descifrar"
translated = encdec(message, key, mode)
... | def main():
message = input('Introducir Mensaje: ')
key = int(input('Key [1-26]: '))
mode = input('Cifrar o Descifrar [c/d]: ')
if mode.lower().startswith('c'):
mode = 'cifrar'
elif mode.lower().startswith('d'):
mode = 'descifrar'
translated = encdec(message, key, mode)
if mo... |
# Problem statement
# write a program to swap two numbers without using third variable
x = input()
y = input()
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
# sample input
# 10
# 20
# sample output... | x = input()
y = input()
print('Before swapping: ')
print('Value of x : ', x, ' and y : ', y)
(x, y) = (y, x)
print('After swapping: ')
print('Value of x : ', x, ' and y : ', y) |
#!/bin/zsh
'''
Table Printer
Write a function named printTable()
that takes a list of lists of strings and displays it in a well-organized table
with each column right-justified.
Assume that all the inner lists will contain the same number of strings.
For example, the value could look like this:
tableData = [['ap... | """
Table Printer
Write a function named printTable()
that takes a list of lists of strings and displays it in a well-organized table
with each column right-justified.
Assume that all the inner lists will contain the same number of strings.
For example, the value could look like this:
tableData = [['apples', 'oran... |
"""
String Formatting
"""
# Create a variable that contains the first 4 lines of lyrics from your favorite song. Add a comment that includes the song title and artist **each on their own line**! Now print out this variable.
"""
Dancing in the Moonlight
King Harvest
"""
fave_song = '''
We get it almost every night
Whe... | """
String Formatting
"""
'\nDancing in the Moonlight\nKing Harvest\n'
fave_song = "\nWe get it almost every night\nWhen that moon is big and bright\nIt's a supernatural delight\nEverybody's dancin' in the moonlight\n"
print(fave_song)
"\nWe get it almost every night\nWhen that moon is big and bright\nIt's a supernatur... |
def stable_match(a_pref: dict, b_pref: dict) -> set:
a_list = list(a_pref.keys())
match_dict = {}
while len(match_dict) != len(a_pref):
print(a_list)
for ai in a_list:
if ai in match_dict.values():
continue
print(f"{ai}")
# obtengo mejor c... | def stable_match(a_pref: dict, b_pref: dict) -> set:
a_list = list(a_pref.keys())
match_dict = {}
while len(match_dict) != len(a_pref):
print(a_list)
for ai in a_list:
if ai in match_dict.values():
continue
print(f'{ai}')
bi = a_pref[ai].po... |
#!/usr/bin/env python3
#errors.py
class ParserTongueError(Exception):
pass
########################
### Tokenizer Errors ###
########################
class TokenizerError(ParserTongueError):
pass
class TokenInstantiationTypeError(TokenizerError):
def __init__(self, message):
self.message = me... | class Parsertongueerror(Exception):
pass
class Tokenizererror(ParserTongueError):
pass
class Tokeninstantiationtypeerror(TokenizerError):
def __init__(self, message):
self.message = message
class Unknowntokentypeerror(TokenizerError):
def __init__(self, message):
self.message = mess... |
# Escreva um programa que leia um valor em metros e o exiba convertido em
# centimetros e milimetros.
n = float(input('Valor em metros: '))
cm = n * 100
mm = n * 1000
print('\033[7mCentimetros:{}cm\033[m\n\033[7mMilimetros:{}mm\033[m'.format(cm,mm)) | n = float(input('Valor em metros: '))
cm = n * 100
mm = n * 1000
print('\x1b[7mCentimetros:{}cm\x1b[m\n\x1b[7mMilimetros:{}mm\x1b[m'.format(cm, mm)) |
"""
This file contains the paths to store the data and models
Must have a dataPath and resPath defined
"""
PATH = {'data': r'/hdd/ersa',
'model': r'/hdd6/Models',
'eval': r'/hdd/Results'}
| """
This file contains the paths to store the data and models
Must have a dataPath and resPath defined
"""
path = {'data': '/hdd/ersa', 'model': '/hdd6/Models', 'eval': '/hdd/Results'} |
class Node:
"""
This class represents the nodes of the different networks on the map.
"""
def __init__(self, index, edges=None, is_taxi_stop=False, is_bus_stop=False, is_metro_stop=False,
is_ferry_stop=False):
"""
Init-function of the Node-class.
:param index: Un... | class Node:
"""
This class represents the nodes of the different networks on the map.
"""
def __init__(self, index, edges=None, is_taxi_stop=False, is_bus_stop=False, is_metro_stop=False, is_ferry_stop=False):
"""
Init-function of the Node-class.
:param index: Unique integer ind... |
x = [1,2,3]
dict = {'name': 'Victoria', 'sister': 1, 'states': ['Texas','California', 'Nevada']}
"""
for key in dict.keys():
... print('{k}: {v}'.format(k=key, v=dict[key]))
...
states: ['Texas', 'California', 'Nevada']
sister: 1
name: Victoria
for key, value in dict.items():
... if key == 'name':
... ... | x = [1, 2, 3]
dict = {'name': 'Victoria', 'sister': 1, 'states': ['Texas', 'California', 'Nevada']}
"\nfor key in dict.keys():\n... print('{k}: {v}'.format(k=key, v=dict[key]))\n...\nstates: ['Texas', 'California', 'Nevada']\nsister: 1\nname: Victoria\n\nfor key, value in dict.items():\n... if key == 'name':\n.... |
OCTICON_UNMUTE = """
<svg class="octicon octicon-unmute" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.563 2.069A.75.75 0 018 2.75v10.5a.75.75 0 01-1.238.57L3.472 11H1.75A1.75 1.75 0 010 9.25v-2.5C0 5.784.784 5 1.75 5h1.723l3.289-2.82a.75.75 0 01.801-.111... | octicon_unmute = '\n<svg class="octicon octicon-unmute" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.563 2.069A.75.75 0 018 2.75v10.5a.75.75 0 01-1.238.57L3.472 11H1.75A1.75 1.75 0 010 9.25v-2.5C0 5.784.784 5 1.75 5h1.723l3.289-2.82a.75.75 0 01.801-.111zM... |
# config.py
cfg_mnet = {
'name': 'mobilenet0.25',
'in_channels': 3,
'min_sizes': [[16, 32], [64, 128], [256, 512]],
'steps': [8, 16, 32],
'variance': [0.1, 0.2],
'clip': False,
'loc_weight': 2.0,
'gpu_train': True,
'batch_size': 64,
'ngpu': 1,
'epoch': 200,
'decay1': 190... | cfg_mnet = {'name': 'mobilenet0.25', 'in_channels': 3, 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 64, 'ngpu': 1, 'epoch': 200, 'decay1': 190, 'decay2': 220, 'image_size': 480, 'pretrain': './weights/pre... |
l = list(map(int, input().split()))
minT = l[0]
maxT = l[0]
maxI = 0
minI = 0
for i in range(0, len(l)):
if minT > l[i]:
minT = l[i]
minI = i
for i in range(0, len(l)):
if maxT < l[i]:
maxT = l[i]
maxI = i
t = l[maxI]
l[maxI] = l[minI]
l[minI] = t
print(' '.join(map(str, l)))
| l = list(map(int, input().split()))
min_t = l[0]
max_t = l[0]
max_i = 0
min_i = 0
for i in range(0, len(l)):
if minT > l[i]:
min_t = l[i]
min_i = i
for i in range(0, len(l)):
if maxT < l[i]:
max_t = l[i]
max_i = i
t = l[maxI]
l[maxI] = l[minI]
l[minI] = t
print(' '.join(map(str, ... |
def is_prime(number):
"""
>>> is_prime(3)
True
>>> is_prime(90)
False
>>> is_prime(67)
True
"""
if number <= 1:
return False
for i in range(2, number - 1):
if number % i == 0:
return False
return True
def prime_numbers(number):
"""
>>> ... | def is_prime(number):
"""
>>> is_prime(3)
True
>>> is_prime(90)
False
>>> is_prime(67)
True
"""
if number <= 1:
return False
for i in range(2, number - 1):
if number % i == 0:
return False
return True
def prime_numbers(number):
"""
>>> pri... |
"""
The negamax agent from the kaggle source code.
Runs faster if we turn down max_depth (originally 4, but too slow).
A very lazy reimplementation of negamax.py for depth 1,
but the kaggle env is tricky so I'm letting myself off.
"""
def negamax_agent(obs, config, depth=1):
columns = config.columns
rows = co... | """
The negamax agent from the kaggle source code.
Runs faster if we turn down max_depth (originally 4, but too slow).
A very lazy reimplementation of negamax.py for depth 1,
but the kaggle env is tricky so I'm letting myself off.
"""
def negamax_agent(obs, config, depth=1):
columns = config.columns
rows = co... |
# Didn't event attempt pt 2. Here's a solution cribbed from https://www.reddit.com/r/adventofcode/comments/7irzg5/2017_day_10_solutions/dr1095j/
f = "165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153"
lengths1 = [int(x) for x in f.strip().split(",")]
lengths2 = [ord(x) for x in f.strip()] + [17, 31, 73, 47, 23]
de... | f = '165,1,255,31,87,52,24,113,0,91,148,254,158,2,73,153'
lengths1 = [int(x) for x in f.strip().split(',')]
lengths2 = [ord(x) for x in f.strip()] + [17, 31, 73, 47, 23]
def run(lengths, times):
position = 0
skip = 0
sequence = list(range(256))
for _ in range(times):
for l in lengths:
... |
def getMoneySpent(keyboards, drives, b):
keyboards.sort(reverse = True)
drives.sort(reverse = True)
cost = -1
for k in keyboards:
for d in drives:
_cost = k + d
if _cost <= b:
if _cost > cost:
cost = _cost
break... | def get_money_spent(keyboards, drives, b):
keyboards.sort(reverse=True)
drives.sort(reverse=True)
cost = -1
for k in keyboards:
for d in drives:
_cost = k + d
if _cost <= b:
if _cost > cost:
cost = _cost
break
if... |
# Python - 2.7.6
Test.describe('Basic Tests')
Test.assert_equals(my_first_kata(3, 5), (3 % 5 + 5 % 3))
Test.assert_equals(my_first_kata('hello', 3), False)
Test.assert_equals(my_first_kata(67, 'bye'), False)
Test.assert_equals(my_first_kata(True, True), False)
Test.assert_equals(my_first_kata(314, 107), (107 % 314 + 3... | Test.describe('Basic Tests')
Test.assert_equals(my_first_kata(3, 5), 3 % 5 + 5 % 3)
Test.assert_equals(my_first_kata('hello', 3), False)
Test.assert_equals(my_first_kata(67, 'bye'), False)
Test.assert_equals(my_first_kata(True, True), False)
Test.assert_equals(my_first_kata(314, 107), 107 % 314 + 314 % 107)
Test.assert... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
r... | class Solution:
def max_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return self.maxDepth_bottom_up(root)
def max_depth_top_down(self, node, depth):
if node is None:
self.max_depth = max(de... |
DOMAIN = 'api.dkc.ru'
VERSION_API = 'v1'
URL_DOMAIN = f"https://{DOMAIN}/{VERSION_API}"
DEFAULT_HEADERS = {
"Accept": "*/*",
} | domain = 'api.dkc.ru'
version_api = 'v1'
url_domain = f'https://{DOMAIN}/{VERSION_API}'
default_headers = {'Accept': '*/*'} |
def strip_react(polymer_fn):
polymer = polymer_fn()
result = {}
letters = list(set(polymer.lower()))
for letter in letters:
stripped = polymer.replace(letter, "").replace(letter.upper(), "")
result[letter] = react(stripped)
return min(result.values())
def react(stripped):
i ... | def strip_react(polymer_fn):
polymer = polymer_fn()
result = {}
letters = list(set(polymer.lower()))
for letter in letters:
stripped = polymer.replace(letter, '').replace(letter.upper(), '')
result[letter] = react(stripped)
return min(result.values())
def react(stripped):
i = 0
... |
'''
Author: ZHAO Zinan
Created: 14-Nov-2018
144. Binary Tree Preorder Traversal
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
"... | """
Author: ZHAO Zinan
Created: 14-Nov-2018
144. Binary Tree Preorder Traversal
"""
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: ... |
# one object multiple reference example
"""
The below program shows that if there is changes in reference
variable, it gets also reflected in another variable too!
because there is only one object and we are creating multiple
reference variable for same object.
"""
class Mobile:
def __init__(self, price, brand):
... | """
The below program shows that if there is changes in reference
variable, it gets also reflected in another variable too!
because there is only one object and we are creating multiple
reference variable for same object.
"""
class Mobile:
def __init__(self, price, brand):
self.price = price
self... |
''' twitter API keys '''
API_KEY = ''
API_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_SECRET = ''
| """ twitter API keys """
api_key = ''
api_secret = ''
access_token = ''
access_secret = '' |
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
count = collections.Counter(words)
count_i = collections.defaultdict(list)
for c in count:
count_i[count[c]].append(c)
large = list( sorted(count_i.keys()) )
... | class Solution:
def top_k_frequent(self, words: List[str], k: int) -> List[str]:
count = collections.Counter(words)
count_i = collections.defaultdict(list)
for c in count:
count_i[count[c]].append(c)
large = list(sorted(count_i.keys()))
total = 0
ans = []... |
name='green'
def get_line(in_f,num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
[T,n] = get_line(in_f,2)
LJ = True
LJ1 = True
for i in range(T):
L = get_line(in_f,n)
... | name = 'green'
def get_line(in_f, num=1):
line = in_f.readline()
obj = line.split(' ')
if len(obj) != num and -1 != num:
print('ERROR')
for i in range(len(obj)):
obj[i] = int(obj[i])
return obj
def check_in_file(in_f):
[t, n] = get_line(in_f, 2)
lj = True
lj1 = True
... |
#
# PySNMP MIB module INNOVX-DTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INNOVX-DTE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:42:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
# Copyright 2019 Trend Micro.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | def override_reconnaissance_scan(api, configuration, api_version, api_exception, computer_id):
""" Overrides a computer to enable Firewall reconnaissance scan.
:param api: The Deep Security API modules.
:param configuration: Configuration object to pass to the api client.
:param api_version: The versio... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
summ = 0
def helper(self, root: TreeNode) -> TreeNode:
if not root: return None
root.r... | class Solution:
summ = 0
def helper(self, root: TreeNode) -> TreeNode:
if not root:
return None
root.right = self.helper(root.right)
Solution.summ += root.val
root.val = Solution.summ
root.left = self.helper(root.left)
return root
def bst_to_gst(... |
class Parent1:
def __call__(self):
return 'parent1'
class Parent2:
def foo(self):
return 'parent2'
class Child1(Parent1):
pass
| class Parent1:
def __call__(self):
return 'parent1'
class Parent2:
def foo(self):
return 'parent2'
class Child1(Parent1):
pass |
class PyCharm:
def execute(self):
print("Compiling")
print("Running")
class MyCharm:
def execute(self):
print("Spell Check")
print("Convention Check")
print("Compiling")
print("Running")
class Laptop:
def code(self, ide):
ide.execute()
ide = PyCh... | class Pycharm:
def execute(self):
print('Compiling')
print('Running')
class Mycharm:
def execute(self):
print('Spell Check')
print('Convention Check')
print('Compiling')
print('Running')
class Laptop:
def code(self, ide):
ide.execute()
ide = py_ch... |
def load_data(file_name: str = "sample"):
file = open(file_name)
data, result = [], []
try:
for line in file.read().splitlines():
data.append(line.split(" "))
except Exception as e:
print(e)
finally:
file.close()
for line in data:
result.append([i for ... | def load_data(file_name: str='sample'):
file = open(file_name)
(data, result) = ([], [])
try:
for line in file.read().splitlines():
data.append(line.split(' '))
except Exception as e:
print(e)
finally:
file.close()
for line in data:
result.append([i fo... |
coordinates = (1, 2, 3)
# coordinates[0] * coordinates[1] * coordinates[2]
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
# x * y * z
# better way
x, y, z = coordinates
# works with lists too
| coordinates = (1, 2, 3)
(x, y, z) = coordinates |
class TargetDensityError(Exception):
def __init__(self, target_density, current_density, target_metric):
p1 = f"""Target Density of {target_density} {target_metric} """
p2 = f"""is greater than Stand Total of {round(current_density, 1)} {target_metric}. """
p3 = f"""Please lower Target Densi... | class Targetdensityerror(Exception):
def __init__(self, target_density, current_density, target_metric):
p1 = f'Target Density of {target_density} {target_metric} '
p2 = f'is greater than Stand Total of {round(current_density, 1)} {target_metric}. '
p3 = f'Please lower Target Density'
... |
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root ... | class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class Binarysearchtree:
def __init__(self):
self.root = None
def create(self, val):
if self.ro... |
"""
This program prints a variable saved in a function.
"""
def print_something():
x = 10
print(x)
print_something() | """
This program prints a variable saved in a function.
"""
def print_something():
x = 10
print(x)
print_something() |
# Time: O(n)
# Space: O(1)
class Solution(object):
def minCostToMoveChips(self, chips):
"""
:type chips: List[int]
:rtype: int
"""
count = [0]*2
for p in chips:
count[p%2] += 1
return min(count)
| class Solution(object):
def min_cost_to_move_chips(self, chips):
"""
:type chips: List[int]
:rtype: int
"""
count = [0] * 2
for p in chips:
count[p % 2] += 1
return min(count) |
"""
Revision Date: 2021.08.15
SPDX-License-Identifier: BSD-2-Clause
Copyright (c) 2021 Stuart Nolan. All rights reserved.
heatOfRxn(dictionary comp, dictionary db, float T):
Parameters:
comp, dictionary of components keys
values: dictionary {stoic: [+,-] float,
... | """
Revision Date: 2021.08.15
SPDX-License-Identifier: BSD-2-Clause
Copyright (c) 2021 Stuart Nolan. All rights reserved.
heatOfRxn(dictionary comp, dictionary db, float T):
Parameters:
comp, dictionary of components keys
values: dictionary {stoic: [+,-] float,
... |
class Character:
def __init__(self, gear: int, name: str, relic: int = 0) -> None:
self.__gear: int = gear
self.__relic = relic
self.__name: str = name
@property
def gear(self) -> int:
return self.__gear
@property
def relic(self):
return self.__relic
@p... | class Character:
def __init__(self, gear: int, name: str, relic: int=0) -> None:
self.__gear: int = gear
self.__relic = relic
self.__name: str = name
@property
def gear(self) -> int:
return self.__gear
@property
def relic(self):
return self.__relic
@pr... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | load('//kotlin/internal:kt.bzl', 'kt')
load('//kotlin/internal:kt_js.bzl', 'kt_js')
load('//kotlin/internal:plugins.bzl', 'plugins')
load('//kotlin/internal:utils.bzl', 'utils')
def _declare_output_directory(ctx, aspect, dir_name):
return ctx.actions.declare_directory('_kotlinc/%s_%s/%s_%s' % (ctx.label.name, aspe... |
'''Example Lambda package file'''
def lambda_handler(event, context):
'''Example lambda function'''
return 'Hello from Cloudify & Lambda'
| """Example Lambda package file"""
def lambda_handler(event, context):
"""Example lambda function"""
return 'Hello from Cloudify & Lambda' |
def foo():
bar("some string", s2="another_string")
def bar(s: str, s2: str):
print("bar(s) here: ", s)
a = 1 + 2
return
| def foo():
bar('some string', s2='another_string')
def bar(s: str, s2: str):
print('bar(s) here: ', s)
a = 1 + 2
return |
if __name__ == "__main__":
f = open('val_files.txt', 'w')
for i in range(108):
f.writelines(['2011_09_26/2011_09_26_drive_0001_sync ', str(i).zfill(10), ' l\n'])
f.close()
print('done') | if __name__ == '__main__':
f = open('val_files.txt', 'w')
for i in range(108):
f.writelines(['2011_09_26/2011_09_26_drive_0001_sync ', str(i).zfill(10), ' l\n'])
f.close()
print('done') |
print('-=-' * 30)
termo = int(input('Termo: '))
razao = int(input('Razao '))
c = 1
while c <= 10:
print('{}'.format(termo), end=' -> ')
termo += razao
c += 1
print('Fim')
| print('-=-' * 30)
termo = int(input('Termo: '))
razao = int(input('Razao '))
c = 1
while c <= 10:
print('{}'.format(termo), end=' -> ')
termo += razao
c += 1
print('Fim') |
# Created by MechAviv
# Map ID :: 931050940
# Classified Lab : Silo
OBJECT_1 = sm.sendNpcController(2159377, -700, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_1, "summon", 0)
OBJECT_2 = sm.sendNpcController(2159378, -800, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_2, "summon", 0)
sm.setSpeakerID(2159383)
sm.removeEs... | object_1 = sm.sendNpcController(2159377, -700, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_1, 'summon', 0)
object_2 = sm.sendNpcController(2159378, -800, 30)
sm.showNpcSpecialActionByObjectId(OBJECT_2, 'summon', 0)
sm.setSpeakerID(2159383)
sm.removeEscapeButton()
sm.setPlayerAsSpeaker()
sm.setSpeakerType(3)
sm.sendNex... |
train_1 = [[[('AUTHOR_FIRST_NAME', u'J.D.'), ('AUTHOR_LAST_NAME', u'Adams'), ('AUTHOR_FIRST_NAME', u'T.L.'), ('AUTHOR_LAST_NAME', u'Herter'), ('AUTHOR_FIRST_NAME', u'G.E.'), ('AUTHOR_LAST_NAME', u'Gull'), ('AUTHOR_FIRST_NAME', u'J.'), ('AUTHOR_LAST_NAME', u'Shoenwald'), ('AUTHOR_FIRST_NAME', u'C.P.'), ('AUTHOR_LAST_N... | train_1 = [[[('AUTHOR_FIRST_NAME', u'J.D.'), ('AUTHOR_LAST_NAME', u'Adams'), ('AUTHOR_FIRST_NAME', u'T.L.'), ('AUTHOR_LAST_NAME', u'Herter'), ('AUTHOR_FIRST_NAME', u'G.E.'), ('AUTHOR_LAST_NAME', u'Gull'), ('AUTHOR_FIRST_NAME', u'J.'), ('AUTHOR_LAST_NAME', u'Shoenwald'), ('AUTHOR_FIRST_NAME', u'C.P.'), ('AUTHOR_LAST_NAM... |
# numbers
assert 2+2==4
assert (50-5*6)/4 == 5.0
assert 8/5 == 1.6
assert 7//3 == 2
assert 7//-3 == -3
width=20
height=5*9
assert width*height == 900
x=y=z=0
assert x == 0
assert y == 0
assert z == 0
assert 3 * 3.75 / 1.5 == 7.5
assert 7.0 / 2 == 3.5
# complex numbers
x = 8j
y = 8.3j
z = 3.2e6j
a = 4+2j
b = 2-3j
c = ... | assert 2 + 2 == 4
assert (50 - 5 * 6) / 4 == 5.0
assert 8 / 5 == 1.6
assert 7 // 3 == 2
assert 7 // -3 == -3
width = 20
height = 5 * 9
assert width * height == 900
x = y = z = 0
assert x == 0
assert y == 0
assert z == 0
assert 3 * 3.75 / 1.5 == 7.5
assert 7.0 / 2 == 3.5
x = 8j
y = 8.3j
z = 3200000j
a = 4 + 2j
b = 2 - 3... |
# OBJECT_TYPES
VIPREQUEST_OBJ_TYPE = 'VipRequest'
SERVERPOOL_OBJ_TYPE = 'ServerPool'
VLAN_OBJ_TYPE = 'Vlan'
| viprequest_obj_type = 'VipRequest'
serverpool_obj_type = 'ServerPool'
vlan_obj_type = 'Vlan' |
class Header:
def __init__(self, opcode, src_addr="127.0.0.1", dest_addr="127.0.0.1"):
self.opcode = str(opcode)
self.src_addr = src_addr
self.dest_addr = dest_addr
def encrypt(self, cipher):
return type(self)(
opcode=cipher.encrypt(self.opcode),
src_addr... | class Header:
def __init__(self, opcode, src_addr='127.0.0.1', dest_addr='127.0.0.1'):
self.opcode = str(opcode)
self.src_addr = src_addr
self.dest_addr = dest_addr
def encrypt(self, cipher):
return type(self)(opcode=cipher.encrypt(self.opcode), src_addr=cipher.encrypt(self.src... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - diff3 algorithm
@copyright: 2002 by Florian Festi
@license: GNU GPL, see COPYING for details.
"""
def text_merge(old, other, new, allow_conflicts=1,
marker1='<<<<<<<<<<<<<<<<<<<<<<<<<\n',
marker2='=========================\n',
... | """
MoinMoin - diff3 algorithm
@copyright: 2002 by Florian Festi
@license: GNU GPL, see COPYING for details.
"""
def text_merge(old, other, new, allow_conflicts=1, marker1='<<<<<<<<<<<<<<<<<<<<<<<<<\n', marker2='=========================\n', marker3='>>>>>>>>>>>>>>>>>>>>>>>>>\n'):
""" do line by line ... |
#!/usr/bin/python
ROS_VISION_NODE_NAME = 'vision'
ROS_BRIDGE_ENCODING = "bgr8"
ROS_CONFIG_FILE_PATH = '/vision/config_folder'
ROS_IS_RECONFIGURE = '/vision/reconfigure'
ROS_SUBSCRIBER_WEBCAM_TOPIC_NAME = "/usb_cam/image_raw"
ROS_SUBSCRIBER_MOUSE_EVENT_TOPIC_NAME = "/ui/mouse_event"
ROS_SUBSCRIBER_CONFIG_START_TOPIC_... | ros_vision_node_name = 'vision'
ros_bridge_encoding = 'bgr8'
ros_config_file_path = '/vision/config_folder'
ros_is_reconfigure = '/vision/reconfigure'
ros_subscriber_webcam_topic_name = '/usb_cam/image_raw'
ros_subscriber_mouse_event_topic_name = '/ui/mouse_event'
ros_subscriber_config_start_topic_name = '/vision/recon... |
n = int(input())
s = 0
for i in range(1,n+1):
if i%3 !=0 and i%5 !=0:
s += i
print(s) | n = int(input())
s = 0
for i in range(1, n + 1):
if i % 3 != 0 and i % 5 != 0:
s += i
print(s) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-10 15:18:29
# @Author : Lewis Tian (taseikyo@gmail.com)
# @Link : github.com/taseikyo
# @Version : Python3.7
# https://projecteuler.net/problem=6
# (1 + 2 + ... 100)^2 - (1^2 + 2^2 + ... 100^2) =
# 2 * [(1*2 + 1*3 + ... 1*100) + (2*3 + 2*4 + ... 2... | def main():
return 2 * sum((x * y for x in range(1, 101) for y in range(x + 1, 101)))
if __name__ == '__main__':
print(main()) |
# Copyright 2020 Google
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | """
Rust Analyzer Bazel rules.
rust_analyzer will generate a rust-project.json file for the
given targets. This file can be consumed by rust-analyzer as an alternative
to Cargo.toml files.
"""
load('@io_bazel_rules_rust//rust:private/utils.bzl', 'find_toolchain')
_rust_rules = ['rust_library', 'rust_binary']
rust_targ... |
class RedshiftSchema(object):
def schema_exists(self, schema):
sql = f"select * from pg_namespace where nspname = '{schema}'"
res = self.query(sql)
return res.num_rows > 0
def create_schema_with_permissions(self, schema, group=None):
"""
Creates a Redshift schema (if it... | class Redshiftschema(object):
def schema_exists(self, schema):
sql = f"select * from pg_namespace where nspname = '{schema}'"
res = self.query(sql)
return res.num_rows > 0
def create_schema_with_permissions(self, schema, group=None):
"""
Creates a Redshift schema (if it... |
"""Module containing the `NodeOrigin` class used to store node origin info."""
class NodeOrigin:
"""
Class representing the origin of an AST node.
Attributes:
file {string} -- Source file from which the node originates.
start {int|None} -- starting line number at which the node was found.... | """Module containing the `NodeOrigin` class used to store node origin info."""
class Nodeorigin:
"""
Class representing the origin of an AST node.
Attributes:
file {string} -- Source file from which the node originates.
start {int|None} -- starting line number at which the node was found.
... |
# Write a Python program to test whether a number is within 100 of 1000 or 2000.
n = int(input("Enter a number: "))
def near_thousand(x):
return ((abs(1000 - x) <= 100) or (abs(2000 - x) <= 100))
print(near_thousand(n))
| n = int(input('Enter a number: '))
def near_thousand(x):
return abs(1000 - x) <= 100 or abs(2000 - x) <= 100
print(near_thousand(n)) |
class Char:
def __init__(self):
self.name = ""
self.max_health = 100
class Attributes:
def __init__(self):
self.str = 0
self.agi = 0
self.dex = 0
self.lck = 0
self.chr = 0
self.end = 0
self.spr = 0
self.wis = 0
| class Char:
def __init__(self):
self.name = ''
self.max_health = 100
class Attributes:
def __init__(self):
self.str = 0
self.agi = 0
self.dex = 0
self.lck = 0
self.chr = 0
self.end = 0
self.spr = 0
self.wis = 0 |
class app:
def __init__(self):
print('test')
if __name__ == '__main__':
app() | class App:
def __init__(self):
print('test')
if __name__ == '__main__':
app() |
class InvalidRequestMethodErr(Exception):
pass
class InvalidDownloadMiddlewareErr(Exception):
pass
class InvalidMiddlewareErr(Exception):
pass
class QueueEmptyErr(Exception):
pass
class InvalidDownloaderErr(Exception):
pass
class UnhandledDownloadErr(Exception):
pass
| class Invalidrequestmethoderr(Exception):
pass
class Invaliddownloadmiddlewareerr(Exception):
pass
class Invalidmiddlewareerr(Exception):
pass
class Queueemptyerr(Exception):
pass
class Invaliddownloadererr(Exception):
pass
class Unhandleddownloaderr(Exception):
pass |
load("@bazel_skylib//lib:unittest.bzl", "asserts", "analysistest")
load("cppwinrt.bzl", "cppwinrt")
def _test_impl(ctx):
env = analysistest.begin(ctx)
target_under_test = analysistest.target_under_test(env)
actions = analysistest.target_actions(env)
header_output = actions[0].outputs.to_list()[0]
a... | load('@bazel_skylib//lib:unittest.bzl', 'asserts', 'analysistest')
load('cppwinrt.bzl', 'cppwinrt')
def _test_impl(ctx):
env = analysistest.begin(ctx)
target_under_test = analysistest.target_under_test(env)
actions = analysistest.target_actions(env)
header_output = actions[0].outputs.to_list()[0]
a... |
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
while nums[i] > 0 and nums[i] <= len(nums) and nums[i] != nums[nums[i]-1]:
t = nums[i] - 1
nums[t], n... | class Solution(object):
def first_missing_positive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
while nums[i] > 0 and nums[i] <= len(nums) and (nums[i] != nums[nums[i] - 1]):
t = nums[i] - 1
(nu... |
(day, month, year) = input().strip().split()
day = int(day); month = int(month); year = int(year)
if month < 3:
month += 12
year -= 1
c = year / 100
k = year % 100
day + 26 * (m + 1) / 10 + k + k/4
week_day_name = ''
# 1. Follow from flowchart
if 0 == week_day:
week_day_name = 'SAT'
elif 1 == week_day... | (day, month, year) = input().strip().split()
day = int(day)
month = int(month)
year = int(year)
if month < 3:
month += 12
year -= 1
c = year / 100
k = year % 100
day + 26 * (m + 1) / 10 + k + k / 4
week_day_name = ''
if 0 == week_day:
week_day_name = 'SAT'
elif 1 == week_day:
week_day_name = 'SUN'
elif ... |
#using strings
myString ="my time is longer"
myInteger= 23
int =455
print(int)
print(myString.upper()) #all in capital letters
print(myString.lower()) #all in lowercase
print(myString.capitalize()) # the first letter is in capital letter
print(myString.swapcase()) #change all in capital letters because the original s... | my_string = 'my time is longer'
my_integer = 23
int = 455
print(int)
print(myString.upper())
print(myString.lower())
print(myString.capitalize())
print(myString.swapcase())
print(myString.count('i'))
print(myString.replace('time', 'computer'))
print(myString.startswith('me'))
print(myString.endswith('longer'))
print(my... |
class Animal():
def __init__(self,name):
self.name =name
#a = Animal("dog")
#print(a.name)
| class Animal:
def __init__(self, name):
self.name = name |
#
# Copyright 2022 Embedded Systems Unit, Fondazione Bruno Kessler
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | """
Module for all PyVmt exceptions
"""
class Pyvmtexception(Exception):
"""
Base exception for pyvmt
"""
class Unexpectedstatevariableerror(PyvmtException):
"""
Raised when a formula which shouldn't have next/prev state variables has one
"""
class Statevariableerror(PyvmtExceptio... |
def save_color_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result'])
def save_depth_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result'])
| def save_color_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result'])
def save_depth_image(db, data):
db.update_snapshot(data['user'], data['timestamp'], data['result']) |
class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
r = []
for row in range(len(matrix)):
m = min(matrix[row])
i = matrix[row].index(m)
flag = True
for k in range(len(matrix)):
if matrix[k][i]>m:
... | class Solution:
def lucky_numbers(self, matrix: List[List[int]]) -> List[int]:
r = []
for row in range(len(matrix)):
m = min(matrix[row])
i = matrix[row].index(m)
flag = True
for k in range(len(matrix)):
if matrix[k][i] > m:
... |
## scale and fit on the scaled data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
pred = KMeans(4).fit_predict(X_scaled)
# plotting
xmin,ymin,xmax,ymax = *X_scaled.min(0), *X_scaled.max(0) # the "*" just unpacks the values, not multiplication
plt.scatter(X_scaled[:,0],X_scaled[:,1], c=pred)
plt.xlim(xm... | scaler = standard_scaler()
x_scaled = scaler.fit_transform(X)
pred = k_means(4).fit_predict(X_scaled)
(xmin, ymin, xmax, ymax) = (*X_scaled.min(0), *X_scaled.max(0))
plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=pred)
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.title('KMeans with scaling') |
class BreakoutException(Exception):
pass
class FunctionThrownException(Exception):
def __init__(self, outer, step):
self.outer = outer
self.step = step
def o_add(input_list, position, param1, param2, param3):
param3(input_list, input_list[position+3], True, param1(input_list, input_lis... | class Breakoutexception(Exception):
pass
class Functionthrownexception(Exception):
def __init__(self, outer, step):
self.outer = outer
self.step = step
def o_add(input_list, position, param1, param2, param3):
param3(input_list, input_list[position + 3], True, param1(input_list, input_list... |
"""
A full binary tree is a tree which has either 0 children or 2 children
"""
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check(root):
if not root:
return True
if not root.left and not root.right:
return True
i... | """
A full binary tree is a tree which has either 0 children or 2 children
"""
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check(root):
if not root:
return True
if not root.left and (not root.right):
return True
if... |
class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's static settings"""
# Screen settings
self.screen_width = 1280
self.screen_height = 720
self.bg_color = (230, 230, 230)
# Ship Settin... | class Settings:
"""A class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's static settings"""
self.screen_width = 1280
self.screen_height = 720
self.bg_color = (230, 230, 230)
self.ship_limit = 2
self.bullet_width = 5
... |
for i in range(0, 9):
if i == 5:
continue
print(i)
print("Loop is end.") | for i in range(0, 9):
if i == 5:
continue
print(i)
print('Loop is end.') |
# -*- coding: utf-8 -*-
def factorial_func(n: int):
if isinstance(n, int) and n < 0:
raise ValueError('Number n must be an integer and n is not an negative!')
res = 1
while n >= 2:
res *= n
n -= 1
return res
def fib_func(n):
if isinstance(n, int) and n < 1:
raise... | def factorial_func(n: int):
if isinstance(n, int) and n < 0:
raise value_error('Number n must be an integer and n is not an negative!')
res = 1
while n >= 2:
res *= n
n -= 1
return res
def fib_func(n):
if isinstance(n, int) and n < 1:
raise value_error('Number n must... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Constants for batch tests (tests with multiple actions)."""
# number of objects in a batch
COUNT = 2
# number of try operations
TRY_COUNT = 2
| """Constants for batch tests (tests with multiple actions)."""
count = 2
try_count = 2 |
fuel_type = input()
fuel_amount = float(input())
club_card = input()
gasoline_price = 2.22
diesel_price = 2.33
gas_price = 0.93
if fuel_type == "Gas":
if club_card == "Yes":
if 20 <= fuel_amount <= 25:
fuel_price = fuel_amount * (gas_price - 0.08)
fuel_price = fuel_price - (fuel_pr... | fuel_type = input()
fuel_amount = float(input())
club_card = input()
gasoline_price = 2.22
diesel_price = 2.33
gas_price = 0.93
if fuel_type == 'Gas':
if club_card == 'Yes':
if 20 <= fuel_amount <= 25:
fuel_price = fuel_amount * (gas_price - 0.08)
fuel_price = fuel_price - fuel_price... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Complete The Pattern #6 - Odd Ladder
#Problem level: 7 kyu
def pattern(n):
return "\n".join(str(i)*i for i in range(1, n+1) if i%2)
| def pattern(n):
return '\n'.join((str(i) * i for i in range(1, n + 1) if i % 2)) |
def power_iteration(A, m0=1, u0=None, eps=1e-8, max_steps=500, verbose=False):
m = m0
u = u0
for k in range(int(max_steps)):
if verbose:
print(k, m, u)
m_prev = m
v = dot(A, u)
mi = argmax(abs(v))
m = v[mi]
u = v / m
... | def power_iteration(A, m0=1, u0=None, eps=1e-08, max_steps=500, verbose=False):
m = m0
u = u0
for k in range(int(max_steps)):
if verbose:
print(k, m, u)
m_prev = m
v = dot(A, u)
mi = argmax(abs(v))
m = v[mi]
u = v / m
if abs(m - m_prev) <= ... |
try:
pass
except:
pass
| try:
pass
except:
pass |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def freeGLUT():
http_archive(
name="FreeGLUT" ,
build_file="//bazel/deps/FreeGLUT:build.BUILD" ,
sha256="90828907e... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def free_glut():
http_archive(name='FreeGLUT', build_file='//bazel/deps/FreeGLUT:build.BUILD', sha256='90828907ea4e30a79ce7f36c5b3e4d60039912d92ec17788fd709c955f4d0a04', strip_prefix='FreeGLUT-349a23dcc1264a76deb79962d1c90462ad0c6f50', urls=['htt... |
def comb(bam_file,fq_start,fq_end):
fq={}
with open(fq_start) as f:
lines = f.readlines()
for i in range(1,len(lines),4):
l = len(lines[i].strip())
name = lines[i-1].strip()[1:]
fq[name]=[str(l)]
with open(fq_end) as f:
lines = f.readlines()
for i in range(1,l... | def comb(bam_file, fq_start, fq_end):
fq = {}
with open(fq_start) as f:
lines = f.readlines()
for i in range(1, len(lines), 4):
l = len(lines[i].strip())
name = lines[i - 1].strip()[1:]
fq[name] = [str(l)]
with open(fq_end) as f:
lines = f.readlines()
for i in... |
__author__ = """
Forzend Mainer
https://github.com/0Kit/
"""
__version__ = '1.0'
| __author__ = '\n Forzend Mainer\n https://github.com/0Kit/\n'
__version__ = '1.0' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.