content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def trailingZeroes(self, n: int) -> int:
l2 = [self.func(i, 2) for i in range(1, n+1) if i % 2 == 0]
l5 = [self.func(i, 5) for i in range(1, n + 1) if i % 5 == 0]
suml2 = sum(l2)
suml5 = sum(l5)
r = min(suml2, suml5)
return r
def func(self, n, i):... | class Solution:
def trailing_zeroes(self, n: int) -> int:
l2 = [self.func(i, 2) for i in range(1, n + 1) if i % 2 == 0]
l5 = [self.func(i, 5) for i in range(1, n + 1) if i % 5 == 0]
suml2 = sum(l2)
suml5 = sum(l5)
r = min(suml2, suml5)
return r
def func(self, n,... |
css = """
body {
font-family: Roboto, Helvetica, Arial, sans-serif;
font-size:14px;
color: #555555;
background-color:#f5f5f5;
margin-left: 5px;
}
.container{
padding-right:5px;
padding-left:5px;
... | css = '\n body {\n font-family: Roboto, Helvetica, Arial, sans-serif;\n font-size:14px;\n color: #555555;\n background-color:#f5f5f5;\n margin-left: 5px;\n }\n .container{\n padding-right:5px;\n padding-left:5p... |
def solution(N):
# write your code in Python 3.6
binary = to_binary(N)
started = False
max_gap = 0
current_gap = 0
for i in range(len(binary)):
if not started:
started = binary[i] == '1'
else:
if binary[i] == '1':
max_gap = max(current_gap,... | def solution(N):
binary = to_binary(N)
started = False
max_gap = 0
current_gap = 0
for i in range(len(binary)):
if not started:
started = binary[i] == '1'
elif binary[i] == '1':
max_gap = max(current_gap, max_gap)
current_gap = 0
else:
... |
# Here follows example input:
fs = 48000 # Sample rate (Hz)
base_freq = 100. # Base frequency (Hz)
bpm = 120 # Beats per minute
| fs = 48000
base_freq = 100.0
bpm = 120 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]':
queue = collections.deque([(root, 0, 0)])
d = collect... | class Solution:
def vertical_traversal(self, root: 'TreeNode') -> 'List[List[int]]':
queue = collections.deque([(root, 0, 0)])
d = collections.defaultdict(list)
while queue:
(node, x, y) = queue.popleft()
d[x].append((y, node.val))
if node.left:
... |
VALIGN_TOP = "top"
VALIGN_CENTER = "center"
VALIGN_BASELINE = "baseline"
VALIGN_BOTTOM = "bottom"
HALIGN_LEFT = "left"
HALIGN_CENTER = "center"
HALIGN_RIGHT = "right"
PROPAGATE_UP = "up"
PROPAGATE_DOWN = "down"
NO_PROPAGATION = "local"
NO_LOCAL_INVOKE = "nolocal"
BOLD = "bold"
NORMAL = "normal"
SEMIBOLD = "semibold"
LE... | valign_top = 'top'
valign_center = 'center'
valign_baseline = 'baseline'
valign_bottom = 'bottom'
halign_left = 'left'
halign_center = 'center'
halign_right = 'right'
propagate_up = 'up'
propagate_down = 'down'
no_propagation = 'local'
no_local_invoke = 'nolocal'
bold = 'bold'
normal = 'normal'
semibold = 'semibold'
le... |
def sum_numbers(first_int, second_int):
"""Returns the sum of the two integers"""
result = first_int + second_int
return result
def subtract(third_int):
"""Returns the difference between the
result of sum_numbers and the third integer"""
diff = sum_numbers(first_int=number_1, second_int=numbe... | def sum_numbers(first_int, second_int):
"""Returns the sum of the two integers"""
result = first_int + second_int
return result
def subtract(third_int):
"""Returns the difference between the
result of sum_numbers and the third integer"""
diff = sum_numbers(first_int=number_1, second_int=number_... |
# -*- coding: utf-8 -*-
"""
Created on 2018-6-12
@author: cheng.li
"""
class PortfolioBuilderException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return str(self.msg) | """
Created on 2018-6-12
@author: cheng.li
"""
class Portfoliobuilderexception(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return str(self.msg) |
# hackerrank problem of problem solving
# problem statement : Picking Numbers
def pickingNumbers(arr) :
left = 0
max_sum = 0;max_left = 0;max_right=0
for i in range(1, len(arr)) :
if abs(arr[i] - arr[i-1]) > 1 :
number = i - left
if number > max_sum :
... | def picking_numbers(arr):
left = 0
max_sum = 0
max_left = 0
max_right = 0
for i in range(1, len(arr)):
if abs(arr[i] - arr[i - 1]) > 1:
number = i - left
if number > max_sum:
max_sum = number
max_left = left
max_right = ... |
st = input()
sum = 0
for s in st:
t = ord(s)
if t >= ord('a'):
sum += t - ord('a') + 1
else:
sum += t - ord('A') + 27
ii = 2
for i in range(2, sum + 1):
if sum % i == 0:
ii = i
break
if ii == sum or sum == 1 :
print('It is a prime word.')
else :
print('It is not a... | st = input()
sum = 0
for s in st:
t = ord(s)
if t >= ord('a'):
sum += t - ord('a') + 1
else:
sum += t - ord('A') + 27
ii = 2
for i in range(2, sum + 1):
if sum % i == 0:
ii = i
break
if ii == sum or sum == 1:
print('It is a prime word.')
else:
print('It is not a p... |
def is_before_after(img_path):
"""
check weather image is a before after
:param img_path:
:return:
""" | def is_before_after(img_path):
"""
check weather image is a before after
:param img_path:
:return:
""" |
mainstr="the quick brown fox jumped over the lazy dog. the dog slept over the verandah"
newstr=mainstr.split(" ")
i=0
a=" "
while i<len(newstr):
if newstr[i]=="over":
a=a+"on"+" "
else:
a=a+newstr[i]+" "
i+=1
print(a) | mainstr = 'the quick brown fox jumped over the lazy dog. the dog slept over the verandah'
newstr = mainstr.split(' ')
i = 0
a = ' '
while i < len(newstr):
if newstr[i] == 'over':
a = a + 'on' + ' '
else:
a = a + newstr[i] + ' '
i += 1
print(a) |
def chemelements():
periodic_elements = ["Ac","Al","Ag","Am","Ar","As","At","Au","B","Ba","Bh","Bi","Be",
"Bk","Br","C","Ca","Cd","Ce","Cf","Cl","Cm","Co","Cr","Cs","Cu",
"Db","Dy","Er","Es","Eu","F","Fe","Fm","Fr","Ga","Gd","Ge","H",
"He","Hf","Hg","Ho... | def chemelements():
periodic_elements = ['Ac', 'Al', 'Ag', 'Am', 'Ar', 'As', 'At', 'Au', 'B', 'Ba', 'Bh', 'Bi', 'Be', 'Bk', 'Br', 'C', 'Ca', 'Cd', 'Ce', 'Cf', 'Cl', 'Cm', 'Co', 'Cr', 'Cs', 'Cu', 'Db', 'Dy', 'Er', 'Es', 'Eu', 'F', 'Fe', 'Fm', 'Fr', 'Ga', 'Gd', 'Ge', 'H', 'He', 'Hf', 'Hg', 'Ho', 'Hs', 'I', 'In', 'Ir'... |
"""Top-level package for evq."""
__author__ = """Sylwester Czmil"""
__email__ = 'sylwekczmil@gmail.com'
__version__ = '0.0.2'
| """Top-level package for evq."""
__author__ = 'Sylwester Czmil'
__email__ = 'sylwekczmil@gmail.com'
__version__ = '0.0.2' |
# -*- coding: utf-8 -*-
"""Top-level package for MagniPy."""
__author__ = """Daniel Gilman"""
__email__ = 'gilmanda@ucla.edu'
__version__ = '0.1.0'
| """Top-level package for MagniPy."""
__author__ = 'Daniel Gilman'
__email__ = 'gilmanda@ucla.edu'
__version__ = '0.1.0' |
class Foo():
def g(self):
pass
class Bar():
def f(self):
pass
| class Foo:
def g(self):
pass
class Bar:
def f(self):
pass |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PRO... | new_registers = [{'target': 'system', 'register': 'vtype', 'size': 64, 'physical_register': 'vtype', 'index': '0xc21', 'fields': [{'field': 'VILL', 'shift': 63, 'size': 1}, {'field': 'RESERVED (WRITE 0)', 'shift': 8, 'size': 55}, {'field': 'VMA', 'shift': 7, 'size': 1}, {'field': 'VTA', 'shift': 6, 'size': 1}, {'field'... |
'''
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes.
The new pile should follow these directions: if cube_i is on top of cube_j then cube_j >= cube_i.
When stacking the cubes, you can only pick up either the
leftmost or the rightmost cube each ti... | """
There is a horizontal row of cubes. The length of each cube is given. You need to create a new vertical pile of cubes.
The new pile should follow these directions: if cube_i is on top of cube_j then cube_j >= cube_i.
When stacking the cubes, you can only pick up either the
leftmost or the rightmost cube each ti... |
# coding: utf-8
# Copyright (c) Scanlon Materials Theory Group
# Distributed under the terms of the MIT License.
"""
Package containing functions for loading and manipulating phonon data.
"""
| """
Package containing functions for loading and manipulating phonon data.
""" |
#: Common folder in which the data file are related.
DATA_ROOT_FOLDER = '/Users/mdartiailh/Labber/Data/2019/'
#: Dictionary of parallel field, file path.
DATA_PATHS = {400: '03/Data_0316/JS124S_BM002_390.hdf5',
# 350: '03/Data_0317/JS124S_BM002_392.hdf5',
# 300: '03/Data_0318/JS124S_BM002_3... | data_root_folder = '/Users/mdartiailh/Labber/Data/2019/'
data_paths = {400: '03/Data_0316/JS124S_BM002_390.hdf5', 250: '03/Data_0318/JS124S_BM002_395.hdf5', 100: '03/Data_0321/JS124S_BM002_405.hdf5', -300: '04/Data_0430/JS124S_BM002_532.hdf5'}
field_ranges = {400: (-0.008, -0.0055), 350: (None, -0.006), 300: (-0.00659,... |
def poly_conversion_array(eq, var):
poly = eq.split()
coeffPower = []
i = 1
while i < len(poly):
poly.insert(i, poly[i] + poly[i + 1])
poly.pop(i + 1)
poly.pop(i + 1)
i += 1
for j in poly:
cp = j.split(var)
if len(cp) == 1:
cp.append(0)
... | def poly_conversion_array(eq, var):
poly = eq.split()
coeff_power = []
i = 1
while i < len(poly):
poly.insert(i, poly[i] + poly[i + 1])
poly.pop(i + 1)
poly.pop(i + 1)
i += 1
for j in poly:
cp = j.split(var)
if len(cp) == 1:
cp.append(0)
... |
def selection(arr):
for i in range(0, len(arr)):
# Min idx starts always at the ith element
min_idx = i
# Look for any local minima going forward
for j in range(i+1, len(arr)):
# If we find one, set the min_idx to what we find
if arr[j] < arr[mi... | def selection(arr):
for i in range(0, len(arr)):
min_idx = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
(arr[i], arr[min_idx]) = (arr[min_idx], arr[i])
if __name__ == '__main__':
arrs = [[4, 3, 3, 7, 6, -1, 10, 3, 8, 4], [10, 11, 9,... |
# This file will store strings for the entire app
# Error Strings
space_in_first_name_error = 'First name may not contain spaces'
space_in_last_name_error = 'Last name may not contain spaces'
# Dashboard Strings
my_projects = "My Projects"
no_projects = "Looks like you don't have any projects yet. Select Add project,... | space_in_first_name_error = 'First name may not contain spaces'
space_in_last_name_error = 'Last name may not contain spaces'
my_projects = 'My Projects'
no_projects = "Looks like you don't have any projects yet. Select Add project, or check back later."
add_project_button = 'add project'
join_code_prompt = 'Enter a jo... |
# Copyright 2020 The XLS Authors
#
# 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 writ... | """See dslx_test()."""
load('//xls/build_rules:genrule_wrapper.bzl', 'genrule_wrapper')
load('//xls/build_rules:dslx_codegen.bzl', 'make_benchmark_args')
_interpreter_main = '//xls/dslx:interpreter_main'
_dslx_test = '//xls/dslx/interpreter:dslx_test'
def _convert_ir(name, src, entry, srcs, deps, tags, args, prove_uno... |
show_in_list = True
title = 'Detector Configuration'
motor_names = ['collect.detector_configuration', 'xray_scope.setup', 'laser_scope.setup']
names = ['detectors', 'xray_scope_setup', 'laser_scope_setup', 'motor2']
motor_labels = ['Detectors', 'X-ray Scope Setup', 'Laser Scope Setup']
widths = [280, 170, 170]
line0.xr... | show_in_list = True
title = 'Detector Configuration'
motor_names = ['collect.detector_configuration', 'xray_scope.setup', 'laser_scope.setup']
names = ['detectors', 'xray_scope_setup', 'laser_scope_setup', 'motor2']
motor_labels = ['Detectors', 'X-ray Scope Setup', 'Laser Scope Setup']
widths = [280, 170, 170]
line0.xr... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# linkIntegrity : Link integrity and bandwidth test
def get_link_integrity_test_result(
self,
ne_id: str,
) -> dict:
"""Retrieve current link integrity test status/results from
appliance
.. list-table::
:heade... | def get_link_integrity_test_result(self, ne_id: str) -> dict:
"""Retrieve current link integrity test status/results from
appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - linkIntegrity
- GET
- /linkIntegri... |
# Setters for the results dictionary
def set_error(name, message):
global _error
_error = {}
_error = {"Hostname": name, "Message": message}
return _error
def new():
return {
'Hostname': None,
'IP': None,
'MD5': None,
'View':... | def set_error(name, message):
global _error
_error = {}
_error = {'Hostname': name, 'Message': message}
return _error
def new():
return {'Hostname': None, 'IP': None, 'MD5': None, 'View': None, 'Results': []}
def set_result(results, key, value):
results[key] = value
def set_ciphers(results, v... |
class FloorType(HostObjAttributes, IDisposable):
""" An object that specifies the type of a floor in Autodesk Revit. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self, *args):
""" getBoundingBox(self: Element,view: View) -> Boundin... | class Floortype(HostObjAttributes, IDisposable):
""" An object that specifies the type of a floor in Autodesk Revit. """
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_bounding_box(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXY... |
def get_input():
with open("input.txt", "r") as file:
return file.read()
def quiz1(data):
print(data.count("(") - data.count(")"))
def quiz2(data):
count = 0
for i, p in enumerate(data):
if p == ("("):
count += 1
if p == (")"):
count -= 1
if c... | def get_input():
with open('input.txt', 'r') as file:
return file.read()
def quiz1(data):
print(data.count('(') - data.count(')'))
def quiz2(data):
count = 0
for (i, p) in enumerate(data):
if p == '(':
count += 1
if p == ')':
count -= 1
if count ... |
user = "DB_USER"
password = "DB_PASS"
token = "API_TOKEN"
valid_chats = []
| user = 'DB_USER'
password = 'DB_PASS'
token = 'API_TOKEN'
valid_chats = [] |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | """Rules for auto-generating the Paths_* module needed in third-party.
Some third-party Haskell packages use a Paths_{package_name}.hs file
which is auto-generated by Cabal. That file lets them
- Get the package's current version number
- Find useful data file
This file exports the "cabal_paths" rule for auto-genera... |
MASK = 0xffffffffffffffff
BLOCK_LEN_INT64 = 8
BLOCK_LEN_BYTES = 8 * BLOCK_LEN_INT64
blake2b_IV = [
0x6a09e667f3bcc908, 0xbb67ae8584caa73b,
0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
0x510e527fade682d1, 0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b, 0x5be0cd19137e2179
]
def rotr(w, c):
return (w >> c) | (w ... | mask = 18446744073709551615
block_len_int64 = 8
block_len_bytes = 8 * BLOCK_LEN_INT64
blake2b_iv = [7640891576956012808, 13503953896175478587, 4354685564936845355, 11912009170470909681, 5840696475078001361, 11170449401992604703, 2270897969802886507, 6620516959819538809]
def rotr(w, c):
return w >> c | w << 64 - c
... |
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
q = 0
m = len(matrix) - 1
while q < len(matrix) // 2:
c = 0
while c < len(matrix) - 1 - q * 2:
n... | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
q = 0
m = len(matrix) - 1
while q < len(matrix) // 2:
c = 0
while c < len(matrix) - 1 - q * 2:
n... |
"""
"""
lengths = []
for len_file in snakemake.input:
with open(len_file, 'r') as lf:
lengths.append(int(lf.readline().strip()))
with open(snakemake.output[0], "w") as out_file:
print(min(lengths), file=out_file)
| """
"""
lengths = []
for len_file in snakemake.input:
with open(len_file, 'r') as lf:
lengths.append(int(lf.readline().strip()))
with open(snakemake.output[0], 'w') as out_file:
print(min(lengths), file=out_file) |
# https://leetcode.com/problems/valid-parentheses/
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c == ')':
if len(stack) > 0 and stack[-1] == '(':
stack.pop()
else:
return Fal... | class Solution:
def is_valid(self, s: str) -> bool:
stack = []
for c in s:
if c == ')':
if len(stack) > 0 and stack[-1] == '(':
stack.pop()
else:
return False
elif c == '}':
if len(stack)... |
def create_lkas(packer, enabled, frame, lat_active, apply_steer):
values = {
"LKA_MODE": 2,
"LKA_ICON": 2 if enabled else 1,
"TORQUE_REQUEST": apply_steer,
"LKA_ASSIST": 1 if lat_active else 0,
"STEER_REQ": 1 if lat_active else 0,
"STEER_MODE": 0,
"SET_ME_1": 0,
"NEW_SIGNAL_1": 0,
... | def create_lkas(packer, enabled, frame, lat_active, apply_steer):
values = {'LKA_MODE': 2, 'LKA_ICON': 2 if enabled else 1, 'TORQUE_REQUEST': apply_steer, 'LKA_ASSIST': 1 if lat_active else 0, 'STEER_REQ': 1 if lat_active else 0, 'STEER_MODE': 0, 'SET_ME_1': 0, 'NEW_SIGNAL_1': 0, 'NEW_SIGNAL_2': 0}
return packe... |
# https://leetcode-cn.com/problems/binary-search/
def binary_search(nums, target):
if not nums:
return -1
if nums[0] > target or nums[-1] < target:
return -1
l, r = 0, len(nums) - 1
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return m
e... | def binary_search(nums, target):
if not nums:
return -1
if nums[0] > target or nums[-1] < target:
return -1
(l, r) = (0, len(nums) - 1)
while l <= r:
m = l + (r - l) // 2
if nums[m] == target:
return m
elif nums[m] > target:
r = m - 1
... |
def human_readable_size(size, decimal_places=2):
for unit in ['B','KB','MB','GB','TB']:
if size < 1024.0:
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
| def human_readable_size(size, decimal_places=2):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0:
break
size /= 1024.0
return f'{size:.{decimal_places}f} {unit}' |
def RemoveA(file1='Weird.txt',file2='WeirdButA.txt'):
f=open(file2,'a')
lst=open(file1,'r').readlines()
f1=open(file1,'w')
for x in lst:
if 'a' in x or 'A' in x:
f.write(x)
else:
f1.write(x)
f.close()
f1.close()
print(open(file1,'r').read(),open(file2,... | def remove_a(file1='Weird.txt', file2='WeirdButA.txt'):
f = open(file2, 'a')
lst = open(file1, 'r').readlines()
f1 = open(file1, 'w')
for x in lst:
if 'a' in x or 'A' in x:
f.write(x)
else:
f1.write(x)
f.close()
f1.close()
print(open(file1, 'r').read()... |
wt0_16_4 = {'192.168.122.111': [8.3103, 8.0392, 7.6612, 7.6962, 7.5176, 7.5481, 7.5683, 7.5518, 7.8167, 7.7147, 7.6347, 7.5667, 7.5034, 7.9934, 7.9606, 7.9429, 7.9216, 7.8997, 7.8826, 8.0898, 8.037, 8.36, 8.3285, 8.4888, 8.4126, 8.3655, 8.2986, 8.258, 8.2224, 8.1874, 8.1354, 8.1046, 8.2392, 8.2046, 8.1844, 8.1706, 8.1... | wt0_16_4 = {'192.168.122.111': [8.3103, 8.0392, 7.6612, 7.6962, 7.5176, 7.5481, 7.5683, 7.5518, 7.8167, 7.7147, 7.6347, 7.5667, 7.5034, 7.9934, 7.9606, 7.9429, 7.9216, 7.8997, 7.8826, 8.0898, 8.037, 8.36, 8.3285, 8.4888, 8.4126, 8.3655, 8.2986, 8.258, 8.2224, 8.1874, 8.1354, 8.1046, 8.2392, 8.2046, 8.1844, 8.1706, 8.15... |
couponTypeId = None
def getImportCouponTypeId(database):
if couponTypeId is not None:
return couponTypeId
with database.cursor as cursor:
query = "SELECT id FROM coupon_type WHERE type_name = 'IMPORTED'"
for row in cursor.execute(query):
return row.id
query = """IN... | coupon_type_id = None
def get_import_coupon_type_id(database):
if couponTypeId is not None:
return couponTypeId
with database.cursor as cursor:
query = "SELECT id FROM coupon_type WHERE type_name = 'IMPORTED'"
for row in cursor.execute(query):
return row.id
query = "... |
a=[]
for x in range(1,101):
if x%3==0:
a.append('Fizz')
elif x%5==0:
a.append('Buzz')
elif x%3==0 and x%5==0:
a.append("FizzBuzz")
else:
a.append(x)
print(*a)
| a = []
for x in range(1, 101):
if x % 3 == 0:
a.append('Fizz')
elif x % 5 == 0:
a.append('Buzz')
elif x % 3 == 0 and x % 5 == 0:
a.append('FizzBuzz')
else:
a.append(x)
print(*a) |
cube = lambda x: x ** 3 # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
a = 0
b = 1
for i in range(n):
yield a
a, b = b, a + b
def main():
n = int(input())
print(list(map(cube, fibonacci(n))))
if __name__ == '__main__':
main()
| cube = lambda x: x ** 3
def fibonacci(n):
a = 0
b = 1
for i in range(n):
yield a
(a, b) = (b, a + b)
def main():
n = int(input())
print(list(map(cube, fibonacci(n))))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
"""
Exception used in the AutoTag project
"""
class BaseAutoTagException(Exception):
"""Base exception for the AutoTag project."""
class DetectorValidationException(BaseAutoTagException):
"""Validation failed on a detector"""
class DetectorNotFound(BaseAutoTagException):
"""Vali... | """
Exception used in the AutoTag project
"""
class Baseautotagexception(Exception):
"""Base exception for the AutoTag project."""
class Detectorvalidationexception(BaseAutoTagException):
"""Validation failed on a detector"""
class Detectornotfound(BaseAutoTagException):
"""Validation failed on a detecto... |
def get_x_request_id(metadata):
"""
Returning x-request-id from response metadata
:param metadata: response metadata from one of VoiceKit methods
return: None if x-request-id don't contain in metadata
"""
x_request_id = tuple(filter(lambda x: x[0] == 'x-request-id', metadata))
if x_requ... | def get_x_request_id(metadata):
"""
Returning x-request-id from response metadata
:param metadata: response metadata from one of VoiceKit methods
return: None if x-request-id don't contain in metadata
"""
x_request_id = tuple(filter(lambda x: x[0] == 'x-request-id', metadata))
if x_reque... |
class Node:
def __init__(self, key="", val=-1, prev=None, next=None):
self.key = key
self.val = val
self.prev = prev
self.next = next
class LRUCache:
"""
@param: capacity: An integer
"""
def __init__(self, capacity):
self.capacity = capacity
self.map... | class Node:
def __init__(self, key='', val=-1, prev=None, next=None):
self.key = key
self.val = val
self.prev = prev
self.next = next
class Lrucache:
"""
@param: capacity: An integer
"""
def __init__(self, capacity):
self.capacity = capacity
self.ma... |
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*'] # TODO: to env
TIME_ZONE = 'Europe/Helsinki' # TODO: to env
FIRST_DAY_OF_WEEK = 1
MONTH_DAY_FORMAT = 'j F '
| debug = True
allowed_hosts = ['*']
time_zone = 'Europe/Helsinki'
first_day_of_week = 1
month_day_format = 'j F ' |
# Random Comment
x = 3
y = x + 2
y = y * 2
print(y)
| x = 3
y = x + 2
y = y * 2
print(y) |
# Anti Diagonals
# https://www.interviewbit.com/problems/anti-diagonals/
#
# Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
#
# Example:
#
# Input:
#
# 1 2 3
# 4 5 6
# 7 8 9
#
# Return the following :
#
# [
# [1],
# [2, 4],
# [3, 5, 7],
# [6, 8],
# [9]
#... | class Solution:
def diagonal(self, A):
res = [list() for i in range(2 * len(A) - 1)]
for i in range(len(A)):
for j in range(len(A)):
res[i + j].append(A[i][j])
return res
if __name__ == '__main__':
s = solution()
print(s.diagonal([[1, 2, 3], [4, 5, 6], [7... |
def extractPenguTaichou(item):
"""
Pengu Taichou
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title'].lower().startswith('sword shisho chapter'):
return buildReleaseMessageWithType(item, 'I... | def extract_pengu_taichou(item):
"""
Pengu Taichou
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if item['title'].lower().startswith('sword shisho chapter'):
return buil... |
orders = ["daisy", "buttercup", "snapdragon", "gardenia", "lily"]
# Create new orders here:
new_orders = ["lilac", "iris"]
orders_combined = orders + new_orders
broken_prices = [5, 3, 4, 5, 4] + [4] | orders = ['daisy', 'buttercup', 'snapdragon', 'gardenia', 'lily']
new_orders = ['lilac', 'iris']
orders_combined = orders + new_orders
broken_prices = [5, 3, 4, 5, 4] + [4] |
# List Comprehension
# adalah metode untuk menambahkan anggota dari suatu list melalui for loop
# Syntax dari List Comprehension adalah
# [expression for item in iterable]
# Original List
original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Original : {original}")
# Output = Original : [1, 2, 3, 4, 5, 6, 7... | original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f'Original : {original}')
original_dua = [value for value in range(5, 11)]
print(f'Original Range : {original_dua}')
exp_list = [item ** 2 for item in original]
print(f'Exponent List : {exp_list}')
genap = [item for item in original if item % 2 == 0]
print(f'Genap : {gen... |
class Solution:
def sumBase(self, n: int, k: int) -> int:
r = 0
while n>0:
r += n%k
n = n//k
return r
| class Solution:
def sum_base(self, n: int, k: int) -> int:
r = 0
while n > 0:
r += n % k
n = n // k
return r |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "workspace_and_buildfile")
def _http_archive_impl(ctx):
"""Buildozer implementation of the http_archive rule."""
if not ctx.attr.url and not ctx.attr.urls:
fail("At least one of url and urls must be provided")
if ctx.attr.build_file and ctx.att... | load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'workspace_and_buildfile')
def _http_archive_impl(ctx):
"""Buildozer implementation of the http_archive rule."""
if not ctx.attr.url and (not ctx.attr.urls):
fail('At least one of url and urls must be provided')
if ctx.attr.build_file and ctx.at... |
# Copyright 2021 Adobe. All rights reserved.
# This file is licensed to you 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... | class Document:
json_hint = {'dc_format': 'dc:format', 'location': 'cpf:location'}
def __init__(self, file_format=None, location=None):
self.dc_format = file_format
self.location = location |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 13:58:31 2017
MIT 6.00.1x course on edX.org: PSet3 P2
Next, implement the function getGuessedWord that takes in two parameters
- a string, secretWord, and a list of letters, lettersGuessed. This function
returns a string that is comprised of letters and underscores,... | """
Created on Thu Jun 15 13:58:31 2017
MIT 6.00.1x course on edX.org: PSet3 P2
Next, implement the function getGuessedWord that takes in two parameters
- a string, secretWord, and a list of letters, lettersGuessed. This function
returns a string that is comprised of letters and underscores, based on what
letters ... |
"""
anviz_sync
~~~~~~~~~~
Sync Anviz Time & Attendance data with specified database.
:copyright: (c) 2014 by Augusto Roccasalva
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.1.0'
| """
anviz_sync
~~~~~~~~~~
Sync Anviz Time & Attendance data with specified database.
:copyright: (c) 2014 by Augusto Roccasalva
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.1.0' |
# This file is used by build_autocachebreakers.py
# Note: both outputs and breakers[n][1] are relative to this file's directory.
targets = [
{"output": "js_minerva/cw/net/autocachebreakers.js",
"breakers": [
("cw.net.breaker_FlashConnector_swf", "minerva/compiled_client/FlashConnector.swf"),
]},
]
| targets = [{'output': 'js_minerva/cw/net/autocachebreakers.js', 'breakers': [('cw.net.breaker_FlashConnector_swf', 'minerva/compiled_client/FlashConnector.swf')]}] |
class Solution(object):
# Runtime: 23 ms, faster than 68.57% of Python online submissions for String to Integer (atoi).00
# Memory Usage: 13.5 MB, less than 79.83% of Python online submissions for String to Integer (atoi).
def myAtoi(self, s):
"""
:type s: str
:rtype: int
... | class Solution(object):
def my_atoi(self, s):
"""
:type s: str
:rtype: int
"""
(i, n) = (0, len(s))
sign = 1
while i < n and s[i] == ' ':
i += 1
if i < n and s[i] in '+-':
sign = -1 if s[i] == '-' else 1
i += 1
... |
# Python program to print connected
# components in an undirected graph
# https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/
class Graph:
# init function to declare class variables
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def DFSUtil(self... | class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def dfs_util(self, temp, v, visited):
visited[v] = True
temp.append(v)
for i in self.adj[v]:
if visited[i] == False:
temp = self.DFSUtil(temp, i, visited)
... |
"""
Question Source:Leetcode
Level: Medium
Topic: String
Solver: Tayyrov
Date: 25.02.2022
"""
def compareVersion(version1: str, version2: str) -> int:
v1 = list(map(int, version1.split(".")))
v2 = list(map(int, version2.split(".")))
dif = abs(len(v1) - len(v2))
extra = [0] * dif
if... | """
Question Source:Leetcode
Level: Medium
Topic: String
Solver: Tayyrov
Date: 25.02.2022
"""
def compare_version(version1: str, version2: str) -> int:
v1 = list(map(int, version1.split('.')))
v2 = list(map(int, version2.split('.')))
dif = abs(len(v1) - len(v2))
extra = [0] * dif
if len(v1) < len(v... |
#
# PySNMP MIB module NBS-NTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-NTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, constraints_union, value_size_constraint) ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 22:16:29 2020
@author: ghanta
"""
my_dict={}
filepath = 'output.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
# print("Line {}: {}".format(cnt, line.strip()))
my_dict[str(line.strip())] = cnt
line = fp.read... | """
Created on Mon Jan 27 22:16:29 2020
@author: ghanta
"""
my_dict = {}
filepath = 'output.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
my_dict[str(line.strip())] = cnt
line = fp.readline()
cnt += 1
print(my_dict)
print('#################################... |
## Some utils for plots
clean_variable_names = {
"age": "Age",
"anosmia": "Anosmia",
"cough": "Cough",
"diarrhea": "Diarrhea",
"fever": "Fever",
"minor_severity_factor": "Number of minor severity factors",
"risk_factor": "Number of risk factors",
"sore_throat_aches": "Sore throat/aches"... | clean_variable_names = {'age': 'Age', 'anosmia': 'Anosmia', 'cough': 'Cough', 'diarrhea': 'Diarrhea', 'fever': 'Fever', 'minor_severity_factor': 'Number of minor severity factors', 'risk_factor': 'Number of risk factors', 'sore_throat_aches': 'Sore throat/aches'}
legend_imp_name = {'SOBOL_TOTAL': 'Sobol Total-order', '... |
"""LSD (least significant digit) string sort algorithm.
This algorithm is based on the Key-indexed counting sorting algorithm. The
main difference is that LSD run the same operation for W characters instead
of just 1 integer. It is assumed that strings are fixed length and that W
is the length of them.
Characteristics... | """LSD (least significant digit) string sort algorithm.
This algorithm is based on the Key-indexed counting sorting algorithm. The
main difference is that LSD run the same operation for W characters instead
of just 1 integer. It is assumed that strings are fixed length and that W
is the length of them.
Characteristics... |
#
# PySNMP MIB module JUNIPER-WX-STATUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-WX-GLOBAL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:01:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
def ordinal(number):
if number <= 0:
return 'none'
tmp = number % 100
if tmp >= 20:
tmp = tmp % 10
if tmp == 1:
return str(number) + 'st'
elif tmp == 2:
return str(number) + 'nd'
elif tmp == 3:
return str(number) + 'rd'
else:
return str(number)... | def ordinal(number):
if number <= 0:
return 'none'
tmp = number % 100
if tmp >= 20:
tmp = tmp % 10
if tmp == 1:
return str(number) + 'st'
elif tmp == 2:
return str(number) + 'nd'
elif tmp == 3:
return str(number) + 'rd'
else:
return str(number)... |
def load_parse_data(path: str) -> list:
with open(path, mode='r', encoding="utf-8") as f:
return list(map(int, f.read().split(',')))
def school_by_age(data: list) -> list:
school_by_age = [0] * 9
for age in data:
school_by_age[age] += 1
return school_by_age
def model_school_growth(sc... | def load_parse_data(path: str) -> list:
with open(path, mode='r', encoding='utf-8') as f:
return list(map(int, f.read().split(',')))
def school_by_age(data: list) -> list:
school_by_age = [0] * 9
for age in data:
school_by_age[age] += 1
return school_by_age
def model_school_growth(scho... |
scores = []
for i in range(5):
scores.append(sum([int(x) for x in input().split(" ")]))
topscore = 0
for score in scores:
if score > topscore:
topscore = score
index = scores.index(topscore) + 1
print(str(index) + " " + str(topscore))
| scores = []
for i in range(5):
scores.append(sum([int(x) for x in input().split(' ')]))
topscore = 0
for score in scores:
if score > topscore:
topscore = score
index = scores.index(topscore) + 1
print(str(index) + ' ' + str(topscore)) |
lines = [line.strip() for line in open("input.txt", 'r') if line.strip() != ""]
tiles = []
# e - 0; se - 1; sw - 2; w - 3; nw - 4; ne - 5
directions = ((1, -1, 0), (0, -1, 1), (-1, 0, 1),
(-1, 1, 0), (0, 1, -1), (1, 0, -1))
for line in lines:
tile = []
while len(line) > 0:
if line[0] =... | lines = [line.strip() for line in open('input.txt', 'r') if line.strip() != '']
tiles = []
directions = ((1, -1, 0), (0, -1, 1), (-1, 0, 1), (-1, 1, 0), (0, 1, -1), (1, 0, -1))
for line in lines:
tile = []
while len(line) > 0:
if line[0] == 's':
tile.append(1 if line[1] == 'e' else 2)
... |
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
max_nums = nums1 if len(nums1) > len(nums2) else nums2
min_nums = nums1 if len(nums1) < len(nums2) else nums2
r_nums =... | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
max_nums = nums1 if len(nums1) > len(nums2) else nums2
min_nums = nums1 if len(nums1) < len(nums2) else nums2
r_nums ... |
# insert CR, insert line above
keys(':setf vim\<CR>jw')
keys('4\<C-Down>')
keys('Ea')
keys('\<CR>')
keys('CARRYING OVER ')
keys('\<Esc>A')
keys('\<CR>')
keys('CR at EOL')
keys('\<Esc>k')
keys('O')
keys('above CR')
keys('\<Esc>\<Esc>')
| keys(':setf vim\\<CR>jw')
keys('4\\<C-Down>')
keys('Ea')
keys('\\<CR>')
keys('CARRYING OVER ')
keys('\\<Esc>A')
keys('\\<CR>')
keys('CR at EOL')
keys('\\<Esc>k')
keys('O')
keys('above CR')
keys('\\<Esc>\\<Esc>') |
# from AI_module import AI_module
def receive_basic_iuput_data(Singal_Loss, Shock_Alert, Oxygen_Supply, Fever, Hypotension, Hypertension):
# Recevie data from input module, then analyze it using some judge functions to generate boolean result
# Boolean Parameters
# If paramter returns True, means it shoul... | def receive_basic_iuput_data(Singal_Loss, Shock_Alert, Oxygen_Supply, Fever, Hypotension, Hypertension):
basic_result = {'Signal_Loss': False, 'Shock_Alert': False, 'Oxygen_Supply': False, 'Fever': False, 'Hypotension': False, 'Hypertension': False}
if Singal_Loss:
BasicResult['Signal Loss'] = True
... |
# -*- coding: utf-8 -*-
"""Top-level package for dbix."""
__author__ = """Alex Bodnaru"""
__email__ = 'alexbodn@gmail.com'
__version__ = '0.3.0'
| """Top-level package for dbix."""
__author__ = 'Alex Bodnaru'
__email__ = 'alexbodn@gmail.com'
__version__ = '0.3.0' |
#
# PySNMP MIB module CISCO-RADIUS-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-RADIUS-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:53:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for i in range(9):
check_r = dict()
check_c = dict()
check_b = dict()
print("_____")
for j in range(9):
print(check_r.keys(),check_c.keys(),check_b.keys())
... | class Solution:
def is_valid_sudoku(self, board: List[List[str]]) -> bool:
for i in range(9):
check_r = dict()
check_c = dict()
check_b = dict()
print('_____')
for j in range(9):
print(check_r.keys(), check_c.keys(), check_b.keys()... |
### Model data
class catboost_model(object):
float_features_index = [
0, 1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 31, 32, 33, 35, 37, 38, 39, 46, 47, 48, 49,
]
float_feature_count = 50
cat_feature_count = 0
binary_feature_count = 36
tree_co... | class Catboost_Model(object):
float_features_index = [0, 1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 28, 31, 32, 33, 35, 37, 38, 39, 46, 47, 48, 49]
float_feature_count = 50
cat_feature_count = 0
binary_feature_count = 36
tree_count = 40
float_feature_bord... |
# http://codingbat.com/prob/p118366
def string_splosion(str):
result = ""
for i in range( len(str) ):
result += str[:i+1]
return result
| def string_splosion(str):
result = ''
for i in range(len(str)):
result += str[:i + 1]
return result |
# Python3
m, n = [int(i) for i in input().split()]
if n <= 1:
print(n)
quit()
lesser_n = (n+2) % 60
lesser_m = (m+1) % 60
def fibo(n):
a, b = 0, 1
for i in range(2, n+1):
c = a+b
c = c % 10
b, a = c, b
return (c-1)
if lesser_n <= 1:
a = lesser... | (m, n) = [int(i) for i in input().split()]
if n <= 1:
print(n)
quit()
lesser_n = (n + 2) % 60
lesser_m = (m + 1) % 60
def fibo(n):
(a, b) = (0, 1)
for i in range(2, n + 1):
c = a + b
c = c % 10
(b, a) = (c, b)
return c - 1
if lesser_n <= 1:
a = lesser_n - 1
else:
a =... |
links_file = open("link_queue.txt", "r")
link_queue = links_file.readlines()
go = []
count = 0
index = 0
while index < len(link_queue):
if link_queue[index].find("interforo") == -1:
go.append(link_queue[index])
del link_queue[index]
else:
index = index + 1
count = count + 1
... | links_file = open('link_queue.txt', 'r')
link_queue = links_file.readlines()
go = []
count = 0
index = 0
while index < len(link_queue):
if link_queue[index].find('interforo') == -1:
go.append(link_queue[index])
del link_queue[index]
else:
index = index + 1
count = count + 1
print... |
class DockablePanes(object):
""" Provides a container of all Revit built-in DockablePaneId instances. """
BuiltInDockablePanes = None
__all__ = [
"BuiltInDockablePanes",
]
| class Dockablepanes(object):
""" Provides a container of all Revit built-in DockablePaneId instances. """
built_in_dockable_panes = None
__all__ = ['BuiltInDockablePanes'] |
class Run(dict):
attributes = ('nx', 'ny', 'nz', 'time', 'NbrOfCores', 'platform', 'configuration', 'repetitions', 'mpiargs', 'tag')
def __init__(self, serie, data, **kwargs):
super(Run, self).__init__(**kwargs)
self.data = data
self.parent = serie
for x in Run.attributes:
... | class Run(dict):
attributes = ('nx', 'ny', 'nz', 'time', 'NbrOfCores', 'platform', 'configuration', 'repetitions', 'mpiargs', 'tag')
def __init__(self, serie, data, **kwargs):
super(Run, self).__init__(**kwargs)
self.data = data
self.parent = serie
for x in Run.attributes:
... |
AVAILABLE_THEMES = [
('suse', 'SUSE', 'themes/suse'),
('default', 'Default', 'themes/default'),
]
| available_themes = [('suse', 'SUSE', 'themes/suse'), ('default', 'Default', 'themes/default')] |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res=ListNode(0)
res.n... | class Solution(object):
def delete_duplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res = list_node(0)
res.next = head
last = res
while last.next:
probe = last.next
depth = 1
while probe and pro... |
callback_classes = [
['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<const ns3::MobilityModel>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty... | callback_classes = [['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<const ns3::MobilityModel>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::... |
"""
Initial extension configuration implementations.
"""
| """
Initial extension configuration implementations.
""" |
# Copyright 2020 https://www.globaletraining.com/
# Generator send method
def simple_gen(start_number=10):
i = start_number
while True:
x = (yield i * 2)
if x: # check if used send()
i += x
else:
i += 1
gen1 = simple_gen()
print(gen1.__next__())
print... | def simple_gen(start_number=10):
i = start_number
while True:
x = (yield (i * 2))
if x:
i += x
else:
i += 1
gen1 = simple_gen()
print(gen1.__next__())
print(gen1.send(10))
print(gen1.__next__())
print(gen1.send(20))
print(gen1.__next__())
print(gen1.__next__())
pr... |
# g code generator for clay extrusions
def gCodeLine(generation):
def __init__(self, coordinates, z_val = True, extrusion_value = None, feed_value = None, absolute_relative = None):
self.X = coordinates.X
self.Y = coordinates.Y
if z_val:
self.Z = coordinates.Z
class... | def g_code_line(generation):
def __init__(self, coordinates, z_val=True, extrusion_value=None, feed_value=None, absolute_relative=None):
self.X = coordinates.X
self.Y = coordinates.Y
if z_val:
self.Z = coordinates.Z
class Gcodesettings:
def __init__(self):
self.noz... |
# Non-unicode strings are assumed to be CP437. We have an indexed table to
# convert CP437 to unicode (index range 0-255 => unicode char) and a dict to
# convert Unicode to CP437 (unicode char => CP437 char). These are used by the
# fsuCP437_to_Unicode and fsUnicode_to_CP437 functions respectively.
asUnicodeCharMapCP43... | as_unicode_char_map_cp437 = [isinstance(x, str) and str(x) or chr(x) for x in [0, 9786, 9787, 9829, 9830, 9827, 9824, 8226, 9688, 9675, 9689, 9794, 9792, 9834, 9835, 9788, 9658, 9668, 8597, 8252, 182, 167, 9644, 8616, 8593, 8595, 8594, 8592, 8735, 8596, 9650, 9660, ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*',... |
monthConversions = {
"Jan": "January",
"Feb": "Februry",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}
print(monthConversions["Oct"])
print(monthC... | month_conversions = {'Jan': 'January', 'Feb': 'Februry', 'Mar': 'March', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October', 'Nov': 'November', 'Dec': 'December'}
print(monthConversions['Oct'])
print(monthConversions.get('Dec'))
for item in monthConversions... |
a=[2,6,7,5,11,15]
n=len(a)
print("old array=",a)
for i in range(n-1):
if a[i]<=a[i+1]:
continue
t=a[i+1]
j=i+1
while j>=1 and a[j-1]>t:
a[j]=a[j-1]
j=j-1
a[j]=t
print("Sorted Array=",a) | a = [2, 6, 7, 5, 11, 15]
n = len(a)
print('old array=', a)
for i in range(n - 1):
if a[i] <= a[i + 1]:
continue
t = a[i + 1]
j = i + 1
while j >= 1 and a[j - 1] > t:
a[j] = a[j - 1]
j = j - 1
a[j] = t
print('Sorted Array=', a) |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Default configuration values for Celery integration.
For further Celery configura... | """Default configuration values for Celery integration.
For further Celery configuration variables see
`Celery <http://docs.celeryproject.org/en/3.1/configuration.html>`_
documentation.
"""
broker_url = 'redis://localhost:6379/0'
celery_broker_url = BROKER_URL
'Broker settings.'
celery_result_backend = 'redis://localh... |
class MarkdownParser:
def __init__(self, whitelist_filters=None):
self._delimiter = '\n'
self._single_delimiters = \
('#', '*', '+', '~', '-', '|', '`', '\n')
self._whitelist_filters = whitelist_filters or [str.isdigit]
def encode(self, text):
content_parts, conten... | class Markdownparser:
def __init__(self, whitelist_filters=None):
self._delimiter = '\n'
self._single_delimiters = ('#', '*', '+', '~', '-', '|', '`', '\n')
self._whitelist_filters = whitelist_filters or [str.isdigit]
def encode(self, text):
(content_parts, content_delimiters) ... |
#!/usr/bin/env python3
# pyre-strict
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
ldops.exceptions
~~~~~~~~~~~
Contains LDOps-wide exceptions.
"""
cl... | """
ldops.exceptions
~~~~~~~~~~~
Contains LDOps-wide exceptions.
"""
class Ldopserror(Exception):
"""
Generic error in LDOps
"""
pass
class Nodenotfounderror(LDOpsError):
"""
Raised when node not found
"""
pass
class Nodeisnotasequencererror(LDOpsError):
"""
Raised when node ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
INPUT_STREAMS = [
'test.count_words_stream.CountWordsStream'
]
REDUCERS = [
'test.count_words_reducer.CountWordsReducer'
]
| input_streams = ['test.count_words_stream.CountWordsStream']
reducers = ['test.count_words_reducer.CountWordsReducer'] |
'''
This problem was asked by Facebook.
There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.
For example, given a 2 by 2 matrix, you should return 2, since there are ... | """
This problem was asked by Facebook.
There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down.
For example, given a 2 by 2 matrix, you should return 2, since there are ... |
"""converted from vga_8x8.bin """
WIDTH = 8
HEIGHT = 8
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\
b'\x66\x66\x24\x00\x00\x00\x00\x00'\
b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\
b'\x18\x3e\x60\x3c\x06\x7c\x18\x00'\
b'\x00\xc6\xcc\x18\x30\x66\xc6\x00'\
b'\x38\x6... | """converted from vga_8x8.bin """
width = 8
height = 8
first = 32
last = 127
_font = b'\x00\x00\x00\x00\x00\x00\x00\x00\x18<<\x18\x18\x00\x18\x00ff$\x00\x00\x00\x00\x00ll\xfel\xfell\x00\x18>`<\x06|\x18\x00\x00\xc6\xcc\x180f\xc6\x008l8v\xdc\xccv\x00\x18\x180\x00\x00\x00\x00\x00\x0c\x18000\x18\x0c\x000\x18\x0c\x0c\x0c\x1... |
"""
configurable.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope tha... | """
configurable.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope tha... |
# Testing Assertions
# Given a sequence of a number of cars,
# the function get_total_cars returns the total number of cars.
# get_total_cars([1, 2, 3, 4])
# outputs: 10
# get_total_cars(['a', 'b', 'c'])
# outputs: ValueError: invalid literal for int() with base 10: 'a'
# Explain in words what the assertions in t... | def get_total(values):
assert len(values) > 0
for element in values:
assert int(element)
values = [int(element) for element in values]
total = sum(values)
assert total > 0
return total |
class Codec:
ENCODING: str
SEPARATOR: bytes
WIDTH: int
@staticmethod
def default():
"""Default codec specified for id3v2.3 (Latin1 / ISO 8859-1)"""
return _CODECS.get(0)
@staticmethod
def get(key):
"""Get codec by magic number specified in id3v2.3
0: Latin1... | class Codec:
encoding: str
separator: bytes
width: int
@staticmethod
def default():
"""Default codec specified for id3v2.3 (Latin1 / ISO 8859-1)"""
return _CODECS.get(0)
@staticmethod
def get(key):
"""Get codec by magic number specified in id3v2.3
0: Latin1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.