content
stringlengths 7
1.05M
|
|---|
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0]*(len(text1)+1) for _ in range(len(text2)+1)]
for i in range(1, len(text2)+1):
for j in range(1, len(text1)+1):
if text2[i - 1] == text1[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[len(text2)][len(text1)]
sol = Solution()
print(sol.longestCommonSubsequence(text1="abcde", text2="ace"))
|
"""
Reversed from binary_search.
Given a item, if the item in the list, return its index.
If not in the list, return the index of the first item that is larger than the the given item
If all items in the list are less then the given item, return -1
"""
def binary_search_fuzzy(alist: list, item) -> int:
low_bound = 0
high_bound = len(alist) - 1
while low_bound <= high_bound:
mid = (low_bound + high_bound) // 2
if alist[mid] == item:
return mid
elif alist[mid] < item:
low_bound = mid + 1
elif alist[mid] > item:
high_bound = mid - 1
if low_bound >= len(alist):
return -1
else:
return low_bound
if __name__ == '__main__':
a = [1, 3, 7, 9, 11, 13, 15]
print(binary_search_fuzzy(a, 16))
|
SCRIPT="""
#!/bin/bash
# Generate train/test script for scenario "{scenario}" using the faster-rcnn "alternating optimization" method
set -x
set -e
rm -f $CAFFE_ROOT/data/cache/*.pkl
rm -f {scenarios_dir}/{scenario}/output/*.pkl
DIR=`pwd`
function quit {{
cd $DIR
exit 0
}}
export PYTHONUNBUFFERED="True"
TRAIN_IMDB={train_imdb}
TEST_IMDB={test_imdb}
cd {py_faster_rcnn}
mkdir -p {scenarios_dir}/{scenario}/logs >/dev/null
LOG="{scenarios_dir}/{scenario}/logs/log.txt.`date +'%Y-%m-%d_%H-%M-%S'`"
exec &> >(tee -a "$LOG")
echo Logging output to "$LOG"
time {train_script} {scenario_file} || quit
time ./tools/test_net.py --gpu {gpu_id} \\
--def {testproto} \\
--net {net_final_path} \\
--imdb {test_imdb} \\
--cfg {config_path} || quit
chmod u+x {plot_script}
{plot_script} $LOG {scenarios_dir}/{scenario}/output/results.png || true
MEAN_AP=`grep "Mean AP = " ${{LOG}} | awk '{{print $3}}'`
echo "{scenario} finished with mAP=$MEAN_AP" >> {scenarios_dir}/status.txt
quit
"""
|
#test for primality
def IsPrime(x):
x = abs(int(x))
if x < 2:
return False
if x == 2:
return True
if not x & 1:
return False
for y in range(3, int(x**0.5)+1, 2):
if x % y == 0:
return False
return True
def QuadatricAnswer(a, b, n):
return n**2 + a*n + b
def CountNumberOfPrimes(a, b):
n = 0
while IsPrime(QuadatricAnswer(a,b,n)):
n = n+1
# print("a=%d, b=%d has %d primes" % (a, b, n))
return n
#boundary values
a_min = -999
a_max = 1000
b_min = -999
b_max = 1000
maxNumberOfPrimes = 0
for a in range(a_min, a_max):
for b in range(b_min, b_max): #iterate through possible values
numberOfPrimes = CountNumberOfPrimes(a,b)
if numberOfPrimes > maxNumberOfPrimes:
maxNumberOfPrimes = numberOfPrimes
print('New Max # of %d primes!' % numberOfPrimes)
print('a=%d, b=%d' % (a, b))
print('Product=%d' % (a * b))
|
class NoRecordsFoundError(Exception):
pass
class J2XException(Exception):
pass
|
"""
Profile ../profile-datasets-py/div52_zen50deg/038.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div52_zen50deg/038.py"
self["Q"] = numpy.array([ 1.619327, 5.956785, 4.367512, 5.966544, 5.988635,
7.336613, 6.150054, 10.02425 , 7.748795, 6.746565,
7.848652, 8.143708, 6.399868, 6.944384, 6.637736,
5.71046 , 5.909629, 5.561485, 5.516982, 5.451449,
5.354534, 5.23527 , 5.090619, 4.882784, 4.665495,
4.445971, 4.33555 , 4.24455 , 4.228264, 4.206028,
4.109932, 4.016939, 3.978498, 3.943255, 3.926937,
3.91893 , 3.913817, 3.914332, 3.914846, 3.919975,
3.925441, 3.934397, 3.947211, 3.959719, 3.971488,
3.982999, 3.995186, 4.007807, 4.018579, 4.019045,
4.019496, 4.01493 , 4.008386, 4.016698, 4.058516,
4.099514, 4.590187, 5.10988 , 6.011561, 7.189825,
8.460967, 10.05411 , 11.61838 , 14.50413 , 17.40478 ,
19.78103 , 21.90165 , 24.44011 , 27.48018 , 30.31075 ,
32.63891 , 35.01159 , 38.0444 , 41.01917 , 41.96547 ,
42.89666 , 48.38523 , 53.96574 , 59.23674 , 64.47107 ,
70.1626 , 76.54991 , 85.13889 , 93.71093 , 102.2625 ,
107.7171 , 111.8628 , 114.223 , 114.8452 , 113.5177 ,
110.5433 , 108.2854 , 110.1149 , 104.2918 , 93.99163 ,
78.51031 , 50.08795 , 15.39714 , 14.97929 , 14.57806 ,
14.19263 ])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56504000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61259000e+01, 6.09895000e+01, 6.61252000e+01,
7.15398000e+01, 7.72395000e+01, 8.32310000e+01,
8.95203000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17777000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23441000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90892000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53627000e+02, 7.77789000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31523000e+02, 9.58591000e+02,
9.86066000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 317.3675, 317.3661, 317.3666, 317.3661, 317.3661, 317.3657,
317.366 , 317.3648, 317.3655, 317.3659, 317.3655, 317.3654,
317.366 , 317.3658, 317.3659, 317.3662, 317.3661, 317.3662,
317.3662, 317.3663, 317.3663, 317.3663, 317.3664, 317.3665,
317.3665, 317.3666, 317.3666, 317.3667, 317.3667, 317.3667,
317.3667, 318.3637, 319.4287, 320.5647, 321.7717, 323.0537,
324.4127, 325.8497, 327.3667, 327.3667, 327.3667, 327.3667,
327.3667, 327.3667, 327.3667, 327.3667, 327.3667, 327.3667,
327.3667, 327.3667, 327.3667, 327.3667, 327.3667, 327.3667,
327.3667, 327.3667, 327.3665, 327.3663, 327.366 , 327.3656,
327.3652, 327.3647, 327.3642, 327.3633, 327.3623, 327.3615,
327.3608, 327.36 , 327.359 , 327.3581, 327.3573, 327.3565,
327.3555, 327.3546, 327.3543, 327.354 , 327.3522, 327.3503,
327.3486, 327.3469, 327.345 , 327.3429, 327.3401, 327.3373,
327.3345, 327.3327, 327.3314, 327.3306, 327.3304, 327.3308,
327.3318, 327.3326, 327.332 , 327.3339, 327.3372, 327.3423,
327.3516, 327.363 , 327.3631, 327.3632, 327.3634])
self["T"] = numpy.array([ 208.144, 225.372, 233.177, 245.265, 257.004, 262.226,
265.74 , 267.391, 269.015, 267.988, 260.633, 246.779,
232.854, 221.232, 213.507, 209.05 , 206.15 , 204.447,
203.83 , 204.139, 205.414, 207.06 , 208.488, 208.879,
208.928, 208.778, 208.504, 208.203, 207.538, 206.933,
206.776, 206.624, 206.568, 206.519, 205.985, 205.254,
204.689, 204.443, 204.205, 205.121, 206.132, 207.086,
207.98 , 208.86 , 210.119, 211.349, 212.399, 213.315,
214.179, 214.82 , 215.447, 216.055, 216.649, 217.224,
217.769, 218.303, 218.725, 219.129, 219.394, 219.556,
219.661, 219.603, 219.545, 219.437, 219.327, 219.153,
218.952, 218.772, 218.614, 218.547, 218.732, 218.952,
219.486, 220.013, 220.743, 221.461, 222.301, 223.132,
224.021, 224.901, 225.805, 226.67 , 227.448, 228.168,
228.832, 229.468, 230.089, 230.695, 231.138, 231.335,
231.256, 231.052, 231.12 , 230.943, 230.323, 229.145,
225.92 , 216.233, 216.233, 216.233, 216.233])
self["O3"] = numpy.array([ 0.4900558 , 0.519964 , 0.5800554 , 0.6837994 , 0.8980769 ,
1.136376 , 1.48558 , 1.992239 , 2.507364 , 3.082146 ,
3.839641 , 4.766185 , 5.593402 , 6.175221 , 6.486727 ,
6.579967 , 6.593362 , 6.525838 , 6.401646 , 6.232317 ,
5.973736 , 5.652493 , 5.336404 , 5.090563 , 4.898364 ,
4.739892 , 4.463794 , 4.180877 , 3.854482 , 3.558012 ,
3.486732 , 3.417758 , 3.274348 , 3.13235 , 2.961193 ,
2.780333 , 2.620231 , 2.4972 , 2.377505 , 2.279946 ,
2.186869 , 2.075623 , 1.944017 , 1.814595 , 1.639969 ,
1.469459 , 1.29283 , 1.112821 , 0.9414424 , 0.8033797 ,
0.6682922 , 0.5882987 , 0.5313038 , 0.4850611 , 0.4617138 ,
0.4388317 , 0.3812881 , 0.3218576 , 0.2606511 , 0.1984164 ,
0.1433774 , 0.1075164 , 0.07230547, 0.05926259, 0.04750463,
0.0433533 , 0.04262317, 0.04276686, 0.04394101, 0.04542562,
0.04783386, 0.0502069 , 0.052577 , 0.05490744, 0.05686248,
0.05878674, 0.06004279, 0.06125448, 0.06145147, 0.06160804,
0.06150028, 0.06146972, 0.06166167, 0.06197792, 0.06241002,
0.06286282, 0.06332897, 0.06382601, 0.06415119, 0.06443305,
0.06480372, 0.06553336, 0.06655114, 0.06732265, 0.06764013,
0.06758204, 0.06678987, 0.06998377, 0.0699838 , 0.06998383,
0.06998385])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 216.233
self["S2M"]["Q"] = 15.5386538073
self["S2M"]["O"] = 0.0699837594526
self["S2M"]["P"] = 1004.71
self["S2M"]["U"] = -1.39825
self["S2M"]["V"] = -0.27037
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 0
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 215.154
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 50.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 67.8369
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([1993, 12, 15])
self["TIME"] = numpy.array([6, 0, 0])
|
n = int(input())
tl = list(map(int, input().split()))
m = int(input())
sum_time = sum(tl)
for _ in range(m):
p, x = map(int, input().split())
print(sum_time - tl[p-1] + x)
|
class Solution:
def reverseWords(self, s: str) -> str:
list_s = s.split(' ')
for i in range(len(list_s)):
list_s[i] = list_s[i][::-1]
return ' '.join(list_s)
print(Solution().reverseWords("Let's take LeetCode contest"))
|
class XmlConverter:
def __init__(self, prefix, method, params):
self.text = ''
self.prefix = prefix
self.method = method
self.params = params
def create_tag(self, parent, elem):
if isinstance(elem, dict):
for key, value in elem.items():
self.text += f'<{self.prefix}:{key}>'
self.create_tag(key, value)
self.text += f'</{self.prefix}:{key}>'
elif isinstance(elem, list):
for value in elem:
self.create_tag(parent, value)
else:
self.text += f'{elem}'
def build_body(self):
self.text += f'<{self.prefix}:{self.method}Request>'
self.create_tag(None, self.params)
self.text += f'</{self.prefix}:{self.method}Request>'
return self.text
def convert_json_to_xml(prefix, method, params):
s = XmlConverter(prefix, method, params)
return s.build_body()
|
# https://stepik.org/lesson/3363/step/4?unit=1135
# Sample Input:
# Петров;85;92;78
# Сидоров;100;88;94
# Иванов;58;72;85
# Sample Output:
# 85.0
# 94.0
# 71.666666667
# 81.0 84.0 85.666666667
def calculate_students_performance(data):
result = [str((int(grade1) + int(grade2) + int(grade3)) / 3) for name, grade1, grade2, grade3 in data]
averageGrade1 = sum([int(grade1) for name, grade1, grade2, grade3 in data]) / len(data)
averageGrade2 = sum([int(grade2) for name, grade1, grade2, grade3 in data]) / len(data)
averageGrade3 = sum([int(grade3) for name, grade1, grade2, grade3 in data]) / len(data)
return result + [str(averageGrade1) + ' ' + str(averageGrade2) + ' ' + str(averageGrade3)]
dataset = []
with open('3.dataset.txt', 'r') as fs:
for line in fs.readlines():
dataset += [line.strip().split(';')]
result = calculate_students_performance(dataset)
with open('3.result.txt', 'w') as fs:
fs.writelines("%s\n" % entry for entry in result)
print(result)
|
print('-------------------------------------------------------------------------')
family=['me','sis','Papa','Mummy','Chacha']
print('Now, we will copy family list to a another list')
for i in range(len(family)):
cpy_family=family[1:4]
print(family)
print('--------------------------------------')
print(cpy_family)
print('--------------------------------------')
cpy_family.append('Chachi')
print(cpy_family)
print('thank you')
print('-------------------------------------------------------------------------')
|
num = 1
num1 = 10
num2 = 20
num3 = 40
num3 = 30
num4 = 50
|
#TODO: Complete os espaços em branco com uma possível solução para o problema.
X, Y = map(int, input().split())
while ( X != Y):
floor = min(X, Y)
top = max(X, Y)
if (X < Y):
print("Crescente")
elif (X > Y):
print("Decrescente")
X, Y = map(int, input().split())
|
# example_traceback.py
def loader(filename):
fin = open(filenam)
loader("data/result_ab.txt")
|
#%%
#https://leetcode.com/problems/divide-two-integers/
#%%
dividend = -2147483648
dividend = -10
divisor = -1
divisor = 3
def divideInt(dividend, divisor):
sign = -1 if dividend * divisor < 0 else 1
if dividend == 0:
return 0
dividend = abs(dividend)
divisor = abs(divisor)
if divisor == 1:
return sign * dividend
remainder = dividend
quotient = 0
remainderOld = 0
while remainder >= 0 and remainderOld != remainder:
remainderOld = remainder
remainder = remainder - divisor
#print(remainder)
quotient += 1
quotient = sign * (quotient - 1)
return quotient
print(divideInt(dividend, divisor))
# %%
|
times = 'atlético-MG','flamengo','palmeiras','bragantino','fortaleza','corinthians','internacional','fluminense','cuiabá','america-MG','atletico-GO','são paulo','ceara SC','athletico-PR','santos','bahia','sport recife','juventude','gremio','chapecoense'
print('OS 5 PRIMEIROS COLOCADOS')
while True:
#print(times[:5])
#print(times[-4:])
#print(sorted(times))
print('='*40)
cont = 0
for pos,c in enumerate(times):
#print(f'c = {c} e pos = {pos}')
if pos <= 4:
print(f'{pos + 1}° COLOCADO {c}')
print('='*20,'OS 4 ULTIMOS COLOCADOS','='*20)
for pos,c in enumerate(times):
if pos >= 16:
print(f'{pos + 1}° COLOCADO {c}')
print('='*20,'TIMES POR ORDEM ALFABETICA','='*20,)
print(f'\n{sorted(times)}')
print('='*50)
for pos,c in enumerate(times):
if c == 'chapecoense':
print(f'ATUALMENTE A CHAPECOENSE SE ENCONTRA NA {pos + 1}° POSIÇÃO')
print('='*50)
break
|
"""
Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha
separados os valores pares e ímpares. No final mostre os valores pares e ímpares em ordem crescente.
"""
lista = [[], []]
n = 0
for indice in range(0, 7):
n = int(input(f'Digite o {indice + 1}º valor: '))
if n % 2 == 0:
lista[0].append(n)
elif n % 2 == 1:
lista[1].append(n)
print()
print('+-' * 35)
lista[0].sort()
lista[1].sort()
print(f'Valores Pares digitados: {lista[0]}')
print(f'Valores Ímpares digitados: {lista[1]}')
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Counter(object):
''' Stores all the samples for a given counter.
'''
def __init__(self, parent, category, name):
self.parent = parent
self.full_name = category + '.' + name
self.category = category
self.name = name
self.samples = []
self.timestamps = []
self.series_names = []
self.totals = []
self.max_total = 0
self._bounds = None
@property
def min_timestamp(self):
if not self._bounds:
self.UpdateBounds()
return self._bounds[0]
@property
def max_timestamp(self):
if not self._bounds:
self.UpdateBounds()
return self._bounds[1]
@property
def num_series(self):
return len(self.series_names)
@property
def num_samples(self):
return len(self.timestamps)
def UpdateBounds(self):
if self.num_series * self.num_samples != len(self.samples):
raise ValueError(
'Length of samples must be a multiple of length of timestamps.')
self.totals = []
self.max_total = 0
if not len(self.samples):
return
self._bounds = (self.timestamps[0], self.timestamps[-1])
max_total = None
for i in xrange(self.num_samples):
total = 0
for j in xrange(self.num_series):
total += self.samples[i * self.num_series + j]
self.totals.append(total)
if max_total is None or total > max_total:
max_total = total
self.max_total = max_total
|
'''<yasir_ahmad>
WAP to create a function which takes 3 arguments (say a,b,ch) where a is length ;b is breadth and ch is choice whether to compute area or perimeter.
Note:- By default is should find area.
'''
def Area_Perimeter(a,b,ch=1):
"""
a(int): Length of the rectangle
b(int): Breadth of the rectangle
ch(int): choice
ch==1>>Area
ch==2>>Perimeter
Returns area or perimeter of the rectangle.
"""
if ch==1:
return 'Area is '+str(a*b)
elif ch==2:
return 'Perimeter is '+str(2*(a+b))
else:
return 'Invalid choice.'
x,y,choice=int(input('a: ')),int(input('b: ')),int(input('choice: '))
print(Area_Perimeter(a=x,ch=choice,b=y))
#help(Area_Perimeter)
|
#Faça um programa que tenha uma função chamada area(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a
#área do terreno.
def area(larg, comp):
a = larg * comp
print(f'A área do terreno {larg}x{comp} é de {a}m2')
print(f'Controle de Terrenos')
l = float(input('Largura (m): '))
c = float(input('Comprimento (m): '))
area(l,c)
|
load("@com_github_reboot_dev_pyprotoc_plugin//:rules.bzl", "create_protoc_plugin_rule")
cc_eventuals_library = create_protoc_plugin_rule(
"@com_github_3rdparty_eventuals_grpc//protoc-gen-eventuals:protoc-gen-eventuals", extensions=(".eventuals.h", ".eventuals.cc")
)
|
class GUIComponent:
def get_surface(self):
return None
def get_position(self):
return None
def initialize(self):
pass
|
__author__ = 'Chirag'
'''iter(<iterable>) = iterator converts
iterable object into in 'iterator' so that
we use can use the next(<iterator>)'''
string = "Hello"
for letter in string:
print(letter)
string_iter = iter(string)
print(next(string_iter))
|
def val_to_list(val):
"""
Convert a single value string or number to a list
:param val:
:return:
"""
if val is not None:
if not isinstance(val, (list, tuple)):
val = [val]
if isinstance(val, tuple):
val = list(val)
return val
def one_list_to_val(val):
"""
Convert a single list element to val
:param val:
:return:
"""
if isinstance(val, list) and len(val) == 1:
result = val[0]
else:
result = val
return result
|
class InfrastructureException(Exception):
"""
Custom exception to be raised to indicate a infrastructure function has failed its checks.
You should be explicit in such checks.
"""
pass
|
x = int (input('Digite um numero :'))
for x in range (0,x):
print (x)
if x % 4 == 0:
print ('[{}]'.format(x))
|
#try out file I/O
myfile=open("example.txt", "a+")
secondfile=open("python.txt", "r")
for _ in range(4):
print(secondfile.read())
|
"""
Non Leetcode Question:
https://www.educative.io/courses/grokking-the-coding-interview/YQQwQMWLx80
Given a string, find the length of the longest substring in it with no more than K distinct characters.
Example 1:
Input: String="araaci", K=2
Output: 4
Explanation: The longest substring with no more than '2' distinct characters is "araa".
Example 2:
Input: String="araaci", K=1
Output: 2
Explanation: The longest substring with no more than '1' distinct characters is "aa".
Example 3:
Input: String="cbbebi", K=3
Output: 5
Explanation: The longest substrings with no more than '3' distinct characters are "cbbeb" & "bbebi".
"""
def longest_substring_with_k_distinct(str, k):
longestLength, windowStart = 0, 0
memory = {}
for windowEnd in range(len(str)):
currentChar = str[windowEnd]
if currentChar not in memory:
memory[currentChar] = 0
memory[currentChar] += 1
while len(memory) > k:
character = str[windowStart]
memory[character] -= 1
if memory[character] == 0:
del memory[character]
windowStart += 1
currentLength = windowEnd - windowStart + 1
longestLength = max(longestLength, currentLength)
return longestLength
|
def nth_sevenish_number(n):
answer, bit_place = 0, 0
while n > 0:
if n & 1 == 1:
answer += 7 ** bit_place
n >>= 1
bit_place += 1
return answer
# n = 1
# print(nth_sevenish_number(n))
for n in range(1, 10):
print(nth_sevenish_number(n))
|
"""
creates decorator for class that counts instances
and allows to return and reset this value
"""
def instances_counter(cls):
"""Some code"""
setattr(cls, 'ins_cnt', 0)
def __init__(self):
cls.ins_cnt += 1
cls.__init__
def get_created_instances(self=None):
return cls.ins_cnt
def reset_instances_counter(self=None):
return cls.ins_cnt
cls.ins_cnt = 0
setattr(cls, '__init__', __init__)
setattr(cls, 'get_created_instances', get_created_instances)
setattr(cls, 'reset_instances_counter', reset_instances_counter)
return cls
@instances_counter
class User:
pass
if __name__ == '__main__':
User.get_created_instances() # 0
user, _, _ = User(), User(), User()
user.get_created_instances() # 3
user.reset_instances_counter() # 3
|
# coding=utf-8
"""
Manages a UDP socket and does two things:
1. Retrieve incoming messages from DCS and update :py:class:`esst.core.status.status`
2. Sends command to the DCS application via the socket
"""
|
# 분해합
# 브루트포스의 정석
# 각각 1부터 쭉 해주는 것에 for문을 쓰는데 인색하지 말자.
# 정말 앞에서부터 하나하나 쓰는 것을 중심으로 가야한다.
# [boj-백준] Brute force 2231 분해 합 - python
n = int(input())
for i in range(1, n+1):
a = list(map(int, str(i)))
sum_sep = sum(a)
sum_all = i + sum_sep
if sum_all == n:
print(i)
break
if i == n:
print(0)
|
'''
Find missing no. in array.
'''
def missingNo(arr):
n = len(arr)
sumOfArr = 0
for num in range(0,n):
sumOfArr = sumOfArr + arr[num]
sumOfNno = (n * (n+1)) // 2
missNumber = sumOfNno - sumOfArr
print(missNumber)
arr = [3,0,1]
missingNo(arr)
|
a = "python"
b = "is"
c = "excellent"
d = a[0] + c[0] + a[len(a)-1] + b
print(d)
|
# weekdays buttons
WEEKDAY_BUTTON = 'timetable_%(weekday)s_button'
TIMETABLE_BUTTON = 'timetable_%(attendance)s_%(week_parity)s_%(weekday)s_button'
# parameters buttons
NAME = 'name_button'
MAILING = 'mailing_parameters_button'
ATTENDANCE = 'attendance_button'
COURSES = 'courses_parameters_button'
PARAMETERS_RETURN = 'return_parameters_button'
EXIT_PARAMETERS = 'exit_parameters_button'
MAIN_SET = {NAME, MAILING, COURSES, ATTENDANCE, PARAMETERS_RETURN}
# attendance buttons
ATTENDANCE_ONLINE = 'online_attendance_button'
ATTENDANCE_OFFLINE = 'offline_attendance_button'
ATTENDANCE_BOTH = 'both_attendance_button'
ATTENDANCE_SET = {ATTENDANCE_BOTH, ATTENDANCE_OFFLINE, ATTENDANCE_ONLINE}
# everyday message buttons
ALLOW_MAILING = 'allowed_mailing_button'
FORBID_MAILING = 'forbidden_mailing_button'
ENABLE_MAILING_NOTIFICATIONS = 'enabled_notification_mailing_button'
DISABLE_MAILING_NOTIFICATIONS = 'disabled_notification_mailing_button'
TZINFO = 'tz_info_button'
MESSAGE_TIME = 'message_time_button'
MAILING_SET = {ALLOW_MAILING, FORBID_MAILING, ENABLE_MAILING_NOTIFICATIONS, DISABLE_MAILING_NOTIFICATIONS,
MESSAGE_TIME, TZINFO}
# courses buttons
OS_TYPE = 'os_type_button'
SP_TYPE = 'sp_type_button'
ENG_GROUP = 'eng_group_button'
HISTORY_GROUP = 'history_group_button'
COURSES_RETURN = 'return_courses_button'
COURSES_SET = {OS_TYPE, SP_TYPE, HISTORY_GROUP, ENG_GROUP, COURSES_RETURN}
# os buttons
OS_ADV = 'os_adv_button'
OS_LITE = 'os_lite_button'
OS_ALL = 'os_all_button'
OS_SET = {OS_ADV, OS_LITE, OS_ALL}
# sp buttons
SP_KOTLIN = 'sp_kotlin_button'
SP_IOS = 'sp_ios_button'
SP_ANDROID = 'sp_android_button'
SP_WEB = 'sp_web_button'
SP_CPP = 'sp_cpp_button'
SP_ALL = 'sp_all_button'
SP_SET = {SP_CPP, SP_IOS, SP_WEB, SP_KOTLIN, SP_ANDROID, SP_ALL}
# eng buttons
ENG_C2_1 = 'eng_c2_1_button'
ENG_C2_2 = 'eng_c2_2_button'
ENG_C2_3 = 'eng_c2_3_button'
ENG_C1_1 = 'eng_c1_1_button'
ENG_C1_2 = 'eng_c1_2_button'
ENG_B2_1 = 'eng_b2_1_button'
ENG_B2_2 = 'eng_b2_2_button'
ENG_B2_3 = 'eng_b2_3_button'
ENG_B11_1 = 'eng_b11_1_button'
ENG_B11_2 = 'eng_b11_2_button'
ENG_B12_1 = 'eng_b12_1_button'
ENG_B12_2 = 'eng_b12_2_button'
ENG_ALL = 'eng_all_button'
ENG_NEXT = 'eng_next_button'
ENG_PREV = 'eng_prev_button'
ENG_SET = {ENG_C2_1, ENG_C2_3, ENG_C1_1, ENG_C1_2, ENG_B2_1, ENG_B2_2, ENG_B2_3, ENG_C2_2, ENG_B11_1, ENG_B11_2,
ENG_B12_1, ENG_B12_2, ENG_ALL, ENG_NEXT, ENG_PREV}
# history buttons
HISTORY_INTERNATIONAL = 'history_international_button'
HISTORY_SCIENCE = 'history_science_button'
HISTORY_EU_PROBLEMS = 'history_eu_problems_button'
HISTORY_CULTURE = 'history_culture_button'
HISTORY_REFORMS = 'history_reforms_button'
HISTORY_STATEHOOD = 'history_statehood_button'
HISTORY_ALL = 'history_all_button'
HISTORY_SET = {HISTORY_CULTURE, HISTORY_EU_PROBLEMS, HISTORY_INTERNATIONAL, HISTORY_REFORMS, HISTORY_SCIENCE,
HISTORY_STATEHOOD, HISTORY_ALL}
def is_course_update(button):
return button in HISTORY_SET or button in ENG_SET or button in OS_SET or button in SP_SET
# SUBJECTS change page
SUBJECT = 'subject_%(subject)s_%(attendance)s_%(page)s_button'
# HELP change page
HELP_MAIN = 'help_main_button'
HELP_ADDITIONAL = 'help_additional_button'
# other
CANCEL = 'cancel_button'
CANCEL_CALLBACK = 'cancel_%(data)s_button'
# admin ls button
ADMIN_LS = 'admin_ls_%(page_number)d_button'
NEXT_PAGE = 'admin_ls_next_button'
PREV_PAGE = 'admin_ls_prev_button'
UPDATE_PAGE = 'admin_ls_update_button'
DEADLINE = 'deadline_%(day_id)s_button'
|
#coding:utf-8
MONGODB=('192.168.1.252',27017)
MONGODB=('127.0.0.1',27018)
# MONGODB=('192.168.1.252',27018)
STRATEGY_SERVER = MONGODB # 策略运行记录数据库
STRATEGY_DB_NAME = 'CTP_BlackLocust'
QUOTES_DB_SERVER = MONGODB # 行情历史k线数据库
TRADE_INTERFACE_SIMNOW = 'http://192.168.1.252:17001'
TRADE_INTERFACE_ZSQH_TEST = 'http://192.168.1.252:17001'
TRADE_INTERFACE_ZSQH_PRD = 'http://192.168.1.252:17001' # 浙商期货
TRADE_INTERFACE_ZSQH_PRD = 'http://127.0.0.1:17001' # 浙商期货
# TRADE_INTERFACE_SIMNOW = 'http://wallizard.com:17001'
TRADE_API_URL = TRADE_INTERFACE_ZSQH_PRD
# MD_BROKER='192.168.1.252:6379:0:'
MD_BROKER='127.0.0.1:6379:0:'
TRADE_PUBSUB_EVENT_NAME = 'zsqh-prd'
TRADE_API_SIMNOW = 1
TRADE_API_ZSQH = 2
TRADE_API_CURRENT = TRADE_API_SIMNOW
CRAWL_WORKTIME = (16,20) # 每日 16 -20 之间
symbols ={
'i2001':'tdx/I2001.txt',
'ru2001':'tdx/RU2001.txt',
'SR001': 'tdx/SR2001.txt',
'jm2001': 'tdx/JM2001.txt',
'TA001': 'tdx/TA2001.txt',
'j2001': 'tdx/J2001.txt',
'rb2001': 'tdx/RB2001.txt',
}
#爬取日k线数据
CRAWL_DAILY_SYMBOLS= {
'i2001':'I2001',
'ru2001':'RU2001',
'SR001':'SR2001',
'jm2001':'JM2001',
'TA001':'TA2001',
'j2001':'J2001',
'rb2001':'RB2001',
}
|
class SearchParams(object):
def __init__(self):
self.maxTweets = 0
def set_username(self, username):
self.username = username
return self
def set_since(self, since):
self.since = since
return self
def set_until(self, until):
self.until = until
return self
def set_search(self, query_search):
self.querySearch = query_search
return self
def set_max_tweets(self, max_tweets):
self.maxTweets = max_tweets
return self
def set_lang(self, lang):
self.lang = lang
return self
|
x = int(input("Please enter any number!"))
if x >= 0:
print( "Positive")
else:
print( "Negative")
|
# IF
# In this program, we check if the number is positive or negative or zero and
# display an appropriate message
# Flow Control
x=7
if x>10:
print("x is big.")
elif x > 0:
print("x is small.")
else:
print("x is not positive.")
# Array
# Variabel array
genap = [14,24,56,80]
ganjil = [13,55,73,23]
nap = 0
jil = 0
# Buat looping for menggunakanvariable dari array yang udah dibuat
for val in genap:
nap = nap+val
for val in ganjil:
jil = jil+val
print("Ini adalah bilangan Genap", nap )
print("Ini adalah bilangan Ganjil", jil )
|
num = int(input("1부터 9 사이 숫자를 입력하세요 : "))
for i in range(1, num+1):
if i % 2 != 0:
for j in range(1, num+1):
if j % 2 != 0:
print(j, end=' ')
else:
for j in range(1, num+1):
if j % 2 == 0:
print(' ', j, end='')
print('\n')
|
# Remember that everything in python is
# pass by reference
if __name__ == '__main__':
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four: ', a[:4]) # same as a[0:4]
# -ve list index starts at position 1
print('Last four: ', a[-4:])
print('Middle two: ', a[3:-3])
# when used in assignments, lists will grow/shrink to accomodate the new
# values
# remember a[x:y] is index x inclusive, y not inclusive
print('Before : ', a) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# list items from index 2:7 will shrink to fit 3 items
a[2:7] = [99, 22, 14]
print('After : ', a) # ['a', 'b', 99, 22, 14, 'h']
# same applies to assignment of a slice with no start/end index
# if you leave out the start/end index in a slice
# you create a copy of the list
b = a[:]
assert b is not a
# but if we were to assign b to a
# a and b are references to the same object
b = a
a[:] = [100, 101, 102]
assert a is b # still the same object
print('Second assignment : ', a) # ['a', 'b', 99, 22, 14, 'h']
|
"""
@author: Alfons
@contact: alfons_xh@163.com
@file: 19-07-Property.py
@time: 18-8-18 下午7:22
@version: v1.0
"""
# ----------------------------------------原始------------------------------------------
class LineItem:
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def SubTotal(self):
return self.weight * self.price
raisins = LineItem('Golden raisins', 10, 6.0)
print(raisins.SubTotal())
raisins.weight = -20
print(raisins.SubTotal())
# ----------------------------------------改进一------------------------------------------
class LineItem2(LineItem):
@property
def weight(self): # 必须与属性(Attribute)名称相同
return self.__weight
@weight.setter
def weight(self, value):
if value > 0:
self.__weight = value
else:
raise ValueError("value must be > 0")
def GetPrice(self):
return self.__price
def SetPrice(self, value):
if value > 0:
self.__price = value
else:
raise ValueError("value must be > 0")
price = property(GetPrice, SetPrice)
raisins2 = LineItem2('Golden raisins', 10, 6.0)
print(vars(raisins2))
print((raisins2.weight, raisins2.price))
# ----------------------------------------改进二------------------------------------------
class LineItem3(LineItem):
def GetWeight(self):
return self.__weight
def SetWeight(self, value):
if value > 0:
self.__weight = value
else:
raise ValueError("value must be > 0")
weight = property(GetWeight, SetWeight, doc="weight in kilograms") # 构建公开的property对象,然后赋值给公开的类属性
raisins3 = LineItem3('Golden raisins', 10, 6.0)
# obj.attr这样的表达式不会从实例obj中开始寻找attr,而是从obj.__class__开始,
# 仅当类中没有名为attr的特性时,才会在实例obj中寻找attr
print(raisins3.__class__.weight)
print(raisins3.weight)
print(help(LineItem3.weight))
# ----------------------------------------改进三(工厂函数)------------------------------------------
def Quantity(storage_name):
def QtyGetter(instance):
return instance.__dict__[storage_name]
def QtySetter(instance, value):
if value > 0:
instance.__dict__[storage_name] = value
else:
raise ValueError("value must be > 0")
def QtyDeleter(instance): # 仅实例调用
if storage_name in instance.__dict__.keys():
del instance.__dict__[storage_name]
else:
print("Del {0} fail, {0} not in.".format(storage_name))
return property(QtyGetter, QtySetter, QtyDeleter, doc="weight in kilograms")
class LineItem4(LineItem):
weight = Quantity("weight")
price = Quantity("price")
raisins4 = LineItem4('Golden raisins', 10, 6.0)
print(raisins4)
print(raisins4.weight)
print(raisins4.__class__.weight)
print(LineItem4.weight)
print(raisins4.price)
print(raisins4.__class__.price)
print(LineItem4.price)
print(raisins4.__dict__)
print(raisins4.__class__.__dict__)
# del raisins4.weight
# print(raisins4.__dict__)
# print(raisins4.__class__.__dict__)
del LineItem4.weight
print(raisins4.__dict__)
print(raisins4.__class__.__dict__)
print("\n\n")
print('\ndir(raisins4) -> ', dir(raisins4))
print('\ngetattr(raisins4, "price") -> ', getattr(raisins4, "price"))
print('\nhasattr(raisins4, "price") -> ', hasattr(raisins4, "price"))
setattr(raisins4, "newattr", 10)
# print('setattr(raisins4, "newattr", 10) -> ', LineItem4.newattr) # 类中不含此属性
print('\nsetattr(raisins4, "newattr", 10) -> ', raisins4.newattr)
print('\nvars(raisins4) -> ', vars(raisins4))
print('\nvars() -> ', vars())
|
## This script contains useful functions to generate a html page given a
## blog post txt file. It also creates meta data for the blog posts to be
## used to make summaries.
## Input should be a txt file of specific format
def read_file(infile):
metadata = []
post = []
with open(infile, 'r') as f:
for line in f:
if line[0] == '#':
metadata.append(line.strip('\n'))
else:
post.append(line)
return {'metadata':metadata, 'post':post}
def get_title(metadata):
title = filter(lambda x: '##title' in x, metadata)
title = title[0][8: len(title[0])]
return title
def get_subtitle(metadata):
subtitle = filter(lambda x: '##subtitle' in x, metadata)
subtitle = subtitle[0][11: len(subtitle[0])]
return subtitle
def get_author(metadata):
author = filter(lambda x: '##author' in x, metadata)
author = author[0][9: len(author[0])]
return author
def get_date(metadata):
date = filter(lambda x: '##date' in x, metadata)
date = date[0][7: len(date[0])]
return date
def get_topic(metadata):
topic = filter(lambda x: '##topic' in x, metadata)
topic = topic[0][8: len(topic[0])]
return topic
def modify_template(file_to_modify, string2find, replace_value, outfile):
# Read in the file
with open(file_to_modify, 'r') as file:
filedata = file.read()
# Replace the target string
for i in range(len(string2find)):
filedata = filedata.replace(string2find[i], str(replace_value[i]))
# Write the file out
with open(outfile, 'w') as file:
file.write(filedata)
|
#!/usr/bin/env python
"""
check out chapter 2 of cam
"""
|
#!/usr/bin/env python3
#chmod +x hello.py
#It will insert space and newline in preset
print ("Hello", "World!")
|
"""Django Asana integration project"""
# :copyright: (c) 2017-2021 by Stephen Bywater.
# :license: MIT, see LICENSE for more details.
VERSION = (1, 4, 8)
__version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:])
__author__ = 'Steve Bywater'
__contact__ = 'steve@regionalhelpwanted.com'
__homepage__ = 'https://github.com/sbywater/django-asana'
__docformat__ = 'restructuredtext'
__license__ = 'MIT'
# -eof meta-
default_app_config = 'djasana.apps.DjsanaConfig'
|
def final_pos():
x = y = 0
with open("input.txt") as inp:
while True:
instr = inp.readline()
try:
cmd, val = instr.split()
except ValueError:
break
else:
if cmd == "forward":
x += int(val)
elif cmd == "down":
y += int(val)
elif cmd == "up":
y -= int(val)
print(f"Final Val: {x * y}")
if __name__ == '__main__':
final_pos()
|
class zoo:
def __init__(self,stock,cuidadores,animales):
pass
class cuidador:
def __init__(self,animales,vacaciones):
pass
class animal:
def __init__(self,dieta):
pass
class vacaciones:
def __init__(self):
pass
class comida:
def __init__(self,dieta):
pass
class stock:
def __init__(self,comida):
pass
class carnivoros:
def __init__(self):
pass
class herbivoros:
def __init__(self):
pass
class insectivoros:
def __init__(self):
pass
print("puerca")
|
PROLOGUE = '''module smcauth(clk, rst, g_input, e_input, o);
input clk;
input [255:0] e_input;
input [255:0] g_input;
output o;
input rst;
'''
EPILOGUE = 'endmodule\n'
OR_CIRCUIT = '''
OR {} (
.A({}),
.B({}),
.Z({})
);
'''
AND_CIRCUIT = '''
ANDN {} (
.A({}),
.B({}),
.Z({})
);
'''
XOR_CIRCUIT = '''
XOR {} (
.A({}),
.B({}),
.Z({})
);
'''
circuit_counter = 0
wire_counter = 0
def circuit():
global circuit_counter
circuit_counter += 1
return 'C%d' % circuit_counter
def wire():
global wire_counter
wire_counter += 1
return 'W%d' % wire_counter
def new_circuit(circuit_template, in1, in2, out=None):
global payload
if out is None:
out = wire()
payload += circuit_template.format(
circuit(),
in1,
in2,
out
)
return out
payload = ''
now = new_circuit(XOR_CIRCUIT, 'g_input[0]', 'e_input[0]')
for i in range(1, 255):
now = new_circuit(XOR_CIRCUIT, 'g_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'e_input[%d]' % i, now)
now = new_circuit(XOR_CIRCUIT, 'g_input[255]', now)
now = new_circuit(XOR_CIRCUIT, 'e_input[255]', now, 'o')
payload += EPILOGUE
wires = ''
for i in range(1, wire_counter+1):
wires += ' wire W%d;\n' % i
payload = PROLOGUE + wires + payload
with open('test.v', 'w') as f:
f.write(payload)
|
SINGLE_MATCHING_ITEM = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_CAPITALISATION = """
<rss version="2.0">
<channel>
<item>
<title>TestShow S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_SPECIAL_CHARS = """
<rss version="2.0">
<channel>
<item>
<title>Mr Robot S02E03 720p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
MULTIPLE_MATCHING_ITEMS = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 720p</title>
<link>testlink</link>
</item>
<item>
<title>testshow S2E3 1080i</title>
<link>testlink</link>
</item>
<item>
<title>testshow 02x03 720i</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
SINGLE_ITEM_LOW_QUALITY = """
<rss version="2.0">
<channel>
<item>
<title>testshow S02E03 480p</title>
<link>testlink</link>
</item>
</channel>
</rss>
"""
|
"""
Loop control version 1.1.10.20
Copyright (c) 2020 Shahibur Rahaman
Licensed under MIT
"""
# Pass
# Continue
# break
# A runner is practicing in a stadium and the coach is giving orders.
t = 180
for i in range(t, 1, -1):
t = t - 5
if t > 150:
print("Time:", t, "| Do another lap.")
continue
if t > 120:
print("Time:", t, "| You are improving your laptime!")
pass
if t < 105:
print("Time:", t, "| Excellent, you have beaten the best runner's record!")
break
print("")
|
"""
Profile ../profile-datasets-py/div83/040.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/040.py"
self["Q"] = numpy.array([ 1.890026, 2.119776, 2.622053, 3.246729,
3.667537, 4.216342, 4.862296, 5.531749,
6.100783, 6.376119, 6.376069, 6.30519 ,
6.187932, 5.998564, 5.778127, 5.603999,
5.44443 , 5.194473, 4.915426, 4.653008,
4.45 , 4.296832, 4.148003, 4.015564,
3.910205, 3.839615, 3.790106, 3.753656,
3.721226, 3.693996, 3.677826, 3.674526,
3.655867, 3.640757, 3.644617, 3.663107,
3.679716, 3.683656, 3.678676, 3.667877,
3.655367, 3.648067, 3.646037, 3.644827,
3.651267, 3.691236, 3.765886, 3.858565,
3.940824, 3.994534, 4.097813, 4.351141,
4.794867, 5.49314 , 6.497828, 8.015136,
10.60419 , 15.81985 , 21.16895 , 24.30741 ,
23.60504 , 24.79699 , 27.87162 , 33.67817 ,
42.22522 , 52.68792 , 65.67979 , 82.04257 ,
102.6225 , 116.7384 , 124.9514 , 131.6637 ,
137.0252 , 130.226 , 119.7127 , 105.9718 ,
104.862 , 125.6962 , 167.5619 , 234.0722 ,
297.3785 , 359.7445 , 423.0569 , 497.9349 ,
552.8482 , 569.9959 , 545.77 , 535.4481 ,
711.82 , 1148.918 , 1499.767 , 1580.109 ,
1531.92 , 1436.304 , 1228.928 , 1011.186 ,
845.8809 , 853.3132 , 830.1563 , 807.9197 , 786.5588 ])
self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02,
7.69000000e-02, 1.37000000e-01, 2.24400000e-01,
3.45400000e-01, 5.06400000e-01, 7.14000000e-01,
9.75300000e-01, 1.29720000e+00, 1.68720000e+00,
2.15260000e+00, 2.70090000e+00, 3.33980000e+00,
4.07700000e+00, 4.92040000e+00, 5.87760000e+00,
6.95670000e+00, 8.16550000e+00, 9.51190000e+00,
1.10038000e+01, 1.26492000e+01, 1.44559000e+01,
1.64318000e+01, 1.85847000e+01, 2.09224000e+01,
2.34526000e+01, 2.61829000e+01, 2.91210000e+01,
3.22744000e+01, 3.56505000e+01, 3.92566000e+01,
4.31001000e+01, 4.71882000e+01, 5.15278000e+01,
5.61260000e+01, 6.09895000e+01, 6.61253000e+01,
7.15398000e+01, 7.72396000e+01, 8.32310000e+01,
8.95204000e+01, 9.61138000e+01, 1.03017000e+02,
1.10237000e+02, 1.17778000e+02, 1.25646000e+02,
1.33846000e+02, 1.42385000e+02, 1.51266000e+02,
1.60496000e+02, 1.70078000e+02, 1.80018000e+02,
1.90320000e+02, 2.00989000e+02, 2.12028000e+02,
2.23442000e+02, 2.35234000e+02, 2.47408000e+02,
2.59969000e+02, 2.72919000e+02, 2.86262000e+02,
3.00000000e+02, 3.14137000e+02, 3.28675000e+02,
3.43618000e+02, 3.58966000e+02, 3.74724000e+02,
3.90893000e+02, 4.07474000e+02, 4.24470000e+02,
4.41882000e+02, 4.59712000e+02, 4.77961000e+02,
4.96630000e+02, 5.15720000e+02, 5.35232000e+02,
5.55167000e+02, 5.75525000e+02, 5.96306000e+02,
6.17511000e+02, 6.39140000e+02, 6.61192000e+02,
6.83667000e+02, 7.06565000e+02, 7.29886000e+02,
7.53628000e+02, 7.77790000e+02, 8.02371000e+02,
8.27371000e+02, 8.52788000e+02, 8.78620000e+02,
9.04866000e+02, 9.31524000e+02, 9.58591000e+02,
9.86067000e+02, 1.01395000e+03, 1.04223000e+03,
1.07092000e+03, 1.10000000e+03])
self["CO2"] = numpy.array([ 370.8133, 370.8152, 370.819 , 370.8248, 370.8346, 370.8484,
370.8592, 370.8579, 370.8967, 370.9416, 370.9656, 370.9707,
371.0187, 371.0558, 371.0859, 371.1189, 371.164 , 371.2181,
371.2882, 371.3753, 371.4853, 371.5974, 371.7105, 371.8065,
371.8855, 371.9556, 371.9716, 371.9786, 371.9036, 371.8306,
371.8296, 371.8286, 371.9816, 372.1516, 372.3736, 372.6286,
372.8946, 373.1656, 373.4526, 373.8036, 374.1786, 374.5586,
374.9416, 375.3396, 375.6096, 375.8926, 376.1336, 376.3425,
376.5465, 376.6605, 376.7785, 376.8464, 376.8902, 376.9449,
377.0346, 377.128 , 377.324 , 377.549 , 377.852 , 378.2698,
378.7031, 379.2006, 379.7134, 380.1292, 380.5039, 380.8129,
380.989 , 381.1627, 381.2329, 381.3075, 381.3593, 381.4038,
381.4637, 381.5393, 381.6193, 381.7075, 381.794 , 381.882 ,
381.973 , 382.0935, 382.2253, 382.3864, 382.5441, 382.6894,
382.8332, 382.9886, 383.1448, 383.2917, 383.3489, 383.3001,
383.2863, 383.3892, 383.5445, 383.7251, 383.9945, 384.3599,
385.021 , 385.4928, 385.8484, 386.0688, 386.149 ])
self["CO"] = numpy.array([ 5.07834 , 4.978429 , 4.783627 , 4.465066 , 4.009665 ,
3.428986 , 2.1168 , 0.7107151 , 0.3604568 , 0.1722319 ,
0.09253791, 0.06835487, 0.06619429, 0.06226643, 0.05921646,
0.05582889, 0.05210092, 0.04852775, 0.04563088, 0.0435902 ,
0.04266791, 0.04196062, 0.04131023, 0.04063314, 0.03983114,
0.03892895, 0.03783966, 0.03667146, 0.03530527, 0.03391147,
0.03270558, 0.03146188, 0.03095409, 0.03045309, 0.03021789,
0.03010279, 0.03018719, 0.03073179, 0.03131748, 0.03369348,
0.03659667, 0.04005435, 0.04421134, 0.04900962, 0.05320021,
0.05796649, 0.06307856, 0.06862024, 0.07462111, 0.07899018,
0.08380636, 0.08758932, 0.09090566, 0.09480198, 0.1001443 ,
0.1059952 , 0.1139498 , 0.1231891 , 0.1334292 , 0.1447495 ,
0.1573193 , 0.1683598 , 0.180545 , 0.1902606 , 0.1989896 ,
0.2064601 , 0.2107932 , 0.2151723 , 0.2166698 , 0.2182195 ,
0.2193496 , 0.220384 , 0.2215356 , 0.222791 , 0.2240452 ,
0.2252751 , 0.2264323 , 0.2273394 , 0.2281768 , 0.2287195 ,
0.2293438 , 0.2301862 , 0.2313281 , 0.2330089 , 0.234985 ,
0.2372327 , 0.2394283 , 0.2416156 , 0.2436684 , 0.2454167 ,
0.2468103 , 0.2475702 , 0.2474194 , 0.2469778 , 0.2469551 ,
0.2485434 , 0.2532306 , 0.2569715 , 0.255173 , 0.2553855 ,
0.2556078 ])
self["T"] = numpy.array([ 201.756, 208.959, 221.236, 232.895, 242.747, 248.786,
248.329, 240.903, 229.68 , 220.741, 219.585, 222.314,
223.457, 223.196, 222.551, 222.843, 222.789, 222.21 ,
221.367, 220.664, 220.666, 221.42 , 221.862, 221.833,
221.445, 221.116, 221.34 , 221.609, 221.876, 222.239,
222.762, 223.15 , 223.03 , 222.598, 221.894, 221.35 ,
221.172, 221.079, 220.7 , 220.162, 219.576, 219.085,
218.821, 218.548, 218.069, 217.619, 217.047, 216.42 ,
215.951, 215.682, 215.498, 215.293, 215.002, 214.535,
213.791, 212.72 , 211.396, 210.082, 209.266, 208.907,
209.051, 209.749, 211.078, 212.777, 214.68 , 216.699,
218.741, 220.833, 222.97 , 225.147, 227.187, 229.093,
230.856, 232.34 , 233.77 , 235.146, 236.509, 237.94 ,
239.449, 241.132, 242.895, 244.697, 246.497, 248.304,
250.093, 251.797, 253.356, 254.716, 255.748, 256.257,
256.617, 256.449, 255.921, 255.521, 254.315, 252.591,
250.969, 251.339, 251.339, 251.339, 251.339])
self["N2O"] = numpy.array([ 1.59999700e-04, 6.39998600e-04, 9.99997400e-04,
1.28999600e-03, 3.35998800e-03, 3.46998500e-03,
2.00999000e-03, 9.29994900e-04, 7.69995300e-04,
1.55999000e-03, 3.49997800e-03, 4.09997400e-03,
3.60997800e-03, 3.51997900e-03, 3.85997800e-03,
5.33997000e-03, 7.33996000e-03, 1.04899500e-02,
1.34499300e-02, 1.60199300e-02, 1.84799200e-02,
2.20899100e-02, 2.61798900e-02, 3.00898800e-02,
5.58597800e-02, 8.34796800e-02, 1.10069600e-01,
1.41009500e-01, 1.72649400e-01, 2.03189200e-01,
2.29059200e-01, 2.39769100e-01, 2.50139100e-01,
2.60199100e-01, 2.68909000e-01, 2.72829000e-01,
2.76629000e-01, 2.80329000e-01, 2.79099000e-01,
2.77989000e-01, 2.76929000e-01, 2.78389000e-01,
2.81049000e-01, 2.83589000e-01, 2.87389000e-01,
2.91148900e-01, 2.94858900e-01, 2.98488800e-01,
3.01988800e-01, 3.05358800e-01, 3.08538700e-01,
3.11508600e-01, 3.14228500e-01, 3.16658300e-01,
3.18747900e-01, 3.19607400e-01, 3.20386600e-01,
3.21084900e-01, 3.21683200e-01, 3.22162200e-01,
3.22532400e-01, 3.22752000e-01, 3.22831000e-01,
3.22829100e-01, 3.22826400e-01, 3.22823000e-01,
3.22818800e-01, 3.22813500e-01, 3.22806900e-01,
3.22802300e-01, 3.22799700e-01, 3.22797500e-01,
3.22795800e-01, 3.22798000e-01, 3.22801400e-01,
3.22805800e-01, 3.22806100e-01, 3.22799400e-01,
3.22785900e-01, 3.22764400e-01, 3.22744000e-01,
3.22723900e-01, 3.22703400e-01, 3.22679200e-01,
3.22661500e-01, 3.22656000e-01, 3.22663800e-01,
3.22667100e-01, 3.22610200e-01, 3.22469100e-01,
3.22355800e-01, 3.22329900e-01, 3.22345400e-01,
3.22376300e-01, 3.22443300e-01, 3.22513500e-01,
3.22566900e-01, 3.22564500e-01, 3.22572000e-01,
3.22579200e-01, 3.22586100e-01])
self["O3"] = numpy.array([ 0.510174 , 0.5621888 , 0.6514743 , 0.7822175 , 0.9318276 ,
1.063576 , 1.310564 , 1.76503 , 2.535005 , 3.648507 ,
4.547261 , 4.78841 , 4.92361 , 5.275468 , 5.694327 ,
5.762868 , 5.783319 , 5.893709 , 6.03422 , 6.160551 ,
6.228622 , 6.203113 , 6.153684 , 6.089276 , 6.012956 ,
5.923467 , 5.849328 , 5.783048 , 5.734829 , 5.679589 ,
5.574619 , 5.39368 , 5.244621 , 5.120821 , 4.922902 ,
4.727543 , 4.524263 , 4.246424 , 3.923376 , 3.604037 ,
3.319568 , 3.047309 , 2.75112 , 2.482241 , 2.317652 ,
2.148792 , 1.885393 , 1.603124 , 1.397604 , 1.272585 ,
1.146755 , 0.9980887 , 0.8611839 , 0.729153 , 0.5870622 ,
0.4483724 , 0.3575272 , 0.2652448 , 0.1737753 , 0.1178921 ,
0.09092905, 0.07172082, 0.05827958, 0.05142367, 0.04863645,
0.04841805, 0.04816644, 0.04715373, 0.04594748, 0.04495205,
0.0455781 , 0.04686353, 0.04873582, 0.04975662, 0.0501041 ,
0.04979462, 0.04934463, 0.04914342, 0.04915406, 0.04921568,
0.04915478, 0.04893549, 0.04849328, 0.04805416, 0.04794348,
0.04790108, 0.0476205 , 0.04700432, 0.04654844, 0.04632991,
0.04646221, 0.04573811, 0.04403783, 0.04091335, 0.03254705,
0.02640277, 0.02501912, 0.02442054, 0.02442111, 0.02442165,
0.02442218])
self["CH4"] = numpy.array([ 0.04183322, 0.07070085, 0.09215896, 0.1150766 , 0.1600424 ,
0.1895992 , 0.203706 , 0.2216318 , 0.2513385 , 0.2618113 ,
0.2802002 , 0.3011591 , 0.323238 , 0.3478319 , 0.3743778 ,
0.4088557 , 0.4408626 , 0.4700776 , 0.4956766 , 0.5058676 ,
0.5155767 , 0.5382237 , 0.5665796 , 0.5937466 , 0.6694654 ,
0.7486761 , 0.8249039 , 0.9082426 , 0.9919303 , 1.046986 ,
1.106076 , 1.169336 , 1.236905 , 1.290275 , 1.341695 ,
1.390245 , 1.434895 , 1.474525 , 1.496414 , 1.519504 ,
1.543804 , 1.569344 , 1.596164 , 1.637644 , 1.659294 ,
1.681934 , 1.697794 , 1.708283 , 1.718413 , 1.722753 ,
1.727263 , 1.729712 , 1.731132 , 1.7327 , 1.734659 ,
1.736686 , 1.740032 , 1.743762 , 1.748043 , 1.753067 ,
1.758228 , 1.763046 , 1.768011 , 1.77186 , 1.775215 ,
1.778026 , 1.779713 , 1.781404 , 1.782387 , 1.783412 ,
1.784227 , 1.784995 , 1.785885 , 1.786897 , 1.788006 ,
1.78924 , 1.790502 , 1.791825 , 1.793189 , 1.79475 ,
1.796366 , 1.798093 , 1.799748 , 1.801223 , 1.802603 ,
1.803951 , 1.805294 , 1.806622 , 1.807672 , 1.80842 ,
1.809452 , 1.811134 , 1.812978 , 1.815059 , 1.817833 ,
1.821496 , 1.829131 , 1.834953 , 1.839252 , 1.841891 ,
1.842819 ])
self["CTP"] = 500.0
self["CFRACTION"] = 0.0
self["IDG"] = 0
self["ISH"] = 0
self["ELEVATION"] = 0.0
self["S2M"]["T"] = 251.339
self["S2M"]["Q"] = 786.558838187
self["S2M"]["O"] = 0.0244221754008
self["S2M"]["P"] = 1007.16998
self["S2M"]["U"] = 0.0
self["S2M"]["V"] = 0.0
self["S2M"]["WFETC"] = 100000.0
self["SKIN"]["SURFTYPE"] = 1
self["SKIN"]["WATERTYPE"] = 1
self["SKIN"]["T"] = 251.339
self["SKIN"]["SALINITY"] = 35.0
self["SKIN"]["FOAM_FRACTION"] = 0.0
self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3])
self["ZENANGLE"] = 0.0
self["AZANGLE"] = 0.0
self["SUNZENANGLE"] = 0.0
self["SUNAZANGLE"] = 0.0
self["LATITUDE"] = 72.967
self["GAS_UNITS"] = 2
self["BE"] = 0.0
self["COSBK"] = 0.0
self["DATE"] = numpy.array([2007, 1, 20])
self["TIME"] = numpy.array([0, 0, 0])
|
class Base(object):
def __init__(self, *args, **kwargs):
pass
def dispose(self, *args, **kwargs):
pass
def prepare(self, *args, **kwargs):
pass
def prepare_page(self, *args, **kwargs):
pass
def cleanup(self, *args, **kwargs):
pass
|
"""Creates the train class"""
class Train:
"""
Each train in the metro is an instance of the Train class.
Methods:
__init__: creates a new train in the station
"""
def __init__(self):
self.cars = None
self.board_rate = 8
self.pop = None
self.travelers_exiting = None
self.dwell_time = None
self.car_capacity = 125
@property
def cap(self):
return self.cars * self.car_capacity
|
n1 = float(input("Write the average of the first student "))
n2 = float(input("Write the average of the second student "))
m = (n1+n2)/2
print("The average of the two students is {}".format(m))
|
"""
https://www.codewars.com/kata/52742f58faf5485cae000b9a/train/python
Given an int that is a number of seconds, return a string.
If int is 0, return 'now'.
Otherwise,
return string in an ordered combination of years, days, hours, minutes, and seconds.
Examples:
format_duration(62) # returns "1 minute and 2 seconds"
format_duration(3662) # returns "1 hour, 1 minute and 2 seconds"
"""
def format_duration(seconds: int) -> str:
if seconds == 0:
return 'now'
time_amounts = {'years': 0, 'days': 0,
'hours': 0, 'minutes': 0, 'seconds': 0}
output = ''
if seconds >= 31536000:
time_amounts['years'] = seconds//31536000
output += str(time_amounts['years'])
output += " years, " if time_amounts['years'] > 1 else " year, "
seconds = seconds % 31536000
if seconds >= 86400:
time_amounts['days'] = seconds//86400
output += str(time_amounts['days'])
output += " days, " if time_amounts['days'] > 1 else " day, "
seconds = seconds % 86400
if seconds >= 3600:
time_amounts['hours'] = seconds//3600
output += str(time_amounts['hours'])
output += " hours, " if time_amounts['hours'] > 1 else " hour, "
seconds = seconds % 3600
if seconds >= 60:
time_amounts['minutes'] = seconds//60
output += str(time_amounts['minutes'])
output += " minutes, " if time_amounts['minutes'] > 1 else " minute, "
seconds = seconds % 60
time_amounts['seconds'] = seconds
# Find left-most comma and replace it with ' and'
num_of_digits = sum(c.isdigit() for c in output)
if num_of_digits > 1:
output = ' and'.join(output.rsplit(',', 1))
else:
output = output[:-2]
# Handle seconds
if num_of_digits == 1 and time_amounts['seconds'] > 0:
output += ' and '
if time_amounts['seconds'] == 1:
output += str(time_amounts['seconds']) + ' second'
elif time_amounts['seconds'] > 1:
output += str(time_amounts['seconds']) + ' seconds'
elif num_of_digits > 1 and time_amounts['seconds'] == 0:
output = output[:-5]
output = ' and'.join(output.rsplit(',', 1))
# print(seconds, time_amounts)
return output
print(format_duration(31536100))
print(format_duration(62))
print(format_duration(3662))
print(format_duration(120))
print(format_duration(1))
print(format_duration(132030240))
|
"""
Takes BUY/SELL/HOLD decision on stocks based on some metrics
"""
def decision(ticker):
pass
|
"""
Module containing LinkedList class and Node class.
"""
class LinkedList():
"""
Class to generate and modify linked list.
"""
def __init__(self, arg=None):
self.head = None
if arg is not None:
if hasattr(arg, '__iter__') and not isinstance(arg, str):
for i in arg:
self.append(i)
else:
self.append(arg)
def insert(self, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* at the beginning of the list.
"""
node = Node(new_data)
if not self.head:
self.head = node
else:
current = self.head
self.head = node
self.head.nxt = current
def includes(self, lookup):
"""
Method to see if there is a node in the linked list with
a .data value of *lookup*.
"""
current = self.head
try:
while current.nxt:
if current.data == lookup:
print('included!')
return True
else:
current = current.nxt
if current.data == lookup:
print('included!')
return True
except:
print('no .nxt')
def print(self):
"""
Method to print a string containing the
.data value in every node.
"""
output = ''
current = self.head
while current:
if current == self.head:
output += current.data
else:
output += ', ' + current.data
current = current.nxt
return output
def append(self, new_data):
"""
Method to create a node in the linked list with a
.data value of *new_data* at the end of the list.
"""
node = Node(new_data)
if not self.head:
self.head = node
else:
current = self.head
while current.nxt:
current = current.nxt
current.nxt = node
def add_before(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data
value of *new_data* before the node with the .data
value of *lookup* in the list.
"""
node = Node(new_data)
if self.includes(lookup):
if self.head.data == lookup:
self.insert(new_data)
else:
current = self.head
while current.nxt.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def add_after(self, lookup, new_data):
"""
Method to create a node in the linked list with a .data value
of *new_data* after the node with the .data
value of *lookup* in the list.
"""
node = Node(new_data)
if self.includes(lookup):
current = self.head
while current.data != lookup:
current = current.nxt
node.nxt = current.nxt
current.nxt = node
else:
print('Lookup data not found in list.')
def k_from_end(self, k):
"""
Method to return the data of the kth node in a linked list.
"""
total_nodes = 0
position = 0
current = self.head
while current and current.nxt:
total_nodes += 1
current = current.nxt
if current and not current.nxt:
total_nodes += 1
else:
return 'Empty Linked List'
if k < total_nodes:
position = total_nodes - k
else:
return 'Exception'
current = self.head
for i in range(1, position):
current = current.nxt
return current.data
def __iter__(self):
current = self.head
while current:
yield current.data
current = current.nxt
def __next__(self):
current = self.head
if current:
yield current.nxt
def __add__(self, val):
output = LinkedList()
for i in self:
output.append(i)
if hasattr(val, '__iter__') and not isinstance(val, str):
for i in val:
output.append(i)
else:
output.append(val)
return output
def __iadd__(self, val):
if hasattr(val, '__iter__') and not isinstance(val, str):
for i in val:
self.append(i)
else:
self.append(val)
return self
class Node():
def __init__(self, data):
"""
Initializes an instance of a node with a
.data value equal to *data*.
"""
self.data = data
self.nxt = None
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Elvis Tombini <elvis@mapom.me>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
WLCONF = 'wlister.conf'
WLPREFIX = 'wlister.log_prefix'
WLACTION = 'wlister.default_action'
WLMAXPOST = 'wlister.max_post_read'
WLMAXPOST_VALUE = 2048
class WLConfig(object):
def __init__(self, request, log):
options = request.get_options()
self.log = log
if WLCONF in options:
self.conf = options[WLCONF]
else:
self.conf = None
if WLPREFIX in options:
self.prefix = options[WLPREFIX].strip() + ' '
else:
self.prefix = ''
self.default_action = 'block'
if WLACTION in options:
if options[WLACTION] in \
['block', 'pass', 'logpass', 'logblock']:
self.default_action = options[WLACTION]
else:
self.log('WARNING - unknown value for ' + WLACTION +
', set to block')
else:
self.log('WARNING - ' + WLACTION + ' not defined, set to block')
if WLMAXPOST in options:
self.max_post_read = options[WLMAXPOST]
else:
self.max_post_read = WLMAXPOST_VALUE
self.log('WARNING - default request body to be read set to ' +
str(WLMAXPOST_VALUE))
rules_schema = \
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Conservative json schema defining wlrule format",
"type": "object",
"required": ["id"],
"additionalProperties": False,
"properties": {
"id": {
"type": "string"
},
"prerequisite": {
"type": "object",
"additionalProperties": False,
"properties": {
"has_tag": {
"type": "array",
"items": {"type": "string"}
},
"has_not_tag": {
"type": "array",
"items": {"type": "string"}
}
}
},
"match": {
"type": "object",
"additionalProperties": False,
"properties": {
"order": {
"type": "array",
"items": {
"type": "string"
}
},
"uri": {
"type": "string"
},
"protocol": {
"type": "string"
},
"method": {
"type": "string"
},
"host": {
"type": "string"
},
"args": {
"type": "string"
},
"parameters": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"headers": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_url_encoded": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_json": {
"type": "object"
},
"parameters_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"headers_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"content_url_encoded_in": {
"type": "array",
"items": {
"type": "array",
"minItems": 2,
"maxItems": 2,
"items": {
"type": "string"
}
}
},
"parameters_list": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_list": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_list": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_list_in": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"headers_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"content_url_encoded_unique": {
"type": "array",
"items": {
"type": "string"
}
},
"parameters_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
"headers_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
"content_url_encoded_all_unique": {
"type": "string",
"enum": ["True", "False"]
},
}
},
"action_if_match": {
"type": "object",
"additionalProperties": False,
"properties": {
"whitelist": {
"type": "string",
"enum": ["True", "False"]
},
"set_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"unset_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"log": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"set_header": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"action_if_mismatch": {
"type": "object",
"additionalProperties": False,
"properties": {
"whitelist": {
"type": "string",
"enum": ["True", "False"]
},
"set_tag": {
"type": "array",
"items": {
"type": "string"
}
},
"log": {
"type": "array",
"items": {
"type": "array",
"items": {
"type": "string"
}
}
},
"unset_tag": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
}
}
|
# This programs aasks for your name and says hello
print('Hello world!')
print('What is your name?') #Ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The lenght of your name is : ')
print(len(myName))
print('What is your age?') #Ask for their age
yourAge = input()
print('You will be ' + str(int(yourAge) + 1) + ' in a year.' )
|
# coding=utf8
"""all possible exceptions"""
class LilacException(Exception):
"""There was an ambiguous exception that occurred while
handling lilac process"""
pass
class SourceDirectoryNotFound(LilacException):
"""Source directory was not found"""
pass
class ParseException(LilacException):
"""There was an exception occurred while parsing the source"""
pass
class RenderException(LilacException):
"""There was an exception occurred while rendering to html"""
pass
class SeparatorNotFound(ParseException):
"""There was no separator found in post's source"""
pass
class PostDateTimeNotFound(ParseException):
"""There was no datetime found in post's source"""
pass
class PostTitleNotFound(ParseException):
"""There was no title found in post's source"""
pass
class PostDateTimeInvalid(ParseException):
"""Invalid datetime format, should like '2012-04-05 10:10'"""
pass
class PostTagsTypeInvalid(ParseException):
"""Invalid tags datatype, should be a array"""
pass
class PostHeaderSyntaxError(ParseException):
"""TomlSyntaxError occurred in post's header"""
pass
class ConfigSyntaxError(LilacException):
"""TomlSyntaxError occurred in config.toml"""
pass
class JinjaTemplateNotFound(RenderException):
"""Jinja2 template was not found"""
pass
|
# project/tests/test_ping.py
def test_ping(test_app):
response = test_app.get("/ping")
assert response.status_code == 200
assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}
|
#!/usr/bin/env python
# coding=utf-8
__version__ = "2.1.4"
|
label_name = []
with open("label_name.txt",encoding='utf-8') as file:
for line in file.readlines():
line = line.strip()
name = (line.split('-')[-1])
if name.count('|') > 0:
name = name.split('|')[-1]
print(name)
label_name.append((name))
for item in label_name:
with open('label_name_1.txt','a') as file:
file.write(item+'\n')
|
class Library(object):
def __init__(self):
self.dictionary = {
"Micah": ["Judgement on Samaria and Judah", "Reason for the judgement", "Judgement on wicked leaders",
"Messianic Kingdom", "Birth of the Messiah", "Indictment 1, 2", "Promise of salvation"]
}
def get(self, book):
return self.dictionary.get(book)
|
# Asal sayı: 1'den ve kendisinde başka sayıya bölünmeyen sayılar. 1'den büyük ve pozitif, minimum 2.
i = 155801
z = 0
with open("primenums.txt", "w") as fop:
while True:
i+=1
f = False
for x in range(2,i):
if i % x == 0:
f = True
if f == False:
fop.write(f"{i},")
print(z)
z+=1
|
def split_full_name(string: str) -> list:
"""Takes a full name and splits it into first and last.
Parameters
----------
string : str
The full name to be parsed.
Returns
-------
list
The first and the last name.
"""
return string.split(" ")
# Test it out.
print(split_full_name(string=100000000))
|
AESEncryptParam = "Key (32 Hex characters)"
S_BOX = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
S_BOX_INVERSE = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
R_CON = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
KEYSIZE_ROUNDS_MAP = {16: 10, 24: 12, 32: 14}
def shiftRows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def shiftRowsInvert(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def addRoundKey(input, roundKey):
for i in range(4):
for j in range(4):
input[i][j] ^= roundKey[i][j]
def substituteGeneric(input, subTable):
for i in range(4):
for j in range(4):
input[i][j] = subTable[input[i][j]]
def substitute(input):
substituteGeneric(input, S_BOX)
def substituteInverse(input):
substituteGeneric(input, S_BOX_INVERSE)
def xtime(a):
return (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mixSingleCol(input):
t = input[0] ^ input[1] ^ input[2] ^ input[3]
u = input[0]
input[0] ^= t ^ xtime(input[0] ^ input[1])
input[1] ^= t ^ xtime(input[1] ^ input[2])
input[2] ^= t ^ xtime(input[2] ^ input[3])
input[3] ^= t ^ xtime(input[3] ^ u)
def mixColumns(input):
for i in range(4):
mixSingleCol(input[i])
def mixColumnsInverse(input):
for i in range(4):
u, v = xtime(xtime(input[i][0] ^ input[i][2])), xtime(
xtime(input[i][1] ^ input[i][3]))
input[i][0] ^= u
input[i][1] ^= v
input[i][2] ^= u
input[i][3] ^= v
mixColumns(input)
def bytesToMatrix(input):
return [list(input[i:i+4]) for i in range(0, len(input), 4)]
def matrixToBytes(matrix):
return bytes(sum(matrix, []))
def xor(a, b):
return bytes(a[i] ^ b[i] for i in range(len(a)))
def expandKey(key, numberOfRounds):
keyColumns = bytesToMatrix(key)
iteration_size = len(key) // 4
i = 1
while len(keyColumns) < ((numberOfRounds + 1) * 4):
word = list(keyColumns[-1])
if len(keyColumns) % iteration_size == 0:
word = word[1:] + [word[0]]
word = [S_BOX[b] for b in word]
word[0] ^= R_CON[i]
i += 1
elif len(key) == 32 and len(keyColumns) % iteration_size == 4:
word = [S_BOX[b] for b in word]
word = xor(word, keyColumns[-iteration_size])
keyColumns.append(word)
return [keyColumns[4*i: 4*(i+1)] for i in range(len(keyColumns) // 4)]
def getInitalInfo(param):
key = bytearray.fromhex(param[0])
numberOfRounds = KEYSIZE_ROUNDS_MAP[len(key)]
keyMatrices = expandKey(key, numberOfRounds)
return numberOfRounds, keyMatrices
def prepareInput(input):
return bytesToMatrix(bytearray.fromhex(input[0].strip()))
def prepareOutput(output):
return [matrixToBytes(output).hex().upper()]
def AESEncrypt(input, param):
numberOfRounds, keyMatrices = getInitalInfo(param)
output = prepareInput(input)
addRoundKey(output, keyMatrices[0])
for i in range(1, numberOfRounds):
substitute(output)
shiftRows(output)
mixColumns(output)
addRoundKey(output, keyMatrices[i])
substitute(output)
shiftRows(output)
addRoundKey(output, keyMatrices[-1])
return prepareOutput(output)
def AESDecrypt(input, param):
numberOfRounds, keyMatrices = getInitalInfo(param)
output = prepareInput(input)
addRoundKey(output, keyMatrices[-1])
shiftRowsInvert(output)
substituteInverse(output)
for i in range(numberOfRounds - 1, 0, -1):
addRoundKey(output, keyMatrices[i])
mixColumnsInverse(output)
shiftRowsInvert(output)
substituteInverse(output)
addRoundKey(output, keyMatrices[0])
return prepareOutput(output)
|
# -*- coding: utf-8 -*-
"""
Top-level package for Los Angeles
CDP instance backend.
"""
__author__ = "Matt Webster"
__version__ = "1.0.0"
def get_module_version() -> str:
return __version__
|
### Sherlock and The Beast - Solution
def findDecentNumber(n):
temp = n
while temp > 0:
if temp%3 == 0:
break
else:
temp -= 5
if temp < 0:
return -1
final_str = ""
rep_count = temp // 3
while rep_count:
final_str += "555"
rep_count -= 1
rep_count = (n-temp) // 5
while rep_count:
final_str += "33333"
rep_count -= 1
return final_str
def main():
t = int(input())
while t:
n = int(input())
result = findDecentNumber(n)
print(result)
t -= 1
main()
|
#!/bin/env python3
class Car:
''' A car description '''
NUMBER_OF_WHEELS = 4 # Class variable.
def __init__(self, name):
self.name = name
self.distance = 0
def drive(self, distance):
''' incrises distance '''
self.distance += distance
def reverse(distance):
''' Class method '''
print("distance %d" % distance)
mycar = Car("Fiat 126p")
print(mycar.__dict__)
mycar.drive(5)
print(mycar.__dict__)
Car.reverse(7)
|
# LeetCode 953. Verifying an Alien Dictionary `E`
# 1sk | 97% | 22'
# A~0v21
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
dic = {c: i for i, c in enumerate(order)}
def cmp(s1, s2):
for i in range(min(len(s1), len(s2))):
if s1[i] != s2[i]:
return dic[s1[i]] <= dic[s2[i]]
return len(s1) <= len(s2)
return all(cmp(words[i], words[i+1]) for i in range(len(words)-1))
|
def beautifulTriplets(d, arr):
t = 0
for i in range(len(arr)):
if arr[i] + d in arr and arr[i] + 2*d in arr:
t += 1
return t
|
prime_numbers = [True for x in range(1001)]
prime_numbers[1] = False
for i in range(2, 1001):
for j in range(2*i, 1001, i):
prime_numbers[j] = False
input()
count = 0
for i in map(int, input().split()):
if prime_numbers[i] is True:
count += 1
print(count)
|
def intersection(right=[], left=[]):
return list(set(right).intersection(set(left)))
def union(right=[], left=[]):
return list(set(right).union(set(left)))
def union(right=[], left=[]):
return list(set(right).difference(set(left))) # not have in left
|
class Book:
"""The Book object contains all the information about a book"""
def __init__(self, title, author, date, genre):
"""Object constructor
:param title: title of the Book
:type title: str
:param author: author of the book
:type author: str
:param data: the date at which the book has been published
:param date: str
:param genre: the subject/type of the book
:type genre: str
"""
self.title = title
self.author = author
self.date = date
self.genre = genre
def to_json(self):
"""
to_json converts the object into a json object
:var json_dict: contains information about the book
:type json_dict: dict
:returns: a dict (json) containing of the information of the book
:rtype: dict
"""
json_dict = {
'title': self.title,
'author': self.author,
'date': self.date,
'genre': self.genre
}
return json_dict
def __eq__(self, other):
return (self.to_json() == other.to_json())
def __repr__(self):
return str(self.to_json())
def __str__(self):
return str(self.to_json())
|
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
class EvaluatedFunctions(dict):
"""
Evaluated functions.
"""
def __init__(self, evaluated_functions):
self.update(evaluated_functions)
@property
def deployment_id(self):
"""
:return: The deployment id this request belongs to.
"""
return self['deployment_id']
@property
def payload(self):
"""
:return: The evaluation payload.
"""
return self['payload']
class EvaluateClient(object):
def __init__(self, api):
self.api = api
def functions(self, deployment_id, context, payload):
"""Evaluate intrinsic functions in payload in respect to the
provided context.
:param deployment_id: The deployment's id of the node.
:param context: The processing context
(dict with optional self, source, target).
:param payload: The payload to process.
:return: The payload with its intrinsic functions references
evaluated.
:rtype: EvaluatedFunctions
"""
assert deployment_id
result = self.api.post('/evaluate/functions', data={
'deployment_id': deployment_id,
'context': context,
'payload': payload
})
return EvaluatedFunctions(result)
|
"""Workspace rules (Nixpkgs)"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load(
"@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_package",
)
def haskell_nixpkgs_package(
name,
attribute_path,
nix_file_deps = [],
repositories = {},
build_file_content = None,
build_file = None,
**kwargs):
"""Load a single haskell package.
The package is expected to be in the form of the packages generated by
`genBazelBuild.nix`
"""
repositories = dicts.add(
{"bazel_haskell_wrapper": "@io_tweag_rules_haskell//haskell:nix/default.nix"},
repositories,
)
nixpkgs_args = dict(
name = name,
attribute_path = attribute_path,
build_file_content = build_file_content,
nix_file_deps = nix_file_deps + ["@io_tweag_rules_haskell//haskell:nix/default.nix"],
repositories = repositories,
**kwargs
)
if build_file_content:
nixpkgs_args["build_file_content"] = build_file_content
elif build_file:
nixpkgs_args["build_file"] = build_file
else:
nixpkgs_args["build_file_content"] = """
package(default_visibility = ["//visibility:public"])
load("@io_tweag_rules_haskell//haskell:import.bzl", haskell_import_new = "haskell_import")
load(":BUILD.bzl", "targets")
targets()
"""
nixpkgs_package(
**nixpkgs_args
)
def _bundle_impl(repository_ctx):
build_file_content = """
package(default_visibility = ["//visibility:public"])
"""
for package in repository_ctx.attr.packages:
build_file_content += """
alias(
name = "{package}",
actual = "@{base_repo}-{package}//:pkg",
)
""".format(
package = package,
base_repo = repository_ctx.attr.base_repository,
)
repository_ctx.file("BUILD", build_file_content)
_bundle = repository_rule(
attrs = {
"packages": attr.string_list(),
"base_repository": attr.string(),
},
implementation = _bundle_impl,
)
"""
Generate an alias from `@base_repo//:package` to `@base_repo-package//:pkg` for
each one of the input package
"""
def haskell_nixpkgs_packages(name, base_attribute_path, packages, **kwargs):
"""Import a set of haskell packages from nixpkgs.
This takes as input the same arguments as
[nixpkgs_package](https://github.com/tweag/rules_nixpkgs#nixpkgs_package),
expecting the `attribute_path` to resolve to a set of haskell packages
(such as `haskellPackages` or `haskell.packages.ghc822`) preprocessed by
the `genBazelBuild` function. It also takes as input a list of packages to
import (which can be generated by the `gen_packages_list` function).
"""
for package in packages:
haskell_nixpkgs_package(
name = name + "-" + package,
attribute_path = base_attribute_path + "." + package,
**kwargs
)
_bundle(
name = name,
packages = packages,
base_repository = name,
)
def _is_nix_platform(repository_ctx):
return repository_ctx.which("nix-build") != None
def _gen_imports_impl(repository_ctx):
repository_ctx.file("BUILD", "")
extra_args_raw = ""
for foo, bar in repository_ctx.attr.extra_args.items():
extra_args_raw += foo + " = " + bar + ", "
bzl_file_content = """
load("{repo_name}", "packages")
load("@io_tweag_rules_haskell//haskell:nixpkgs.bzl", "haskell_nixpkgs_packages")
def import_packages(name):
haskell_nixpkgs_packages(
name = name,
packages = packages,
{extra_args_raw}
)
""".format(
repo_name = repository_ctx.attr.packages_list_file,
extra_args_raw = extra_args_raw,
)
# A dummy 'packages.bzl' file with a no-op 'import_packages()' on unsupported platforms
bzl_file_content_unsupported_platform = """
def import_packages(name):
return
"""
if _is_nix_platform(repository_ctx):
repository_ctx.file("packages.bzl", bzl_file_content)
else:
repository_ctx.file("packages.bzl", bzl_file_content_unsupported_platform)
_gen_imports_str = repository_rule(
implementation = _gen_imports_impl,
attrs = dict(
packages_list_file = attr.label(doc = "A list containing the list of packages to import"),
# We pass the extra arguments to `haskell_nixpkgs_packages` as strings
# since we can't forward arbitrary arguments in a rule and they will be
# converted to strings anyways.
extra_args = attr.string_dict(doc = "Extra arguments for `haskell_nixpkgs_packages`"),
),
)
"""
Generate a repository containing a file `packages.bzl` which imports the given
packages list.
"""
def _gen_imports(name, packages_list_file, extra_args):
"""
A wrapper around `_gen_imports_str` which allows passing an arbitrary set of
`extra_args` instead of a set of strings
"""
extra_args_str = {label: repr(value) for (label, value) in extra_args.items()}
_gen_imports_str(
name = name,
packages_list_file = packages_list_file,
extra_args = extra_args_str,
)
def haskell_nixpkgs_packageset(name, base_attribute_path, repositories = {}, **kwargs):
"""Import all the available haskell packages.
The arguments are the same as the arguments of ``nixpkgs_package``, except
for the ``base_attribute_path`` which should point to an `haskellPackages`
set in the nix expression
Example:
In `haskellPackages.nix`:
```nix
with import <nixpkgs> {};
let wrapPackages = callPackage <bazel_haskell_wrapper> { }; in
{ haskellPackages = wrapPackages haskell.packages.ghc822; }
```
In your `WORKSPACE`
```bazel
# Define a nix repository to fetch the packages from
load("@io_tweag_rules_nixpkgs//nixpkgs:nixpkgs.bzl",
"nixpkgs_git_repository")
nixpkgs_git_repository(
name = "nixpkgs",
revision = "9a787af6bc75a19ac9f02077ade58ddc248e674a",
)
load("@io_tweag_rules_haskell//haskell:nixpkgs.bzl",
"haskell_nixpkgs_packageset",
# Generate a list of all the available haskell packages
haskell_nixpkgs_packageset(
name = "hackage-packages",
repositories = {"@nixpkgs": "nixpkgs"},
nix_file = "//haskellPackages.nix",
base_attribute_path = "haskellPackages",
)
load("@hackage-packages//:packages.bzl", "import_packages")
import_packages(name = "hackage")
```
Then in your `BUILD` files, you can access to the whole of hackage as
`@hackage//:{your-package-name}`
"""
repositories = dicts.add(
{"bazel_haskell_wrapper": "@io_tweag_rules_haskell//haskell:nix/default.nix"},
repositories,
)
nixpkgs_package(
name = name + "-packages-list",
attribute_path = base_attribute_path + ".packageNames",
repositories = repositories,
build_file_content = """
exports_files(["all-haskell-packages.bzl"])
""",
fail_not_supported = False,
**kwargs
)
_gen_imports(
name = name,
packages_list_file = "@" + name + "-packages-list//:all-haskell-packages.bzl",
extra_args = dict(
repositories = repositories,
base_attribute_path = base_attribute_path,
**kwargs
),
)
def _ghc_nixpkgs_toolchain_impl(repository_ctx):
# These constraints might look tautological, because they always
# match the host platform if it is the same as the target
# platform. But they are important to state because Bazel
# toolchain resolution prefers other toolchains with more specific
# constraints otherwise.
target_constraints = ["@bazel_tools//platforms:x86_64"]
if repository_ctx.os.name == "linux":
target_constraints.append("@bazel_tools//platforms:linux")
elif repository_ctx.os.name == "mac os x":
target_constraints.append("@bazel_tools//platforms:osx")
exec_constraints = list(target_constraints)
exec_constraints.append("@io_tweag_rules_haskell//haskell/platforms:nixpkgs")
repository_ctx.file(
"BUILD",
executable = False,
content = """
load("@io_tweag_rules_haskell//haskell:toolchain.bzl", "haskell_toolchain")
haskell_toolchain(
name = "toolchain",
tools = "{tools}",
version = "{version}",
compiler_flags = {compiler_flags},
haddock_flags = {haddock_flags},
repl_ghci_args = {repl_ghci_args},
# On Darwin we don't need a locale archive. It's a Linux-specific
# hack in Nixpkgs.
locale_archive = "{locale_archive}",
exec_compatible_with = {exec_constraints},
target_compatible_with = {target_constraints},
)
""".format(
tools = "@io_tweag_rules_haskell_ghc-nixpkgs//:bin",
version = repository_ctx.attr.version,
compiler_flags = str(repository_ctx.attr.compiler_flags),
haddock_flags = str(repository_ctx.attr.haddock_flags),
repl_ghci_args = str(repository_ctx.attr.repl_ghci_args),
locale_archive = repository_ctx.attr.locale_archive,
exec_constraints = exec_constraints,
target_constraints = target_constraints,
),
)
_ghc_nixpkgs_toolchain = repository_rule(
_ghc_nixpkgs_toolchain_impl,
local = False,
attrs = {
# These attributes just forward to haskell_toolchain.
# They are documented there.
"version": attr.string(),
"compiler_flags": attr.string_list(),
"haddock_flags": attr.string_list(),
"repl_ghci_args": attr.string_list(),
"locale_archive": attr.string(),
},
)
def haskell_register_ghc_nixpkgs(
version,
compiler_flags = None,
haddock_flags = None,
repl_ghci_args = None,
locale_archive = None,
attribute_path = "haskellPackages.ghc",
nix_file = None,
nix_file_deps = [],
repositories = {}):
"""Register a package from Nixpkgs as a toolchain.
Toolchains can be used to compile Haskell code. To have this
toolchain selected during [toolchain
resolution][toolchain-resolution], set a host platform that
includes the `@io_tweag_rules_haskell//haskell/platforms:nixpkgs`
constraint value.
[toolchain-resolution]: https://docs.bazel.build/versions/master/toolchains.html#toolchain-resolution
Example:
```
haskell_register_ghc_nixpkgs(
locale_archive = "@glibc_locales//:locale-archive",
atttribute_path = "haskellPackages.ghc",
version = "1.2.3", # The version of GHC
)
```
Setting the host platform can be done on the command-line like
in the following:
```
--host_platform=@io_tweag_rules_haskell//haskell/platforms:linux_x86_64_nixpkgs
```
"""
haskell_nixpkgs_package(
name = "io_tweag_rules_haskell_ghc-nixpkgs",
attribute_path = attribute_path,
build_file = "//haskell:ghc.BUILD",
nix_file = nix_file,
nix_file_deps = nix_file_deps,
repositories = repositories,
)
_ghc_nixpkgs_toolchain(
name = "io_tweag_rules_haskell_ghc-nixpkgs-toolchain",
version = version,
compiler_flags = compiler_flags,
haddock_flags = haddock_flags,
repl_ghci_args = repl_ghci_args,
locale_archive = locale_archive,
)
native.register_toolchains("@io_tweag_rules_haskell_ghc-nixpkgs-toolchain//:toolchain")
|
{
"target_defaults":
{
"cflags" : ["-Wall", "-Wextra", "-Wno-unused-parameter"],
"include_dirs": ["<!(node -e \"require('..')\")", "<!(node -e \"require('nan')\")",]
},
"targets": [
{
"target_name" : "primeNumbers",
"sources" : [ "cpp/primeNumbers.cpp" ],
"target_conditions": [
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'GCC_ENABLE_CPP_RTTI': 'YES',
'OTHER_CFLAGS': [ '-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++' ],
'OTHER_CPLUSPLUSFLAGS': [ '-g', '-mmacosx-version-min=10.7', '-std=c++11', '-stdlib=libc++' ]
}
}],
['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', {
'libraries!': [ '-undefined dynamic_lookup' ],
'cflags_cc!': [ '-fno-exceptions', '-fno-rtti' ],
"cflags": [ '-std=c++11', '-fexceptions', '-frtti' ],
}]
]
}
]}
|
"""Data for Python 3 style errors.
The following fields are rendered as HTML.
- solution
- explanation
"""
DATA = {
"E101": {
"original_message": "indentation contains mixed spaces and tabs",
"title_templated": False,
"title": "Line is indented using a mixture of spaces and tabs.",
"solution": "You should indent your code using only spaces.",
"explanation": "Python expects the indentation method to be consistent line to line. Spaces are the preferred indentation method."
},
"E111": {
"original_message": "indentation is not a multiple of four",
"title_templated": False,
"title": "Line has an indentation level that is not a multiple of four.",
"solution": "Ensure that the first indentation level is 4 spaces, the second indentation level is 8 spaces and so on.",
"explanation": ""
},
"E112": {
"original_message": "expected an indented block",
"title_templated": False,
"title": "Line is not indented at the correct level.",
"solution": "Add indentation to this line until it is indented at the correct level.",
"explanation": ""
},
"E113": {
"original_message": "unexpected indentation",
"title_templated": False,
"title": "Line is indented when it shouldn't be.",
"solution": "Remove indentation from this line until it is indented at the correct level.",
"explanation": ""
},
"E114": {
"original_message": "indentation is not a multiple of four (comment)",
"title_templated": False,
"title": "Line has an indentation level that is not a multiple of four.",
"solution": "Ensure that the first indentation level is 4 spaces, the second indentation level is 8 spaces and so on.",
"explanation": ""
},
"E115": {
"original_message": "expected an indented block (comment)",
"title_templated": False,
"title": "Line is not indented at the correct level.",
"solution": "Add indentation to this line until it is indented at the correct level.",
"explanation": "Comments should be indented relative to the code block they are in."
},
"E116": {
"original_message": "unexpected indentation (comment)",
"title_templated": False,
"title": "Line is indented when it shouldn't be.",
"solution": "Remove indentation from this line until it is indented at the correct level.",
"explanation": ""
},
"E117": {
"original_message": "over-indented",
"title_templated": False,
"title": "Line has too many indentation levels.",
"solution": "Remove indentation from this line until it is indented at the correct level.",
"explanation": ""
},
# E121 ignored by default
"E121": {
"original_message": "continuation line under-indented for hanging indent",
"title_templated": False,
"title": "Line is less indented than it should be.",
"solution": "Add indentation to this line until it is indented at the correct level.",
"explanation": ""
},
"E122": {
"original_message": "continuation line missing indentation or outdented",
"title_templated": False,
"title": "Line is not indented as far as it should be or is indented too far.",
"solution": "Add or remove indentation levels until it is indented at the correct level.",
"explanation": ""
},
# E123 ignored by default
"E123": {
"original_message": "closing bracket does not match indentation of opening bracket’s line",
"title_templated": False,
"title": "Line has a closing bracket that does not match the indentation level of the line that the opening bracket started on.",
"solution": "Add or remove indentation of the closing bracket so it matches the indentation of the line that the opening bracket is on.",
"explanation": ""
},
"E124": {
"original_message": "closing bracket does not match visual indentation",
"title_templated": False,
"title": "Line has a closing bracket that does not match the indentation of the opening bracket.",
"solution": "Add or remove indentation of the closing bracket so it matches the indentation of the opening bracket.",
"explanation": ""
},
"E125": {
"original_message": "continuation line with same indent as next logical line",
"title_templated": False,
"title": "Line has a continuation that should be indented one extra level so that it can be distinguished from the next logical line.",
"solution": "Add an indentation level to the line continuation so that it is indented one more level than the next logical line.",
"explanation": "Continuation lines should not be indented at the same level as the next logical line. Instead, they should be indented to one more level so as to distinguish them from the next line."
},
# E126 ignored by default
"E126": {
"original_message": "continuation line over-indented for hanging indent",
"title_templated": False,
"title": "Line is indented more than it should be.",
"solution": "Remove indentation from this line until it is indented at the correct level.",
"explanation": ""
},
"E127": {
"original_message": "continuation line over-indented for visual indent",
"title_templated": False,
"title": "Line is indented more than it should be.",
"solution": "Remove indentation from this line until it is indented at the correct level.",
"explanation": ""
},
"E128": {
"original_message": "continuation line under-indented for visual indent",
"title_templated": False,
"title": "Line is indented less than it should be.",
"solution": "Add indentation to this line until it is indented at the correct level.",
"explanation": ""
},
"E129": {
"original_message": "visually indented line with same indent as next logical line",
"title_templated": False,
"title": "Line has the same indentation as the next logical line.",
"solution": "Add an indentation level to the visually indented line so that it is indented one more level than the next logical line.",
"explanation": "A visually indented line that has the same indentation as the next logical line is hard to read."
},
"E131": {
"original_message": "continuation line unaligned for hanging indent",
"title_templated": False,
"title": "Line is not aligned correctly for a hanging indent.",
"solution": "Add or remove indentation so that the lines are aligned with each other.",
"explanation": ""
},
# E133 ignored by default
# "E133": {
# "original_message": "closing bracket is missing indentation",
# "title_templated": False,
# "title": "",
# "solution": "",
# "explanation": "",
# },
"E201": {
"original_message": "whitespace after '{character}'",
"title_templated": True,
"title": "Line contains {article} {character_description} that has a space after it.",
"solution": "Remove any spaces that appear after the `{character}` character.",
"explanation": ""
},
"E202": {
"original_message": "whitespace before '{character}'",
"title_templated": True,
"title": "Line contains {article} {character_description} that has a space before it.",
"solution": "Remove any spaces that appear before the `{character}` character.",
"explanation": ""
},
"E203": {
"original_message": "whitespace before '{character}'",
"title_templated": True,
"title": "Line contains {article} {character_description} that has a space before it.",
"solution": "Remove any spaces that appear before the `{character}` character.",
"explanation": ""
},
"E211": {
"original_message": "whitespace before '{character}'",
"title_templated": True,
"title": "Line contains {article} {character_description} that has a space before it.",
"solution": "Remove any spaces that appear before the `{character}` character.",
"explanation": ""
},
"E221": {
"original_message": "multiple spaces before operator",
"title_templated": False,
"title": "Line has multiple spaces before an operator.",
"solution": "Remove any extra spaces that appear before the operator on this line.",
"explanation": ""
},
"E222": {
"original_message": "multiple spaces after operator",
"title_templated": False,
"title": "Line has multiple spaces after an operator.",
"solution": "Remove any extra spaces that appear after the operator on this line.",
"explanation": ""
},
"E223": {
"original_message": "tab before operator",
"title_templated": False,
"title": "Line contains a tab character before an operator.",
"solution": "Remove any tab characters that appear before the operator on this line. Operators should only have one space before them.",
"explanation": ""
},
"E224": {
"original_message": "tab after operator",
"title_templated": False,
"title": "Line contains a tab character after an operator.",
"solution": "Remove any tab characters that appear after the operator on this line. Operators should only have one space after them.",
"explanation": ""
},
"E225": {
"original_message": "missing whitespace around operator",
"title_templated": False,
"title": "Line is missing whitespace around an operator.",
"solution": "Ensure there is one space before and after all operators.",
"explanation": ""
},
# E226 ignored by default
"E226": {
"original_message": "missing whitespace around arithmetic operator",
"title_templated": False,
"title": "Line is missing whitespace around an arithmetic operator (`+`, `-`, `/` and `*`).",
"solution": "Ensure there is one space before and after all arithmetic operators (`+`, `-`, `/` and `*`).",
"explanation": ""
},
"E227": {
"original_message": "missing whitespace around bitwise or shift operator",
"title_templated": False,
"title": "Line is missing whitespace around a bitwise or shift operator (`<<`, `>>`, `&`, `|`, `^`).",
"solution": "Ensure there is one space before and after all bitwise and shift operators (`<<`, `>>`, `&`, `|`, `^`).",
"explanation": ""
},
"E228": {
"original_message": "missing whitespace around modulo operator",
"title_templated": False,
"title": "Line is missing whitespace around a modulo operator (`%`).",
"solution": "Ensure there is one space before and after the modulo operator (`%`).",
"explanation": ""
},
"E231": {
"original_message": "missing whitespace after ‘,’, ‘;’, or ‘:’",
"title_templated": False,
"title": "Line is missing whitespace around one of the following characters: `,` `;` and `:`.",
"solution": "Ensure there is one space before and after any of the following characters: `,` `;` and `:`.",
"explanation": ""
},
# E241 ignored by default
"E241": {
"original_message": "multiple spaces after ‘,’",
"title_templated": False,
"title": "Line has multiple spaces after the `,` character.",
"solution": "Ensure there is one space before and after any `,` characters.",
"explanation": ""
},
# E242 ignored by default
"E242": {
"original_message": "tab after ‘,’",
"title_templated": False,
"title": "Line contains a tab character after the `,` character.",
"solution": "Remove any tab characters and ensure there is one space before and after any `,` characters.",
"explanation": ""
},
"E251": {
"original_message": "unexpected spaces around keyword / parameter equals",
"title_templated": False,
"title": "Line contains spaces before or after the `=` in a function definition.",
"solution": "Remove any spaces that appear either before or after the `=` character in your function definition.",
"explanation": ""
},
"E261": {
"original_message": "at least two spaces before inline comment",
"title_templated": False,
"title": "Line contains an inline comment that does not have 2 spaces before it.",
"solution": "Ensure that your inline comment has 2 spaces before the `#` character.",
"explanation": ""
},
"E262": {
"original_message": "inline comment should start with ‘# ‘",
"title_templated": False,
"title": "Comments have a space between the `#` character and the comment message.",
"solution": "Ensure that your inline comment has a space between the `#` character and the comment message.",
"explanation": ""
},
"E265": {
"original_message": "block comment should start with ‘# ‘",
"title_templated": False,
"title": "Comments should start with a `#` character and have one space between the `#` character and the comment itself.",
"solution": "Ensure that your block comment has a space between the `#` character and the comment message.",
"explanation": ""
},
"E266": {
"original_message": "too many leading ‘#’ for block comment",
"title_templated": False,
"title": "Comments should only start with a single `#` character.",
"solution": "Ensure your comment only starts with one `#` character.",
"explanation": ""
},
"E271": {
"original_message": "multiple spaces after keyword",
"title_templated": False,
"title": "Line contains more than one space after a keyword.",
"solution": "Ensure there is only one space after any keywords.",
"explanation": ""
},
"E272": {
"original_message": "multiple spaces before keyword",
"title_templated": False,
"title": "Line contains more than one space before a keyword.",
"solution": "Ensure there is only one space before any keywords.",
"explanation": ""
},
"E273": {
"original_message": "tab after keyword",
"title_templated": False,
"title": "Line contains a tab character after a keyword.",
"solution": "Ensure there is only one space after any keywords.",
"explanation": ""
},
"E274": {
"original_message": "tab before keyword",
"title_templated": False,
"title": "Line contains a tab character before a keyword.",
"solution": "Ensure there is only one space before any keywords.",
"explanation": ""
},
"E275": {
"original_message": "missing whitespace after keyword",
"title_templated": False,
"title": "Line is missing a space after a keyword.",
"solution": "Ensure there is one space after any keywords.",
"explanation": ""
},
"E301": {
"original_message": "expected 1 blank line, found 0",
"title_templated": False,
"title": "Line is missing a blank line between the methods of a class.",
"solution": "Add a blank line in between your class methods.",
"explanation": ""
},
"E302": {
"original_message": "expected 2 blank lines, found 0",
"title_templated": False,
"title": "Two blank lines are expected before and after each function or class.",
"solution": "Ensure there are two blank lines before and after each function and class.",
"explanation": ""
},
"E303": {
"original_message": "too many blank lines (3)",
"title_templated": False,
"title": "Too many blank lines.",
"solution": "Ensure there are only two blank lines between functions and classes and one blank line between methods of a class.",
"explanation": ""
},
"E304": {
"original_message": "blank lines found after function decorator",
"title_templated": False,
"title": "Line contains a blank line after a function decorator.",
"solution": "Ensure that there are no blank lines between a function decorator and the function it is decorating.",
"explanation": ""
},
"E305": {
"original_message": "expected 2 blank lines after end of function or class",
"title_templated": False,
"title": "Functions and classes should have two blank lines after them.",
"solution": "Ensure that functions and classes should have two blank lines after them.",
"explanation": ""
},
"E306": {
"original_message": "expected 1 blank line before a nested definition",
"title_templated": False,
"title": "Nested definitions should have one blank line before them.",
"solution": "Ensure there is a blank line above your nested definition.",
"explanation": ""
},
"E401": {
"original_message": "multiple imports on one line",
"title_templated": False,
"title": "Line contains imports from different modules on the same line.",
"solution": "Ensure import statements from different modules occur on their own line.",
"explanation": ""
},
"E402": {
"original_message": "module level import not at top of file",
"title_templated": False,
"title": "Module imports should be at the top of the file and there should be no statements in between module level imports.",
"solution": "Ensure all import statements are at the top of the file and there are no statements in between imports.",
"explanation": ""
},
"E501": {
"original_message": "line too long (82 > 79 characters)",
"title_templated": False,
"title": "Line is longer than 79 characters.",
"solution": "You should rewrite your long line of code by breaking it down across multiple lines.",
"explanation": "By making sure your lines of code are not too complicated means it's easier to understand by other people. Also by limiting the line width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns."
},
"E502": {
"original_message": "the backslash is redundant between brackets",
"title_templated": False,
"title": "There is no need for a backslash (`\\`) between brackets.",
"solution": "Remove any backslashes between brackets.",
"explanation": ""
},
"E701": {
"original_message": "multiple statements on one line (colon)",
"title_templated": False,
"title": "Line contains multiple statements.",
"solution": "Make sure that each statement is on its own line.",
"explanation": "This improves readability."
},
"E702": {
"original_message": "multiple statements on one line (semicolon)",
"title_templated": False,
"title": "Line contains multiple statements.",
"solution": "Make sure that each statement is on its own line.",
"explanation": "This improves readability of your code."
},
"E703": {
"original_message": "statement ends with a semicolon",
"title_templated": False,
"title": "Line ends in a semicolon (`;`).",
"solution": "Remove the semicolon from the end of the line, these are not used in Python 3.",
"explanation": ""
},
# E704 ignored by default
"E704": {
"original_message": "multiple statements on one line (def)",
"title_templated": False,
"title": "Line contains multiple statements.",
"solution": "Make sure multiple statements of a function definition are on their own separate lines.",
"explanation": ""
},
"E711": {
"original_message": "comparison to None should be ‘if cond is None:’",
"title_templated": False,
"title": "Comparisons to objects such as `True`, `False`, and `None` should use `is` or `is not` instead of `==` and `!=`.",
"solution": "Replace `!=` with `is not` and `==` with `is`.",
"explanation": "This makes your code easier to read, as it's using words rather than symbols."
},
"E712": {
"original_message": "comparison to True should be ‘if cond is True:’ or ‘if cond:’",
"title_templated": False,
"title": "Comparisons to objects such as `True`, `False`, and `None` should use `is` or `is not` instead of `==` and `!=`.",
"solution": "Replace `!=` with `is not` and `==` with `is`.",
"explanation": "This makes your code easier to read, as it's using words rather than symbols."
},
"E713": {
"original_message": "test for membership should be ‘not in’",
"title_templated": False,
"title": "When testing whether or not something is in an object use the form `x not in the_object` instead of `not x in the_object`.",
"solution": "Use the form `not x in the_object` instead of `x not in the_object`.",
"explanation": "This improves readability of your code as it reads more naturally."
},
"E714": {
"original_message": "test for object identity should be ‘is not’",
"title_templated": False,
"title": "When testing for object identity use the form `x is not None` rather than `not x is None`.",
"solution": "Use the form `x is not None` rather than `not x is None`.",
"explanation": "This improves readability of your code as it reads more naturally."
},
"E721": {
"original_message": "do not compare types, use ‘isinstance()’",
"title_templated": False,
"title": "You should compare an objects type by using `isinstance()` instead of `==`. This is because `isinstance` can handle subclasses as well.",
"solution": "Use `if isinstance(dog, Animal)` instead of `if type(dog) == Animal`.",
"explanation": ""
},
"E722": {
"original_message": "do not use bare except, specify exception instead",
"title_templated": False,
"title": "Except block is calling all exceptions, instead it should catch a specific exception.",
# TODO: Add a simple multi-except example
"solution": "Add the specific exception the block is expected to catch, you may need to use multiple `except` blocks if you were catching multiple exceptions.",
"explanation": "This helps other to know exactly what the `except` is expected to catch."
},
"E731": {
"original_message": "do not assign a lambda expression, use a def",
"title_templated": False,
"title": "Line assigns a lambda expression instead of defining it as a function using `def`.",
"solution": "Define the line as a function using `def`.",
"explanation": "The primary reason for this is debugging. Lambdas show as `<lambda>` in tracebacks, where functions will display the function’s name."
},
"E741": {
"original_message": "do not use variables named `l`, `O`, or `I`",
"title_templated": False,
"title": "Line uses one of the variables named `l`, `O`, or `I`",
"solution": "Change the names of these variables to something more descriptive.",
"explanation": "Variables named `l`, `O`, or `I` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused."
},
"E742": {
"original_message": "do not define classes named `l`, `O`, or `I`",
"title_templated": False,
"title": "Line contains a class named `l`, `O`, or `I`",
"solution": "Change the names of these classes to something more descriptive.",
"explanation": "Classes named `l`, `O`, or `I` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused."
},
"E743": {
"original_message": "do not define functions named `l`, `O`, or `I`",
"title_templated": False,
"title": "Line contains a function named `l`, `O`, or `I`",
"solution": "Change the names of these functions to something more descriptive.",
"explanation": "Functions named `l`, `O`, or `I` can be very hard to read. This is because the letter `I` and the letter `l` are easily confused, and the letter `O` and the number `0` can be easily confused."
},
"E999": {
"original_message": "Syntax error",
"title_templated": False,
"title": "Program failed to compile.",
"solution": "Make sure your code is working.",
"explanation": ""
},
# TODO: Continue from this point onwards with checking text and adding templating boolean
"W191": {
"original_message": "indentation contains tabs",
"title_templated": False,
"title": "Line contains tabs when only spaces are expected.",
"solution": "Replace any tabs in your indentation with spaces.",
"explanation": "Using a consistent character for whitespace makes it much easier for editors to read your file."
},
"W291": {
"original_message": "trailing whitespace",
"title_templated": False,
"title": "Line contains whitespace after the final character.",
"solution": "Remove any extra whitespace at the end of each line.",
"explanation": ""
},
"W292": {
"original_message": "no newline at end of file",
"title_templated": False,
"title": "Files should end with a newline.",
"solution": "Add a newline to the end of your file.",
"explanation": "All text files should automatically end with a new line character, but some code editors can allow you to remove it."
},
"W293": {
"original_message": "blank line contains whitespace",
"title_templated": False,
"title": "Blank lines should not contain any tabs or spaces.",
"solution": "Remove any whitespace from blank lines.",
"explanation": ""
},
"W391": {
"original_message": "blank line at end of file",
"title_templated": False,
"title": "There are either zero, two, or more than two blank lines at the end of your file.",
"solution": "Ensure there is only one blank line at the end of your file.",
"explanation": ""
},
# W503 ignored by default
# This seems contradicitng... https://lintlyci.github.io/Flake8Rules/rules/W503.html
"W503": {
"original_message": "line break before binary operator",
"title_templated": False,
"title": "Line break is before a binary operator.",
"solution": "",
"explanation": ""
},
# W504 ignored by default
# same as above https://lintlyci.github.io/Flake8Rules/rules/W504.html
"W504": {
"original_message": "line break after binary operator",
"title_templated": False,
"title": "Line break is after a binary operator.",
"solution": "",
"explanation": ""
},
# W505 ignored by default
"W505": {
"original_message": "doc line too long (82 > 79 characters)",
"title_templated": False,
"title": "Line is longer than 79 characters.",
"solution": "You should rewrite your long line of code by breaking it down across multiple lines.",
"explanation": "By making sure your lines of code are not too complicated means it's easier to understand by other people. Also by limiting the line width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns."
},
"W601": {
"original_message": ".has_key() is deprecated, use ‘in’",
"title_templated": False,
"title": "`.has_key()` was deprecated in Python 2. It is recommended to use the `in` operator instead.",
"solution": """
Use `in` instead of `.has_key()`.
For example:
```
if 8054 in postcodes:
```
""",
"explanation": ""
},
"W602": {
"original_message": "deprecated form of raising exception",
"title_templated": False,
"title": "Using `raise ExceptionType, message` is not supported.",
"solution": "Instead of using `raise ExceptionType, 'Error message'`, passing the text as a parameter to the exception, like `raise ExceptionType('Error message')`.",
"explanation": ""
},
"W603": {
"original_message": "‘<>’ is deprecated, use ‘!=’",
"title_templated": False,
"title": "`<>` has been removed in Python 3.",
"solution": "Replace any occurences of `<>` with `!=`.",
"explanation": "The `!=` is the common programming symbols for stating not equal."
},
"W604": {
"original_message": "backticks are deprecated, use ‘repr()’",
"title_templated": False,
"title": "Backticks have been removed in Python 3.",
"solution": "Use the built-in function `repr()` instead.",
"explanation": ""
},
"W605": {
"original_message": "invalid escape sequence ‘x’",
"title_templated": False,
"title": "Backslash is used to escape a character that cannot be escaped.",
"solution": "Either don't use the backslash, or check your string is correct.",
"explanation": ""
},
"W606": {
"original_message": "`async` and `await` are reserved keywords starting with Python 3.7",
"title_templated": False,
"title": "`async` and `await` are reserved names",
"solution": "Do not name variables or functions as `async` or `await`.",
"explanation": ""
},
"D100": {
"original_message": "Missing docstring in public module",
"title_templated": False,
"title": "Module (the term for the Python file) should have a docstring.",
"solution": "Add a docstring to your module.",
"explanation": """
A docstring is a special comment at the top of your module that briefly explains the purpose of the module. It should have 3 sets of quotes to start and finish the comment.
For example:
```
\"\"\"This file calculates required dietary requirements for kiwis.
```
"""
},
"D101": {
"original_message": "Missing docstring in public class",
"title_templated": False,
"title": "Class should have a docstring.",
"solution": "Add a docstring to your class.",
"explanation": """
A docstring is a special comment at the top of your class that briefly explains the purpose of the class. It should have 3 sets of quotes to start and finish the comment.
For example:
```
class Kiwi():
\"\"\"Represents a kiwi bird from New Zealand.\"\"\"
```
"""
},
"D102": {
"original_message": "Missing docstring in public method",
"title_templated": False,
"title": "Methods should have docstrings.",
"solution": "Add a docstring to your method.",
"explanation": """
A docstring is a special comment at the top of your method that briefly explains the purpose of the method. It should have 3 sets of quotes to start and finish the comment.
For example:
```
class Kiwi():
\"\"\"Represents a kiwi bird from New Zealand.\"\"\"
def eat_plants(amount):
\"\"\"Calculates calories from the given amount of plant food and eats it.\"\"\"
```
"""
},
"D103": {
"original_message": "Missing docstring in public function",
"title_templated": False,
"title": "This function should have a docstring.",
"solution": "Add a docstring to your function.",
"explanation": """
A docstring is a special comment at the top of your module that briefly explains the purpose of the function. It should have 3 sets of quotes to start and finish the comment.
For example:
```
def get_waypoint_latlng(number):
\"\"\"Return the latitude and longitude values of the waypoint.\"\"\"
```
"""
},
"D104": {
"original_message": "Missing docstring in public package",
"title_templated": False,
"title": "Packages should have docstrings.",
"solution": "Add a docstring to your package.",
"explanation": ""
},
"D105": {
"original_message": "Missing docstring in magic method",
"title_templated": False,
"title": "Magic methods should have docstrings.",
"solution": "Add a docstring to your magic method.",
"explanation": ""
},
"D106": {
"original_message": "Missing docstring in public nested class",
"title_templated": False,
"title": "Public nested classes should have docstrings.",
"solution": "Add a docstring to your public nested class.",
"explanation": ""
},
"D107": {
"original_message": "Missing docstring in __init__",
"title_templated": False,
"title": "The `__init__` method should have a docstring.",
"solution": "Add a docstring to your `__init__` method.",
"explanation": "This helps understand how objects of your class are created."
},
"D200": {
"original_message": "One-line docstring should fit on one line with quotes",
"title_templated": False,
"title": "Docstrings that are one line long should fit on one line with quotes.",
"solution": "Put your docstring on one line with quotes.",
"explanation": ""
},
"D201": {
"original_message": "No blank lines allowed before function docstring",
"title_templated": False,
"title": "Function docstrings should not have blank lines before them.",
"solution": "Remove any blank lines before your function docstring.",
"explanation": ""
},
"D202": {
"original_message": "No blank lines allowed after function docstring",
"title_templated": False,
"title": "Function docstrings should not have blank lines after them.",
"solution": "Remove any blank lines after your function docstring.",
"explanation": ""
},
"D203": {
"original_message": "1 blank line required before class docstring",
"title_templated": False,
"title": "Class docstrings should have 1 blank line before them.",
"solution": "Insert 1 blank line before your class docstring.",
"explanation": ""
},
"D204": {
"original_message": "1 blank line required after class docstring",
"title_templated": False,
"title": "Class docstrings should have 1 blank line after them.",
"solution": "Insert 1 blank line after your class docstring.",
"explanation": "This improves the readability of your code."
},
"D205": {
"original_message": "1 blank line required between summary line and description",
"title_templated": False,
"title": "There should be 1 blank line between the summary line and the description.",
"solution": "Insert 1 blank line between the summary line and the description.",
"explanation": """
This makes larger docstrings easier to read.
For example:
```
def get_stock_level(book):
\"\"\"Return the stock level for the given book.
This calculates the stock level across multiple stores in the city,
excluding books reserved for customers.
Args:
book (str): Name of the book.
Returns:
String of publication date in the format of 'DD/MM/YYYY'.
\"\"\"
```
"""
},
"D206": {
"original_message": "Docstring should be indented with spaces, not tabs",
"title_templated": False,
"title": "Docstrings should be indented using spaces, not tabs.",
"solution": "Make sure your docstrings are indented using spaces instead of tabs.",
"explanation": ""
},
"D207": {
"original_message": "Docstring is under-indented",
"title_templated": False,
"title": "Docstring is under-indented.",
"solution": "Add indentation levels to your docstring until it is at the correct indentation level.",
"explanation": ""
},
"D208": {
"original_message": "Docstring is over-indented",
"title_templated": False,
"title": "Docstring is over-indented.",
"solution": "Remove indentation levels from your docstring until it is at the correct indentation level.",
"explanation": ""
},
"D209": {
"original_message": "Multi-line docstring closing quotes should be on a separate line",
"title_templated": False,
"title": "Docstrings that are longer than one line should have closing quotes on a separate line.",
"solution": "Put the closing quotes of your docstring on a separate line.",
"explanation": """
This makes larger docstrings easier to read.
For example:
```
def get_stock_level(book):
\"\"\"Return the stock level for the given book.
This calculates the stock level across multiple stores in the city,
excluding books reserved for customers.
Args:
book (str): Name of the book.
Returns:
String of publication date in the format of 'DD/MM/YYYY'.
\"\"\"
```
"""
},
"D210": {
"original_message": "No whitespaces allowed surrounding docstring text",
"title_templated": False,
"title": "Text in docstrings should not be surrounded by whitespace.",
"solution": "Remove any whitespace from the start and end of your docstring.",
"explanation": ""
},
"D211": {
"original_message": "No blank lines allowed before class docstring",
"title_templated": False,
"title": "Class docstrings should not have blank lines before them.",
"solution": "Remove any blank lines before your class docstring.",
"explanation": ""
},
"D212": {
"original_message": "Multi-line docstring summary should start at the first line",
"title_templated": False,
"title": "Docstrings that are more than one line long should start at the first line.",
"solution": """
Ensure your docstring starts on the first line with quotes.
For example:
```
def get_stock_level(book):
\"\"\"Return the stock level for the given book.
```
""",
"explanation": ""
},
"D213": {
"original_message": "Multi-line docstring summary should start at the second line",
"title_templated": False,
"title": "Docstrings that are more than one line long should start at the second line.",
"solution": "Ensure your docstring starts on the second line, which is the first line without quotes.",
"explanation": ""
},
"D214": {
"original_message": "Section is over-indented",
"title_templated": False,
"title": "Section is indented by too many levels.",
"solution": "Remove indentation levels from this section until it is at the correct indentation level.",
"explanation": ""
},
"D215": {
"original_message": "Section underline is over-indented",
"title_templated": False,
"title": "Section underline is indented by too many levels.",
"solution": "Remove indentation levels from this section underline until it is at the correct indentation level.",
"explanation": ""
},
"D300": {
"original_message": "Use \"\"\"triple double quotes\"\"\"",
"title_templated": False,
"title": "Use \"\"\"triple double quotes\"\"\" around docstrings.",
"solution": "Use \"\"\" triple double quotes around your docstring.",
"explanation": ""
},
"D301": {
"original_message": "Use r\"\"\" if any backslashes in a docstring",
"title_templated": False,
"title": "Use r\"\"\" if there are any backslashes in a docstring.",
"solution": "Use r\"\"\" at the beginning of your docstring if it contains any backslashes.",
"explanation": ""
},
"D302": {
"original_message": "Use u\"\"\" for Unicode docstrings",
"title_templated": False,
"title": "Use u\"\"\" for docstrings that contain Unicode.",
"solution": "Use u\"\"\" at the beginning of your docstring if it contains any Unicode.",
"explanation": ""
},
"D400": {
"original_message": "First line should end with a period",
"title_templated": False,
"title": "The first line in docstrings should end with a period.",
"solution": "Add a period to the end of the first line in your docstring. It should be a short summary of your code, if it's too long you may need to break it apart into multiple sentences.",
"explanation": ""
},
"D401": {
"original_message": "First line should be in imperative mood",
"title_templated": False,
"title": "The first line in docstrings should read like a command.",
"solution": "Ensure the first line in your docstring reads like a command, not a description. For example 'Do this' instead of 'Does this', 'Return this' instead of 'Returns this'.",
"explanation": ""
},
"D402": {
"original_message": "First line should not be the function’s signature",
"title_templated": False,
"title": "The first line in docstrings should not be a copy of the function’s definition.",
"solution": "Rewrite the docstring to describe the purpose of the function.",
"explanation": ""
},
"D403": {
"original_message": "First word of the first line should be properly capitalized",
"title_templated": False,
"title": "The first word in the first line should be capitalised.",
"solution": "Capitalise the first word.",
"explanation": ""
},
"D404": {
"original_message": "First word of the docstring should not be 'This'",
"title_templated": False,
"title": "First word of the docstring should not be 'This'.",
"solution": "Rephrase the docstring so that the first word is not 'This'.",
"explanation": ""
},
"D405": {
"original_message": "Section name should be properly capitalized",
"title_templated": False,
"title": "Section name should be properly capitalised.",
"solution": "Capitalise the section name.",
"explanation": ""
},
"D406": {
"original_message": "Section name should end with a newline",
"title_templated": False,
"title": "Section names should end with a newline.",
"solution": "Add a newline after the section name.",
"explanation": ""
},
"D407": {
"original_message": "Missing dashed underline after section",
"title_templated": False,
"title": "Section names should have a dashed line underneath them.",
"solution": "Add a dashed line underneath the section name.",
"explanation": ""
},
"D408": {
"original_message": "Section underline should be in the line following the section’s name",
"title_templated": False,
"title": "Dashed line should be on the line following the section's name.",
"solution": "Put the dashed underline on the line immediately following the section name.",
"explanation": ""
},
"D409": {
"original_message": "Section underline should match the length of its name",
"title_templated": False,
"title": "Dashed section underline should match the length of the section's name.",
"solution": "Add or remove dashes from the dashed underline until it matches the length of the section name.",
"explanation": ""
},
"D410": {
"original_message": "Missing blank line after section",
"title_templated": False,
"title": "Section should have a blank line after it.",
"solution": "Add a blank line after the section.",
"explanation": ""
},
"D411": {
"original_message": "Missing blank line before section",
"title_templated": False,
"title": "Section should have a blank line before it.",
"solution": "Add a blank line before the section.",
"explanation": ""
},
"D412": {
"original_message": "No blank lines allowed between a section header and its content",
"title_templated": False,
"title": "There should be no blank lines between a section header and its content.",
"solution": "Remove any blank lines that are between the section header and its content.",
"explanation": ""
},
"D413": {
"original_message": "Missing blank line after last section",
"title_templated": False,
"title": "The last section in a docstring should have a blank line after it.",
"solution": "Add a blank line after the last section in your docstring.",
"explanation": ""
},
"D414": {
"original_message": "Section has no content",
"title_templated": False,
"title": "Sections in docstrings must have content.",
"solution": "Add content to the section in your docstring.",
"explanation": ""
},
"D415": {
"original_message": "First line should end with a period, question mark, or exclamation point",
"title_templated": False,
"title": "The first line in your docstring should end with a period, question mark, or exclamation point.",
"solution": "Add a period, question mark, or exclamation point to the end of the first line in your docstring.",
"explanation": ""
},
"D416": {
"original_message": "Section name should end with a colon",
"title_templated": False,
"title": "Section names should end with a colon.",
"solution": "Add a colon to the end of your section name.",
"explanation": ""
},
"D417": {
"original_message": "Missing argument descriptions in the docstring",
"title_templated": False,
"title": "Docstrings should include argument descriptions.",
"solution": "Add argument descriptions to your docstring.",
"explanation": ""
},
"N801": {
"original_message": "class names should use CapWords convention",
"title_templated": False,
"title": "Class names should use the CapWords convention.",
"solution": "Edit your class names to follow the CapWords convention, where each word is capitalised with no spaces.",
"explanation": ""
},
"N802": {
"original_message": "function name should be lowercase",
"title_templated": False,
"title": "Function names should be lowercase.",
"solution": "Edit your function names to be lowercase, with underscores for spaces.",
"explanation": ""
},
"N803": {
"original_message": "argument name should be lowercase",
"title_templated": False,
"title": "Argument names should be lowercase.",
"solution": "Edit your function names to be lowercase, with underscores for spaces.",
"explanation": ""
},
"N804": {
"original_message": "first argument of a classmethod should be named `cls`",
"title_templated": False,
"title": "The first argument of a classmethod should be named `cls`.",
"solution": "Edit the first argument in your classmethod to be named `cls`.",
"explanation": "This is the common term that Python programmers use for a classmethod."
},
"N805": {
"original_message": "first argument of a method should be named `self`",
"title_templated": False,
"title": "The first argument of a method should be named `self`.",
"solution": "Edit the first argument in your method to be named `self`.",
"explanation": "This is the common term that Python programmers use for the object of a class's method."
},
"N806": {
"original_message": "variable in function should be lowercase",
"title_templated": False,
"title": "Variables in functions should be lowercase.",
"solution": "Edit the variable in your function to be lowercase.",
"explanation": ""
},
"N807": {
"original_message": "function name should not start and end with `__`",
"title_templated": False,
"title": "Function names should not start and end with `__` (double underscore).",
"solution": "Edit the function name so that it does not start and end with `__`",
"explanation": ""
},
"N811": {
"original_message": "constant imported as non constant",
"title_templated": False,
"title": "Import that should have been imported as a constant has been imported as a non constant.",
"solution": "Edit the import to be imported as a constant (use all capital letters in the 'import as...' name).",
"explanation": ""
},
"N812": {
"original_message": "lowercase imported as non lowercase",
"title_templated": False,
"title": "Import that should have been imported as lowercase has been imported as non lowercase",
"solution": "Edit the import to be imported as lowercase (use lowercase in the `import as` name).",
"explanation": ""
},
"N813": {
"original_message": "camelcase imported as lowercase",
"title_templated": False,
"title": "Import that should have been imported as camelCase has been imported as lowercase.",
"solution": "Edit the import to be imported as camelCase (use camelCase in the 'import as ...' name).",
"explanation": ""
},
"N814": {
"original_message": "camelcase imported as constant",
"title_templated": False,
"title": "Import that should have been imported as camelCase has been imported as a constant.",
"solution": "Edit the import to be imported as camelCase (use camelCase in the 'import as ...' name).",
"explanation": ""
},
"N815": {
"original_message": "mixedCase variable in class scope",
"title_templated": False,
"title": "Mixed case variable used in the class scope",
"solution": "Edit the variable name so that it doesn't use mixedCase.",
"explanation": ""
},
"N816": {
"original_message": "mixedCase variable in global scope",
"title_templated": False,
"title": "Mixed case variable used in the global scope",
"solution": "Edit the variable name so that it doesn't use mixedCase.",
"explanation": ""
},
"N817": {
"original_message": "camelcase imported as acronym",
"title_templated": False,
"title": "Import that should have been imported as camelCase has been imported as an acronym.",
"solution": "Edit the import to be imported as camelCase (use camelCase in the 'import as...' name).",
"explanation": ""
},
"Q000": {
"original_message": "Remove bad quotes",
"title_templated": False,
"title": "Use single quotes (') instead of double quotes (\").",
"solution": "Replace any double quotes with single quotes.",
"explanation": ""
},
"Q001": {
"original_message": "Remove bad quotes from multiline string",
"title_templated": False,
"title": "Use single quotes (') instead of double quotes (\") in multiline strings.",
"solution": "Replace any double quotes in your multiline string with single quotes.",
"explanation": ""
},
"Q002": {
"original_message": "Remove bad quotes from docstring",
"title_templated": False,
"title": "Use single quotes (') instead of double quotes (\") in docstrings.",
"solution": "Replace any double quotes in your docstring with single quotes.",
"explanation": ""
},
"Q003": {
"original_message": "Change outer quotes to avoid escaping inner quotes",
"title_templated": False,
"title": "Change outer quotes to avoid escaping inner quotes.",
"solution": "Make either the outer quotes single (`'`) and the inner quotes double (`\"`), or the outer quotes double and the inner quotes single.",
"explanation": ""
},
}
|
# 洗濯機
def get_E_Elc_washer_d_t(E_Elc_washer_wash_rtd, tm_washer_wash_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
E_Elc_washer_wash_rtd : float
標準コースの洗濯の定格消費電力量,Wh
tm_washer_wash_d_t : ndarray(N-dimensional array)
1年間の全時間の洗濯回数を格納したND配列, 回
d日t時の洗濯回数が年開始時から8760個連続して格納されている
Returns
----------
E_Elc_toilet_seat_heater_d_t : ndarray(N-dimensional array)
1年間の全時間の消費電力量を格納したND配列, Wh
d日t時の消費電力量が年開始時から8760個連続して格納されている
"""
E_Elc_washer_wash = get_E_Elc_washer_wash(E_Elc_washer_wash_rtd)
E_Elc_washer_d_t = E_Elc_washer_wash * tm_washer_wash_d_t
E_Elc_washer_d_t = E_Elc_washer_d_t * 10**(-3)
return E_Elc_washer_d_t
def get_E_Elc_washer_wash(E_Elc_washer_wash_rtd):
"""洗濯時の消費電力量を計算する
Parameters
----------
E_Elc_washer_wash_rtd : float
標準コースの洗濯の定格消費電力量,Wh
Returns
----------
E_Elc_washer_wash : float
1回の洗濯の消費電力量,Wh
"""
E_Elc_washer_wash = 1.3503 * E_Elc_washer_wash_rtd - 42.848
return E_Elc_washer_wash
|
line = input()
a, b = line.split()
a = int(a)
b = int(b)
if a < b:
print(a, b)
else:
print(b, a)
"""nums = [int(i) for i in input().split()]
print(f"{min(nums)} {max(nums)}")"""
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
def main():
print(add(5,10))
print(add(5))
print(add(5,6))
print(add(x=5, y=2))
# print(add(x=5, 2)) # Error we need to use the both with name if you use the first one as named argument
print(add(5,y=2))
print(1,2,3,4,5, sep=" - ")
def add(x, y=3):
total = x + y
return total
if __name__ == "__main__":
main()
|
"""Created by sgoswami on 7/3/17."""
"""Given two binary strings, return their sum (also a binary string).
For example,
a = \"11\"
b = \"1\"
Return \"100\"."""
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
if __name__ == '__main__':
solution = Solution()
print(solution.addBinary('11', '1'))
|
# 59. Spiral Matrix II
# O(n) time | O(n) space
class Solution:
def fillMatrix(self, spiralMatrix: [[int]], startIter: int, endIter: int, runningValue=1) -> None:
if startIter > endIter:
return
for index in range(startIter, endIter + 1):
spiralMatrix[startIter][index] = runningValue
runningValue += 1
for index in range(startIter + 1, endIter + 1):
spiralMatrix[index][endIter] = runningValue
runningValue += 1
for index in reversed(range(startIter, endIter)):
spiralMatrix[endIter][index] = runningValue
runningValue += 1
for index in reversed(range(startIter + 1, endIter)):
spiralMatrix[index][startIter] = runningValue
runningValue += 1
self.fillMatrix(spiralMatrix, startIter + 1, endIter - 1, runningValue)
def generateMatrix(self, n: int) -> [[int]]:
"""
Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
"""
matrix = [[None for _ in range(n)] for _ in range(n)]
self.fillMatrix(matrix, 0, n - 1)
print(matrix)
return matrix
|
"""
Space = O(1)
Time = O(n log n)
"""
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
ans = 0
intervals.sort(key=lambda a: (a[0], -a[1]))
end = 0
for i, j in intervals:
if j > end:
ans += 1
end = max(end, j)
return ans
|
AgentID = str
""" Assigned by Kentik """
TestID = str
""" Assigned by Kentik """
Threshold = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
MetricValue = float
""" latency and jitter in milliseconds, packet_loss in percent (0-100) """
|
#!/usr/bin/python3
class VectorFeeder:
def __init__(self, vectors, words, cursor=0):
self.data = vectors
self.cursor = cursor
self.words = words
print('len words', len(self.words), 'len data', len(self.data))
def get_next_batch(self, size):
batch = self.data[self.cursor:(self.cursor+size)]
word_batch = self.words[self.cursor:(self.cursor+size)]
self.cursor += size
return batch, word_batch
def has_next(self):
return self.cursor < len(self.data)
def get_cursor(self):
return self.cursor
|
expected_output = {
"instance": {
"default": {
"vrf": {
"VRF1": {
"address_family": {
"vpnv4 unicast RD 100:100": {
"default_vrf": "VRF1",
"prefixes": {
"10.229.11.11/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"inaccessible": False,
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"next_hop_via": "vrf VRF1",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"weight": "32768",
}
},
"paths": "1 available, best #1, table VRF1",
"table_version": "2",
}
},
"route_distinguisher": "100:100",
},
"vpnv6 unicast RD 100:100": {
"default_vrf": "VRF1",
"prefixes": {
"2001:11:11::11/128": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"inaccessible": False,
"localpref": 100,
"metric": 0,
"next_hop": "::",
"next_hop_via": "vrf VRF1",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"weight": "32768",
}
},
"paths": "1 available, best #1, table VRF1",
"table_version": "2",
}
},
"route_distinguisher": "100:100",
},
}
},
"default": {
"address_family": {
"ipv4 unicast": {
"prefixes": {
"10.4.1.1/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 3,
"weight": "32768",
}
},
"paths": "1 available, best #1, table default, RIB-failure(17)",
"table_version": "4",
},
"10.1.1.0/24": {
"available_path": "2",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "0.0.0.0",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 3,
"weight": "32768",
},
2: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 3,
},
},
"paths": "2 available, best #1, table default",
"table_version": "5",
},
"10.16.2.2/32": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
}
},
"paths": "1 available, best #1, table default",
"table_version": "2",
},
}
},
"ipv6 unicast": {
"prefixes": {
"2001:1:1:1::1/128": {
"available_path": "1",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "::",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 1,
"weight": "32768",
}
},
"paths": "1 available, best #1, table default",
"table_version": "4",
},
"2001:2:2:2::2/128": {
"available_path": "2",
"best_path": "1",
"index": {
1: {
"gateway": "2001:DB8:1:1::2",
"localpref": 100,
"metric": 0,
"next_hop": "2001:DB8:1:1::2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
},
2: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "::FFFF:10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
},
},
"paths": "2 available, best #1, table default",
"table_version": "2",
},
"2001:DB8:1:1::/64": {
"available_path": "3",
"best_path": "1",
"index": {
1: {
"gateway": "0.0.0.0",
"localpref": 100,
"metric": 0,
"next_hop": "::",
"origin_codes": "?",
"originator": "10.1.1.1",
"recipient_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "*>",
"transfer_pathid": "0x0",
"update_group": 1,
"weight": "32768",
},
2: {
"gateway": "2001:DB8:1:1::2",
"localpref": 100,
"metric": 0,
"next_hop": "2001:DB8:1:1::2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 1,
},
3: {
"gateway": "10.1.1.2",
"localpref": 100,
"metric": 0,
"next_hop": "::FFFF:10.1.1.2",
"origin_codes": "?",
"originator": "10.1.1.2",
"recipient_pathid": "0",
"transfer_pathid": "0",
"refresh_epoch": 1,
"route_info": "Local",
"status_codes": "* i",
"update_group": 1,
},
},
"paths": "3 available, best #1, table default",
"table_version": "5",
},
}
},
}
},
}
}
}
}
|
n=6
x=1
for i in range(1,n+1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
for i in range(n,0,-1):
for j in range(i,0,-1):
ch=chr(ord('Z')-j+1)
print(ch,end="")
x=x+1
print()
|
name1_1_0_0_0_0_0 = None
name1_1_0_0_0_0_1 = None
name1_1_0_0_0_0_2 = None
name1_1_0_0_0_0_3 = None
name1_1_0_0_0_0_4 = None
|
def soma(*args):
total = 0
for n in args:
total += n
return total
print(__name__)
print(soma())
print(soma(1))
print(soma(1, 2))
print(soma(1, 2, 5))
|
infty = 999999
def whitespace(words, i, j):
return (L-(j-i)-sum([len(word) for word in words[i:j+1]]))
def cost(words,i,j):
total_char_length = sum([len(word) for word in words[i:j+1]])
if total_char_length > L-(j-i):
return infty
if j==len(words)-1:
return 0
return whitespace(words,i,j)**3
#words = ["one","two","three","four","five","six","seven"]
#L = 10
words = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa"]
L=15
# Setting up tables
costs = [[None for i in range(len(words))] for j in range(len(words))]
optimum_costs = [[None for i in range(len(words))] for j in range(len(words))]
break_table = [[None for i in range(len(words))] for j in range(len(words))]
for i in range(len(costs)):
for j in range(len(costs[i])):
costs[i][j] = cost(words,i,j)
def get_opt_cost(words,i,j):
# If this subproblem is already solved, return result
if(optimum_costs[i][j] != None):
return optimum_costs[i][j]
# There are now two main classes of ways we could get the optimum
# 1) The best choice is that we put all the words on one line
canidate_costs = [costs[i][j]]
canidate_list = [None]
if i!=j:
for k in range(i,j):
# Calculate optimum of words before line split
left_optimum = get_opt_cost(words,i,k)
optimum_costs[i][k] = left_optimum
# Calculate optimum of words after line split
right_optimum = get_opt_cost(words,k+1,j)
optimum_costs[k+1][j] = right_optimum
total_optimum = left_optimum+right_optimum
canidate_costs.append(total_optimum)
canidate_list.append(k)
min_cost= infty
min_canidate = None
for n, cost in enumerate(canidate_costs):
if cost < min_cost:
min_cost = cost
min_canidate = canidate_list[n]
break_table[i][j] = min_canidate
return min_cost
# Calculate the line breaks
def get_line_breaks(i,j):
if break_table[i][j] != None:
opt_break = get_line_breaks(break_table[i][j]+1,j)
return [break_table[i][j]]+opt_break
else:
return []
final_cost = get_opt_cost(words,0,len(words)-1)
breaks = get_line_breaks(0,len(words)-1)
def print_final_paragraph(words,breaks):
final_str = ""
cur_break_point = 0
for n, word in enumerate(words):
final_str = final_str+word+" "
if cur_break_point < len(breaks) and n==breaks[cur_break_point]:
final_str+="\n"
cur_break_point+=1
print(final_str)
print("Final Cost: ",final_cost)
print("Break Locations: ",breaks)
print("----")
print_final_paragraph(words,breaks)
|
class MinStack:
# Update Min every pop (Accepted), O(1) push, pop, top, min
def __init__(self):
self.stack = []
self.min = None
def push(self, val: int) -> None:
if self.stack:
self.min = min(self.min, val)
self.stack.append((val, self.min))
else:
self.min = val
self.stack.append((val, self.min))
def pop(self) -> None:
val, min_ = self.stack.pop()
if self.stack:
self.min = self.stack[-1][1]
else:
self.min = None
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
def getMin(self) -> int:
return self.min
class MinStack:
# Find min in last elem (Top Voted), O(1) push, pop, top, min
def __init__(self):
self.q = []
def push(self, x: int) -> None:
curMin = self.getMin()
if curMin == None or x < curMin:
curMin = x
self.q.append((x, curMin))
def pop(self) -> None:
self.q.pop()
def top(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][0]
def getMin(self) -> int:
if len(self.q) == 0:
return None
else:
return self.q[len(self.q) - 1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 13:09:04 2020
@author: 766810
"""
tab = []
loop = 'loop'
# tab will hold all Kaprekar numbers found
# loop is just for better wording
def asc(n):
# puts the number's digits in ascending...
return int(''.join(sorted(str(n))))
def desc(n):
# ...and descending order
return int(''.join(sorted(str(n))[::-1]))
n = input("Specify a number: ")
try:
n = int(n)
except:
# assuming n = 2016 to prevent program from crashing
print("\nInvalid number specified!!!\nAssuming n = 2020.")
n = "2020"
print("\nTransforming", str(n) + ":")
while True:
# iterates, assigns the new diff
print(desc(n), "-", asc(n), "=", desc(n)-asc(n))
n = desc(n) - asc(n)
if n not in tab:
# checks if already hit that number
tab.append(n)
else:
if tab.index(n) == len(tab)-1:
# if found as the last, it is a constant...
tab = []
tab.append(n)
loop = 'constant'
else:
# ...otherwise it is a loop
tab = tab[tab.index(n):]
# strip the first, non-looping items
break
print('Kaprekar', loop, 'reached:', tab)
|
def main():
try:
with open('cat_200_300.jpg', 'rb') as fs1:
data = fs1.read()
print(type(data))
with open('cat1.jpg', 'wb') as fs2:
fs2.write(data)
except FileNotFoundError as e:
print(e)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
class Point:
def __init__(self, x, y, t, err):
"""
This class represents a gaze point
@param x:
@param y:
@param t:
@param err:
"""
self.error = err
self.timestamp = t
self.coord = []
self.coord.append(x)
self.coord.append(y)
def at(self, k):
"""
index into the coords of this Point
@param k: x if 0, y if 1
@return: coordinate
"""
return self.coord[k]
def set(self, x, y):
"""
set coords
@param x:
@param y:
"""
self.coord[0] = x
self.coord[1] = y
def get_status(self):
"""
Get error status of point
@return:
"""
return self.error
def valid(self):
"""
a gaze point is valid if it's normalized coordinates are in the range [0,1] and both eyes are present
@return:
"""
if self.error == "None" and \
self.coord[0] > 0 and self.coord[1] > 0 and \
self.coord[0] < 1 and self.coord[1] < 1:
return True
else:
return False
def get_timestamp(self):
return self.timestamp
|
"""
*AbstractProperty*
"""
__all__ = ["AbstractProperty"]
class AbstractProperty:
pass
|
# -*- coding: utf-8 -*-
"""Conventions for data, coordinate and attribute names."""
measurement_type = 'measurement'
peak_coord = 'peak'
"""Index coordinate denoting passband peaks of the FPI."""
number_of_peaks = 'npeaks'
"""Number of passband peaks included in a given image."""
setpoint_coord = 'setpoint_index'
"""Coordinate denoting the the setpoint (which voltage it denotes)"""
setpoint_data = 'setpoint'
"""Values of the setpoints."""
sinv_data = 'sinvs'
"""Inversion coefficients for radiance calculation."""
colour_coord = 'colour'
"""Colour coordinate for values indexed w.r.t. CFA colours."""
radiance_data = 'radiance'
"""DataArray containing a stack of radiance images."""
reflectance_data = 'reflectance'
"""DataArray containing a stack of reflectance images."""
cfa_data = 'dn'
"""DataArray containing a stack of raw CFA images."""
dark_corrected_cfa_data = 'dn_dark_corrected'
"""DataArray containing a stack of raw images with dark current corrected"""
rgb_data = 'rgb'
"""DataArray containing a stack of RGB images."""
dark_reference_data = 'dark'
"""DataArray containing a dark current reference."""
wavelength_data = 'wavelength'
"""Passband center wavelength values."""
fwhm_data = 'fwhm'
"""Full Width at Half Maximum values"""
camera_gain = 'gain'
"""Camera analog gain value."""
camera_exposure = 'exposure'
"""Camera exposure time in milliseconds."""
genicam_exposure = 'ExposureTime'
"""Camera exposure time in microseconds as defined by GenICam."""
cfa_pattern_data = 'bayer_pattern'
"""String denoting the pattern (e.g. RGGB) of the colour filter array."""
genicam_pattern_data = 'PixelColorFilter'
"""String denoting the pattern (e.g. BayerGB) of the colour filter array."""
image_index = 'index'
"""Index number of the image in a given stack."""
band_index = 'band'
"""Index for wavelength band data."""
image_width = 'width'
image_height = 'height'
height_coord = 'y'
width_coord = 'x'
cfa_dims = (image_index, height_coord, width_coord)
"""Convention for CFA image stacks."""
dark_ref_dims = (height_coord, width_coord)
"""Convention for dark reference image dimensions."""
radiance_dims = (band_index, height_coord, width_coord)
"""Convention for radiance image stacks."""
RGB_dims = (height_coord, width_coord, colour_coord)
"""Convention for RGB images."""
sinv_dims = (image_index, peak_coord, colour_coord)
"""Convention for inversion coefficient dimensions."""
|
while True:
a = input()
if a == '-1':
break
L = list(map(int, a.split()))[:-1]
cnt = 0
for i in L:
if i*2 in L:
cnt += 1
print(cnt)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.