blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
69
| license_type
stringclasses 2
values | repo_name
stringlengths 5
118
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
63
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 2.91k
686M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 213
values | src_encoding
stringclasses 30
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 2
10.3M
| extension
stringclasses 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ce543f9c2b46e85ee8ec87555bcd6214c88c6126
|
c487af858ec7bdf45bb0872985d832e3f4584978
|
/src/mq2rest/mq2rest.py
|
079ea002e23a6ccf07476c931671fc3422e7e3c9
|
[] |
no_license
|
MarkHallett/MySite
|
7054030b97c70bc4d3f507571102eef0e290408c
|
f2f4e8a1fb3acb234add5f5bca19e50cc0a8c68e
|
refs/heads/master
| 2021-01-20T09:55:48.475864
| 2019-05-13T18:25:19
| 2019-05-13T18:25:19
| 90,306,854
| 0
| 0
| null | 2018-02-16T14:38:42
| 2017-05-04T20:31:44
|
Python
|
UTF-8
|
Python
| false
| false
| 6,882
|
py
|
#!/usr/bin/env python2.7
# mq2rest.py
import os
import json
import random
#from tornado import websocket, web, ioloop
import datetime
from time import time
import logging
import logging.config
import pika
from requests import put, get, post, delete, request
cl = []
# Random number generator
r = lambda: random.randint(0,255)
# Boilerplate WebSocket code
class Mq2rest(object):#websocket.WebSocketHandler):
# Our function to get new data for charts
def wait_for_data(self):
logging.info('wait_for_data')
url1 = os.environ['MR_RABITMQ']
connection = pika.BlockingConnection(pika.URLParameters(url1))
channel = connection.channel()
q1 = 'GBP/USD/EUR'
channel.exchange_declare(exchange=q1, type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange=q1, queue=queue_name)
channel.basic_consume(self.callback_gbp_usd_eur, queue=queue_name, no_ack=True)
channel2 = connection.channel()
q2 = 'GBP/USD'
channel2.exchange_declare(exchange=q2, type='fanout')
result2 = channel2.queue_declare(exclusive=True)
queue_name2 = result2.method.queue
channel2.queue_bind(exchange=q2, queue=queue_name2)
channel2.basic_consume(self.callback_gbp_usd, queue=queue_name2, no_ack=True)
channel3 = connection.channel()
q3 = 'USD/EUR'
channel3.exchange_declare(exchange=q3, type='fanout')
result3 = channel3.queue_declare(exclusive=True)
queue_name3 = result3.method.queue
channel3.queue_bind(exchange=q3, queue=queue_name3)
channel3.basic_consume(self.callback_usd_eur, queue=queue_name3, no_ack=True)
channel4 = connection.channel()
q4 = 'EUR/GBP'
channel4.exchange_declare(exchange=q4, type='fanout')
result4 = channel4.queue_declare(exclusive=True)
queue_name4 = result4.method.queue
channel4.queue_bind(exchange=q4, queue=queue_name4)
channel4.basic_consume(self.callback_eur_gbp, queue=queue_name4, no_ack=True)
logger.info('Waiting for messages. GBP/USD/EUR')
#print(' [*] To exit press CTRL+C')
channel.start_consuming()
# Call this again within the next 0-25 seconds
timeout = r() / 50
#for c in cl:
#for c in cl:
ioloop.IOLaoop.instance().add_timeout(datetime.timedelta(seconds=timeout), self.wait_for_data)
def callback_gbp_usd_eur(self,ch, method, properties, body):
# send data
logging.info('callback_gbp_usd_eur (s) %s' %body)
try:
t, v = str(body).split(',')
except:
v = body
t = datetime.datetime.now()
if v in ('e','?'):
return
if isinstance(v,str):
v = v.strip("'")
try:
y = float(v)
except:
return # not ideal way to handle it
y = round(y,4)
#y = self.x.get_value('GBP/USD/EUR')
#logger.info('send y')
logging.info(('t',t))
#msg = 'write %s' %point_data
#logging.info(msg)
payload = {'name':'GBP/USD/EUR','id':4,'value':y, 'trade_time':str(t)}
#print put('http://127.0.0.1:5000/todo/api/v1.0/tasks/1', json=payload )
print ('post http://0.0.0.0:8888/api', payload )
post ('http://0.0.0.0:8888/api', payload )
def callback_gbp_usd(self,ch, method, properties, body):
logging.info('callback_gbp_usd %s' %body)
print('callback_gbp_usd %s' %body)
t, v = str(body).split(',')
if v in ('e','?'):
return
if isinstance(v,str):
v = v.strip("'")
y = float(v)
#y = float(v[0:-1])
#y = float(body)
#y = self.x.get_value('GBP/USD/EUR')
#logger.info('send y')
# odd but true, container needs this
if len(t) == 28:
t = t[2:]
payload = {'name':'GBP/USD','id':1,'value':y, 'trade_time':t}
logging.info('post...')
logging.info(payload)
#print put('http://127.0.0.1:5000/todo/api/v1.0/tasks/1', json=payload )
#print ('post http://0.0.0.0:8888/api', payload )
#post ('http://0.0.0.0:8888/api', json=payload )
url = "http://0.0.0.0:8888/api"
response = request("POST", url, params=payload)
logging.info(response.text)
def callback_usd_eur(self,ch, method, properties, body):
logging.info('callback_usd_eur %s' %body)
t, v = str(body).split(',')
#y = float(v[:-1])
if v in ('e','?'):
return
if isinstance(v,str):
v = v.strip("'")
y = float(v)
#y = float(body)
#y = self.x.get_value('GBP/USD/EUR')
#logger.info('send y')
# odd but true container needs this
if len(t) == 28:
t = t[2:]
payload = {'name':'USD/EUR','id':2,'value':y, 'trade_time':t}
#print ('post http://0.0.0.0:8888/api', payload )
url = "http://0.0.0.0:8888/api"
response = request("POST", url, params=payload)
logging.info(response.text)
#self.write_message(json.dumps(point_data))
def callback_eur_gbp(self,ch, method, properties, body):
logging.info('callback_eur_gbp %s' %body)
t, v = str(body).split(',')
#y = float(v[:-1])
if v in ('e','?'):
return
if isinstance(v,str):
v = v.strip("'")
y = float(v)
#y = float(body)
#y = self.x.get_value('GBP/USD/EUR')
#logger.info('send y')
# odd but true, container needs this
if len(t) == 28:
t = t[2:]
logging.info(t)
payload = {'name':'EUR/GBP','id':3,'value':y, 'trade_time':t}
url = "http://0.0.0.0:8888/api"
response = request("POST", url, params=payload)
logging.info(response.text)
if __name__ == "__main__":
LOG = os.environ.get('LOG','/mr/log')
INI = os.environ.get('INI','/mr/ini')
print ('LOG', LOG)
print ('INI', INI)
log_ini = os.path.join(INI,'logging_config_mq2rest.ini')
if not os.path.isfile(log_ini):
print (log_ini)
print ("ini file missing")
else:
print (log_ini)
print ("ini files exists")
logging.config.fileConfig(log_ini)
logger = logging.getLogger()#.addHandler(logging.StreamHandler())
logger.info('Start')
mq2rest = Mq2rest()
mq2rest.wait_for_data()
#try:
#except Exception, e:
# print 'ss'
# logger.exception("Fatal error in get_prices")
#application.listen(8002)
#ioloop.IOLoop.instance().start()
#logger.info('End')
|
[
"markhallett@Marks-MBP.connect"
] |
markhallett@Marks-MBP.connect
|
f4e880e252d3c8acd16a6ca5305873e12ab1f18b
|
fe29a6362e8db8681ae3b460a820cac0a682f2cf
|
/lab3/colorhouse.py
|
945468025efb3d2a8d185cf0925a7f24b108d586
|
[] |
no_license
|
ZhuofeiXieKatlin/CS-0008
|
8eb78910281f89fd60588e1792ceca237bad41ad
|
d9243cb4e5d8ac7747452456d89351d0972c06a1
|
refs/heads/master
| 2020-04-25T12:43:35.626587
| 2019-03-20T20:12:11
| 2019-03-20T20:12:11
| 157,258,637
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,557
|
py
|
from turtle import *
import turtle as t
import math
t.setup(800,800)
'''
You are to use functions and turtle graphics to draw the colored house
shown in the lab3 document. Choice of colors is up to you. Have fun.
'''
def drawoutline(t):
'''
This function draws the outline of a house using turtle t.
'''
### Draw the rectangluar face of the house
t.fillcolor('pink')
t.begin_fill()
t.forward(200) ### <---- Your code goes there
t.left(90)
t.forward(150)
t.left(90)
t.forward(400)
t.left(90)
t.forward(150)
t.left(90)
t.forward(200)
t.end_fill()
### Draw the roof
t.penup() ### <---- Your code goes there
t.goto(200,150)
t.left(120)
t.pendown()
t.fillcolor('brown')
t.begin_fill()
t.forward(150)
t.left(60)
t.forward(250)
t.left(60)
t.forward(150)
t.end_fill()
def drawwindow(x, y, side,t,color):
'''
Draws a square window of length side with upper-left corner at
the point (x, y) using turtle t.
'''
t.penup() ### these lines move the turtle to the
t.goto(x, y) ### point (x, y) and orient the turtle
t.setheading(0)
t.fillcolor('white') ## to face East
t.pendown()
t.begin_fill()
### Enter code to draw the sides of a window using a for-loop
for count in range(4):
t.forward(side)
t.right(90)
t.end_fill()
def drawdoor(x,y,side,t,color):
t.penup() ### these lines move the turtle to the
t.goto(x, y) ### point (x, y) and orient the turtle
t.setheading(0)
t.fillcolor('grey') ## to face East
t.pendown()
t.begin_fill()
for count in range(4):
t.forward(side)
t.right(90)
t.end_fill()
def drawchimney(x,y,side,t,color):
t.penup()
t.goto(x,y)
t.setheading(0)
t.pendown()
t.fillcolor('darkgrey')
t.begin_fill()
for count in range(4):
t.forward(side)
t.right(90)
t.end_fill()
def drawdoorknob(x, y, radius, t,color):
'''
Draws a circular doorknob of radius r using turtle t.
'''
t.penup() ### these lines move the turtle to the
t.goto(x, y - radius) ### point (x, y) and orient the turtle
t.setheading(0) ### to face East
t.pendown()
t.fillcolor('black')
t.begin_fill()
t.circle(radius)
t.end_fill()
### Enter code to draw a circle for the doorknob
def drawmoon(x,y,radius,t,color):
t.penup()
t.goto(x,y-radius)
t.setheading(0)
t.pendown()
t.fillcolor('darkgrey') ### <---- Your code goes there
t.begin_fill()
t.circle(radius)
t.end_fill()
def drawcrater(x,y,radius,t,color):
t.penup()
t.goto(x,y-radius)
t.setheading(0)
t.pendown()
t.fillcolor('white') ### <---- Your code goes there
t.begin_fill()
t.circle(radius)
t.end_fill()
def drawwalk(t):
'''
This function draws the walkway with turtle t.
'''
### Draw three lines to produce the walk.
t.penup()
t.goto(-55,0)
t.pendown()
t.goto(-95,-250)
t.goto(95,-250)
t.goto(55,0)
def drawhouse(t):
'''
Draws a detailed house and moon using turtle t.
'''
drawoutline(t) ### draw the house's outline
drawwindow(110, 130, 50,t,color) ### draw right window - each of these is a call to drawwindow()
drawwindow(-160,130,50,t,color) ### draw left window
drawdoor(-50,105,100,t,color) ### draw door
drawchimney(70,320,40,t,color) ### draw chimney
drawdoorknob(40,55,5,t,color) ### draw the doorknob - each of these is a call to drawdoorknob()
drawmoon(-300,350,70,t,color) ### draw the moon
drawcrater(-270,320,10,t,color) ### draw crater 1
drawcrater(-290,300,5,t,color) ### draw crater 2
drawcrater(-310,330,7,t,color) ### draw crater 3
drawcrater(-350,320,8,t,color) ### draw crater 4
drawwalk(t)### draw the walkway
### main() starter code
wn = Screen()
alex = Turtle()
drawhouse(alex) ### draw it
alex.penup()
alex.goto(-300, -300) ### move turtle off to the side
t.done()
input()
|
[
"zhx34@pitt.edu"
] |
zhx34@pitt.edu
|
551a89bdfa5370cf71f92c90d382adbedcaedfdd
|
da1b0ea9baf236774d3956a0db981388bf2ef19d
|
/python/python_core_advanced/multi-threading/using_subclass.py
|
be240f2744c7e89305fc88fa841c9dcddacce4b8
|
[] |
no_license
|
am3lla/projects
|
5418fe782033f14990ee608628525bea060c810b
|
b02ee17055dd9bfea472d44092bb357e618cd047
|
refs/heads/master
| 2022-07-27T14:21:19.167610
| 2020-05-12T11:53:29
| 2020-05-12T11:53:29
| 114,195,303
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 308
|
py
|
#!/usr/bin/env python3
from threading import current_thread, Thread
class MyThread(Thread):
def run(self):
i = 0
print(current_thread().getName())
while i < 11:
print (f"{i}", end = ' ')
i += 1
print(current_thread().getName())
t = MyThread()
t.start()
|
[
"andres.mella.romero@gmail.com"
] |
andres.mella.romero@gmail.com
|
9daf85e11405dcc90c806f627978128430164a80
|
4db44e7eafa618672a3b6d4751c5c7d0715b429d
|
/realizeazaSintezaTexturii.py
|
9a09a00bc65ed8c6f39e61ccea5660da414aca01
|
[] |
no_license
|
Asuciu1986/Texture-Synthesis-and-Transfer
|
74d914f84ece29c736cfbba13e57da702c6e2180
|
304255d3bfedf7f7ea176b4af09f4ccf4e03e9c8
|
refs/heads/master
| 2020-05-23T15:19:21.750045
| 2018-12-25T13:40:35
| 2018-12-25T13:40:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 10,432
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 24 21:17:56 2018
@author: gabriel
"""
import numpy as np
import math
from itertools import product
from functiiUtile import (genereazaBlocuri, calculeazaDistantaSuprapunere,
gasesteDrumMinim, floodFillIterativ)
def realizeazaSintezaTexturii(parametri):
dimBloc = parametri.dimensiuneBloc
nrBlocuri = parametri.nrBlocuri
HT = parametri.dimensiuneTexturaSintetizata[0]
WT = parametri.dimensiuneTexturaSintetizata[1]
eroareTolerata = parametri.eroareTolerata + 1
dimSuprapunere = math.floor(parametri.portiuneSuprapunere * dimBloc)
blocuri = genereazaBlocuri(parametri.textura, nrBlocuri, dimBloc)
# aflam numarul de blocuri pentru imaginea mare
nrBlocuriY = math.ceil(HT / dimBloc)
nrBlocuriX = math.ceil(WT / dimBloc)
if parametri.metodaSinteza == 'blocuriAleatoare':
# completeaza imaginea de obtinut cu blocuri aleatoare
texturaSintetizata = np.empty((HT, WT, 3), np.uint8)
texturaSintetizataMaiMare = np.empty(
(nrBlocuriY * dimBloc, nrBlocuriX * dimBloc, 3),
np.uint8)
for y, x in product(range(nrBlocuriY), range(nrBlocuriX)):
# se alege un bloc aleator
indice = np.random.randint(nrBlocuri)
# adaugam acel bloc in imagine
texturaSintetizataMaiMare[
y * dimBloc : (y+1) * dimBloc,
x * dimBloc : (x+1) * dimBloc,
:] = blocuri[:, :, :, indice]
# cropam imaginea mare la dimensiunea dorita
texturaSintetizata = texturaSintetizataMaiMare[:HT, :WT, :]
else:
# completeaza imaginea de obtinut cu blocuri ales
# in functie de eroare de suprapunere
# calculam dimensiunile imaginii tinand cont de suprapunere
dimY = nrBlocuriY * (dimBloc - dimSuprapunere) + dimSuprapunere
dimX = nrBlocuriX * (dimBloc - dimSuprapunere) + dimSuprapunere
texturaSintetizata = np.zeros((dimY, dimX, 3), np.uint8)
for y, x in product(range(nrBlocuriY), range(nrBlocuriX)):
# calculam indicii plasarii blocului suprapus
startY = y * (dimBloc - dimSuprapunere)
startX = x * (dimBloc - dimSuprapunere)
endY = startY + dimBloc
endX = startX + dimBloc
if y == 0 and x == 0:
# daca e primul bloc, il alegem aleator
indice = np.random.randint(nrBlocuri)
texturaSintetizata[
startY : endY,
startX : endX,
:] = blocuri[:, :, :, indice]
continue
if y:
# calculam suprapunerea orizontala
suprapunereImagineY = texturaSintetizata[
startY : startY + dimSuprapunere,
startX : endX,
:]
# aflam distanta pentru portiunea suprapusa orizontal dintre
# imaginea sintetizata pana acum si toate celelalte blocuri
distanteY = calculeazaDistantaSuprapunere(
blocuri, suprapunereImagineY, dimSuprapunere, 'Y')
if x:
# calculam suprapunerea verticala
suprapunereImagineX = texturaSintetizata[
startY : endY,
startX : startX + dimSuprapunere,
:]
# aflam distanta pentru portiunea suprapusa vertical dintre
# imaginea sintetizata pana acum si toate celelalte blocuri
distanteX = calculeazaDistantaSuprapunere(
blocuri, suprapunereImagineX, dimSuprapunere, 'X')
if y and x:
# calculam suprapunerea comuna
suprapunereImagineXY = texturaSintetizata[
startY : startY + dimSuprapunere,
startX : startX + dimSuprapunere,
:]
# aflam distanta pentru portiunea suprapusa diagonal dintre
# imaginea sintetizata pana acum si toate celelalte blocuri
distanteXY = calculeazaDistantaSuprapunere(
blocuri, suprapunereImagineXY, dimSuprapunere, 'XY')
# distanta totala de suprapunere pentru fiecare bloc
distante = np.zeros((nrBlocuri,))
if y:
# adaugam suprapunerea orizontala
distante += distanteY
if x:
# adaugam suprapunerea verticala
distante += distanteX
if y and x:
# scadem suprapunerea comuna, ca sa nu fie calculata de 2 ori
distante -= distanteXY
# aflam distanta minima dintre toate distantele
bestMatch = distante.min()
# aflam o multime de indici cu o distanta aproapiata de cea minima
# cu scopul de a varia blocurile folosite
indici = np.flatnonzero(distante <= eroareTolerata * bestMatch)
# alegem aleator un indice din acea multime
indice = np.random.choice(indici)
if parametri.metodaSinteza == 'eroareSuprapunere':
# suprapunem blocurile in totalitate
texturaSintetizata[
startY : endY,
startX : endX,
:] = blocuri[:, :, :, indice]
elif parametri.metodaSinteza == 'frontieraMinima':
# suprapunem blocurile la o frontiera de cost minim
mascaSuprapunere = np.zeros((dimBloc, dimBloc), np.uint8)
if y:
# partea orizontala de suprapus a imaginii
oldY = texturaSintetizata[
startY : startY + dimSuprapunere,
startX : endX,
:]
# partea verticala a blocului care urmeaza sa suprapuna
newY = blocuri[:dimSuprapunere, :, :, indice]
# matricea de cost al fiecarei suprapuneri
EY = np.power((oldY - newY), 2)
EY = EY[:, :, 0] + EY[:, :, 1] + EY[:, :, 2]
# frontiera de cost minim
drumMinimY = gasesteDrumMinim(EY)
for i in range(dimBloc):
mascaSuprapunere[drumMinimY[i], i] += 1
if x:
# partea orizontala de suprapus a imaginii
oldX = texturaSintetizata[
startY : endY,
startX : startX + dimSuprapunere,
:]
# partea verticala a blocului care urmeaza sa suprapuna
newX = blocuri[:, :dimSuprapunere, :, indice]
# matricea de cost al fiecarei suprapuneri
EX = np.power((oldX - newX), 2)
EX = EX[:, :, 0] + EX[:, :, 1] + EX[:, :, 2]
# frontiera de cost minim
drumMinimX = gasesteDrumMinim(EX)
for i in range(dimBloc):
mascaSuprapunere[i, drumMinimX[i]] += 1
if x and y:
# adaugam 2 si in zona in care drumurile se
# intersecteaza pe diagonala
for i, j in product(
range(dimSuprapunere-1), range(dimSuprapunere-1)):
if (mascaSuprapunere[i][j]
and mascaSuprapunere[i+1][j]
and mascaSuprapunere[i][j+1]
and mascaSuprapunere[i+1][j+1]):
mascaSuprapunere[i][j] = 2
mascaSuprapunere[i+1][j] = 2
mascaSuprapunere[i][j+1] = 2
mascaSuprapunere[i+1][j+1] = 2
# stergem drumul y pana la intersectia cu x
for i in range(dimBloc):
j = drumMinimY[i]
if mascaSuprapunere[j, i] == 2:
indY = i
break
else:
mascaSuprapunere[j, i] = 0
# stergem drumul x pana la intersectia cu y
for i in range(dimBloc):
j = drumMinimX[i]
if mascaSuprapunere[i, j] == 2:
indX = i
break
else:
mascaSuprapunere[i, j] = 0
# inlocuim 2 urile cu 1
for i in range(indY, dimBloc):
j = drumMinimY[i]
if mascaSuprapunere[j, i] == 2:
mascaSuprapunere[j, i] = 1
for i in range(indX, dimBloc):
j = drumMinimX[i]
if mascaSuprapunere[i, j] == 2:
mascaSuprapunere[i, j] = 1
# Umple cu 1 partea care urmeaza sa fie scrisa
floodFillIterativ(mascaSuprapunere, dimBloc-1, dimBloc-1)
# partea de suprapus a imaginii sintetizate pana acum
old = texturaSintetizata[startY:endY, startX:endX, :]
# blocul care urmeaza sa suprapuna imaginea
new = blocuri[:, :, :, indice]
mascaNegata = np.logical_not(mascaSuprapunere)
# transformam mastile la dimensiunea unei imagini
mascaSuprapunere = np.repeat(
mascaSuprapunere[:, :, np.newaxis], 3, axis=2)
mascaNegata = np.repeat(
mascaNegata[:, :, np.newaxis], 3, axis=2)
# partea imaginii sintetizate care nu va fi suprapusa
old = old * mascaNegata
# partea blocului care suprapune imaginea
new = new * mascaSuprapunere
rezultat = old + new
texturaSintetizata[
startY : endY,
startX : endX,
:] = rezultat
return texturaSintetizata
|
[
"noreply@github.com"
] |
Asuciu1986.noreply@github.com
|
4c50b86c0bb3ed7ec5af1d5809396e964553638a
|
8a128b88c550ad777fe0d195790b14d30818c4b3
|
/python/axidraw_server.py
|
b61db6349ebad922929b10e404b719691b3a0965
|
[
"MIT"
] |
permissive
|
NduatiK/elm-generative
|
89671d0ad1c69a4b008f40faee153448374e9304
|
e07f94e45240539ca1c7524e136c404f3199b31c
|
refs/heads/master
| 2023-04-25T02:04:52.264266
| 2021-05-20T10:47:24
| 2021-05-20T10:47:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,965
|
py
|
#!/usr/bin/env python3
"""
A simple webapp that works with the elm-generative webpage
EXTREMELY EXPERIMENTAL
Author: Xavier Ho <xavier@jtg.design>
## To start axidraw-server on port 6743, listening from all hosts
python axidraw_server.py
## REST API usage:
* Content-Type is always `application/json`
* Success is 200 OK (or any of the 2xx family)
* Failure is 4xx or 5xx
- Failure response structure:
{
"reason": "..."
}
"""
# For as long as axidraw-standalone is in private beta, we need to copy the
# module side by side with this module, and import it here
import os
import sys
import subprocess
import json
import time
import tempfile
import traceback
from flask import Flask
from flask_restful import Resource, Api, reqparse, abort
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
class Print(Resource):
"""
Manages plotter operations.
"""
def get(self):
"""### GET /print
Inquires the current plotter version
"""
result = subprocess.run(["axicli", "--mode", "manual"], capture_output=True)
return json.dumps({"version": str(result.stderr)})
def post(self):
"""### POST /print
Sends a SVG document to the printer, and immediately starts printing.
Response body: (see GET /print)
"""
try:
parser = reqparse.RequestParser()
parser.add_argument("svg")
args = parser.parse_args()
data = args["svg"]
subprocess.run(["axicli", "--mode", "manual", "-M", "enable_xy"])
subprocess.run(["axicli", "--mode", "manual", "-M", "raise_pen"])
with tempfile.NamedTemporaryFile(dir="C:\\crap", delete=False) as fp:
fp.write(data.encode())
fp.seek(0)
print(fp.name)
time.sleep(1)
subprocess.run(["axicli", fp.name])
return self.get()
except:
abort(500, reason=traceback.format_exc())
def put(self):
"""### PUT /print
Toggle between raising or lowering the pen
Request body: (empty)
Response body: (see GET /print)
"""
subprocess.run(["axicli", "--mode", "manual", "-M", "enable_xy"])
subprocess.run(["axicli", "--mode", "toggle"])
return self.get()
def delete(self):
"""### DELETE /print
Turns the motor off.
Request body: (empty)
Response body: (see GET /print)
"""
subprocess.run(["axicli", "--mode", "manual", "-M", "enable_xy"])
subprocess.run(["axicli", "--mode", "manual", "-M", "raise_pen"])
subprocess.run(["axicli", "--mode", "manual", "-M", "disable_xy"])
return self.get()
api.add_resource(Print, "/print")
if __name__ == "__main__":
app.run(debug=True, port=6743, host="0.0.0.0")
|
[
"xavier.ho@monash.edu"
] |
xavier.ho@monash.edu
|
3ba82926b8b04c2a02d0f4ae63e753a070f95e62
|
cc9efde4edbf4739b8f2fd628e35ebc254866341
|
/Classifiers/CNN/ker_cnn_2.py
|
6d2dad2ef367fb672da23c1cb639851ed747acb4
|
[] |
no_license
|
thomaspage/MNIST
|
47b99c3896f5afe6d22eb40f52b1a93fd423ceee
|
b16760dc3c765b77b6a4e8934bd40956a92f634c
|
refs/heads/master
| 2021-08-11T20:54:05.467475
| 2017-11-14T04:31:39
| 2017-11-14T04:31:39
| 108,304,951
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,727
|
py
|
from __future__ import print_function
import csv
import keras
import struct
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.preprocessing.image import ImageDataGenerator as gen
batch_size = 64
num_classes = 82
epochs = 25
zca = False
data_aug = False
def load_files():
train_x = './train_x.csv'
train_y = './train_y.csv'
test_x = './test_x.csv'
print('Loading Training')
train_x = np.loadtxt(train_x, delimiter=",") # load from text
train_y = np.loadtxt(train_y, delimiter=",")
print('Loading Kaggle')
test_x = np.loadtxt(test_x, delimiter=",")
return train_x, train_y, test_x
def write_csv(output):
with open('predictions_cnn.csv', 'w') as csvoutput:
writer = csv.writer(csvoutput)
writer.writerow(['Id'] + ['Label'])
for i in range(len(output)):
writer.writerow([str(i + 1)] + [output[i]])
# input image dimensions
img_rows, img_cols = 64, 64
# the data, shuffled and split between train and test sets
# (x_train, y_train), (x_test, y_test) = mnist.load_data()
print('Loading Files...\n')
train_x, train_y, kaggle = load_files()
kaggle = kaggle.reshape(-1, 64, 64, 1)
x_train = train_x.reshape(-1, 64, 64, 1)
x_test = x_train[40000:]
x_train = x_train[:40000]
y_train = train_y
y_test = y_train[40000:]
y_train = y_train[:40000]
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
kaggle = kaggle.reshape(kaggle.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
kaggle = kaggle.reshape(kaggle.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
kaggle = kaggle.astype('float32')
# x_train /= 255
# x_test /= 255
kaggle /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(kaggle.shape[0], 'kaggle samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
train_preproc = gen(
rescale=1./255,
vertical_flip=data_aug,
horizontal_flip=data_aug,
zca_whitening=zca
)
valid_preproc = gen(
rescale=1./255
)
if zca:
train_preproc.fit(x_train)
train_preproc.fit(x_test)
train_generator = train_preproc.flow(x_train, y_train, batch_size=batch_size)
validation_generator = valid_preproc.flow(x_test, y_test, batch_size=batch_size)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(128, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(256, (3,3), activation='relu'))
model.add(Conv2D(256, (3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
# model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
# model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(128, activation='relu'))
model.add(Flatten())
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
model.fit_generator(train_generator,
steps_per_epoch=800,
epochs=epochs,
verbose=1,
validation_data=validation_generator,
validation_steps=625,
)
x_train /= 255
x_test /= 255
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
predictions = model.predict(kaggle, verbose=1)
# print(predictions[:100])
output = predictions.argmax(axis=1)
# print(output[:100])
print('\nWriting CSV File...\n')
write_csv(output)
|
[
"matthew.chan2@mail.mcgill.ca"
] |
matthew.chan2@mail.mcgill.ca
|
ac216aebef88aa0f448d29380e7acea53e4a96c6
|
8979ad5a2073bf8715019d54983d30dcfe3b45f5
|
/ImageFormatter.py
|
ae5d149d641c7d0986db6e4528d608c2fe87a086
|
[] |
no_license
|
jambobjambo/LUXCNN
|
014564b7c3c019d2e1ad3d92ad4ce3efec1df999
|
259721ced5946ef3277331a9cf5a89182bcef77c
|
refs/heads/master
| 2021-01-01T05:57:41.373922
| 2017-07-23T11:27:38
| 2017-07-23T11:27:38
| 97,319,071
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 935
|
py
|
from PIL import Image
from resizeimage import resizeimage
import os
ImageDirectoryIn = "../RNNImages/"
ImageDirectoryOut = "../TrainingData/Mask/"
def ReFormat(ImageDir, Name):
Filename = ImageDirectoryIn + ImageDir + '/' + Name
with open(Filename, 'r+b') as f:
with Image.open(f) as image:
cover = resizeimage.resize_contain(image, [300, 300])
if not os.path.exists(ImageDirectoryOut + ImageDir + '/'):
os.makedirs(ImageDirectoryOut + ImageDir + '/')
cover.save(ImageDirectoryOut + ImageDir + '/' + Name, image.format)
DirectoryComplete = 0
for Directory in os.listdir(ImageDirectoryIn):
print("Directory " + str(DirectoryComplete) + " out of: " + str(len(os.listdir(ImageDirectoryIn))))
DirectoryComplete += 1
if Directory != ".DS_Store":
for ImageFile in os.listdir(ImageDirectoryIn + Directory):
ReFormat(Directory, ImageFile)
|
[
"jamie.a.mcinally@gmail.com"
] |
jamie.a.mcinally@gmail.com
|
de5732d2e5a0bc8f26e9b137e0fd51ba4282fdf3
|
ffdd1a9fb403d5cbea79c3e30b19502150b7f07b
|
/algorithms/morse_code.py
|
a357576d70f471df63496e452e6e97f70998519d
|
[] |
no_license
|
yanik-ai/multy_crypter
|
ed86638d58fec0d2368f15474dcc76175b92013b
|
c6edc63a5b4fc26d95946ef79ad24804395960e3
|
refs/heads/master
| 2021-05-30T17:24:55.356946
| 2016-03-09T23:10:46
| 2016-03-09T23:10:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,961
|
py
|
# -*- coding: utf-8 -*
from __future__ import unicode_literals
class MorseCode(object):
def __init__(self):
# International Morse Code Alphabet
# http://morsecode.scphillips.com/morse2.html
self.alphabet = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.',
'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---',
'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--',
'Z': '--..', '0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....', '6': '-....',
'7': '--...', '8': '---..', '9': '----.', ',': '--..--',
' ': '/'}
self.inveresed_alphabet = dict((v, k) for (k, v) in self.alphabet.items())
# we will encode only allowed characters
self.allowed_characters = ''.join(ch for ch in self.alphabet.keys())
def encode(self, msg):
result = []
words = msg.upper().split()
for word in words:
# jar for collecting morse characters
morse_ch = []
for ch in word:
# check if we know about this character
if ch in self.allowed_characters:
morse_ch.append(self.alphabet[ch])
# skip unknown characters
if len(morse_ch) > 0:
result.append(' '.join(morse_ch))
return ' / '.join(result)
def decode(self, msg):
result = []
words = msg.split('/')
for word in words:
morse_letters = word.split()
letter = ''.join([self.inveresed_alphabet[l] for l in morse_letters])
result.append(letter)
return ' '.join(result)
|
[
"yanikkoval@devrecords.com"
] |
yanikkoval@devrecords.com
|
a3432d391d2a981b089d443addec2146a9aa8e71
|
cf07288b1d6a9d352ca35414ad44ad1b4bbb557c
|
/stepik4_4.py
|
948fdd8d3cc6a678e92b67e5f49619eb4ba81815
|
[] |
no_license
|
VetaGryff21/algorithms
|
2ba7c9b43f2ae87f87f5375051af67305604d2cb
|
c1b9ced159928c374b0712bc27f47a3ae7f74513
|
refs/heads/master
| 2020-12-07T07:34:03.721603
| 2020-01-08T23:16:25
| 2020-01-08T23:16:25
| 232,672,839
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 521
|
py
|
count = 0
list = []
with open('dataset_3363_4.txt') as file:
for string in file:
string = string.strip().split(';')
print(string)
for i in string[1::]:
count += int(i)
print(count / 3)
string.append(count / 3)
print(string)
list.append(string)
print(list)
count = 0
math = 0
phys = 0
rus = 0
for i in list:
math += int(i[1])
phys += int(i[2])
rus += int(i[3])
print(math / len(list), phys / len(list), rus / len(list))
|
[
"vetagryff21@gmail.com"
] |
vetagryff21@gmail.com
|
6dc0a0220f04043e1874f030691529d0afc76d63
|
aa1fb9dfa629fb760b99c6de56685084256389f9
|
/Mission_to_Mars_Challenge.py
|
89f467d7c1ac84927b999974e381c629dc6d7079
|
[] |
no_license
|
roxhensa02/Mission_To_Mars
|
b166cf160114d3dff22c16987c8ac54ef23538be
|
2655457412e282980ecc83c82ef59ee3bc78a3a2
|
refs/heads/main
| 2023-09-02T23:07:28.865954
| 2021-11-16T20:55:13
| 2021-11-16T20:55:13
| 428,810,327
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,109
|
py
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Import Splinter, BeautifulSoup, and Pandas
get_ipython().system('pip install webdriver_manager')
from splinter import Browser
from bs4 import BeautifulSoup as soup
import pandas as pd
from webdriver_manager.chrome import ChromeDriverManager
# In[2]:
# Set the executable path and initialize Splinter
executable_path = {'executable_path': ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=False)
# ### Visit the NASA Mars News Site
# In[3]:
# Visit the mars nasa news site
url = 'https://redplanetscience.com/'
browser.visit(url)
# Optional delay for loading the page
browser.is_element_present_by_css('div.list_text', wait_time=1)
# In[4]:
# Convert the browser html to a soup object and then quit the browser
html = browser.html
news_soup = soup(html, 'html.parser')
slide_elem = news_soup.select_one('div.list_text')
# In[5]:
slide_elem.find('div', class_='content_title')
# In[6]:
# Use the parent element to find the first a tag and save it as `news_title`
news_title = slide_elem.find('div', class_='content_title').get_text()
news_title
# In[7]:
# Use the parent element to find the paragraph text
news_p = slide_elem.find('div', class_='article_teaser_body').get_text()
news_p
# ### JPL Space Images Featured Image
# In[8]:
# Visit URL
url = 'https://spaceimages-mars.com'
browser.visit(url)
# In[9]:
# Find and click the full image button
full_image_elem = browser.find_by_tag('button')[1]
full_image_elem.click()
# In[10]:
# Parse the resulting html with soup
html = browser.html
img_soup = soup(html, 'html.parser')
img_soup
# In[11]:
# find the relative image url
img_url_rel = img_soup.find('img', class_='fancybox-image').get('src')
img_url_rel
# In[12]:
# Use the base url to create an absolute url
img_url = f'https://spaceimages-mars.com/{img_url_rel}'
img_url
# ### Mars Facts
# In[13]:
df = pd.read_html('https://galaxyfacts-mars.com')[0]
df.head()
# In[14]:
df.columns=['Description', 'Mars', 'Earth']
df.set_index('Description', inplace=True)
df
# In[15]:
df.to_html()
# # D1: Scrape High-Resolution Mars’ Hemisphere Images and Titles
# ### Hemispheres
# In[16]:
# 1. Use browser to visit the URL
url ='https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
browser.visit(url)
# In[17]:
# 2. Create a list to hold the images and titles.
hemisphere_image_urls = []
# 3. Write code to retrieve the image urls and titles for each hemisphere.
for i in range(4):
hemispheres = {}
browser.find_by_css('a.itemLink.product-item h3')[i].click()
element = browser.find_link_by_text('Sample').first
img_url = element['href']
title = browser.find_by_css("h2.title").text
hemispheres["img_url"] = img_url
hemispheres["title"] = title
hemisphere_image_urls.append(hemispheres)
browser.back()
# In[18]:
# 4. Print the list that holds the dictionary of each image url and title.
hemisphere_image_urls
# In[19]:
# 5. Quit the browser
browser.quit()
# In[ ]:
|
[
"noreply@github.com"
] |
roxhensa02.noreply@github.com
|
549d8f7ade40cfa0e6ba5544d528f1d7c8bcdccd
|
4b44a299bafbd4ca408ce1c89c9fe4a449632783
|
/python3/10_Modules/14_turtle_module/18_USA_flag.py
|
98d05fb7b9f945b3411273edc11fe92f22cc5bfa
|
[] |
no_license
|
umunusb1/PythonMaterial
|
ecd33d32b2de664eaaae5192be7c3f6d6bef1d67
|
1e0785c55ccb8f5b9df1978e1773365a29479ce0
|
refs/heads/master
| 2023-01-23T23:39:35.797800
| 2020-12-02T19:29:00
| 2020-12-02T19:29:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,672
|
py
|
#!/usr/bin/python
"""
Purpose: To create USA flag using turtle.
"""
import turtle
import time
# create a screen
screen = turtle.getscreen()
# set background color of screen
screen.bgcolor('white')
# set tile of screen
screen.title('USA Flag')
oogway = turtle.Turtle()
# set the cursor/turtle speed. Higher value, faster is the turtle
oogway.speed(100)
oogway.penup()
# decide the shape of cursor/turtle
oogway.shape('turtle')
# flag height to width ratio is 1:1.9
flag_height = 250
flag_width = 475
# starting points
# start from the first quardant, half of flag width and half of flag height
start_x = -237
start_y = 125
# For red and white stripes (total 13 stripes in flag), each strip width will be flag_height/13 = 19.2 approx
stripe_height = flag_height/13
stripe_width = flag_width
# length of one arm of star
star_size = 10
def draw_fill_rectangle(x, y, height, width, color):
oogway.goto(x,y)
oogway.pendown()
oogway.color(color)
oogway.begin_fill()
oogway.forward(width)
oogway.right(90)
oogway.forward(height)
oogway.right(90)
oogway.forward(width)
oogway.right(90)
oogway.forward(height)
oogway.right(90)
oogway.end_fill()
oogway.penup()
def draw_star(x,y,color,length) :
oogway.goto(x,y)
oogway.setheading(0)
oogway.pendown()
oogway.begin_fill()
oogway.color(color)
for turn in range(0,5) :
oogway.forward(length)
oogway.right(144)
oogway.forward(length)
oogway.right(144)
oogway.end_fill()
oogway.penup()
# this function is used to create 13 red and white stripes of flag
def draw_stripes():
x = start_x
y = start_y
# we need to draw total 13 stripes, 7 red and 6 white
# so we first create, 6 red and 6 white stripes alternatively
for stripe in range(0,6):
for color in ['red', 'white']:
draw_fill_rectangle(x, y, stripe_height, stripe_width, color)
# decrease value of y by stripe_height
y = y - stripe_height
# create last red stripe
draw_fill_rectangle(x, y, stripe_height, stripe_width, 'red')
y = y - stripe_height
# this function create navy color square
# height = 7/13 of flag_height
# width = 0.76 * flag_height
# check references section for these values
def draw_square():
square_height = (7/13) * flag_height
square_width = (0.76) * flag_height
draw_fill_rectangle(start_x, start_y, square_height, square_width, 'navy')
def draw_six_stars_rows():
gap_between_stars = 30
gap_between_lines = stripe_height + 6
y = 112
# create 5 rows of stars
for row in range(0,5) :
x = -222
# create 6 stars in each row
for star in range (0,6) :
draw_star(x, y, 'white', star_size)
x = x + gap_between_stars
y = y - gap_between_lines
def draw_five_stars_rows():
gap_between_stars = 30
gap_between_lines = stripe_height + 6
y = 100
# create 4 rows of stars
for row in range(0,4) :
x = -206
# create 5 stars in each row
for star in range (0,5) :
draw_star(x, y, 'white', star_size)
x = x + gap_between_stars
y = y - gap_between_lines
# start after 5 seconds.
time.sleep(5)
# draw 13 stripes
draw_stripes()
# draw squares to hold stars
draw_square()
# draw 30 stars, 6 * 5
draw_six_stars_rows()
# draw 20 stars, 5 * 4. total 50 stars representing 50 states of USA
draw_five_stars_rows()
# hide the cursor/turtle
oogway.hideturtle()
# keep holding the screen until closed manually
screen.mainloop()
# ref: https://www.codesters.com/preview/6fe8df0ccc45b1460ab24e5553497c5684987fb5/
|
[
"uday3prakash@gmail.com"
] |
uday3prakash@gmail.com
|
5c4046060f4537dc3aded470b9e0e04c2eddeb3b
|
3c7c8cd58ba38e222d459c202de5bc36213b8a51
|
/gunting_batu_kertas.py
|
c9b639eb41f2adb9b3cbf3ef1e9fb4846a4a6a71
|
[] |
no_license
|
Guruh15/Projek_ku
|
b130ed8d0f63e485859ca089f79c310c7cea174a
|
c58c3aa4c68bc0dce61d23fce61244ce736ac7a1
|
refs/heads/main
| 2023-08-23T11:24:27.959062
| 2021-10-13T04:02:39
| 2021-10-13T04:02:39
| 416,572,205
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,064
|
py
|
from random import randint
pilihan = ["Gunting", "Batu", "Kertas"]
komputer = pilihan[randint(0,2)]
player = False
while player == False:
#Set pemain ke True
print("Masukkan pilihan anda")
player = input("Gunting, Batu, Kertas : ")
if player == komputer:
print("Imbang")
elif player == "Batu":
if komputer == "Kertas":
print("Anda Kalah", komputer, "mengalahkan", player)
else:
print("Anda Menang!", player, "mengalahkan", komputer)
elif player == "Kertas":
if komputer == "Gunting":
print("Anda Kalah", komputer, "mengalahkan", player)
else:
print("Anda Menang", player, "mengalahkan", komputer)
elif player == "Gunting":
if komputer == "Batu":
print("Anda Kalah", komputer, "mengalahkan", player)
else:
print("Anda Menang", player, "mengalahkan", komputer)
else:
print("Pilihan yang kamu masukan salah...")
player = False
komputer = pilihan[randint(0,2)]
|
[
"noreply@github.com"
] |
Guruh15.noreply@github.com
|
b6a0047b357526884a40eaaa9456bbe0df2c1d73
|
f71ee969fa331560b6a30538d66a5de207e03364
|
/scripts/client/messenger/formatters/service_channel.py
|
1f37d8492abec598dcbad8d94a60152f7567d5d8
|
[] |
no_license
|
webiumsk/WOT-0.9.8-CT
|
31356ed01cb110e052ba568e18cb2145d4594c34
|
aa8426af68d01ee7a66c030172bd12d8ca4d7d96
|
refs/heads/master
| 2016-08-03T17:54:51.752169
| 2015-05-12T14:26:00
| 2015-05-12T14:26:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 90,507
|
py
|
# Embedded file name: scripts/client/messenger/formatters/service_channel.py
import types
from FortifiedRegionBase import FORT_ATTACK_RESULT, NOT_ACTIVATED
from adisp import async, process
from chat_shared import decompressSysMessage
from club_shared import ladderRating
import constants
from debug_utils import LOG_ERROR, LOG_WARNING, LOG_CURRENT_EXCEPTION, LOG_DEBUG
import account_helpers
import ArenaType
import BigWorld
from gui.goodies.GoodiesCache import g_goodiesCache
import potapov_quests
from gui import GUI_SETTINGS
from gui.LobbyContext import g_lobbyContext
from gui.clubs.formatters import getLeagueString, getDivisionString
from gui.clubs.settings import getLeagueByDivision
from gui.Scaleform.framework import AppRef
from gui.Scaleform.locale.MESSENGER import MESSENGER
from gui.shared.utils import BoundMethodWeakref
from gui.shared import formatters as shared_fmts
from gui.shared.fortifications import formatters as fort_fmts
from gui.shared.fortifications.FortBuilding import FortBuilding
from gui.shared.gui_items.Tankman import Tankman, calculateRoleLevel
from gui.shared.gui_items.dossier.factories import getAchievementFactory
from gui.shared.notifications import NotificationPriorityLevel, NotificationGuiSettings, MsgCustomEvents
from gui.shared.utils.transport import z_loads
from messenger.m_constants import MESSENGER_I18N_FILE
from messenger.proto.bw.wrappers import ServiceChannelMessage
import offers
from gui.prb_control.formatters import getPrebattleFullDescription
from gui.shared.utils.gui_items import formatPrice
from helpers import i18n, html, getClientLanguage, getLocalizedData
from helpers import time_utils
from items import getTypeInfoByIndex, getTypeInfoByName
from items import vehicles as vehicles_core
from account_helpers import rare_achievements
from dossiers2.custom.records import DB_ID_TO_RECORD
from dossiers2.ui.achievements import ACHIEVEMENT_BLOCK
from dossiers2.ui.layouts import IGNORED_BY_BATTLE_RESULTS
from messenger import g_settings
from predefined_hosts import g_preDefinedHosts
from constants import INVOICE_ASSET, AUTO_MAINTENANCE_TYPE, PREBATTLE_INVITE_STATE, AUTO_MAINTENANCE_RESULT, PREBATTLE_TYPE, FINISH_REASON, KICK_REASON_NAMES, KICK_REASON, NC_MESSAGE_TYPE, NC_MESSAGE_PRIORITY, SYS_MESSAGE_CLAN_EVENT, SYS_MESSAGE_CLAN_EVENT_NAMES, SYS_MESSAGE_FORT_EVENT, SYS_MESSAGE_FORT_EVENT_NAMES, FORT_BUILDING_TYPE, FORT_ORDER_TYPE, FORT_BUILDING_TYPE_NAMES, ARENA_GUI_TYPE
from messenger.formatters import TimeFormatter, NCContextItemFormatter
def _getTimeStamp(message):
import time
if message.createdAt is not None:
result = time.mktime(message.createdAt.timetuple())
else:
LOG_WARNING('Invalid value of created_at = None')
result = time.time()
return result
def _extendCustomizationData(newData, extendable):
if extendable is None:
return
else:
customizations = newData.get('customizations', [])
for customizationItem in customizations:
custType = customizationItem['custType']
custValue = customizationItem['value']
custIsPermanent = customizationItem['isPermanent']
if custValue < 0:
extendable.append(i18n.makeString('#system_messages:customization/removed/%s' % custType))
elif custIsPermanent and custValue > 1:
extendable.append(i18n.makeString('#system_messages:customization/added/%sValue' % custType, custValue))
else:
extendable.append(i18n.makeString('#system_messages:customization/added/%s' % custType))
return
class ServiceChannelFormatter(object):
def format(self, data, *args):
return (None, None)
def isNotify(self):
return True
def isAsync(self):
return False
def _getGuiSettings(self, data, key = None, priorityLevel = None):
if isinstance(data, ServiceChannelMessage):
isAlert = data.isHighImportance and data.active
else:
isAlert = False
if priorityLevel is None:
priorityLevel = g_settings.msgTemplates.priority(key)
return NotificationGuiSettings(self.isNotify(), priorityLevel, isAlert)
class ServerRebootFormatter(ServiceChannelFormatter):
def format(self, message, *args):
if message.data:
local_dt = time_utils.utcToLocalDatetime(message.data)
formatted = g_settings.msgTemplates.format('serverReboot', ctx={'date': local_dt.strftime('%c')})
return (formatted, self._getGuiSettings(message, 'serverReboot'))
else:
return (None, None)
return None
class ServerRebootCancelledFormatter(ServiceChannelFormatter):
def format(self, message, *args):
if message.data:
local_dt = time_utils.utcToLocalDatetime(message.data)
formatted = g_settings.msgTemplates.format('serverRebootCancelled', ctx={'date': local_dt.strftime('%c')})
return (formatted, self._getGuiSettings(message, 'serverRebootCancelled'))
else:
return (None, None)
return None
class BattleResultsFormatter(ServiceChannelFormatter):
__battleResultKeys = {-1: 'battleDefeatResult',
0: 'battleDrawGameResult',
1: 'battleVictoryResult'}
__goldTemplateKey = 'battleResultGold'
__questsTemplateKey = 'battleQuests'
__i18n_penalty = i18n.makeString('#%s:serviceChannelMessages/battleResults/penaltyForDamageAllies' % MESSENGER_I18N_FILE)
__i18n_contribution = i18n.makeString('#%s:serviceChannelMessages/battleResults/contributionForDamageAllies' % MESSENGER_I18N_FILE)
def isNotify(self):
return True
def format(self, message, *args):
battleResults = message.data
commonBattleResult = next(message.data.itervalues())
arenaTypeID = commonBattleResult.get('arenaTypeID', 0)
arenaType = ArenaType.g_cache[arenaTypeID] if arenaTypeID > 0 else None
arenaCreateTime = commonBattleResult.get('arenaCreateTime', None)
if arenaCreateTime and arenaType:
vehicleNames = {}
ctx = {'arenaName': i18n.makeString(arenaType.name),
'vehicleNames': 'N/A',
'xp': '0',
'credits': '0'}
battleResKey = commonBattleResult.get('isWinner', 0)
team = commonBattleResult.get('team', 0)
guiType = commonBattleResult.get('guiType', 0)
arenaUniqueID = commonBattleResult.get('arenaUniqueID', 0)
xp = 0
xpPenalty = 0
gold = 0
credits = 0
creditsToDraw = 0
creditsPenalty = 0
creditsContributionIn = 0
creditsContributionOut = 0
popUpRecords = []
marksOfMastery = []
vehicleNameParts = []
for vehIntCD, battleResult in battleResults.iteritems():
vt = vehicles_core.getVehicleType(vehIntCD)
vehicleNameParts.append(vt.userString)
vehicleNames[vehIntCD] = vt.userString
xp += battleResult.get('xp', 0)
xpPenalty += battleResult.get('xpPenalty', 0)
gold += battleResult.get('gold', 0)
credits += battleResult.get('credits', 0)
creditsToDraw += battleResult.get('creditsToDraw', 0)
creditsPenalty += battleResult.get('creditsPenalty', 0)
creditsContributionIn += battleResult.get('creditsContributionIn', 0)
creditsContributionOut += battleResult.get('creditsContributionOut', 0)
popUpRecords.extend(popUpRecords)
if 'markOfMastery' in battleResult and battleResult['markOfMastery'] > 0:
marksOfMastery.append(battleResult['markOfMastery'])
ctx['vehicleNames'] = ', '.join(vehicleNameParts)
if xp:
ctx['xp'] = BigWorld.wg_getIntegralFormat(xp)
ctx['xpEx'] = self.__makeXpExString(xp, battleResKey, xpPenalty, battleResults)
ctx['gold'] = self.__makeGoldString(gold)
accCredits = credits - creditsToDraw
if accCredits:
ctx['credits'] = BigWorld.wg_getIntegralFormat(accCredits)
ctx['creditsEx'] = self.__makeCreditsExString(accCredits, creditsPenalty, creditsContributionIn, creditsContributionOut)
ctx['fortResource'] = self.__makeFortResourceString(commonBattleResult)
ctx['achieves'] = self.__makeAchievementsString(popUpRecords, marksOfMastery)
ctx['lock'] = self.__makeVehicleLockString(vehicleNames, battleResults)
ctx['quests'] = self.__makeQuestsAchieve(message)
ctx['fortBuilding'] = ''
fortBuilding = commonBattleResult.get('fortBuilding')
if fortBuilding is not None:
buildTypeID, buildTeam = fortBuilding.get('buildTypeID'), fortBuilding.get('buildTeam')
if buildTypeID:
ctx['fortBuilding'] = g_settings.htmlTemplates.format('battleResultFortBuilding', ctx={'fortBuilding': FortBuilding(typeID=buildTypeID).userName,
'clanAbbrev': ''})
if battleResKey == 0:
battleResKey = 1 if buildTeam == team else -1
ctx['club'] = self.__makeClubString(commonBattleResult)
templateName = self.__battleResultKeys[battleResKey]
bgIconSource = None
if guiType == ARENA_GUI_TYPE.FORT_BATTLE:
bgIconSource = 'FORT_BATTLE'
formatted = g_settings.msgTemplates.format(templateName, ctx=ctx, data={'timestamp': arenaCreateTime,
'savedData': arenaUniqueID}, bgIconSource=bgIconSource)
settings = self._getGuiSettings(message, templateName)
return (formatted, settings)
else:
return (None, None)
return
def __makeFortResourceString(self, battleResult):
fortResource = battleResult.get('fortResource', None)
if fortResource is None:
return ''
else:
fortResourceStr = BigWorld.wg_getIntegralFormat(fortResource) if not battleResult['isLegionary'] else '-'
return g_settings.htmlTemplates.format('battleResultFortResource', ctx={'fortResource': fortResourceStr})
def __makeQuestsAchieve(self, message):
fmtMsg = TokenQuestsFormatter(asBattleFormatter=True)._formatQuestAchieves(message)
if fmtMsg is not None:
return g_settings.htmlTemplates.format('battleQuests', {'achieves': fmtMsg})
else:
return ''
def __makeClubString(self, battleResult):
result = []
club = battleResult.get('club')
if club:
curDiv, prevDiv = club.get('divisions', (0, 0))
curLeague, prevLeague = getLeagueByDivision(curDiv), getLeagueByDivision(prevDiv)
curRating, prevRating = map(ladderRating, club.get('ratings', ((0, 0), (0, 0))))
if curRating != prevRating:
if curRating > prevRating:
tplKey = 'battleResultClubRatingUp'
else:
tplKey = 'battleResultClubRatingDown'
result.append(g_settings.htmlTemplates.format(tplKey, ctx={'rating': abs(curRating - prevRating)}))
if curDiv != prevDiv:
result.append(g_settings.htmlTemplates.format('battleResultClubNewDivision', ctx={'division': getDivisionString(curDiv)}))
if curLeague != prevLeague:
result.append(g_settings.htmlTemplates.format('battleResultClubNewLeague', ctx={'league': getLeagueString(curLeague)}))
return ''.join(result)
def __makeVehicleLockString(self, vehicleNames, battleResults):
locks = []
for vehIntCD, battleResult in battleResults.iteritems():
expireTime = battleResult.get('vehTypeUnlockTime', 0)
if not expireTime:
continue
vehicleName = vehicleNames.get(vehIntCD)
if vehicleName is None:
continue
locks.append(g_settings.htmlTemplates.format('battleResultLocks', ctx={'vehicleName': vehicleName,
'expireTime': TimeFormatter.getLongDatetimeFormat(expireTime)}))
return ', '.join(locks)
def __makeXpExString(self, xp, battleResKey, xpPenalty, battleResults):
if not xp:
return ''
exStrings = []
if xpPenalty > 0:
exStrings.append(self.__i18n_penalty % BigWorld.wg_getIntegralFormat(xpPenalty))
if battleResKey == 1:
xpFactorStrings = []
for battleResult in battleResults.itervalues():
xpFactor = battleResult.get('dailyXPFactor', 1)
if xpFactor > 1:
xpFactorStrings.append(i18n.makeString('#%s:serviceChannelMessages/battleResults/doubleXpFactor' % MESSENGER_I18N_FILE) % xpFactor)
if xpFactorStrings:
exStrings.append(', '.join(xpFactorStrings))
if len(exStrings):
return ' ({0:>s})'.format('; '.join(exStrings))
return ''
def __makeCreditsExString(self, accCredits, creditsPenalty, creditsContributionIn, creditsContributionOut):
if not accCredits:
return ''
exStrings = []
penalty = sum([creditsPenalty, creditsContributionOut])
if penalty > 0:
exStrings.append(self.__i18n_penalty % BigWorld.wg_getIntegralFormat(penalty))
if creditsContributionIn > 0:
exStrings.append(self.__i18n_contribution % BigWorld.wg_getIntegralFormat(creditsContributionIn))
if len(exStrings):
return ' ({0:>s})'.format('; '.join(exStrings))
return ''
def __makeGoldString(self, gold):
if not gold:
return ''
return g_settings.htmlTemplates.format(self.__goldTemplateKey, {'gold': BigWorld.wg_getGoldFormat(gold)})
@classmethod
def __makeAchievementsString(cls, popUpRecords, marksOfMastery):
result = []
for recordIdx, value in popUpRecords:
recordName = DB_ID_TO_RECORD[recordIdx]
if recordName in IGNORED_BY_BATTLE_RESULTS:
continue
achieve = getAchievementFactory(recordName).create(value=value)
if achieve is not None and not achieve.isApproachable():
result.append(achieve)
for markOfMastery in marksOfMastery:
achieve = getAchievementFactory((ACHIEVEMENT_BLOCK.TOTAL, 'markOfMastery')).create(value=markOfMastery)
if achieve is not None:
result.append(achieve)
res = ''
if len(result):
res = g_settings.htmlTemplates.format('battleResultAchieves', {'achieves': ', '.join(map(lambda a: a.getUserName(), sorted(result)))})
return res
class AutoMaintenanceFormatter(ServiceChannelFormatter):
__messages = {AUTO_MAINTENANCE_RESULT.NOT_ENOUGH_ASSETS: {AUTO_MAINTENANCE_TYPE.REPAIR: '#messenger:serviceChannelMessages/autoRepairError',
AUTO_MAINTENANCE_TYPE.LOAD_AMMO: '#messenger:serviceChannelMessages/autoLoadError',
AUTO_MAINTENANCE_TYPE.EQUIP: '#messenger:serviceChannelMessages/autoEquipError'},
AUTO_MAINTENANCE_RESULT.OK: {AUTO_MAINTENANCE_TYPE.REPAIR: '#messenger:serviceChannelMessages/autoRepairSuccess',
AUTO_MAINTENANCE_TYPE.LOAD_AMMO: '#messenger:serviceChannelMessages/autoLoadSuccess',
AUTO_MAINTENANCE_TYPE.EQUIP: '#messenger:serviceChannelMessages/autoEquipSuccess'},
AUTO_MAINTENANCE_RESULT.NOT_PERFORMED: {AUTO_MAINTENANCE_TYPE.REPAIR: '#messenger:serviceChannelMessages/autoRepairSkipped',
AUTO_MAINTENANCE_TYPE.LOAD_AMMO: '#messenger:serviceChannelMessages/autoLoadSkipped',
AUTO_MAINTENANCE_TYPE.EQUIP: '#messenger:serviceChannelMessages/autoEquipSkipped'},
AUTO_MAINTENANCE_RESULT.DISABLED_OPTION: {AUTO_MAINTENANCE_TYPE.REPAIR: '#messenger:serviceChannelMessages/autoRepairDisabledOption',
AUTO_MAINTENANCE_TYPE.LOAD_AMMO: '#messenger:serviceChannelMessages/autoLoadDisabledOption',
AUTO_MAINTENANCE_TYPE.EQUIP: '#messenger:serviceChannelMessages/autoEquipDisabledOption'},
AUTO_MAINTENANCE_RESULT.NO_WALLET_SESSION: {AUTO_MAINTENANCE_TYPE.REPAIR: '#messenger:serviceChannelMessages/autoRepairErrorNoWallet',
AUTO_MAINTENANCE_TYPE.LOAD_AMMO: '#messenger:serviceChannelMessages/autoLoadErrorNoWallet',
AUTO_MAINTENANCE_TYPE.EQUIP: '#messenger:serviceChannelMessages/autoEquipErrorNoWallet'}}
def isNotify(self):
return True
def format(self, message, *args):
vehicleCompDescr = message.data.get('vehTypeCD', None)
result = message.data.get('result', None)
typeID = message.data.get('typeID', None)
cost = message.data.get('cost', (0, 0))
if vehicleCompDescr is not None and result is not None and typeID is not None:
vt = vehicles_core.getVehicleType(vehicleCompDescr)
if typeID == AUTO_MAINTENANCE_TYPE.REPAIR:
formatMsgType = 'RepairSysMessage'
else:
formatMsgType = 'PurchaseForCreditsSysMessage' if cost[1] == 0 else 'PurchaseForGoldSysMessage'
msg = i18n.makeString(self.__messages[result][typeID]) % vt.userString
priorityLevel = NotificationPriorityLevel.MEDIUM
if result == AUTO_MAINTENANCE_RESULT.OK:
priorityLevel = NotificationPriorityLevel.LOW
templateName = formatMsgType
elif result == AUTO_MAINTENANCE_RESULT.NOT_ENOUGH_ASSETS:
templateName = 'ErrorSysMessage'
else:
templateName = 'WarningSysMessage'
if result == AUTO_MAINTENANCE_RESULT.OK:
msg += formatPrice((abs(cost[0]), abs(cost[1])))
formatted = g_settings.msgTemplates.format(templateName, {'text': msg})
return (formatted, self._getGuiSettings(message, priorityLevel=priorityLevel))
else:
return (None, None)
return
class AchievementFormatter(ServiceChannelFormatter):
@async
def __getRareTitle(self, rareID, callback):
rare_achievements.getRareAchievementText(getClientLanguage(), rareID, lambda rID, text: callback(text.get('title')))
def isNotify(self):
return True
def isAsync(self):
return True
@async
@process
def format(self, message, callback):
yield lambda callback: callback(True)
achievesList = list()
achieves = message.data.get('popUpRecords')
if achieves is not None:
achievesList.extend([ i18n.makeString('#achievements:{0[1]:>s}'.format(name)) for name in achieves ])
rares = message.data.get('rareAchievements')
if rares is not None:
unknownAchieves = 0
for rareID in rares:
if rareID > 0:
title = yield self.__getRareTitle(rareID)
if title is None:
unknownAchieves += 1
else:
achievesList.append(title)
if unknownAchieves:
achievesList.append(i18n.makeString('#system_messages:%s/title' % ('actionAchievements' if unknownAchieves > 1 else 'actionAchievement')))
if not len(achievesList):
callback((None, None))
return
else:
formatted = g_settings.msgTemplates.format('achievementReceived', {'achieves': ', '.join(achievesList)})
callback((formatted, self._getGuiSettings(message, 'achievementReceived')))
return
class GoldReceivedFormatter(ServiceChannelFormatter):
def format(self, message, *args):
data = message.data
gold = data.get('gold', None)
transactionTime = data.get('date', None)
if gold and transactionTime:
formatted = g_settings.msgTemplates.format('goldReceived', {'date': TimeFormatter.getLongDatetimeFormat(transactionTime),
'gold': BigWorld.wg_getGoldFormat(account_helpers.convertGold(gold))})
return (formatted, self._getGuiSettings(message, 'goldReceived'))
else:
return (None, None)
return
class GiftReceivedFormatter(ServiceChannelFormatter):
__handlers = {'money': ('_GiftReceivedFormatter__formatMoneyGiftMsg', {1: 'creditsReceivedAsGift',
2: 'goldReceivedAsGift',
3: 'creditsAndGoldReceivedAsGift'}),
'xp': ('_GiftReceivedFormatter__formatXPGiftMsg', 'xpReceivedAsGift'),
'premium': ('_GiftReceivedFormatter__formatPremiumGiftMsg', 'premiumReceivedAsGift'),
'item': ('_GiftReceivedFormatter__formatItemGiftMsg', 'itemReceivedAsGift'),
'vehicle': ('_GiftReceivedFormatter__formatVehicleGiftMsg', 'vehicleReceivedAsGift')}
def format(self, message, *args):
data = message.data
giftType = data.get('type')
if giftType is not None:
handlerName, templateKey = self.__handlers.get(giftType, (None, None))
if handlerName is not None:
formatted, templateKey = getattr(self, handlerName)(templateKey, data)
return (formatted, self._getGuiSettings(message, templateKey))
return (None, None)
def __formatMoneyGiftMsg(self, keys, data):
accCredits = data.get('credits', 0)
gold = data.get('gold', 0)
result = (None, '')
ctx = {}
idx = 0
if accCredits > 0:
idx |= 1
ctx['credits'] = BigWorld.wg_getIntegralFormat(accCredits)
if gold > 0:
idx |= 2
ctx['gold'] = BigWorld.wg_getGoldFormat(gold)
if idx in keys:
key = keys[idx]
result = (g_settings.msgTemplates.format(keys[idx], ctx), key)
return result
def __formatXPGiftMsg(self, key, data):
xp = data.get('amount', 0)
result = None
if xp > 0:
result = g_settings.msgTemplates.format(key, ctx={'freeXP': BigWorld.wg_getIntegralFormat(xp)})
return (result, key)
def __formatPremiumGiftMsg(self, key, data):
days = data.get('amount', 0)
result = None
if days > 0:
result = g_settings.msgTemplates.format(key, ctx={'days': days})
return (result, key)
def __formatItemGiftMsg(self, key, data):
amount = data.get('amount', 0)
result = None
itemTypeIdx = data.get('itemTypeIdx')
itemCompactDesc = data.get('itemCD')
if amount > 0 and itemTypeIdx is not None and itemCompactDesc is not None:
result = g_settings.msgTemplates.format(key, ctx={'typeName': getTypeInfoByIndex(itemTypeIdx)['userString'],
'itemName': vehicles_core.getDictDescr(itemCompactDesc)['userString'],
'amount': amount})
return (result, key)
def __formatVehicleGiftMsg(self, key, data):
vCompDesc = data.get('typeCD', None)
result = None
if vCompDesc is not None:
result = g_settings.msgTemplates.format(key, ctx={'vehicleName': vehicles_core.getVehicleType(vCompDesc).userString})
return (result, key)
class InvoiceReceivedFormatter(ServiceChannelFormatter):
__assetHandlers = {INVOICE_ASSET.GOLD: '_InvoiceReceivedFormatter__formatAmount',
INVOICE_ASSET.CREDITS: '_InvoiceReceivedFormatter__formatAmount',
INVOICE_ASSET.PREMIUM: '_InvoiceReceivedFormatter__formatAmount',
INVOICE_ASSET.FREE_XP: '_InvoiceReceivedFormatter__formatAmount',
INVOICE_ASSET.DATA: '_InvoiceReceivedFormatter__formatData'}
__operationTemplateKeys = {INVOICE_ASSET.GOLD: 'goldAccruedInvoiceReceived',
INVOICE_ASSET.CREDITS: 'creditsAccruedInvoiceReceived',
INVOICE_ASSET.PREMIUM: 'premiumAccruedInvoiceReceived',
INVOICE_ASSET.FREE_XP: 'freeXpAccruedInvoiceReceived',
INVOICE_ASSET.GOLD | 16: 'goldDebitedInvoiceReceived',
INVOICE_ASSET.CREDITS | 16: 'creditsDebitedInvoiceReceived',
INVOICE_ASSET.PREMIUM | 16: 'premiumDebitedInvoiceReceived',
INVOICE_ASSET.FREE_XP | 16: 'freeXpDebitedInvoiceReceived'}
__messageTemplateKeys = {INVOICE_ASSET.GOLD: 'goldInvoiceReceived',
INVOICE_ASSET.CREDITS: 'creditsInvoiceReceived',
INVOICE_ASSET.PREMIUM: 'premiumInvoiceReceived',
INVOICE_ASSET.FREE_XP: 'freeXpInvoiceReceived',
INVOICE_ASSET.DATA: 'dataInvoiceReceived'}
__i18nPiecesString = i18n.makeString('#{0:>s}:serviceChannelMessages/invoiceReceived/pieces'.format(MESSENGER_I18N_FILE))
__i18nCrewLvlString = i18n.makeString('#{0:>s}:serviceChannelMessages/invoiceReceived/crewLvl'.format(MESSENGER_I18N_FILE))
__i18nCrewDroppedString = i18n.makeString('#{0:>s}:serviceChannelMessages/invoiceReceived/droppedCrewsToBarracks'.format(MESSENGER_I18N_FILE))
def __getOperationTimeString(self, data):
operationTime = data.get('at', None)
if operationTime:
fDatetime = TimeFormatter.getLongDatetimeFormat(time_utils.makeLocalServerTime(operationTime))
else:
fDatetime = 'N/A'
return fDatetime
def __getFinOperationString(self, assetType, amount):
templateKey = 0 if amount > 0 else 16
templateKey |= assetType
ctx = {}
if assetType == INVOICE_ASSET.GOLD:
ctx['amount'] = BigWorld.wg_getGoldFormat(abs(amount))
else:
ctx['amount'] = BigWorld.wg_getIntegralFormat(abs(amount))
return g_settings.htmlTemplates.format(self.__operationTemplateKeys[templateKey], ctx=ctx)
def __getItemsString(self, items):
accrued = []
debited = []
for itemCompactDescr, count in items.iteritems():
if count:
try:
item = vehicles_core.getDictDescr(itemCompactDescr)
itemString = '{0:>s} "{1:>s}" - {2:d} {3:>s}'.format(getTypeInfoByName(item['itemTypeName'])['userString'], item['userString'], abs(count), self.__i18nPiecesString)
if count > 0:
accrued.append(itemString)
else:
debited.append(itemString)
except:
LOG_ERROR('itemCompactDescr can not parse ', itemCompactDescr)
LOG_CURRENT_EXCEPTION()
result = ''
if len(accrued):
result = g_settings.htmlTemplates.format('itemsAccruedInvoiceReceived', ctx={'items': ', '.join(accrued)})
if len(debited):
if len(result):
result += '<br/>'
result += g_settings.htmlTemplates.format('itemsDebitedInvoiceReceived', ctx={'items': ', '.join(debited)})
return result
@classmethod
def __getVehicleName(cls, vehCompDescr, vehData, showCrewLvl = True, showRent = True):
crewLvl = 50
vInfo = []
if showRent and 'rent' in vehData:
rentDays = vehData.get('rent', {}).get('expires', {}).get('after', None)
if rentDays:
rentDaysStr = g_settings.htmlTemplates.format('rentDays', {'value': str(rentDays)})
vInfo.append(rentDaysStr)
if showCrewLvl:
crewLvl = calculateRoleLevel(vehData.get('crewLvl', 50), vehData.get('crewFreeXP', 0))
vehUserString = None
try:
vehUserString = vehicles_core.getVehicleType(vehCompDescr).userString
if crewLvl > 50:
crewLvl = cls.__i18nCrewLvlString % crewLvl
if 'crewInBarracks' in vehData:
if 'crewFreeXP' in vehData or 'crewLvl' in vehData or 'tankmen' in vehData:
crewLvl = '%s %s' % (crewLvl, cls.__i18nCrewDroppedString)
vInfo.append(crewLvl)
if len(vInfo):
vInfoStr = '; '.join(vInfo)
vehUserString = '{0:>s} ({1:>s})'.format(vehUserString, vInfoStr)
except:
LOG_ERROR('Wrong vehicle compact descriptor', vehCompDescr)
LOG_CURRENT_EXCEPTION()
return vehUserString
@classmethod
def _getVehicleNames(cls, vehicles):
addVehNames = []
removeVehNames = []
rentedVehNames = []
for vehCompDescr, vehData in vehicles.iteritems():
if 'customCompensation' in vehData:
continue
isNegative = False
if type(vehCompDescr) is types.IntType:
isNegative = vehCompDescr < 0
vehCompDescr = abs(vehCompDescr)
isRented = 'rent' in vehData
vehUserString = cls.__getVehicleName(vehCompDescr, vehData)
if vehUserString is None:
continue
if isNegative:
removeVehNames.append(vehUserString)
elif isRented:
rentedVehNames.append(vehUserString)
else:
addVehNames.append(vehUserString)
return (addVehNames, removeVehNames, rentedVehNames)
@classmethod
def _getVehiclesString(cls, vehicles, htmlTplPostfix = 'InvoiceReceived'):
addVehNames, removeVehNames, rentedVehNames = cls._getVehicleNames(vehicles)
result = []
if len(addVehNames):
result.append(g_settings.htmlTemplates.format('vehiclesAccrued' + htmlTplPostfix, ctx={'vehicles': ', '.join(addVehNames)}))
if len(removeVehNames):
result.append(g_settings.htmlTemplates.format('vehiclesDebited' + htmlTplPostfix, ctx={'vehicles': ', '.join(removeVehNames)}))
if len(rentedVehNames):
result.append(g_settings.htmlTemplates.format('vehiclesRented' + htmlTplPostfix, ctx={'vehicles': ', '.join(rentedVehNames)}))
return '<br/>'.join(result)
@classmethod
def _getComptnString(cls, vehicles, htmlTplPostfix = 'InvoiceReceived'):
html = g_settings.htmlTemplates
result = []
for vehCompDescr, vehData in vehicles.iteritems():
vehUserString = cls.__getVehicleName(vehCompDescr, vehData, showCrewLvl=False, showRent=False)
if vehUserString is None:
continue
if 'rentCompensation' in vehData:
credits, gold = vehData['rentCompensation']
if gold > 0:
key = 'goldRentCompensationReceived'
formattedGold = BigWorld.wg_getGoldFormat(account_helpers.convertGold(gold))
ctx = {'gold': formattedGold,
'vehicleName': vehUserString}
else:
key = 'creditsRentCompensationReceived'
formattedCredits = BigWorld.wg_getIntegralFormat(credits)
ctx = {'credits': formattedCredits,
'vehicleName': vehUserString}
result.append(html.format(key, ctx=ctx))
if 'customCompensation' in vehData:
itemNames = [vehUserString]
credits, gold = vehData['customCompensation']
values = []
if gold > 0:
values.append(html.format('goldCompensation' + htmlTplPostfix, ctx={'amount': BigWorld.wg_getGoldFormat(gold)}))
if credits > 0:
values.append(html.format('creditsCompensation' + htmlTplPostfix, ctx={'amount': BigWorld.wg_getIntegralFormat(credits)}))
if len(values):
result.append(html.format('compensationFor' + htmlTplPostfix, ctx={'items': ', '.join(itemNames),
'compensation': ', '.join(values)}))
return '<br/>'.join(result)
@classmethod
def _getTankmenString(cls, tmen):
tmanUserStrings = []
for tmanData in tmen:
try:
if isinstance(tmanData, dict):
tankman = Tankman(tmanData['tmanCompDescr'])
else:
tankman = Tankman(tmanData)
tmanUserStrings.append('{0:>s} {1:>s} ({2:>s}, {3:>s}, {4:d}%)'.format(tankman.rankUserName, tankman.lastUserName, tankman.roleUserName, tankman.vehicleNativeDescr.type.userString, tankman.roleLevel))
except:
LOG_ERROR('Wrong tankman data', tmanData)
LOG_CURRENT_EXCEPTION()
result = ''
if len(tmanUserStrings):
result = g_settings.htmlTemplates.format('tankmenInvoiceReceived', ctx={'tankman': ', '.join(tmanUserStrings)})
return result
@classmethod
def _getGoodiesString(cls, goodies):
boostersStrings = []
for goodieID, ginfo in goodies.iteritems():
booster = g_goodiesCache.getBooster(goodieID)
if booster is not None:
boostersStrings.append(booster.userName)
result = ''
if len(boostersStrings):
result = g_settings.htmlTemplates.format('boostersInvoiceReceived', ctx={'boosters': ', '.join(boostersStrings)})
return result
def __getSlotsString(self, slots):
if slots > 0:
template = 'slotsAccruedInvoiceReceived'
else:
template = 'slotsDebitedInvoiceReceived'
return g_settings.htmlTemplates.format(template, {'amount': BigWorld.wg_getIntegralFormat(abs(slots))})
@classmethod
def __getBerthsString(cls, berths):
if berths > 0:
template = 'berthsAccruedInvoiceReceived'
else:
template = 'berthsDebitedInvoiceReceived'
return g_settings.htmlTemplates.format(template, {'amount': BigWorld.wg_getIntegralFormat(abs(berths))})
def __getL10nDescription(self, data):
descr = ''
lData = getLocalizedData(data.get('data', {}), 'localized_description', defVal=None)
if lData:
descr = i18n.encodeUtf8(html.escape(lData.get('description', u'')))
if len(descr):
descr = '<br/>' + descr
return descr
@classmethod
def _processCompensations(cls, data):
vehicles = data.get('vehicles')
credits = 0
gold = 0
if vehicles is not None:
for value in vehicles.itervalues():
if 'rentCompensation' in value:
credits += value['rentCompensation'][0]
gold += value['rentCompensation'][1]
if 'customCompensation' in value:
credits += value['customCompensation'][0]
gold += value['customCompensation'][1]
if 'gold' in data:
data['gold'] -= gold
if data['gold'] == 0:
del data['gold']
if 'credits' in data:
data['credits'] -= credits
if data['credits'] == 0:
del data['credits']
return
def __formatAmount(self, assetType, data):
amount = data.get('amount', None)
if amount is None:
return
else:
return g_settings.msgTemplates.format(self.__messageTemplateKeys[assetType], ctx={'at': self.__getOperationTimeString(data),
'desc': self.__getL10nDescription(data),
'op': self.__getFinOperationString(assetType, amount)})
def __formatData(self, assetType, data):
dataEx = data.get('data', {})
if dataEx is None or not len(dataEx):
return
operations = []
self._processCompensations(dataEx)
gold = dataEx.get('gold')
if gold is not None:
operations.append(self.__getFinOperationString(INVOICE_ASSET.GOLD, gold))
accCredtis = dataEx.get('credits')
if accCredtis is not None:
operations.append(self.__getFinOperationString(INVOICE_ASSET.CREDITS, accCredtis))
freeXp = dataEx.get('freeXP')
if freeXp is not None:
operations.append(self.__getFinOperationString(INVOICE_ASSET.FREE_XP, freeXp))
premium = dataEx.get('premium')
if premium is not None:
operations.append(self.__getFinOperationString(INVOICE_ASSET.PREMIUM, premium))
items = dataEx.get('items', {})
if items is not None and len(items) > 0:
operations.append(self.__getItemsString(items))
tmen = dataEx.get('tankmen', [])
vehicles = dataEx.get('vehicles', {})
if vehicles is not None and len(vehicles) > 0:
result = self._getVehiclesString(vehicles)
if len(result):
operations.append(result)
comptnStr = self._getComptnString(vehicles)
if len(comptnStr):
operations.append(comptnStr)
for v in vehicles.itervalues():
tmen.extend(v.get('tankmen', []))
if tmen is not None and len(tmen) > 0:
operations.append(self._getTankmenString(tmen))
slots = dataEx.get('slots')
if slots:
operations.append(self.__getSlotsString(slots))
berths = dataEx.get('berths')
if berths:
operations.append(self.__getBerthsString(berths))
goodies = data.get('goodies', {})
if goodies is not None and len(goodies) > 0:
operations.append(self._getGoodiesString(goodies))
_extendCustomizationData(dataEx, operations)
if not operations:
return
else:
return g_settings.msgTemplates.format(self.__messageTemplateKeys[assetType], ctx={'at': self.__getOperationTimeString(data),
'desc': self.__getL10nDescription(data),
'op': '<br/>'.join(operations)})
def format(self, message, *args):
LOG_DEBUG('invoiceReceived', message)
data = message.data
assetType = data.get('assetType', -1)
handler = self.__assetHandlers.get(assetType)
if handler is not None:
formatted = getattr(self, handler)(assetType, data)
if formatted is not None:
return (formatted, self._getGuiSettings(message, self.__messageTemplateKeys[assetType]))
else:
return (None, None)
class AdminMessageFormatter(ServiceChannelFormatter):
def format(self, message, *args):
data = decompressSysMessage(message.data)
if data:
dataType = type(data)
text = ''
if dataType in types.StringTypes:
text = data
elif dataType is types.DictType:
text = getLocalizedData({'value': data}, 'value')
if not text:
LOG_ERROR('Text of message not found', message)
return (None, None)
formatted = g_settings.msgTemplates.format('adminMessage', {'text': text})
return (formatted, self._getGuiSettings(message, 'adminMessage'))
else:
return (None, None)
return None
class AccountTypeChangedFormatter(ServiceChannelFormatter):
def format(self, message, *args):
data = message.data
isPremium = data.get('isPremium', None)
expiryTime = data.get('expiryTime', None)
result = (None, None)
if isPremium is not None:
accountTypeName = i18n.makeString('#menu:accountTypes/premium') if isPremium else i18n.makeString('#menu:accountTypes/base')
expiryDatetime = TimeFormatter.getLongDatetimeFormat(expiryTime) if expiryTime else None
if expiryDatetime:
templateKey = 'accountTypeChangedWithExpiration'
ctx = {'accType': accountTypeName,
'expiryTime': expiryDatetime}
else:
templateKey = 'accountTypeChanged'
ctx = {'accType': accountTypeName}
formatted = g_settings.msgTemplates.format(templateKey, ctx=ctx)
result = (formatted, self._getGuiSettings(message, templateKey))
return result
class PremiumActionFormatter(ServiceChannelFormatter):
_templateKey = None
def _getMessage(self, isPremium, expiryTime):
return None
def format(self, message, *args):
data = message.data
isPremium = data.get('isPremium', None)
expiryTime = data.get('expiryTime', None)
if isPremium is not None:
return (self._getMessage(isPremium, expiryTime), self._getGuiSettings(message, self._templateKey))
else:
return (None, None)
class PremiumBoughtFormatter(PremiumActionFormatter):
_templateKey = 'premiumBought'
def _getMessage(self, isPremium, expiryTime):
result = None
if isPremium is True and expiryTime > 0:
result = g_settings.msgTemplates.format(self._templateKey, ctx={'expiryTime': TimeFormatter.getLongDatetimeFormat(expiryTime)})
return result
class PremiumExtendedFormatter(PremiumBoughtFormatter):
_templateKey = 'premiumExtended'
class PremiumExpiredFormatter(PremiumActionFormatter):
_templateKey = 'premiumExpired'
def _getMessage(self, isPremium, expiryTime):
result = None
if isPremium is False:
result = g_settings.msgTemplates.format(self._templateKey)
return result
class WaresSoldFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
result = (None, None)
if message.data:
offer = offers._makeOutOffer(message.data)
formatted = g_settings.msgTemplates.format('waresSoldAsGold', ctx={'srcWares': BigWorld.wg_getGoldFormat(offer.srcWares),
'dstName': offer.dstName,
'fee': offer.fee})
result = (formatted, self._getGuiSettings(message, 'waresSoldAsGold'))
return result
class WaresBoughtFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
result = (None, None)
if message.data:
offer = offers._makeInOffer(message.data)
formatted = g_settings.msgTemplates.format('waresBoughtAsGold', ctx={'srcName': offer.srcName,
'srcWares': BigWorld.wg_getGoldFormat(offer.srcWares)})
result = (formatted, self._getGuiSettings(message, 'waresBoughtAsGold'))
return result
class PrebattleFormatter(ServiceChannelFormatter):
__battleTypeByPrebattleType = {PREBATTLE_TYPE.TOURNAMENT: 'tournament',
PREBATTLE_TYPE.CLAN: 'clan'}
_battleFinishReasonKeys = {}
_defaultBattleFinishReasonKey = ('base', True)
def isNotify(self):
return True
def _getIconId(self, prbType):
iconId = 'BattleResultIcon'
if prbType == PREBATTLE_TYPE.CLAN:
iconId = 'ClanBattleResultIcon'
elif prbType == PREBATTLE_TYPE.TOURNAMENT:
iconId = 'TournamentBattleResultIcon'
return iconId
def _makeBattleTypeString(self, prbType):
typeString = self.__battleTypeByPrebattleType.get(prbType, 'prebattle')
key = '#{0:>s}:serviceChannelMessages/prebattle/battleType/{1:>s}'.format(MESSENGER_I18N_FILE, typeString)
return i18n.makeString(key)
def _makeDescriptionString(self, data, showBattlesCount = True):
if data.has_key('localized_data') and len(data['localized_data']):
description = getPrebattleFullDescription(data, escapeHtml=True)
else:
prbType = data.get('type')
description = self._makeBattleTypeString(prbType)
battlesLimit = data.get('battlesLimit', 0)
if showBattlesCount and battlesLimit > 1:
battlesCount = data.get('battlesCount')
if battlesCount > 0:
key = '#{0:>s}:serviceChannelMessages/prebattle/numberOfBattle'.format(MESSENGER_I18N_FILE)
numberOfBattleString = i18n.makeString(key, battlesCount)
description = '{0:>s} {1:>s}'.format(description, numberOfBattleString)
else:
LOG_WARNING('Invalid value of battlesCount ', battlesCount)
return description
def _getOpponentsString(self, opponents):
first = i18n.encodeUtf8(opponents.get('1', {}).get('name', ''))
second = i18n.encodeUtf8(opponents.get('2', {}).get('name', ''))
result = ''
if len(first) > 0 and len(second) > 0:
result = g_settings.htmlTemplates.format('prebattleOpponents', ctx={'first': html.escape(first),
'second': html.escape(second)})
return result
def _getBattleResultString(self, winner, team):
result = 'undefined'
if 3 > winner > -1 and team in (1, 2):
if not winner:
result = 'draftGame'
else:
result = 'defeat' if team != winner else 'win'
return result
def _makeBattleResultString(self, finishReason, winner, team):
finishString, showResult = self._battleFinishReasonKeys.get(finishReason, self._defaultBattleFinishReasonKey)
if showResult:
resultString = self._getBattleResultString(winner, team)
key = '#{0:>s}:serviceChannelMessages/prebattle/finish/{1:>s}/{2:>s}'.format(MESSENGER_I18N_FILE, finishString, resultString)
else:
key = '#{0:>s}:serviceChannelMessages/prebattle/finish/{1:>s}'.format(MESSENGER_I18N_FILE, finishString)
return i18n.makeString(key)
class PrebattleArenaFinishFormatter(PrebattleFormatter):
_battleFinishReasonKeys = {FINISH_REASON.TECHNICAL: ('technical', True),
FINISH_REASON.FAILURE: ('failure', False),
FINISH_REASON.UNKNOWN: ('failure', False)}
def format(self, message, *args):
LOG_DEBUG('prbArenaFinish', message)
data = message.data
prbType = data.get('type')
winner = data.get('winner')
team = data.get('team')
wins = data.get('wins')
finishReason = data.get('finishReason')
if None in [prbType,
winner,
team,
wins,
finishReason]:
return
else:
battleResult = self._makeBattleResultString(finishReason, winner, team)
subtotal = ''
battlesLimit = data.get('battlesLimit', 0)
if battlesLimit > 1:
battlesCount = data.get('battlesCount', -1)
winsLimit = data.get('winsLimit', -1)
if battlesCount == battlesLimit or winsLimit == wins[1] or winsLimit == wins[2]:
playerTeamWins = wins[team]
otherTeamWins = wins[2 if team == 1 else 1]
if winsLimit > 0 and playerTeamWins < winsLimit and otherTeamWins < winsLimit:
winner = None
elif playerTeamWins == otherTeamWins:
winner = 0
else:
winner = 1 if wins[1] > wins[2] else 2
sessionResult = self._makeBattleResultString(-1, winner, team)
subtotal = g_settings.htmlTemplates.format('prebattleTotal', ctx={'result': sessionResult,
'first': wins[1],
'second': wins[2]})
else:
subtotal = g_settings.htmlTemplates.format('prebattleSubtotal', ctx={'first': wins[1],
'second': wins[2]})
formatted = g_settings.msgTemplates.format('prebattleArenaFinish', ctx={'desc': self._makeDescriptionString(data),
'opponents': self._getOpponentsString(data.get('opponents', {})),
'result': battleResult,
'subtotal': subtotal}, data={'timestamp': _getTimeStamp(message),
'icon': self._getIconId(prbType)})
return (formatted, self._getGuiSettings(message, 'prebattleArenaFinish'))
class PrebattleKickFormatter(PrebattleFormatter):
def format(self, message, *args):
data = message.data
result = (None, None)
prbType = data.get('type')
kickReason = data.get('kickReason')
if prbType > 0 and kickReason > 0:
ctx = {}
key = '#system_messages:prebattle/kick/type/unknown'
if prbType == PREBATTLE_TYPE.SQUAD:
key = '#system_messages:prebattle/kick/type/squad'
elif prbType == PREBATTLE_TYPE.COMPANY:
key = '#system_messages:prebattle/kick/type/team'
ctx['type'] = i18n.makeString(key)
kickName = KICK_REASON_NAMES[kickReason]
key = '#system_messages:prebattle/kick/reason/{0:>s}'.format(kickName)
ctx['reason'] = i18n.makeString(key)
formatted = g_settings.msgTemplates.format('prebattleKick', ctx=ctx)
result = (formatted, self._getGuiSettings(message, 'prebattleKick'))
return result
class PrebattleDestructionFormatter(PrebattleFormatter):
_battleFinishReasonKeys = {KICK_REASON.ARENA_CREATION_FAILURE: ('failure', False),
KICK_REASON.AVATAR_CREATION_FAILURE: ('failure', False),
KICK_REASON.VEHICLE_CREATION_FAILURE: ('failure', False),
KICK_REASON.PREBATTLE_CREATION_FAILURE: ('failure', False),
KICK_REASON.BASEAPP_CRASH: ('failure', False),
KICK_REASON.CELLAPP_CRASH: ('failure', False),
KICK_REASON.UNKNOWN_FAILURE: ('failure', False),
KICK_REASON.CREATOR_LEFT: ('creatorLeft', False),
KICK_REASON.PLAYERKICK: ('playerKick', False),
KICK_REASON.TIMEOUT: ('timeout', False)}
def format(self, message, *args):
LOG_DEBUG('prbDestruction', message)
data = message.data
prbType = data.get('type')
team = data.get('team')
wins = data.get('wins')
kickReason = data.get('kickReason')
if None in [prbType,
team,
wins,
kickReason]:
return (None, None)
else:
playerTeamWins = wins[team]
otherTeamWins = wins[2 if team == 1 else 1]
winsLimit = data.get('winsLimit')
if winsLimit > 0 and playerTeamWins < winsLimit and otherTeamWins < winsLimit:
winner = None
elif playerTeamWins == otherTeamWins:
winner = 0
else:
winner = 1 if wins[1] > wins[2] else 2
battleResult = self._makeBattleResultString(kickReason, winner, team)
total = ''
if data.get('battlesLimit', 0) > 1:
total = '({0:d}:{1:d})'.format(wins[1], wins[2])
formatted = g_settings.msgTemplates.format('prebattleDestruction', ctx={'desc': self._makeDescriptionString(data, showBattlesCount=False),
'opponents': self._getOpponentsString(data.get('opponents', {})),
'result': battleResult,
'total': total}, data={'timestamp': _getTimeStamp(message),
'icon': self._getIconId(prbType)})
return (formatted, self._getGuiSettings(message, 'prebattleDestruction'))
class VehCamouflageTimedOutFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
data = message.data
formatted = None
vehTypeCompDescr = data.get('vehTypeCompDescr')
if vehTypeCompDescr is not None:
vType = vehicles_core.getVehicleType(vehTypeCompDescr)
if vType is not None:
formatted = g_settings.msgTemplates.format('vehCamouflageTimedOut', ctx={'vehicleName': vType.userString})
return (formatted, self._getGuiSettings(message, 'vehCamouflageTimedOut'))
class VehEmblemTimedOutFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
data = message.data
formatted = None
vehTypeCompDescr = data.get('vehTypeCompDescr')
if vehTypeCompDescr is not None:
vType = vehicles_core.getVehicleType(vehTypeCompDescr)
if vType is not None:
formatted = g_settings.msgTemplates.format('vehEmblemTimedOut', ctx={'vehicleName': vType.userString})
return (formatted, self._getGuiSettings(message, 'vehEmblemTimedOut'))
class VehInscriptionTimedOutFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
data = message.data
formatted = None
vehTypeCompDescr = data.get('vehTypeCompDescr')
if vehTypeCompDescr is not None:
vType = vehicles_core.getVehicleType(vehTypeCompDescr)
if vType is not None:
formatted = g_settings.msgTemplates.format('vehInscriptionTimedOut', ctx={'vehicleName': vType.userString})
return (formatted, self._getGuiSettings(message, 'vehInscriptionTimedOut'))
class ConverterFormatter(ServiceChannelFormatter):
def __i18nValue(self, key, isReceived, **kwargs):
key = ('%sReceived' if isReceived else '%sWithdrawn') % key
key = '#messenger:serviceChannelMessages/sysMsg/converter/%s' % key
return i18n.makeString(key) % kwargs
def __vehName(self, vehCompDescr):
return vehicles_core.getVehicleType(abs(vehCompDescr)).userString
def format(self, message, *args):
data = message.data
text = []
if data.get('inscriptions'):
text.append(i18n.makeString('#messenger:serviceChannelMessages/sysMsg/converter/inscriptions'))
if data.get('emblems'):
text.append(i18n.makeString('#messenger:serviceChannelMessages/sysMsg/converter/emblems'))
if data.get('camouflages'):
text.append(i18n.makeString('#messenger:serviceChannelMessages/sysMsg/converter/camouflages'))
vehicles = data.get('vehicles')
if vehicles:
vehiclesReceived = [ self.__vehName(cd) for cd in vehicles if cd > 0 ]
if len(vehiclesReceived):
text.append(self.__i18nValue('vehicles', True, vehicles=', '.join(vehiclesReceived)))
vehiclesWithdrawn = [ self.__vehName(cd) for cd in vehicles if cd < 0 ]
if len(vehiclesWithdrawn):
text.append(self.__i18nValue('vehicles', False, vehicles=', '.join(vehiclesWithdrawn)))
slots = data.get('slots')
if slots:
text.append(self.__i18nValue('slots', slots > 0, slots=BigWorld.wg_getIntegralFormat(abs(slots))))
gold = data.get('gold')
if gold:
text.append(self.__i18nValue('gold', gold > 0, gold=BigWorld.wg_getGoldFormat(abs(gold))))
accCredits = data.get('credits')
if accCredits:
text.append(self.__i18nValue('credits', accCredits > 0, credits=BigWorld.wg_getIntegralFormat(abs(accCredits))))
freeXP = data.get('freeXP')
if freeXP:
text.append(self.__i18nValue('freeXP', freeXP > 0, freeXP=BigWorld.wg_getIntegralFormat(abs(freeXP))))
formatted = g_settings.msgTemplates.format('ConverterNotify', {'text': '<br/>'.join(text)})
return (formatted, self._getGuiSettings(message, 'ConverterNotify'))
class ClientSysMessageFormatter(ServiceChannelFormatter):
__templateKey = '%sSysMessage'
def format(self, data, *args):
if len(args):
msgType = args[0][0]
else:
msgType = 'Error'
templateKey = self.__templateKey % msgType
formatted = g_settings.msgTemplates.format(templateKey, ctx={'text': data})
return (formatted, self._getGuiSettings(args, templateKey))
def _getGuiSettings(self, data, key = None, priorityLevel = None):
if type(data) is types.TupleType and len(data):
auxData = data[0][:]
else:
auxData = []
if priorityLevel is None:
priorityLevel = g_settings.msgTemplates.priority(key)
else:
priorityLevel = NotificationPriorityLevel.MEDIUM
return NotificationGuiSettings(self.isNotify(), priorityLevel=priorityLevel, auxData=auxData)
class PremiumAccountExpiryFormatter(ClientSysMessageFormatter):
def format(self, data, *args):
formatted = g_settings.msgTemplates.format('durationOfPremiumAccountExpires', ctx={'expiryTime': TimeFormatter.getLongDatetimeFormat(data)})
return (formatted, self._getGuiSettings(args, 'durationOfPremiumAccountExpires'))
class AOGASNotifyFormatter(ClientSysMessageFormatter):
def format(self, data, *args):
formatted = g_settings.msgTemplates.format('AOGASNotify', {'text': i18n.makeString('#AOGAS:{0:>s}'.format(data.name()))})
return (formatted, self._getGuiSettings(args, 'AOGASNotify'))
class VehicleTypeLockExpired(ServiceChannelFormatter):
def format(self, message, *args):
result = (None, None)
if message.data:
ctx = {}
vehTypeCompDescr = message.data.get('vehTypeCompDescr')
if vehTypeCompDescr is None:
templateKey = 'vehiclesAllLockExpired'
else:
templateKey = 'vehicleLockExpired'
ctx['vehicleName'] = vehicles_core.getVehicleType(vehTypeCompDescr).userString
formatted = g_settings.msgTemplates.format(templateKey, ctx=ctx)
result = (formatted, self._getGuiSettings(message, 'vehicleLockExpired'))
return result
class ServerDowntimeCompensation(ServiceChannelFormatter):
__templateKey = 'serverDowntimeCompensation'
def format(self, message, *args):
result = (None, None)
subjects = ''
data = message.data
if data is not None:
for key, value in data.items():
if value:
if len(subjects) > 0:
subjects += ', '
subjects += i18n.makeString('#%s:serviceChannelMessages/' % MESSENGER_I18N_FILE + self.__templateKey + '/' + key)
if len(subjects) > 0:
formatted = g_settings.msgTemplates.format(self.__templateKey, ctx={'text': i18n.makeString('#%s:serviceChannelMessages/' % MESSENGER_I18N_FILE + self.__templateKey) % subjects})
result = (formatted, self._getGuiSettings(message, self.__templateKey))
return result
class ActionNotificationFormatter(ClientSysMessageFormatter):
__templateKey = 'action%s'
def format(self, message, *args):
result = (None, None)
data = message.get('data')
if data:
templateKey = self.__templateKey % message.get('state', '')
formatted = g_settings.msgTemplates.format(templateKey, ctx={'text': data}, data={'icon': message.get('type', '')})
result = (formatted, self._getGuiSettings(args, templateKey))
return result
class BattleTutorialResultsFormatter(ClientSysMessageFormatter):
__resultKeyWithBonuses = 'battleTutorialResBonuses'
__resultKeyWoBonuses = 'battleTutorialResWoBonuses'
def isNotify(self):
return True
def format(self, data, *args):
LOG_DEBUG('message data', data)
finishReason = data.get('finishReason', -1)
resultKey = data.get('resultKey', None)
finishKey = data.get('finishKey', None)
if finishReason > -1 and resultKey and finishKey:
resultString = i18n.makeString('#{0:>s}:serviceChannelMessages/battleTutorial/results/{1:>s}'.format(MESSENGER_I18N_FILE, resultKey))
reasonString = i18n.makeString('#{0:>s}:serviceChannelMessages/battleTutorial/reasons/{1:>s}'.format(MESSENGER_I18N_FILE, finishKey))
arenaTypeID = data.get('arenaTypeID', 0)
arenaName = 'N/A'
if arenaTypeID > 0:
arenaName = ArenaType.g_cache[arenaTypeID].name
vTypeCD = data.get('vTypeCD', None)
vName = 'N/A'
if vTypeCD is not None:
vName = vehicles_core.getVehicleType(vTypeCD).userString
ctx = {'result': resultString,
'reason': reasonString,
'arenaName': i18n.makeString(arenaName),
'vehicleName': vName,
'freeXP': '0',
'credits': '0'}
freeXP = 0
credits_ = 0
chapters = data.get('chapters', [])
for chapter in chapters:
if chapter.get('received', False):
bonus = chapter.get('bonus', {})
freeXP += bonus.get('freeXP', 0)
credits_ += bonus.get('credits', 0)
if freeXP:
ctx['freeXP'] = BigWorld.wg_getIntegralFormat(freeXP)
if credits_:
ctx['credits'] = BigWorld.wg_getIntegralFormat(credits_)
all_ = data.get('areAllBonusesReceived', False)
if all_ and credits_ <= 0 and freeXP <= 0:
key = self.__resultKeyWoBonuses
else:
key = self.__resultKeyWithBonuses
import time
startedAtTime = data.get('startedAt', time.time())
formatted = g_settings.msgTemplates.format(key, ctx=ctx, data={'timestamp': startedAtTime,
'savedData': data.get('arenaUniqueID', 0)})
return (formatted, self._getGuiSettings(args, key))
else:
return (None, None)
return
class TokenQuestsFormatter(ServiceChannelFormatter):
def __init__(self, asBattleFormatter = False):
self._asBattleFormatter = asBattleFormatter
def format(self, message, *args):
formatted, settings = (None, None)
data = message.data or {}
completedQuestIDs = data.get('completedQuestIDs', set())
fmt = self._formatQuestAchieves(message)
if fmt is not None:
settings = self._getGuiSettings(message, self._getTemplateName(completedQuestIDs))
formatted = g_settings.msgTemplates.format(self._getTemplateName(completedQuestIDs), {'achieves': fmt})
return (formatted, settings)
def _getTemplateName(self, completedQuestIDs = set()):
if len(completedQuestIDs):
for qID in completedQuestIDs:
if potapov_quests.g_cache.isPotapovQuest(qID):
return 'potapovQuests'
return 'tokenQuests'
def _formatQuestAchieves(self, message):
data = message.data
result = []
InvoiceReceivedFormatter._processCompensations(data)
if not self._asBattleFormatter:
gold = data.get('gold', 0)
if gold:
result.append(self.__makeQuestsAchieve('battleQuestsGold', gold=BigWorld.wg_getIntegralFormat(gold)))
premium = data.get('premium', 0)
if premium:
result.append(self.__makeQuestsAchieve('battleQuestsPremium', days=premium))
if not self._asBattleFormatter:
freeXP = data.get('freeXP', 0)
if freeXP:
result.append(self.__makeQuestsAchieve('battleQuestsFreeXP', freeXP=BigWorld.wg_getIntegralFormat(freeXP)))
vehicles = data.get('vehicles', {})
if vehicles is not None and len(vehicles) > 0:
msg = InvoiceReceivedFormatter._getVehiclesString(vehicles, htmlTplPostfix='QuestsReceived')
if len(msg):
result.append(msg)
comptnStr = InvoiceReceivedFormatter._getComptnString(vehicles, htmlTplPostfix='QuestsReceived')
if len(comptnStr):
result.append('<br/>' + comptnStr)
if not self._asBattleFormatter:
creditsVal = data.get('credits', 0)
if creditsVal:
result.append(self.__makeQuestsAchieve('battleQuestsCredits', credits=BigWorld.wg_getIntegralFormat(creditsVal)))
slots = data.get('slots', 0)
if slots:
result.append(self.__makeQuestsAchieve('battleQuestsSlots', slots=BigWorld.wg_getIntegralFormat(slots)))
items = data.get('items', {})
itemsNames = []
for intCD, count in items.iteritems():
itemDescr = vehicles_core.getDictDescr(intCD)
itemsNames.append(i18n.makeString('#messenger:serviceChannelMessages/battleResults/quests/items/name', name=itemDescr['userString'], count=BigWorld.wg_getIntegralFormat(count)))
if len(itemsNames):
result.append(self.__makeQuestsAchieve('battleQuestsItems', names=', '.join(itemsNames)))
_extendCustomizationData(data, result)
berths = data.get('berths', 0)
if berths:
result.append(self.__makeQuestsAchieve('battleQuestsBerths', berths=BigWorld.wg_getIntegralFormat(berths)))
tmen = data.get('tankmen', {})
if tmen is not None and len(tmen) > 0:
result.append(InvoiceReceivedFormatter._getTankmenString(tmen))
goodies = data.get('goodies', {})
if goodies is not None and len(goodies) > 0:
result.append(InvoiceReceivedFormatter._getGoodiesString(goodies))
if not self._asBattleFormatter:
achieves = data.get('popUpRecords', [])
achievesNames = set()
for recordIdx, value in achieves:
factory = getAchievementFactory(DB_ID_TO_RECORD[recordIdx])
if factory is not None:
a = factory.create(value=int(value))
if a is not None:
achievesNames.add(a.getUserName())
if len(achievesNames):
result.append(self.__makeQuestsAchieve('battleQuestsPopUps', achievements=', '.join(achievesNames)))
if len(result):
return '<br/>'.join(result)
else:
return
@classmethod
def __makeQuestsAchieve(cls, key, **kwargs):
return g_settings.htmlTemplates.format(key, kwargs)
class HistoricalCostsReservedFormatter(ServiceChannelFormatter):
__htmlKeys = {1: 'historicalGoldReturn',
2: 'historicalCreditsReturn',
17: 'historicalGoldDebited',
18: 'historicalCreditsDebited'}
def format(self, message, *args):
data = message.data
accCredits, gold = (0, 0)
if 'gold' in data:
gold = data['gold']
if 'credits' in data:
accCredits = data['credits']
if accCredits or gold:
resource = []
priority = NotificationPriorityLevel.LOW
templateKey = self.__getTemplateKey(1, gold)
if templateKey:
priority = NotificationPriorityLevel.MEDIUM
resource.append(g_settings.htmlTemplates.format(templateKey, ctx={'gold': BigWorld.wg_getGoldFormat(abs(gold))}))
templateKey = self.__getTemplateKey(2, accCredits)
if templateKey:
resource.append(g_settings.htmlTemplates.format(templateKey, ctx={'credits': BigWorld.wg_getIntegralFormat(abs(accCredits))}))
if len(resource):
templateName = 'historicalCostsReserved'
formatted = g_settings.msgTemplates.format(templateName, ctx={'resource': '<br/>'.join(resource)})
settings = self._getGuiSettings(message, templateName, priority)
return (formatted, settings)
else:
return (None, None)
else:
return (None, None)
return None
def __getTemplateKey(self, primary, value):
if not value:
return
else:
key = primary
if value < 0:
key |= 16
result = None
if key in self.__htmlKeys:
result = self.__htmlKeys[key]
return result
class NCMessageFormatter(ServiceChannelFormatter):
__templateKeyFormat = 'notificationsCenterMessage_{0}'
def format(self, message, *args):
LOG_DEBUG('Message has received from notification center', message)
data = z_loads(message.data)
if not data:
return (None, None)
elif 'body' not in data or not data['body']:
return (None, None)
else:
templateKey = self.__getTemplateKey(data)
priority = self.__getGuiPriority(data)
topic = self.__getTopic(data)
body = self.__getBody(data)
settings = self._getGuiSettings(message, templateKey, priority)
msgType = data['type']
if msgType == NC_MESSAGE_TYPE.POLL:
if not GUI_SETTINGS.isPollEnabled:
return (None, None)
if not self.__fetchPollData(data, settings):
return (None, None)
formatted = g_settings.msgTemplates.format(templateKey, ctx={'topic': topic,
'body': body})
return (formatted, settings)
def __getTemplateKey(self, data):
if 'type' in data:
msgType = data['type']
if msgType not in NC_MESSAGE_TYPE.RANGE:
LOG_WARNING('Type of message is not valid, uses default type', msgType)
msgType = NC_MESSAGE_TYPE.INFO
else:
msgType = NC_MESSAGE_TYPE.INFO
return self.__templateKeyFormat.format(msgType)
def __getGuiPriority(self, data):
priority = NC_MESSAGE_PRIORITY.DEFAULT
if 'priority' in data:
priority = data['priority']
if priority not in NC_MESSAGE_PRIORITY.ORDER:
LOG_WARNING('Priority of message is not valid, uses default priority', priority)
priority = NC_MESSAGE_PRIORITY.DEFAULT
return NotificationPriorityLevel.convertFromNC(priority)
def __getTopic(self, data):
topic = ''
if 'topic' in data:
topic = i18n.encodeUtf8(data['topic'])
if len(topic):
topic = g_settings.htmlTemplates.format('notificationsCenterTopic', ctx={'topic': topic})
return topic
def __getBody(self, data):
body = i18n.encodeUtf8(data['body'])
if 'context' in data:
body = body % self.__formatContext(data['context'])
return body
def __fetchPollData(self, data, settings):
result = False
if 'link' in data and data['link']:
if 'topic' in data:
topic = i18n.encodeUtf8(data['topic'])
else:
topic = ''
settings.auxData = [data['link'], topic]
result = True
return result
def __formatContext(self, ctx):
result = {}
if type(ctx) is not types.DictType:
LOG_ERROR('Context is invalid', ctx)
return result
getItemFormat = NCContextItemFormatter.getItemFormat
for key, item in ctx.iteritems():
if len(item) > 1:
itemType, itemValue = item[0:2]
result[key] = getItemFormat(itemType, itemValue)
else:
LOG_ERROR('Context item is invalid', item)
result[key] = str(item)
return result
class ClanMessageFormatter(ServiceChannelFormatter):
__templates = {SYS_MESSAGE_CLAN_EVENT.LEFT_CLAN: 'clanMessageWarning'}
def format(self, message, *args):
LOG_DEBUG('Message has received from clan', message)
data = message.data
if data and 'event' in data:
event = data['event']
templateKey = self.__templates.get(event)
message = i18n.makeString('#messenger:serviceChannelMessages/clan/%s' % SYS_MESSAGE_CLAN_EVENT_NAMES[event])
formatted = g_settings.msgTemplates.format(templateKey, ctx={'message': message})
settings = self._getGuiSettings(message, templateKey)
return (formatted, settings)
else:
return (None, None)
return None
class FortMessageFormatter(ServiceChannelFormatter, AppRef):
__templates = {SYS_MESSAGE_FORT_EVENT.DEF_HOUR_SHUTDOWN: 'fortHightPriorityMessageWarning',
SYS_MESSAGE_FORT_EVENT.BASE_DESTROYED: 'fortHightPriorityMessageWarning'}
DEFAULT_WARNING = 'fortMessageWarning'
def __init__(self):
super(FortMessageFormatter, self).__init__()
self.__messagesFormatters = {SYS_MESSAGE_FORT_EVENT.FORT_READY: BoundMethodWeakref(self._simpleMessage),
SYS_MESSAGE_FORT_EVENT.DEF_HOUR_SHUTDOWN: BoundMethodWeakref(self._simpleMessage),
SYS_MESSAGE_FORT_EVENT.RESERVE_ACTIVATED: BoundMethodWeakref(self._reserveActivatedMessage),
SYS_MESSAGE_FORT_EVENT.RESERVE_EXPIRED: BoundMethodWeakref(self._reserveExpiredMessage),
SYS_MESSAGE_FORT_EVENT.RESERVE_PRODUCED: BoundMethodWeakref(self._reserveProducedMessage),
SYS_MESSAGE_FORT_EVENT.STORAGE_OVERFLOW: BoundMethodWeakref(self._storageOverflowMessage),
SYS_MESSAGE_FORT_EVENT.ORDER_CANCELED: BoundMethodWeakref(self._orderCanceledMessage),
SYS_MESSAGE_FORT_EVENT.REATTACHED_TO_BASE: BoundMethodWeakref(self._reattachedToBaseMessage),
SYS_MESSAGE_FORT_EVENT.DEF_HOUR_ACTIVATED: BoundMethodWeakref(self._defHourManipulationMessage),
SYS_MESSAGE_FORT_EVENT.DEF_HOUR_CHANGED: BoundMethodWeakref(self._defHourManipulationMessage),
SYS_MESSAGE_FORT_EVENT.OFF_DAY_ACTIVATED: BoundMethodWeakref(self._offDayActivatedMessage),
SYS_MESSAGE_FORT_EVENT.VACATION_STARTED: BoundMethodWeakref(self._vacationActivatedMessage),
SYS_MESSAGE_FORT_EVENT.VACATION_FINISHED: BoundMethodWeakref(self._vacationFinishedMessage),
SYS_MESSAGE_FORT_EVENT.PERIPHERY_CHANGED: BoundMethodWeakref(self._peripheryChangedMessage),
SYS_MESSAGE_FORT_EVENT.BUILDING_DAMAGED: BoundMethodWeakref(self._buildingDamagedMessage),
SYS_MESSAGE_FORT_EVENT.BASE_DESTROYED: BoundMethodWeakref(self._simpleMessage),
SYS_MESSAGE_FORT_EVENT.ORDER_COMPENSATED: BoundMethodWeakref(self._orderCompensationMessage),
SYS_MESSAGE_FORT_EVENT.ATTACK_PLANNED: BoundMethodWeakref(self._attackPlannedMessage),
SYS_MESSAGE_FORT_EVENT.DEFENCE_PLANNED: BoundMethodWeakref(self._defencePlannedMessage),
SYS_MESSAGE_FORT_EVENT.BATTLE_DELETED: BoundMethodWeakref(self._battleDeletedMessage),
SYS_MESSAGE_FORT_EVENT.SPECIAL_ORDER_EXPIRED: BoundMethodWeakref(self._specialReserveExpiredMessage),
SYS_MESSAGE_FORT_EVENT.RESOURCE_SET: BoundMethodWeakref(self._resourceSetMessage),
SYS_MESSAGE_FORT_EVENT.RESERVE_SET: BoundMethodWeakref(self._reserveSetMessage)}
def format(self, message, *args):
LOG_DEBUG('Message has received from fort', message)
data = message.data
if data and 'event' in data:
event = data['event']
templateKey = self.__templates.get(event, self.DEFAULT_WARNING)
formatter = self.__messagesFormatters.get(event)
if formatter is not None:
messageSting = formatter(data)
formatted = g_settings.msgTemplates.format(templateKey, ctx={'message': messageSting})
settings = self._getGuiSettings(message, templateKey)
return (formatted, settings)
LOG_WARNING('FortMessageFormatter has no available formatters for given message type: ', event)
return (None, None)
def _buildMessage(self, event, ctx = None):
if ctx is None:
ctx = {}
return i18n.makeString(('#messenger:serviceChannelMessages/fort/%s' % SYS_MESSAGE_FORT_EVENT_NAMES[event]), **ctx)
def _simpleMessage(self, data):
return self._buildMessage(data['event'])
def _peripheryChangedMessage(self, data):
return self._buildMessage(data['event'], {'peripheryName': g_preDefinedHosts.periphery(data['peripheryID']).name})
def _reserveActivatedMessage(self, data):
event = data['event']
orderTypeID = data['orderTypeID']
order = fort_fmts.getOrderUserString(data['orderTypeID'])
if event == SYS_MESSAGE_FORT_EVENT.RESERVE_ACTIVATED and FORT_ORDER_TYPE.isOrderPermanent(orderTypeID):
return i18n.makeString(MESSENGER.SERVICECHANNELMESSAGES_FORT_PERMANENT_RESERVE_ACTIVATED, order=order)
timeExpiration = self.app.utilsManager.textManager.getTimeDurationStr(time_utils.getTimeDeltaFromNow(time_utils.makeLocalServerTime(data['timeExpiration'])))
return self._buildMessage(event, {'order': order,
'time': timeExpiration})
def _reserveExpiredMessage(self, data):
return self._buildMessage(data['event'], {'order': fort_fmts.getOrderUserString(data['orderTypeID'])})
def _reserveProducedMessage(self, data):
return self._buildMessage(data['event'], {'order': fort_fmts.getOrderUserString(data['orderTypeID']),
'count': data['count']})
def _storageOverflowMessage(self, data):
return self._buildMessage(data['event'], {'building': fort_fmts.getBuildingUserString(data['buildTypeID'])})
def _orderCanceledMessage(self, data):
import fortified_regions
buildTypeID = data['buildTypeID']
orderTypeID = fortified_regions.g_cache.buildings[buildTypeID].orderType
return self._buildMessage(data['event'], {'building': fort_fmts.getBuildingUserString(buildTypeID),
'order': fort_fmts.getOrderUserString(orderTypeID)})
def _reattachedToBaseMessage(self, data):
return self._buildMessage(data['event'], {'building': fort_fmts.getBuildingUserString(FORT_BUILDING_TYPE.MILITARY_BASE)})
def _defHourManipulationMessage(self, data):
return self._buildMessage(data['event'], {'defenceHour': fort_fmts.getDefencePeriodString(time_utils.getTimeTodayForUTC(data['defenceHour']))})
def _offDayActivatedMessage(self, data):
offDay = data['offDay']
if offDay == NOT_ACTIVATED:
return i18n.makeString(MESSENGER.SERVICECHANNELMESSAGES_FORT_NO_OFF_DAY_ACTIVATED)
if 'defenceHour' in data:
from gui.shared.fortifications.fort_helpers import adjustOffDayToLocal, adjustDefenceHourToLocal
offDayLocal = adjustOffDayToLocal(offDay, adjustDefenceHourToLocal(data['defenceHour'])[0])
else:
LOG_WARNING('_offDayActivatedMessage: received incorrect data, using offDay without adjustment... ', data)
offDayLocal = offDay
return self._buildMessage(data['event'], {'offDay': fort_fmts.getDayOffString(offDayLocal)})
def _vacationActivatedMessage(self, data):
return self._buildMessage(data['event'], {'finish': BigWorld.wg_getShortDateFormat(data['timeEnd'])})
def _vacationFinishedMessage(self, data):
return self._buildMessage(data['event'])
def _buildingDamagedMessage(self, data):
buildTypeID = data['buildTypeID']
if buildTypeID == FORT_BUILDING_TYPE.MILITARY_BASE:
return i18n.makeString('#messenger:serviceChannelMessages/fort/{0}_{1}'.format(SYS_MESSAGE_FORT_EVENT_NAMES[data['event']], FORT_BUILDING_TYPE_NAMES[FORT_BUILDING_TYPE.MILITARY_BASE]))
return self._buildMessage(data['event'], {'building': fort_fmts.getBuildingUserString(buildTypeID)})
def _orderCompensationMessage(self, data):
return self._buildMessage(data['event'], {'orderTypeName': fort_fmts.getOrderUserString(data['orderTypeID'])})
def _attackPlannedMessage(self, data):
return self._buildMessage(data['event'], {'clan': shared_fmts.getClanAbbrevString(data['defenderClanAbbrev']),
'date': BigWorld.wg_getShortDateFormat(data['timeAttack']),
'time': BigWorld.wg_getShortTimeFormat(data['timeAttack'])})
def _defencePlannedMessage(self, data):
return self._buildMessage(data['event'], {'clan': shared_fmts.getClanAbbrevString(data['attackerClanAbbrev']),
'date': BigWorld.wg_getShortDateFormat(data['timeAttack']),
'time': BigWorld.wg_getShortTimeFormat(data['timeAttack'])})
def _battleDeletedMessage(self, data):
return self._buildMessage(data['event'], {'clan': shared_fmts.getClanAbbrevString(data['enemyClanAbbrev'])})
def _specialReserveExpiredMessage(self, data):
resInc, resDec = data['resBonus']
resTotal = resInc - resDec
orderTypeID = data['orderTypeID']
messageKey = '#messenger:serviceChannelMessages/fort/SPECIAL_ORDER_EXPIRED_%s' % constants.FORT_ORDER_TYPE_NAMES[orderTypeID]
additional = ''
if resDec:
additional = i18n.makeString('%s_ADDITIONAL' % messageKey, resInc=BigWorld.wg_getIntegralFormat(resInc), resDec=BigWorld.wg_getIntegralFormat(resDec))
return i18n.makeString(messageKey, additional=additional, resTotal=BigWorld.wg_getIntegralFormat(resTotal))
def _resourceSetMessage(self, data):
try:
resourceDelta = data['resourceDelta']
if resourceDelta > 0:
messageKey = MESSENGER.SERVICECHANNELMESSAGES_FORT_PROM_RESOURCE_EARNED
else:
messageKey = MESSENGER.SERVICECHANNELMESSAGES_FORT_PROM_RESOURCE_WITHDRAWN
return i18n.makeString(messageKey, promresource=abs(resourceDelta))
except:
LOG_CURRENT_EXCEPTION()
def _reserveSetMessage(self, data):
try:
reserveDelta = data['reserveDelta']
if reserveDelta > 0:
messageKey = MESSENGER.SERVICECHANNELMESSAGES_FORT_RESERVES_EARNED
else:
messageKey = MESSENGER.SERVICECHANNELMESSAGES_FORT_RESERVES_WITHDRAWN
return i18n.makeString(messageKey, reserves=abs(reserveDelta))
except:
LOG_CURRENT_EXCEPTION()
class FortBattleResultsFormatter(ServiceChannelFormatter):
__battleResultKeys = {-1: 'battleFortDefeatResult',
0: 'battleFortDrawGameResult',
1: 'battleFortVictoryResult'}
def isNotify(self):
return True
def format(self, message, *args):
battleResult = message.data
if battleResult:
enemyClanAbbrev = battleResult.get('enemyClanName', '')
winnerCode = battleResult['isWinner']
if winnerCode == 0 and battleResult['attackResult'] == FORT_ATTACK_RESULT.TECHNICAL_DRAW:
winnerCode = -1
battleResult['isWinner'] = winnerCode
resourceKey = 'fortResourceCaptureByClan' if winnerCode > 0 else 'fortResourceLostByClan'
ctx = {'enemyClanAbbrev': shared_fmts.getClanAbbrevString(enemyClanAbbrev),
'resourceClan': BigWorld.wg_getIntegralFormat(battleResult.get(resourceKey, 0)),
'resourcePlayer': BigWorld.wg_getIntegralFormat(battleResult.get('fortResource', 0))}
ctx['achieves'] = self._makeAchievementsString(battleResult)
templateName = self.__battleResultKeys[winnerCode]
settings = self._getGuiSettings(message, templateName)
settings.setCustomEvent(MsgCustomEvents.FORT_BATTLE_FINISHED, battleResult.get('battleID'))
formatted = g_settings.msgTemplates.format(templateName, ctx=ctx, data={'savedData': {'battleResult': battleResult}})
return (formatted, settings)
else:
return (None, None)
@classmethod
def _makeAchievementsString(cls, battleResult):
result = []
for recordIdx, value in battleResult.get('popUpRecords', []):
recordName = DB_ID_TO_RECORD[recordIdx]
if recordName in IGNORED_BY_BATTLE_RESULTS:
continue
achieve = getAchievementFactory(recordName).create(value=value)
if achieve is not None and not achieve.isApproachable():
result.append(achieve)
if 'markOfMastery' in battleResult and battleResult['markOfMastery'] > 0:
achieve = getAchievementFactory((ACHIEVEMENT_BLOCK.TOTAL, 'markOfMastery')).create(value=battleResult['markOfMastery'])
if achieve is not None:
result.append(achieve)
res = ''
if len(result):
res = g_settings.htmlTemplates.format('battleResultAchieves', {'achieves': ', '.join(map(lambda a: a.getUserName(), sorted(result)))})
return res
class FortBattleRoundEndFormatter(ServiceChannelFormatter):
__battleResultKeys = {-1: 'combatFortTechDefeatResult',
1: 'combatFortTechVictoryResult'}
def isNotify(self):
return True
def format(self, message, *args):
battleResult = message.data
if battleResult is not None:
ctx = {}
winnerCode = battleResult['isWinner']
if winnerCode == 0:
winnerCode = -1
templateName = self.__battleResultKeys[winnerCode]
settings = self._getGuiSettings(message, templateName)
if 'combats' in battleResult:
_, _, _, isDefendersBuilding, buildTypeID = battleResult['combats']
if battleResult['isDefence'] is isDefendersBuilding:
buildOwnerClanAbbrev = battleResult['ownClanName']
else:
buildOwnerClanAbbrev = battleResult['enemyClanName']
ctx['fortBuilding'] = g_settings.htmlTemplates.format('battleResultFortBuilding', ctx={'fortBuilding': FortBuilding(typeID=buildTypeID).userName,
'clanAbbrev': '[%s]' % buildOwnerClanAbbrev})
else:
ctx['fortBuilding'] = ''
formatted = g_settings.msgTemplates.format(templateName, ctx=ctx)
return (formatted, settings)
else:
return (None, None)
class FortBattleInviteFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
from gui.prb_control.formatters.invites import PrbFortBattleInviteHtmlTextFormatter
battleData = message.data
if battleData:
inviteWrapper = self.__toFakeInvite(battleData)
formatter = PrbFortBattleInviteHtmlTextFormatter()
if message.createdAt is not None:
timestamp = time_utils.getTimestampFromUTC(message.createdAt.timetuple())
else:
timestamp = time_utils.getCurrentTimestamp()
msgType = 'fortBattleInvite'
battleID = battleData.get('battleID')
formatted = g_settings.msgTemplates.format(msgType, ctx={'text': formatter.getText(inviteWrapper)}, data={'timestamp': timestamp,
'savedData': {'battleID': battleID,
'peripheryID': battleData.get('peripheryID'),
'battleFinishTime': time_utils.getTimestampFromUTC(message.finishedAt.timetuple())},
'icon': formatter.getIconName(inviteWrapper)})
guiSettings = self._getGuiSettings(message, msgType)
guiSettings.setCustomEvent(MsgCustomEvents.FORT_BATTLE_INVITE, battleID)
return (formatted, guiSettings)
else:
return (None, None)
@classmethod
def __toFakeInvite(cls, battleData):
from gui.shared.ClanCache import g_clanCache
from gui.prb_control.invites import PrbInviteWrapper
return PrbInviteWrapper(clientID=-1, receiver=BigWorld.player().name, state=PREBATTLE_INVITE_STATE.ACTIVE, receiverDBID=BigWorld.player().databaseID, prebattleID=-1, receiverClanAbbrev=g_lobbyContext.getClanAbbrev(g_clanCache.clanInfo), peripheryID=battleData.get('peripheryID'), extraData=battleData, type=PREBATTLE_TYPE.FORT_BATTLE, alwaysAvailable=True)
class VehicleRentedFormatter(ServiceChannelFormatter):
_templateKey = 'vehicleRented'
def format(self, message, *args):
data = message.data
vehTypeCD = data.get('vehTypeCD', None)
expiryTime = data.get('expiryTime', None)
if vehTypeCD is not None:
return (self._getMessage(vehTypeCD, expiryTime), self._getGuiSettings(message, self._templateKey))
else:
return (None, None)
def _getMessage(self, vehTypeCD, expiryTime):
vehicleName = vehicles_core.getVehicleType(vehTypeCD).userString
ctx = {'vehicleName': vehicleName,
'expiryTime': TimeFormatter.getLongDatetimeFormat(expiryTime)}
return g_settings.msgTemplates.format(self._templateKey, ctx=ctx)
class RentalsExpiredFormatter(ServiceChannelFormatter):
_templateKey = 'rentalsExpired'
def format(self, message, *args):
vehTypeCD = message.data.get('vehTypeCD', None)
if vehTypeCD is not None:
return (self._getMessage(vehTypeCD), self._getGuiSettings(message, self._templateKey))
else:
return (None, None)
def _getMessage(self, vehTypeCD):
vehicleName = vehicles_core.getVehicleType(vehTypeCD).userString
ctx = {'vehicleName': vehicleName}
return g_settings.msgTemplates.format(self._templateKey, ctx=ctx)
class RefSystemReferralBoughtVehicleFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
settings = self._getGuiSettings(message, 'refSystemBoughtVehicle')
formatted = g_settings.msgTemplates.format('refSystemBoughtVehicle', {'userName': message.data.get('nickName', '')})
return (formatted, settings)
class RefSystemReferralContributedXPFormatter(ServiceChannelFormatter):
def isNotify(self):
return True
def format(self, message, *args):
data = message.data
settings = self._getGuiSettings(message, 'refSystemContributeXp')
formatted = g_settings.msgTemplates.format('refSystemContributeXp', {'userName': data.get('nickName', ''),
'xp': BigWorld.wg_getIntegralFormat(data.get('xp', 0))})
return (formatted, settings)
class RefSystemQuestsFormatter(TokenQuestsFormatter):
def _getTemplateName(self, completedQuestIDs = set()):
return 'refSystemQuests'
class PotapovQuestsFormatter(TokenQuestsFormatter):
def _getTemplateName(self, completedQuestIDs = set()):
return 'potapovQuests'
class GoodieRemovedFormatter(ServiceChannelFormatter):
def format(self, message, *args):
if message.data:
goodieID = message.data.get('gid', None)
if goodieID is not None:
booster = g_goodiesCache.getBooster(goodieID)
if booster is not None:
formatted = g_settings.msgTemplates.format('boosterExpired', ctx={'boosterName': booster.userName})
return (formatted, self._getGuiSettings(message, 'boosterExpired'))
return (None, None)
else:
return (None, None)
return
|
[
"info@webium.sk"
] |
info@webium.sk
|
7f3573b907615326768f9b99f8b75c8208c8dc62
|
15785beca775f85c596ba3a3897f199ba7a09281
|
/codes/test.smple.py
|
58aebb616b4032a236f7873fbb378ef098c0ad68
|
[] |
no_license
|
j4robot/tensorflow-with-tim
|
8b95576e736372414100c6da1f9a532aa9ea0636
|
e186d8c0cf0c0f59d734427616c7f3df438b8a26
|
refs/heads/master
| 2022-12-21T02:21:36.669877
| 2020-09-27T08:38:19
| 2020-09-27T08:38:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 520
|
py
|
def fashionably_late(arrivals, name):
"""Given an ordered list of arrivals to the party and a name, return whether the guest with that
name was fashionably late.
"""
print((len(arrivals) / 2))
return (arrivals.index(name) + 1 != len(arrivals)) and (arrivals.index(name) >= (len(arrivals) / 2))
party_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford']
s = ['Paul', 'John', 'Ringo', 'George']
print(fashionably_late(s, 'Ringo'))
#print(fashionably_late(party_attendees, 'Ford'))
|
[
"achanamosey@gmail.com"
] |
achanamosey@gmail.com
|
7a0776d75b4d09bb0af39d568c302ed5fb0984b3
|
9fa4091b49772208fd1caf0734603f8dd39f52a6
|
/api/migrations/0004_auto_20150701_1903.py
|
4b13f2b398753c6f4f5d1df07f8b6304d67d4c92
|
[] |
no_license
|
faderskd/Docs
|
e586454fcb15c7e9c0a2d6d97b6936d76b319c7a
|
9bd421af5afb3f839407653a8cdbc32ba0d7a7f3
|
refs/heads/master
| 2021-01-18T21:37:23.968717
| 2015-12-22T02:27:31
| 2015-12-22T02:27:31
| 38,111,451
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 990
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def copy_publishers(apps, schema_editor):
Book = apps.get_model("api", "Book")
for book in Book.objects.all():
authors = book.authors.all()
for author in authors:
author.publisher = book.publisher
author.save()
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20150626_1314'),
]
operations = [
migrations.AlterModelOptions(
name='author',
options={'ordering': ['salutation']},
),
migrations.AddField(
model_name='author',
name='publisher',
field=models.ForeignKey(to='api.Publisher', default=1),
preserve_default=False,
),
migrations.RunPython(copy_publishers),
migrations.RemoveField(
model_name='book',
name='publisher',
),
]
|
[
"daniel.faderski@gmail.com"
] |
daniel.faderski@gmail.com
|
09107cfb604f6b2991d2f609a97bce88bcd4bdc6
|
71115b689aeb58ece0e765b4589e5033d845e183
|
/scraper/export.py
|
20b2166fdf83b94cdee35a103e2c5a2f7a3165d4
|
[] |
no_license
|
fcpauldiaz-archive/CronService-Keydex
|
112d0331e982f274e8225ca88e5d892662a44dbe
|
60c43dfb217a0f168d57ed314c278c699da110e0
|
refs/heads/master
| 2021-03-19T10:47:03.922441
| 2017-08-26T18:50:41
| 2017-08-26T18:50:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,218
|
py
|
import os
import csv
from datetime import datetime
import psycopg2
import settings
from helpers import log
# conn = psycopg2.connect(database=settings.database, host=settings.host, user=settings.user, password=settings.password)
# cur = conn.cursor()
def dump_latest_scrape():
# Export everything
# cur.execute("SELECT products.* FROM products")
# Export only the latest crawl
# cur.execute("SELECT products.* FROM products JOIN (SELECT MAX(crawl_time) FROM products) AS p ON products.crawl_time = p.max;")
# Dedupe products on their primary_img URL
cur.execute("SELECT DISTINCT ON (primary_img) * FROM products;")
return cur.fetchall()
def write_to_csv(data):
file_name = "{}-amazon-crawl.csv".format(datetime.today().strftime("%Y-%m-%d"))
file_path = os.path.join(settings.export_dir, file_name)
with open(file_path, "w") as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
return file_path
if __name__ == '__main__':
log("Beginning export")
rows = dump_latest_scrape()
log("Got {} rows from database".format(len(rows)))
file_path = write_to_csv(rows)
log("Wrote data to {}".format(file_path))
|
[
"pablo5_diaz@hotmail.com"
] |
pablo5_diaz@hotmail.com
|
f9e315f18a0e2d73e3e4b70e0e87cc8893975c0c
|
e169045b956ec50bafae3c729281f260ac45778e
|
/algs_searchproblem.py
|
a43a9e9840538edd4768dec7d5faf2dfae67be1d
|
[] |
no_license
|
utmcontent/algs_poetry_whynotthisname
|
a10225d41dced525c00daa02c6c951f4752a1df9
|
39aa7ccb5d88451e851fec50438cbda71485e070
|
refs/heads/master
| 2023-02-12T14:48:45.899863
| 2020-10-19T19:51:57
| 2020-10-20T15:58:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 296
|
py
|
def x_2(a,b):
atob=[]
for i in a:
if i not in b:
for j in range(abs(a.count(i)-b.count(i))):
atob.append(i)
delete=[]
for i in b:
if i not in a:
for j in range(abs(a.count(i)-b.count(i))):
delete.append(i)
return atob,delete
class Ab(object):
def __init__(self):
pass
|
[
"d@d.com"
] |
d@d.com
|
c04b01aae7001bb9c75d374b42c6394111250b51
|
6bb08a716a718482ab36bead873abc8fd22131a2
|
/hello.py
|
75d2ed7a0b4ba06a27c290c89a0e53f543038335
|
[] |
no_license
|
RasulKg/intro2python
|
8692a9bafbc5df549cb24e41b50af86df6902346
|
c646fbc015b99839e2acdaa7f6e43f7a92ac1101
|
refs/heads/master
| 2021-01-10T16:14:55.034882
| 2015-12-14T08:42:57
| 2015-12-14T08:42:57
| 43,351,695
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 61
|
py
|
print "Enter your name",
name=raw_input()
print "hello", name
|
[
"mashanlo_r@12-04.iuca.loc"
] |
mashanlo_r@12-04.iuca.loc
|
27b5ab2a5b5b71f5124444c8ac9e574999e6b3de
|
e3365bc8fa7da2753c248c2b8a5c5e16aef84d9f
|
/indices/eth.py
|
4a292a43afe90a446c9d2d8144317014fb34d1a0
|
[] |
no_license
|
psdh/WhatsintheVector
|
e8aabacc054a88b4cb25303548980af9a10c12a8
|
a24168d068d9c69dc7a0fd13f606c080ae82e2a6
|
refs/heads/master
| 2021-01-25T10:34:22.651619
| 2015-09-23T11:54:06
| 2015-09-23T11:54:06
| 42,749,205
| 2
| 3
| null | 2015-09-23T11:54:07
| 2015-09-18T22:06:38
|
Python
|
UTF-8
|
Python
| false
| false
| 470
|
py
|
ii = [('FerrSDO3.py', 2), ('CookGHP.py', 1), ('PettTHE.py', 2), ('AubePRP.py', 2), ('FitzRNS3.py', 3), ('ClarGE2.py', 1), ('KiddJAE.py', 2), ('BailJD1.py', 2), ('CrokTPS.py', 1), ('WestJIT2.py', 1), ('MedwTAI.py', 1), ('WadeJEB.py', 1), ('FerrSDO2.py', 3), ('KirbWPW2.py', 1), ('WheeJPT.py', 1), ('MereHHB3.py', 4), ('MereHHB.py', 3), ('WilkJMC.py', 1), ('FitzRNS4.py', 1), ('CoolWHM3.py', 1), ('ThomGLG.py', 1), ('MereHHB2.py', 2), ('BrewDTO.py', 3), ('KeigTSS.py', 1)]
|
[
"prabhjyotsingh95@gmail.com"
] |
prabhjyotsingh95@gmail.com
|
40767c9568481a8c43dfe59b74dc14b435951af0
|
4185e7c695bbe41d0dd50e35bb54bdb76e3bd3ac
|
/scdc/initial/response.py
|
832abd113d53b0f0a83bbb3d8ffe991b3d961224
|
[] |
no_license
|
LBJ-Wade/LightDM_in_superconductor
|
4ccc3851a13fdd4382c0c7b06fbbc393f666482a
|
c559ed6cdbb7e70f09808d35312c494ca36b5a7d
|
refs/heads/main
| 2023-08-04T16:22:33.190430
| 2021-09-13T00:00:42
| 2021-09-13T00:00:42
| 408,343,124
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,554
|
py
|
"""This module defines coherence factors for use in computing the initial
angular distribution of excitations produced by a hard scatter."""
import tensorflow as tf
class ResponseFunction(object):
"""Base class for response functions."""
def __call__(self, r1, r2, q, omega):
"""Evaluate the response function.
Args:
r1 (float): magnitude of momentum of QP 1.
r2 (float): magnitude of momentum of QP 2.
q (float): magnitude of total momentum transfer.
omega (float): energy deposit.
Returns:
float: value of the response function.
"""
raise NotImplementedError
class HybridResponseFunction(ResponseFunction):
"""Approximate (BCS + Lindhard) response function.
This response function approximates the numerator of the loss function,
:math:`\mathrm{Im}(\epsilon_{\mathrm{BCS}})`, in terms of the BCS
coherence factor, yielding a response function of the form
:math:`F_{\mathrm{BCS}} / |\epsilon_{\mathrm{L}}|^2.`
Args:
material (:obj:`Material`): material object.
coherence_sign (int): sign in the coherence factor (1 or -1).
"""
def __init__(self, material, coherence_sign):
self.material = material
self.coherence_sign = coherence_sign
def __call__(self, r1, r2, q, omega):
return tf.abs(
self.material.coherence_uvvu(
self.coherence_sign, r1, r2
)
) / tf.abs(self.material.epsilon_lindhard(q, omega))**2
|
[
"benvlehmann@gmail.com"
] |
benvlehmann@gmail.com
|
3d366ea8ffb2b3fabe0d8947eb251746b25769d3
|
a74a0ec937006fb7e3ca18a430d422c1ce97faab
|
/labb7/labb7a.py
|
f627c3b76d172b04d0a4f5235c875688382ea259
|
[] |
no_license
|
GlockenGold/TDDE23
|
74e751bda91afde6e37b3bcaa8424982e9022bf8
|
e98b102296c03cb97185c33fb0e0b3506877d384
|
refs/heads/master
| 2022-04-13T01:53:56.518465
| 2020-03-26T21:10:59
| 2020-03-26T21:10:59
| 250,372,153
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,745
|
py
|
def search(pattern, db):
""" Returns all entries matching pattern in db """
books = []
for i in range(len(db)):
temp = match(db[i], pattern)
if temp:
books.append(db[i])
return books
def match(seq, pattern):
"""
Returns whether given sequence matches the given pattern
"""
if not pattern:
return not seq
elif isinstance(pattern[0], list):
if not seq:
return False
if isinstance(seq[0], list):
return match(seq[0], pattern[0]) and match(seq[1:], pattern[1:])
elif pattern[0] == '--':
if not seq:
if len(pattern) == 1:
return True
return False
elif match(seq, pattern[1:]):
return True
else:
return match(seq[1:], pattern)
elif not seq:
return False
elif pattern[0] == '&':
return match(seq[1:], pattern[1:])
elif seq[0] == pattern[0]:
return match(seq[1:], pattern[1:])
else:
return False
db = [[['författare', ['john', 'zelle']],
['titel', ['python', 'programming', 'an', 'introduction', 'to', 'computer', 'science']],
['år', 2010]],
[['författare', ['armen', 'asratian']],
['titel', ['diskret', 'matematik']],
['år', 2012]],
[['författare', ['j', 'glenn', 'brookshear']],
['titel', ['computer', 'science', 'an', 'overview']],
['år', 2011]],
[['författare', ['john', 'zelle']],
['titel', ['data', 'structures', 'and', 'algorithms', 'using', 'python', 'and', 'c++']],
['år', 2009]],
[['författare', ['anders', 'haraldsson']],
['titel', ['programmering', 'i', 'lisp']],
['år', 1993]]]
|
[
"glockengold19@live.se"
] |
glockengold19@live.se
|
795a9dfe379f8cccfc7570f3fa55b128860921e1
|
f93a67890e54736d88d927a6e375b167e28e18a2
|
/100Days/DataStructure/set.py
|
bd280cd85d3bead8d034d5becfad37b717cf250d
|
[] |
no_license
|
doubleZ0108/my-python-study
|
8b86e118239eefdc2dee7604448369f55515c02d
|
7ea30fe2c0518d23262fc89399949f21dac91d41
|
refs/heads/master
| 2021-07-03T02:08:35.159660
| 2020-10-07T15:42:26
| 2020-10-07T15:42:26
| 179,608,426
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 653
|
py
|
# 数据结构
## 集合
set1 = {1,2,1,1,2,3} # 去重
len(set1) # [Output]: 3
set2 = set(range(1,11))
### 添加元素
set1.add(4)
set1.add(3)
set2.update([11,12])
### 删除元素
set2.discard(5)
set2.discard(100)
# set2.remove(888) # remove的元素如果不存在会引发KeyError
set1.pop() # 删除第一个元素 -> 1
## 集合运算
# 交
set1 & set2
set1.intersection(set2)
# 并
set1 | set2
set1.union(set2)
# 差
set1 - set2
set1.difference(set2)
# 对称差
set1 ^ set2
set2.symmetric_difference(set2)
# 子集
set1 < set2
set1.issubset(set2)
# 真子集
set1 <= set2
set1.issuperset(set2)
print(set1)
print(set2)
|
[
"noreply@github.com"
] |
doubleZ0108.noreply@github.com
|
232137fe99281193eee58f17e65cc65bf909a510
|
72a729ba2c983f2892043b12d924390ecd8d381a
|
/ex8.py
|
45867536faf584f548c9c0531baf0e1458088152
|
[] |
no_license
|
jskescola/exercicios_python_1-10
|
e16118d3e929a2a679e902fbc34fd1b3ea2d536f
|
bcace34d28a40d52c5f97e5b895cb25b3566c0c8
|
refs/heads/main
| 2023-06-29T05:19:48.782802
| 2021-08-02T12:12:09
| 2021-08-02T12:12:09
| 391,932,942
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 266
|
py
|
#8. Desenvolva um programa que receba duas notas de um aluno e calcule sua média.
nota1 = float(input('Digite a primeira nota do aluno:'))
nota2 = float(input('Digite a segunda nota do aluno:'))
print('A média do aluno foi de: {:.1f}'.format((nota1+nota2)/2))
|
[
"noreply@github.com"
] |
jskescola.noreply@github.com
|
6dc6c66022879503e8e6ed4991cf188bd229eabe
|
7029ca0804fd9440151736f3609e8b99e04c28f9
|
/models.py
|
9544bad927fc6c7db758f97f211d89b9a85803b7
|
[
"MIT"
] |
permissive
|
michaelzhou0723/proxprop
|
a27a8f0687d80ed7b73c739c7b0176fd95143b51
|
42ce2800564f2d4bd13d5e00ed70a745e8d630d2
|
refs/heads/master
| 2020-05-27T18:03:40.813381
| 2019-03-17T18:58:52
| 2019-03-17T18:58:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,176
|
py
|
from functools import reduce
from operator import mul
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.utils.data as data
import torch.nn.functional as F
from torch.autograd import Variable
from ProxProp import ProxPropLinear, ProxPropConv2d
class ProxPropConvNet(nn.Module):
def __init__(self, input_size, num_classes, tau_prox, optimization_mode='prox_cg1'):
super(ProxPropConvNet, self).__init__()
img_dim = input_size[0]
self.layers = nn.Sequential(
ProxPropConv2d(img_dim, 16, kernel_size=5, tau_prox=tau_prox, padding=2, optimization_mode=optimization_mode),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
ProxPropConv2d(16, 20, kernel_size=5, tau_prox=tau_prox, padding=2, optimization_mode=optimization_mode),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
ProxPropConv2d(20, 20, kernel_size=5, tau_prox=tau_prox, padding=2, optimization_mode=optimization_mode),
nn.ReLU()
)
self.final_fc = nn.Linear(input_size[1]*input_size[2]//16 * 20 , 10)
def forward(self, x):
x = self.layers(x)
return self.final_fc(x.view(x.size(0), -1))
class ProxPropMLP(nn.Module):
def __init__(self, input_size, hidden_sizes, num_classes, tau_prox=1., optimization_mode='prox_cg1'):
super(ProxPropMLP, self).__init__()
input_size_flat = reduce(mul, input_size, 1)
self.layers = []
self.layers.append(ProxPropLinear(input_size_flat, hidden_sizes[0], tau_prox=tau_prox, optimization_mode=optimization_mode))
for k, _ in enumerate(hidden_sizes[:-1]):
self.layers.append(ProxPropLinear(hidden_sizes[k], hidden_sizes[k+1], tau_prox=tau_prox, optimization_mode=optimization_mode))
self.layers = nn.ModuleList(self.layers)
self.final_fc = nn.Linear(hidden_sizes[-1], num_classes)
self.relu = nn.ReLU()
def forward(self, x):
x = x.view(x.size(0), -1)
for layer in self.layers:
x = layer(x)
x = self.relu(x)
x = self.final_fc(x)
return x
|
[
"thomas.frerix@tum.de"
] |
thomas.frerix@tum.de
|
1c10c895290852f2ecfd26e2b92da019494cea1c
|
18fd4062e7bdc626df99229eba78affa9b94859b
|
/flaskk/signals.py
|
26c50cddb1a0a666f07caa501f7bbcae25547fce
|
[] |
no_license
|
root-sudip/Search-Engine
|
57290708924895a4d26dc5252a0300453b7d7b31
|
e24db9e14e3330b59f140269cbd687ab338e95d6
|
refs/heads/master
| 2021-01-20T05:52:41.168438
| 2017-05-11T11:29:38
| 2017-05-11T11:29:38
| 89,817,062
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,155
|
py
|
# -*- coding: utf-8 -*-
"""
flask.signals
~~~~~~~~~~~~~
Implements signals based on blinker if available, otherwise
falls silently back to a noop.
:copyright: (c) 2015 by Sudip Das.
"""
signals_available = False
try:
from blinker import Namespace
signals_available = True
except ImportError:
class Namespace(object):
def signal(self, name, doc=None):
return _FakeSignal(name, doc)
class _FakeSignal(object):
"""If blinker is unavailable, create a fake class with the same
interface that allows sending of signals but will fail with an
error on anything else. Instead of doing anything on send, it
will just ignore the arguments and do nothing instead.
"""
def __init__(self, name, doc=None):
self.name = name
self.__doc__ = doc
def _fail(self, *args, **kwargs):
raise RuntimeError('signalling support is unavailable '
'because the blinker library is '
'not installed.')
send = lambda *a, **kw: None
connect = disconnect = has_receivers_for = receivers_for = \
temporarily_connected_to = connected_to = _fail
del _fail
# The namespace for code signals. If you are not flask code, do
# not put signals in here. Create your own namespace instead.
_signals = Namespace()
# Core signals. For usage examples grep the source code or consult
# the API documentation in docs/api.rst as well as docs/signals.rst
template_rendered = _signals.signal('template-rendered')
before_render_template = _signals.signal('before-render-template')
request_started = _signals.signal('request-started')
request_finished = _signals.signal('request-finished')
request_tearing_down = _signals.signal('request-tearing-down')
got_request_exception = _signals.signal('got-request-exception')
appcontext_tearing_down = _signals.signal('appcontext-tearing-down')
appcontext_pushed = _signals.signal('appcontext-pushed')
appcontext_popped = _signals.signal('appcontext-popped')
message_flashed = _signals.signal('message-flashed')
|
[
"touch.das@gmail.com"
] |
touch.das@gmail.com
|
5012216c82fce82b5a70774eb214395a73364ceb
|
3846dc3c1597d7728ddae16fbdcd4b5f6f745124
|
/benchmark/__init__.py
|
8371bc9a56e99e85960b8b037c45751783d093b5
|
[
"MIT"
] |
permissive
|
OldhamMade/exemelopy
|
f4d49462333cd6e821651df188a7848bc18d213d
|
5f5141b169e61a5b6912146a995917f5d862ee9c
|
refs/heads/master
| 2020-03-25T13:08:34.010844
| 2015-02-20T16:41:54
| 2015-02-20T16:41:54
| 1,250,062
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 160
|
py
|
from basic import BasicBenchmark
def main():
print 'Running benchmarks, please wait...'
BasicBenchmark().run()
if __name__ == '__main__':
main()
|
[
"phillip.oldham@gmail.com"
] |
phillip.oldham@gmail.com
|
7ee1eb09f3b377ee80873031e80cd55c2156a3e4
|
c27ea1b4a7947e850947d74508376f2658cb3fcc
|
/src/lib/item_utils.py
|
a026ceb2326990df6afdc797053052d0229b2aa8
|
[] |
no_license
|
bmdeveloppement/back_boe
|
6441dc33ff13ececf582eac5146f106dd5152a72
|
6172886b55472f327d9a3c0d5c029998cc6e06bd
|
refs/heads/master
| 2021-01-10T21:06:40.869072
| 2014-04-20T22:18:57
| 2014-04-20T22:18:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
# -*- coding: utf-8 -*-
def copy_items(from_obj, to_obj, items):
for item in items:
setattr(to_obj, item, from_obj[item])
|
[
"benoit.minard+1@gmail.com"
] |
benoit.minard+1@gmail.com
|
f2da3199f091814377b762e379e23c9ca123ddca
|
e2dc65bbd279b137f40ed4991cb00cecc28ad5ac
|
/venv/Scripts/rstpep2html.py
|
ce50914731eafffa0dc6d291dd8af68885d67712
|
[] |
no_license
|
zaka1/mj
|
79278a22355f261d157e591bfc9b06c7f6d5ae39
|
f43a2f205adcb2312db5d526f7432d7853be8afd
|
refs/heads/master
| 2021-01-11T10:19:09.487400
| 2016-11-05T09:01:11
| 2016-11-05T09:01:11
| 72,414,237
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 683
|
py
|
#!d:\mj\venv\scripts\python.exe
# $Id: rstpep2html.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing HTML from PEP
(Python Enhancement Proposal) documents.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates (X)HTML from reStructuredText-format PEP files. '
+ default_description)
publish_cmdline(reader_name='pep', writer_name='pep_html',
description=description)
|
[
"q2821408@yahoo.com.tw"
] |
q2821408@yahoo.com.tw
|
c93284732df89aa3c501500bf7a55d041b53fb72
|
f77028577e88d228e9ce8252cc8e294505f7a61b
|
/web_backend/backend_services/nvl_tracker_service/---nvltracker_server_specification.py
|
68efc79edf49df6b881f5f66c3a0c9d30b4aa1cf
|
[] |
no_license
|
Sud-26/Arkally
|
e82cebb7f907a3869443b714de43a1948d42519e
|
edf519067d0ac4c204c12450b6f19a446afc327e
|
refs/heads/master
| 2023-07-07T02:14:28.012545
| 2021-08-06T10:29:42
| 2021-08-06T10:29:42
| 392,945,826
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,146
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '0.1.0'
# INSERT IN TO HW MODULE POSITION VIEW -> NOT USER ANY MORE
# TODO: REMOVE UNNECESSARY CODE
query_str_detect = """
INSERT INTO hw_module_position_view
(traceable_object_id, hw_module_id, position, raw_nmea,
meta_information, show_on_map, active, deleted, created_on, updated_on, record_time)
SELECT hm.traceable_object_id,
hm.id,
ST_SetSRID(ST_MakePoint(%s,%s), 4326), %s, %s,
hm.show_on_map, TRUE, FALSE, now(), now(), now()
FROM public.hw_module AS hm
WHERE hm.module_id = %s
AND hm.active IS TRUE
AND hm.deleted IS FALSE
RETURNING *;
"""
# INSERT IN TO HW MODULE USER POSITION VIEW
create_hw_module_user_position_element_query = """
INSERT INTO hw_module_user_position_view
(user_id, traceable_object_id, hw_module_id, position, raw_nmea,
meta_information, show_on_map, active, deleted, created_on, updated_on, record_time)
SELECT hm.user_id,
hm.traceable_object_id,
hm.id,
ST_SetSRID(ST_MakePoint(%s,%s), 4326), %s,
%s, hm.show_on_map, TRUE, FALSE, now(), now(), now()
FROM public.hw_module AS hm
WHERE hm.module_id = %s
AND hm.active IS TRUE
AND hm.deleted IS FALSE
RETURNING *;
"""
# TODO: REMOVE UNUSED CODE
query_intersect = """
SELECT clc, command_value, proto_field, action_id FROM(
SELECT ST_Intersects(un.pos, un.area_dta) AS clc, un.command_value, un.proto_field, un.action_id
FROM (
SELECT hac.geom AS area_dta, hac.command_value, pos.pos, hac.proto_field, hac.action_id
FROM public.user_hw_action_collection AS hac
CROSS JOIN (
SELECT hmp.position AS pos, hw_module_id
FROM public.hw_module_user_position AS hmp
WHERE hmp.id = %s) AS pos
WHERE hac.action_id not in (2, 8)
AND pos.hw_module_id = ANY(hac.hw_list)
) AS un
) as dta
WHERE dta.clc is TRUE;
"""
# TODO: REMOVE UNUSED QUERY
# query_find_command_for_device = """
# SELECT uhc.id AS id,
# uhc.proto_field AS proto_field,
# uhc.field_type as field_type,
# uhc.value as field_value,
# uhc.ack_message as ack_message
# FROM public.user_hw_command AS uhc
# WHERE uhc.state = 'pending'
# AND uhc.hw_module_id in (
# SELECT id
# from public.hw_module AS hm
# WHERE hm.active IS TRUE
# AND hm.deleted is FALSE
# AND hm.module_id = %s
#
# LIMIT 1
# )
# order by created_on asc
# LIMIT 1;
# """
query_find_command_for_device = """
SELECT uhc.id AS id,
uhc.proto_field AS proto_field,
uhc.field_type as field_type,
uhc.value as field_value,
uhc.ack_message as ack_message,
uhc.date_from,
uhc.date_to
FROM public.user_hw_command AS uhc
WHERE uhc.state = 'pending'
AND uhc.date_to >= now() - '3 seconds'::interval and date_to <= now() + '3 seconds'::interval
--AND uhc.date_to >= now()
AND uhc.date_from <= now()
AND uhc.hw_module_id in (
SELECT id
from public.hw_module AS hm
WHERE hm.active IS TRUE
AND hm.deleted is FALSE
AND hm.module_id = %s
LIMIT 1
)
order by date_to asc
LIMIT 1;
"""
query_change_command_state_for_device = """
UPDATE public.user_hw_command AS uhc
SET state = 'executed',
updated_on = now()
WHERE id = %s
AND hw_module_id in (
SELECT id
from public.hw_module AS hm
WHERE hm.active IS TRUE
AND hm.deleted is FALSE
AND hm.module_id = %s
LIMIT 1
)
RETURNING *
"""
check_collision_avoidance_system_query = """
SELECT tob.collision_avoidance_system AS collision_avoidance_system,
hm.traceable_object_id AS traceable_object_id,
hm.id AS hw_module_id,
hm.module_id AS hw_module_module_id
FROM public.traceable_object AS tob
LEFT OUTER JOIN public.hw_module AS hm ON tob.id = hm.traceable_object_id
WHERE hm.module_id = %s
"""
# INSERT OD UPDATE CAS TABLE TODO: REMOVE
# upsert_collision_avoidance_system_last_point_query = """
# INSERT INTO hw_cas (
# hw_module_id, position, record_time, active, deleted, created_on, updated_on) VALUES (
# %s, ST_SetSRID(ST_MakePoint(%s,%s), 4326), %s, True, False, now(), now())
# ON CONFLICT(hw_module_id) DO UPDATE SET position= ST_SetSRID(ST_MakePoint(%s,%s), 4326),
# record_time = %s, updated_on = now();
# """
# INSERT OD UPDATE CAS TABLE
upsert_collision_avoidance_system_last_point_query = """
INSERT INTO hw_cas (
hw_module_id, position, record_time, active, deleted, created_on, updated_on)
(SELECT hm.id , ST_SetSRID(ST_MakePoint(%s,%s), 4326), %s, True, False, now(), now() FROM public.hw_module as hm
WHERE hm.module_id = %s)
ON CONFLICT(hw_module_id) DO UPDATE SET position= ST_SetSRID(ST_MakePoint(%s,%s), 4326),
record_time = %s, updated_on = now() RETURNING *;
"""
# TODO: CURRENTLY UNUSED REMOVE IN PRODUCTION
get_low_speed_on_poly_intersect_query = """
SELECT min(fin.command_value) FROM (
SELECT ST_Intersects(un.pos, un.area_dta), un.command_value
FROM (
SELECT hac.geom AS area_dta, hac.command_value, pos
FROM public.user_hw_action_collection AS hac
CROSS JOIN (
SELECT hmp.position AS pos
FROM public.hw_module_user_position AS hmp
LEFT OUTER JOIN hw_module AS hm ON hm.id = hmp.hw_module_id
WHERE hm.module_id = %s
ORDER BY record_time DESC LIMIT 1
) AS pos
) AS un
) as fin
WHERE fin.st_intersects IS TRUE;
"""
# GET CALCULATED THROTTLE VALUE
get_throttle_value_for_hw_module_module_id_query = """
SELECT * FROM get_throttle_value(%s, %s, %s, %s);
"""
create_hw_command_element_query = """
INSERT INTO public.user_hw_command
(user_id, hw_action_id, hw_module_id, proto_field, field_type,
value, active, deleted, created_on, updated_on,
ack_message, state, date_from, date_to, traceable_object_id)
SELECT hm.user_id,
8,
hm.id,
'throttle',
'bool',
%s,
TRUE,
FALSE,
now(),
now(),
True,
'pending',
now(),
now(),
hm.traceable_object_id
FROM public.hw_module AS hm
WHERE hm.module_id = %s
AND hm.active IS TRUE
AND hm.deleted IS FALSE
RETURNING *;
"""
create_hw_command_element_on_intersect_query = """
INSERT INTO public.user_hw_command
(user_id, hw_action_id, hw_module_id, proto_field, field_type,
value, active, deleted, created_on, updated_on,
ack_message, state, date_from, date_to, traceable_object_id)
SELECT hm.user_id,
%s,
hm.id,
%s,
'bool',
%s,
TRUE,
FALSE,
now(),
now(),
True,
'pending',
now(),
now(),
hm.traceable_object_id
FROM public.hw_module AS hm
WHERE hm.module_id = %s
AND hm.active IS TRUE
AND hm.deleted IS FALSE
RETURNING *;
"""
last_device_lock_state_query = """
SELECT uhc.value FROM public.user_hw_command AS uhc
LEFT OUTER JOIN public.hw_module AS hm ON uhc.hw_module_id = hm.id
WHERE uhc.state = 'executed' AND uhc.hw_action_id = 5
AND hm.module_id = %s
ORDER BY uhc.updated_on DESC
LIMIT 1;
"""
|
[
"sudhakar@satmatgroup.com"
] |
sudhakar@satmatgroup.com
|
fe7f6915772aad3000be35c9ad18bfbfe1c29a61
|
f51505ad716c39b22a5577ff7431ccbe87dec67e
|
/assignments/models.py
|
97bbcf8e72718257fbc5013ff67f3002bcc9d9b3
|
[] |
no_license
|
klenth/demo_assignment_tracker
|
d9c8524e751d068372e8e54b33efa37be10e2d60
|
cf48a9f00470d1cd0e9dad872d5d969ebe63d44d
|
refs/heads/main
| 2023-08-14T14:15:36.526973
| 2021-09-14T18:47:18
| 2021-09-14T18:47:18
| 401,784,423
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 522
|
py
|
from django.db import models
# Create your models here.
class Course(models.Model):
title = models.CharField(max_length=64, null=False, blank=False)
def __str__(self):
return self.title
class Assignment(models.Model):
course = models.ForeignKey(to=Course, null=False, on_delete=models.CASCADE)
title = models.CharField(max_length=64, null=False, blank=False)
due_date = models.DateField()
complete = models.BooleanField(default=False)
def __str__(self):
return self.title
|
[
"klenth@westminstercollege.edu"
] |
klenth@westminstercollege.edu
|
13345717d13107aaef24ff6a218de02358738b3b
|
57c64accbc491e8fb1d026a93d189f68c72287b3
|
/trabalho/trabalho/wsgi.py
|
8d4a35ea812eb43e517db437b139d6929b02fd19
|
[
"Apache-2.0"
] |
permissive
|
Sparks-FIT/-404-----LMS-
|
fe0663de8a47fb1a336f3027725a27ef6fae6616
|
bb429cf07aef6dfc90baa97591c05c09fb24b6d4
|
refs/heads/master
| 2021-08-22T04:56:21.793102
| 2017-11-29T10:36:37
| 2017-11-29T10:36:37
| 110,590,395
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 410
|
py
|
"""
WSGI config for trabalho project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trabalho.settings")
application = get_wsgi_application()
|
[
"noreply@github.com"
] |
Sparks-FIT.noreply@github.com
|
8f2019f8cd0d5dc06b763af7e26628a31820a729
|
9d0ef5976b977338c05aca3931c8fab1a94de4de
|
/Decision Trees/metrics.py
|
b8cbf3c24fcdcbc9f1c540972d37d42dd4144a8a
|
[] |
no_license
|
Flishworks/Machine-Learning
|
0eef1f480c04f15ac038877f99874ecb8ec75f6e
|
a7f719550a25b15d26cdf364c691aef5d1c1745b
|
refs/heads/master
| 2020-06-08T20:39:06.385960
| 2019-06-23T03:44:02
| 2019-06-23T03:44:02
| 193,303,054
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,844
|
py
|
import numpy as np
def confusion_matrix(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the confusion matrix. The confusion
matrix for a binary classifier would be a 2x2 matrix as follows:
[
[true_negatives, false_positives],
[false_negatives, true_positives]
]
YOU DO NOT NEED TO IMPLEMENT CONFUSION MATRICES THAT ARE FOR MORE THAN TWO
CLASSES (binary).
Compute and return the confusion matrix.
Args:
actual (np.array): predicted labels of length N
predictions (np.array): predicted labels of length N
Output:
confusion_matrix (np.array): 2x2 confusion matrix between predicted and actual labels
"""
if predictions.shape[0] != actual.shape[0]:
raise ValueError("predictions and actual must be the same length!")
true = predictions[actual[:] == predictions[:]]
false = predictions[actual[:] != predictions[:]]
confusion = np.array([len(true[true[:] == 0]),len(false[false[:] == 1]), len(false[false[:] == 0]), len(true[true[:] == 1])])
return confusion.reshape(2,2)
def accuracy(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the accuracy:
Hint: implement and use the confusion_matrix function!
Args:
actual (np.array): predicted labels of length N
predictions (np.array): predicted labels of length N
Output:
accuracy (float): accuracy
"""
if predictions.shape[0] != actual.shape[0]:
raise ValueError("predictions and actual must be the same length!")
assert len(predictions) > 0, "prediction vector cannot be of length zero"
return len(predictions[actual[:] == predictions[:]])/len(predictions)
def precision_and_recall(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the precision and recall:
https://en.wikipedia.org/wiki/Precision_and_recall
Hint: implement and use the confusion_matrix function!
Args:
actual (np.array): predicted labels of length N
predictions (np.array): predicted labels of length N
Output:
precision (float): precision
recall (float): recall
"""
if predictions.shape[0] != actual.shape[0]:
raise ValueError("predictions and actual must be the same length!")
confusion = confusion_matrix(actual, predictions)
#[true_negatives, false_positives],
#[false_negatives, true_positives]
tp = confusion[1,1]
tp = 0 if np.isnan(tp) else tp
fp = confusion[0,1]
fp = 0 if np.isnan(fp) else fp
fn = confusion[1,0]
fn = 0 if np.isnan(fn) else fn
if (tp+fp)>0:
precision = tp/(tp+fp)
else:
precision = 0
if (tp+fn)>0:
recall = tp/(tp+fn)
else:
recall = 0
return precision, recall
def f1_measure(actual, predictions):
"""
Given predictions (an N-length numpy vector) and actual labels (an N-length
numpy vector), compute the F1-measure:
https://en.wikipedia.org/wiki/Precision_and_recall#F-measure
Hint: implement and use the precision_and_recall function!
Args:
actual (np.array): predicted labels of length N
predictions (np.array): predicted labels of length N
Output:
f1_measure (float): F1 measure of dataset (harmonic mean of precision and
recall)
"""
if predictions.shape[0] != actual.shape[0]:
raise ValueError("predictions and actual must be the same length!")
precision, recall = precision_and_recall(actual, predictions)
if (precision+recall) > 0:
return 2*precision*recall/(precision+recall)
else:
return 0
|
[
"akazen@northwestern.edu"
] |
akazen@northwestern.edu
|
75783a7101f7271039173747d73fbd0e2ac83521
|
7132d06b8ae153815d124007c28bfe43686beb88
|
/scripts/gen_hdf5_from_b.py
|
2617502a8af985c54d16d4b719a973be3595a8d6
|
[] |
no_license
|
Rogety/TTS_DNN
|
a075aca2df0d100389a9cf323fa5b10cced8c61d
|
b84ed59664aa8c2eca7030c5f3b992a81da910c3
|
refs/heads/main
| 2023-07-22T20:48:12.400111
| 2021-09-03T13:49:06
| 2021-09-03T13:49:06
| 399,358,628
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,940
|
py
|
import os
import sys
import h5py
import numpy as np
from os import path
import tts
import json
import argparse as ap
import torch as th
import torch.utils.data as data
import torch.optim as optim
import pdb
import shutil
import utils as ut
'''
SaveDirectory = os.getcwd()
print(SaveDirectory)
#h = ut.read_hdf5( "../tr_slt/arctic_a0001.h5", "/world")
#print(h)
#print(h.shape)
f1 = h5py.File( "../tr_slt/arctic_a0001.h5", "r")
f2 = h5py.File( "../tr_slt/stats.h5", "r")
for key in f1.keys():
print(f1[key].name)
print(f1[key].shape)
#print(f[key].value)
for key in f2.keys():
print(f2[key].name)
#print(f2[key].shape)
#print(f2[key].value)
print(f2)
group2 = f2.get('world/scale')
print(group2)
uv_fn = File.join(gen_dir_path, "#{base}.uv")
f0_mlpg_fn = File.join(gen_dir_path, "#{base}.lf0.mlpg")
mgc_mlpg_fn = File.join(gen_dir_path, "#{base}.mgc.mlpg")
'''
'''
with open(path.join("configs","IOConfigs.json")) as io_configs_file:
io_configs = json.load(io_configs_file)
a_order = io_configs["a_order"]
b_order = io_configs["b_order"]
c_order = io_configs["c_order"]
d_order = io_configs["d_order"]
d_class = io_configs["d_class"]
SaveDirectory = os.getcwd()
print("curren directory : " , SaveDirectory)
source_dir_path = path.join("gen","source","from_a")
gen_dir_path = path.join("gen","source","hdf5")
print("source_dir_path :",source_dir_path)
print("gen_dir_path :",gen_dir_path)
if not path.isdir(source_dir_path):
os.mkdir(source_dir_path)
if not path.isdir(gen_dir_path):
os.mkdir(gen_dir_path)
lf0_mlpg = []
mgc_mlpg = []
uv = []
for root, dirs, files in os.walk(source_dir_path, topdown=False):
for name in files:
path = os.path.join(root, name)
if name.endswith(".lf0.mlpg"):
lf0_mlpg.append(path)
if name.endswith(".mgc.mlpg"):
mgc_mlpg.append(path)
if name.endswith(".uv"):
uv.append(path)
a = tts.load_bin( lf0_mlpg[0], 'float32').view(-1,a_order)
print(a.shape)
'''
parser = ap.ArgumentParser()
parser.add_argument("--source", action="store_true")
parser.add_argument("--target", action="store_true")
args = parser.parse_args()
with open(path.join("configs","Configs.json")) as configs_file:
configs = json.load(configs_file)
with open(path.join("configs","IOConfigs.json")) as io_configs_file:
io_configs = json.load(io_configs_file)
a_order = io_configs["a_order"]
b_order = io_configs["b_order"]
c_order = io_configs["c_order"]
d_order = io_configs["d_order"]
mgc_order = configs["mgc_order"]
lf0_order = configs["lf0_order"]
hidden_size = configs["hidden_size"]
use_cuda = configs["use_cuda"]
sampling_rate = configs["sampling_rate"]
frame_shift = configs["frame_shift"]
number_of_states = configs["number_of_states"]
model_dir_path = path.join("model")
state_in_phone_min = configs["state_in_phone_min"]
state_in_phone_max = configs["state_in_phone_max"]
frame_in_state_min = configs["frame_in_state_min"]
frame_in_state_max = configs["frame_in_state_max"]
frame_in_phone_min = configs["frame_in_phone_min"]
frame_in_phone_max = configs["frame_in_phone_max"]
if args.source:
a_dir_path = path.join("data","source","set","a")
b_dir_path = path.join("data","source","set","b")
stat_dir_path = path.join("data","source", "stat")
gen_dir_path = path.join("gen", "hdf5_DNN")
trn_hdf5_path = path.join(gen_dir_path,"tr_slt")
ev_hdf5_path = path.join(gen_dir_path,"ev_slt")
hdf5_path = path.join(gen_dir_path,"hdf5")
var_path = path.join(stat_dir_path, "c_trn_var.pt")
dur_state_dict_path = path.join(model_dir_path, "dur.state_dict")
am_state_dict_path = path.join(model_dir_path, "am.state_dict")
device = th.device("cuda" if use_cuda else "cpu")
variance = th.load(var_path)
dur_model = tts.DurationModel( b_order, hidden_size).to(device)
am_model = tts.AcousticModel( a_order, hidden_size, c_order, variance=variance).to(device)
dur_state_dict = th.load(dur_state_dict_path )
am_state_dict = th.load( am_state_dict_path )
dur_model.load_state_dict(dur_state_dict)
am_model.load_state_dict(am_state_dict)
if os.path.isdir(trn_hdf5_path) != True:
os.makedirs(trn_hdf5_path)
if os.path.isdir(ev_hdf5_path) != True:
os.makedirs(ev_hdf5_path)
if os.path.isdir(hdf5_path) != True:
os.makedirs(hdf5_path)
hdf5_filename_list = []
with th.no_grad():
var_lf0_mgc = variance[0:c_order-1].view(1,3, (lf0_order+mgc_order))
for filename in sorted(os.listdir(a_dir_path)):
if filename.endswith(".bin"):
base = path.splitext(filename)[0]
b_path = path.join(b_dir_path, "{}.bin".format(base))
b = ut.load_binfile(b_path)
b = np.asarray(b,dtype=np.float32)
b = np.reshape(b , (-1,b_order))
b = th.from_numpy(b)
b = b.to(device)
#d = dur_model(b).argmax(1, keepdim=False).view(-1, number_of_states)
d = dur_model(b).round().int().view(-1, number_of_states)
#print("d:",d.shape)
#import pdb; pdb.set_trace()
# 去掉 語速資訊
#b = b[:,0: b_order-1].view(-1, number_of_states, b_order-1)
b = b[:,0: b_order].view(-1, number_of_states, b_order)
a = []
for (phone_index, phone) in enumerate(d):
# shape = (number_of_states, b_order-1)
ans_of_cur_phone = b[phone_index]
total_frames_in_phone = phone.sum().item()
cur_frame_in_phone = 0
for (state_index, state) in enumerate(phone):
#(b_order-1)
ans_of_cur_state = ans_of_cur_phone[state_index]
total_frames_in_state = state.item()
for frame_index in range(0,total_frames_in_state):
ans_of_cur_frame = ans_of_cur_state.clone()
frame_in_state_fwd_n = (frame_index) / (frame_in_state_max-frame_in_state_min)
frame_in_state_bwd_n = (total_frames_in_state - frame_index - frame_in_state_min) / (frame_in_phone_max-frame_in_phone_min)
frame_in_phone_fwd_n = (cur_frame_in_phone) / (frame_in_phone_max - frame_in_phone_min)
frame_in_phone_bwd_n = (total_frames_in_phone - cur_frame_in_phone - frame_in_phone_min ) / (frame_in_phone_max-frame_in_phone_min)
frame_info = ans_of_cur_frame.new([frame_in_state_fwd_n, frame_in_state_bwd_n, frame_in_phone_fwd_n, frame_in_phone_bwd_n])
a.append( th.cat( (ans_of_cur_state, frame_info) ) )
cur_frame_in_phone += 1
a = th.stack(a)
c_ = am_model(a)
feat = c_.cpu()
print("feat : ",feat.shape)
#import pdb; pdb.set_trace()
hdf5_filename = path.join(hdf5_path,base) + ".h5"
# print(hdf5_filename)
hdf5_filename_list.append(hdf5_filename)
if os.path.isdir(gen_dir_path) != True:
os.makedirs(gen_dir_path)
print(hdf5_filename)
with h5py.File(hdf5_filename , 'w') as hdf :
#hdf['world'] = feat
G4 = hdf.create_dataset('world' , data = feat)
print("write {}.h5 finished".format(base))
'''
with h5py.File(hdf5_filename , 'r') as hdf :
base_items= list(hdf.items())
print("items in the base directory: ", base_items)
lf0 = hdf.get('lf0')
G2_items = list(lf0.items())
print('Items in mean: ', G2_items)
dataset3 = np.array(lf0.get('mean'))
dataset4 = np.array(lf0.get('variance'))
print(dataset3.shape)
print(dataset4.shape)
'''
if os.path.isdir(trn_hdf5_path) != True:
os.makedirs(trn_hdf5_path)
if os.path.isdir(ev_hdf5_path) != True:
os.makedirs(ev_hdf5_path)
dataset_num = 1132 ## 1132
trn_num = 1028 # 1028
ev_num = dataset_num - trn_num
hdf5_filename_list.sort()
#print(hdf5_filename_list)
print("dataset_num :",dataset_num)
print("trn_num :",trn_num)
print("ev_num :",ev_num)
for i in range(0,dataset_num):
shutil.copy(hdf5_filename_list[i] , trn_hdf5_path)
for i in range(trn_num,dataset_num):
shutil.copy(hdf5_filename_list[i] , ev_hdf5_path)
|
[
"noreply@github.com"
] |
Rogety.noreply@github.com
|
56aed275e818acd116fab05130fc7723f21b448d
|
ff5404ecdac6281b982376fcb664f28fda46ecef
|
/mars/conftest.py
|
cb1dbcfd6c8b6a1f27e194de981a2a51f36b189e
|
[
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"ISC",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
qinxuye/mars
|
628aa106214eb85bcc84d3b5b27761d4b51c57f8
|
6ffc7b909c790c2b4094d8a80bd749a6d90d2006
|
refs/heads/master
| 2022-06-17T04:58:57.885557
| 2022-06-06T12:11:11
| 2022-06-06T12:11:11
| 160,643,357
| 0
| 2
|
Apache-2.0
| 2019-11-28T14:44:34
| 2018-12-06T08:28:59
|
Python
|
UTF-8
|
Python
| false
| false
| 8,702
|
py
|
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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.
import concurrent.futures
import os
import subprocess
import psutil
import pytest
from mars.config import option_context
from mars.core.mode import is_kernel_mode, is_build_mode
from mars.lib.aio.lru import clear_all_alru_caches
from mars.oscar.backends.router import Router
from mars.oscar.backends.ray.communication import RayServer
from mars.serialization.ray import register_ray_serializers, unregister_ray_serializers
from mars.utils import lazy_import
ray = lazy_import("ray")
MARS_CI_BACKEND = os.environ.get("MARS_CI_BACKEND", "mars")
@pytest.fixture(autouse=True)
def auto_cleanup(request):
request.addfinalizer(clear_all_alru_caches)
@pytest.fixture(scope="module", autouse=True)
def check_router_cleaned(request):
def route_checker():
if Router.get_instance() is not None:
assert len(Router.get_instance()._mapping) == 0
assert len(Router.get_instance()._local_mapping) == 0
request.addfinalizer(route_checker)
@pytest.fixture(scope="module")
def ray_start_regular_shared(request): # pragma: no cover
yield from _ray_start_regular(request)
@pytest.fixture(scope="module")
def ray_start_regular_shared2(request): # pragma: no cover
os.environ["RAY_kill_idle_workers_interval_ms"] = "0"
param = getattr(request, "param", {})
num_cpus = param.get("num_cpus", 64)
total_memory_mb = num_cpus * 2 * 1024**2
try:
try:
job_config = ray.job_config.JobConfig(total_memory_mb=total_memory_mb)
except TypeError:
job_config = None
yield ray.init(num_cpus=num_cpus, job_config=job_config)
finally:
ray.shutdown()
Router.set_instance(None)
os.environ.pop("RAY_kill_idle_workers_interval_ms", None)
@pytest.fixture
def ray_start_regular(request): # pragma: no cover
yield from _ray_start_regular(request)
def _ray_start_regular(request): # pragma: no cover
param = getattr(request, "param", {})
if not param.get("enable", True):
yield
else:
num_cpus = param.get("num_cpus", 64)
total_memory_mb = num_cpus * 2 * 1024**2
try:
register_ray_serializers()
try:
job_config = ray.job_config.JobConfig(total_memory_mb=total_memory_mb)
except TypeError:
job_config = None
yield ray.init(num_cpus=num_cpus, job_config=job_config)
finally:
ray.shutdown()
unregister_ray_serializers()
Router.set_instance(None)
RayServer.clear()
if "COV_CORE_SOURCE" in os.environ:
# Remove this when https://github.com/ray-project/ray/issues/16802 got fixed
subprocess.check_call(["ray", "stop", "--force"])
@pytest.fixture(scope="module")
def ray_large_cluster_shared(request): # pragma: no cover
yield from _ray_large_cluster(request)
@pytest.fixture
def ray_large_cluster(request): # pragma: no cover
yield from _ray_large_cluster(request)
def _ray_large_cluster(request): # pragma: no cover
param = getattr(request, "param", {})
num_nodes = param.get("num_nodes", 3)
num_cpus = param.get("num_cpus", 16)
from ray.cluster_utils import Cluster
cluster = Cluster()
remote_nodes = []
for i in range(num_nodes):
remote_nodes.append(
cluster.add_node(num_cpus=num_cpus, memory=num_cpus * 2 * 1024**3)
)
if len(remote_nodes) == 1:
try:
job_config = ray.job_config.JobConfig(
total_memory_mb=num_nodes * 32 * 1024**3
)
except TypeError:
job_config = None
ray.init(address=cluster.address, job_config=job_config)
use_ray_serialization = param.get("use_ray_serialization", True)
if use_ray_serialization:
register_ray_serializers()
try:
yield cluster
finally:
if use_ray_serialization:
unregister_ray_serializers()
Router.set_instance(None)
RayServer.clear()
ray.shutdown()
cluster.shutdown()
if "COV_CORE_SOURCE" in os.environ:
# Remove this when https://github.com/ray-project/ray/issues/16802 got fixed
subprocess.check_call(["ray", "stop", "--force"])
@pytest.fixture
def stop_ray(request): # pragma: no cover
yield
if ray.is_initialized():
ray.shutdown()
Router.set_instance(None)
@pytest.fixture
async def ray_create_mars_cluster(request, check_router_cleaned):
from mars.deploy.oscar.ray import new_cluster, _load_config
ray_config = _load_config()
param = getattr(request, "param", {})
supervisor_mem = param.get("supervisor_mem", 1 * 1024**3)
worker_num = param.get("worker_num", 2)
worker_cpu = param.get("worker_cpu", 2)
worker_mem = param.get("worker_mem", 256 * 1024**2)
ray_config.update(param.get("config", {}))
client = await new_cluster(
supervisor_mem=supervisor_mem,
worker_num=worker_num,
worker_cpu=worker_cpu,
worker_mem=worker_mem,
config=ray_config,
)
try:
async with client:
yield client
finally:
Router.set_instance(None)
@pytest.fixture
def stop_mars():
try:
yield
finally:
import mars
mars.stop_server()
@pytest.fixture(scope="module")
def _new_test_session(check_router_cleaned):
from .deploy.oscar.tests.session import new_test_session
sess = new_test_session(
address="test://127.0.0.1",
backend=MARS_CI_BACKEND,
init_local=True,
default=True,
timeout=300,
)
with option_context({"show_progress": False}):
try:
yield sess
finally:
sess.stop_server(isolation=False)
Router.set_instance(None)
@pytest.fixture(scope="module")
def _new_integrated_test_session(check_router_cleaned):
from .deploy.oscar.tests.session import new_test_session
sess = new_test_session(
address="127.0.0.1",
backend=MARS_CI_BACKEND,
init_local=True,
n_worker=2,
default=True,
timeout=300,
)
with option_context({"show_progress": False}):
try:
yield sess
finally:
try:
sess.stop_server(isolation=False)
except concurrent.futures.TimeoutError:
Router.set_instance(None)
subprocesses = psutil.Process().children(recursive=True)
for proc in subprocesses:
proc.terminate()
for proc in subprocesses:
try:
proc.wait(1)
except (psutil.TimeoutExpired, psutil.NoSuchProcess):
pass
try:
proc.kill()
except psutil.NoSuchProcess:
pass
@pytest.fixture(scope="module")
def _new_gpu_test_session(check_router_cleaned): # pragma: no cover
from .deploy.oscar.tests.session import new_test_session
from .resource import cuda_count
cuda_devices = list(range(min(cuda_count(), 2)))
sess = new_test_session(
address="127.0.0.1",
backend=MARS_CI_BACKEND,
init_local=True,
n_worker=1,
n_cpu=1,
cuda_devices=cuda_devices,
default=True,
timeout=300,
)
with option_context({"show_progress": False}):
try:
yield sess
finally:
sess.stop_server(isolation=False)
Router.set_instance(None)
@pytest.fixture
def setup(_new_test_session):
_new_test_session.as_default()
yield _new_test_session
assert not (is_build_mode() or is_kernel_mode())
@pytest.fixture
def setup_cluster(_new_integrated_test_session):
_new_integrated_test_session.as_default()
yield _new_integrated_test_session
@pytest.fixture
def setup_gpu(_new_gpu_test_session): # pragma: no cover
_new_gpu_test_session.as_default()
yield _new_test_session
|
[
"noreply@github.com"
] |
qinxuye.noreply@github.com
|
716729a67b142fe506fc9e95c95763d0e754a439
|
0d3cc48ea0912ce3dbae4acbf0974b9bd2683d13
|
/batch_norm_gradient_check.py
|
82e2032cc0dc26863aa73565fb856c085d4835a4
|
[] |
no_license
|
maniizu/practice_DL
|
3d6101f53fcc55f05344472a1a2e5667267ce9e1
|
0b9170a3b266bf5f7bc2d587061f9d4063e3d6fb
|
refs/heads/master
| 2020-03-08T15:11:59.865870
| 2018-05-17T07:47:38
| 2018-05-17T07:47:38
| 128,205,399
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 797
|
py
|
"""
Name: batch_norm_gradient_check.py
Usage: ターミナルで python3 batch_norm_gradient_check.py
Description:
Batch Normalization の更新がうまくいくか調べる.
"""
import numpy as np
from train_NN import get_mnist_data
from multi_layer_net_extend import MultiLayerNetExtend
#データの読み込み
[x_train, t_train, x_test, t_test] = get_mnist_data()
network = MultiLayerNetExtend(input_size=784, hidden_size_list=[100, 100], \
output_size=10, use_batchnorm=True)
x_batch = x_train[:1]
t_batch = t_train[:1]
grad_backprop = network.gradient(x_batch, t_batch)
grad_numerical = network.numerical_gradient(x_batch, t_batch)
for key in grad_numerical.keys():
diff = np.average( np.abs(grad_backprop[key] - grad_numerical[key]) )
print(key + ":" + str(diff))
|
[
"hondakazunori@kc19.local"
] |
hondakazunori@kc19.local
|
ef8232552a837998f23b8c3784733729c73d6cef
|
9ba97bf120f4bcc3a7844f8af9ddfd6592b5913b
|
/Exercicios Curso em Video/ex042.py
|
7c24784966329ea7d92b64e5c9f8b1e4814a7120
|
[] |
no_license
|
renatomarquesteles/estudos-python
|
cbc1ae527e93f5282b7dadc1d6cc29778ea3b199
|
477e51393b1cef72cbf58f35acd85442dfe51e58
|
refs/heads/master
| 2020-07-08T10:59:51.054709
| 2019-10-08T21:52:33
| 2019-10-08T21:52:33
| 203,652,908
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 464
|
py
|
s1 = int(input('Primeiro segmento: '))
s2 = int(input('Segundo segmento: '))
s3 = int(input('Terceiro segmento: '))
if s1 < s2 + s3 and s2 < s1 + s3 and s3 < s1 + s2:
print('Os segmentos acima PODEM FORMAR um triângulo ', end='')
if s1 == s2 == s3:
print('EQUILÁTERO')
elif s1 == s2 or s2 == s3 or s1 == s3:
print('ISÓSCELES')
else:
print('ESCALENO')
else:
print('Os segmentos acima NÃO PODEM formar um triângulo')
|
[
"renatomarquesteles@gmail.com"
] |
renatomarquesteles@gmail.com
|
00d25ebb974f40d94fe4584e0efe92a3a94c5fe2
|
0123540469b176b0a9809d150c05714385676892
|
/build/lesson_move_group/catkin_generated/pkg.installspace.context.pc.py
|
68fc636c42dca0dcb5fa635f735d0c39b1481683
|
[] |
no_license
|
MarcoMura85/VisualHatpic
|
9f27396e1e598bf3fbbe3a66a4616b0844e95b66
|
a4033a298b5af556cf53f322703832b9b71d17ed
|
refs/heads/master
| 2016-08-12T17:32:02.061211
| 2015-10-19T12:34:33
| 2015-10-19T12:34:33
| 44,103,395
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 539
|
py
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/yasmeen/MarcoStuff/catkin_ws/install/include".split(';') if "/home/yasmeen/MarcoStuff/catkin_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "moveit_ros_planning_interface;moveit_core;roscpp".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "move_group_test"
PROJECT_SPACE_DIR = "/home/yasmeen/MarcoStuff/catkin_ws/install"
PROJECT_VERSION = "0.0.0"
|
[
"m.mura@sssup.it"
] |
m.mura@sssup.it
|
5269c25274b9f10bea869197ee9a4e6ac7b3ba56
|
f272f2c40ae4668b9ea3483cc1b8593bb3c9a369
|
/fit1.py
|
dd0cd02d07341ccea25450b73f3bd19fea57c731
|
[] |
no_license
|
rlin264/Misc
|
8f36ec791b955c08cd635a0b12b95e1bb7a3150f
|
4b9fd136d363d1b971a6d4dd4a36ad67be260601
|
refs/heads/master
| 2020-04-01T08:26:42.653471
| 2018-10-15T00:14:34
| 2018-10-15T00:14:34
| 153,030,855
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 717
|
py
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * x ** 2 + b * x + c * x
x = np.array([1.45631068, 1.496010638, 1.537410318, 1.612036539, 1.624548736])
y = np.array([0.539, 0.588, 0.637, 0.686, 0.735])
popt_cons, _ = curve_fit(func, x, y, bounds=([-np.inf, 0, 0], [np.inf, 0.000000000000001, 0.000000000000001]))
print(popt_cons)
residuals = y - func(x, popt_cons[0], popt_cons[1], popt_cons[2])
ss_res = np.sum(residuals**2)
ss_tot = np.sum((y-np.mean(y))**2)
r_squared = 1 - (ss_res/ss_tot)
print(r_squared)
xnew = np.linspace(0,10)
plt.plot(x, y, 'bo')
plt.plot(xnew, func(xnew, *popt_cons), 'r-')
plt.axis([0, 2, 0, 2])
plt.show()
|
[
"noreply@github.com"
] |
rlin264.noreply@github.com
|
70623543690c376fabdc663860b226b007c66fc1
|
8240cbf57b645db8daaacf22bacba292a20ff0ca
|
/group3_ml_project/movies/migrations/0002_ml100kmovies.py
|
83acea2f0035aede5bf8486c86b9a7d844a25ea6
|
[] |
no_license
|
bdowd91/Machine-Learning-Proj
|
2f404179dd21c7dfd75ea2db31dc0568c9f99a67
|
5717dfafce02c8b5755717b1c40114d603b5b70e
|
refs/heads/master
| 2022-06-20T02:56:58.922498
| 2020-05-08T12:17:01
| 2020-05-08T12:17:01
| 258,335,120
| 0
| 0
| null | 2020-05-08T12:11:17
| 2020-04-23T21:29:15
| null |
UTF-8
|
Python
| false
| false
| 562
|
py
|
# Generated by Django 3.0.6 on 2020-05-07 19:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ml100kmovies',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('movie_id', models.IntegerField()),
('title', models.CharField(max_length=528)),
],
),
]
|
[
"t_doan2@uncg.edu"
] |
t_doan2@uncg.edu
|
e570b7d3b542a041d082343d2e862fc29bf101fc
|
581bcf321e0cc1cda534ec42632bc5902670e72f
|
/opportunities/urls.py
|
80e28f154c9085e721d7358d8f9148dcfd895343
|
[] |
no_license
|
ToferC/careers
|
55514869604b99a6a7ba77bc0f8758a9871006ef
|
2d0144d54fc266667eb7a2204b15bd8915f1c163
|
refs/heads/master
| 2022-12-12T01:36:04.083525
| 2018-02-19T22:46:17
| 2018-02-19T22:46:17
| 122,020,129
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 525
|
py
|
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('opportunity/<str:opportunity_slug>/', views.view_opportunity,
name='view_opportunity'),
path('review_applicants/<str:opportunity_slug>/', views.review_applicants,
name='review_applicants'),
path('member/<str:member_slug>/', views.view_member,
name='view_member'),
path('application/<str:application_slug>/', views.view_application,
name='view_application'),
]
|
[
"cgeist7@gmail.com"
] |
cgeist7@gmail.com
|
0289a7e6b86fdae225bf9306639ad41ed91abc54
|
e0c9a8ee83d2fd8a61281b506365dba25d87ae08
|
/manage.py
|
103109d21aa99bb829d599396b4bc642752f570f
|
[] |
no_license
|
kefassatrio/tugas-pti
|
56ce626b94900287e72c382394a6838f4ea6b716
|
e4c742946abde8a97b6abc6da8563d5435b64d12
|
refs/heads/master
| 2020-04-20T07:02:13.231719
| 2019-02-01T15:49:45
| 2019-02-01T15:49:45
| 168,700,909
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 542
|
py
|
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TA_SBF_PTI.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
|
[
"kefassatrio@gmail.com"
] |
kefassatrio@gmail.com
|
fb0929a7b7ba8e0ee3d8e6d0241e8039a33ad34c
|
df46db080e0e5892851988534d1706c879c1a939
|
/nlmk/feature_selection.py
|
01dbb3cf455b39963a3f1488818a11c35b2f851b
|
[] |
no_license
|
ivbelkin/raai_nlmk
|
d2523cf77bb3af4792525bbcec150f0c10fc8bcc
|
d7baaed969d5b2c9398124f791dfe9318d69da04
|
refs/heads/master
| 2022-01-14T02:09:00.902470
| 2019-07-22T04:25:41
| 2019-07-22T04:25:41
| 198,215,601
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,442
|
py
|
import numpy as np
import os
from tqdm import tqdm_notebook as tqdm
from collections import Counter
from multiprocessing import Pool
from sys import stderr, stdout
from copy import deepcopy
from xgboost import XGBRegressor
def add_del(params, train_X, train_y, valid_X, valid_y, features_init=None, n_workers=1):
features_all = set(train_X.columns)
features = features_init or set()
feature_sets = []
last_train_score = np.inf
last_valid_score = np.inf
while True:
print("ADD")
feature, train_score, valid_score = add_one(params, train_X, train_y, valid_X, valid_y, features, n_workers)
if valid_score < last_valid_score and not feature.startswith("rnd_"):
features = features.union({feature})
feature_sets.append(features)
last_valid_score = valid_score
print("\t", feature, "TRAIN SCORE", train_score, "VALID SCORE", valid_score)
else:
break
while True:
print("DEL")
feature, train_score, valid_score = del_one(params, train_X, train_y, valid_X, valid_y, features, n_workers)
if valid_score < last_valid_score and not feature.startswith("rnd_"):
features = features - {feature}
feature_sets.append(features)
last_valid_score = valid_score
print("\t", feature, "TRAIN SCORE", train_score, "VALID SCORE", valid_score)
else:
break
return features
def evaluate(params, train_X, train_y, valid_X, valid_y):
model = XGBRegressor(**params)
model.fit(
train_X, train_y,
eval_set=[(train_X, train_y), (valid_X, valid_y)],
verbose=False
)
idx = np.argmin(model.evals_result()["validation_1"]["rmse"])
train_score = model.evals_result()["validation_0"]["rmse"][idx]
valid_score = model.evals_result()["validation_1"]["rmse"][idx]
return train_score, valid_score
def add_one(params, train_X, train_y, valid_X, valid_y, features, n_workers=1):
features_all = set(train_X.columns)
features_unused = features_all - features
with Pool(n_workers) as p:
seq = [(f, params, train_X, train_y, valid_X, valid_y, features, n_workers) for f in features_unused]
scores = dict(p.map(add, seq))
best_feature, (train_score, valid_score) = min(scores.items(), key=lambda x: x[1][1])
return best_feature, train_score, valid_score
def add(args):
feature, params, train_X, train_y, valid_X, valid_y, features, n_workers = args
params["gpu_id"] = os.getpid() % n_workers
features_new = list(features.union({feature}))
print("pid", os.getpid(), "gpu", params["gpu_id"], feature); stdout.flush()
return feature, evaluate(
params,
train_X[features_new], train_y,
valid_X[features_new], valid_y
)
def del_one(params, train_X, train_y, valid_X, valid_y, features, n_workers=1):
with Pool(n_workers) as p:
seq = [(f, params, train_X, train_y, valid_X, valid_y, features, n_workers) for f in features]
scores = dict(p.map(del_, seq))
best_feature, (train_score, valid_score) = min(scores.items(), key=lambda x: x[1][1])
return best_feature, train_score, valid_score
def del_(args):
feature, params, train_X, train_y, valid_X, valid_y, features, n_workers = args
params["gpu_id"] = os.getpid() % n_workers
features_new = list(features - {feature})
print("pid", os.getpid(), "gpu", params["gpu_id"], feature); stdout.flush()
return feature, evaluate(
params,
train_X[features_new], train_y,
valid_X[features_new], valid_y
)
def add_noisy_features(X, factor=1, features=None):
features = features or list(X.columns)
idx = np.arange(len(X))
for _ in range(factor):
for feature in features:
np.random.shuffle(idx)
X["rnd_" + feature] = X[feature].values[idx]
return X
def non_constant_features(train_X, features=None):
features = features or list(train_X.columns)
train_nu = train_X[features].nunique()
return list(train_nu[train_nu > 1].index)
def variative_features(train_X, features=None, q=0.99):
features = features or list(train_X.columns)
N = len(train_X)
features_new = []
for feature in features:
cnt = Counter(train_X[feature])
if cnt.most_common()[0][1] / N < q:
features_new.append(feature)
return features_new
|
[
"ilya.belkin-trade@yandex.ru"
] |
ilya.belkin-trade@yandex.ru
|
bc8d07d07fc59dbf3181e2e10dba2c7dc1c4c850
|
33d8fcecbca828085011a69b2aa29184e9f5be3f
|
/ascii.py
|
61df7aae183ae79518bc6d0b2e1e0c815e267f11
|
[
"MIT"
] |
permissive
|
thomas-ayissi/EsotericTensorFlow
|
c68cf667dda8484e9feb87b8b86098e52218d705
|
dd4dc4eb8297799418d1f1e6eeba8cee5c54a27e
|
refs/heads/master
| 2023-03-17T03:24:02.331349
| 2017-11-17T08:02:03
| 2017-11-17T08:02:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 909
|
py
|
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def ascii2char(x):
default = tf.constant('', dtype=tf.string)
table = tf.constant([chr(i) for i in range(127)], dtype=tf.string)
cond = tf.logical_and(tf.greater_equal(x, tf.constant(0)), tf.less(x, tf.constant(127)))
return tf.cond(cond, lambda: table[x], lambda: default)
if __name__ == '__main__':
SP = ascii2char(tf.constant(0))
A = ascii2char(tf.constant(65))
B = ascii2char(tf.constant(66))
C = ascii2char(tf.constant(67))
x = ascii2char(tf.constant(120))
TILDE = ascii2char(tf.constant(126))
d1 = ascii2char(tf.constant(127))
d2 = ascii2char(tf.constant(-1))
with tf.Session() as sess:
ret = sess.run([SP,A,B,C,x,TILDE,d1,d2])
for ch in ret:
print(ch)
|
[
"kimura.akim.asa@gmail.com"
] |
kimura.akim.asa@gmail.com
|
73baad18b527c56c73d4cd351649e759b1d161d3
|
8f2fe58d7d987507bba834f4bec67964b2c3bc6b
|
/server.py
|
6cd0daddb28d7569cd413a2e2e928f677f9a54ca
|
[] |
no_license
|
jlbagrel1/demo_web_spa
|
963db1e5d1d7ac1df1858eb509edc28740b14e59
|
5d17a3ef86828aa430bf1162db2fc6715e626b7c
|
refs/heads/master
| 2023-06-09T04:08:54.900631
| 2021-06-25T09:56:15
| 2021-06-25T09:56:15
| 380,175,667
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,103
|
py
|
from flask import (
Flask, jsonify,render_template,send_from_directory,request,
)
from flask_cors import CORS
from base64 import b64encode
app = Flask(__name__)
app.config["DEBUG"] = True
CORS(app)
STATIC_DIR = "/home/jlbagrel/Bureau/demo_web_spa"
tickets_restants = 10
def creer_numero(n, nom, prenom):
return b64encode((str(n) + nom + prenom).encode("utf-8")).decode("utf-8")
@app.route("/tickets_restants", methods=["GET"])
def get_tickets_restants():
global tickets_restants
return {"tickets": tickets_restants}
@app.route("/reserver", methods=["POST"])
def post_reserver():
global tickets_restants
if tickets_restants <= 0:
return {"numero": None}
else:
n = tickets_restants
tickets_restants -= 1
corps = request.get_json()
print(corps)
return {"numero": creer_numero(n, corps["nom"], corps["prenom"]) }
@app.route("/")
def serve_index():
return send_from_directory(STATIC_DIR, "index.html")
@app.route("/client.js", methods=["GET"])
def serve_app_js():
return send_from_directory(STATIC_DIR, "client.js")
|
[
"jloup.13.bagrel@gmail.com"
] |
jloup.13.bagrel@gmail.com
|
53297db8ae1040f1cbdd14102ee8561fab00635f
|
8239a6d4f47e510c79b9ca9266bdae74a4a65c62
|
/stats_scripts/LineageSeqAnalysis.py
|
68d6e566ed1d2d4f744f5298e0094c85e4b864a5
|
[
"Apache-2.0"
] |
permissive
|
MitsuhaMiyamizu/altanalyze
|
37e41e31be5b8e0bda3bbc21a49ae38a0e5bb0b1
|
6cf103d14eb0d1643345b23a82a73ed969e75d40
|
refs/heads/master
| 2022-12-16T00:45:33.075476
| 2020-09-13T19:49:06
| 2020-09-13T19:49:06
| 295,673,614
| 1
| 0
|
Apache-2.0
| 2020-09-15T09:08:18
| 2020-09-15T09:08:18
| null |
UTF-8
|
Python
| false
| false
| 3,442
|
py
|
import sys,string,os
sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies
import export
import unique
import traceback
""" Intersecting Coordinate Files """
def cleanUpLine(line):
line = string.replace(line,'\n','')
line = string.replace(line,'\c','')
data = string.replace(line,'\r','')
data = string.replace(data,'"','')
return data
def importLookupTable(fn):
""" Import a gRNA to valid tag lookup table """
lookup_table = []
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
gRNA,tag = t
lookup_table.append((gRNA,tag))
return lookup_table
def importCountMatrix(fn,mask=False):
""" Import a count matrix """
classification = {}
firstRow = True
for line in open(fn,'rU').xreadlines():
data = cleanUpLine(line)
t = string.split(data,'\t')
if firstRow:
headers = t[1:]
firstRow = False
else:
barcode = t[0]
values = map(int,t[1:])
if mask:
sum_counts = sum(values[2:])
else:
sum_counts = sum(values)
def threshold(val):
if val>0.3: return 1
else: return 0
if sum_counts>0:
ratios = map(lambda x: (1.000*x)/sum_counts, values)
if mask:
original_ratios = ratios
ratios = ratios[2:] ### mask the first two controls which are saturating
else:
original_ratios = ratios
hits = map(lambda x: threshold(x), ratios)
hits = sum(hits)
if sum_counts>20 and hits == 1:
index=0
for ratio in ratios:
if ratio>0.3:
header = headers[index]
index+=1
classification[barcode] = header
print len(classification),fn
return classification
def exportGuideToTags(lookup_table,gRNA_barcode,tag_barcode,output):
export_object = open(output,'w')
for barcode in gRNA_barcode:
gRNA = gRNA_barcode[barcode]
if barcode in tag_barcode:
tag = tag_barcode[barcode]
if (gRNA,tag) in lookup_table:
uid = tag+'__'+gRNA
export_object.write(barcode+'\t'+uid+'\t'+uid+'\n')
export_object.close()
if __name__ == '__main__':
################ Comand-line arguments ################
import getopt
if len(sys.argv[1:])<=1: ### Indicates that there are insufficient number of command-line arguments
print 'WARNING!!!! Too commands supplied.'
else:
options, remainder = getopt.getopt(sys.argv[1:],'', ['species=','gRNA=', 'tag=', 'lookup=','output='])
#print sys.argv[1:]
for opt, arg in options:
if opt == '--gRNA':
gRNA = arg
elif opt == '--tag':
tag = arg
elif opt == '--lookup':
lookup = arg
elif opt == '--output':
output = arg
lookup_table = importLookupTable(lookup)
gRNA_barcode = importCountMatrix(gRNA)
tag_barcode = importCountMatrix(tag)
exportGuideToTags(lookup_table,gRNA_barcode,tag_barcode,output)
|
[
"nsalomonis@gmail.com"
] |
nsalomonis@gmail.com
|
9006ea41b14767232ecfeab06e0a211bf3355c55
|
5e7a09799bcd965e94763439d2cdddb85e961f82
|
/converter.py
|
5abeeda33452121b95f9c0fdcd0eb7878c431c91
|
[] |
no_license
|
volsn/TextCorrector
|
c6fccf20d95db56a67085dfef5c0e303dc344890
|
e232b1d8b3be8e9c5dbfd2d692a7c900b27bda0f
|
refs/heads/master
| 2022-08-09T18:01:16.408447
| 2019-07-19T15:50:47
| 2019-07-19T15:50:47
| 197,633,686
| 0
| 0
| null | 2022-06-21T22:21:56
| 2019-07-18T17:58:11
|
Python
|
UTF-8
|
Python
| false
| false
| 3,113
|
py
|
import cv2
import numpy as np
import os
import svgwrite
def locate_letters(image):
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
img_cnt, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
boxes = []
letters = []
(H,W) = image.shape[:2]
for i, cnt in enumerate(cnts):
if hierarchy[0][i][3] == 0:
(x,y,w,h) = cv2.boundingRect(cnt)
roi = thresh[y-5:y+h+5, x-5:x+w+5].copy()
hull = cv2.convexHull(cnts[i], False)
mask = np.zeros((H,W), dtype=np.uint8)
mask = cv2.drawContours(mask, [hull], -1, (255,255,255), -1)
mask = mask[y-5:y+h+5, x-5:x+w+5].copy()
boxes.append((y-5, y+h+5, x-5, x+w+5))
roi[mask == 0] = 255
letters.append(roi)
return letters, boxes
def preprocess_letters(letters):
for i, letter in enumerate(letters):
roi = letter
"""scale_percent = 150
width = int(roi.shape[1] * scale_percent / 100)
height = int(roi.shape[0] * scale_percent / 100)
dim = (width, height)
roi = cv2.resize(roi, dim, interpolation=cv2.INTER_AREA)"""
blurred = cv2.GaussianBlur(roi, (7,7), 0)
ret, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
letters[i] = thresh
return letters
def affect_letters(letters, mode, ksize=5, iterations=3):
for i, letter in enumerate(letters):
if mode == 'erode':
eroded = cv2.erode(letter, (ksize, ksize), iterations=iterations)
letters[i] = eroded
elif mode == 'dilate':
dilated = cv2.dilate(letter, (ksize, ksize), iterations=iterations)
letters[i] = dilated
#cv2.imwrite('Result/{}.png'.format(i), eroded)
return letters
def generate_svg(image, color='#000000'):
img_cnt, cnts, hierarchy = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
outer_points_groups = []
inner_points_groups = []
for i, cnt in enumerate(cnts):
if hierarchy[0][i][3] == 0:
outer_points = []
for point in cnt[::2]:
pnt = (int(point[0][0]),int(point[0][1]))
outer_points.append(pnt)
outer_points_groups.append(outer_points)
elif hierarchy[0][i][3] > 0:
inner_points = []
for point in cnt[::2]:
pnt = (int(point[0][0]),int(point[0][1]))
inner_points.append(pnt)
inner_points_groups.append(inner_points)
dwg = svgwrite.Drawing('static/vector.svg', profile='tiny')
for group in outer_points_groups:
dwg.add(dwg.polyline(group, fill=color))
for group in inner_points_groups:
dwg.add(dwg.polyline(group, fill='#ffffff'))
dwg.save()
|
[
"noreply@github.com"
] |
volsn.noreply@github.com
|
59ffaa062f026bd109f7179f6a030914c71a1fcb
|
d8e28eadab859095e3653812d9d32ed4df3e8323
|
/LeetCode/590.N-ary_Tree_Postorder_Traversal.py
|
14d12b35e8d6822a87f32ae3dad801aefb5ab317
|
[] |
no_license
|
prashkumara/Data-Structures
|
d72b9e9845de7eeda62fd21b80e0942317ea85e1
|
b95fe9a28aad61b54cc685ee7d44cb501f32e631
|
refs/heads/master
| 2020-04-15T11:30:40.121096
| 2019-05-02T11:10:14
| 2019-05-02T11:10:14
| 164,633,582
| 0
| 0
| null | 2019-05-02T11:10:15
| 2019-01-08T11:23:19
|
Python
|
UTF-8
|
Python
| false
| false
| 498
|
py
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res = []
self.dfs(root,res)
return res
def dfs(self,root,res):
if root:
for child in root.children:
self.dfs(child,res)
res.append(root.val)
|
[
"prashkumar.a@gmail.com"
] |
prashkumar.a@gmail.com
|
88c11e5aa905c12f6ff1d2337df5c7c5f384719f
|
2fa0ce90609924c807c66dac2d0435f50fc2213f
|
/clustering_coef.py
|
6245d1ec8f8a0b7b1e4e0f3a9b2de3d1a66c84ed
|
[] |
no_license
|
sheyma/nonlinear_dynamics
|
3fd1f603989ba92e6b18b5a8f9ca9db152b1727b
|
c81e652aaa6489e7441a7dbc27dc783c57ca489b
|
refs/heads/master
| 2021-01-01T20:42:05.656048
| 2014-07-16T18:14:36
| 2014-07-16T18:14:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,185
|
py
|
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import networkx as nx
import numpy as np
import itertools
import random
import math
import networkx as nx
from networkx.generators.classic import empty_graph, path_graph, complete_graph
import matplotlib.pyplot as pl
B = np.array([[0,1,1,1],[1,0,0,1],[1,0,0,1],[1,1,1,0]])
G = nx.from_numpy_matrix(B)
N = nx.number_of_nodes(G)
ADJ = {}
triads ={}
def degree_node(G,node_i):
# connected neigbors of a given node
# returns a list
ADJ[node_i] = []
for j in G.nodes():
if G.has_edge(j,node_i):
ADJ[node_i].append(j)
return ADJ[node_i]
def triangle_node(G,nodes):
# number of triangles around a given node
# returns an integer
ADJ[nodes] = []
for j in G.nodes():
if G.has_edge(j,nodes):
ADJ[nodes].append(j) # list of neigbors
for node_i in ADJ:
triads[node_i] = []
adjacent_i= set(ADJ[node_i])
count_tri = 0
for node_j in adjacent_i:
new_set = set(G[node_j])-set([node_j])
count_tri +=len(adjacent_i.intersection(new_set))
return int(count_tri/2)
def cluster_coef_numer(G):
# calculates average cluster coefficient of a graph
# Watts and Strogatz
clust_coef=0
N = nx.number_of_nodes(G)
for nodes in G:
k_i = len(degree_node(G,nodes)) # number of degrees
t_i = triangle_node(G,nodes) # number of triads
clust_coef += 2 * float(t_i) /(k_i * (k_i - 1))
return clust_coef/float(N)
#print nx.average_clustering(G)
#print cluster_coef_numer(G)
def plot_graph(G):
pos = nx.shell_layout(G)
nx.draw(G, pos)
pl.show()
def path_node(G,node):
# finds path lengths of given node to all other nodes
# returns a dict, keys are other nodes, values distances
node_paths = {}
distance = 0
temp_nodes = {node:0}
while len(temp_nodes) != 0:
new_nodes = temp_nodes
temp_nodes = {}
for v in new_nodes:
if v not in node_paths:
node_paths[v] = distance
temp_nodes.update(G[v])
distance=distance+1
return node_paths
def path_ave(G):
N = nx.number_of_nodes(G)
summ = 0
for node_i in G:
for keys in path_node(G , node_i):
summ = summ + path_node(G, node_i)[keys]
return summ / float(N*(N-1))
|
[
"seymaba@gmail.com"
] |
seymaba@gmail.com
|
6d5350b4a2529f526f2b40301f9e064b6f4d99f2
|
56062fb29e67a27585934add78343e066352c72c
|
/blog/models.py
|
7ce064dc87da4930f7985609caaec49caf149169
|
[] |
no_license
|
AhmadKafi/blog_app
|
cb05a391c35df0ed91ea710e51e29182d0e435c1
|
bd8edeee3f2fc92c8a98405605edde43be4bd7a5
|
refs/heads/master
| 2022-12-26T10:29:13.882569
| 2020-10-05T21:29:20
| 2020-10-05T21:29:20
| 287,182,863
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,061
|
py
|
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def approved_comments(self):
return self.comments.filter(approved=True)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved = models.BooleanField(default=False)
def approve(self):
self.approved = True
self.save()
def __str__(self):
return self.text
|
[
"kafi@Ahmadkafi.localdomain"
] |
kafi@Ahmadkafi.localdomain
|
7a00bbe92188c8b80c2648067c697f5945fa472f
|
146db8997ca59945d63750089fe03aea2ce9c77d
|
/src/cool/compiler/checksemantics.py
|
53716c10fcd96fc6a6045a9123e7faadf13429ca
|
[
"MIT"
] |
permissive
|
arod40/cool-compiler-rodrigo-alejandro-jorge
|
91321a99e42dd4aea15ac23b921b23399f53765c
|
3647846cd4c8ad83c2698cbd941efde4fdb3ac85
|
refs/heads/master
| 2023-06-16T05:15:29.199042
| 2019-06-25T18:59:23
| 2019-06-25T18:59:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 17,175
|
py
|
from cool.utils import visitor
from cool.structs.environment import *
import cool.structs.cool_ast_hierarchy as cool
from cool.utils.config import *
class CheckSemanticsVisitor:
def __init__(self):
self.errors = []
self.environment: Environment = Environment(self.errors)
@visitor.on("node")
def visit(self, node):
pass
@visitor.when(cool.ProgramNode)
def visit(self, node: cool.ProgramNode):
ok = False
if self.environment.build_env(node):
ok = True
for cl in node.class_list:
ok &= self.visit(cl)
return ok
@visitor.when(cool.ClassNode)
def visit(self, node: cool.ClassNode):
self.environment.enter_in_class(node.class_name)
self.environment.create_child_scope()
self.environment.define_variable("self", SELF_TYPE)
ok = True
if not self.environment.is_class_defined(node.ancestor):
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Class {node.ancestor} is not defined."))
ok = False
for attr in node.attrs_list:
ok &= self.visit(attr)
for meth in node.methods_list:
ok &= self.visit(meth)
self.environment.checkout_parent_scope()
return ok
@visitor.when(cool.AttributeDeclarationNode)
def visit(self, node: cool.AttributeDeclarationNode):
ok1 = True
if node.attr_type != SELF_TYPE and not self.environment.is_class_defined(node.attr_type):
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Type {node.attr_type} is not defined."))
ok1 = False
ok2 = True
if node.init_expr:
expr_type, ok2 = self.visit(node.init_expr)
ok = ok1 and ok2
if ok and node.init_expr and not self.environment.conforms_to(expr_type, node.attr_type):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Init expresion type ({expr_type}) does not conform to attribute declared type ({node.attr_type})."))
ok = False
return ok
@visitor.when(cool.MethodDefinitionNode)
def visit(self, node: cool.MethodDefinitionNode):
self.environment.create_child_scope()
self.environment.define_variable("self", SELF_TYPE)
ok = True
node.signature_vinfos = []
for name, type in node.signature:
if self.environment.is_local(name):
self.errors.append(Error(node.row, node.column, SEMANTIC_ERROR,
f"Duplicate argument '{name}' in method definition."))
ok = False
break
if type == SELF_TYPE:
self.errors.append(
Error(node.row, node.column, SEMANTIC_ERROR, f"Invalid usage of 'SELF_TYPE'."))
ok = False
else:
node.signature_vinfos.append(
self.environment.define_variable(name, type))
if ok:
expr_type, ok = self.visit(node.body_expr)
if ok and not self.environment.conforms_to(expr_type, node.return_type):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Body expression type ({expr_type}) does not conform to method return type ({node.return_type})."))
ok = False
self.environment.checkout_parent_scope()
return ok
@visitor.when(cool.ArithmeticExpressionNode)
def visit(self, node: cool.ArithmeticExpressionNode):
left_type, ok1 = self.visit(node.left_expr)
right_type, ok2 = self.visit(node.right_expr)
ok = ok1 and ok2
if ok and (not left_type == INT or not right_type == INT):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Undefined operation between type {left_type} and type {right_type}."))
ok = False
node.type = INT
return node.type, ok
@visitor.when(cool.CompareExpressionNode)
def visit(self, node: cool.CompareExpressionNode):
left_type, ok1 = self.visit(node.left_expr)
right_type, ok2 = self.visit(node.right_expr)
ok = ok1 and ok2
if ok and not left_type == INT or not right_type == INT:
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Undefined operation between type {left_type} and type {right_type}."))
ok = False
node.type = BOOL
return node.type, ok
@visitor.when(cool.EqualNode)
def visit(self, node: cool.EqualNode):
left_type, ok1 = self.visit(node.left_expr)
right_type, ok2 = self.visit(node.right_expr)
ok = ok1 and ok2
if left_type in [INT, BOOL, STRING] and not left_type == right_type:
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Undefined operation between type {left_type} and type {right_type}."))
ok = False
node.type = BOOL
return node.type, ok
@visitor.when(cool.ArithNegationNode)
def visit(self, node: cool.ArithNegationNode):
expr_type, ok = self.visit(node.expr)
if ok and not expr_type == INT:
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Undefined operation on type {expr_type}."))
node.type = INT
return node.type, ok
@visitor.when(cool.BooleanNegationNode)
def visit(self, node: cool.ArithNegationNode):
expr_type, ok = self.visit(node.expr)
if ok and not expr_type == BOOL:
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Undefined operation on type {expr_type}."))
node.type = BOOL
return node.type, ok
@visitor.when(cool.VariableNode)
def visit(self, node: cool.VariableNode):
ok = True
if not self.environment.is_variable_defined(node.var_name):
if not self.environment.is_attr_defined(node.var_name):
self.errors.append(Error(node.row, node.column, NAME_ERROR,
f"Undefined name {node.var_name} in current scope."))
ok = False
else:
node.variable_info = self.environment.get_attr_info(
node.var_name)
else:
node.variable_info = self.environment.get_variable_info(
node.var_name)
node.type = node.variable_info.type_name if ok else None
return node.type, ok
@visitor.when(cool.AssignNode)
def visit(self, node: cool.AssignNode):
ok1 = True
if node.var_name == "self":
self.errors.append(
Error(node.row, node.column, SEMANTIC_ERROR, f"Cannot assign variable self."))
ok1 = False
if ok1 and not self.environment.is_variable_defined(node.var_name):
if not self.environment.is_attr_defined(node.var_name):
self.errors.append(Error(node.row, node.column, NAME_ERROR,
f"Undefined variable {node.var_name} in current scope."))
ok1 = False
else:
node.variable_info = self.environment.get_attr_info(
node.var_name)
else:
node.variable_info = self.environment.get_variable_info(
node.var_name)
expr_type, ok2 = self.visit(node.expr)
ok = ok1 and ok2
if ok and not self.environment.conforms_to(expr_type, node.variable_info.type_name):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Expression type ({expr_type}) does not conform to variable/attribute declared type ({node.variable_info.type_name})."))
ok = False
node.type = expr_type
return node.type, ok
@visitor.when(cool.BooleanNode)
def visit(self, node: cool.BooleanNode):
node.type = BOOL
return BOOL, True
@visitor.when(cool.IntegerNode)
def visit(self, node: cool.IntegerNode):
node.type = INT
return INT, True
@visitor.when(cool.StringNode)
def visit(self, node: cool.StringNode):
node.type = STRING
return STRING, True
@visitor.when(cool.NewNode)
def visit(self, node: cool.NewNode):
ok = True
if node.type_name != SELF_TYPE and not self.environment.is_class_defined(node.type_name):
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Type {node.type_name} is not defined."))
ok = False
node.type = node.type_name
return node.type, ok
@visitor.when(cool.DynamicDispatchNode)
def visit(self, node: cool.DynamicDispatchNode):
dispatch_expr_type, ok1 = self.visit(node.dispatch_expr)
dispatch_expr_type_prime = dispatch_expr_type if dispatch_expr_type != SELF_TYPE else self.environment.current_class_name
ok2 = True
if ok1 and not self.environment.is_method_defined(node.method_name, dispatch_expr_type_prime):
self.errors.append(Error(node.row, node.column, ATTRIBUTE_ERROR,
f"Method {node.method_name} not defined in class {dispatch_expr_type_prime}."))
ok2 = False
params = [self.visit(param) for param in node.parameters]
ok3 = all([ok for _, ok in params])
params_types = [param_type for param_type, _ in params]
ok4 = True
if ok1 and ok2 and ok3:
method_info = self.environment.get_method_info(
node.method_name, dispatch_expr_type_prime)
for param_type, arg_type in zip(params_types, method_info.signature):
if not self.environment.conforms_to(param_type, arg_type):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Parameter type {param_type} does not conform to argument type {arg_type}"))
ok4 = False
ok = ok1 and ok2 and ok3 and ok4
node.type = (
dispatch_expr_type if method_info.signature[-1] == SELF_TYPE else method_info.signature[-1]) if ok else None
return node.type, ok
@visitor.when(cool.StaticDispatchNode)
def visit(self, node: cool.StaticDispatchNode):
dispatch_expr_type, ok1 = self.visit(node.dispatch_expr)
dispatch_expr_type_prime = dispatch_expr_type if dispatch_expr_type != SELF_TYPE else self.environment.current_class_name
ok5 = True
if not self.environment.conforms_to(dispatch_expr_type, node.class_name):
errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Type {node.class_name} does not conform to type {dispatch_expr_type}"))
ok2 = True
if ok1 and not self.environment.is_method_defined(node.method_name, node.class_name):
errors.append(Error(node.row, node.column, ATTRIBUTE_ERROR,
f"Method {node.method_name} not defined in class {node.class_name}."))
ok2 = False
params = [self.visit(param) for param in node.parameters]
ok3 = all([ok for _, ok in params])
params_types = [param_type for param_type, _ in params]
ok4 = True
if ok1 and ok2 and ok3:
method_info = self.environment.get_method_info(
node.method_name, dispatch_expr_type_prime)
for param_type, arg_type in zip(params_types, method_info.signature):
if not self.environment.conforms_to(param_type, arg_type):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Parameter type {param_type} does not conform to argument type {arg_type}"))
ok4 = False
ok = ok1 and ok2 and ok3 and ok4
node.type = (
dispatch_expr_type if method_info.signature[-1] == SELF_TYPE else method_info.signature[-1]) if ok else None
return node.type, ok
@visitor.when(cool.IfNode)
def visit(self, node: cool.IfNode):
cond_type, ok1 = self.visit(node.cond_expr)
ok2 = True
if not cond_type == BOOL:
errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Condition expression type must be Bool."))
ok2 = False
then_type, ok3 = self.visit(node.then_expr)
else_type, ok4 = self.visit(node.else_expr)
if ok3 and ok4:
joint_type = self.environment.join_types([then_type, else_type])
ok = ok1 and ok2 and ok3 and ok4
node.type = joint_type if ok else None
return node.type, ok
@visitor.when(cool.BlockNode)
def visit(self, node: cool.BlockNode):
ok = True
for expr in node.exprs_list:
node.type, ok1 = self.visit(expr)
ok &= ok1
return node.type, ok
@visitor.when(cool.LetNode)
def visit(self, node: cool.LetNode):
self.environment.create_child_scope()
ok = True
for declaration in node.declaration_list:
ok &= self.visit(declaration)
if ok:
expr_type, ok = self.visit(node.expr)
self.environment.checkout_parent_scope()
node.type = expr_type if ok else None
return node.type, ok
@visitor.when(cool.LetDeclarationNode)
def visit(self, node: cool.LetDeclarationNode):
ok1 = True
if node.var_name == "self":
self.errors.append(Error(
node.row, node.column, SEMANTIC_ERROR, f"Invalid variable identifier self."))
ok1 = False
if ok1 and node.type_name != SELF_TYPE and not self.environment.is_class_defined(node.type_name):
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Type {node.type_name} is not defined."))
ok1 = False
ok2 = True
if node.expr:
expr_type, ok2 = self.visit(node.expr)
ok = ok1 and ok2
if ok and node.expr and not self.environment.conforms_to(expr_type, node.type_name):
self.errors.append(Error(node.row, node.column, TYPE_ERROR,
f"Init expresion type ({expr_type}) does not conform to variable declared type ({node.type_name})."))
ok = False
if self.environment.is_local(node.var_name):
self.errors.append(Error(node.row, node.column, SEMANTIC_ERROR,
f"Variable '{node.var_name}' already declared in this scope."))
ok = False
else:
node.variable_info = self.environment.define_variable(
node.var_name, node.type_name)
return ok
@visitor.when(cool.WhileNode)
def visit(self, node: cool.WhileNode):
cond_type, ok1 = self.visit(node.cond_expr)
ok2 = True
if not cond_type == BOOL:
self.errors.append(Error(
node.row, node.column, TYPE_ERROR, f"Condition expression type must be Bool."))
ok2 = False
body_type, ok3 = self.visit(node.body_expr)
ok = ok1 and ok2 and ok3
node.type = OBJECT
return node.type, ok
@visitor.when(cool.IsVoidNode)
def visit(self, node: cool.IsVoidNode):
expr_type, ok = self.visit(node.expr)
node.type = BOOL
return node.type, ok
@visitor.when(cool.CaseNode)
def visit(self, node: cool.CaseNode):
match_type, ok1 = self.visit(node.match_expr)
ok2 = True
declared_types = set()
expr_types = []
node.variable_info_list = []
for var_name, type_name, case_expr in node.cases_list:
if var_name == "self":
self.errors.append(Error(
node.row, node.column, SEMANTIC_ERROR, f"Invalid variable identifier self."))
ok2 = False
if type_name == SELF_TYPE:
self.errors.append(
Error(node.row, node.column, SEMANTIC_ERROR, f"Invalid usage of 'SELF_TYPE'."))
ok2 = False
if type_name in declared_types:
self.errors.append(Error(
node.row, node.column, SEMANTIC_ERROR, f"Repeated types in case branches."))
ok2 = False
declared_types.add(type_name)
self.environment.create_child_scope()
node.variable_info_list.append(
self.environment.define_variable(var_name, type_name))
expr_type, ok = self.visit(case_expr)
expr_types.append(expr_type)
ok2 &= ok
self.environment.checkout_parent_scope()
ok = ok1 and ok2
node.type = self.environment.join_types(expr_types) if ok else None
return node.type, ok
|
[
"r.garcia@estudiantes.matcom.uh.cu"
] |
r.garcia@estudiantes.matcom.uh.cu
|
7dbe7a3f1fe497edaf1092a26bf86d082b359138
|
3ea205870103ac5557ef429e063a9b03f931ebb3
|
/getData.py
|
0ad18810cb188483015d13362a963afad4f3a745
|
[] |
no_license
|
bascoe10/flask-api-for-discoversalone-db
|
05e192c61049cf0e974d73321c182e2fc019f3cd
|
fc6d08aa26ef3fb7b95687c589a132bfe338ae48
|
refs/heads/master
| 2021-06-07T12:59:22.316570
| 2015-11-05T15:36:50
| 2015-11-05T15:36:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 12,437
|
py
|
#!/usr/bin/python
from flask import Flask,jsonify,abort, make_response
import MySQLdb, re
app = Flask(__name__)
db = MySQLdb.connect("localhost", "root", ENV["password"], "db_name")
@app.route('/api/v1.0/all', methods=['GET'])
def all():
hotels = get_hotels()
return jsonify({'HOTELS': hotels})
@app.route('/api/v1.0/hotels', methods=['GET'])
def get_hotels():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM hotels")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data hotels"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/casino', methods=['GET'])
def get_casino():
response = []
db = MySQLdb.connect("localhost", "root",ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM casinogaming")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data hotels"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/guesthouses', methods=['GET'])
def get_gh():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM guesthouses")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data hotels"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/nightclubs', methods=['GET'])
def get_nightclubs():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM nightclubs")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data hotels"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/restaurants', methods=['GET'])
def get_rest():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM resturants")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data hotels"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/lodges', methods=['GET'])
def get_lodges():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM lodges")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data lodges"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/snacks', methods=['GET'])
def get_snacks():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM snacks")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data lodges"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/newdev', methods=['GET'])
def get_dev():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM newdevelopment")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Name"] = re.sub(r'\s\'\s', "",reading[1].replace("',",",").replace("''","'").strip().rstrip('\''), flags=re.IGNORECASE)
line["Address"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().rstrip('\'')
line["Region"] = reading [3].replace("',",",").replace("''","'").strip().strip('\'')
line["Email"] = reading[4].replace("',",",").replace("''","'").replace(" ", "").strip().rstrip('\'')
line["Website"] = reading[5].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Rating"] = reading[6].replace("',",",").replace("''","'").strip().rstrip('\'')
line["Phone No"] = reading[7].replace("',",",").replace("''","'").strip().rstrip('\'')
line["GoeCoord"] = str(reading[8]).replace("',",",").replace("''","'").strip().rstrip('\'')
line["Fbook"] = reading[9].replace("',",",").replace("''","'").strip().rstrip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data lodges"
return jsonify({'response': 'Success', 'body':response})
@app.route('/api/v1.0/landmarks', methods=['GET'])
def get_landm():
response = []
db = MySQLdb.connect("localhost", "root", ENV["password"], "ExploreSL")
curs = db.cursor()
try:
curs.execute("SELECT * FROM landmarks")
for reading in curs.fetchall():
line = {}
line["id"] = str(reading[0]).replace("',",",").replace("''","'").strip().strip('\'')
line["Name"] = reading[1].replace("'", "").strip().strip('\'')
line["Image"] = reading [2].replace("',",",").replace("''","'").replace("\" ", "\"").strip().strip('\'')
line["Link"] = str(reading[3]).replace("',",",").replace("''","'").strip().strip('\'')
response.append(line)
db.close()
except:
print "Error: unable to fetch data lodges"
return jsonify({'response': 'Success', 'body':response})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'response': 'failed'}), 404)
if __name__ == '__main__':
app.run(debug=True, port=ENV["port"], host=ENV["host"])
|
[
"bassco10@gmail.com"
] |
bassco10@gmail.com
|
7e813c0b2cfbb074bc7a5adfa1cbe7ec0151f91d
|
44bacf97ba9e92e6460a58a423db6cdfc09c9b74
|
/HTML_JS/Week5/Multiples1.py
|
87ebf59173c8538b9b7330c1a8b8eb019cbb7da0
|
[] |
no_license
|
junhwang77/Jun-s-Repository
|
ce0f3e20f54ad356ef95af85dbe3e6c03291b0d8
|
4bc35c04586948d59ab9d93dcb918e96f838f8f6
|
refs/heads/master
| 2021-01-19T21:45:18.335953
| 2017-04-19T04:58:35
| 2017-04-19T04:58:35
| 88,701,284
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 71
|
py
|
for count in range (1, 1000):
if count%2 != 0:
print count
|
[
"junhwang@Jun-Hyuns-MBP.hsd1.ca.comcast.net"
] |
junhwang@Jun-Hyuns-MBP.hsd1.ca.comcast.net
|
b8e8b3edbc2c89ee54390fb4adb926604db20551
|
4716b0a77fc101e7268b4e7b5372dc501d22c5ae
|
/src/MyData.py
|
5f4ef1c818b91bdb36280fde10e81fd7c38c97fd
|
[] |
no_license
|
chinasilva/cat_vs_dog
|
81e3100b2d09aa000a743ab033b8600c33899b39
|
fe6fb6547024e0ceb00ac9c73b5cc45683624189
|
refs/heads/master
| 2020-05-28T02:56:24.109573
| 2019-05-28T13:12:48
| 2019-05-28T13:12:48
| 188,852,987
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,075
|
py
|
import os
import torch
import numpy as np
from torch.utils import data
from PIL import Image
class MyData(data.Dataset):
def __init__(self,path):
super().__init__()
# self.dataset=dataset
self.path=path
self.dataset=[]
# 以列表形式链接所有地址
self.dataset.extend(os.listdir(path))
# 获取数据长度
def __len__(self):
# return 20
return len(self.dataset)
# 获取数据中x,y
def __getitem__(self, index):
# data.dataloader()
imgInfo=self.dataset[index]
label=torch.Tensor(np.array([int(imgInfo[0])]))
imagePath=os.path.join(self.path,imgInfo)
#打开获取图片内容
img=Image.open(imagePath)
#imageData 对图片进行归一化,去均值操作
imageData=torch.Tensor(np.array(img)/255 - 0.5)
return imageData,label
# if __name__ == "__main__":
# print(np.array([2,3]))
# myData=MyData("img")
# x=myData[6000][0]
# y=myData[6000][1]
# print("x:",x)
# print("y:",y)
|
[
"YSP@email.com"
] |
YSP@email.com
|
1a340439e7d0d09ad7a844c67259b4dc90b85c4d
|
0220af0584cb5b9df56aa09d81b8d450b3733156
|
/Easy/Brackets, extreme edition.py
|
18465f2c9047fb2f5ace051d71f045df83879a21
|
[] |
no_license
|
SpiralT/Codingame
|
5cb1afbe58daccd9c1474a369b700e5a31a2684a
|
d4c4e0a4754870740f2db6bafa981e78461ca9d8
|
refs/heads/master
| 2020-06-11T16:14:05.504063
| 2019-07-02T14:20:05
| 2019-07-02T14:20:05
| 194,020,120
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 650
|
py
|
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
expression = input()
opens = tuple("{[(")
close = tuple("}])")
match = dict(zip(opens,close))
check = []
for i in expression:
#print("i is",i)
if i in opens:
check.append(match[i])
#print("check append",i,check)
elif i in close:
if not check or i!= check.pop():
print("false")
quit()
if not check:
print("true")
else:
print("false")
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
|
[
"noreply@github.com"
] |
SpiralT.noreply@github.com
|
6000db7daccd37a78e2c96d02dc7fc51ee9b2d74
|
7d787c2f9b2cb2130a1f3b8cdbc773d2d157b85e
|
/2012/03/blogging-with-wordpress/set-to-publish.py
|
20637ded020320c445bf5239887143011ca378bd
|
[] |
no_license
|
ananelson/dexy-blog
|
632162996937b36832f57d1dde1867fc5c8237ea
|
70402f003bd471ac6e4277e8ec168ef84328b6cf
|
refs/heads/master
| 2016-09-01T18:58:38.102986
| 2015-01-28T04:44:13
| 2015-01-28T04:44:13
| 3,689,629
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 210
|
py
|
import json
import sys
filename = sys.argv[1]
with open(filename, "rb") as f:
data = json.load(f)
data['publish'] = True
with open(filename, "wb") as f:
json.dump(data, f, sort_keys=True, indent=4)
|
[
"ana@ananelson.com"
] |
ana@ananelson.com
|
edd8e5eff2a1895c50da85b6e8978dc81f62a573
|
dc25934eaf8ec6f4eb6b91db48e53554243dad18
|
/utils/data_pro_for_nnsum.py
|
e6fb147424c6ae8d00bfa2be95b5c75b070dd2be
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
Warren195/ecml-pkdd-2019-J3R-explainable-recommender
|
7bf70b4e84545020fed2a885dfd9fd0eed7b9579
|
e3de264bca9b7f4de1026527341ff519d8ab6856
|
refs/heads/master
| 2020-09-15T04:50:33.642127
| 2019-07-16T11:29:01
| 2019-07-16T11:29:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,918
|
py
|
import numpy as np
import re
import itertools
from collections import Counter
import csv
import os
import pickle
import argparse
import spacy
import sys
import tensorflow as tf
import codecs
from nltk import word_tokenize
import json
def mkdirp(path):
if path == '':
return
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
pass
def write_to_onmt_files(data_path, data_file, review_summaries, output_type="nnsum"):
mkdirp(data_path)
fp = codecs.open(data_file, "r", encoding="utf-8")
src_path = "%s.src" % (data_path)
tgt_path = "%s.tgt" % (data_path)
with codecs.open(src_path, 'w', encoding="utf-8") as fp1, codecs.open(tgt_path , 'w', encoding="utf-8") as fp2:
for i, line in enumerate(fp):
line = line.split(',')
user_id = int(line[0])
item_id = int(line[1])
review, summary = review_summaries[(user_id, item_id)]
review_tokens = word_tokenize(review)
summary_tokens = word_tokenize(summary)
if len(review_tokens) < 10 or len(summary_tokens) < 4:
continue
fp1.write(" ".join(review_tokens).lower() + "\n")
fp2.write(" ".join(summary_tokens).lower() + "\n")
def write_to_nnsum_files(data_path, data_file, review_summaries):
mkdirp(data_path)
fp = codecs.open(data_file, "r")
for i, line in enumerate(fp):
line = line.split(',')
user_id = int(line[0])
item_id = int(line[1])
review, summary = review_summaries[(user_id, item_id)]
review_tokens = word_tokenize(review)
summary_tokens = word_tokenize(summary)
if len(review_tokens) < 10 or len(summary_tokens) < 4:
continue
file_path = "%s/%s_%s.json" % (data_path, line[0], line[1])
data = {}
data['user_id'] = user_id
data['item_id'] = item_id
data['review'] = " ".join(review_tokens).lower()
data['summary'] = " ".join(summary_tokens).lower()
with open(file_path, 'w') as outfile:
json.dump(data, outfile)
def load_data(data_path, train_data, valid_data, test_data, review_summary, output_type):
f1 = open(review_summary)
review_summaries = pickle.load(f1)
if output_type == "nnsum":
print("Processing NNSUM training data")
write_to_nnsum_files(data_path + '/train', train_data, review_summaries)
print("Processing NNSUM validation data")
write_to_nnsum_files(data_path + '/valid', valid_data, review_summaries)
print("Processing NNSUM test data")
write_to_nnsum_files(data_path + '/test', valid_data, review_summaries)
if output_type == "onmt":
print("Processing ONMT training data")
write_to_onmt_files(data_path + '/train', train_data, review_summaries)
print("Processing ONMT validation data")
write_to_onmt_files(data_path + '/valid', valid_data, review_summaries)
print("Processing ONMT test data")
write_to_onmt_files(data_path + '/test', valid_data, review_summaries)
def get_args():
''' This function parses and return arguments passed in'''
parser = argparse.ArgumentParser(description='Process Amazon and Yelp data for NNSUM')
parser.add_argument('-d', '--data_set', type=str, help='Dataset music, tv, electronics, kindle, toys, cds, yelp', required=True)
parser.add_argument('-o', '--output_type', type=str, help='Dataset music, tv, electronics, kindle, toys, cds, yelp', required=False, default="nnsum")
args = parser.parse_args()
return args
if __name__ == '__main__':
args = get_args()
TPS_DIR = '../data/%s' %(args.data_set)
tf.flags.DEFINE_string("valid_data","../data/%s/%s_valid.csv" % (args.data_set, args.data_set), "Data for validation")
tf.flags.DEFINE_string("test_data", "../data/%s/%s_test.csv" % (args.data_set, args.data_set), "Data for testing")
tf.flags.DEFINE_string("train_data", "../data/%s/%s_train.csv" % (args.data_set, args.data_set), "Data for training")
tf.flags.DEFINE_string("review_summary", "../data/%s/review_summary" % (args.data_set), "Review Summary Pairs")
tf.flags.DEFINE_string("output_type", args.output_type, "Output Type nnsum or onmt")
if args.output_type == "nnsum":
tf.flags.DEFINE_string("data_path","../../../summarize/nnsum/data/raw/%s/" % (args.data_set), "Data path for NNSUM")
if args.output_type == "onmt":
tf.flags.DEFINE_string("data_path","../../../summarize/OpenNMT-py/data/%s/" % (args.data_set), "Data path for NNSUM")
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
load_data(FLAGS.data_path, FLAGS.train_data, FLAGS.valid_data, FLAGS.test_data, FLAGS.review_summary, FLAGS.output_type)
|
[
"avinesh@aiphes.tu-darmstadt.de"
] |
avinesh@aiphes.tu-darmstadt.de
|
a7bc9a7df0c9d94eb1eede66c7194282299df1c4
|
e7ed228f9f54d3911e3ee76dd7876bce2609240e
|
/src/christmas_tree_firework.py
|
853e0628462b053fd4d3cd55f48e019cd0e2e501
|
[] |
no_license
|
Inndy/tkinter_samples
|
ea1f8f30b11e78e6925a6f4318c9db3174026b8d
|
a5e299694caa6040024b60769fee8f1acbcaaf2e
|
refs/heads/master
| 2023-08-31T10:22:12.192690
| 2015-06-07T06:27:48
| 2015-06-07T06:27:48
| 37,006,955
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,652
|
py
|
import random
import math
from tkinter import *
colors = [ "#00f", "#0f0", "#0ff", "#f00", "#f0f", "#ff0" ]
def draw_triangle(canvas, top, dx, dy):
p1 = (top[0] - dx, top[1] + dy)
p2 = (top[0] + dx, top[1] + dy)
canvas.create_polygon(top + p1 + p2, fill = "#0B610B")
def draw_christmas_tree(canvas, top, n):
for i in range(n):
p = (top[0], top[1] + i * 30)
dx = 70 + i * 15
dy = 40
draw_triangle(canvas, p, dx, dy)
y = top[1] + (n - 1) * 30 + dy
p = (top[0] - 20, y, top[0] + 20, y + 100)
canvas.create_rectangle(p, fill = "#3B170B", outline = "")
def calc_point(center, r, angle):
return (center[0] + r * math.cos((angle - 90) * math.pi / 180),
center[1] + r * math.sin((angle - 90) * math.pi / 180))
def draw_firework(canvas, pos, size, count):
n = random.randint(8, 15)
for i in range(count):
width = random.randint(1, 5)
r1 = random.randint(15, 25)
r2 = size + random.randint(0, 30)
color = random.choice(colors)
for j in range(0, 360, 360 // n):
j += i * 360 // (count * n)
p1 = calc_point(pos, r1, j)
p2 = calc_point(pos, r2, j)
canvas.create_line(p1 + p2, fill = color, width = width)
root = Tk()
root.title("Christmas Tree")
canvas = Canvas(root, width = 600, height = 400)
canvas.grid()
draw_christmas_tree(canvas, (300, 20), 3)
canvas.create_text((200, 20), text = "Merry Christmas!")
for i in range(10):
pos = (random.randint(50, 550), random.randint(50, 350))
draw_firework(canvas, pos, random.randint(10, 50), random.randint(1, 4))
root.mainloop()
|
[
"inndy.mail@gmail.com"
] |
inndy.mail@gmail.com
|
7f2b05a37101aba648ba6c7debe31e448876d76b
|
23d474495347a5270006356e36ac074a7650b350
|
/helper.py
|
9d463c265e248063c04455e8d1289896ebc6f404
|
[] |
no_license
|
kailunxu/eecs445_pj1
|
bbcad171740c2b8edec0d904e948a180c4e12571
|
fa2c54a0173a64e2e8b36127978c9178d5a1c78a
|
refs/heads/master
| 2020-12-28T10:59:43.403072
| 2020-02-04T20:51:22
| 2020-02-04T20:51:22
| 238,302,208
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,651
|
py
|
# EECS 445 - Fall 2019
# Project 1 - helper.py
import pandas as pd
import numpy as np
import project1
def load_data(fname):
"""
Reads in a csv file and return a dataframe. A dataframe df is similar to dictionary.
You can access the label by calling df['label'], the content by df['content']
the rating by df['rating']
"""
return pd.read_csv(fname)
def get_split_binary_data(class_size=500):
"""
Reads in the data from data/dataset.csv and returns it using
extract_dictionary and generate_feature_matrix split into training and test sets.
The binary labels take two values:
-1: poor/average
1: good
Also returns the dictionary used to create the feature matrices.
Input:
class_size: Size of each class (pos/neg) of training dataset.
"""
fname = "data/dataset.csv"
dataframe = load_data(fname)
dataframe = dataframe[dataframe['label'] != 0]
positiveDF = dataframe[dataframe['label'] == 1].copy()
negativeDF = dataframe[dataframe['label'] == -1].copy()
X_train = pd.concat([positiveDF[:class_size], negativeDF[:class_size]]).reset_index(drop=True).copy()
dictionary = project1.extract_dictionary(X_train)
X_test = pd.concat([positiveDF[class_size:(int(1.5 * class_size))],
negativeDF[class_size:(int(1.5 * class_size))]]).reset_index(drop=True).copy()
Y_train = X_train['label'].values.copy()
Y_test = X_test['label'].values.copy()
X_train = project1.generate_feature_matrix(X_train, dictionary)
X_test = project1.generate_feature_matrix(X_test, dictionary)
return (X_train, Y_train, X_test, Y_test, dictionary)
def get_imbalanced_data(dictionary, positive_class_size=800, ratio=0.25):
"""
Reads in the data from data/imbalanced.csv and returns it using
extract_dictionary and generate_feature_matrix as a tuple
(X_train, Y_train) where the labels are binary as follows
-1: poor/average
1: good
Input:
dictionary: the dictionary created via get_split_binary_data
positive_class_size: the size of the positive data
ratio: ratio of negative_class_size to positive_class_size
"""
fname = "data/imbalanced.csv"
dataframe = load_data(fname)
dataframe = dataframe[dataframe['label'] != 0]
positiveDF = dataframe[dataframe['label'] == 1].copy()
negativeDF = dataframe[dataframe['label'] == -1].copy()
dataframe = pd.concat([positiveDF[:positive_class_size],
negativeDF[:(int(positive_class_size * ratio))]]).reset_index(drop=True).copy()
X_train = project1.generate_feature_matrix(dataframe, dictionary)
Y_train = dataframe['label'].values.copy()
return (X_train, Y_train)
def get_imbalanced_test(dictionary, positive_class_size=200, ratio=0.25):
"""
Reads in the data from data/dataset.csv and returns a subset of it
reflecting an imbalanced test dataset
-1: poor/average
1: good
Input:
dictionary: the dictionary created via get_split_binary_data
positive_class_size: the size of the positive data
ratio: ratio of negative_class_size to positive_class_size
"""
fname = "data/dataset.csv"
dataframe = load_data(fname)
dataframe = dataframe[dataframe['label'] != 0]
positiveDF = dataframe[dataframe['label'] == 1].copy()
negativeDF = dataframe[dataframe['label'] == -1].copy()
X_test = pd.concat([positiveDF[:positive_class_size],
negativeDF[:int(positive_class_size * ratio)]]).reset_index(drop=True).copy()
Y_test = X_test['label'].values.copy()
X_test = project1.generate_feature_matrix(X_test, dictionary)
return (X_test, Y_test)
def get_multiclass_training_data(class_size=400):
"""
Reads in the data from data/dataset.csv and returns it using
extract_dictionary and generate_feature_matrix as a tuple
(X_train, Y_train) where the labels are multiclass as follows
-1: poor
0: average
1: good
Also returns the dictionary used to create X_train.
Input:
class_size: Size of each class (pos/neg/neu) of training dataset.
"""
fname = "data/dataset.csv"
dataframe = load_data(fname)
neutralDF = dataframe[dataframe['label'] == 0].copy()
positiveDF = dataframe[dataframe['label'] == 1].copy()
negativeDF = dataframe[dataframe['label'] == -1].copy()
X_train = pd.concat([positiveDF[:class_size], negativeDF[:class_size], neutralDF[:class_size]]).reset_index(drop=True).copy()
dictionary = project1.extract_dictionary(X_train)
Y_train = X_train['label'].values.copy()
X_train = project1.generate_feature_matrix(X_train, dictionary)
return (X_train, Y_train, dictionary)
def get_heldout_reviews(dictionary):
"""
Reads in the data from data/heldout.csv and returns it as a feature
matrix based on the functions extract_dictionary and generate_feature_matrix
Input:
dictionary: the dictionary created by get_multiclass_training_data
"""
fname = "data/heldout.csv"
dataframe = load_data(fname)
X = project1.generate_feature_matrix(dataframe, dictionary)
return X
def generate_challenge_labels(y, uniqname):
"""
Takes in a numpy array that stores the prediction of your multiclass
classifier and output the prediction to held_out_result.csv. Please make sure that
you do not change the order of the ratings in the heldout dataset since we will
this file to evaluate your classifier.
"""
pd.Series(np.array(y)).to_csv(uniqname+'.csv', header=['label'], index=False)
return
|
[
"xukailun@dc3sp13.dc.umich.edu"
] |
xukailun@dc3sp13.dc.umich.edu
|
05178addab477cfead26f5762abbc06e719fc755
|
70cd46dcd43c6a2e197043f70d664abc7b203251
|
/aliyun-python-sdk-ecs/aliyunsdkecs/request/v20140526/ModifyInstanceMaintenanceAttributesRequest.py
|
877c6b6b68a8af5af3a553860b5087a1c0b72363
|
[
"Apache-2.0"
] |
permissive
|
gbhayana96/aliyun-openapi-python-sdk
|
2d5e6aaeafba28d6735bff51f1ae2ea60f1bc5fb
|
59c93f507342bc094ca7d7cf244a611ce2eb5c40
|
refs/heads/master
| 2023-03-01T18:27:57.938577
| 2021-02-08T02:28:19
| 2021-02-08T02:28:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,174
|
py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable 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.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkecs.endpoint import endpoint_data
class ModifyInstanceMaintenanceAttributesRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'ModifyInstanceMaintenanceAttributes','ecs')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_ResourceOwnerId(self):
return self.get_query_params().get('ResourceOwnerId')
def set_ResourceOwnerId(self,ResourceOwnerId):
self.add_query_param('ResourceOwnerId',ResourceOwnerId)
def get_MaintenanceWindows(self):
return self.get_query_params().get('MaintenanceWindow')
def set_MaintenanceWindows(self, MaintenanceWindows):
for depth1 in range(len(MaintenanceWindows)):
if MaintenanceWindows[depth1].get('StartTime') is not None:
self.add_query_param('MaintenanceWindow.' + str(depth1 + 1) + '.StartTime', MaintenanceWindows[depth1].get('StartTime'))
if MaintenanceWindows[depth1].get('EndTime') is not None:
self.add_query_param('MaintenanceWindow.' + str(depth1 + 1) + '.EndTime', MaintenanceWindows[depth1].get('EndTime'))
def get_ActionOnMaintenance(self):
return self.get_query_params().get('ActionOnMaintenance')
def set_ActionOnMaintenance(self,ActionOnMaintenance):
self.add_query_param('ActionOnMaintenance',ActionOnMaintenance)
def get_ResourceOwnerAccount(self):
return self.get_query_params().get('ResourceOwnerAccount')
def set_ResourceOwnerAccount(self,ResourceOwnerAccount):
self.add_query_param('ResourceOwnerAccount',ResourceOwnerAccount)
def get_OwnerAccount(self):
return self.get_query_params().get('OwnerAccount')
def set_OwnerAccount(self,OwnerAccount):
self.add_query_param('OwnerAccount',OwnerAccount)
def get_OwnerId(self):
return self.get_query_params().get('OwnerId')
def set_OwnerId(self,OwnerId):
self.add_query_param('OwnerId',OwnerId)
def get_InstanceIds(self):
return self.get_query_params().get('InstanceId')
def set_InstanceIds(self, InstanceIds):
for depth1 in range(len(InstanceIds)):
if InstanceIds[depth1] is not None:
self.add_query_param('InstanceId.' + str(depth1 + 1) , InstanceIds[depth1])
|
[
"sdk-team@alibabacloud.com"
] |
sdk-team@alibabacloud.com
|
16c2af5664d1d04814a411a2f4af13814e1c0552
|
1c015a97448e5390aa501dc5a8347579611463ef
|
/features/steps/login.py
|
d949827124bf72c07c47df87f339da552a72bdaf
|
[] |
no_license
|
kruczyna/behave_python_with_page_object
|
442e627f9b8cc9cd525351e8503d6fade1585f6f
|
f3b5894d848ffbfd7c1d628d8a754d1d00f2b061
|
refs/heads/master
| 2022-04-04T03:10:16.106446
| 2020-02-23T10:43:37
| 2020-02-23T10:43:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 709
|
py
|
from behave import given, use_step_matcher, when, then
from features.page_objects.login_page import LoginPage
use_step_matcher("re")
@given('I navigate to Sign In form')
def main_page(context):
page = LoginPage(context.driver)
page.navigate_to_sign_in()
@when('I submit "([^"]*)" and "([^"]*)"')
def submit_login_form(context, login, password):
page = LoginPage(context.driver)
page.submit_login_form(login, password)
@then('I see form "([^"]*)" massage')
def form_error(context, error):
page = LoginPage(context.driver)
page.login_form_error(error)
@then('I am a logged in user')
def login_to_website(context):
page = LoginPage(context.driver)
page.logged_in_user()
|
[
"victoria.kruczek@stxnext.pl"
] |
victoria.kruczek@stxnext.pl
|
9354365fdbc89661fb16a9f1d392e782d4f4d306
|
fc2c13f82401bf3476d306ca83a6971933cfcd9b
|
/pairsamtools/pairsam_phase.py
|
4f9a9602df5623df18d5e4b272e5190017bdb32e
|
[
"MIT"
] |
permissive
|
OlgaVT/pairsamtools
|
e86750485f84d1dd4527855634fc0713e45f470d
|
a951a3982e464a62b93c8e8594436f5a2d7b1f2d
|
refs/heads/master
| 2020-03-17T11:04:38.449324
| 2018-05-08T11:17:44
| 2018-05-08T11:17:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,658
|
py
|
import sys
import click
import re, fnmatch
from . import _fileio, _pairsam_format, cli, _headerops, common_io_options
UTIL_NAME = 'pairsam_phase'
@cli.command()
@click.argument(
'pairsam_path',
type=str,
required=False)
@click.option(
'-o', "--output",
type=str,
default="",
help='output file.'
' If the path ends with .gz or .lz4, the output is pbgzip-/lz4c-compressed.'
' By default, the output is printed into stdout.')
@click.option(
"--phase-suffixes",
nargs=2,
#type=click.Tuple([str, str]),
help='phase suffixes.'
)
@click.option(
"--clean-output",
is_flag=True,
help='drop all columns besides the standard ones and phase1/2'
)
@common_io_options
def phase(
pairsam_path,
output,
phase_suffixes,
clean_output,
**kwargs
):
'''
PAIRSAM_PATH : input .pairsam file. If the path ends with .gz or .lz4, the
input is decompressed by pbgzip/lz4c. By default, the input is read from stdin.
'''
phase_py(
pairsam_path, output, phase_suffixes, clean_output,
**kwargs
)
def phase_py(
pairsam_path, output, phase_suffixes, clean_output,
**kwargs
):
instream = (_fileio.auto_open(pairsam_path, mode='r',
nproc=kwargs.get('nproc_in'),
command=kwargs.get('cmd_in', None))
if pairsam_path else sys.stdin)
outstream = (_fileio.auto_open(output, mode='w',
nproc=kwargs.get('nproc_out'),
command=kwargs.get('cmd_out', None))
if output else sys.stdout)
header, body_stream = _headerops.get_header(instream)
header = _headerops.append_new_pg(header, ID=UTIL_NAME, PN=UTIL_NAME)
old_column_names = _headerops.extract_column_names(header)
if clean_output:
new_column_names = [col for col in old_column_names
if col in _pairsam_format.COLUMNS]
new_column_idxs = [i for i,col in enumerate(old_column_names)
if col in _pairsam_format.COLUMNS] + [
len(old_column_names), len(old_column_names)+1]
else:
new_column_names = list(old_column_names)
new_column_names.append('phase1')
new_column_names.append('phase2')
header = _headerops._update_header_entry(
header, 'columns', ' '.join(new_column_names))
if ( ('XA1' not in old_column_names)
or ('XA2' not in old_column_names)
or ('AS1' not in old_column_names)
or ('AS2' not in old_column_names)
or ('XS1' not in old_column_names)
or ('XS2' not in old_column_names)
):
raise ValueError(
'The input pairs file must be parsed with the flag --add-columns XA,AS,XS --min-mapq 0')
COL_XA1 = old_column_names.index('XA1')
COL_XA2 = old_column_names.index('XA2')
COL_AS1 = old_column_names.index('AS1')
COL_AS2 = old_column_names.index('AS2')
COL_XS1 = old_column_names.index('XS1')
COL_XS2 = old_column_names.index('XS2')
outstream.writelines((l+'\n' for l in header))
def get_chrom_phase(chrom, phase_suffixes):
if chrom.endswith(phase_suffixes[0]):
return '0', chrom[:-len(phase_suffixes[0])]
elif chrom.endswith(phase_suffixes[1]):
return '1', chrom[:-len(phase_suffixes[1])]
else:
return '!', chrom
def phase_side(chrom, XA, AS, XS, phase_suffixes):
phase, chrom_base = get_chrom_phase(chrom, phase_suffixes)
XAs = XA.split(';')
if AS > XS:
return phase, chrom_base
else:
# this should be technically impossible, b/c when AS==XS at least
# one alternative alignment must be reported
if len(XAs) == 1 and len(XAs[0]) == 0:
return phase, chrom_base
elif len(XAs) == 1 and len(XAs[0]) > 0:
alt_chrom, alt_pos, alt_CIGAR, alt_NM = XAs[0].split(',')
alt_phase, alt_chrom_base = get_chrom_phase(alt_chrom, phase_suffixes)
alt_is_homologue = (
(chrom_base == alt_chrom_base)
and
(
((phase=='0') and (alt_phase=='1'))
or
((phase=='1') and (alt_phase=='0'))
)
)
if alt_is_homologue:
return '.', chrom_base
return '!', '!'
for line in body_stream:
cols = line.rstrip().split(_pairsam_format.PAIRSAM_SEP)
cols.append('!')
cols.append('!')
pair_type = cols[_pairsam_format.COL_PTYPE]
if cols[_pairsam_format.COL_C1] != _pairsam_format.UNMAPPED_CHROM:
phase1, chrom_base1 = phase_side(
cols[_pairsam_format.COL_C1],
cols[COL_XA1],
int(cols[COL_AS1]),
int(cols[COL_XS1]),
phase_suffixes
)
cols[-2] = phase1
cols[_pairsam_format.COL_C1] = chrom_base1
if chrom_base1 == '!':
cols[_pairsam_format.COL_C1] = _pairsam_format.UNMAPPED_CHROM
cols[_pairsam_format.COL_P1] = str(_pairsam_format.UNMAPPED_POS)
cols[_pairsam_format.COL_S1] = _pairsam_format.UNMAPPED_STRAND
pair_type = 'M' + pair_type[1]
if cols[_pairsam_format.COL_C2] != _pairsam_format.UNMAPPED_CHROM:
phase2, chrom_base2 = phase_side(
cols[_pairsam_format.COL_C2],
cols[COL_XA2],
int(cols[COL_AS2]),
int(cols[COL_XS2]),
phase_suffixes
)
cols[-1] = phase2
cols[_pairsam_format.COL_C2] = chrom_base2
if chrom_base2 == '!':
cols[_pairsam_format.COL_C2] = _pairsam_format.UNMAPPED_CHROM
cols[_pairsam_format.COL_P2] = str(_pairsam_format.UNMAPPED_POS)
cols[_pairsam_format.COL_S2] = _pairsam_format.UNMAPPED_STRAND
pair_type = pair_type[0] + 'M'
cols[_pairsam_format.COL_PTYPE] = pair_type
if clean_output:
cols = [cols[i] for i in new_column_idxs]
outstream.write(_pairsam_format.PAIRSAM_SEP.join(cols))
outstream.write('\n')
if instream != sys.stdin:
instream.close()
if outstream != sys.stdout:
outstream.close()
if __name__ == '__main__':
phase()
|
[
"agalitzina@gmail.com"
] |
agalitzina@gmail.com
|
cefce502e45b0f5489d3a2c4b13d4c0838bba046
|
6a61f19dd5e5d8cc9e6d7c20af2df93a17a85d94
|
/Notes/Python/src/exercise/reverse_iter_demo.py
|
71c5a85d2527fd411d9e15c701ae09b097c205fa
|
[
"MIT"
] |
permissive
|
liuhll/BlogAndNotes
|
4d6e8aa426a6bb511c4b2c16039bdfb60ccaf13b
|
23b3b69178b0616837cd6f0b588bda943366b448
|
refs/heads/master
| 2021-06-12T06:00:28.489670
| 2016-12-12T14:25:48
| 2016-12-12T14:25:48
| 65,984,223
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 671
|
py
|
# -*- coding:utf-8 -*-
class FloatRange(object):
def __init__(self,start,end,step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
t = self.start
while t <= self.end:
yield t
t += self.step
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
# 正向迭代
for x in FloatRange(1,10,0.2):
print x
print "-"*40
# 逆向迭代,使用python的内置函数 reversed(iter_obj) ,需要可迭代对象实现了专有函数 __reversed__()
for x in reversed(FloatRange(1,10,0.5)):
print x
|
[
"1029765111@qq.com"
] |
1029765111@qq.com
|
80553f6f8277ae9b88e910fd2ce12233c9070760
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02389/s602338133.py
|
30cae6914208cdbb7161fe208d08cdf68b405004
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102
| 2021-05-13T17:27:22
| 2021-05-13T17:27:22
| 367,112,348
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 64
|
py
|
k = map(int,raw_input().split())
print k[0]*k[1],k[0]*2+k[1]*2
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
19160147765c6671b5a24625c6fcd96f28b45701
|
dc965a62709bbb2c6c9ad01859a83507d7457941
|
/Assignments/Class Assignments/ownfromkeysMethod.py
|
d6966305ed7b2703cc1cfe6cc77ddcc6e01db57a
|
[] |
no_license
|
JyotiSathe/Python
|
ead31a84cde86d734acdf0ad83c27c6bb1c1a331
|
846371d678ba225c210493605233b262a51bd950
|
refs/heads/master
| 2021-05-11T22:38:30.299035
| 2018-06-24T14:08:37
| 2018-06-24T14:08:37
| 117,364,196
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,225
|
py
|
def fromkeys_my(x,y):
temp={}
if(type(y)==int):
temp=dict.fromkeys(x,y)
else:
i=0
if(len(y)>=len(x.keys())):
for key in x:
temp[key]=y[i]
i+=1
elif(len(y)<len(x.keys())):
for key in x:
if(len(y)!=i):
temp[key]=y[i]
else:
temp[key]="None"
i+=1
return temp
def fromkeys(input_dict,output_dict_values):
result_dict={}
if(type(output_dict_values)==list or type(output_dict_values)==tuple):
keys_list=input_dict.keys()
values_length=len(output_dict_values)
for i in range(len(keys_list)):
if i<values_length:
result_dict[keys_list[i]]=output_dict_values[i]
else:
result_dict[keys_list[i]]="None"
else:
result_dict=dict.fromkeys(input_dict,output_dict_values)
return result_dict
def main():
#x={1:2,2:3,3:4}
x=input("Enter dictionary")
y=input("Enter what you want to enter as values")
result=fromkeys(x,y)
print result
if __name__=='__main__':
main()
|
[
"noreply@github.com"
] |
JyotiSathe.noreply@github.com
|
1f0b4dca55699e00e3c7e179f5cb4a1a40c1a91b
|
2080822bc6a185c7b76e11dd6f0cfa7f1d2c3e5e
|
/lib-test/test_serialize.py
|
9510b866528e09d88a6d80f4968091260f633f53
|
[] |
no_license
|
yunlongmain/python-test
|
13cbd4ca89397547a404622ca683053d1179b7a9
|
791d714651bbf132e21ba89b83e31d7a200ed05e
|
refs/heads/master
| 2020-04-06T07:00:10.241178
| 2015-04-13T08:43:58
| 2015-04-13T08:43:58
| 33,234,227
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 533
|
py
|
# coding=utf-8
'''
cPickle包的功能和用法与pickle包几乎完全相同 (其存在差别的地方实际上很少用到),不同在于cPickle是基于c语言编写的,速度是pickle包的1000倍
如果想使用cPickle包,我们都可以将import语句改为:
'''
import cPickle as pickle
# define class
class Bird(object):
have_feather = True
way_of_reproduction = 'egg'
summer = Bird() # construct an object
picklestring = pickle.dumps(summer) # serialize object
print(picklestring)
|
[
"yunlong@baidu.com"
] |
yunlong@baidu.com
|
87b90834369ef9117e632a6ed4d575c6e8ab8f1b
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_011/ch29_2019_04_12_15_04_40_053669.py
|
9f61e6f295344ce342be9d70439027af77e7c7e8
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 125
|
py
|
def calcula_aumento(x):
calcula_aumento=x*0.10
if x<=1250:
calcula_aumento=x*0.15
return calcula_aumento
|
[
"you@example.com"
] |
you@example.com
|
e8161252e675f5b794937524d2cf6fe8ac4544e2
|
a9bc638b83cbb4023bf9ee974b258922a6b4e19b
|
/projeto/consulta/models.py
|
c8ad218375a926785389e7ac6e1ad9904ea99064
|
[] |
no_license
|
ThiagoRossiRocha/sistemaPythonDjangoTriagemCovid19
|
9916205cee622019a3076da8ca414d2f57128088
|
25a9cced7b09b9621dd7a4b1f0461de7c2e17789
|
refs/heads/main
| 2023-04-29T23:00:55.391971
| 2023-04-13T14:29:52
| 2023-04-13T14:29:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,392
|
py
|
from __future__ import unicode_literals
from datetime import datetime
from django.core.validators import MaxValueValidator, MinValueValidator
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from utils.gerador_hash import gerar_hash
class Consulta(models.Model):
medico = models.ForeignKey('usuario.Usuario', verbose_name= 'Médico na consulta *', on_delete=models.PROTECT, related_name='medico')
unidade = models.ForeignKey('unidade.Unidade', verbose_name= 'Unidade de Atendimento *', on_delete=models.PROTECT, related_name='unidade_consulta')
data = models.DateField('Data da consulta ', max_length=10, help_text='Use dd/mm/aaaa')
hora = models.TimeField('Hora da consulta ', max_length=10, help_text='Use hh:mm')
paciente = models.CharField('Informe o nome completo do paciente *', max_length=100, help_text= '* indica campos obrigatórios')
prescricao = models.TextField('Prescrição *', max_length=1000, help_text= '* indica campos obrigatórios')
medicamentos = models.ManyToManyField('medicamento.Medicamento', verbose_name='Medicamento(s)', null=True, blank=True, related_name='medicamento', help_text='Para selecionar ou deselecionar um medicamento pressione CTRL + Botão Esquerdo do mouse ou Command + Botão Esquerdo do mouse')
slug = models.SlugField('Hash',max_length= 200, null=True, blank=True)
objects = models.Manager()
class Meta:
ordering = ['-data', '-hora', 'paciente']
verbose_name = ('consulta')
verbose_name_plural = ('consultas')
unique_together = [['data','hora','paciente']]
def __str__(self):
return "Paciente: %s. Médico: %s. Data: %s. Hora: %s." % (self.paciente, self.medico, self.data, self.hora)
def save(self, *args, **kwargs):
self.paciente = self.paciente.upper()
self.data = datetime.now()
self.hora = datetime.now()
if not self.slug:
self.slug = gerar_hash()
super(Consulta, self).save(*args, **kwargs)
@property
def get_absolute_url(self):
return reverse('consulta_update', args=[str(self.id)])
@property
def get_delete_url(self):
return reverse('consulta_delete', args=[str(self.id)])
|
[
"alexandre.o.zamberlan@gmail.com"
] |
alexandre.o.zamberlan@gmail.com
|
c8d4fac6b49562381cb01ed28c0a2a36f666b573
|
004f8f49e335f8e41462eae512bbe20d750fce8c
|
/rldb/db/paper__dudqn/algo__human/__init__.py
|
b357cc070b9982d22f87cc8a797e54ab755442e6
|
[
"MIT"
] |
permissive
|
seungjaeryanlee/rldb
|
3ab4317e26a39e6fa9b6e7ed9063907dc6a60070
|
8c471c4666d6210c68f3cb468e439a2b168c785d
|
refs/heads/master
| 2020-04-29T15:50:26.890588
| 2019-12-19T08:31:12
| 2019-12-19T08:31:12
| 176,241,314
| 52
| 2
|
MIT
| 2019-05-16T06:33:17
| 2019-03-18T08:54:24
|
Python
|
UTF-8
|
Python
| false
| false
| 425
|
py
|
"""
DuDQN scores from DuDQN paper.
114 entries
- 49 human entries from Gorila DQN
------------------------------------------------------------------------
65 unique entries
"""
from .entries import entries
# Specify ALGORITHM
algo = {
# ALGORITHM
"algo-title": "Human",
"algo-nickname": "Human",
}
# Populate entries
entries = [{**entry, **algo} for entry in entries]
assert len(entries) == 8 + 57
|
[
"noreply@github.com"
] |
seungjaeryanlee.noreply@github.com
|
68e787e4648287ca6ae2ab5203c404c0bd1053f8
|
9102f34f89867d2cc9b31ba64ab352019ccdc623
|
/wordSegment/lstm.py
|
b950a3172be32ade046029511c07e89968cd342c
|
[] |
no_license
|
sadscv/NLP_assignment
|
8d8632ac17da68620d66b13aef6858997d3912a7
|
3231f96810e188d1d54dee0c521b703eac68d1a3
|
refs/heads/master
| 2021-01-17T15:46:52.435967
| 2017-06-13T13:08:09
| 2017-06-13T13:08:09
| 83,686,202
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,729
|
py
|
import os
import theano
import theano.tensor as T
import numpy as np
class LSTM(object):
def __init__(self, embedding_dim, hidden_dim, num_clas, wind_size, vocab_size, bptt_truncate=-1):
'''
embedding_dim : dimension of word embeddings
hidden_dim : dimension of hidden layer
num_clas : number of classes
wind_size : word window context size
vocab_size : vocabulary size
'''
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.num_clas = num_clas
self.wind_size = wind_size
self.vocab_size = vocab_size
self.bptt_truncate = bptt_truncate
# Randomly initialize the network parameters
self.E = theano.shared(np.random.uniform(-np.sqrt(1./embedding_dim), np.sqrt(1./embedding_dim), \
(vocab_size+1, embedding_dim)).astype(theano.config.floatX))
self.U = theano.shared(np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), \
(4, embedding_dim * wind_size, hidden_dim)).astype(theano.config.floatX))
self.W = theano.shared(np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), \
(4, hidden_dim, hidden_dim)).astype(theano.config.floatX))
self.V = theano.shared(np.random.uniform(-np.sqrt(1./hidden_dim), np.sqrt(1./hidden_dim), \
(hidden_dim, num_clas)).astype(theano.config.floatX))
self.b = theano.shared(np.zeros((4, hidden_dim)).astype(theano.config.floatX))
self.c = theano.shared(np.zeros(num_clas).astype(theano.config.floatX))
self.params = [self.E, self.U, self.W, self.V, self.b, self.c]
self.names = ['E', 'U', 'W', 'V', 'b', 'c']
self.__theano_build__()
def __theano_build__(self):
idxs = T.imatrix()
x = self.E[idxs].reshape((idxs.shape[0], self.wind_size * self.embedding_dim))
y = T.ivector('y')
def forward_prop_step(x_t, s_t_prev, c_t_prev):
# LSTM layer
i_t = T.nnet.hard_sigmoid(T.dot(x_t, self.U[0]) + T.dot(s_t_prev, self.W[0]) + self.b[0])
f_t = T.nnet.hard_sigmoid(T.dot(x_t, self.U[1]) + T.dot(s_t_prev, self.W[1]) + self.b[1])
o_t = T.nnet.hard_sigmoid(T.dot(x_t, self.U[2]) + T.dot(s_t_prev, self.W[2]) + self.b[2])
g_t = T.tanh(T.dot(x_t, self.U[3]) + T.dot(s_t_prev, self.W[3]) + self.b[3])
c_t = c_t_prev * f_t + g_t * i_t
s_t = T.tanh(c_t) * o_t
# Final output calculation
# Theano's softmax returns a matrix with one row, we only need the row
output_t = T.nnet.softmax(T.dot(s_t, self.V) + self.c)[0]
return [output_t, s_t, c_t]
[o, s, c], _ = theano.scan(
forward_prop_step,
sequences = x,
truncate_gradient = self.bptt_truncate,
outputs_info = [None,
dict(initial=T.zeros(self.hidden_dim)),
dict(initial=T.zeros(self.hidden_dim))])
prediction = T.argmax(o, axis=1)
o_err = T.sum(T.nnet.categorical_crossentropy(o, y))
# square of L2 norm
self.l2_sqr = 0
self.l2_sqr += (self.W ** 2).sum()
self.l2_sqr += (self.U ** 2).sum()
self.l2_sqr += (self.V ** 2).sum()
# Totol cost (could add regularization here)
cost = o_err + 0.0002 * self.l2_sqr
# Gradients
dE = T.grad(cost, self.E)
dU = T.grad(cost, self.U)
dW = T.grad(cost, self.W)
dV = T.grad(cost, self.V)
db = T.grad(cost, self.b)
dc = T.grad(cost, self.c)
self.predict = theano.function([idxs], o)
self.predict_class = theano.function([idxs], prediction)
self.ce_err = theano.function([idxs, y], cost)
lr = T.scalar('learning_rate')
self.sgd_step = theano.function(
[idxs, y, lr],
[],
updates = [(self.E, self.E - lr * dE),
(self.U, self.U - lr * dU),
(self.W, self.W - lr * dW),
(self.V, self.V - lr * dV),
(self.b, self.b - lr * db),
(self.c, self.c - lr * dc)])
def calculate_total_loss(self, X, Y):
return np.sum([self.ce_err(x, y) for x, y in zip(X, Y) if len(y) >= 5])
def calculate_loss(self, X, Y):
num_words = np.sum([len(y) for y in Y])
return self.calculate_total_loss(X,Y) / float(num_words)
def save_model(self, floder):
for param, name in zip(self.params, self.names):
np.save(os.path.join(floder, name + '.npy'), param.get_value())
print("save model to %s." % floder)
|
[
"sadscv@hotmail.com"
] |
sadscv@hotmail.com
|
44131fa42f5759fc67f906e586dd6a2cf2a72c78
|
10388e24c0668a6176d2b961a9465bc02e3535b9
|
/lib/ua/agents/yahoo.py
|
36573fd8724de97f4047bb88557e9bd620722092
|
[
"BSD-2-Clause"
] |
permissive
|
hdknr/ua
|
5d6e90b23b94200136ceb3be986566df066c8fcd
|
bc41f5b46fb99d0d576c7542c2184b39679f4ebf
|
refs/heads/master
| 2021-05-16T02:03:18.266356
| 2016-10-02T20:55:07
| 2016-10-02T20:55:07
| 18,771,412
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 111
|
py
|
''' Yahoo Bot
'''
from . import BaseAgent, DeviceClass
class Agent(BaseAgent):
CLASS = DeviceClass.OTHER
|
[
"hdknr@ic-tact.co.jp"
] |
hdknr@ic-tact.co.jp
|
8073129917effeaa239d559288fe4dff61937ca0
|
37fdc797f0060a67c1e9318032bc7102d4fd9ecd
|
/spider/beautifulsoup_test/lib/python3.7/site-packages/twisted/conch/ssh/keys.py
|
fe5798703c0ab2b1464a40a85cc1d996b054efc6
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
Change0224/PycharmProjects
|
8fa3d23b399c5fb55661a79ca059f3da79847feb
|
818ba4fd5dd8bcdaacae490ed106ffda868b6ca4
|
refs/heads/master
| 2021-02-06T15:37:16.653849
| 2020-03-03T14:30:44
| 2020-03-03T14:30:44
| 243,927,023
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 55,143
|
py
|
# -*- threading_test-case-name: twisted.conch.threading_test.test_keys -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Handling of RSA, DSA, and EC keys.
"""
from __future__ import absolute_import, division
import binascii
import itertools
from hashlib import md5, sha256
import base64
import struct
import bcrypt
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa, rsa, padding, ec
from cryptography.hazmat.primitives.serialization import (
load_pem_private_key, load_ssh_public_key)
from cryptography import utils
try:
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_dss_signature, decode_dss_signature)
except ImportError:
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_rfc6979_signature as encode_dss_signature,
decode_rfc6979_signature as decode_dss_signature)
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from pyasn1.error import PyAsn1Error
from pyasn1.type import univ
from pyasn1.codec.ber import decoder as berDecoder
from pyasn1.codec.ber import encoder as berEncoder
from twisted.conch.ssh import common, sexpy
from twisted.conch.ssh.common import int_from_bytes, int_to_bytes
from twisted.python import randbytes
from twisted.python.compat import (
iterbytes, long, izip, nativeString, unicode, _PY3,
_b64decodebytes as decodebytes, _b64encodebytes as encodebytes)
from twisted.python.constants import NamedConstant, Names
# Curve lookup table
_curveTable = {
b'ecdsa-sha2-nistp256': ec.SECP256R1(),
b'ecdsa-sha2-nistp384': ec.SECP384R1(),
b'ecdsa-sha2-nistp521': ec.SECP521R1(),
}
_secToNist = {
b'secp256r1' : b'nistp256',
b'secp384r1' : b'nistp384',
b'secp521r1' : b'nistp521',
}
class BadKeyError(Exception):
"""
Raised when a key isn't what we expected from it.
XXX: we really need to check for bad keys
"""
class EncryptedKeyError(Exception):
"""
Raised when an encrypted key is presented to fromString/fromFile without
a password.
"""
class BadFingerPrintFormat(Exception):
"""
Raises when unsupported fingerprint formats are presented to fingerprint.
"""
class FingerprintFormats(Names):
"""
Constants representing the supported formats of key fingerprints.
@cvar MD5_HEX: Named constant representing fingerprint format generated
using md5[RFC1321] algorithm in hexadecimal encoding.
@type MD5_HEX: L{twisted.python.constants.NamedConstant}
@cvar SHA256_BASE64: Named constant representing fingerprint format
generated using sha256[RFC4634] algorithm in base64 encoding
@type SHA256_BASE64: L{twisted.python.constants.NamedConstant}
"""
MD5_HEX = NamedConstant()
SHA256_BASE64 = NamedConstant()
class Key(object):
"""
An object representing a key. A key can be either a public or
private key. A public key can verify a signature; a private key can
create or verify a signature. To generate a string that can be stored
on disk, use the toString method. If you have a private key, but want
the string representation of the public key, use Key.public().toString().
"""
@classmethod
def fromFile(cls, filename, type=None, passphrase=None):
"""
Load a key from a file.
@param filename: The path to load key data from.
@type type: L{str} or L{None}
@param type: A string describing the format the key data is in, or
L{None} to attempt detection of the type.
@type passphrase: L{bytes} or L{None}
@param passphrase: The passphrase the key is encrypted with, or L{None}
if there is no encryption.
@rtype: L{Key}
@return: The loaded key.
"""
with open(filename, 'rb') as f:
return cls.fromString(f.read(), type, passphrase)
@classmethod
def fromString(cls, data, type=None, passphrase=None):
"""
Return a Key object corresponding to the string data.
type is optionally the type of string, matching a _fromString_*
method. Otherwise, the _guessStringType() classmethod will be used
to guess a type. If the key is encrypted, passphrase is used as
the decryption key.
@type data: L{bytes}
@param data: The key data.
@type type: L{str} or L{None}
@param type: A string describing the format the key data is in, or
L{None} to attempt detection of the type.
@type passphrase: L{bytes} or L{None}
@param passphrase: The passphrase the key is encrypted with, or L{None}
if there is no encryption.
@rtype: L{Key}
@return: The loaded key.
"""
if isinstance(data, unicode):
data = data.encode("utf-8")
if isinstance(passphrase, unicode):
passphrase = passphrase.encode("utf-8")
if type is None:
type = cls._guessStringType(data)
if type is None:
raise BadKeyError('cannot guess the type of %r' % (data,))
method = getattr(cls, '_fromString_%s' % (type.upper(),), None)
if method is None:
raise BadKeyError('no _fromString method for %s' % (type,))
if method.__code__.co_argcount == 2: # No passphrase
if passphrase:
raise BadKeyError('key not encrypted')
return method(data)
else:
return method(data, passphrase)
@classmethod
def _fromString_BLOB(cls, blob):
"""
Return a public key object corresponding to this public key blob.
The format of a RSA public key blob is::
string 'ssh-rsa'
integer e
integer n
The format of a DSA public key blob is::
string 'ssh-dss'
integer p
integer q
integer g
integer y
The format of ECDSA-SHA2-* public key blob is::
string 'ecdsa-sha2-[identifier]'
integer x
integer y
identifier is the standard NIST curve name.
@type blob: L{bytes}
@param blob: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if the key type (the first string) is unknown.
"""
keyType, rest = common.getNS(blob)
if keyType == b'ssh-rsa':
e, n, rest = common.getMP(rest, 2)
return cls(
rsa.RSAPublicNumbers(e, n).public_key(default_backend()))
elif keyType == b'ssh-dss':
p, q, g, y, rest = common.getMP(rest, 4)
return cls(
dsa.DSAPublicNumbers(
y=y,
parameter_numbers=dsa.DSAParameterNumbers(
p=p,
q=q,
g=g
)
).public_key(default_backend())
)
elif keyType in _curveTable:
return cls(
ec.EllipticCurvePublicKey.from_encoded_point(
_curveTable[keyType], common.getNS(rest, 2)[1]
)
)
else:
raise BadKeyError('unknown blob type: %s' % (keyType,))
@classmethod
def _fromString_PRIVATE_BLOB(cls, blob):
"""
Return a private key object corresponding to this private key blob.
The blob formats are as follows:
RSA keys::
string 'ssh-rsa'
integer n
integer e
integer d
integer u
integer p
integer q
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
EC keys::
string 'ecdsa-sha2-[identifier]'
string identifier
string q
integer privateValue
identifier is the standard NIST curve name.
@type blob: L{bytes}
@param blob: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if
* the key type (the first string) is unknown
* the curve name of an ECDSA key does not match the key type
"""
keyType, rest = common.getNS(blob)
if keyType == b'ssh-rsa':
n, e, d, u, p, q, rest = common.getMP(rest, 6)
return cls._fromRSAComponents(n=n, e=e, d=d, p=p, q=q)
elif keyType == b'ssh-dss':
p, q, g, y, x, rest = common.getMP(rest, 5)
return cls._fromDSAComponents(y=y, g=g, p=p, q=q, x=x)
elif keyType in _curveTable:
curve = _curveTable[keyType]
curveName, q, rest = common.getNS(rest, 2)
if curveName != _secToNist[curve.name.encode('ascii')]:
raise BadKeyError('ECDSA curve name %r does not match key '
'type %r' % (curveName, keyType))
privateValue, rest = common.getMP(rest)
return cls._fromECEncodedPoint(
encodedPoint=q, curve=keyType, privateValue=privateValue)
else:
raise BadKeyError('unknown blob type: %s' % (keyType,))
@classmethod
def _fromString_PUBLIC_OPENSSH(cls, data):
"""
Return a public key object corresponding to this OpenSSH public key
string. The format of an OpenSSH public key string is::
<key type> <base64-encoded public key blob>
@type data: L{bytes}
@param data: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if the blob type is unknown.
"""
# ECDSA keys don't need base64 decoding which is required
# for RSA or DSA key.
if data.startswith(b'ecdsa-sha2'):
return cls(load_ssh_public_key(data, default_backend()))
blob = decodebytes(data.split()[1])
return cls._fromString_BLOB(blob)
@classmethod
def _fromPrivateOpenSSH_v1(cls, data, passphrase):
"""
Return a private key object corresponding to this OpenSSH private key
string, in the "openssh-key-v1" format introduced in OpenSSH 6.5.
The format of an openssh-key-v1 private key string is::
-----BEGIN OPENSSH PRIVATE KEY-----
<base64-encoded SSH protocol string>
-----END OPENSSH PRIVATE KEY-----
The SSH protocol string is as described in
U{PROTOCOL.key<https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.key>}.
@type data: L{bytes}
@param data: The key data.
@type passphrase: L{bytes} or L{None}
@param passphrase: The passphrase the key is encrypted with, or L{None}
if it is not encrypted.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if
* a passphrase is provided for an unencrypted key
* the SSH protocol encoding is incorrect
@raises EncryptedKeyError: if
* a passphrase is not provided for an encrypted key
"""
lines = data.strip().splitlines()
keyList = decodebytes(b''.join(lines[1:-1]))
if not keyList.startswith(b'openssh-key-v1\0'):
raise BadKeyError('unknown OpenSSH private key format')
keyList = keyList[len(b'openssh-key-v1\0'):]
cipher, kdf, kdfOptions, rest = common.getNS(keyList, 3)
n = struct.unpack('!L', rest[:4])[0]
if n != 1:
raise BadKeyError('only OpenSSH private key files containing '
'a single key are supported')
# Ignore public key
_, encPrivKeyList, _ = common.getNS(rest[4:], 2)
if cipher != b'none':
if not passphrase:
raise EncryptedKeyError('Passphrase must be provided '
'for an encrypted key')
# Determine cipher
if cipher in (b'aes128-ctr', b'aes192-ctr', b'aes256-ctr'):
algorithmClass = algorithms.AES
blockSize = 16
keySize = int(cipher[3:6]) // 8
ivSize = blockSize
else:
raise BadKeyError('unknown encryption type %r' % (cipher,))
if kdf == b'bcrypt':
salt, rest = common.getNS(kdfOptions)
rounds = struct.unpack('!L', rest[:4])[0]
decKey = bcrypt.kdf(
passphrase, salt, keySize + ivSize, rounds,
# We can only use the number of rounds that OpenSSH used.
ignore_few_rounds=True)
else:
raise BadKeyError('unknown KDF type %r' % (kdf,))
if (len(encPrivKeyList) % blockSize) != 0:
raise BadKeyError('bad padding')
decryptor = Cipher(
algorithmClass(decKey[:keySize]),
modes.CTR(decKey[keySize:keySize + ivSize]),
backend=default_backend()
).decryptor()
privKeyList = (
decryptor.update(encPrivKeyList) + decryptor.finalize())
else:
if kdf != b'none':
raise BadKeyError('private key specifies KDF %r but no '
'cipher' % (kdf,))
privKeyList = encPrivKeyList
check1 = struct.unpack('!L', privKeyList[:4])[0]
check2 = struct.unpack('!L', privKeyList[4:8])[0]
if check1 != check2:
raise BadKeyError('check values do not match: %d != %d' %
(check1, check2))
return cls._fromString_PRIVATE_BLOB(privKeyList[8:])
@classmethod
def _fromPrivateOpenSSH_PEM(cls, data, passphrase):
"""
Return a private key object corresponding to this OpenSSH private key
string, in the old PEM-based format.
The format of a PEM-based OpenSSH private key string is::
-----BEGIN <key type> PRIVATE KEY-----
[Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,<initialization value>]
<base64-encoded ASN.1 structure>
------END <key type> PRIVATE KEY------
The ASN.1 structure of a RSA key is::
(0, n, e, d, p, q)
The ASN.1 structure of a DSA key is::
(0, p, q, g, y, x)
The ASN.1 structure of a ECDSA key is::
(ECParameters, OID, NULL)
@type data: L{bytes}
@param data: The key data.
@type passphrase: L{bytes} or L{None}
@param passphrase: The passphrase the key is encrypted with, or L{None}
if it is not encrypted.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if
* a passphrase is provided for an unencrypted key
* the ASN.1 encoding is incorrect
@raises EncryptedKeyError: if
* a passphrase is not provided for an encrypted key
"""
lines = data.strip().splitlines()
kind = lines[0][11:-17]
if lines[1].startswith(b'Proc-Type: 4,ENCRYPTED'):
if not passphrase:
raise EncryptedKeyError('Passphrase must be provided '
'for an encrypted key')
# Determine cipher and initialization vector
try:
_, cipherIVInfo = lines[2].split(b' ', 1)
cipher, ivdata = cipherIVInfo.rstrip().split(b',', 1)
except ValueError:
raise BadKeyError('invalid DEK-info %r' % (lines[2],))
if cipher in (b'AES-128-CBC', b'AES-256-CBC'):
algorithmClass = algorithms.AES
keySize = int(cipher.split(b'-')[1]) // 8
if len(ivdata) != 32:
raise BadKeyError('AES encrypted key with a bad IV')
elif cipher == b'DES-EDE3-CBC':
algorithmClass = algorithms.TripleDES
keySize = 24
if len(ivdata) != 16:
raise BadKeyError('DES encrypted key with a bad IV')
else:
raise BadKeyError('unknown encryption type %r' % (cipher,))
# Extract keyData for decoding
iv = bytes(bytearray([int(ivdata[i:i + 2], 16)
for i in range(0, len(ivdata), 2)]))
ba = md5(passphrase + iv[:8]).digest()
bb = md5(ba + passphrase + iv[:8]).digest()
decKey = (ba + bb)[:keySize]
b64Data = decodebytes(b''.join(lines[3:-1]))
decryptor = Cipher(
algorithmClass(decKey),
modes.CBC(iv),
backend=default_backend()
).decryptor()
keyData = decryptor.update(b64Data) + decryptor.finalize()
removeLen = ord(keyData[-1:])
keyData = keyData[:-removeLen]
else:
b64Data = b''.join(lines[1:-1])
keyData = decodebytes(b64Data)
try:
decodedKey = berDecoder.decode(keyData)[0]
except PyAsn1Error as e:
raise BadKeyError(
'Failed to decode key (Bad Passphrase?): %s' % (e,))
if kind == b'EC':
return cls(
load_pem_private_key(data, passphrase, default_backend()))
if kind == b'RSA':
if len(decodedKey) == 2: # Alternate RSA key
decodedKey = decodedKey[0]
if len(decodedKey) < 6:
raise BadKeyError('RSA key failed to decode properly')
n, e, d, p, q, dmp1, dmq1, iqmp = [
long(value) for value in decodedKey[1:9]
]
return cls(
rsa.RSAPrivateNumbers(
p=p,
q=q,
d=d,
dmp1=dmp1,
dmq1=dmq1,
iqmp=iqmp,
public_numbers=rsa.RSAPublicNumbers(e=e, n=n),
).private_key(default_backend())
)
elif kind == b'DSA':
p, q, g, y, x = [long(value) for value in decodedKey[1: 6]]
if len(decodedKey) < 6:
raise BadKeyError('DSA key failed to decode properly')
return cls(
dsa.DSAPrivateNumbers(
x=x,
public_numbers=dsa.DSAPublicNumbers(
y=y,
parameter_numbers=dsa.DSAParameterNumbers(
p=p,
q=q,
g=g
)
)
).private_key(backend=default_backend())
)
else:
raise BadKeyError("unknown key type %s" % (kind,))
@classmethod
def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
"""
Return a private key object corresponding to this OpenSSH private key
string. If the key is encrypted, passphrase MUST be provided.
Providing a passphrase for an unencrypted key is an error.
@type data: L{bytes}
@param data: The key data.
@type passphrase: L{bytes} or L{None}
@param passphrase: The passphrase the key is encrypted with, or L{None}
if it is not encrypted.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if
* a passphrase is provided for an unencrypted key
* the encoding is incorrect
@raises EncryptedKeyError: if
* a passphrase is not provided for an encrypted key
"""
if data.strip().splitlines()[0][11:-17] == b'OPENSSH':
# New-format (openssh-key-v1) key
return cls._fromPrivateOpenSSH_v1(data, passphrase)
else:
# Old-format (PEM) key
return cls._fromPrivateOpenSSH_PEM(data, passphrase)
@classmethod
def _fromString_PUBLIC_LSH(cls, data):
"""
Return a public key corresponding to this LSH public key string.
The LSH public key string format is::
<s-expression: ('public-key', (<key type>, (<name, <value>)+))>
The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
The names for a DSA (key type 'dsa') key are: y, g, p, q.
@type data: L{bytes}
@param data: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if the key type is unknown
"""
sexp = sexpy.parse(decodebytes(data[1:-1]))
assert sexp[0] == b'public-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.getMP(common.NS(data))[0]
if sexp[1][0] == b'dsa':
return cls._fromDSAComponents(
y=kd[b'y'], g=kd[b'g'], p=kd[b'p'], q=kd[b'q'])
elif sexp[1][0] == b'rsa-pkcs1-sha1':
return cls._fromRSAComponents(n=kd[b'n'], e=kd[b'e'])
else:
raise BadKeyError('unknown lsh key type %s' % (sexp[1][0],))
@classmethod
def _fromString_PRIVATE_LSH(cls, data):
"""
Return a private key corresponding to this LSH private key string.
The LSH private key string format is::
<s-expression: ('private-key', (<key type>, (<name>, <value>)+))>
The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
The names for a DSA (key type 'dsa') key are: y, g, p, q, x.
@type data: L{bytes}
@param data: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if the key type is unknown
"""
sexp = sexpy.parse(data)
assert sexp[0] == b'private-key'
kd = {}
for name, data in sexp[1][1:]:
kd[name] = common.getMP(common.NS(data))[0]
if sexp[1][0] == b'dsa':
assert len(kd) == 5, len(kd)
return cls._fromDSAComponents(
y=kd[b'y'], g=kd[b'g'], p=kd[b'p'], q=kd[b'q'], x=kd[b'x'])
elif sexp[1][0] == b'rsa-pkcs1':
assert len(kd) == 8, len(kd)
if kd[b'p'] > kd[b'q']: # Make p smaller than q
kd[b'p'], kd[b'q'] = kd[b'q'], kd[b'p']
return cls._fromRSAComponents(
n=kd[b'n'], e=kd[b'e'], d=kd[b'd'], p=kd[b'p'], q=kd[b'q'])
else:
raise BadKeyError('unknown lsh key type %s' % (sexp[1][0],))
@classmethod
def _fromString_AGENTV3(cls, data):
"""
Return a private key object corresponsing to the Secure Shell Key
Agent v3 format.
The SSH Key Agent v3 format for a RSA key is::
string 'ssh-rsa'
integer e
integer d
integer n
integer u
integer p
integer q
The SSH Key Agent v3 format for a DSA key is::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
@type data: L{bytes}
@param data: The key data.
@return: A new key.
@rtype: L{twisted.conch.ssh.keys.Key}
@raises BadKeyError: if the key type (the first string) is unknown
"""
keyType, data = common.getNS(data)
if keyType == b'ssh-dss':
p, data = common.getMP(data)
q, data = common.getMP(data)
g, data = common.getMP(data)
y, data = common.getMP(data)
x, data = common.getMP(data)
return cls._fromDSAComponents(y=y, g=g, p=p, q=q, x=x)
elif keyType == b'ssh-rsa':
e, data = common.getMP(data)
d, data = common.getMP(data)
n, data = common.getMP(data)
u, data = common.getMP(data)
p, data = common.getMP(data)
q, data = common.getMP(data)
return cls._fromRSAComponents(n=n, e=e, d=d, p=p, q=q, u=u)
else:
raise BadKeyError("unknown key type %s" % (keyType,))
@classmethod
def _guessStringType(cls, data):
"""
Guess the type of key in data. The types map to _fromString_*
methods.
@type data: L{bytes}
@param data: The key data.
"""
if data.startswith(b'ssh-') or data.startswith(b'ecdsa-sha2-'):
return 'public_openssh'
elif data.startswith(b'-----BEGIN'):
return 'private_openssh'
elif data.startswith(b'{'):
return 'public_lsh'
elif data.startswith(b'('):
return 'private_lsh'
elif data.startswith(b'\x00\x00\x00\x07ssh-') or data.startswith(b'\x00\x00\x00\x13ecdsa-'):
ignored, rest = common.getNS(data)
count = 0
while rest:
count += 1
ignored, rest = common.getMP(rest)
if count > 4:
return 'agentv3'
else:
return 'blob'
@classmethod
def _fromRSAComponents(cls, n, e, d=None, p=None, q=None, u=None):
"""
Build a key from RSA numerical components.
@type n: L{int}
@param n: The 'n' RSA variable.
@type e: L{int}
@param e: The 'e' RSA variable.
@type d: L{int} or L{None}
@param d: The 'd' RSA variable (optional for a public key).
@type p: L{int} or L{None}
@param p: The 'p' RSA variable (optional for a public key).
@type q: L{int} or L{None}
@param q: The 'q' RSA variable (optional for a public key).
@type u: L{int} or L{None}
@param u: The 'u' RSA variable. Ignored, as its value is determined by
p and q.
@rtype: L{Key}
@return: An RSA key constructed from the values as given.
"""
publicNumbers = rsa.RSAPublicNumbers(e=e, n=n)
if d is None:
# We have public components.
keyObject = publicNumbers.public_key(default_backend())
else:
privateNumbers = rsa.RSAPrivateNumbers(
p=p,
q=q,
d=d,
dmp1=rsa.rsa_crt_dmp1(d, p),
dmq1=rsa.rsa_crt_dmq1(d, q),
iqmp=rsa.rsa_crt_iqmp(p, q),
public_numbers=publicNumbers,
)
keyObject = privateNumbers.private_key(default_backend())
return cls(keyObject)
@classmethod
def _fromDSAComponents(cls, y, p, q, g, x=None):
"""
Build a key from DSA numerical components.
@type y: L{int}
@param y: The 'y' DSA variable.
@type p: L{int}
@param p: The 'p' DSA variable.
@type q: L{int}
@param q: The 'q' DSA variable.
@type g: L{int}
@param g: The 'g' DSA variable.
@type x: L{int} or L{None}
@param x: The 'x' DSA variable (optional for a public key)
@rtype: L{Key}
@return: A DSA key constructed from the values as given.
"""
publicNumbers = dsa.DSAPublicNumbers(
y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
if x is None:
# We have public components.
keyObject = publicNumbers.public_key(default_backend())
else:
privateNumbers = dsa.DSAPrivateNumbers(
x=x, public_numbers=publicNumbers)
keyObject = privateNumbers.private_key(default_backend())
return cls(keyObject)
@classmethod
def _fromECComponents(cls, x, y, curve, privateValue=None):
"""
Build a key from EC components.
@param x: The affine x component of the public point used for verifying.
@type x: L{int}
@param y: The affine y component of the public point used for verifying.
@type y: L{int}
@param curve: NIST name of elliptic curve.
@type curve: L{bytes}
@param privateValue: The private value.
@type privateValue: L{int}
"""
publicNumbers = ec.EllipticCurvePublicNumbers(
x=x, y=y, curve=_curveTable[curve])
if privateValue is None:
# We have public components.
keyObject = publicNumbers.public_key(default_backend())
else:
privateNumbers = ec.EllipticCurvePrivateNumbers(
private_value=privateValue, public_numbers=publicNumbers)
keyObject = privateNumbers.private_key(default_backend())
return cls(keyObject)
@classmethod
def _fromECEncodedPoint(cls, encodedPoint, curve, privateValue=None):
"""
Build a key from an EC encoded point.
@param encodedPoint: The public point encoded as in SEC 1 v2.0
section 2.3.3.
@type encodedPoint: L{bytes}
@param curve: NIST name of elliptic curve.
@type curve: L{bytes}
@param privateValue: The private value.
@type privateValue: L{int}
"""
if privateValue is None:
# We have public components.
keyObject = ec.EllipticCurvePublicKey.from_encoded_point(
_curveTable[curve], encodedPoint
)
else:
keyObject = ec.derive_private_key(
privateValue, _curveTable[curve], default_backend()
)
return cls(keyObject)
def __init__(self, keyObject):
"""
Initialize with a private or public
C{cryptography.hazmat.primitives.asymmetric} key.
@param keyObject: Low level key.
@type keyObject: C{cryptography.hazmat.primitives.asymmetric} key.
"""
self._keyObject = keyObject
def __eq__(self, other):
"""
Return True if other represents an object with the same key.
"""
if type(self) == type(other):
return self.type() == other.type() and self.data() == other.data()
else:
return NotImplemented
def __ne__(self, other):
"""
Return True if other represents anything other than this key.
"""
result = self.__eq__(other)
if result == NotImplemented:
return result
return not result
def __repr__(self):
"""
Return a pretty representation of this object.
"""
if self.type() == 'EC':
data = self.data()
name = data['curve'].decode('utf-8')
if self.isPublic():
out = '<Elliptic Curve Public Key (%s bits)' % (name[-3:],)
else:
out = '<Elliptic Curve Private Key (%s bits)' % (name[-3:],)
for k, v in sorted(data.items()):
if _PY3 and k == 'curve':
out += "\ncurve:\n\t%s" % (name,)
else:
out += "\n%s:\n\t%s" % (k, v)
return out + ">\n"
else:
lines = [
'<%s %s (%s bits)' % (
nativeString(self.type()),
self.isPublic() and 'Public Key' or 'Private Key',
self._keyObject.key_size)]
for k, v in sorted(self.data().items()):
lines.append('attr %s:' % (k,))
by = common.MP(v)[4:]
while by:
m = by[:15]
by = by[15:]
o = ''
for c in iterbytes(m):
o = o + '%02x:' % (ord(c),)
if len(m) < 15:
o = o[:-1]
lines.append('\t' + o)
lines[-1] = lines[-1] + '>'
return '\n'.join(lines)
def isPublic(self):
"""
Check if this instance is a public key.
@return: C{True} if this is a public key.
"""
return isinstance(
self._keyObject,
(rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey))
def public(self):
"""
Returns a version of this key containing only the public key data.
If this is a public key, this may or may not be the same object
as self.
@rtype: L{Key}
@return: A public key.
"""
if self.isPublic():
return self
else:
return Key(self._keyObject.public_key())
def fingerprint(self, format=FingerprintFormats.MD5_HEX):
"""
The fingerprint of a public key consists of the output of the
message-digest algorithm in the specified format.
Supported formats include L{FingerprintFormats.MD5_HEX} and
L{FingerprintFormats.SHA256_BASE64}
The input to the algorithm is the public key data as specified by [RFC4253].
The output of sha256[RFC4634] algorithm is presented to the
user in the form of base64 encoded sha256 hashes.
Example: C{US5jTUa0kgX5ZxdqaGF0yGRu8EgKXHNmoT8jHKo1StM=}
The output of the MD5[RFC1321](default) algorithm is presented to the user as
a sequence of 16 octets printed as hexadecimal with lowercase letters
and separated by colons.
Example: C{c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87}
@param format: Format for fingerprint generation. Consists
hash function and representation format.
Default is L{FingerprintFormats.MD5_HEX}
@since: 8.2
@return: the user presentation of this L{Key}'s fingerprint, as a
string.
@rtype: L{str}
"""
if format is FingerprintFormats.SHA256_BASE64:
return nativeString(base64.b64encode(
sha256(self.blob()).digest()))
elif format is FingerprintFormats.MD5_HEX:
return nativeString(
b':'.join([binascii.hexlify(x)
for x in iterbytes(md5(self.blob()).digest())]))
else:
raise BadFingerPrintFormat(
'Unsupported fingerprint format: %s' % (format,))
def type(self):
"""
Return the type of the object we wrap. Currently this can only be
'RSA', 'DSA', or 'EC'.
@rtype: L{str}
@raises RuntimeError: If the object type is unknown.
"""
if isinstance(
self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)):
return 'RSA'
elif isinstance(
self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)):
return 'DSA'
elif isinstance(
self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)):
return 'EC'
else:
raise RuntimeError(
'unknown type of object: %r' % (self._keyObject,))
def sshType(self):
"""
Get the type of the object we wrap as defined in the SSH protocol,
defined in RFC 4253, Section 6.6. Currently this can only be b'ssh-rsa',
b'ssh-dss' or b'ecdsa-sha2-[identifier]'.
identifier is the standard NIST curve name
@return: The key type format.
@rtype: L{bytes}
"""
if self.type() == 'EC':
return b'ecdsa-sha2-' + _secToNist[self._keyObject.curve.name.encode('ascii')]
else:
return {'RSA': b'ssh-rsa', 'DSA': b'ssh-dss'}[self.type()]
def size(self):
"""
Return the size of the object we wrap.
@return: The size of the key.
@rtype: L{int}
"""
if self._keyObject is None:
return 0
elif self.type() == 'EC':
return self._keyObject.curve.key_size
return self._keyObject.key_size
def data(self):
"""
Return the values of the public key as a dictionary.
@rtype: L{dict}
"""
if isinstance(self._keyObject, rsa.RSAPublicKey):
numbers = self._keyObject.public_numbers()
return {
"n": numbers.n,
"e": numbers.e,
}
elif isinstance(self._keyObject, rsa.RSAPrivateKey):
numbers = self._keyObject.private_numbers()
return {
"n": numbers.public_numbers.n,
"e": numbers.public_numbers.e,
"d": numbers.d,
"p": numbers.p,
"q": numbers.q,
# Use a trick: iqmp is q^-1 % p, u is p^-1 % q
"u": rsa.rsa_crt_iqmp(numbers.q, numbers.p),
}
elif isinstance(self._keyObject, dsa.DSAPublicKey):
numbers = self._keyObject.public_numbers()
return {
"y": numbers.y,
"g": numbers.parameter_numbers.g,
"p": numbers.parameter_numbers.p,
"q": numbers.parameter_numbers.q,
}
elif isinstance(self._keyObject, dsa.DSAPrivateKey):
numbers = self._keyObject.private_numbers()
return {
"x": numbers.x,
"y": numbers.public_numbers.y,
"g": numbers.public_numbers.parameter_numbers.g,
"p": numbers.public_numbers.parameter_numbers.p,
"q": numbers.public_numbers.parameter_numbers.q,
}
elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
numbers = self._keyObject.public_numbers()
return {
"x": numbers.x,
"y": numbers.y,
"curve": self.sshType(),
}
elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
numbers = self._keyObject.private_numbers()
return {
"x": numbers.public_numbers.x,
"y": numbers.public_numbers.y,
"privateValue": numbers.private_value,
"curve": self.sshType(),
}
else:
raise RuntimeError("Unexpected key type: %s" % (self._keyObject,))
def blob(self):
"""
Return the public key blob for this key. The blob is the
over-the-wire format for public keys.
SECSH-TRANS RFC 4253 Section 6.6.
RSA keys::
string 'ssh-rsa'
integer e
integer n
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
EC keys::
string 'ecdsa-sha2-[identifier]'
integer x
integer y
identifier is the standard NIST curve name
@rtype: L{bytes}
"""
type = self.type()
data = self.data()
if type == 'RSA':
return (common.NS(b'ssh-rsa') + common.MP(data['e']) +
common.MP(data['n']))
elif type == 'DSA':
return (common.NS(b'ssh-dss') + common.MP(data['p']) +
common.MP(data['q']) + common.MP(data['g']) +
common.MP(data['y']))
else: # EC
byteLength = (self._keyObject.curve.key_size + 7) // 8
return (common.NS(data['curve']) + common.NS(data["curve"][-8:]) +
common.NS(b'\x04' + utils.int_to_bytes(data['x'], byteLength) +
utils.int_to_bytes(data['y'], byteLength)))
def privateBlob(self):
"""
Return the private key blob for this key. The blob is the
over-the-wire format for private keys:
Specification in OpenSSH PROTOCOL.agent
RSA keys::
string 'ssh-rsa'
integer n
integer e
integer d
integer u
integer p
integer q
DSA keys::
string 'ssh-dss'
integer p
integer q
integer g
integer y
integer x
EC keys::
string 'ecdsa-sha2-[identifier]'
integer x
integer y
integer privateValue
identifier is the NIST standard curve name.
"""
type = self.type()
data = self.data()
if type == 'RSA':
iqmp = rsa.rsa_crt_iqmp(data['p'], data['q'])
return (common.NS(b'ssh-rsa') + common.MP(data['n']) +
common.MP(data['e']) + common.MP(data['d']) +
common.MP(iqmp) + common.MP(data['p']) +
common.MP(data['q']))
elif type == 'DSA':
return (common.NS(b'ssh-dss') + common.MP(data['p']) +
common.MP(data['q']) + common.MP(data['g']) +
common.MP(data['y']) + common.MP(data['x']))
else: # EC
return (common.NS(data['curve']) + common.MP(data['x']) +
common.MP(data['y']) + common.MP(data['privateValue']))
def toString(self, type, extra=None):
"""
Create a string representation of this key. If the key is a private
key and you want the representation of its public key, use
C{key.public().toString()}. type maps to a _toString_* method.
@param type: The type of string to emit. Currently supported values
are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
@type type: L{str}
@param extra: Any extra data supported by the selected format which
is not part of the key itself. For public OpenSSH keys, this is
a comment. For private OpenSSH keys, this is a passphrase to
encrypt with.
@type extra: L{bytes} or L{unicode} or L{None}
@rtype: L{bytes}
"""
if isinstance(extra, unicode):
extra = extra.encode("utf-8")
method = getattr(self, '_toString_%s' % (type.upper(),), None)
if method is None:
raise BadKeyError('unknown key type: %s' % (type,))
if method.__code__.co_argcount == 2:
return method(extra)
else:
return method()
def _toString_OPENSSH(self, extra):
"""
Return a public or private OpenSSH string. See
_fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the
string formats. If extra is present, it represents a comment for a
public key, or a passphrase for a private key.
@param extra: Comment for a public key or passphrase for a
private key
@type extra: L{bytes}
@rtype: L{bytes}
"""
data = self.data()
if self.isPublic():
if self.type() == 'EC':
if not extra:
extra = b''
return (self._keyObject.public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH
) + b' ' + extra).strip()
b64Data = encodebytes(self.blob()).replace(b'\n', b'')
if not extra:
extra = b''
return (self.sshType() + b' ' + b64Data + b' ' + extra).strip()
else:
if self.type() == 'EC':
# EC keys has complex ASN.1 structure hence we do this this way.
if not extra:
# unencrypted private key
encryptor = serialization.NoEncryption()
else:
encryptor = serialization.BestAvailableEncryption(extra)
return self._keyObject.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
encryptor)
lines = [b''.join((b'-----BEGIN ', self.type().encode('ascii'),
b' PRIVATE KEY-----'))]
if self.type() == 'RSA':
p, q = data['p'], data['q']
iqmp = rsa.rsa_crt_iqmp(p, q)
objData = (0, data['n'], data['e'], data['d'], p, q,
data['d'] % (p - 1), data['d'] % (q - 1),
iqmp)
else:
objData = (0, data['p'], data['q'], data['g'], data['y'],
data['x'])
asn1Sequence = univ.Sequence()
for index, value in izip(itertools.count(), objData):
asn1Sequence.setComponentByPosition(index, univ.Integer(value))
asn1Data = berEncoder.encode(asn1Sequence)
if extra:
iv = randbytes.secureRandom(8)
hexiv = ''.join(['%02X' % (ord(x),) for x in iterbytes(iv)])
hexiv = hexiv.encode('ascii')
lines.append(b'Proc-Type: 4,ENCRYPTED')
lines.append(b'DEK-Info: DES-EDE3-CBC,' + hexiv + b'\n')
ba = md5(extra + iv).digest()
bb = md5(ba + extra + iv).digest()
encKey = (ba + bb)[:24]
padLen = 8 - (len(asn1Data) % 8)
asn1Data += (chr(padLen) * padLen).encode('ascii')
encryptor = Cipher(
algorithms.TripleDES(encKey),
modes.CBC(iv),
backend=default_backend()
).encryptor()
asn1Data = encryptor.update(asn1Data) + encryptor.finalize()
b64Data = encodebytes(asn1Data).replace(b'\n', b'')
lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)]
lines.append(b''.join((b'-----END ', self.type().encode('ascii'),
b' PRIVATE KEY-----')))
return b'\n'.join(lines)
def _toString_LSH(self):
"""
Return a public or private LSH key. See _fromString_PUBLIC_LSH and
_fromString_PRIVATE_LSH for the key formats.
@rtype: L{bytes}
"""
data = self.data()
type = self.type()
if self.isPublic():
if type == 'RSA':
keyData = sexpy.pack([[b'public-key',
[b'rsa-pkcs1-sha1',
[b'n', common.MP(data['n'])[4:]],
[b'e', common.MP(data['e'])[4:]]]]])
elif type == 'DSA':
keyData = sexpy.pack([[b'public-key',
[b'dsa',
[b'p', common.MP(data['p'])[4:]],
[b'q', common.MP(data['q'])[4:]],
[b'g', common.MP(data['g'])[4:]],
[b'y', common.MP(data['y'])[4:]]]]])
else:
raise BadKeyError("unknown key type %s" % (type,))
return (b'{' + encodebytes(keyData).replace(b'\n', b'') +
b'}')
else:
if type == 'RSA':
p, q = data['p'], data['q']
iqmp = rsa.rsa_crt_iqmp(p, q)
return sexpy.pack([[b'private-key',
[b'rsa-pkcs1',
[b'n', common.MP(data['n'])[4:]],
[b'e', common.MP(data['e'])[4:]],
[b'd', common.MP(data['d'])[4:]],
[b'p', common.MP(q)[4:]],
[b'q', common.MP(p)[4:]],
[b'a', common.MP(
data['d'] % (q - 1))[4:]],
[b'b', common.MP(
data['d'] % (p - 1))[4:]],
[b'c', common.MP(iqmp)[4:]]]]])
elif type == 'DSA':
return sexpy.pack([[b'private-key',
[b'dsa',
[b'p', common.MP(data['p'])[4:]],
[b'q', common.MP(data['q'])[4:]],
[b'g', common.MP(data['g'])[4:]],
[b'y', common.MP(data['y'])[4:]],
[b'x', common.MP(data['x'])[4:]]]]])
else:
raise BadKeyError("unknown key type %s'" % (type,))
def _toString_AGENTV3(self):
"""
Return a private Secure Shell Agent v3 key. See
_fromString_AGENTV3 for the key format.
@rtype: L{bytes}
"""
data = self.data()
if not self.isPublic():
if self.type() == 'RSA':
values = (data['e'], data['d'], data['n'], data['u'],
data['p'], data['q'])
elif self.type() == 'DSA':
values = (data['p'], data['q'], data['g'], data['y'],
data['x'])
return common.NS(self.sshType()) + b''.join(map(common.MP, values))
def sign(self, data):
"""
Sign some data with this key.
SECSH-TRANS RFC 4253 Section 6.6.
@type data: L{bytes}
@param data: The data to sign.
@rtype: L{bytes}
@return: A signature for the given data.
"""
keyType = self.type()
if keyType == 'RSA':
sig = self._keyObject.sign(data, padding.PKCS1v15(), hashes.SHA1())
ret = common.NS(sig)
elif keyType == 'DSA':
sig = self._keyObject.sign(data, hashes.SHA1())
(r, s) = decode_dss_signature(sig)
# SSH insists that the DSS signature blob be two 160-bit integers
# concatenated together. The sig[0], [1] numbers from obj.sign
# are just numbers, and could be any length from 0 to 160 bits.
# Make sure they are padded out to 160 bits (20 bytes each)
ret = common.NS(int_to_bytes(r, 20) + int_to_bytes(s, 20))
elif keyType == 'EC': # Pragma: no branch
# Hash size depends on key size
keySize = self.size()
if keySize <= 256:
hashSize = hashes.SHA256()
elif keySize <= 384:
hashSize = hashes.SHA384()
else:
hashSize = hashes.SHA512()
signature = self._keyObject.sign(data, ec.ECDSA(hashSize))
(r, s) = decode_dss_signature(signature)
rb = int_to_bytes(r)
sb = int_to_bytes(s)
# Int_to_bytes returns rb[0] as a str in python2
# and an as int in python3
if type(rb[0]) is str:
rcomp = ord(rb[0])
else:
rcomp = rb[0]
# If the MSB is set, prepend a null byte for correct formatting.
if rcomp & 0x80:
rb = b"\x00" + rb
if type(sb[0]) is str:
scomp = ord(sb[0])
else:
scomp = sb[0]
if scomp & 0x80:
sb = b"\x00" + sb
ret = common.NS(common.NS(rb) + common.NS(sb))
return common.NS(self.sshType()) + ret
def verify(self, signature, data):
"""
Verify a signature using this key.
@type signature: L{bytes}
@param signature: The signature to verify.
@type data: L{bytes}
@param data: The signed data.
@rtype: L{bool}
@return: C{True} if the signature is valid.
"""
if len(signature) == 40:
# DSA key with no padding
signatureType, signature = b'ssh-dss', common.NS(signature)
else:
signatureType, signature = common.getNS(signature)
if signatureType != self.sshType():
return False
keyType = self.type()
if keyType == 'RSA':
k = self._keyObject
if not self.isPublic():
k = k.public_key()
args = (
common.getNS(signature)[0],
data,
padding.PKCS1v15(),
hashes.SHA1(),
)
elif keyType == 'DSA':
concatenatedSignature = common.getNS(signature)[0]
r = int_from_bytes(concatenatedSignature[:20], 'big')
s = int_from_bytes(concatenatedSignature[20:], 'big')
signature = encode_dss_signature(r, s)
k = self._keyObject
if not self.isPublic():
k = k.public_key()
args = (signature, data, hashes.SHA1())
elif keyType == 'EC': # Pragma: no branch
concatenatedSignature = common.getNS(signature)[0]
rstr, sstr, rest = common.getNS(concatenatedSignature, 2)
r = int_from_bytes(rstr, 'big')
s = int_from_bytes(sstr, 'big')
signature = encode_dss_signature(r, s)
k = self._keyObject
if not self.isPublic():
k = k.public_key()
keySize = self.size()
if keySize <= 256: # Hash size depends on key size
hashSize = hashes.SHA256()
elif keySize <= 384:
hashSize = hashes.SHA384()
else:
hashSize = hashes.SHA512()
args = (signature, data, ec.ECDSA(hashSize))
try:
k.verify(*args)
except InvalidSignature:
return False
else:
return True
def _getPersistentRSAKey(location, keySize=4096):
"""
This function returns a persistent L{Key}.
The key is loaded from a PEM file in C{location}. If it does not exist, a
key with the key size of C{keySize} is generated and saved.
@param location: Where the key is stored.
@type location: L{twisted.python.filepath.FilePath}
@param keySize: The size of the key, if it needs to be generated.
@type keySize: L{int}
@returns: A persistent key.
@rtype: L{Key}
"""
location.parent().makedirs(ignoreExistingDirectory=True)
# If it doesn't exist, we want to generate a new key and save it
if not location.exists():
privateKey = rsa.generate_private_key(
public_exponent=65537,
key_size=keySize,
backend=default_backend()
)
pem = privateKey.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
location.setContent(pem)
# By this point (save any hilarious race conditions) we should have a
# working PEM file. Load it!
# (Future archaeological readers: I chose not to short circuit above,
# because then there's two exit paths to this code!)
with location.open("rb") as keyFile:
privateKey = serialization.load_pem_private_key(
keyFile.read(),
password=None,
backend=default_backend()
)
return Key(privateKey)
|
[
"lijj0224@163.com"
] |
lijj0224@163.com
|
4ad6c645c3472bd641fdab6e780eb708a37c8502
|
8a7071ecb065b03a5ed5d685bffa34109a728c45
|
/Pandas/06_summary_of_dataframe.py
|
dd601e6fcbad51faadd76bf0425d0b6ae2550138
|
[] |
no_license
|
RinkuAkash/Python-libraries-for-ML
|
a932dfc0aefae15e4c9047075b5de9de32207b39
|
c9e4393631b4b77b71e771021f4946f900c091b3
|
refs/heads/master
| 2020-12-14T11:48:29.131421
| 2020-01-24T12:19:38
| 2020-01-24T12:19:38
| 234,731,712
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 715
|
py
|
'''
Created on 21/01/2020
@author: B Akash
'''
'''
Problem statement:
Write a Python program to display a summary of the basic information about a specified Data Frame and its data.
Sample Python dictionary data and list labels:
'''
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
dataFrame=pd.DataFrame(exam_data,labels)
print(dataFrame.describe())
|
[
"akashrinku2@outlook.com"
] |
akashrinku2@outlook.com
|
b87e493684eee5cb2ba9da10d55a6b2bef34c4b5
|
adb47f48c7cf998ec673ec7c975e71fbbcdc65d9
|
/maximising_xor.py
|
0282d03832694b7f019f4c0970dea95509101574
|
[] |
no_license
|
jamoemills/misc
|
6f9d362926d05b587bd10735cdfeb4ee3f8252a0
|
9fc011b6ccaf0f549ae38023c57be0df61942085
|
refs/heads/master
| 2021-01-11T03:17:48.158088
| 2015-01-20T12:19:06
| 2015-01-20T12:19:06
| 28,448,119
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 360
|
py
|
#!\usr\bin\python
# -*- coding: utf-8 -*-
import sys
def maxXor( l, r):
Xor_values = []
x = r - l
while x != 0:
for i in range(l + x, r + 1): # O(n**2)
Xor = (l + x) ^ i
Xor_values.append(Xor)
x -= 1
return max(Xor_values)
_l = sys.stdin.readline()
_r = sys.stdin.readline()
_l = int(_l)
_r = int(_r)
res = maxXor(_l, _r);
print(res)
|
[
"jamiermiles@me.com"
] |
jamiermiles@me.com
|
0269e2a46b181e82f34c2d0a59334f0cbc1bfd5d
|
fd09b4aff625d7a7c960e10af3c12a1107085c65
|
/01_using_azure_ml/project_1_optimizing_an_ml_pipeline_in_azure/train.py
|
89ceed821b5eb7f1642bde97e8eb3f547e9e4dc6
|
[] |
no_license
|
sebastianbirk/udacity-aml-engineer-nanodegree
|
d5eb752f63662ffae39001aba1050abb224d28f1
|
ce31bd06b7a925cc8cbc61330e71fdff779b5ea7
|
refs/heads/master
| 2023-02-02T04:37:26.236319
| 2020-12-18T15:39:04
| 2020-12-18T15:39:04
| 318,105,050
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,002
|
py
|
from sklearn.linear_model import LogisticRegression
import argparse
import os
import joblib
import numpy as np
from sklearn.metrics import mean_squared_error
import joblib
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
from azureml.core.run import Run
from azureml.data.dataset_factory import TabularDatasetFactory
def clean_data(data, split=True):
# Dict for cleaning data
months = {"jan":1, "feb":2, "mar":3, "apr":4, "may":5, "jun":6, "jul":7, "aug":8, "sep":9, "oct":10, "nov":11, "dec":12}
weekdays = {"mon":1, "tue":2, "wed":3, "thu":4, "fri":5, "sat":6, "sun":7}
# Clean and one hot encode data
x_df = data.to_pandas_dataframe().dropna()
jobs = pd.get_dummies(x_df.job, prefix="job")
x_df.drop("job", inplace=True, axis=1)
x_df = x_df.join(jobs)
x_df["marital"] = x_df.marital.apply(lambda s: 1 if s == "married" else 0)
x_df["default"] = x_df.default.apply(lambda s: 1 if s == "yes" else 0)
x_df["housing"] = x_df.housing.apply(lambda s: 1 if s == "yes" else 0)
x_df["loan"] = x_df.loan.apply(lambda s: 1 if s == "yes" else 0)
contact = pd.get_dummies(x_df.contact, prefix="contact")
x_df.drop("contact", inplace=True, axis=1)
x_df = x_df.join(contact)
education = pd.get_dummies(x_df.education, prefix="education")
x_df.drop("education", inplace=True, axis=1)
x_df = x_df.join(education)
x_df["month"] = x_df.month.map(months)
x_df["day_of_week"] = x_df.day_of_week.map(weekdays)
x_df["poutcome"] = x_df.poutcome.apply(lambda s: 1 if s == "success" else 0)
if not split:
return x_df
else:
y_df = x_df.pop("y").apply(lambda s: 1 if s == "yes" else 0)
return x_df, y_df
def main():
run = Run.get_context()
# Add arguments to script
parser = argparse.ArgumentParser()
parser.add_argument('--C', type=float, default=1.0, help="Inverse of regularization strength. Smaller values cause stronger regularization")
parser.add_argument('--max_iter', type=int, default=100, help="Maximum number of iterations to converge")
args = parser.parse_args()
run.log("Regularization Strength:", np.float(args.C))
run.log("Max iterations:", np.int(args.max_iter))
ds = TabularDatasetFactory.from_delimited_files("https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/bankmarketing_train.csv")
x, y = clean_data(ds)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
model = LogisticRegression(C=args.C, max_iter=args.max_iter).fit(x_train, y_train)
accuracy = model.score(x_test, y_test)
run.log("Accuracy", np.float(accuracy))
os.makedirs('outputs', exist_ok=True)
# files saved in the "outputs" folder are automatically uploaded into run history
joblib.dump(model, 'outputs/hyperdrive_model.pkl')
if __name__ == '__main__':
main()
|
[
"sebastian.birk@outlook.com"
] |
sebastian.birk@outlook.com
|
5fe834ca4a1aa9f6217f7c8772b850527aa6581d
|
6646f40d8a43c03e3499141d3388220add677d94
|
/exception.py
|
c16aeaf1d1a6781737d1c1ba9c172791a4bd4377
|
[] |
no_license
|
andrewnnov/Auto_py
|
63a14bc7d6532d3b02ac7a59e02d82c2fe2aad53
|
cf3aa1b7cfde4f305282f44164a7af24c24b03be
|
refs/heads/master
| 2021-02-20T23:56:55.851037
| 2020-04-21T19:29:59
| 2020-04-21T19:29:59
| 245,347,276
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 733
|
py
|
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Переменная symbol должна быть односимвольной строкой.')
if width <=2:
raise Exception('Значение width должно превышать 2.')
if height <=2:
raise Exception('Значение height должно превышать 2.')
print(symbol*width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol*width)
for sym, w, h in (('*', 4, 4), ('o', 20, 5), ('x', 1, 3), ('zz', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('Возникло исключение' + str(err))
|
[
"andrewnnov@yandex.ru"
] |
andrewnnov@yandex.ru
|
e2a3e21bc440b7674cd5fa8ed950cbe961441ebb
|
4f409ce499d941139e8db3afadc9a880947c01c0
|
/Experiments/DBpedia/VBMLTM/p_error.py
|
4652df0838ea5453cd95f1b3b78bcf809f1450eb
|
[] |
no_license
|
manirupa/MLTM
|
62177b9648f02fd529e558e8d41cedf864dc5211
|
355c469a814b50618a31bdbdd550ccdad8ed543b
|
refs/heads/master
| 2020-06-23T02:28:01.188003
| 2017-04-02T14:24:04
| 2017-04-02T14:24:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,177
|
py
|
import numpy as np
import os, re, sys
#from sklearn import metrics
#from sklearn.linear_model import LogisticRegression
#sys.path.insert(0, '/'.join(os.getcwd().split('/')[:-4]))
#import myAUC
#Code = '../../../../../Code/MLTMVB/MLTMVB'
#LDACode = '../../../../../Code/LDA_VB_Parallel/lda_vb'
Datapath = '../../../Data/DBpedia'
#trfile = '%s/train-data.dat' %Datapath
prop = '1'
if (prop != '1'):
trlblfile = '%s/train-label%s.dat' %(Datapath,prop)
else:
trlblfile = '%s/train-label.dat' %Datapath
#tfile = '%s/test-data.dat' %Datapath
#tlblfile = '%s/test-label.dat' %Datapath
#vfile = '%s/valid-data.dat' %Datapath
#vlblfile = '%s/valid-label.dat' %Datapath
#vocabfile = '%s/vocabs.txt' %Datapath
#tslblfile = '%s/test-sentlabel.dat' %Datapath
#ofile = '%s/obsvd-data.dat' %Datapath
#hfile = '%s/lda_hldout-data.dat' %Datapath
for prop in ['0.01', '0.05', '0.1', '0.3', '0.6', '0.8', '0.9', '1']:
for random_iter in range(1,6):
print (prop, random_iter)
dirpath = '%s/%s/dir' %(prop, str(random_iter))
trlbl = np.loadtxt(trlblfile)
(Dtr, C) = trlbl.shape
# compute probability of labeling error
prob_lbling_error = 0.0
cnt = 0.0
slbl_pred = open('%s/001.y' %dirpath).readlines()
prob_lbling_error = np.zeros(C)
prob1 = np.zeros(C)
prob0 = np.zeros(C)
for d, doc in enumerate(slbl_pred):
sents_pred = doc.split('|')[:-1]
pys = np.zeros((len(sents_pred), C))
for s, sent in enumerate(sents_pred):
pys[s, :] = np.array([float(x) for x in sent.split()])
A = np.max(pys, 0)
B = 1.0 - np.prod(1-pys, 0)
prob1 += (A * (1.0 - B))
prob0 += ((1.0 - A) * B)
prob_lbling_error += ((1.0 - A) * B) + (A * (1.0 - B))
'''# class 0
ind = trlbl[d,:]==0
prob_lbling_error[ind] += ((1.0 - A) * B)[ind]
cnt_per_class[ind] += 1
# class -1
ind = trlbl[d,:]==-1
prob_lbling_error[ind] += ((1.0 - A) * B)[ind] + (A * (1.0 - B))[ind]
cnt_per_class[ind] += 1'''
cnt += 1.0
prob_lbling_error /= cnt
prob1 /= cnt
prob0 /= cnt
fp = open('%s/%s/prob_lbling_error.txt' %(prop, str(random_iter)), 'w')
fp.write('%f %f %f' %(np.mean(prob_lbling_error), np.mean(prob1), np.mean(prob0)))
fp.close()
|
[
"hosein.soleimani@gmail.com"
] |
hosein.soleimani@gmail.com
|
ace86fe08576352c4ef4471b8c321b4110a7ab16
|
c4bb2d8ecc521287afeba251a176d7a8837b6bf7
|
/sentences/classify_parser/science_spot_parser.py
|
1c80da77a5f2b94a31b57f93ff4373ee111613a0
|
[] |
no_license
|
17680329677/Forestry_LAW
|
057080e175ffa4aab50a1751f75a3f63c757b926
|
4b9bd2c3e1b614f6f180950f169fc9eebe028a8e
|
refs/heads/master
| 2022-12-22T06:36:44.838644
| 2020-06-13T09:54:08
| 2020-06-13T09:54:08
| 204,466,380
| 16
| 3
| null | 2022-12-08T07:01:26
| 2019-08-26T12:01:41
|
Python
|
UTF-8
|
Python
| false
| false
| 3,071
|
py
|
# -*- coding : utf-8 -*-
# coding: utf-8
# 风景名胜管理条例相关法律法规的解析---并存入mysql数据库中做初步的格式化
import os
from data.property_collect import law_parse
from data_resource import conn
def science_spot_parser(file_path):
dir_path = "C:\\Users\\dhz1216\\Desktop\\washing\\风景名胜"
file_name = file_path.split("\\")[-1]
cursor = conn.cursor()
select_sql = "select id, name from law where text_name = %s"
cursor.execute(select_sql, (file_name.split('.')[0]))
law_id = cursor.fetchone()[0]
count = 0
with open(file_path, "r", encoding='gbk', errors='ignore') as f:
line = f.readline()
while line:
if line.startswith('【法规全文】'):
with open(dir_path + "\\" + file_name, "a") as w:
line = line.replace('【法规全文】', '')
# line = f.readline()
while line:
if len(line.lstrip().split(' ')) > 1:
key_title = line.lstrip().split(' ')[0]
value_content = line.lstrip().split(' ')[1]
line = f.readline()
while line:
if len(line.lstrip().split(' ')) <= 1:
value_content = value_content + line.lstrip().split(' ')[0]
line = f.readline()
else:
break
w.write(key_title + ':' + value_content + '\n')
insert_sql = "insert into law_content (law_id, p_key, p_content, law_class) " \
"value (%s, %s, %s, %s)"
try:
cursor.execute(insert_sql, (law_id, key_title, value_content, '风景名胜'))
conn.commit()
count = count + 1
print('\033[1;37;40m' + file_name + ': PARSE SUCCESS' + '\033[0m')
except Exception as e:
print(e)
conn.rollback()
print('\033[1;32;41m' + file_name + ': PARSE FAILED---------' + '\033[0m')
else:
line = f.readline()
else:
line = f.readline()
print('共插入:' + str(count) + '条')
def science_spot_filter(file_name):
invalid_words = ['修订', '修正', '修改']
if '风景名胜' not in file_name:
return False
for word in invalid_words:
if word in file_name:
return False
return True
if __name__ == '__main__':
dir_path = "C:\\Users\\dhz1216\\Desktop\\wenben"
for file in os.listdir(dir_path):
if science_spot_filter(file):
file_path = dir_path + "\\" + file
science_spot_parser(file_path)
|
[
"laobahepijiu@163.com"
] |
laobahepijiu@163.com
|
7412475f7a6305dc02e7b0f8dced96e2ee15c394
|
4000a83fdd095726d382eeb55552dff3db688cc1
|
/LoadAndDeliverPackages.py
|
ce80b6e05bf710d942dd699a2dec0701c18da5d2
|
[] |
no_license
|
JasonPBurke/Package_Delivery_System
|
3f02856c18d3a866239e810a05d8f3ce71500274
|
ba59cde436951aa82560cabd93daf4ce08d76c07
|
refs/heads/master
| 2020-05-06T15:34:45.649589
| 2019-04-25T21:18:03
| 2019-04-25T21:18:03
| 180,197,249
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 20,851
|
py
|
# Jason Burke
from QuadraticProbingHashTable import EmptyBucket
from interface import interface
from truck import Truck
from datetime import datetime, time, timedelta
# This greedy algorithm will find the closest vertex from our starting hub vertex(WGU)
# and add the package(s) to the first truck that are to be delivered there.
# We add the package(s) for that vertex, and continue this process
# until the truck has at most 16 packages on it to deliver. Then fill the next
# truck to at most 16 and so on until all packages have been loaded/delivered.
# This method takes graph and truck objects a starting vertex, the current_time,
# any packages that must be delivered first in a list, and an empty list to hold
# all packages when they are loaded to a truck. It loads packages onto a truck
# object and returns the miles that will need to be traveled to deliver the packages
# on time and with consideration to the special notes for the packages.
## Big O: This function has a O(n*p*pkg) time
def load_truck(hash_table, graph, truck, start_vertex, current_time, deliver_first, packages_loaded):
# This assumes that all packages to a specific destination are loaded on the same
# truck and at the same time. When this is not the case, the flag is changed to
# True further below.
visit_vertex_again = False
# Base case for recursion
if not start_vertex:
return 0
# THIS GETS ME A DICT OF ALL THE EDGES AND THEIR WEIGHTS FOR THE CURRENT VERTEX
# CAN USE THIS TO DETERMINE THE NEXT PACKAGE STOP. THEN ADD THE PACKAGES FOR THAT
# STOP TO THE TRUCK TILL IT HAS AT MOST 16 PACKAGES ON IT.
edge_dict = {}
for key, value in graph.edge_weights.items():
if start_vertex is key[0]:
edge_dict[key[1]] = value
## O(n*p*pkg) time
for vertex, edge_distance in sorted(edge_dict.items(), key=lambda kv: kv[1]):
# Check if deliver_first has any packages in it, if it does, check if the
# current vertex.address matches any packages in the deliver_first list.
# If the address doesnt match, continue to the next vertex and check again.
if deliver_first:
# first_pkg = deliver_first[0] #### this would be used if I want to take the earliest
# package delivery and deliver it first ##### should not have to do this...it balloons
# my milage by 20%-30%!!!!!
if vertex.address[0] not in [i.address for i in deliver_first]:#!= first_pkg.address: #
continue
else:
# the addresses match so remove the address-matched item from deliver_first for the next loop
for p in deliver_first:
if vertex.address[0] == p.address:
deliver_first.remove(p)
# print('\nDeliver_first after removing package:', deliver_first)
# Find all packages to be delivered to the current vertex address
same_address_packages = hash_table.search_by(lambda pkg: pkg.address == vertex.address[0] and pkg.delivery_status == 'At HUB')
# Here we are checking to see if the package needs to be on a specific truck, and checking
# if the current truck is that specified truck. We remove it from the list if it does not
# belong on the current truck.
deliver_with_pkgs = []
if same_address_packages:
for p in same_address_packages:
# if there are special notes and the note is for a sepecified truck and the current
# truck is NOT the truck the package must be on, remove that package from
# from same_address_packages and check the next one
if p.notes and p.notes[0] == 'specified_truck' and int(p.notes[1]) != truck.get_truck_id():
# print(f'Package {p.id_num} must be on truck {p.notes[1]} and not on {truck.get_truck_id()} (current truck).')
# Specified truck does not match current truck so dont add this package to truck
same_address_packages.remove(p)
# We will need to visit this vertex again
visit_vertex_again = True
# Create a list holding any packages that need to be on the same truck as the current package
# These will be added to the truck further below
if p.notes and p.notes[0] == 'deliver_with':
deliver_with_pkgs.append(hash_table.search_by_id(p.notes[1][0]))
deliver_with_pkgs.append(hash_table.search_by_id(p.notes[1][1]))
if p.notes and p.notes[0] == 'flight_delay' and current_time < p.notes[1]:
same_address_packages.remove(p)
# We will need to visit this vertex again
visit_vertex_again = True
if p.notes and p.notes[0] == 'wrong_address' and current_time < p.notes[1]:
same_address_packages.remove(p)
# Skip any vertex that has been visited already
if vertex.visited:
continue
# CHECK VALID PACKAGES FOR THE TRUCK HERE (ALL SPECIAL NOTES)
if not same_address_packages:
continue
# If the current number of pkgs on truck + the number of pkgs in same_address_packages
# totals no more than 16, then add the packages from same_address_packages to the truck.
if len(truck.package_list) + len(same_address_packages) + len(deliver_with_pkgs) <= 14:
print(f'\nDistance from {start_vertex} to {vertex} is:', edge_distance)
print(f'\nTrying to add package(s) {same_address_packages, deliver_with_pkgs} to truck {truck.truck_id} for current location: {vertex} \n')
# Add the packages to be delivered to the current address to the truck
## O(p) time
for p in same_address_packages:
# if p.id_num in packages_loaded: print(f'Rejecting Package {p.id_num} b/c in packages_loaded already(2).')
if p.id_num not in packages_loaded:
p.change_package_status('In route')
truck.add_package(p)
truck.add_miles(edge_distance / len(same_address_packages)) #len(same_address_packages))
print('Current miles:', truck.get_miles())
packages_loaded.append(p.id_num)
pkg_and_edge_distance = [len(same_address_packages), edge_distance]
truck.add_edge_info(pkg_and_edge_distance)
# Mark current vertex as visited
if not visit_vertex_again:
vertex.vertex_visited(True)
# If there is a package to this address that must be on the truck with other pkgs, add them
if deliver_with_pkgs:
## O(pkg) time
for pkg in deliver_with_pkgs:
if pkg.id_num not in packages_loaded:
# Get the vertex that the current pkg is to be delivered to
next_vertex = graph.get_vertex_by_address(pkg.address)
# Get the edge_distance between vertex and next_vertex
edge_distance = graph.get_edge_weight(vertex, next_vertex)
# Add the package to the truck
truck.add_package(pkg)
pkg_and_edge_distance = [1, edge_distance]
truck.add_edge_info(pkg_and_edge_distance)
# Change pkg status
pkg.change_package_status('In route')
# Add the milage to the truck
truck.add_miles(edge_distance)
# Add pkg to packages_loaded
packages_loaded.append(pkg.id_num)
# Remove the current pkg from the deliver_with_pkgs list
deliver_with_pkgs.remove(pkg)
# Mark current vertex as visited
if not visit_vertex_again:
vertex.vertex_visited(True)
# Set vetex to next_vertex to calculate info for the next pkg
vertex = next_vertex
print('\nPackages on truck:', truck.show_packages())
# Recursively find the next package and load it
# also add the edge distances together to get the total distance.
print('-----------------------------------------------------------------------------')
return edge_distance + load_truck(hash_table, graph, truck, vertex, current_time, deliver_first, packages_loaded)
return 0
# This method will call load_truck when a truck is available at the hub. It will also
# step through time to make the package deliveries as the trucks reach the package delivery
# locations. It will mark the packages as delivered and remove the package from the trucks
# package list. When the trucks package list is empty, the truck will return to the hub if
# its return_to_hub flag is set to True, and be reloaded for another delivery.
## O(n^3) time
def deliver_packages(todays_packages, hash_table, distance_graph, hub_vertex, deliver_first):
packages_loaded = []
# The first item in each nested list is the truck number, the second is if the
# truck must return to the hub for another set of packages.
order_of_trucks_delivering_today = [[1, True],[2, True],[2, False],[1, False]]
# current_time begins at 08:00AM
current_time = datetime(10,1,1,8,00,00)
truck_1 = None
truck_2 = None
# to calculate the time new packages can be loaded on the truck
time_back_to_the_hub = None
# total_miles is used to calculate/display the total distance the trucks drive
total_miles = 0
# used to automate pkg delivery...
fast = False
# Loop until all needed trucks have been loaded for the day
# The lambda function insures the pkg is not EmptyBucket and that it has not been dilivered.
# will exit the loop when all packages have been delivered.
## O(n) time
while(hash_table.search_by(lambda pkg: type(pkg) is not EmptyBucket and pkg.delivery_status != 'Delivered')):
# This block corrects the wrong address data when the clock time is >= 10:20AM
## O(n) time
for p in todays_packages:
if p.notes and p.notes[0] == 'wrong_address' and current_time.time() >= p.notes[1]:
p.change_address(p.notes[2], p.notes[3], p.notes[4])
# This corrected address vertex may have been visited. Set
# vertex_visited to False so we can visit it again.
v = distance_graph.get_vertex_by_address(p.address)
v.vertex_visited(False)
print('\ntodays packages left to deliver:', todays_packages)
# Trucks one and two will be arriving back at the hub at different times for
# their second loads, so I need to sepparate the loading of the trucks to be
# independant of eachother.
# if trucks still need to be loaded, then try to load them
if order_of_trucks_delivering_today:
if truck_1 is None or truck_1.at_hub == True:
# Create truck objects using the truck numbers/return info found in order_of_trucks_delivering_today
truck_info = order_of_trucks_delivering_today.pop(0)
truck_1 = Truck(truck_info[0])
# Determine if the truck must return to the hub after empty
truck_1.set_return_to_hub(truck_info[1])
truck_1.set_start_time(current_time)
if truck_2 is None or truck_2.at_hub == True:
truck_info = order_of_trucks_delivering_today.pop(0)
truck_2 = Truck(truck_info[0])
truck_2.set_return_to_hub(truck_info[1])
truck_2.set_start_time(current_time)
truck_list = [truck_1, truck_2]
# This block is where the trucks are actually loaded if they are qualified to be loaded
if time_back_to_the_hub is None or time_back_to_the_hub.time() < current_time.time():
# Load the trucks
## O(t) time
for t in truck_list:
# if no packages on truck and it is at the hub
if not t.package_list and t.at_hub:
miles = load_truck(hash_table, distance_graph, t, hub_vertex, current_time.time(), deliver_first, packages_loaded)
# if we are unsuccessful loading the truck (pkgs not ready to load due to delays/wrong address)
# then return the popped info to the list so we can try again.
total_miles += t.get_miles()
if not t.package_list:
order_of_trucks_delivering_today.append(truck_info)
break
# If the truck needs to return for another load, and is currently at the hub,
# this calculates the edge info between the last vertex and the hub.
if t.return_to_hub and t.at_hub:
last_vertex = distance_graph.get_vertex_by_address(t.package_list[-1].address)
# t.add_miles(distance_graph.get_edge_weight(last_vertex, hub_vertex))
total_miles += distance_graph.get_edge_weight(last_vertex, hub_vertex)
t.add_edge_info(['HUB', distance_graph.get_edge_weight(last_vertex, hub_vertex)])
t.set_at_hub(False)
# A truck was not loaded, so put the truck load info back in the list.
else:
order_of_trucks_delivering_today.append(truck_info)
# Move the clock forward one step and then assign packages as delivered with their
# correct delivery times for those that would have reached their delivery location
# prior to the current clock time. Then allow user to check package info or move
# the clock time forward again, and repeat until all packages on the two trucks are
# delivered.
while(True):
print('\n\n-----------------------------\nTo continue delivery, enter 1')
print('To look up or add packages, enter 2')
if not fast:
user_choice = input('\nEnter choice now: ')
else:
user_choice = '1'
if user_choice == 'f':
fast = True
user_choice = '1'
if user_choice == str(1):
# move clock ahead by desired time in seconds (5 minutes = 300 seconds)
current_time += timedelta(seconds = 300)
# In five minute clock jumps, the trucks will travel 1.5 miles
distance_traveled_in_5_mins = 1.5
# add 1.5 miles to total distance traveled each loop to both trucks...traveling 1.5 miles / 5 minutes
for t in truck_list:
if t.package_list:
t.add_miles_traveled(distance_traveled_in_5_mins)
print(f'\nCurrent time is: {current_time.time()}')
# Make the deliveries and mark the time of delivery. Change the package_status to 'delivered'
## O(n*t*t.package_list) time
for t in truck_list:
while(t.package_list):
if t.pkg_and_edge_distance[0][0] == 'HUB':
break
t.add_hub_to_next_stop_miles(t.pkg_and_edge_distance[0][1])
if t.hub_to_next_stop_miles < t.miles_traveled: # Traveled at least as far as the stop and can deliver
# remove all pkgs that go to this stop. use len(t.pkg_and_edge_distance[0][0])
## O(n) time
for p in range(t.pkg_and_edge_distance[0][0]):
package = t.package_list.pop(0)
# todays_packages.remove(package)
# Change pkg status to Delivered
package.change_package_status('Delivered')
# Calculate the actual delivery time of the package
miles = t.hub_to_next_stop_miles/18# use hub_next_stop and calculate the actual time it was delivered ############
hrs, decimal = divmod(miles, 1)
decimal = decimal * 60 # to get whole minutes to the left of the decimal
mins, secs = divmod(decimal, 1)
total_seconds = int(hrs) * 3600 + int(mins) * 60 + round(secs * 60)
delivery_time = t.start_time + timedelta(seconds = total_seconds)
package.set_delivery_time(delivery_time)
print(f'\n\nDelivered package {package.id_num} at {delivery_time.time()} from truck {t.truck_id}.')
print(f'Miles traveled so far for truck {t.truck_id}: {t.miles_traveled}')
print(package)
print(f'\n\nTruck {t.truck_id} Package List: {t.package_list}')
# We have reached this delivery location so remove it from the list
t.pkg_and_edge_distance.pop(0)
# Havent reached this stop, so check the other truck
else:
# remove the milage as we cant move on to the next stop yet..will need this compare again
t.hub_to_next_stop_miles -= t.pkg_and_edge_distance[0][1]
break
if not t.package_list and t.return_to_hub:
t.set_at_hub(True)
#### THE BELOW CODE TO CALCULATE A RETURN TRIP TO THE HUB COULD/SHOULD GO HERE!!!!!
elif user_choice == str(2):
# CALL INTERFACE HERE TO ALLOW USER TO LOOK UP PACKAGE INFO
interface(hash_table, current_time)
continue
else:
print(f'Entry {user_choice} was not recognized. Try again.')
# If either truck has delivered all packages, break to the outer loop and
# load the truck
if not truck_list[0].package_list or not truck_list[1].package_list:
## O(t) time
for t in truck_list:
# If the truck is still at the hub because it is waiting to load pkgs, it
# wont have a pkg_and_edge_distance populated, so pass and break
try:
if t.pkg_and_edge_distance[0][0] == 'HUB':
distance_to_hub = t.pkg_and_edge_distance[0][1]
# I need to calculate the time that the truck will arrive back at the
# hub so I know what time its next load starts delivering.
# convert distance_to_hub to total seconds to drive back to hub
secs = (distance_to_hub/18) * 3600
time_back_to_the_hub = current_time + timedelta(seconds = secs)
break
except:
pass
break
# search and populate todays_packages again to account for any packages that were added by user.
todays_packages = hash_table.search_by(lambda pkg: type(pkg) is not EmptyBucket and pkg.delivery_status == 'At HUB')
# Calculate total miles traveled
# total_miles += hub_return_distances
print(f'\n\n----------------------\nAll Packages Delivered: Total miles driven: {total_miles}\n----------------------')
# print(f'Total miles driven: {total_miles}')
while(True):
print('\n\nTo look up or add packages, enter 2')
print("To exit program, enter 'exit'")
user_choice = input('\nEnter choice now: ')
if user_choice == str(2):
# CALL INTERFACE HERE TO ALLOW USER TO LOOK UP PACKAGE INFO
interface(hash_table, current_time)
elif user_choice.lower() == 'exit':
break
else:
print(f'Entry {user_choice} not recognized. Try again.')
|
[
"jpburke77@gmail.com"
] |
jpburke77@gmail.com
|
fee5d4a3265c202f2fc23c7c9191ad8f717f107d
|
bf5a4d4d943d1a6f398bb4a0703f602fc825f846
|
/gym_SmartPrimer/examples/plotAgentAnalysis.py
|
8ed67cc7487b1c79afbd2c9ff8d70d50f7afd883
|
[
"MIT"
] |
permissive
|
StanfordAI4HI/SmartPrimer_Gym
|
b76ea0bc1bbd2aa94cb59c2351095461181babbe
|
12f379ed9553c75f0e2924d11d603a2e975a1871
|
refs/heads/main
| 2023-08-18T04:31:10.030153
| 2021-05-15T16:46:17
| 2021-05-15T16:46:17
| 354,095,079
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 322
|
py
|
import numpy as np
data = np.loadtxt('/Users/williamsteenbergen/PycharmProjects/SmartPrimerFall/gym_SmartPrimer/examples/actionResultsAcrossModels', delimiter=',')
dataSeed = np.loadtxt('/Users/williamsteenbergen/PycharmProjects/SmartPrimerFall/gym_SmartPrimer/examples/actionResultsAcrossModelswSeed', delimiter=',')
a=1
|
[
"wsteen@federato.ai"
] |
wsteen@federato.ai
|
3e188b609c688851ce26ca9a52386d9c724d1b03
|
f782a8e8ba31a09c03d160c5813b592590e4ab1e
|
/rugby_team_create/urls.py
|
a5fe9153c5f304c851eefb62daa0a8ece868d576
|
[] |
no_license
|
nicemiddle/rugby-team-create
|
fdba9b9542232f9c50da968671a13a26cc75c3b4
|
a97cecf7e82efc9dd698624878fcbea7502132c7
|
refs/heads/master
| 2022-05-31T21:59:25.701082
| 2020-05-05T04:25:47
| 2020-05-05T04:25:47
| 254,811,406
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 716
|
py
|
from django.urls import path
from . import views
app_name = 'rugby_team_create'
urlpatterns = [
path('top/', views.TopTemplate.as_view(), name='top'),
path('team_list/', views.TeamList.as_view(), name='team_list'),
path('team_detail/<int:pk>', views.TeamDetail.as_view(), name='team_detail'),
path('team_create/', views.TeamCreate.as_view(), name='team_create'),
path('player_list/', views.PlayerList.as_view(), name='player_list'),
path('player_create/', views.PlayerCreate.as_view(), name='player_create'),
path('team_delete_confirm/<int:pk>', views.TeamDelete.as_view(), name='team_delete_confirm'),
path('team_update/<int:pk>', views.TeamUpdate.as_view(), name='team_update')
]
|
[
"p20lite1108@gmail.com"
] |
p20lite1108@gmail.com
|
231cbae623fed0554cc23c8c6a61a1fc68693fe3
|
cd9031cd698d23b4117106e1fba1a26c74e543a9
|
/dattq/logger.py
|
0091cb9bee575406b6f909a8b1969e6f0fb0f221
|
[] |
no_license
|
dattran2346/rsna-2019
|
89150cdec26da3fcdb67125b50925efaa9a027da
|
d454e049a267fdade1a81a02a696a0cb3ad33b5b
|
refs/heads/master
| 2020-09-18T18:45:40.115631
| 2019-11-26T14:28:18
| 2019-11-26T14:28:18
| 224,168,197
| 10
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,714
|
py
|
import logging
from pathlib import Path
from terminaltables import AsciiTable
import time
import sys
import numpy as np
class TrainingLogger:
## TRAINING LOGER
def __init__(self, args):
## Setup training logger
# checkdir = Path(f'{args.checkdir}/{args.checkname}')
self.args = args
checkdir = Path(f'runs/{args.checkname}')
checkdir.mkdir(exist_ok=True, parents=True)
self.terminal = sys.stdout
if args.resume:
mode = 'a' # append to prev
else:
mode = 'w+' # open and write new
self.file = open(checkdir/"training.log", mode)
## Print training setting
if self.args.start_epoch == 0:
# only print log at the start of training
self.write_all('='*20 + 'TRAINING START' + '='*20)
self.write_all('\n\n')
table_data = [['Setting', 'Value']]
table_data.append(['Backbone', args.backbone])
table_data.append(['Image size', args.image_size])
table_data.append(['Fold', args.fold])
table_data.append(['Epochs', args.epochs])
table_data.append(['Warmup', args.warmup])
table_data.append(["Batch size", args.batch_size])
table_data.append(['Gradient accumulation', args.gds])
table_data.append(['Lr', args.lr])
table_data.append(['Optimizer', args.optim])
table_data.append(['Scheduler', args.sched])
table_data.append(['Mix window', args.mix_window])
table_data.append(['#slies', args.nslices])
table_data.append(['LSTM dropout', args.lstm_dropout])
table_data.append(['Conv LSTM', args.conv_lstm])
table_data.append(['Cut block', args.cut_block])
table_data.append(['Dropblock', args.drop_block])
table_data.append(['Auxilary', args.aux])
table = AsciiTable(table_data)
self.write_all(table.table)
self.write_all('\n\n')
# ['any', 'epidural', 'subdural', 'subarachnoid', 'intraparenchymal', 'intraventricular']
self.file.write(f'Epoch | LR | Train Loss - Any - Epidural - Subdural - Subara - Intraparen- Intraven | Valid Loss - Any - Epidural - Subdural - Subara - Intraparen- Intraven | Time \n')
self.file.write('---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n')
def write_all(self, log):
self.terminal.write(f'{log}\n')
self.file.write(f'{log}\n')
def on_epoch_start(self, epoch):
# record epoch start time
self.start_time = time.time()
self.terminal.write(f'EPOCH: {epoch}\n')
def on_epoch_end(self, epoch, lr, train_losses, val_losses):
## Write log to file
# train_time = (time.time() - self.start_time) / 60
train_time = np.random.uniform(0) * 10
train_loss = train_losses.mean()
val_loss = val_losses.mean()
self.file.write(f'{epoch:5d} |{lr:0.8f}| {train_loss:8.8f} - {train_losses[0]:8.8f} - {train_losses[1]:8.8f} - {train_losses[2]:8.8f} - {train_losses[3]:.8f} - {train_losses[4]:.8f} - {train_losses[5]:8.8f} | {val_loss:8.8f} - {val_losses[0]:8.8f} - {val_losses[1]:8.8f} - {val_losses[2]:8.8f} - {val_losses[3]:8.8f} - {val_losses[4]:8.8f} - {val_losses[5]:8.8f} | {train_time:3.1f}min\n')
## Write log to terminal
self.terminal.write(f'Traininng loss: {train_loss:.5f}\n')
self.terminal.write(f'Validation loss: {val_loss:.5f}\n')
def on_training_end(self, best_loss, best_epoch):
self.file.write('---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n')
self.write_all('\n\n')
msg = f'====== Finish training, best loss {best_loss:.5f}@e{best_epoch+1} ======'
self.file.write(msg)
self.terminal.write(msg)
if __name__ == "__main__":
### Test logger
from options import Options
import numpy as np
opt = Options()
args = opt.parse()
args.checkname = 'logger_test'
args.checkdir = 'test'
logger = TrainingLogger(args)
for e in range(10):
logger.on_epoch_start(e)
train_loss, lr = np.random.uniform(0), np.random.uniform(0)
val_loss = np.random.uniform(0)
logger.on_epoch_end(e, lr, train_loss, val_loss)
logger.on_training_end(0.1, 9)
|
[
"v.datnt41@vingroup.net"
] |
v.datnt41@vingroup.net
|
b1f7422ef4b4a059e84976566cc78d4d683fde87
|
c3d8e82100f02482f1a9ea1fa8e92e176982ecee
|
/printable.py
|
9766102c5013de00fe1dd9257c6942e68f14ccb2
|
[] |
no_license
|
sopoour/blockchain-python
|
ba83704c20a0c1b06486b4307c9eb65adfa1a1ba
|
2bc9e18a5ffbe2bbb617f8cd4b6029007843b29f
|
refs/heads/main
| 2023-06-01T06:55:55.942060
| 2021-07-05T19:01:40
| 2021-07-05T19:01:40
| 265,257,624
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 183
|
py
|
class Printable:
#Convert the transaction objects to a dict and in order to be printable as string convert that to string
def __repr__(self):
return str(self.__dict__)
|
[
"sophia,auer@googlemail.com"
] |
sophia,auer@googlemail.com
|
88cc5ef0a54f620a14398b2249217be062c7e877
|
6e5e455223109d808ce6397beddb71be25c3d8eb
|
/builder/__init__.py
|
962f058f1a1f7a280ea451d89ea1445847ce2d9e
|
[] |
no_license
|
tdesposito/Pi-Appliance
|
cfbba185ebe40660ddb2fa400286dc5340504b80
|
355dbbd5aedba3a70dcc6c3323da3735fd94bd93
|
refs/heads/main
| 2023-04-04T14:34:53.434970
| 2021-04-20T19:35:38
| 2021-04-20T19:35:38
| 357,302,269
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,968
|
py
|
# Builder - common functions
import functools
import json
from pathlib import Path
import subprocess
from urllib.parse import urlparse
CONFIG_FILE = Path(__file__).parent.parent / "appliance_config.json"
SECRETS_DIR = Path(__file__).parent.parent / 'secrets'
SECRETS_FILE = SECRETS_DIR / 'secrets.json'
SECRETS_NAMES = {
'aws_access_key_id': ('AWS Access Key ID', '[A-Z0-9]{20}'),
'aws_secret_access_key': ('AWS Secret Access Key', '\S{40}'),
'region': ('AWS Region', 'us-(east|west)-[1-9]'),
'git_user': ('Git User Name', '\S{5}'),
'git_pwd': ('Git Password', '\S{5}'),
'repo_host': ('Repository Host', '^\S+\.(com|org|net)'),
'repo_url': ('Repository URL (skip https://)', '^\S+'),
}
echo = functools.partial(print, end='', flush=True)
def do_menu(term, title, menu):
def draw_menu(term, title, menu):
prep_screen(term, title)
for key, item in menu.items():
print(f" {key}) {item[0]}")
print(" x) Exit\n")
echo(f"{term.bright_blue}Option?{term.white} ")
with term.fullscreen():
draw_menu(term, title, menu)
while True:
with term.cbreak(): key = term.inkey()
if key == 'x' or key == 'X':
return False
if key.upper() in menu.keys():
menu[key.upper()][1](term)
return True # Forces re-build of menu options
draw_menu(term, title, menu)
def load_config():
with open(CONFIG_FILE, 'r') as _:
return json.load(_)
def load_secrets():
try:
if SECRETS_FILE.exists():
with open(SECRETS_FILE, 'r') as _:
return json.load(_)
except:
pass
return {k:"" for k in SECRETS_NAMES.keys()}
def prep_screen(term, title=None):
echo(term.home + term.clear)
print(term.center(f"{term.green}PiAppliance -- Configure and Build{term.white}"))
if title:
print(f"\n{term.bright_yellow}{title}{term.white}\n")
def press_any_key(term, msg):
print(msg)
echo(f"\n{term.bright_blue}Press any key to return to the menu: {term.white}")
with term.cbreak(): term.inkey()
return
def runcmd(cmd, params=None):
c = cmd.split(' ')
if params:
c.append(params)
return subprocess.run(c, capture_output=True)
def save_config(config):
with open(CONFIG_FILE, 'w') as _:
json.dump(config, _, indent=2, sort_keys=True)
def save_secrets(secrets):
if not SECRETS_DIR.exists():
SECRETS_DIR.mkdir()
with open(SECRETS_FILE, 'w') as _:
json.dump(secrets, _, indent=2, sort_keys=True)
def try_command(cmd, error, params=None):
proc = runcmd(cmd, params)
if proc.returncode:
raise Exception(f"{error}: {proc.stderr}")
__all__ = [
"do_menu",
"echo",
"load_config",
"load_secrets",
"prep_screen",
"press_any_key",
"runcmd",
"save_config",
"save_secrets",
"SECRETS_NAMES",
"try_command",
]
|
[
"todd@toddesposito.com"
] |
todd@toddesposito.com
|
cedc61464047cd576e65a826c10359d22cbf1609
|
72774acfc4aebe83b40cab2b57046b3fd46cdadc
|
/main.py
|
aad820b048399dfc0592ff771ef11f0546dfb9b0
|
[] |
no_license
|
matosagencia/Functions-to-MySQL
|
b06cdcb7d75533d1ab3712084c5ca8ca32e75cd1
|
46ae32284c6eb3077ec5d633270263bec16e2a83
|
refs/heads/main
| 2023-04-22T00:16:12.892881
| 2021-04-27T08:02:06
| 2021-04-27T08:02:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,742
|
py
|
from mysql.connector import connect
#show_schemas = "SHOW SCHEMAS"
#params = None
# ################################## >>>>>> FUNÇÃO DE EXECUÇÃO <<<<<< #########################################
def execute(sql, params=None):
# Executa um comando no mysql e salva os valores. Serve para:
# insert, update, delete, create, alter, drop
with connect(host="localhost", user="root", password="root", database="bluecommerce") as conn:
with conn.cursor() as cursor:
cursor.execute(sql, params)
conn.commit()
# ################################## >>>>>> FUNÇÃO DE 'BUSCA' <<<<<< ##########################################
# Executa um comando no mysql e retorna o resultado
# Serve para: Select, SHOW
def query(sql, params=None):
with connect(host="localhost", user="root", password="root", database="bluecommerce") as conn:
with conn.cursor() as cursor:
cursor.execute(sql, params)
return cursor.fetchall()
# ################################## >>>>>> FUNÇÃO PARA CRIAR TABELAS <<<<<< ###################################
def create_table(nome_tabela, colunas):
execute(f"""CREATE TABLE {nome_tabela}
(id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, {colunas})""")
# ################################# >>>>>> FUNÇÃO PARA CHAVE ESTRANGEIRA <<<<<< ##################################
def foreing_key(tabela, fk, coluna, tabela_referencia, coluna_referencia):
execute(f"""ALTER TABLE {tabela}
ADD CONSTRAINT {fk} FOREIGN KEY {coluna} REFERENCES {tabela_referencia}({coluna_referencia})""")
# ################################# >>>>>> FUNÇÃO PARA APAGAR UM VALOR <<<<<< ######################################
def delete_value(nome_tabela, coluna, id):
execute(f"DELETE FROM {nome_tabela} WHERE {coluna} = {id}")
# ########################## >>>>>> FUNÇÃO PARA INSERIR UM VALOR IGNORANDO REPETIDOS <<<<<< #########################
def insert_value(nome_tabela, colunas, inserir_valor):
execute(f"INSERT IGNORE INTO {nome_tabela}({colunas}) VALUES ({inserir_valor})")
# ################################# >>>>>> FUNÇÃO PARA BUSCAR UM VALOR <<<<<< ######################################
def select_value(coluna, tabela, condicao, valor):
print(query(f"""SELECT {coluna} FROM {tabela} WHERE {condicao} = {valor}"""))
# ################################# >>>>>> FUNÇÃO PARA ALTERAR UM VALOR <<<<<< ######################################
def update_value(tabela, coluna, valor_alterar, condicao, valor_condicao):
execute(f"""UPDATE {tabela} SET {coluna} = {valor_alterar} WHERE {condicao} = {valor_condicao}""")
|
[
"noreply@github.com"
] |
matosagencia.noreply@github.com
|
471512ef653813c7a297681963b7ff21e648036a
|
bd10597dc133237e68d07d8d6f9a2a1914e551ad
|
/MCA/Machine Learning/swap.py
|
6bf8294e6020ae1bffac2e3d6670237ee697ea7c
|
[
"MIT"
] |
permissive
|
muhammadmuzzammil1998/CollegeStuff
|
a1bf16a3d9a5b8586c10dd4ea2c0078baaae64fa
|
618cec9ebfbfd29a2d1e5a182b90cfb36b38a906
|
refs/heads/master
| 2021-12-26T16:57:33.875599
| 2021-12-21T21:43:15
| 2021-12-21T21:43:15
| 125,047,706
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 99
|
py
|
a, b = 5, 6
print("a = {}, b = {}".format(a, b))
a, b = b, a
print("a = {}, b = {}".format(a, b))
|
[
"muhammadmuzzammil.cs@gmail.com"
] |
muhammadmuzzammil.cs@gmail.com
|
11002ce9a66d6dd01dd3255c64061bf99832f835
|
35fc3136ca3f4af52ebeb36cedcd30b41d685146
|
/RNASeq/pipelines_reg/RNASeq_MDD6.py
|
063bd01f225742f1770e18d723c47a560ede2e36
|
[] |
no_license
|
stockedge/tpot-fss
|
cf260d9fd90fdd4b3d50da168f8b780bb2430fd1
|
d1ee616b7552ef254eb3832743c49a32e1203d6a
|
refs/heads/master
| 2022-09-19T13:10:30.479297
| 2020-06-02T15:43:16
| 2020-06-02T15:43:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 981
|
py
|
import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
# NOTE: Make sure that the class is labeled 'target' in the data file
tpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)
features = tpot_data.drop('target', axis=1).values
training_features, testing_features, training_target, testing_target = \
train_test_split(features, tpot_data['target'].values, random_state=6)
# Average CV score on the training set was:0.6838260869565217
exported_pipeline = make_pipeline(
MinMaxScaler(),
ExtraTreesClassifier(bootstrap=True, criterion="gini", max_features=0.9500000000000001, min_samples_leaf=5, min_samples_split=2, n_estimators=100)
)
exported_pipeline.fit(training_features, training_target)
results = exported_pipeline.predict(testing_features)
|
[
"grixor@gmail.com"
] |
grixor@gmail.com
|
f55e9b9731ecf77dcf752f1daaf3c8e570512a0a
|
ee4a142eb9f7e7f86ef2f74821ed07ff2bed23cc
|
/snort_csv.py
|
e8f55dfe4ddc16d38038f426e675dc04d193c1b8
|
[
"Apache-2.0"
] |
permissive
|
kairotavares/snortrules-csv
|
046ce7e9947344462a3d342a5fd2e3238d2ad6ec
|
b985c8e89ef41a6ae9d2d559e8f0458f9e021705
|
refs/heads/master
| 2022-09-03T17:51:09.266372
| 2020-05-29T21:43:31
| 2020-05-29T21:43:31
| 260,497,254
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,080
|
py
|
import snortparser.snortparser
import csv
import sys
from os import listdir
from os.path import isfile, join
all_options = []
ignore_options = ['msg', 'metadata', 'classtype', 'sid', 'rev', 'reference', 'tag']
ignore_list = ['snort3-deleted.rules']
def is_rule(rule_line):
return len(rule_line) > 100
def read_rules(path, filter_commented_rules=True):
rules = []
with open(path, 'rb') as f:
rules = f.read()
parsed_rules = [snortparser.snortparser.Parser(active_rule.decode("utf-8").replace("#", ""))
for active_rule in rules.splitlines()
if is_rule(active_rule)]
return parsed_rules
def get_keys(row):
return row.keys()
def parse_port(value):
if "$" in value or ":" in value:
return value
return int(value)
def to_row_value(row):
values = []
for _, value in row.header.items():
if type(value) == tuple:
has_data, data = value
if type(data) == list:
data_list = [parse_port(data_tuple) for has_data_tuple, data_tuple in data if has_data_tuple]
values.append(data_list)
else:
values.append(data) if has_data else values.append('')
else:
values.append(value)
_, msg = row.options[0]
values.append(msg[0])
options = []
options_signature = []
for _, data in row.options.items():
t, d = data
if t not in ignore_options:
options.append(t)
options_signature.append(data)
all_options.extend(options)
values.append(str(options))
values.append(str(options_signature))
return values
def write_to_file(output_file, header, rows):
with open(output_file, "w") as outfile:
csvwriter = csv.writer(outfile)
csvwriter.writerow(header)
for row in rows:
csvwriter.writerow(to_row_value(row))
def process_single_file(rules_file, output_file):
rules = read_rules(rules_file)
header = list(get_keys(rules[0].header))
header.extend(['msg', 'options', 'options_signature'])
write_to_file(output_file, header, rules)
print("Done. Processed {}".format(len(rules)))
def process_multiple_files(rules_files, output_file):
rules = []
for file in rules_files:
print(file)
file_rules = read_rules(file)
rules.extend(file_rules)
print(len(rules))
header = list(get_keys(rules[0].header))
header.extend(['msg', 'options', 'options_signature'])
write_to_file(output_file, header, rules)
print("Done. Processed {}".format(len(rules)))
if __name__ == '__main__':
rules_path = sys.argv[1]
output_file = sys.argv[2]
if isfile(rules_path):
process_single_file(rules_path, output_file)
else:
files = [join(rules_path, f) for f in listdir(rules_path)
if isfile(join(rules_path, f)) and '.rules' in f and f not in ignore_list]
process_multiple_files(files, output_file)
#all = list(set(all_options))
#all.sort()
#print(len(all))
#[ print(a) for a in all]
|
[
"kairo.ces.tavares@hpe.com"
] |
kairo.ces.tavares@hpe.com
|
b0e54b36346883493651de7f791ebe6ef592ed6a
|
f5cef01c9786a265d69a2f180057b4ac59e96c0e
|
/ml/m23_FI4_cancer.py
|
89e50b8471b65134ac5f9c52a36c8ee4332ac15d
|
[] |
no_license
|
4dv3ntur3/bit_seoul
|
5cb018dd1932100a15ad431034ba80515c7108be
|
8e1ee8a0c648e92abc14b47b271876d43861a0ad
|
refs/heads/master
| 2023-02-03T14:03:40.191623
| 2020-12-20T14:54:51
| 2020-12-20T14:54:51
| 311,263,882
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,330
|
py
|
#2020-11-25
#feature importance:cancer
#기준은 xbgoost
# 0. 디폴트 xgboost
# 1. feature importance=0인 것 제거. 압축 아님 or #2. 하위 30% 제거
# 1. feature_importance=0인 것 제거
# 실행 3번
import numpy as np
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from xgboost import XGBClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
#1. 데이터
datasets = load_breast_cancer()
x = datasets.data
y = datasets.target #y값 보고 회귀인지 분류인지 판단. 단, 시계열의 경우 y값을 뭘로 할지는 내가 선택.
print(x.shape) #569, 30
print(y.shape) #569,
#무식한 방법
# x_1 = x[:, :4]
# x_2 = x[:, 5:13]
# x_3 = x[:, 14:20]
# x_4 = x[:, 21:29]
# x = np.concatenate([x_1, x_2, x_3, x_4], axis=1)
x_train, x_test, y_train, y_test = train_test_split(
x, y, train_size=0.8, random_state=66 #or cancer.data, cancer.target
)
#2. 모델 구성
#max_depth 바꿔 보기
model = XGBClassifier(max_depth=4)
#3. 훈련
model.fit(x_train, y_train)
#4. 평가 및 예측
acc = model.score(x_test, y_test)
print("acc: ", acc)
print(model.feature_importances_) #column은 30개고, 각 column마다 중요도가 나온다
#column값이 0인 것들은 필요 없는 column
#얘네까지 같이 돌리면 1. 속도저하 2. 자원량 낭비
#따라서 0이 아닌 column만 모아서 돌려도 결과는 동일하다
#단, 조건: accuracy_score를 신뢰할 수 있어야 함
#4-2. FI 적용
fi = model.feature_importances_
indices = np.argsort(fi)[::-1]
print("FI 내림차순 정렬: ", indices)
del_index = []
for i in indices:
if i < int(0.7*len(fi)):
del_index.append(i)
print("삭제할 columns: ", del_index)
x_train = x_train[:, del_index]
x_test = x_test[:, del_index]
model.fit(x_train, y_train)
acc = model.score(x_test, y_test)
print("acc: ", acc)
# feature importance
# import matplotlib.pyplot as plt
# import numpy as np
# def plot_feature_importances_cancer(model):
# n_features = datasets.data.shape[1]
# plt.barh(np.arange(n_features), model.feature_importances_,
# align='center')
# plt.yticks(np.arange(n_features), datasets.feature_names)
# plt.xlabel("feature importances")
# plt.ylabel("features")
# plt.ylim(-1, n_features)
# plot_feature_importances_cancer(model)
# plt.show() #[0.01759811 0.02607087 0.6192673 0.33706376]
'''
1. default
acc: 0.9736842105263158
[0. 0.03518598 0.00053468 0.02371635 0.00661651 0.02328466
0.00405836 0.09933352 0.00236719 0. 0.01060954 0.00473884
0.01074011 0.01426315 0.0022232 0.00573987 0.00049415 0.00060479
0.00522006 0.00680739 0.01785728 0.0190929 0.3432317 0.24493258
0.00278067 0. 0.01099805 0.09473949 0.00262496 0.00720399]
2. 하위 30% 제거
FI 내림차순 정렬: [22 23 7 27 1 3 5 21 20 13 26 12 10 29 19 4 15 18 11 6 24 28 8 14 17 2 16 9 25 0]
삭제할 columns: [7, 1, 3, 5, 20, 13, 12, 10, 19, 4, 15, 18, 11, 6, 8, 14, 17, 2, 16, 9, 0]
acc: 0.9824561403508771
'''
|
[
"allyep13.07@gmail.com"
] |
allyep13.07@gmail.com
|
ca8ec424843b1095331a340c03a555af12aca256
|
c901d523500aaedd9d87ce9b14c83db216890fc2
|
/itech/asgi.py
|
b1c515b11c90d847468b1485e615974840f3cacb
|
[] |
no_license
|
Imran122/personal_blog
|
9bcd76605ea69f138618bbdb429f8ce5c823810c
|
e240ed9bcc374cc51441b3f3b08fa09e0cb051d4
|
refs/heads/master
| 2023-01-05T09:20:04.958620
| 2020-11-07T17:31:27
| 2020-11-07T17:31:27
| 310,887,933
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 387
|
py
|
"""
ASGI config for itech project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'itech.settings')
application = get_asgi_application()
|
[
"imransardar122@gmail.com"
] |
imransardar122@gmail.com
|
de0387838dc323a425a63d71b630a0d224917274
|
070b693744e7e73634c19b1ee5bc9e06f9fb852a
|
/python/problem-dynamic-programming/jump_game.py
|
199c3094474b5251eda2a8fedf6bc3b8892e146a
|
[] |
no_license
|
rheehot/practice
|
a7a4ce177e8cb129192a60ba596745eec9a7d19e
|
aa0355d3879e61cf43a4333a6446f3d377ed5580
|
refs/heads/master
| 2021-04-15T22:04:34.484285
| 2020-03-20T17:20:00
| 2020-03-20T17:20:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 140,306
|
py
|
# https://leetcode.com/problems/jump-game
# https://leetcode.com/problems/jump-game/solution
class Solution:
# Time Limit Exceeded
def canJump0(self, nums):
if nums is None or 0 == len(nums):
return False
dp = [False] * len(nums)
dp[0] = True
for i, n in enumerate(nums):
if not dp[i]:
continue
for j in range(i, i + n + 1):
if j < len(nums):
dp[j] = True
return dp[-1]
# 19.42%
def canJump(self, nums):
if nums is None or 0 == len(nums):
return False
lenNums = len(nums)
dp = [False] * lenNums
dp[0] = True
for i, n in enumerate(nums):
if not dp[i]:
continue
for j in range(min(lenNums - 1, i + n), i, -1):
if dp[j]:
break
dp[j] = True
return dp[-1]
s = Solution()
data = [([2, 3, 1, 1, 4], True),
([3, 2, 1, 0, 4], False),
([2, 0], True),
([25000,24999,24998,24997,24996,24995,24994,24993,24992,24991,24990,24989,24988,24987,24986,24985,24984,24983,24982,24981,24980,24979,24978,24977,24976,24975,24974,24973,24972,24971,24970,24969,24968,24967,24966,24965,24964,24963,24962,24961,24960,24959,24958,24957,24956,24955,24954,24953,24952,24951,24950,24949,24948,24947,24946,24945,24944,24943,24942,24941,24940,24939,24938,24937,24936,24935,24934,24933,24932,24931,24930,24929,24928,24927,24926,24925,24924,24923,24922,24921,24920,24919,24918,24917,24916,24915,24914,24913,24912,24911,24910,24909,24908,24907,24906,24905,24904,24903,24902,24901,24900,24899,24898,24897,24896,24895,24894,24893,24892,24891,24890,24889,24888,24887,24886,24885,24884,24883,24882,24881,24880,24879,24878,24877,24876,24875,24874,24873,24872,24871,24870,24869,24868,24867,24866,24865,24864,24863,24862,24861,24860,24859,24858,24857,24856,24855,24854,24853,24852,24851,24850,24849,24848,24847,24846,24845,24844,24843,24842,24841,24840,24839,24838,24837,24836,24835,24834,24833,24832,24831,24830,24829,24828,24827,24826,24825,24824,24823,24822,24821,24820,24819,24818,24817,24816,24815,24814,24813,24812,24811,24810,24809,24808,24807,24806,24805,24804,24803,24802,24801,24800,24799,24798,24797,24796,24795,24794,24793,24792,24791,24790,24789,24788,24787,24786,24785,24784,24783,24782,24781,24780,24779,24778,24777,24776,24775,24774,24773,24772,24771,24770,24769,24768,24767,24766,24765,24764,24763,24762,24761,24760,24759,24758,24757,24756,24755,24754,24753,24752,24751,24750,24749,24748,24747,24746,24745,24744,24743,24742,24741,24740,24739,24738,24737,24736,24735,24734,24733,24732,24731,24730,24729,24728,24727,24726,24725,24724,24723,24722,24721,24720,24719,24718,24717,24716,24715,24714,24713,24712,24711,24710,24709,24708,24707,24706,24705,24704,24703,24702,24701,24700,24699,24698,24697,24696,24695,24694,24693,24692,24691,24690,24689,24688,24687,24686,24685,24684,24683,24682,24681,24680,24679,24678,24677,24676,24675,24674,24673,24672,24671,24670,24669,24668,24667,24666,24665,24664,24663,24662,24661,24660,24659,24658,24657,24656,24655,24654,24653,24652,24651,24650,24649,24648,24647,24646,24645,24644,24643,24642,24641,24640,24639,24638,24637,24636,24635,24634,24633,24632,24631,24630,24629,24628,24627,24626,24625,24624,24623,24622,24621,24620,24619,24618,24617,24616,24615,24614,24613,24612,24611,24610,24609,24608,24607,24606,24605,24604,24603,24602,24601,24600,24599,24598,24597,24596,24595,24594,24593,24592,24591,24590,24589,24588,24587,24586,24585,24584,24583,24582,24581,24580,24579,24578,24577,24576,24575,24574,24573,24572,24571,24570,24569,24568,24567,24566,24565,24564,24563,24562,24561,24560,24559,24558,24557,24556,24555,24554,24553,24552,24551,24550,24549,24548,24547,24546,24545,24544,24543,24542,24541,24540,24539,24538,24537,24536,24535,24534,24533,24532,24531,24530,24529,24528,24527,24526,24525,24524,24523,24522,24521,24520,24519,24518,24517,24516,24515,24514,24513,24512,24511,24510,24509,24508,24507,24506,24505,24504,24503,24502,24501,24500,24499,24498,24497,24496,24495,24494,24493,24492,24491,24490,24489,24488,24487,24486,24485,24484,24483,24482,24481,24480,24479,24478,24477,24476,24475,24474,24473,24472,24471,24470,24469,24468,24467,24466,24465,24464,24463,24462,24461,24460,24459,24458,24457,24456,24455,24454,24453,24452,24451,24450,24449,24448,24447,24446,24445,24444,24443,24442,24441,24440,24439,24438,24437,24436,24435,24434,24433,24432,24431,24430,24429,24428,24427,24426,24425,24424,24423,24422,24421,24420,24419,24418,24417,24416,24415,24414,24413,24412,24411,24410,24409,24408,24407,24406,24405,24404,24403,24402,24401,24400,24399,24398,24397,24396,24395,24394,24393,24392,24391,24390,24389,24388,24387,24386,24385,24384,24383,24382,24381,24380,24379,24378,24377,24376,24375,24374,24373,24372,24371,24370,24369,24368,24367,24366,24365,24364,24363,24362,24361,24360,24359,24358,24357,24356,24355,24354,24353,24352,24351,24350,24349,24348,24347,24346,24345,24344,24343,24342,24341,24340,24339,24338,24337,24336,24335,24334,24333,24332,24331,24330,24329,24328,24327,24326,24325,24324,24323,24322,24321,24320,24319,24318,24317,24316,24315,24314,24313,24312,24311,24310,24309,24308,24307,24306,24305,24304,24303,24302,24301,24300,24299,24298,24297,24296,24295,24294,24293,24292,24291,24290,24289,24288,24287,24286,24285,24284,24283,24282,24281,24280,24279,24278,24277,24276,24275,24274,24273,24272,24271,24270,24269,24268,24267,24266,24265,24264,24263,24262,24261,24260,24259,24258,24257,24256,24255,24254,24253,24252,24251,24250,24249,24248,24247,24246,24245,24244,24243,24242,24241,24240,24239,24238,24237,24236,24235,24234,24233,24232,24231,24230,24229,24228,24227,24226,24225,24224,24223,24222,24221,24220,24219,24218,24217,24216,24215,24214,24213,24212,24211,24210,24209,24208,24207,24206,24205,24204,24203,24202,24201,24200,24199,24198,24197,24196,24195,24194,24193,24192,24191,24190,24189,24188,24187,24186,24185,24184,24183,24182,24181,24180,24179,24178,24177,24176,24175,24174,24173,24172,24171,24170,24169,24168,24167,24166,24165,24164,24163,24162,24161,24160,24159,24158,24157,24156,24155,24154,24153,24152,24151,24150,24149,24148,24147,24146,24145,24144,24143,24142,24141,24140,24139,24138,24137,24136,24135,24134,24133,24132,24131,24130,24129,24128,24127,24126,24125,24124,24123,24122,24121,24120,24119,24118,24117,24116,24115,24114,24113,24112,24111,24110,24109,24108,24107,24106,24105,24104,24103,24102,24101,24100,24099,24098,24097,24096,24095,24094,24093,24092,24091,24090,24089,24088,24087,24086,24085,24084,24083,24082,24081,24080,24079,24078,24077,24076,24075,24074,24073,24072,24071,24070,24069,24068,24067,24066,24065,24064,24063,24062,24061,24060,24059,24058,24057,24056,24055,24054,24053,24052,24051,24050,24049,24048,24047,24046,24045,24044,24043,24042,24041,24040,24039,24038,24037,24036,24035,24034,24033,24032,24031,24030,24029,24028,24027,24026,24025,24024,24023,24022,24021,24020,24019,24018,24017,24016,24015,24014,24013,24012,24011,24010,24009,24008,24007,24006,24005,24004,24003,24002,24001,24000,23999,23998,23997,23996,23995,23994,23993,23992,23991,23990,23989,23988,23987,23986,23985,23984,23983,23982,23981,23980,23979,23978,23977,23976,23975,23974,23973,23972,23971,23970,23969,23968,23967,23966,23965,23964,23963,23962,23961,23960,23959,23958,23957,23956,23955,23954,23953,23952,23951,23950,23949,23948,23947,23946,23945,23944,23943,23942,23941,23940,23939,23938,23937,23936,23935,23934,23933,23932,23931,23930,23929,23928,23927,23926,23925,23924,23923,23922,23921,23920,23919,23918,23917,23916,23915,23914,23913,23912,23911,23910,23909,23908,23907,23906,23905,23904,23903,23902,23901,23900,23899,23898,23897,23896,23895,23894,23893,23892,23891,23890,23889,23888,23887,23886,23885,23884,23883,23882,23881,23880,23879,23878,23877,23876,23875,23874,23873,23872,23871,23870,23869,23868,23867,23866,23865,23864,23863,23862,23861,23860,23859,23858,23857,23856,23855,23854,23853,23852,23851,23850,23849,23848,23847,23846,23845,23844,23843,23842,23841,23840,23839,23838,23837,23836,23835,23834,23833,23832,23831,23830,23829,23828,23827,23826,23825,23824,23823,23822,23821,23820,23819,23818,23817,23816,23815,23814,23813,23812,23811,23810,23809,23808,23807,23806,23805,23804,23803,23802,23801,23800,23799,23798,23797,23796,23795,23794,23793,23792,23791,23790,23789,23788,23787,23786,23785,23784,23783,23782,23781,23780,23779,23778,23777,23776,23775,23774,23773,23772,23771,23770,23769,23768,23767,23766,23765,23764,23763,23762,23761,23760,23759,23758,23757,23756,23755,23754,23753,23752,23751,23750,23749,23748,23747,23746,23745,23744,23743,23742,23741,23740,23739,23738,23737,23736,23735,23734,23733,23732,23731,23730,23729,23728,23727,23726,23725,23724,23723,23722,23721,23720,23719,23718,23717,23716,23715,23714,23713,23712,23711,23710,23709,23708,23707,23706,23705,23704,23703,23702,23701,23700,23699,23698,23697,23696,23695,23694,23693,23692,23691,23690,23689,23688,23687,23686,23685,23684,23683,23682,23681,23680,23679,23678,23677,23676,23675,23674,23673,23672,23671,23670,23669,23668,23667,23666,23665,23664,23663,23662,23661,23660,23659,23658,23657,23656,23655,23654,23653,23652,23651,23650,23649,23648,23647,23646,23645,23644,23643,23642,23641,23640,23639,23638,23637,23636,23635,23634,23633,23632,23631,23630,23629,23628,23627,23626,23625,23624,23623,23622,23621,23620,23619,23618,23617,23616,23615,23614,23613,23612,23611,23610,23609,23608,23607,23606,23605,23604,23603,23602,23601,23600,23599,23598,23597,23596,23595,23594,23593,23592,23591,23590,23589,23588,23587,23586,23585,23584,23583,23582,23581,23580,23579,23578,23577,23576,23575,23574,23573,23572,23571,23570,23569,23568,23567,23566,23565,23564,23563,23562,23561,23560,23559,23558,23557,23556,23555,23554,23553,23552,23551,23550,23549,23548,23547,23546,23545,23544,23543,23542,23541,23540,23539,23538,23537,23536,23535,23534,23533,23532,23531,23530,23529,23528,23527,23526,23525,23524,23523,23522,23521,23520,23519,23518,23517,23516,23515,23514,23513,23512,23511,23510,23509,23508,23507,23506,23505,23504,23503,23502,23501,23500,23499,23498,23497,23496,23495,23494,23493,23492,23491,23490,23489,23488,23487,23486,23485,23484,23483,23482,23481,23480,23479,23478,23477,23476,23475,23474,23473,23472,23471,23470,23469,23468,23467,23466,23465,23464,23463,23462,23461,23460,23459,23458,23457,23456,23455,23454,23453,23452,23451,23450,23449,23448,23447,23446,23445,23444,23443,23442,23441,23440,23439,23438,23437,23436,23435,23434,23433,23432,23431,23430,23429,23428,23427,23426,23425,23424,23423,23422,23421,23420,23419,23418,23417,23416,23415,23414,23413,23412,23411,23410,23409,23408,23407,23406,23405,23404,23403,23402,23401,23400,23399,23398,23397,23396,23395,23394,23393,23392,23391,23390,23389,23388,23387,23386,23385,23384,23383,23382,23381,23380,23379,23378,23377,23376,23375,23374,23373,23372,23371,23370,23369,23368,23367,23366,23365,23364,23363,23362,23361,23360,23359,23358,23357,23356,23355,23354,23353,23352,23351,23350,23349,23348,23347,23346,23345,23344,23343,23342,23341,23340,23339,23338,23337,23336,23335,23334,23333,23332,23331,23330,23329,23328,23327,23326,23325,23324,23323,23322,23321,23320,23319,23318,23317,23316,23315,23314,23313,23312,23311,23310,23309,23308,23307,23306,23305,23304,23303,23302,23301,23300,23299,23298,23297,23296,23295,23294,23293,23292,23291,23290,23289,23288,23287,23286,23285,23284,23283,23282,23281,23280,23279,23278,23277,23276,23275,23274,23273,23272,23271,23270,23269,23268,23267,23266,23265,23264,23263,23262,23261,23260,23259,23258,23257,23256,23255,23254,23253,23252,23251,23250,23249,23248,23247,23246,23245,23244,23243,23242,23241,23240,23239,23238,23237,23236,23235,23234,23233,23232,23231,23230,23229,23228,23227,23226,23225,23224,23223,23222,23221,23220,23219,23218,23217,23216,23215,23214,23213,23212,23211,23210,23209,23208,23207,23206,23205,23204,23203,23202,23201,23200,23199,23198,23197,23196,23195,23194,23193,23192,23191,23190,23189,23188,23187,23186,23185,23184,23183,23182,23181,23180,23179,23178,23177,23176,23175,23174,23173,23172,23171,23170,23169,23168,23167,23166,23165,23164,23163,23162,23161,23160,23159,23158,23157,23156,23155,23154,23153,23152,23151,23150,23149,23148,23147,23146,23145,23144,23143,23142,23141,23140,23139,23138,23137,23136,23135,23134,23133,23132,23131,23130,23129,23128,23127,23126,23125,23124,23123,23122,23121,23120,23119,23118,23117,23116,23115,23114,23113,23112,23111,23110,23109,23108,23107,23106,23105,23104,23103,23102,23101,23100,23099,23098,23097,23096,23095,23094,23093,23092,23091,23090,23089,23088,23087,23086,23085,23084,23083,23082,23081,23080,23079,23078,23077,23076,23075,23074,23073,23072,23071,23070,23069,23068,23067,23066,23065,23064,23063,23062,23061,23060,23059,23058,23057,23056,23055,23054,23053,23052,23051,23050,23049,23048,23047,23046,23045,23044,23043,23042,23041,23040,23039,23038,23037,23036,23035,23034,23033,23032,23031,23030,23029,23028,23027,23026,23025,23024,23023,23022,23021,23020,23019,23018,23017,23016,23015,23014,23013,23012,23011,23010,23009,23008,23007,23006,23005,23004,23003,23002,23001,23000,22999,22998,22997,22996,22995,22994,22993,22992,22991,22990,22989,22988,22987,22986,22985,22984,22983,22982,22981,22980,22979,22978,22977,22976,22975,22974,22973,22972,22971,22970,22969,22968,22967,22966,22965,22964,22963,22962,22961,22960,22959,22958,22957,22956,22955,22954,22953,22952,22951,22950,22949,22948,22947,22946,22945,22944,22943,22942,22941,22940,22939,22938,22937,22936,22935,22934,22933,22932,22931,22930,22929,22928,22927,22926,22925,22924,22923,22922,22921,22920,22919,22918,22917,22916,22915,22914,22913,22912,22911,22910,22909,22908,22907,22906,22905,22904,22903,22902,22901,22900,22899,22898,22897,22896,22895,22894,22893,22892,22891,22890,22889,22888,22887,22886,22885,22884,22883,22882,22881,22880,22879,22878,22877,22876,22875,22874,22873,22872,22871,22870,22869,22868,22867,22866,22865,22864,22863,22862,22861,22860,22859,22858,22857,22856,22855,22854,22853,22852,22851,22850,22849,22848,22847,22846,22845,22844,22843,22842,22841,22840,22839,22838,22837,22836,22835,22834,22833,22832,22831,22830,22829,22828,22827,22826,22825,22824,22823,22822,22821,22820,22819,22818,22817,22816,22815,22814,22813,22812,22811,22810,22809,22808,22807,22806,22805,22804,22803,22802,22801,22800,22799,22798,22797,22796,22795,22794,22793,22792,22791,22790,22789,22788,22787,22786,22785,22784,22783,22782,22781,22780,22779,22778,22777,22776,22775,22774,22773,22772,22771,22770,22769,22768,22767,22766,22765,22764,22763,22762,22761,22760,22759,22758,22757,22756,22755,22754,22753,22752,22751,22750,22749,22748,22747,22746,22745,22744,22743,22742,22741,22740,22739,22738,22737,22736,22735,22734,22733,22732,22731,22730,22729,22728,22727,22726,22725,22724,22723,22722,22721,22720,22719,22718,22717,22716,22715,22714,22713,22712,22711,22710,22709,22708,22707,22706,22705,22704,22703,22702,22701,22700,22699,22698,22697,22696,22695,22694,22693,22692,22691,22690,22689,22688,22687,22686,22685,22684,22683,22682,22681,22680,22679,22678,22677,22676,22675,22674,22673,22672,22671,22670,22669,22668,22667,22666,22665,22664,22663,22662,22661,22660,22659,22658,22657,22656,22655,22654,22653,22652,22651,22650,22649,22648,22647,22646,22645,22644,22643,22642,22641,22640,22639,22638,22637,22636,22635,22634,22633,22632,22631,22630,22629,22628,22627,22626,22625,22624,22623,22622,22621,22620,22619,22618,22617,22616,22615,22614,22613,22612,22611,22610,22609,22608,22607,22606,22605,22604,22603,22602,22601,22600,22599,22598,22597,22596,22595,22594,22593,22592,22591,22590,22589,22588,22587,22586,22585,22584,22583,22582,22581,22580,22579,22578,22577,22576,22575,22574,22573,22572,22571,22570,22569,22568,22567,22566,22565,22564,22563,22562,22561,22560,22559,22558,22557,22556,22555,22554,22553,22552,22551,22550,22549,22548,22547,22546,22545,22544,22543,22542,22541,22540,22539,22538,22537,22536,22535,22534,22533,22532,22531,22530,22529,22528,22527,22526,22525,22524,22523,22522,22521,22520,22519,22518,22517,22516,22515,22514,22513,22512,22511,22510,22509,22508,22507,22506,22505,22504,22503,22502,22501,22500,22499,22498,22497,22496,22495,22494,22493,22492,22491,22490,22489,22488,22487,22486,22485,22484,22483,22482,22481,22480,22479,22478,22477,22476,22475,22474,22473,22472,22471,22470,22469,22468,22467,22466,22465,22464,22463,22462,22461,22460,22459,22458,22457,22456,22455,22454,22453,22452,22451,22450,22449,22448,22447,22446,22445,22444,22443,22442,22441,22440,22439,22438,22437,22436,22435,22434,22433,22432,22431,22430,22429,22428,22427,22426,22425,22424,22423,22422,22421,22420,22419,22418,22417,22416,22415,22414,22413,22412,22411,22410,22409,22408,22407,22406,22405,22404,22403,22402,22401,22400,22399,22398,22397,22396,22395,22394,22393,22392,22391,22390,22389,22388,22387,22386,22385,22384,22383,22382,22381,22380,22379,22378,22377,22376,22375,22374,22373,22372,22371,22370,22369,22368,22367,22366,22365,22364,22363,22362,22361,22360,22359,22358,22357,22356,22355,22354,22353,22352,22351,22350,22349,22348,22347,22346,22345,22344,22343,22342,22341,22340,22339,22338,22337,22336,22335,22334,22333,22332,22331,22330,22329,22328,22327,22326,22325,22324,22323,22322,22321,22320,22319,22318,22317,22316,22315,22314,22313,22312,22311,22310,22309,22308,22307,22306,22305,22304,22303,22302,22301,22300,22299,22298,22297,22296,22295,22294,22293,22292,22291,22290,22289,22288,22287,22286,22285,22284,22283,22282,22281,22280,22279,22278,22277,22276,22275,22274,22273,22272,22271,22270,22269,22268,22267,22266,22265,22264,22263,22262,22261,22260,22259,22258,22257,22256,22255,22254,22253,22252,22251,22250,22249,22248,22247,22246,22245,22244,22243,22242,22241,22240,22239,22238,22237,22236,22235,22234,22233,22232,22231,22230,22229,22228,22227,22226,22225,22224,22223,22222,22221,22220,22219,22218,22217,22216,22215,22214,22213,22212,22211,22210,22209,22208,22207,22206,22205,22204,22203,22202,22201,22200,22199,22198,22197,22196,22195,22194,22193,22192,22191,22190,22189,22188,22187,22186,22185,22184,22183,22182,22181,22180,22179,22178,22177,22176,22175,22174,22173,22172,22171,22170,22169,22168,22167,22166,22165,22164,22163,22162,22161,22160,22159,22158,22157,22156,22155,22154,22153,22152,22151,22150,22149,22148,22147,22146,22145,22144,22143,22142,22141,22140,22139,22138,22137,22136,22135,22134,22133,22132,22131,22130,22129,22128,22127,22126,22125,22124,22123,22122,22121,22120,22119,22118,22117,22116,22115,22114,22113,22112,22111,22110,22109,22108,22107,22106,22105,22104,22103,22102,22101,22100,22099,22098,22097,22096,22095,22094,22093,22092,22091,22090,22089,22088,22087,22086,22085,22084,22083,22082,22081,22080,22079,22078,22077,22076,22075,22074,22073,22072,22071,22070,22069,22068,22067,22066,22065,22064,22063,22062,22061,22060,22059,22058,22057,22056,22055,22054,22053,22052,22051,22050,22049,22048,22047,22046,22045,22044,22043,22042,22041,22040,22039,22038,22037,22036,22035,22034,22033,22032,22031,22030,22029,22028,22027,22026,22025,22024,22023,22022,22021,22020,22019,22018,22017,22016,22015,22014,22013,22012,22011,22010,22009,22008,22007,22006,22005,22004,22003,22002,22001,22000,21999,21998,21997,21996,21995,21994,21993,21992,21991,21990,21989,21988,21987,21986,21985,21984,21983,21982,21981,21980,21979,21978,21977,21976,21975,21974,21973,21972,21971,21970,21969,21968,21967,21966,21965,21964,21963,21962,21961,21960,21959,21958,21957,21956,21955,21954,21953,21952,21951,21950,21949,21948,21947,21946,21945,21944,21943,21942,21941,21940,21939,21938,21937,21936,21935,21934,21933,21932,21931,21930,21929,21928,21927,21926,21925,21924,21923,21922,21921,21920,21919,21918,21917,21916,21915,21914,21913,21912,21911,21910,21909,21908,21907,21906,21905,21904,21903,21902,21901,21900,21899,21898,21897,21896,21895,21894,21893,21892,21891,21890,21889,21888,21887,21886,21885,21884,21883,21882,21881,21880,21879,21878,21877,21876,21875,21874,21873,21872,21871,21870,21869,21868,21867,21866,21865,21864,21863,21862,21861,21860,21859,21858,21857,21856,21855,21854,21853,21852,21851,21850,21849,21848,21847,21846,21845,21844,21843,21842,21841,21840,21839,21838,21837,21836,21835,21834,21833,21832,21831,21830,21829,21828,21827,21826,21825,21824,21823,21822,21821,21820,21819,21818,21817,21816,21815,21814,21813,21812,21811,21810,21809,21808,21807,21806,21805,21804,21803,21802,21801,21800,21799,21798,21797,21796,21795,21794,21793,21792,21791,21790,21789,21788,21787,21786,21785,21784,21783,21782,21781,21780,21779,21778,21777,21776,21775,21774,21773,21772,21771,21770,21769,21768,21767,21766,21765,21764,21763,21762,21761,21760,21759,21758,21757,21756,21755,21754,21753,21752,21751,21750,21749,21748,21747,21746,21745,21744,21743,21742,21741,21740,21739,21738,21737,21736,21735,21734,21733,21732,21731,21730,21729,21728,21727,21726,21725,21724,21723,21722,21721,21720,21719,21718,21717,21716,21715,21714,21713,21712,21711,21710,21709,21708,21707,21706,21705,21704,21703,21702,21701,21700,21699,21698,21697,21696,21695,21694,21693,21692,21691,21690,21689,21688,21687,21686,21685,21684,21683,21682,21681,21680,21679,21678,21677,21676,21675,21674,21673,21672,21671,21670,21669,21668,21667,21666,21665,21664,21663,21662,21661,21660,21659,21658,21657,21656,21655,21654,21653,21652,21651,21650,21649,21648,21647,21646,21645,21644,21643,21642,21641,21640,21639,21638,21637,21636,21635,21634,21633,21632,21631,21630,21629,21628,21627,21626,21625,21624,21623,21622,21621,21620,21619,21618,21617,21616,21615,21614,21613,21612,21611,21610,21609,21608,21607,21606,21605,21604,21603,21602,21601,21600,21599,21598,21597,21596,21595,21594,21593,21592,21591,21590,21589,21588,21587,21586,21585,21584,21583,21582,21581,21580,21579,21578,21577,21576,21575,21574,21573,21572,21571,21570,21569,21568,21567,21566,21565,21564,21563,21562,21561,21560,21559,21558,21557,21556,21555,21554,21553,21552,21551,21550,21549,21548,21547,21546,21545,21544,21543,21542,21541,21540,21539,21538,21537,21536,21535,21534,21533,21532,21531,21530,21529,21528,21527,21526,21525,21524,21523,21522,21521,21520,21519,21518,21517,21516,21515,21514,21513,21512,21511,21510,21509,21508,21507,21506,21505,21504,21503,21502,21501,21500,21499,21498,21497,21496,21495,21494,21493,21492,21491,21490,21489,21488,21487,21486,21485,21484,21483,21482,21481,21480,21479,21478,21477,21476,21475,21474,21473,21472,21471,21470,21469,21468,21467,21466,21465,21464,21463,21462,21461,21460,21459,21458,21457,21456,21455,21454,21453,21452,21451,21450,21449,21448,21447,21446,21445,21444,21443,21442,21441,21440,21439,21438,21437,21436,21435,21434,21433,21432,21431,21430,21429,21428,21427,21426,21425,21424,21423,21422,21421,21420,21419,21418,21417,21416,21415,21414,21413,21412,21411,21410,21409,21408,21407,21406,21405,21404,21403,21402,21401,21400,21399,21398,21397,21396,21395,21394,21393,21392,21391,21390,21389,21388,21387,21386,21385,21384,21383,21382,21381,21380,21379,21378,21377,21376,21375,21374,21373,21372,21371,21370,21369,21368,21367,21366,21365,21364,21363,21362,21361,21360,21359,21358,21357,21356,21355,21354,21353,21352,21351,21350,21349,21348,21347,21346,21345,21344,21343,21342,21341,21340,21339,21338,21337,21336,21335,21334,21333,21332,21331,21330,21329,21328,21327,21326,21325,21324,21323,21322,21321,21320,21319,21318,21317,21316,21315,21314,21313,21312,21311,21310,21309,21308,21307,21306,21305,21304,21303,21302,21301,21300,21299,21298,21297,21296,21295,21294,21293,21292,21291,21290,21289,21288,21287,21286,21285,21284,21283,21282,21281,21280,21279,21278,21277,21276,21275,21274,21273,21272,21271,21270,21269,21268,21267,21266,21265,21264,21263,21262,21261,21260,21259,21258,21257,21256,21255,21254,21253,21252,21251,21250,21249,21248,21247,21246,21245,21244,21243,21242,21241,21240,21239,21238,21237,21236,21235,21234,21233,21232,21231,21230,21229,21228,21227,21226,21225,21224,21223,21222,21221,21220,21219,21218,21217,21216,21215,21214,21213,21212,21211,21210,21209,21208,21207,21206,21205,21204,21203,21202,21201,21200,21199,21198,21197,21196,21195,21194,21193,21192,21191,21190,21189,21188,21187,21186,21185,21184,21183,21182,21181,21180,21179,21178,21177,21176,21175,21174,21173,21172,21171,21170,21169,21168,21167,21166,21165,21164,21163,21162,21161,21160,21159,21158,21157,21156,21155,21154,21153,21152,21151,21150,21149,21148,21147,21146,21145,21144,21143,21142,21141,21140,21139,21138,21137,21136,21135,21134,21133,21132,21131,21130,21129,21128,21127,21126,21125,21124,21123,21122,21121,21120,21119,21118,21117,21116,21115,21114,21113,21112,21111,21110,21109,21108,21107,21106,21105,21104,21103,21102,21101,21100,21099,21098,21097,21096,21095,21094,21093,21092,21091,21090,21089,21088,21087,21086,21085,21084,21083,21082,21081,21080,21079,21078,21077,21076,21075,21074,21073,21072,21071,21070,21069,21068,21067,21066,21065,21064,21063,21062,21061,21060,21059,21058,21057,21056,21055,21054,21053,21052,21051,21050,21049,21048,21047,21046,21045,21044,21043,21042,21041,21040,21039,21038,21037,21036,21035,21034,21033,21032,21031,21030,21029,21028,21027,21026,21025,21024,21023,21022,21021,21020,21019,21018,21017,21016,21015,21014,21013,21012,21011,21010,21009,21008,21007,21006,21005,21004,21003,21002,21001,21000,20999,20998,20997,20996,20995,20994,20993,20992,20991,20990,20989,20988,20987,20986,20985,20984,20983,20982,20981,20980,20979,20978,20977,20976,20975,20974,20973,20972,20971,20970,20969,20968,20967,20966,20965,20964,20963,20962,20961,20960,20959,20958,20957,20956,20955,20954,20953,20952,20951,20950,20949,20948,20947,20946,20945,20944,20943,20942,20941,20940,20939,20938,20937,20936,20935,20934,20933,20932,20931,20930,20929,20928,20927,20926,20925,20924,20923,20922,20921,20920,20919,20918,20917,20916,20915,20914,20913,20912,20911,20910,20909,20908,20907,20906,20905,20904,20903,20902,20901,20900,20899,20898,20897,20896,20895,20894,20893,20892,20891,20890,20889,20888,20887,20886,20885,20884,20883,20882,20881,20880,20879,20878,20877,20876,20875,20874,20873,20872,20871,20870,20869,20868,20867,20866,20865,20864,20863,20862,20861,20860,20859,20858,20857,20856,20855,20854,20853,20852,20851,20850,20849,20848,20847,20846,20845,20844,20843,20842,20841,20840,20839,20838,20837,20836,20835,20834,20833,20832,20831,20830,20829,20828,20827,20826,20825,20824,20823,20822,20821,20820,20819,20818,20817,20816,20815,20814,20813,20812,20811,20810,20809,20808,20807,20806,20805,20804,20803,20802,20801,20800,20799,20798,20797,20796,20795,20794,20793,20792,20791,20790,20789,20788,20787,20786,20785,20784,20783,20782,20781,20780,20779,20778,20777,20776,20775,20774,20773,20772,20771,20770,20769,20768,20767,20766,20765,20764,20763,20762,20761,20760,20759,20758,20757,20756,20755,20754,20753,20752,20751,20750,20749,20748,20747,20746,20745,20744,20743,20742,20741,20740,20739,20738,20737,20736,20735,20734,20733,20732,20731,20730,20729,20728,20727,20726,20725,20724,20723,20722,20721,20720,20719,20718,20717,20716,20715,20714,20713,20712,20711,20710,20709,20708,20707,20706,20705,20704,20703,20702,20701,20700,20699,20698,20697,20696,20695,20694,20693,20692,20691,20690,20689,20688,20687,20686,20685,20684,20683,20682,20681,20680,20679,20678,20677,20676,20675,20674,20673,20672,20671,20670,20669,20668,20667,20666,20665,20664,20663,20662,20661,20660,20659,20658,20657,20656,20655,20654,20653,20652,20651,20650,20649,20648,20647,20646,20645,20644,20643,20642,20641,20640,20639,20638,20637,20636,20635,20634,20633,20632,20631,20630,20629,20628,20627,20626,20625,20624,20623,20622,20621,20620,20619,20618,20617,20616,20615,20614,20613,20612,20611,20610,20609,20608,20607,20606,20605,20604,20603,20602,20601,20600,20599,20598,20597,20596,20595,20594,20593,20592,20591,20590,20589,20588,20587,20586,20585,20584,20583,20582,20581,20580,20579,20578,20577,20576,20575,20574,20573,20572,20571,20570,20569,20568,20567,20566,20565,20564,20563,20562,20561,20560,20559,20558,20557,20556,20555,20554,20553,20552,20551,20550,20549,20548,20547,20546,20545,20544,20543,20542,20541,20540,20539,20538,20537,20536,20535,20534,20533,20532,20531,20530,20529,20528,20527,20526,20525,20524,20523,20522,20521,20520,20519,20518,20517,20516,20515,20514,20513,20512,20511,20510,20509,20508,20507,20506,20505,20504,20503,20502,20501,20500,20499,20498,20497,20496,20495,20494,20493,20492,20491,20490,20489,20488,20487,20486,20485,20484,20483,20482,20481,20480,20479,20478,20477,20476,20475,20474,20473,20472,20471,20470,20469,20468,20467,20466,20465,20464,20463,20462,20461,20460,20459,20458,20457,20456,20455,20454,20453,20452,20451,20450,20449,20448,20447,20446,20445,20444,20443,20442,20441,20440,20439,20438,20437,20436,20435,20434,20433,20432,20431,20430,20429,20428,20427,20426,20425,20424,20423,20422,20421,20420,20419,20418,20417,20416,20415,20414,20413,20412,20411,20410,20409,20408,20407,20406,20405,20404,20403,20402,20401,20400,20399,20398,20397,20396,20395,20394,20393,20392,20391,20390,20389,20388,20387,20386,20385,20384,20383,20382,20381,20380,20379,20378,20377,20376,20375,20374,20373,20372,20371,20370,20369,20368,20367,20366,20365,20364,20363,20362,20361,20360,20359,20358,20357,20356,20355,20354,20353,20352,20351,20350,20349,20348,20347,20346,20345,20344,20343,20342,20341,20340,20339,20338,20337,20336,20335,20334,20333,20332,20331,20330,20329,20328,20327,20326,20325,20324,20323,20322,20321,20320,20319,20318,20317,20316,20315,20314,20313,20312,20311,20310,20309,20308,20307,20306,20305,20304,20303,20302,20301,20300,20299,20298,20297,20296,20295,20294,20293,20292,20291,20290,20289,20288,20287,20286,20285,20284,20283,20282,20281,20280,20279,20278,20277,20276,20275,20274,20273,20272,20271,20270,20269,20268,20267,20266,20265,20264,20263,20262,20261,20260,20259,20258,20257,20256,20255,20254,20253,20252,20251,20250,20249,20248,20247,20246,20245,20244,20243,20242,20241,20240,20239,20238,20237,20236,20235,20234,20233,20232,20231,20230,20229,20228,20227,20226,20225,20224,20223,20222,20221,20220,20219,20218,20217,20216,20215,20214,20213,20212,20211,20210,20209,20208,20207,20206,20205,20204,20203,20202,20201,20200,20199,20198,20197,20196,20195,20194,20193,20192,20191,20190,20189,20188,20187,20186,20185,20184,20183,20182,20181,20180,20179,20178,20177,20176,20175,20174,20173,20172,20171,20170,20169,20168,20167,20166,20165,20164,20163,20162,20161,20160,20159,20158,20157,20156,20155,20154,20153,20152,20151,20150,20149,20148,20147,20146,20145,20144,20143,20142,20141,20140,20139,20138,20137,20136,20135,20134,20133,20132,20131,20130,20129,20128,20127,20126,20125,20124,20123,20122,20121,20120,20119,20118,20117,20116,20115,20114,20113,20112,20111,20110,20109,20108,20107,20106,20105,20104,20103,20102,20101,20100,20099,20098,20097,20096,20095,20094,20093,20092,20091,20090,20089,20088,20087,20086,20085,20084,20083,20082,20081,20080,20079,20078,20077,20076,20075,20074,20073,20072,20071,20070,20069,20068,20067,20066,20065,20064,20063,20062,20061,20060,20059,20058,20057,20056,20055,20054,20053,20052,20051,20050,20049,20048,20047,20046,20045,20044,20043,20042,20041,20040,20039,20038,20037,20036,20035,20034,20033,20032,20031,20030,20029,20028,20027,20026,20025,20024,20023,20022,20021,20020,20019,20018,20017,20016,20015,20014,20013,20012,20011,20010,20009,20008,20007,20006,20005,20004,20003,20002,20001,20000,19999,19998,19997,19996,19995,19994,19993,19992,19991,19990,19989,19988,19987,19986,19985,19984,19983,19982,19981,19980,19979,19978,19977,19976,19975,19974,19973,19972,19971,19970,19969,19968,19967,19966,19965,19964,19963,19962,19961,19960,19959,19958,19957,19956,19955,19954,19953,19952,19951,19950,19949,19948,19947,19946,19945,19944,19943,19942,19941,19940,19939,19938,19937,19936,19935,19934,19933,19932,19931,19930,19929,19928,19927,19926,19925,19924,19923,19922,19921,19920,19919,19918,19917,19916,19915,19914,19913,19912,19911,19910,19909,19908,19907,19906,19905,19904,19903,19902,19901,19900,19899,19898,19897,19896,19895,19894,19893,19892,19891,19890,19889,19888,19887,19886,19885,19884,19883,19882,19881,19880,19879,19878,19877,19876,19875,19874,19873,19872,19871,19870,19869,19868,19867,19866,19865,19864,19863,19862,19861,19860,19859,19858,19857,19856,19855,19854,19853,19852,19851,19850,19849,19848,19847,19846,19845,19844,19843,19842,19841,19840,19839,19838,19837,19836,19835,19834,19833,19832,19831,19830,19829,19828,19827,19826,19825,19824,19823,19822,19821,19820,19819,19818,19817,19816,19815,19814,19813,19812,19811,19810,19809,19808,19807,19806,19805,19804,19803,19802,19801,19800,19799,19798,19797,19796,19795,19794,19793,19792,19791,19790,19789,19788,19787,19786,19785,19784,19783,19782,19781,19780,19779,19778,19777,19776,19775,19774,19773,19772,19771,19770,19769,19768,19767,19766,19765,19764,19763,19762,19761,19760,19759,19758,19757,19756,19755,19754,19753,19752,19751,19750,19749,19748,19747,19746,19745,19744,19743,19742,19741,19740,19739,19738,19737,19736,19735,19734,19733,19732,19731,19730,19729,19728,19727,19726,19725,19724,19723,19722,19721,19720,19719,19718,19717,19716,19715,19714,19713,19712,19711,19710,19709,19708,19707,19706,19705,19704,19703,19702,19701,19700,19699,19698,19697,19696,19695,19694,19693,19692,19691,19690,19689,19688,19687,19686,19685,19684,19683,19682,19681,19680,19679,19678,19677,19676,19675,19674,19673,19672,19671,19670,19669,19668,19667,19666,19665,19664,19663,19662,19661,19660,19659,19658,19657,19656,19655,19654,19653,19652,19651,19650,19649,19648,19647,19646,19645,19644,19643,19642,19641,19640,19639,19638,19637,19636,19635,19634,19633,19632,19631,19630,19629,19628,19627,19626,19625,19624,19623,19622,19621,19620,19619,19618,19617,19616,19615,19614,19613,19612,19611,19610,19609,19608,19607,19606,19605,19604,19603,19602,19601,19600,19599,19598,19597,19596,19595,19594,19593,19592,19591,19590,19589,19588,19587,19586,19585,19584,19583,19582,19581,19580,19579,19578,19577,19576,19575,19574,19573,19572,19571,19570,19569,19568,19567,19566,19565,19564,19563,19562,19561,19560,19559,19558,19557,19556,19555,19554,19553,19552,19551,19550,19549,19548,19547,19546,19545,19544,19543,19542,19541,19540,19539,19538,19537,19536,19535,19534,19533,19532,19531,19530,19529,19528,19527,19526,19525,19524,19523,19522,19521,19520,19519,19518,19517,19516,19515,19514,19513,19512,19511,19510,19509,19508,19507,19506,19505,19504,19503,19502,19501,19500,19499,19498,19497,19496,19495,19494,19493,19492,19491,19490,19489,19488,19487,19486,19485,19484,19483,19482,19481,19480,19479,19478,19477,19476,19475,19474,19473,19472,19471,19470,19469,19468,19467,19466,19465,19464,19463,19462,19461,19460,19459,19458,19457,19456,19455,19454,19453,19452,19451,19450,19449,19448,19447,19446,19445,19444,19443,19442,19441,19440,19439,19438,19437,19436,19435,19434,19433,19432,19431,19430,19429,19428,19427,19426,19425,19424,19423,19422,19421,19420,19419,19418,19417,19416,19415,19414,19413,19412,19411,19410,19409,19408,19407,19406,19405,19404,19403,19402,19401,19400,19399,19398,19397,19396,19395,19394,19393,19392,19391,19390,19389,19388,19387,19386,19385,19384,19383,19382,19381,19380,19379,19378,19377,19376,19375,19374,19373,19372,19371,19370,19369,19368,19367,19366,19365,19364,19363,19362,19361,19360,19359,19358,19357,19356,19355,19354,19353,19352,19351,19350,19349,19348,19347,19346,19345,19344,19343,19342,19341,19340,19339,19338,19337,19336,19335,19334,19333,19332,19331,19330,19329,19328,19327,19326,19325,19324,19323,19322,19321,19320,19319,19318,19317,19316,19315,19314,19313,19312,19311,19310,19309,19308,19307,19306,19305,19304,19303,19302,19301,19300,19299,19298,19297,19296,19295,19294,19293,19292,19291,19290,19289,19288,19287,19286,19285,19284,19283,19282,19281,19280,19279,19278,19277,19276,19275,19274,19273,19272,19271,19270,19269,19268,19267,19266,19265,19264,19263,19262,19261,19260,19259,19258,19257,19256,19255,19254,19253,19252,19251,19250,19249,19248,19247,19246,19245,19244,19243,19242,19241,19240,19239,19238,19237,19236,19235,19234,19233,19232,19231,19230,19229,19228,19227,19226,19225,19224,19223,19222,19221,19220,19219,19218,19217,19216,19215,19214,19213,19212,19211,19210,19209,19208,19207,19206,19205,19204,19203,19202,19201,19200,19199,19198,19197,19196,19195,19194,19193,19192,19191,19190,19189,19188,19187,19186,19185,19184,19183,19182,19181,19180,19179,19178,19177,19176,19175,19174,19173,19172,19171,19170,19169,19168,19167,19166,19165,19164,19163,19162,19161,19160,19159,19158,19157,19156,19155,19154,19153,19152,19151,19150,19149,19148,19147,19146,19145,19144,19143,19142,19141,19140,19139,19138,19137,19136,19135,19134,19133,19132,19131,19130,19129,19128,19127,19126,19125,19124,19123,19122,19121,19120,19119,19118,19117,19116,19115,19114,19113,19112,19111,19110,19109,19108,19107,19106,19105,19104,19103,19102,19101,19100,19099,19098,19097,19096,19095,19094,19093,19092,19091,19090,19089,19088,19087,19086,19085,19084,19083,19082,19081,19080,19079,19078,19077,19076,19075,19074,19073,19072,19071,19070,19069,19068,19067,19066,19065,19064,19063,19062,19061,19060,19059,19058,19057,19056,19055,19054,19053,19052,19051,19050,19049,19048,19047,19046,19045,19044,19043,19042,19041,19040,19039,19038,19037,19036,19035,19034,19033,19032,19031,19030,19029,19028,19027,19026,19025,19024,19023,19022,19021,19020,19019,19018,19017,19016,19015,19014,19013,19012,19011,19010,19009,19008,19007,19006,19005,19004,19003,19002,19001,19000,18999,18998,18997,18996,18995,18994,18993,18992,18991,18990,18989,18988,18987,18986,18985,18984,18983,18982,18981,18980,18979,18978,18977,18976,18975,18974,18973,18972,18971,18970,18969,18968,18967,18966,18965,18964,18963,18962,18961,18960,18959,18958,18957,18956,18955,18954,18953,18952,18951,18950,18949,18948,18947,18946,18945,18944,18943,18942,18941,18940,18939,18938,18937,18936,18935,18934,18933,18932,18931,18930,18929,18928,18927,18926,18925,18924,18923,18922,18921,18920,18919,18918,18917,18916,18915,18914,18913,18912,18911,18910,18909,18908,18907,18906,18905,18904,18903,18902,18901,18900,18899,18898,18897,18896,18895,18894,18893,18892,18891,18890,18889,18888,18887,18886,18885,18884,18883,18882,18881,18880,18879,18878,18877,18876,18875,18874,18873,18872,18871,18870,18869,18868,18867,18866,18865,18864,18863,18862,18861,18860,18859,18858,18857,18856,18855,18854,18853,18852,18851,18850,18849,18848,18847,18846,18845,18844,18843,18842,18841,18840,18839,18838,18837,18836,18835,18834,18833,18832,18831,18830,18829,18828,18827,18826,18825,18824,18823,18822,18821,18820,18819,18818,18817,18816,18815,18814,18813,18812,18811,18810,18809,18808,18807,18806,18805,18804,18803,18802,18801,18800,18799,18798,18797,18796,18795,18794,18793,18792,18791,18790,18789,18788,18787,18786,18785,18784,18783,18782,18781,18780,18779,18778,18777,18776,18775,18774,18773,18772,18771,18770,18769,18768,18767,18766,18765,18764,18763,18762,18761,18760,18759,18758,18757,18756,18755,18754,18753,18752,18751,18750,18749,18748,18747,18746,18745,18744,18743,18742,18741,18740,18739,18738,18737,18736,18735,18734,18733,18732,18731,18730,18729,18728,18727,18726,18725,18724,18723,18722,18721,18720,18719,18718,18717,18716,18715,18714,18713,18712,18711,18710,18709,18708,18707,18706,18705,18704,18703,18702,18701,18700,18699,18698,18697,18696,18695,18694,18693,18692,18691,18690,18689,18688,18687,18686,18685,18684,18683,18682,18681,18680,18679,18678,18677,18676,18675,18674,18673,18672,18671,18670,18669,18668,18667,18666,18665,18664,18663,18662,18661,18660,18659,18658,18657,18656,18655,18654,18653,18652,18651,18650,18649,18648,18647,18646,18645,18644,18643,18642,18641,18640,18639,18638,18637,18636,18635,18634,18633,18632,18631,18630,18629,18628,18627,18626,18625,18624,18623,18622,18621,18620,18619,18618,18617,18616,18615,18614,18613,18612,18611,18610,18609,18608,18607,18606,18605,18604,18603,18602,18601,18600,18599,18598,18597,18596,18595,18594,18593,18592,18591,18590,18589,18588,18587,18586,18585,18584,18583,18582,18581,18580,18579,18578,18577,18576,18575,18574,18573,18572,18571,18570,18569,18568,18567,18566,18565,18564,18563,18562,18561,18560,18559,18558,18557,18556,18555,18554,18553,18552,18551,18550,18549,18548,18547,18546,18545,18544,18543,18542,18541,18540,18539,18538,18537,18536,18535,18534,18533,18532,18531,18530,18529,18528,18527,18526,18525,18524,18523,18522,18521,18520,18519,18518,18517,18516,18515,18514,18513,18512,18511,18510,18509,18508,18507,18506,18505,18504,18503,18502,18501,18500,18499,18498,18497,18496,18495,18494,18493,18492,18491,18490,18489,18488,18487,18486,18485,18484,18483,18482,18481,18480,18479,18478,18477,18476,18475,18474,18473,18472,18471,18470,18469,18468,18467,18466,18465,18464,18463,18462,18461,18460,18459,18458,18457,18456,18455,18454,18453,18452,18451,18450,18449,18448,18447,18446,18445,18444,18443,18442,18441,18440,18439,18438,18437,18436,18435,18434,18433,18432,18431,18430,18429,18428,18427,18426,18425,18424,18423,18422,18421,18420,18419,18418,18417,18416,18415,18414,18413,18412,18411,18410,18409,18408,18407,18406,18405,18404,18403,18402,18401,18400,18399,18398,18397,18396,18395,18394,18393,18392,18391,18390,18389,18388,18387,18386,18385,18384,18383,18382,18381,18380,18379,18378,18377,18376,18375,18374,18373,18372,18371,18370,18369,18368,18367,18366,18365,18364,18363,18362,18361,18360,18359,18358,18357,18356,18355,18354,18353,18352,18351,18350,18349,18348,18347,18346,18345,18344,18343,18342,18341,18340,18339,18338,18337,18336,18335,18334,18333,18332,18331,18330,18329,18328,18327,18326,18325,18324,18323,18322,18321,18320,18319,18318,18317,18316,18315,18314,18313,18312,18311,18310,18309,18308,18307,18306,18305,18304,18303,18302,18301,18300,18299,18298,18297,18296,18295,18294,18293,18292,18291,18290,18289,18288,18287,18286,18285,18284,18283,18282,18281,18280,18279,18278,18277,18276,18275,18274,18273,18272,18271,18270,18269,18268,18267,18266,18265,18264,18263,18262,18261,18260,18259,18258,18257,18256,18255,18254,18253,18252,18251,18250,18249,18248,18247,18246,18245,18244,18243,18242,18241,18240,18239,18238,18237,18236,18235,18234,18233,18232,18231,18230,18229,18228,18227,18226,18225,18224,18223,18222,18221,18220,18219,18218,18217,18216,18215,18214,18213,18212,18211,18210,18209,18208,18207,18206,18205,18204,18203,18202,18201,18200,18199,18198,18197,18196,18195,18194,18193,18192,18191,18190,18189,18188,18187,18186,18185,18184,18183,18182,18181,18180,18179,18178,18177,18176,18175,18174,18173,18172,18171,18170,18169,18168,18167,18166,18165,18164,18163,18162,18161,18160,18159,18158,18157,18156,18155,18154,18153,18152,18151,18150,18149,18148,18147,18146,18145,18144,18143,18142,18141,18140,18139,18138,18137,18136,18135,18134,18133,18132,18131,18130,18129,18128,18127,18126,18125,18124,18123,18122,18121,18120,18119,18118,18117,18116,18115,18114,18113,18112,18111,18110,18109,18108,18107,18106,18105,18104,18103,18102,18101,18100,18099,18098,18097,18096,18095,18094,18093,18092,18091,18090,18089,18088,18087,18086,18085,18084,18083,18082,18081,18080,18079,18078,18077,18076,18075,18074,18073,18072,18071,18070,18069,18068,18067,18066,18065,18064,18063,18062,18061,18060,18059,18058,18057,18056,18055,18054,18053,18052,18051,18050,18049,18048,18047,18046,18045,18044,18043,18042,18041,18040,18039,18038,18037,18036,18035,18034,18033,18032,18031,18030,18029,18028,18027,18026,18025,18024,18023,18022,18021,18020,18019,18018,18017,18016,18015,18014,18013,18012,18011,18010,18009,18008,18007,18006,18005,18004,18003,18002,18001,18000,17999,17998,17997,17996,17995,17994,17993,17992,17991,17990,17989,17988,17987,17986,17985,17984,17983,17982,17981,17980,17979,17978,17977,17976,17975,17974,17973,17972,17971,17970,17969,17968,17967,17966,17965,17964,17963,17962,17961,17960,17959,17958,17957,17956,17955,17954,17953,17952,17951,17950,17949,17948,17947,17946,17945,17944,17943,17942,17941,17940,17939,17938,17937,17936,17935,17934,17933,17932,17931,17930,17929,17928,17927,17926,17925,17924,17923,17922,17921,17920,17919,17918,17917,17916,17915,17914,17913,17912,17911,17910,17909,17908,17907,17906,17905,17904,17903,17902,17901,17900,17899,17898,17897,17896,17895,17894,17893,17892,17891,17890,17889,17888,17887,17886,17885,17884,17883,17882,17881,17880,17879,17878,17877,17876,17875,17874,17873,17872,17871,17870,17869,17868,17867,17866,17865,17864,17863,17862,17861,17860,17859,17858,17857,17856,17855,17854,17853,17852,17851,17850,17849,17848,17847,17846,17845,17844,17843,17842,17841,17840,17839,17838,17837,17836,17835,17834,17833,17832,17831,17830,17829,17828,17827,17826,17825,17824,17823,17822,17821,17820,17819,17818,17817,17816,17815,17814,17813,17812,17811,17810,17809,17808,17807,17806,17805,17804,17803,17802,17801,17800,17799,17798,17797,17796,17795,17794,17793,17792,17791,17790,17789,17788,17787,17786,17785,17784,17783,17782,17781,17780,17779,17778,17777,17776,17775,17774,17773,17772,17771,17770,17769,17768,17767,17766,17765,17764,17763,17762,17761,17760,17759,17758,17757,17756,17755,17754,17753,17752,17751,17750,17749,17748,17747,17746,17745,17744,17743,17742,17741,17740,17739,17738,17737,17736,17735,17734,17733,17732,17731,17730,17729,17728,17727,17726,17725,17724,17723,17722,17721,17720,17719,17718,17717,17716,17715,17714,17713,17712,17711,17710,17709,17708,17707,17706,17705,17704,17703,17702,17701,17700,17699,17698,17697,17696,17695,17694,17693,17692,17691,17690,17689,17688,17687,17686,17685,17684,17683,17682,17681,17680,17679,17678,17677,17676,17675,17674,17673,17672,17671,17670,17669,17668,17667,17666,17665,17664,17663,17662,17661,17660,17659,17658,17657,17656,17655,17654,17653,17652,17651,17650,17649,17648,17647,17646,17645,17644,17643,17642,17641,17640,17639,17638,17637,17636,17635,17634,17633,17632,17631,17630,17629,17628,17627,17626,17625,17624,17623,17622,17621,17620,17619,17618,17617,17616,17615,17614,17613,17612,17611,17610,17609,17608,17607,17606,17605,17604,17603,17602,17601,17600,17599,17598,17597,17596,17595,17594,17593,17592,17591,17590,17589,17588,17587,17586,17585,17584,17583,17582,17581,17580,17579,17578,17577,17576,17575,17574,17573,17572,17571,17570,17569,17568,17567,17566,17565,17564,17563,17562,17561,17560,17559,17558,17557,17556,17555,17554,17553,17552,17551,17550,17549,17548,17547,17546,17545,17544,17543,17542,17541,17540,17539,17538,17537,17536,17535,17534,17533,17532,17531,17530,17529,17528,17527,17526,17525,17524,17523,17522,17521,17520,17519,17518,17517,17516,17515,17514,17513,17512,17511,17510,17509,17508,17507,17506,17505,17504,17503,17502,17501,17500,17499,17498,17497,17496,17495,17494,17493,17492,17491,17490,17489,17488,17487,17486,17485,17484,17483,17482,17481,17480,17479,17478,17477,17476,17475,17474,17473,17472,17471,17470,17469,17468,17467,17466,17465,17464,17463,17462,17461,17460,17459,17458,17457,17456,17455,17454,17453,17452,17451,17450,17449,17448,17447,17446,17445,17444,17443,17442,17441,17440,17439,17438,17437,17436,17435,17434,17433,17432,17431,17430,17429,17428,17427,17426,17425,17424,17423,17422,17421,17420,17419,17418,17417,17416,17415,17414,17413,17412,17411,17410,17409,17408,17407,17406,17405,17404,17403,17402,17401,17400,17399,17398,17397,17396,17395,17394,17393,17392,17391,17390,17389,17388,17387,17386,17385,17384,17383,17382,17381,17380,17379,17378,17377,17376,17375,17374,17373,17372,17371,17370,17369,17368,17367,17366,17365,17364,17363,17362,17361,17360,17359,17358,17357,17356,17355,17354,17353,17352,17351,17350,17349,17348,17347,17346,17345,17344,17343,17342,17341,17340,17339,17338,17337,17336,17335,17334,17333,17332,17331,17330,17329,17328,17327,17326,17325,17324,17323,17322,17321,17320,17319,17318,17317,17316,17315,17314,17313,17312,17311,17310,17309,17308,17307,17306,17305,17304,17303,17302,17301,17300,17299,17298,17297,17296,17295,17294,17293,17292,17291,17290,17289,17288,17287,17286,17285,17284,17283,17282,17281,17280,17279,17278,17277,17276,17275,17274,17273,17272,17271,17270,17269,17268,17267,17266,17265,17264,17263,17262,17261,17260,17259,17258,17257,17256,17255,17254,17253,17252,17251,17250,17249,17248,17247,17246,17245,17244,17243,17242,17241,17240,17239,17238,17237,17236,17235,17234,17233,17232,17231,17230,17229,17228,17227,17226,17225,17224,17223,17222,17221,17220,17219,17218,17217,17216,17215,17214,17213,17212,17211,17210,17209,17208,17207,17206,17205,17204,17203,17202,17201,17200,17199,17198,17197,17196,17195,17194,17193,17192,17191,17190,17189,17188,17187,17186,17185,17184,17183,17182,17181,17180,17179,17178,17177,17176,17175,17174,17173,17172,17171,17170,17169,17168,17167,17166,17165,17164,17163,17162,17161,17160,17159,17158,17157,17156,17155,17154,17153,17152,17151,17150,17149,17148,17147,17146,17145,17144,17143,17142,17141,17140,17139,17138,17137,17136,17135,17134,17133,17132,17131,17130,17129,17128,17127,17126,17125,17124,17123,17122,17121,17120,17119,17118,17117,17116,17115,17114,17113,17112,17111,17110,17109,17108,17107,17106,17105,17104,17103,17102,17101,17100,17099,17098,17097,17096,17095,17094,17093,17092,17091,17090,17089,17088,17087,17086,17085,17084,17083,17082,17081,17080,17079,17078,17077,17076,17075,17074,17073,17072,17071,17070,17069,17068,17067,17066,17065,17064,17063,17062,17061,17060,17059,17058,17057,17056,17055,17054,17053,17052,17051,17050,17049,17048,17047,17046,17045,17044,17043,17042,17041,17040,17039,17038,17037,17036,17035,17034,17033,17032,17031,17030,17029,17028,17027,17026,17025,17024,17023,17022,17021,17020,17019,17018,17017,17016,17015,17014,17013,17012,17011,17010,17009,17008,17007,17006,17005,17004,17003,17002,17001,17000,16999,16998,16997,16996,16995,16994,16993,16992,16991,16990,16989,16988,16987,16986,16985,16984,16983,16982,16981,16980,16979,16978,16977,16976,16975,16974,16973,16972,16971,16970,16969,16968,16967,16966,16965,16964,16963,16962,16961,16960,16959,16958,16957,16956,16955,16954,16953,16952,16951,16950,16949,16948,16947,16946,16945,16944,16943,16942,16941,16940,16939,16938,16937,16936,16935,16934,16933,16932,16931,16930,16929,16928,16927,16926,16925,16924,16923,16922,16921,16920,16919,16918,16917,16916,16915,16914,16913,16912,16911,16910,16909,16908,16907,16906,16905,16904,16903,16902,16901,16900,16899,16898,16897,16896,16895,16894,16893,16892,16891,16890,16889,16888,16887,16886,16885,16884,16883,16882,16881,16880,16879,16878,16877,16876,16875,16874,16873,16872,16871,16870,16869,16868,16867,16866,16865,16864,16863,16862,16861,16860,16859,16858,16857,16856,16855,16854,16853,16852,16851,16850,16849,16848,16847,16846,16845,16844,16843,16842,16841,16840,16839,16838,16837,16836,16835,16834,16833,16832,16831,16830,16829,16828,16827,16826,16825,16824,16823,16822,16821,16820,16819,16818,16817,16816,16815,16814,16813,16812,16811,16810,16809,16808,16807,16806,16805,16804,16803,16802,16801,16800,16799,16798,16797,16796,16795,16794,16793,16792,16791,16790,16789,16788,16787,16786,16785,16784,16783,16782,16781,16780,16779,16778,16777,16776,16775,16774,16773,16772,16771,16770,16769,16768,16767,16766,16765,16764,16763,16762,16761,16760,16759,16758,16757,16756,16755,16754,16753,16752,16751,16750,16749,16748,16747,16746,16745,16744,16743,16742,16741,16740,16739,16738,16737,16736,16735,16734,16733,16732,16731,16730,16729,16728,16727,16726,16725,16724,16723,16722,16721,16720,16719,16718,16717,16716,16715,16714,16713,16712,16711,16710,16709,16708,16707,16706,16705,16704,16703,16702,16701,16700,16699,16698,16697,16696,16695,16694,16693,16692,16691,16690,16689,16688,16687,16686,16685,16684,16683,16682,16681,16680,16679,16678,16677,16676,16675,16674,16673,16672,16671,16670,16669,16668,16667,16666,16665,16664,16663,16662,16661,16660,16659,16658,16657,16656,16655,16654,16653,16652,16651,16650,16649,16648,16647,16646,16645,16644,16643,16642,16641,16640,16639,16638,16637,16636,16635,16634,16633,16632,16631,16630,16629,16628,16627,16626,16625,16624,16623,16622,16621,16620,16619,16618,16617,16616,16615,16614,16613,16612,16611,16610,16609,16608,16607,16606,16605,16604,16603,16602,16601,16600,16599,16598,16597,16596,16595,16594,16593,16592,16591,16590,16589,16588,16587,16586,16585,16584,16583,16582,16581,16580,16579,16578,16577,16576,16575,16574,16573,16572,16571,16570,16569,16568,16567,16566,16565,16564,16563,16562,16561,16560,16559,16558,16557,16556,16555,16554,16553,16552,16551,16550,16549,16548,16547,16546,16545,16544,16543,16542,16541,16540,16539,16538,16537,16536,16535,16534,16533,16532,16531,16530,16529,16528,16527,16526,16525,16524,16523,16522,16521,16520,16519,16518,16517,16516,16515,16514,16513,16512,16511,16510,16509,16508,16507,16506,16505,16504,16503,16502,16501,16500,16499,16498,16497,16496,16495,16494,16493,16492,16491,16490,16489,16488,16487,16486,16485,16484,16483,16482,16481,16480,16479,16478,16477,16476,16475,16474,16473,16472,16471,16470,16469,16468,16467,16466,16465,16464,16463,16462,16461,16460,16459,16458,16457,16456,16455,16454,16453,16452,16451,16450,16449,16448,16447,16446,16445,16444,16443,16442,16441,16440,16439,16438,16437,16436,16435,16434,16433,16432,16431,16430,16429,16428,16427,16426,16425,16424,16423,16422,16421,16420,16419,16418,16417,16416,16415,16414,16413,16412,16411,16410,16409,16408,16407,16406,16405,16404,16403,16402,16401,16400,16399,16398,16397,16396,16395,16394,16393,16392,16391,16390,16389,16388,16387,16386,16385,16384,16383,16382,16381,16380,16379,16378,16377,16376,16375,16374,16373,16372,16371,16370,16369,16368,16367,16366,16365,16364,16363,16362,16361,16360,16359,16358,16357,16356,16355,16354,16353,16352,16351,16350,16349,16348,16347,16346,16345,16344,16343,16342,16341,16340,16339,16338,16337,16336,16335,16334,16333,16332,16331,16330,16329,16328,16327,16326,16325,16324,16323,16322,16321,16320,16319,16318,16317,16316,16315,16314,16313,16312,16311,16310,16309,16308,16307,16306,16305,16304,16303,16302,16301,16300,16299,16298,16297,16296,16295,16294,16293,16292,16291,16290,16289,16288,16287,16286,16285,16284,16283,16282,16281,16280,16279,16278,16277,16276,16275,16274,16273,16272,16271,16270,16269,16268,16267,16266,16265,16264,16263,16262,16261,16260,16259,16258,16257,16256,16255,16254,16253,16252,16251,16250,16249,16248,16247,16246,16245,16244,16243,16242,16241,16240,16239,16238,16237,16236,16235,16234,16233,16232,16231,16230,16229,16228,16227,16226,16225,16224,16223,16222,16221,16220,16219,16218,16217,16216,16215,16214,16213,16212,16211,16210,16209,16208,16207,16206,16205,16204,16203,16202,16201,16200,16199,16198,16197,16196,16195,16194,16193,16192,16191,16190,16189,16188,16187,16186,16185,16184,16183,16182,16181,16180,16179,16178,16177,16176,16175,16174,16173,16172,16171,16170,16169,16168,16167,16166,16165,16164,16163,16162,16161,16160,16159,16158,16157,16156,16155,16154,16153,16152,16151,16150,16149,16148,16147,16146,16145,16144,16143,16142,16141,16140,16139,16138,16137,16136,16135,16134,16133,16132,16131,16130,16129,16128,16127,16126,16125,16124,16123,16122,16121,16120,16119,16118,16117,16116,16115,16114,16113,16112,16111,16110,16109,16108,16107,16106,16105,16104,16103,16102,16101,16100,16099,16098,16097,16096,16095,16094,16093,16092,16091,16090,16089,16088,16087,16086,16085,16084,16083,16082,16081,16080,16079,16078,16077,16076,16075,16074,16073,16072,16071,16070,16069,16068,16067,16066,16065,16064,16063,16062,16061,16060,16059,16058,16057,16056,16055,16054,16053,16052,16051,16050,16049,16048,16047,16046,16045,16044,16043,16042,16041,16040,16039,16038,16037,16036,16035,16034,16033,16032,16031,16030,16029,16028,16027,16026,16025,16024,16023,16022,16021,16020,16019,16018,16017,16016,16015,16014,16013,16012,16011,16010,16009,16008,16007,16006,16005,16004,16003,16002,16001,16000,15999,15998,15997,15996,15995,15994,15993,15992,15991,15990,15989,15988,15987,15986,15985,15984,15983,15982,15981,15980,15979,15978,15977,15976,15975,15974,15973,15972,15971,15970,15969,15968,15967,15966,15965,15964,15963,15962,15961,15960,15959,15958,15957,15956,15955,15954,15953,15952,15951,15950,15949,15948,15947,15946,15945,15944,15943,15942,15941,15940,15939,15938,15937,15936,15935,15934,15933,15932,15931,15930,15929,15928,15927,15926,15925,15924,15923,15922,15921,15920,15919,15918,15917,15916,15915,15914,15913,15912,15911,15910,15909,15908,15907,15906,15905,15904,15903,15902,15901,15900,15899,15898,15897,15896,15895,15894,15893,15892,15891,15890,15889,15888,15887,15886,15885,15884,15883,15882,15881,15880,15879,15878,15877,15876,15875,15874,15873,15872,15871,15870,15869,15868,15867,15866,15865,15864,15863,15862,15861,15860,15859,15858,15857,15856,15855,15854,15853,15852,15851,15850,15849,15848,15847,15846,15845,15844,15843,15842,15841,15840,15839,15838,15837,15836,15835,15834,15833,15832,15831,15830,15829,15828,15827,15826,15825,15824,15823,15822,15821,15820,15819,15818,15817,15816,15815,15814,15813,15812,15811,15810,15809,15808,15807,15806,15805,15804,15803,15802,15801,15800,15799,15798,15797,15796,15795,15794,15793,15792,15791,15790,15789,15788,15787,15786,15785,15784,15783,15782,15781,15780,15779,15778,15777,15776,15775,15774,15773,15772,15771,15770,15769,15768,15767,15766,15765,15764,15763,15762,15761,15760,15759,15758,15757,15756,15755,15754,15753,15752,15751,15750,15749,15748,15747,15746,15745,15744,15743,15742,15741,15740,15739,15738,15737,15736,15735,15734,15733,15732,15731,15730,15729,15728,15727,15726,15725,15724,15723,15722,15721,15720,15719,15718,15717,15716,15715,15714,15713,15712,15711,15710,15709,15708,15707,15706,15705,15704,15703,15702,15701,15700,15699,15698,15697,15696,15695,15694,15693,15692,15691,15690,15689,15688,15687,15686,15685,15684,15683,15682,15681,15680,15679,15678,15677,15676,15675,15674,15673,15672,15671,15670,15669,15668,15667,15666,15665,15664,15663,15662,15661,15660,15659,15658,15657,15656,15655,15654,15653,15652,15651,15650,15649,15648,15647,15646,15645,15644,15643,15642,15641,15640,15639,15638,15637,15636,15635,15634,15633,15632,15631,15630,15629,15628,15627,15626,15625,15624,15623,15622,15621,15620,15619,15618,15617,15616,15615,15614,15613,15612,15611,15610,15609,15608,15607,15606,15605,15604,15603,15602,15601,15600,15599,15598,15597,15596,15595,15594,15593,15592,15591,15590,15589,15588,15587,15586,15585,15584,15583,15582,15581,15580,15579,15578,15577,15576,15575,15574,15573,15572,15571,15570,15569,15568,15567,15566,15565,15564,15563,15562,15561,15560,15559,15558,15557,15556,15555,15554,15553,15552,15551,15550,15549,15548,15547,15546,15545,15544,15543,15542,15541,15540,15539,15538,15537,15536,15535,15534,15533,15532,15531,15530,15529,15528,15527,15526,15525,15524,15523,15522,15521,15520,15519,15518,15517,15516,15515,15514,15513,15512,15511,15510,15509,15508,15507,15506,15505,15504,15503,15502,15501,15500,15499,15498,15497,15496,15495,15494,15493,15492,15491,15490,15489,15488,15487,15486,15485,15484,15483,15482,15481,15480,15479,15478,15477,15476,15475,15474,15473,15472,15471,15470,15469,15468,15467,15466,15465,15464,15463,15462,15461,15460,15459,15458,15457,15456,15455,15454,15453,15452,15451,15450,15449,15448,15447,15446,15445,15444,15443,15442,15441,15440,15439,15438,15437,15436,15435,15434,15433,15432,15431,15430,15429,15428,15427,15426,15425,15424,15423,15422,15421,15420,15419,15418,15417,15416,15415,15414,15413,15412,15411,15410,15409,15408,15407,15406,15405,15404,15403,15402,15401,15400,15399,15398,15397,15396,15395,15394,15393,15392,15391,15390,15389,15388,15387,15386,15385,15384,15383,15382,15381,15380,15379,15378,15377,15376,15375,15374,15373,15372,15371,15370,15369,15368,15367,15366,15365,15364,15363,15362,15361,15360,15359,15358,15357,15356,15355,15354,15353,15352,15351,15350,15349,15348,15347,15346,15345,15344,15343,15342,15341,15340,15339,15338,15337,15336,15335,15334,15333,15332,15331,15330,15329,15328,15327,15326,15325,15324,15323,15322,15321,15320,15319,15318,15317,15316,15315,15314,15313,15312,15311,15310,15309,15308,15307,15306,15305,15304,15303,15302,15301,15300,15299,15298,15297,15296,15295,15294,15293,15292,15291,15290,15289,15288,15287,15286,15285,15284,15283,15282,15281,15280,15279,15278,15277,15276,15275,15274,15273,15272,15271,15270,15269,15268,15267,15266,15265,15264,15263,15262,15261,15260,15259,15258,15257,15256,15255,15254,15253,15252,15251,15250,15249,15248,15247,15246,15245,15244,15243,15242,15241,15240,15239,15238,15237,15236,15235,15234,15233,15232,15231,15230,15229,15228,15227,15226,15225,15224,15223,15222,15221,15220,15219,15218,15217,15216,15215,15214,15213,15212,15211,15210,15209,15208,15207,15206,15205,15204,15203,15202,15201,15200,15199,15198,15197,15196,15195,15194,15193,15192,15191,15190,15189,15188,15187,15186,15185,15184,15183,15182,15181,15180,15179,15178,15177,15176,15175,15174,15173,15172,15171,15170,15169,15168,15167,15166,15165,15164,15163,15162,15161,15160,15159,15158,15157,15156,15155,15154,15153,15152,15151,15150,15149,15148,15147,15146,15145,15144,15143,15142,15141,15140,15139,15138,15137,15136,15135,15134,15133,15132,15131,15130,15129,15128,15127,15126,15125,15124,15123,15122,15121,15120,15119,15118,15117,15116,15115,15114,15113,15112,15111,15110,15109,15108,15107,15106,15105,15104,15103,15102,15101,15100,15099,15098,15097,15096,15095,15094,15093,15092,15091,15090,15089,15088,15087,15086,15085,15084,15083,15082,15081,15080,15079,15078,15077,15076,15075,15074,15073,15072,15071,15070,15069,15068,15067,15066,15065,15064,15063,15062,15061,15060,15059,15058,15057,15056,15055,15054,15053,15052,15051,15050,15049,15048,15047,15046,15045,15044,15043,15042,15041,15040,15039,15038,15037,15036,15035,15034,15033,15032,15031,15030,15029,15028,15027,15026,15025,15024,15023,15022,15021,15020,15019,15018,15017,15016,15015,15014,15013,15012,15011,15010,15009,15008,15007,15006,15005,15004,15003,15002,15001,15000,14999,14998,14997,14996,14995,14994,14993,14992,14991,14990,14989,14988,14987,14986,14985,14984,14983,14982,14981,14980,14979,14978,14977,14976,14975,14974,14973,14972,14971,14970,14969,14968,14967,14966,14965,14964,14963,14962,14961,14960,14959,14958,14957,14956,14955,14954,14953,14952,14951,14950,14949,14948,14947,14946,14945,14944,14943,14942,14941,14940,14939,14938,14937,14936,14935,14934,14933,14932,14931,14930,14929,14928,14927,14926,14925,14924,14923,14922,14921,14920,14919,14918,14917,14916,14915,14914,14913,14912,14911,14910,14909,14908,14907,14906,14905,14904,14903,14902,14901,14900,14899,14898,14897,14896,14895,14894,14893,14892,14891,14890,14889,14888,14887,14886,14885,14884,14883,14882,14881,14880,14879,14878,14877,14876,14875,14874,14873,14872,14871,14870,14869,14868,14867,14866,14865,14864,14863,14862,14861,14860,14859,14858,14857,14856,14855,14854,14853,14852,14851,14850,14849,14848,14847,14846,14845,14844,14843,14842,14841,14840,14839,14838,14837,14836,14835,14834,14833,14832,14831,14830,14829,14828,14827,14826,14825,14824,14823,14822,14821,14820,14819,14818,14817,14816,14815,14814,14813,14812,14811,14810,14809,14808,14807,14806,14805,14804,14803,14802,14801,14800,14799,14798,14797,14796,14795,14794,14793,14792,14791,14790,14789,14788,14787,14786,14785,14784,14783,14782,14781,14780,14779,14778,14777,14776,14775,14774,14773,14772,14771,14770,14769,14768,14767,14766,14765,14764,14763,14762,14761,14760,14759,14758,14757,14756,14755,14754,14753,14752,14751,14750,14749,14748,14747,14746,14745,14744,14743,14742,14741,14740,14739,14738,14737,14736,14735,14734,14733,14732,14731,14730,14729,14728,14727,14726,14725,14724,14723,14722,14721,14720,14719,14718,14717,14716,14715,14714,14713,14712,14711,14710,14709,14708,14707,14706,14705,14704,14703,14702,14701,14700,14699,14698,14697,14696,14695,14694,14693,14692,14691,14690,14689,14688,14687,14686,14685,14684,14683,14682,14681,14680,14679,14678,14677,14676,14675,14674,14673,14672,14671,14670,14669,14668,14667,14666,14665,14664,14663,14662,14661,14660,14659,14658,14657,14656,14655,14654,14653,14652,14651,14650,14649,14648,14647,14646,14645,14644,14643,14642,14641,14640,14639,14638,14637,14636,14635,14634,14633,14632,14631,14630,14629,14628,14627,14626,14625,14624,14623,14622,14621,14620,14619,14618,14617,14616,14615,14614,14613,14612,14611,14610,14609,14608,14607,14606,14605,14604,14603,14602,14601,14600,14599,14598,14597,14596,14595,14594,14593,14592,14591,14590,14589,14588,14587,14586,14585,14584,14583,14582,14581,14580,14579,14578,14577,14576,14575,14574,14573,14572,14571,14570,14569,14568,14567,14566,14565,14564,14563,14562,14561,14560,14559,14558,14557,14556,14555,14554,14553,14552,14551,14550,14549,14548,14547,14546,14545,14544,14543,14542,14541,14540,14539,14538,14537,14536,14535,14534,14533,14532,14531,14530,14529,14528,14527,14526,14525,14524,14523,14522,14521,14520,14519,14518,14517,14516,14515,14514,14513,14512,14511,14510,14509,14508,14507,14506,14505,14504,14503,14502,14501,14500,14499,14498,14497,14496,14495,14494,14493,14492,14491,14490,14489,14488,14487,14486,14485,14484,14483,14482,14481,14480,14479,14478,14477,14476,14475,14474,14473,14472,14471,14470,14469,14468,14467,14466,14465,14464,14463,14462,14461,14460,14459,14458,14457,14456,14455,14454,14453,14452,14451,14450,14449,14448,14447,14446,14445,14444,14443,14442,14441,14440,14439,14438,14437,14436,14435,14434,14433,14432,14431,14430,14429,14428,14427,14426,14425,14424,14423,14422,14421,14420,14419,14418,14417,14416,14415,14414,14413,14412,14411,14410,14409,14408,14407,14406,14405,14404,14403,14402,14401,14400,14399,14398,14397,14396,14395,14394,14393,14392,14391,14390,14389,14388,14387,14386,14385,14384,14383,14382,14381,14380,14379,14378,14377,14376,14375,14374,14373,14372,14371,14370,14369,14368,14367,14366,14365,14364,14363,14362,14361,14360,14359,14358,14357,14356,14355,14354,14353,14352,14351,14350,14349,14348,14347,14346,14345,14344,14343,14342,14341,14340,14339,14338,14337,14336,14335,14334,14333,14332,14331,14330,14329,14328,14327,14326,14325,14324,14323,14322,14321,14320,14319,14318,14317,14316,14315,14314,14313,14312,14311,14310,14309,14308,14307,14306,14305,14304,14303,14302,14301,14300,14299,14298,14297,14296,14295,14294,14293,14292,14291,14290,14289,14288,14287,14286,14285,14284,14283,14282,14281,14280,14279,14278,14277,14276,14275,14274,14273,14272,14271,14270,14269,14268,14267,14266,14265,14264,14263,14262,14261,14260,14259,14258,14257,14256,14255,14254,14253,14252,14251,14250,14249,14248,14247,14246,14245,14244,14243,14242,14241,14240,14239,14238,14237,14236,14235,14234,14233,14232,14231,14230,14229,14228,14227,14226,14225,14224,14223,14222,14221,14220,14219,14218,14217,14216,14215,14214,14213,14212,14211,14210,14209,14208,14207,14206,14205,14204,14203,14202,14201,14200,14199,14198,14197,14196,14195,14194,14193,14192,14191,14190,14189,14188,14187,14186,14185,14184,14183,14182,14181,14180,14179,14178,14177,14176,14175,14174,14173,14172,14171,14170,14169,14168,14167,14166,14165,14164,14163,14162,14161,14160,14159,14158,14157,14156,14155,14154,14153,14152,14151,14150,14149,14148,14147,14146,14145,14144,14143,14142,14141,14140,14139,14138,14137,14136,14135,14134,14133,14132,14131,14130,14129,14128,14127,14126,14125,14124,14123,14122,14121,14120,14119,14118,14117,14116,14115,14114,14113,14112,14111,14110,14109,14108,14107,14106,14105,14104,14103,14102,14101,14100,14099,14098,14097,14096,14095,14094,14093,14092,14091,14090,14089,14088,14087,14086,14085,14084,14083,14082,14081,14080,14079,14078,14077,14076,14075,14074,14073,14072,14071,14070,14069,14068,14067,14066,14065,14064,14063,14062,14061,14060,14059,14058,14057,14056,14055,14054,14053,14052,14051,14050,14049,14048,14047,14046,14045,14044,14043,14042,14041,14040,14039,14038,14037,14036,14035,14034,14033,14032,14031,14030,14029,14028,14027,14026,14025,14024,14023,14022,14021,14020,14019,14018,14017,14016,14015,14014,14013,14012,14011,14010,14009,14008,14007,14006,14005,14004,14003,14002,14001,14000,13999,13998,13997,13996,13995,13994,13993,13992,13991,13990,13989,13988,13987,13986,13985,13984,13983,13982,13981,13980,13979,13978,13977,13976,13975,13974,13973,13972,13971,13970,13969,13968,13967,13966,13965,13964,13963,13962,13961,13960,13959,13958,13957,13956,13955,13954,13953,13952,13951,13950,13949,13948,13947,13946,13945,13944,13943,13942,13941,13940,13939,13938,13937,13936,13935,13934,13933,13932,13931,13930,13929,13928,13927,13926,13925,13924,13923,13922,13921,13920,13919,13918,13917,13916,13915,13914,13913,13912,13911,13910,13909,13908,13907,13906,13905,13904,13903,13902,13901,13900,13899,13898,13897,13896,13895,13894,13893,13892,13891,13890,13889,13888,13887,13886,13885,13884,13883,13882,13881,13880,13879,13878,13877,13876,13875,13874,13873,13872,13871,13870,13869,13868,13867,13866,13865,13864,13863,13862,13861,13860,13859,13858,13857,13856,13855,13854,13853,13852,13851,13850,13849,13848,13847,13846,13845,13844,13843,13842,13841,13840,13839,13838,13837,13836,13835,13834,13833,13832,13831,13830,13829,13828,13827,13826,13825,13824,13823,13822,13821,13820,13819,13818,13817,13816,13815,13814,13813,13812,13811,13810,13809,13808,13807,13806,13805,13804,13803,13802,13801,13800,13799,13798,13797,13796,13795,13794,13793,13792,13791,13790,13789,13788,13787,13786,13785,13784,13783,13782,13781,13780,13779,13778,13777,13776,13775,13774,13773,13772,13771,13770,13769,13768,13767,13766,13765,13764,13763,13762,13761,13760,13759,13758,13757,13756,13755,13754,13753,13752,13751,13750,13749,13748,13747,13746,13745,13744,13743,13742,13741,13740,13739,13738,13737,13736,13735,13734,13733,13732,13731,13730,13729,13728,13727,13726,13725,13724,13723,13722,13721,13720,13719,13718,13717,13716,13715,13714,13713,13712,13711,13710,13709,13708,13707,13706,13705,13704,13703,13702,13701,13700,13699,13698,13697,13696,13695,13694,13693,13692,13691,13690,13689,13688,13687,13686,13685,13684,13683,13682,13681,13680,13679,13678,13677,13676,13675,13674,13673,13672,13671,13670,13669,13668,13667,13666,13665,13664,13663,13662,13661,13660,13659,13658,13657,13656,13655,13654,13653,13652,13651,13650,13649,13648,13647,13646,13645,13644,13643,13642,13641,13640,13639,13638,13637,13636,13635,13634,13633,13632,13631,13630,13629,13628,13627,13626,13625,13624,13623,13622,13621,13620,13619,13618,13617,13616,13615,13614,13613,13612,13611,13610,13609,13608,13607,13606,13605,13604,13603,13602,13601,13600,13599,13598,13597,13596,13595,13594,13593,13592,13591,13590,13589,13588,13587,13586,13585,13584,13583,13582,13581,13580,13579,13578,13577,13576,13575,13574,13573,13572,13571,13570,13569,13568,13567,13566,13565,13564,13563,13562,13561,13560,13559,13558,13557,13556,13555,13554,13553,13552,13551,13550,13549,13548,13547,13546,13545,13544,13543,13542,13541,13540,13539,13538,13537,13536,13535,13534,13533,13532,13531,13530,13529,13528,13527,13526,13525,13524,13523,13522,13521,13520,13519,13518,13517,13516,13515,13514,13513,13512,13511,13510,13509,13508,13507,13506,13505,13504,13503,13502,13501,13500,13499,13498,13497,13496,13495,13494,13493,13492,13491,13490,13489,13488,13487,13486,13485,13484,13483,13482,13481,13480,13479,13478,13477,13476,13475,13474,13473,13472,13471,13470,13469,13468,13467,13466,13465,13464,13463,13462,13461,13460,13459,13458,13457,13456,13455,13454,13453,13452,13451,13450,13449,13448,13447,13446,13445,13444,13443,13442,13441,13440,13439,13438,13437,13436,13435,13434,13433,13432,13431,13430,13429,13428,13427,13426,13425,13424,13423,13422,13421,13420,13419,13418,13417,13416,13415,13414,13413,13412,13411,13410,13409,13408,13407,13406,13405,13404,13403,13402,13401,13400,13399,13398,13397,13396,13395,13394,13393,13392,13391,13390,13389,13388,13387,13386,13385,13384,13383,13382,13381,13380,13379,13378,13377,13376,13375,13374,13373,13372,13371,13370,13369,13368,13367,13366,13365,13364,13363,13362,13361,13360,13359,13358,13357,13356,13355,13354,13353,13352,13351,13350,13349,13348,13347,13346,13345,13344,13343,13342,13341,13340,13339,13338,13337,13336,13335,13334,13333,13332,13331,13330,13329,13328,13327,13326,13325,13324,13323,13322,13321,13320,13319,13318,13317,13316,13315,13314,13313,13312,13311,13310,13309,13308,13307,13306,13305,13304,13303,13302,13301,13300,13299,13298,13297,13296,13295,13294,13293,13292,13291,13290,13289,13288,13287,13286,13285,13284,13283,13282,13281,13280,13279,13278,13277,13276,13275,13274,13273,13272,13271,13270,13269,13268,13267,13266,13265,13264,13263,13262,13261,13260,13259,13258,13257,13256,13255,13254,13253,13252,13251,13250,13249,13248,13247,13246,13245,13244,13243,13242,13241,13240,13239,13238,13237,13236,13235,13234,13233,13232,13231,13230,13229,13228,13227,13226,13225,13224,13223,13222,13221,13220,13219,13218,13217,13216,13215,13214,13213,13212,13211,13210,13209,13208,13207,13206,13205,13204,13203,13202,13201,13200,13199,13198,13197,13196,13195,13194,13193,13192,13191,13190,13189,13188,13187,13186,13185,13184,13183,13182,13181,13180,13179,13178,13177,13176,13175,13174,13173,13172,13171,13170,13169,13168,13167,13166,13165,13164,13163,13162,13161,13160,13159,13158,13157,13156,13155,13154,13153,13152,13151,13150,13149,13148,13147,13146,13145,13144,13143,13142,13141,13140,13139,13138,13137,13136,13135,13134,13133,13132,13131,13130,13129,13128,13127,13126,13125,13124,13123,13122,13121,13120,13119,13118,13117,13116,13115,13114,13113,13112,13111,13110,13109,13108,13107,13106,13105,13104,13103,13102,13101,13100,13099,13098,13097,13096,13095,13094,13093,13092,13091,13090,13089,13088,13087,13086,13085,13084,13083,13082,13081,13080,13079,13078,13077,13076,13075,13074,13073,13072,13071,13070,13069,13068,13067,13066,13065,13064,13063,13062,13061,13060,13059,13058,13057,13056,13055,13054,13053,13052,13051,13050,13049,13048,13047,13046,13045,13044,13043,13042,13041,13040,13039,13038,13037,13036,13035,13034,13033,13032,13031,13030,13029,13028,13027,13026,13025,13024,13023,13022,13021,13020,13019,13018,13017,13016,13015,13014,13013,13012,13011,13010,13009,13008,13007,13006,13005,13004,13003,13002,13001,13000,12999,12998,12997,12996,12995,12994,12993,12992,12991,12990,12989,12988,12987,12986,12985,12984,12983,12982,12981,12980,12979,12978,12977,12976,12975,12974,12973,12972,12971,12970,12969,12968,12967,12966,12965,12964,12963,12962,12961,12960,12959,12958,12957,12956,12955,12954,12953,12952,12951,12950,12949,12948,12947,12946,12945,12944,12943,12942,12941,12940,12939,12938,12937,12936,12935,12934,12933,12932,12931,12930,12929,12928,12927,12926,12925,12924,12923,12922,12921,12920,12919,12918,12917,12916,12915,12914,12913,12912,12911,12910,12909,12908,12907,12906,12905,12904,12903,12902,12901,12900,12899,12898,12897,12896,12895,12894,12893,12892,12891,12890,12889,12888,12887,12886,12885,12884,12883,12882,12881,12880,12879,12878,12877,12876,12875,12874,12873,12872,12871,12870,12869,12868,12867,12866,12865,12864,12863,12862,12861,12860,12859,12858,12857,12856,12855,12854,12853,12852,12851,12850,12849,12848,12847,12846,12845,12844,12843,12842,12841,12840,12839,12838,12837,12836,12835,12834,12833,12832,12831,12830,12829,12828,12827,12826,12825,12824,12823,12822,12821,12820,12819,12818,12817,12816,12815,12814,12813,12812,12811,12810,12809,12808,12807,12806,12805,12804,12803,12802,12801,12800,12799,12798,12797,12796,12795,12794,12793,12792,12791,12790,12789,12788,12787,12786,12785,12784,12783,12782,12781,12780,12779,12778,12777,12776,12775,12774,12773,12772,12771,12770,12769,12768,12767,12766,12765,12764,12763,12762,12761,12760,12759,12758,12757,12756,12755,12754,12753,12752,12751,12750,12749,12748,12747,12746,12745,12744,12743,12742,12741,12740,12739,12738,12737,12736,12735,12734,12733,12732,12731,12730,12729,12728,12727,12726,12725,12724,12723,12722,12721,12720,12719,12718,12717,12716,12715,12714,12713,12712,12711,12710,12709,12708,12707,12706,12705,12704,12703,12702,12701,12700,12699,12698,12697,12696,12695,12694,12693,12692,12691,12690,12689,12688,12687,12686,12685,12684,12683,12682,12681,12680,12679,12678,12677,12676,12675,12674,12673,12672,12671,12670,12669,12668,12667,12666,12665,12664,12663,12662,12661,12660,12659,12658,12657,12656,12655,12654,12653,12652,12651,12650,12649,12648,12647,12646,12645,12644,12643,12642,12641,12640,12639,12638,12637,12636,12635,12634,12633,12632,12631,12630,12629,12628,12627,12626,12625,12624,12623,12622,12621,12620,12619,12618,12617,12616,12615,12614,12613,12612,12611,12610,12609,12608,12607,12606,12605,12604,12603,12602,12601,12600,12599,12598,12597,12596,12595,12594,12593,12592,12591,12590,12589,12588,12587,12586,12585,12584,12583,12582,12581,12580,12579,12578,12577,12576,12575,12574,12573,12572,12571,12570,12569,12568,12567,12566,12565,12564,12563,12562,12561,12560,12559,12558,12557,12556,12555,12554,12553,12552,12551,12550,12549,12548,12547,12546,12545,12544,12543,12542,12541,12540,12539,12538,12537,12536,12535,12534,12533,12532,12531,12530,12529,12528,12527,12526,12525,12524,12523,12522,12521,12520,12519,12518,12517,12516,12515,12514,12513,12512,12511,12510,12509,12508,12507,12506,12505,12504,12503,12502,12501,12500,12499,12498,12497,12496,12495,12494,12493,12492,12491,12490,12489,12488,12487,12486,12485,12484,12483,12482,12481,12480,12479,12478,12477,12476,12475,12474,12473,12472,12471,12470,12469,12468,12467,12466,12465,12464,12463,12462,12461,12460,12459,12458,12457,12456,12455,12454,12453,12452,12451,12450,12449,12448,12447,12446,12445,12444,12443,12442,12441,12440,12439,12438,12437,12436,12435,12434,12433,12432,12431,12430,12429,12428,12427,12426,12425,12424,12423,12422,12421,12420,12419,12418,12417,12416,12415,12414,12413,12412,12411,12410,12409,12408,12407,12406,12405,12404,12403,12402,12401,12400,12399,12398,12397,12396,12395,12394,12393,12392,12391,12390,12389,12388,12387,12386,12385,12384,12383,12382,12381,12380,12379,12378,12377,12376,12375,12374,12373,12372,12371,12370,12369,12368,12367,12366,12365,12364,12363,12362,12361,12360,12359,12358,12357,12356,12355,12354,12353,12352,12351,12350,12349,12348,12347,12346,12345,12344,12343,12342,12341,12340,12339,12338,12337,12336,12335,12334,12333,12332,12331,12330,12329,12328,12327,12326,12325,12324,12323,12322,12321,12320,12319,12318,12317,12316,12315,12314,12313,12312,12311,12310,12309,12308,12307,12306,12305,12304,12303,12302,12301,12300,12299,12298,12297,12296,12295,12294,12293,12292,12291,12290,12289,12288,12287,12286,12285,12284,12283,12282,12281,12280,12279,12278,12277,12276,12275,12274,12273,12272,12271,12270,12269,12268,12267,12266,12265,12264,12263,12262,12261,12260,12259,12258,12257,12256,12255,12254,12253,12252,12251,12250,12249,12248,12247,12246,12245,12244,12243,12242,12241,12240,12239,12238,12237,12236,12235,12234,12233,12232,12231,12230,12229,12228,12227,12226,12225,12224,12223,12222,12221,12220,12219,12218,12217,12216,12215,12214,12213,12212,12211,12210,12209,12208,12207,12206,12205,12204,12203,12202,12201,12200,12199,12198,12197,12196,12195,12194,12193,12192,12191,12190,12189,12188,12187,12186,12185,12184,12183,12182,12181,12180,12179,12178,12177,12176,12175,12174,12173,12172,12171,12170,12169,12168,12167,12166,12165,12164,12163,12162,12161,12160,12159,12158,12157,12156,12155,12154,12153,12152,12151,12150,12149,12148,12147,12146,12145,12144,12143,12142,12141,12140,12139,12138,12137,12136,12135,12134,12133,12132,12131,12130,12129,12128,12127,12126,12125,12124,12123,12122,12121,12120,12119,12118,12117,12116,12115,12114,12113,12112,12111,12110,12109,12108,12107,12106,12105,12104,12103,12102,12101,12100,12099,12098,12097,12096,12095,12094,12093,12092,12091,12090,12089,12088,12087,12086,12085,12084,12083,12082,12081,12080,12079,12078,12077,12076,12075,12074,12073,12072,12071,12070,12069,12068,12067,12066,12065,12064,12063,12062,12061,12060,12059,12058,12057,12056,12055,12054,12053,12052,12051,12050,12049,12048,12047,12046,12045,12044,12043,12042,12041,12040,12039,12038,12037,12036,12035,12034,12033,12032,12031,12030,12029,12028,12027,12026,12025,12024,12023,12022,12021,12020,12019,12018,12017,12016,12015,12014,12013,12012,12011,12010,12009,12008,12007,12006,12005,12004,12003,12002,12001,12000,11999,11998,11997,11996,11995,11994,11993,11992,11991,11990,11989,11988,11987,11986,11985,11984,11983,11982,11981,11980,11979,11978,11977,11976,11975,11974,11973,11972,11971,11970,11969,11968,11967,11966,11965,11964,11963,11962,11961,11960,11959,11958,11957,11956,11955,11954,11953,11952,11951,11950,11949,11948,11947,11946,11945,11944,11943,11942,11941,11940,11939,11938,11937,11936,11935,11934,11933,11932,11931,11930,11929,11928,11927,11926,11925,11924,11923,11922,11921,11920,11919,11918,11917,11916,11915,11914,11913,11912,11911,11910,11909,11908,11907,11906,11905,11904,11903,11902,11901,11900,11899,11898,11897,11896,11895,11894,11893,11892,11891,11890,11889,11888,11887,11886,11885,11884,11883,11882,11881,11880,11879,11878,11877,11876,11875,11874,11873,11872,11871,11870,11869,11868,11867,11866,11865,11864,11863,11862,11861,11860,11859,11858,11857,11856,11855,11854,11853,11852,11851,11850,11849,11848,11847,11846,11845,11844,11843,11842,11841,11840,11839,11838,11837,11836,11835,11834,11833,11832,11831,11830,11829,11828,11827,11826,11825,11824,11823,11822,11821,11820,11819,11818,11817,11816,11815,11814,11813,11812,11811,11810,11809,11808,11807,11806,11805,11804,11803,11802,11801,11800,11799,11798,11797,11796,11795,11794,11793,11792,11791,11790,11789,11788,11787,11786,11785,11784,11783,11782,11781,11780,11779,11778,11777,11776,11775,11774,11773,11772,11771,11770,11769,11768,11767,11766,11765,11764,11763,11762,11761,11760,11759,11758,11757,11756,11755,11754,11753,11752,11751,11750,11749,11748,11747,11746,11745,11744,11743,11742,11741,11740,11739,11738,11737,11736,11735,11734,11733,11732,11731,11730,11729,11728,11727,11726,11725,11724,11723,11722,11721,11720,11719,11718,11717,11716,11715,11714,11713,11712,11711,11710,11709,11708,11707,11706,11705,11704,11703,11702,11701,11700,11699,11698,11697,11696,11695,11694,11693,11692,11691,11690,11689,11688,11687,11686,11685,11684,11683,11682,11681,11680,11679,11678,11677,11676,11675,11674,11673,11672,11671,11670,11669,11668,11667,11666,11665,11664,11663,11662,11661,11660,11659,11658,11657,11656,11655,11654,11653,11652,11651,11650,11649,11648,11647,11646,11645,11644,11643,11642,11641,11640,11639,11638,11637,11636,11635,11634,11633,11632,11631,11630,11629,11628,11627,11626,11625,11624,11623,11622,11621,11620,11619,11618,11617,11616,11615,11614,11613,11612,11611,11610,11609,11608,11607,11606,11605,11604,11603,11602,11601,11600,11599,11598,11597,11596,11595,11594,11593,11592,11591,11590,11589,11588,11587,11586,11585,11584,11583,11582,11581,11580,11579,11578,11577,11576,11575,11574,11573,11572,11571,11570,11569,11568,11567,11566,11565,11564,11563,11562,11561,11560,11559,11558,11557,11556,11555,11554,11553,11552,11551,11550,11549,11548,11547,11546,11545,11544,11543,11542,11541,11540,11539,11538,11537,11536,11535,11534,11533,11532,11531,11530,11529,11528,11527,11526,11525,11524,11523,11522,11521,11520,11519,11518,11517,11516,11515,11514,11513,11512,11511,11510,11509,11508,11507,11506,11505,11504,11503,11502,11501,11500,11499,11498,11497,11496,11495,11494,11493,11492,11491,11490,11489,11488,11487,11486,11485,11484,11483,11482,11481,11480,11479,11478,11477,11476,11475,11474,11473,11472,11471,11470,11469,11468,11467,11466,11465,11464,11463,11462,11461,11460,11459,11458,11457,11456,11455,11454,11453,11452,11451,11450,11449,11448,11447,11446,11445,11444,11443,11442,11441,11440,11439,11438,11437,11436,11435,11434,11433,11432,11431,11430,11429,11428,11427,11426,11425,11424,11423,11422,11421,11420,11419,11418,11417,11416,11415,11414,11413,11412,11411,11410,11409,11408,11407,11406,11405,11404,11403,11402,11401,11400,11399,11398,11397,11396,11395,11394,11393,11392,11391,11390,11389,11388,11387,11386,11385,11384,11383,11382,11381,11380,11379,11378,11377,11376,11375,11374,11373,11372,11371,11370,11369,11368,11367,11366,11365,11364,11363,11362,11361,11360,11359,11358,11357,11356,11355,11354,11353,11352,11351,11350,11349,11348,11347,11346,11345,11344,11343,11342,11341,11340,11339,11338,11337,11336,11335,11334,11333,11332,11331,11330,11329,11328,11327,11326,11325,11324,11323,11322,11321,11320,11319,11318,11317,11316,11315,11314,11313,11312,11311,11310,11309,11308,11307,11306,11305,11304,11303,11302,11301,11300,11299,11298,11297,11296,11295,11294,11293,11292,11291,11290,11289,11288,11287,11286,11285,11284,11283,11282,11281,11280,11279,11278,11277,11276,11275,11274,11273,11272,11271,11270,11269,11268,11267,11266,11265,11264,11263,11262,11261,11260,11259,11258,11257,11256,11255,11254,11253,11252,11251,11250,11249,11248,11247,11246,11245,11244,11243,11242,11241,11240,11239,11238,11237,11236,11235,11234,11233,11232,11231,11230,11229,11228,11227,11226,11225,11224,11223,11222,11221,11220,11219,11218,11217,11216,11215,11214,11213,11212,11211,11210,11209,11208,11207,11206,11205,11204,11203,11202,11201,11200,11199,11198,11197,11196,11195,11194,11193,11192,11191,11190,11189,11188,11187,11186,11185,11184,11183,11182,11181,11180,11179,11178,11177,11176,11175,11174,11173,11172,11171,11170,11169,11168,11167,11166,11165,11164,11163,11162,11161,11160,11159,11158,11157,11156,11155,11154,11153,11152,11151,11150,11149,11148,11147,11146,11145,11144,11143,11142,11141,11140,11139,11138,11137,11136,11135,11134,11133,11132,11131,11130,11129,11128,11127,11126,11125,11124,11123,11122,11121,11120,11119,11118,11117,11116,11115,11114,11113,11112,11111,11110,11109,11108,11107,11106,11105,11104,11103,11102,11101,11100,11099,11098,11097,11096,11095,11094,11093,11092,11091,11090,11089,11088,11087,11086,11085,11084,11083,11082,11081,11080,11079,11078,11077,11076,11075,11074,11073,11072,11071,11070,11069,11068,11067,11066,11065,11064,11063,11062,11061,11060,11059,11058,11057,11056,11055,11054,11053,11052,11051,11050,11049,11048,11047,11046,11045,11044,11043,11042,11041,11040,11039,11038,11037,11036,11035,11034,11033,11032,11031,11030,11029,11028,11027,11026,11025,11024,11023,11022,11021,11020,11019,11018,11017,11016,11015,11014,11013,11012,11011,11010,11009,11008,11007,11006,11005,11004,11003,11002,11001,11000,10999,10998,10997,10996,10995,10994,10993,10992,10991,10990,10989,10988,10987,10986,10985,10984,10983,10982,10981,10980,10979,10978,10977,10976,10975,10974,10973,10972,10971,10970,10969,10968,10967,10966,10965,10964,10963,10962,10961,10960,10959,10958,10957,10956,10955,10954,10953,10952,10951,10950,10949,10948,10947,10946,10945,10944,10943,10942,10941,10940,10939,10938,10937,10936,10935,10934,10933,10932,10931,10930,10929,10928,10927,10926,10925,10924,10923,10922,10921,10920,10919,10918,10917,10916,10915,10914,10913,10912,10911,10910,10909,10908,10907,10906,10905,10904,10903,10902,10901,10900,10899,10898,10897,10896,10895,10894,10893,10892,10891,10890,10889,10888,10887,10886,10885,10884,10883,10882,10881,10880,10879,10878,10877,10876,10875,10874,10873,10872,10871,10870,10869,10868,10867,10866,10865,10864,10863,10862,10861,10860,10859,10858,10857,10856,10855,10854,10853,10852,10851,10850,10849,10848,10847,10846,10845,10844,10843,10842,10841,10840,10839,10838,10837,10836,10835,10834,10833,10832,10831,10830,10829,10828,10827,10826,10825,10824,10823,10822,10821,10820,10819,10818,10817,10816,10815,10814,10813,10812,10811,10810,10809,10808,10807,10806,10805,10804,10803,10802,10801,10800,10799,10798,10797,10796,10795,10794,10793,10792,10791,10790,10789,10788,10787,10786,10785,10784,10783,10782,10781,10780,10779,10778,10777,10776,10775,10774,10773,10772,10771,10770,10769,10768,10767,10766,10765,10764,10763,10762,10761,10760,10759,10758,10757,10756,10755,10754,10753,10752,10751,10750,10749,10748,10747,10746,10745,10744,10743,10742,10741,10740,10739,10738,10737,10736,10735,10734,10733,10732,10731,10730,10729,10728,10727,10726,10725,10724,10723,10722,10721,10720,10719,10718,10717,10716,10715,10714,10713,10712,10711,10710,10709,10708,10707,10706,10705,10704,10703,10702,10701,10700,10699,10698,10697,10696,10695,10694,10693,10692,10691,10690,10689,10688,10687,10686,10685,10684,10683,10682,10681,10680,10679,10678,10677,10676,10675,10674,10673,10672,10671,10670,10669,10668,10667,10666,10665,10664,10663,10662,10661,10660,10659,10658,10657,10656,10655,10654,10653,10652,10651,10650,10649,10648,10647,10646,10645,10644,10643,10642,10641,10640,10639,10638,10637,10636,10635,10634,10633,10632,10631,10630,10629,10628,10627,10626,10625,10624,10623,10622,10621,10620,10619,10618,10617,10616,10615,10614,10613,10612,10611,10610,10609,10608,10607,10606,10605,10604,10603,10602,10601,10600,10599,10598,10597,10596,10595,10594,10593,10592,10591,10590,10589,10588,10587,10586,10585,10584,10583,10582,10581,10580,10579,10578,10577,10576,10575,10574,10573,10572,10571,10570,10569,10568,10567,10566,10565,10564,10563,10562,10561,10560,10559,10558,10557,10556,10555,10554,10553,10552,10551,10550,10549,10548,10547,10546,10545,10544,10543,10542,10541,10540,10539,10538,10537,10536,10535,10534,10533,10532,10531,10530,10529,10528,10527,10526,10525,10524,10523,10522,10521,10520,10519,10518,10517,10516,10515,10514,10513,10512,10511,10510,10509,10508,10507,10506,10505,10504,10503,10502,10501,10500,10499,10498,10497,10496,10495,10494,10493,10492,10491,10490,10489,10488,10487,10486,10485,10484,10483,10482,10481,10480,10479,10478,10477,10476,10475,10474,10473,10472,10471,10470,10469,10468,10467,10466,10465,10464,10463,10462,10461,10460,10459,10458,10457,10456,10455,10454,10453,10452,10451,10450,10449,10448,10447,10446,10445,10444,10443,10442,10441,10440,10439,10438,10437,10436,10435,10434,10433,10432,10431,10430,10429,10428,10427,10426,10425,10424,10423,10422,10421,10420,10419,10418,10417,10416,10415,10414,10413,10412,10411,10410,10409,10408,10407,10406,10405,10404,10403,10402,10401,10400,10399,10398,10397,10396,10395,10394,10393,10392,10391,10390,10389,10388,10387,10386,10385,10384,10383,10382,10381,10380,10379,10378,10377,10376,10375,10374,10373,10372,10371,10370,10369,10368,10367,10366,10365,10364,10363,10362,10361,10360,10359,10358,10357,10356,10355,10354,10353,10352,10351,10350,10349,10348,10347,10346,10345,10344,10343,10342,10341,10340,10339,10338,10337,10336,10335,10334,10333,10332,10331,10330,10329,10328,10327,10326,10325,10324,10323,10322,10321,10320,10319,10318,10317,10316,10315,10314,10313,10312,10311,10310,10309,10308,10307,10306,10305,10304,10303,10302,10301,10300,10299,10298,10297,10296,10295,10294,10293,10292,10291,10290,10289,10288,10287,10286,10285,10284,10283,10282,10281,10280,10279,10278,10277,10276,10275,10274,10273,10272,10271,10270,10269,10268,10267,10266,10265,10264,10263,10262,10261,10260,10259,10258,10257,10256,10255,10254,10253,10252,10251,10250,10249,10248,10247,10246,10245,10244,10243,10242,10241,10240,10239,10238,10237,10236,10235,10234,10233,10232,10231,10230,10229,10228,10227,10226,10225,10224,10223,10222,10221,10220,10219,10218,10217,10216,10215,10214,10213,10212,10211,10210,10209,10208,10207,10206,10205,10204,10203,10202,10201,10200,10199,10198,10197,10196,10195,10194,10193,10192,10191,10190,10189,10188,10187,10186,10185,10184,10183,10182,10181,10180,10179,10178,10177,10176,10175,10174,10173,10172,10171,10170,10169,10168,10167,10166,10165,10164,10163,10162,10161,10160,10159,10158,10157,10156,10155,10154,10153,10152,10151,10150,10149,10148,10147,10146,10145,10144,10143,10142,10141,10140,10139,10138,10137,10136,10135,10134,10133,10132,10131,10130,10129,10128,10127,10126,10125,10124,10123,10122,10121,10120,10119,10118,10117,10116,10115,10114,10113,10112,10111,10110,10109,10108,10107,10106,10105,10104,10103,10102,10101,10100,10099,10098,10097,10096,10095,10094,10093,10092,10091,10090,10089,10088,10087,10086,10085,10084,10083,10082,10081,10080,10079,10078,10077,10076,10075,10074,10073,10072,10071,10070,10069,10068,10067,10066,10065,10064,10063,10062,10061,10060,10059,10058,10057,10056,10055,10054,10053,10052,10051,10050,10049,10048,10047,10046,10045,10044,10043,10042,10041,10040,10039,10038,10037,10036,10035,10034,10033,10032,10031,10030,10029,10028,10027,10026,10025,10024,10023,10022,10021,10020,10019,10018,10017,10016,10015,10014,10013,10012,10011,10010,10009,10008,10007,10006,10005,10004,10003,10002,10001,10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989,9988,9987,9986,9985,9984,9983,9982,9981,9980,9979,9978,9977,9976,9975,9974,9973,9972,9971,9970,9969,9968,9967,9966,9965,9964,9963,9962,9961,9960,9959,9958,9957,9956,9955,9954,9953,9952,9951,9950,9949,9948,9947,9946,9945,9944,9943,9942,9941,9940,9939,9938,9937,9936,9935,9934,9933,9932,9931,9930,9929,9928,9927,9926,9925,9924,9923,9922,9921,9920,9919,9918,9917,9916,9915,9914,9913,9912,9911,9910,9909,9908,9907,9906,9905,9904,9903,9902,9901,9900,9899,9898,9897,9896,9895,9894,9893,9892,9891,9890,9889,9888,9887,9886,9885,9884,9883,9882,9881,9880,9879,9878,9877,9876,9875,9874,9873,9872,9871,9870,9869,9868,9867,9866,9865,9864,9863,9862,9861,9860,9859,9858,9857,9856,9855,9854,9853,9852,9851,9850,9849,9848,9847,9846,9845,9844,9843,9842,9841,9840,9839,9838,9837,9836,9835,9834,9833,9832,9831,9830,9829,9828,9827,9826,9825,9824,9823,9822,9821,9820,9819,9818,9817,9816,9815,9814,9813,9812,9811,9810,9809,9808,9807,9806,9805,9804,9803,9802,9801,9800,9799,9798,9797,9796,9795,9794,9793,9792,9791,9790,9789,9788,9787,9786,9785,9784,9783,9782,9781,9780,9779,9778,9777,9776,9775,9774,9773,9772,9771,9770,9769,9768,9767,9766,9765,9764,9763,9762,9761,9760,9759,9758,9757,9756,9755,9754,9753,9752,9751,9750,9749,9748,9747,9746,9745,9744,9743,9742,9741,9740,9739,9738,9737,9736,9735,9734,9733,9732,9731,9730,9729,9728,9727,9726,9725,9724,9723,9722,9721,9720,9719,9718,9717,9716,9715,9714,9713,9712,9711,9710,9709,9708,9707,9706,9705,9704,9703,9702,9701,9700,9699,9698,9697,9696,9695,9694,9693,9692,9691,9690,9689,9688,9687,9686,9685,9684,9683,9682,9681,9680,9679,9678,9677,9676,9675,9674,9673,9672,9671,9670,9669,9668,9667,9666,9665,9664,9663,9662,9661,9660,9659,9658,9657,9656,9655,9654,9653,9652,9651,9650,9649,9648,9647,9646,9645,9644,9643,9642,9641,9640,9639,9638,9637,9636,9635,9634,9633,9632,9631,9630,9629,9628,9627,9626,9625,9624,9623,9622,9621,9620,9619,9618,9617,9616,9615,9614,9613,9612,9611,9610,9609,9608,9607,9606,9605,9604,9603,9602,9601,9600,9599,9598,9597,9596,9595,9594,9593,9592,9591,9590,9589,9588,9587,9586,9585,9584,9583,9582,9581,9580,9579,9578,9577,9576,9575,9574,9573,9572,9571,9570,9569,9568,9567,9566,9565,9564,9563,9562,9561,9560,9559,9558,9557,9556,9555,9554,9553,9552,9551,9550,9549,9548,9547,9546,9545,9544,9543,9542,9541,9540,9539,9538,9537,9536,9535,9534,9533,9532,9531,9530,9529,9528,9527,9526,9525,9524,9523,9522,9521,9520,9519,9518,9517,9516,9515,9514,9513,9512,9511,9510,9509,9508,9507,9506,9505,9504,9503,9502,9501,9500,9499,9498,9497,9496,9495,9494,9493,9492,9491,9490,9489,9488,9487,9486,9485,9484,9483,9482,9481,9480,9479,9478,9477,9476,9475,9474,9473,9472,9471,9470,9469,9468,9467,9466,9465,9464,9463,9462,9461,9460,9459,9458,9457,9456,9455,9454,9453,9452,9451,9450,9449,9448,9447,9446,9445,9444,9443,9442,9441,9440,9439,9438,9437,9436,9435,9434,9433,9432,9431,9430,9429,9428,9427,9426,9425,9424,9423,9422,9421,9420,9419,9418,9417,9416,9415,9414,9413,9412,9411,9410,9409,9408,9407,9406,9405,9404,9403,9402,9401,9400,9399,9398,9397,9396,9395,9394,9393,9392,9391,9390,9389,9388,9387,9386,9385,9384,9383,9382,9381,9380,9379,9378,9377,9376,9375,9374,9373,9372,9371,9370,9369,9368,9367,9366,9365,9364,9363,9362,9361,9360,9359,9358,9357,9356,9355,9354,9353,9352,9351,9350,9349,9348,9347,9346,9345,9344,9343,9342,9341,9340,9339,9338,9337,9336,9335,9334,9333,9332,9331,9330,9329,9328,9327,9326,9325,9324,9323,9322,9321,9320,9319,9318,9317,9316,9315,9314,9313,9312,9311,9310,9309,9308,9307,9306,9305,9304,9303,9302,9301,9300,9299,9298,9297,9296,9295,9294,9293,9292,9291,9290,9289,9288,9287,9286,9285,9284,9283,9282,9281,9280,9279,9278,9277,9276,9275,9274,9273,9272,9271,9270,9269,9268,9267,9266,9265,9264,9263,9262,9261,9260,9259,9258,9257,9256,9255,9254,9253,9252,9251,9250,9249,9248,9247,9246,9245,9244,9243,9242,9241,9240,9239,9238,9237,9236,9235,9234,9233,9232,9231,9230,9229,9228,9227,9226,9225,9224,9223,9222,9221,9220,9219,9218,9217,9216,9215,9214,9213,9212,9211,9210,9209,9208,9207,9206,9205,9204,9203,9202,9201,9200,9199,9198,9197,9196,9195,9194,9193,9192,9191,9190,9189,9188,9187,9186,9185,9184,9183,9182,9181,9180,9179,9178,9177,9176,9175,9174,9173,9172,9171,9170,9169,9168,9167,9166,9165,9164,9163,9162,9161,9160,9159,9158,9157,9156,9155,9154,9153,9152,9151,9150,9149,9148,9147,9146,9145,9144,9143,9142,9141,9140,9139,9138,9137,9136,9135,9134,9133,9132,9131,9130,9129,9128,9127,9126,9125,9124,9123,9122,9121,9120,9119,9118,9117,9116,9115,9114,9113,9112,9111,9110,9109,9108,9107,9106,9105,9104,9103,9102,9101,9100,9099,9098,9097,9096,9095,9094,9093,9092,9091,9090,9089,9088,9087,9086,9085,9084,9083,9082,9081,9080,9079,9078,9077,9076,9075,9074,9073,9072,9071,9070,9069,9068,9067,9066,9065,9064,9063,9062,9061,9060,9059,9058,9057,9056,9055,9054,9053,9052,9051,9050,9049,9048,9047,9046,9045,9044,9043,9042,9041,9040,9039,9038,9037,9036,9035,9034,9033,9032,9031,9030,9029,9028,9027,9026,9025,9024,9023,9022,9021,9020,9019,9018,9017,9016,9015,9014,9013,9012,9011,9010,9009,9008,9007,9006,9005,9004,9003,9002,9001,9000,8999,8998,8997,8996,8995,8994,8993,8992,8991,8990,8989,8988,8987,8986,8985,8984,8983,8982,8981,8980,8979,8978,8977,8976,8975,8974,8973,8972,8971,8970,8969,8968,8967,8966,8965,8964,8963,8962,8961,8960,8959,8958,8957,8956,8955,8954,8953,8952,8951,8950,8949,8948,8947,8946,8945,8944,8943,8942,8941,8940,8939,8938,8937,8936,8935,8934,8933,8932,8931,8930,8929,8928,8927,8926,8925,8924,8923,8922,8921,8920,8919,8918,8917,8916,8915,8914,8913,8912,8911,8910,8909,8908,8907,8906,8905,8904,8903,8902,8901,8900,8899,8898,8897,8896,8895,8894,8893,8892,8891,8890,8889,8888,8887,8886,8885,8884,8883,8882,8881,8880,8879,8878,8877,8876,8875,8874,8873,8872,8871,8870,8869,8868,8867,8866,8865,8864,8863,8862,8861,8860,8859,8858,8857,8856,8855,8854,8853,8852,8851,8850,8849,8848,8847,8846,8845,8844,8843,8842,8841,8840,8839,8838,8837,8836,8835,8834,8833,8832,8831,8830,8829,8828,8827,8826,8825,8824,8823,8822,8821,8820,8819,8818,8817,8816,8815,8814,8813,8812,8811,8810,8809,8808,8807,8806,8805,8804,8803,8802,8801,8800,8799,8798,8797,8796,8795,8794,8793,8792,8791,8790,8789,8788,8787,8786,8785,8784,8783,8782,8781,8780,8779,8778,8777,8776,8775,8774,8773,8772,8771,8770,8769,8768,8767,8766,8765,8764,8763,8762,8761,8760,8759,8758,8757,8756,8755,8754,8753,8752,8751,8750,8749,8748,8747,8746,8745,8744,8743,8742,8741,8740,8739,8738,8737,8736,8735,8734,8733,8732,8731,8730,8729,8728,8727,8726,8725,8724,8723,8722,8721,8720,8719,8718,8717,8716,8715,8714,8713,8712,8711,8710,8709,8708,8707,8706,8705,8704,8703,8702,8701,8700,8699,8698,8697,8696,8695,8694,8693,8692,8691,8690,8689,8688,8687,8686,8685,8684,8683,8682,8681,8680,8679,8678,8677,8676,8675,8674,8673,8672,8671,8670,8669,8668,8667,8666,8665,8664,8663,8662,8661,8660,8659,8658,8657,8656,8655,8654,8653,8652,8651,8650,8649,8648,8647,8646,8645,8644,8643,8642,8641,8640,8639,8638,8637,8636,8635,8634,8633,8632,8631,8630,8629,8628,8627,8626,8625,8624,8623,8622,8621,8620,8619,8618,8617,8616,8615,8614,8613,8612,8611,8610,8609,8608,8607,8606,8605,8604,8603,8602,8601,8600,8599,8598,8597,8596,8595,8594,8593,8592,8591,8590,8589,8588,8587,8586,8585,8584,8583,8582,8581,8580,8579,8578,8577,8576,8575,8574,8573,8572,8571,8570,8569,8568,8567,8566,8565,8564,8563,8562,8561,8560,8559,8558,8557,8556,8555,8554,8553,8552,8551,8550,8549,8548,8547,8546,8545,8544,8543,8542,8541,8540,8539,8538,8537,8536,8535,8534,8533,8532,8531,8530,8529,8528,8527,8526,8525,8524,8523,8522,8521,8520,8519,8518,8517,8516,8515,8514,8513,8512,8511,8510,8509,8508,8507,8506,8505,8504,8503,8502,8501,8500,8499,8498,8497,8496,8495,8494,8493,8492,8491,8490,8489,8488,8487,8486,8485,8484,8483,8482,8481,8480,8479,8478,8477,8476,8475,8474,8473,8472,8471,8470,8469,8468,8467,8466,8465,8464,8463,8462,8461,8460,8459,8458,8457,8456,8455,8454,8453,8452,8451,8450,8449,8448,8447,8446,8445,8444,8443,8442,8441,8440,8439,8438,8437,8436,8435,8434,8433,8432,8431,8430,8429,8428,8427,8426,8425,8424,8423,8422,8421,8420,8419,8418,8417,8416,8415,8414,8413,8412,8411,8410,8409,8408,8407,8406,8405,8404,8403,8402,8401,8400,8399,8398,8397,8396,8395,8394,8393,8392,8391,8390,8389,8388,8387,8386,8385,8384,8383,8382,8381,8380,8379,8378,8377,8376,8375,8374,8373,8372,8371,8370,8369,8368,8367,8366,8365,8364,8363,8362,8361,8360,8359,8358,8357,8356,8355,8354,8353,8352,8351,8350,8349,8348,8347,8346,8345,8344,8343,8342,8341,8340,8339,8338,8337,8336,8335,8334,8333,8332,8331,8330,8329,8328,8327,8326,8325,8324,8323,8322,8321,8320,8319,8318,8317,8316,8315,8314,8313,8312,8311,8310,8309,8308,8307,8306,8305,8304,8303,8302,8301,8300,8299,8298,8297,8296,8295,8294,8293,8292,8291,8290,8289,8288,8287,8286,8285,8284,8283,8282,8281,8280,8279,8278,8277,8276,8275,8274,8273,8272,8271,8270,8269,8268,8267,8266,8265,8264,8263,8262,8261,8260,8259,8258,8257,8256,8255,8254,8253,8252,8251,8250,8249,8248,8247,8246,8245,8244,8243,8242,8241,8240,8239,8238,8237,8236,8235,8234,8233,8232,8231,8230,8229,8228,8227,8226,8225,8224,8223,8222,8221,8220,8219,8218,8217,8216,8215,8214,8213,8212,8211,8210,8209,8208,8207,8206,8205,8204,8203,8202,8201,8200,8199,8198,8197,8196,8195,8194,8193,8192,8191,8190,8189,8188,8187,8186,8185,8184,8183,8182,8181,8180,8179,8178,8177,8176,8175,8174,8173,8172,8171,8170,8169,8168,8167,8166,8165,8164,8163,8162,8161,8160,8159,8158,8157,8156,8155,8154,8153,8152,8151,8150,8149,8148,8147,8146,8145,8144,8143,8142,8141,8140,8139,8138,8137,8136,8135,8134,8133,8132,8131,8130,8129,8128,8127,8126,8125,8124,8123,8122,8121,8120,8119,8118,8117,8116,8115,8114,8113,8112,8111,8110,8109,8108,8107,8106,8105,8104,8103,8102,8101,8100,8099,8098,8097,8096,8095,8094,8093,8092,8091,8090,8089,8088,8087,8086,8085,8084,8083,8082,8081,8080,8079,8078,8077,8076,8075,8074,8073,8072,8071,8070,8069,8068,8067,8066,8065,8064,8063,8062,8061,8060,8059,8058,8057,8056,8055,8054,8053,8052,8051,8050,8049,8048,8047,8046,8045,8044,8043,8042,8041,8040,8039,8038,8037,8036,8035,8034,8033,8032,8031,8030,8029,8028,8027,8026,8025,8024,8023,8022,8021,8020,8019,8018,8017,8016,8015,8014,8013,8012,8011,8010,8009,8008,8007,8006,8005,8004,8003,8002,8001,8000,7999,7998,7997,7996,7995,7994,7993,7992,7991,7990,7989,7988,7987,7986,7985,7984,7983,7982,7981,7980,7979,7978,7977,7976,7975,7974,7973,7972,7971,7970,7969,7968,7967,7966,7965,7964,7963,7962,7961,7960,7959,7958,7957,7956,7955,7954,7953,7952,7951,7950,7949,7948,7947,7946,7945,7944,7943,7942,7941,7940,7939,7938,7937,7936,7935,7934,7933,7932,7931,7930,7929,7928,7927,7926,7925,7924,7923,7922,7921,7920,7919,7918,7917,7916,7915,7914,7913,7912,7911,7910,7909,7908,7907,7906,7905,7904,7903,7902,7901,7900,7899,7898,7897,7896,7895,7894,7893,7892,7891,7890,7889,7888,7887,7886,7885,7884,7883,7882,7881,7880,7879,7878,7877,7876,7875,7874,7873,7872,7871,7870,7869,7868,7867,7866,7865,7864,7863,7862,7861,7860,7859,7858,7857,7856,7855,7854,7853,7852,7851,7850,7849,7848,7847,7846,7845,7844,7843,7842,7841,7840,7839,7838,7837,7836,7835,7834,7833,7832,7831,7830,7829,7828,7827,7826,7825,7824,7823,7822,7821,7820,7819,7818,7817,7816,7815,7814,7813,7812,7811,7810,7809,7808,7807,7806,7805,7804,7803,7802,7801,7800,7799,7798,7797,7796,7795,7794,7793,7792,7791,7790,7789,7788,7787,7786,7785,7784,7783,7782,7781,7780,7779,7778,7777,7776,7775,7774,7773,7772,7771,7770,7769,7768,7767,7766,7765,7764,7763,7762,7761,7760,7759,7758,7757,7756,7755,7754,7753,7752,7751,7750,7749,7748,7747,7746,7745,7744,7743,7742,7741,7740,7739,7738,7737,7736,7735,7734,7733,7732,7731,7730,7729,7728,7727,7726,7725,7724,7723,7722,7721,7720,7719,7718,7717,7716,7715,7714,7713,7712,7711,7710,7709,7708,7707,7706,7705,7704,7703,7702,7701,7700,7699,7698,7697,7696,7695,7694,7693,7692,7691,7690,7689,7688,7687,7686,7685,7684,7683,7682,7681,7680,7679,7678,7677,7676,7675,7674,7673,7672,7671,7670,7669,7668,7667,7666,7665,7664,7663,7662,7661,7660,7659,7658,7657,7656,7655,7654,7653,7652,7651,7650,7649,7648,7647,7646,7645,7644,7643,7642,7641,7640,7639,7638,7637,7636,7635,7634,7633,7632,7631,7630,7629,7628,7627,7626,7625,7624,7623,7622,7621,7620,7619,7618,7617,7616,7615,7614,7613,7612,7611,7610,7609,7608,7607,7606,7605,7604,7603,7602,7601,7600,7599,7598,7597,7596,7595,7594,7593,7592,7591,7590,7589,7588,7587,7586,7585,7584,7583,7582,7581,7580,7579,7578,7577,7576,7575,7574,7573,7572,7571,7570,7569,7568,7567,7566,7565,7564,7563,7562,7561,7560,7559,7558,7557,7556,7555,7554,7553,7552,7551,7550,7549,7548,7547,7546,7545,7544,7543,7542,7541,7540,7539,7538,7537,7536,7535,7534,7533,7532,7531,7530,7529,7528,7527,7526,7525,7524,7523,7522,7521,7520,7519,7518,7517,7516,7515,7514,7513,7512,7511,7510,7509,7508,7507,7506,7505,7504,7503,7502,7501,7500,7499,7498,7497,7496,7495,7494,7493,7492,7491,7490,7489,7488,7487,7486,7485,7484,7483,7482,7481,7480,7479,7478,7477,7476,7475,7474,7473,7472,7471,7470,7469,7468,7467,7466,7465,7464,7463,7462,7461,7460,7459,7458,7457,7456,7455,7454,7453,7452,7451,7450,7449,7448,7447,7446,7445,7444,7443,7442,7441,7440,7439,7438,7437,7436,7435,7434,7433,7432,7431,7430,7429,7428,7427,7426,7425,7424,7423,7422,7421,7420,7419,7418,7417,7416,7415,7414,7413,7412,7411,7410,7409,7408,7407,7406,7405,7404,7403,7402,7401,7400,7399,7398,7397,7396,7395,7394,7393,7392,7391,7390,7389,7388,7387,7386,7385,7384,7383,7382,7381,7380,7379,7378,7377,7376,7375,7374,7373,7372,7371,7370,7369,7368,7367,7366,7365,7364,7363,7362,7361,7360,7359,7358,7357,7356,7355,7354,7353,7352,7351,7350,7349,7348,7347,7346,7345,7344,7343,7342,7341,7340,7339,7338,7337,7336,7335,7334,7333,7332,7331,7330,7329,7328,7327,7326,7325,7324,7323,7322,7321,7320,7319,7318,7317,7316,7315,7314,7313,7312,7311,7310,7309,7308,7307,7306,7305,7304,7303,7302,7301,7300,7299,7298,7297,7296,7295,7294,7293,7292,7291,7290,7289,7288,7287,7286,7285,7284,7283,7282,7281,7280,7279,7278,7277,7276,7275,7274,7273,7272,7271,7270,7269,7268,7267,7266,7265,7264,7263,7262,7261,7260,7259,7258,7257,7256,7255,7254,7253,7252,7251,7250,7249,7248,7247,7246,7245,7244,7243,7242,7241,7240,7239,7238,7237,7236,7235,7234,7233,7232,7231,7230,7229,7228,7227,7226,7225,7224,7223,7222,7221,7220,7219,7218,7217,7216,7215,7214,7213,7212,7211,7210,7209,7208,7207,7206,7205,7204,7203,7202,7201,7200,7199,7198,7197,7196,7195,7194,7193,7192,7191,7190,7189,7188,7187,7186,7185,7184,7183,7182,7181,7180,7179,7178,7177,7176,7175,7174,7173,7172,7171,7170,7169,7168,7167,7166,7165,7164,7163,7162,7161,7160,7159,7158,7157,7156,7155,7154,7153,7152,7151,7150,7149,7148,7147,7146,7145,7144,7143,7142,7141,7140,7139,7138,7137,7136,7135,7134,7133,7132,7131,7130,7129,7128,7127,7126,7125,7124,7123,7122,7121,7120,7119,7118,7117,7116,7115,7114,7113,7112,7111,7110,7109,7108,7107,7106,7105,7104,7103,7102,7101,7100,7099,7098,7097,7096,7095,7094,7093,7092,7091,7090,7089,7088,7087,7086,7085,7084,7083,7082,7081,7080,7079,7078,7077,7076,7075,7074,7073,7072,7071,7070,7069,7068,7067,7066,7065,7064,7063,7062,7061,7060,7059,7058,7057,7056,7055,7054,7053,7052,7051,7050,7049,7048,7047,7046,7045,7044,7043,7042,7041,7040,7039,7038,7037,7036,7035,7034,7033,7032,7031,7030,7029,7028,7027,7026,7025,7024,7023,7022,7021,7020,7019,7018,7017,7016,7015,7014,7013,7012,7011,7010,7009,7008,7007,7006,7005,7004,7003,7002,7001,7000,6999,6998,6997,6996,6995,6994,6993,6992,6991,6990,6989,6988,6987,6986,6985,6984,6983,6982,6981,6980,6979,6978,6977,6976,6975,6974,6973,6972,6971,6970,6969,6968,6967,6966,6965,6964,6963,6962,6961,6960,6959,6958,6957,6956,6955,6954,6953,6952,6951,6950,6949,6948,6947,6946,6945,6944,6943,6942,6941,6940,6939,6938,6937,6936,6935,6934,6933,6932,6931,6930,6929,6928,6927,6926,6925,6924,6923,6922,6921,6920,6919,6918,6917,6916,6915,6914,6913,6912,6911,6910,6909,6908,6907,6906,6905,6904,6903,6902,6901,6900,6899,6898,6897,6896,6895,6894,6893,6892,6891,6890,6889,6888,6887,6886,6885,6884,6883,6882,6881,6880,6879,6878,6877,6876,6875,6874,6873,6872,6871,6870,6869,6868,6867,6866,6865,6864,6863,6862,6861,6860,6859,6858,6857,6856,6855,6854,6853,6852,6851,6850,6849,6848,6847,6846,6845,6844,6843,6842,6841,6840,6839,6838,6837,6836,6835,6834,6833,6832,6831,6830,6829,6828,6827,6826,6825,6824,6823,6822,6821,6820,6819,6818,6817,6816,6815,6814,6813,6812,6811,6810,6809,6808,6807,6806,6805,6804,6803,6802,6801,6800,6799,6798,6797,6796,6795,6794,6793,6792,6791,6790,6789,6788,6787,6786,6785,6784,6783,6782,6781,6780,6779,6778,6777,6776,6775,6774,6773,6772,6771,6770,6769,6768,6767,6766,6765,6764,6763,6762,6761,6760,6759,6758,6757,6756,6755,6754,6753,6752,6751,6750,6749,6748,6747,6746,6745,6744,6743,6742,6741,6740,6739,6738,6737,6736,6735,6734,6733,6732,6731,6730,6729,6728,6727,6726,6725,6724,6723,6722,6721,6720,6719,6718,6717,6716,6715,6714,6713,6712,6711,6710,6709,6708,6707,6706,6705,6704,6703,6702,6701,6700,6699,6698,6697,6696,6695,6694,6693,6692,6691,6690,6689,6688,6687,6686,6685,6684,6683,6682,6681,6680,6679,6678,6677,6676,6675,6674,6673,6672,6671,6670,6669,6668,6667,6666,6665,6664,6663,6662,6661,6660,6659,6658,6657,6656,6655,6654,6653,6652,6651,6650,6649,6648,6647,6646,6645,6644,6643,6642,6641,6640,6639,6638,6637,6636,6635,6634,6633,6632,6631,6630,6629,6628,6627,6626,6625,6624,6623,6622,6621,6620,6619,6618,6617,6616,6615,6614,6613,6612,6611,6610,6609,6608,6607,6606,6605,6604,6603,6602,6601,6600,6599,6598,6597,6596,6595,6594,6593,6592,6591,6590,6589,6588,6587,6586,6585,6584,6583,6582,6581,6580,6579,6578,6577,6576,6575,6574,6573,6572,6571,6570,6569,6568,6567,6566,6565,6564,6563,6562,6561,6560,6559,6558,6557,6556,6555,6554,6553,6552,6551,6550,6549,6548,6547,6546,6545,6544,6543,6542,6541,6540,6539,6538,6537,6536,6535,6534,6533,6532,6531,6530,6529,6528,6527,6526,6525,6524,6523,6522,6521,6520,6519,6518,6517,6516,6515,6514,6513,6512,6511,6510,6509,6508,6507,6506,6505,6504,6503,6502,6501,6500,6499,6498,6497,6496,6495,6494,6493,6492,6491,6490,6489,6488,6487,6486,6485,6484,6483,6482,6481,6480,6479,6478,6477,6476,6475,6474,6473,6472,6471,6470,6469,6468,6467,6466,6465,6464,6463,6462,6461,6460,6459,6458,6457,6456,6455,6454,6453,6452,6451,6450,6449,6448,6447,6446,6445,6444,6443,6442,6441,6440,6439,6438,6437,6436,6435,6434,6433,6432,6431,6430,6429,6428,6427,6426,6425,6424,6423,6422,6421,6420,6419,6418,6417,6416,6415,6414,6413,6412,6411,6410,6409,6408,6407,6406,6405,6404,6403,6402,6401,6400,6399,6398,6397,6396,6395,6394,6393,6392,6391,6390,6389,6388,6387,6386,6385,6384,6383,6382,6381,6380,6379,6378,6377,6376,6375,6374,6373,6372,6371,6370,6369,6368,6367,6366,6365,6364,6363,6362,6361,6360,6359,6358,6357,6356,6355,6354,6353,6352,6351,6350,6349,6348,6347,6346,6345,6344,6343,6342,6341,6340,6339,6338,6337,6336,6335,6334,6333,6332,6331,6330,6329,6328,6327,6326,6325,6324,6323,6322,6321,6320,6319,6318,6317,6316,6315,6314,6313,6312,6311,6310,6309,6308,6307,6306,6305,6304,6303,6302,6301,6300,6299,6298,6297,6296,6295,6294,6293,6292,6291,6290,6289,6288,6287,6286,6285,6284,6283,6282,6281,6280,6279,6278,6277,6276,6275,6274,6273,6272,6271,6270,6269,6268,6267,6266,6265,6264,6263,6262,6261,6260,6259,6258,6257,6256,6255,6254,6253,6252,6251,6250,6249,6248,6247,6246,6245,6244,6243,6242,6241,6240,6239,6238,6237,6236,6235,6234,6233,6232,6231,6230,6229,6228,6227,6226,6225,6224,6223,6222,6221,6220,6219,6218,6217,6216,6215,6214,6213,6212,6211,6210,6209,6208,6207,6206,6205,6204,6203,6202,6201,6200,6199,6198,6197,6196,6195,6194,6193,6192,6191,6190,6189,6188,6187,6186,6185,6184,6183,6182,6181,6180,6179,6178,6177,6176,6175,6174,6173,6172,6171,6170,6169,6168,6167,6166,6165,6164,6163,6162,6161,6160,6159,6158,6157,6156,6155,6154,6153,6152,6151,6150,6149,6148,6147,6146,6145,6144,6143,6142,6141,6140,6139,6138,6137,6136,6135,6134,6133,6132,6131,6130,6129,6128,6127,6126,6125,6124,6123,6122,6121,6120,6119,6118,6117,6116,6115,6114,6113,6112,6111,6110,6109,6108,6107,6106,6105,6104,6103,6102,6101,6100,6099,6098,6097,6096,6095,6094,6093,6092,6091,6090,6089,6088,6087,6086,6085,6084,6083,6082,6081,6080,6079,6078,6077,6076,6075,6074,6073,6072,6071,6070,6069,6068,6067,6066,6065,6064,6063,6062,6061,6060,6059,6058,6057,6056,6055,6054,6053,6052,6051,6050,6049,6048,6047,6046,6045,6044,6043,6042,6041,6040,6039,6038,6037,6036,6035,6034,6033,6032,6031,6030,6029,6028,6027,6026,6025,6024,6023,6022,6021,6020,6019,6018,6017,6016,6015,6014,6013,6012,6011,6010,6009,6008,6007,6006,6005,6004,6003,6002,6001,6000,5999,5998,5997,5996,5995,5994,5993,5992,5991,5990,5989,5988,5987,5986,5985,5984,5983,5982,5981,5980,5979,5978,5977,5976,5975,5974,5973,5972,5971,5970,5969,5968,5967,5966,5965,5964,5963,5962,5961,5960,5959,5958,5957,5956,5955,5954,5953,5952,5951,5950,5949,5948,5947,5946,5945,5944,5943,5942,5941,5940,5939,5938,5937,5936,5935,5934,5933,5932,5931,5930,5929,5928,5927,5926,5925,5924,5923,5922,5921,5920,5919,5918,5917,5916,5915,5914,5913,5912,5911,5910,5909,5908,5907,5906,5905,5904,5903,5902,5901,5900,5899,5898,5897,5896,5895,5894,5893,5892,5891,5890,5889,5888,5887,5886,5885,5884,5883,5882,5881,5880,5879,5878,5877,5876,5875,5874,5873,5872,5871,5870,5869,5868,5867,5866,5865,5864,5863,5862,5861,5860,5859,5858,5857,5856,5855,5854,5853,5852,5851,5850,5849,5848,5847,5846,5845,5844,5843,5842,5841,5840,5839,5838,5837,5836,5835,5834,5833,5832,5831,5830,5829,5828,5827,5826,5825,5824,5823,5822,5821,5820,5819,5818,5817,5816,5815,5814,5813,5812,5811,5810,5809,5808,5807,5806,5805,5804,5803,5802,5801,5800,5799,5798,5797,5796,5795,5794,5793,5792,5791,5790,5789,5788,5787,5786,5785,5784,5783,5782,5781,5780,5779,5778,5777,5776,5775,5774,5773,5772,5771,5770,5769,5768,5767,5766,5765,5764,5763,5762,5761,5760,5759,5758,5757,5756,5755,5754,5753,5752,5751,5750,5749,5748,5747,5746,5745,5744,5743,5742,5741,5740,5739,5738,5737,5736,5735,5734,5733,5732,5731,5730,5729,5728,5727,5726,5725,5724,5723,5722,5721,5720,5719,5718,5717,5716,5715,5714,5713,5712,5711,5710,5709,5708,5707,5706,5705,5704,5703,5702,5701,5700,5699,5698,5697,5696,5695,5694,5693,5692,5691,5690,5689,5688,5687,5686,5685,5684,5683,5682,5681,5680,5679,5678,5677,5676,5675,5674,5673,5672,5671,5670,5669,5668,5667,5666,5665,5664,5663,5662,5661,5660,5659,5658,5657,5656,5655,5654,5653,5652,5651,5650,5649,5648,5647,5646,5645,5644,5643,5642,5641,5640,5639,5638,5637,5636,5635,5634,5633,5632,5631,5630,5629,5628,5627,5626,5625,5624,5623,5622,5621,5620,5619,5618,5617,5616,5615,5614,5613,5612,5611,5610,5609,5608,5607,5606,5605,5604,5603,5602,5601,5600,5599,5598,5597,5596,5595,5594,5593,5592,5591,5590,5589,5588,5587,5586,5585,5584,5583,5582,5581,5580,5579,5578,5577,5576,5575,5574,5573,5572,5571,5570,5569,5568,5567,5566,5565,5564,5563,5562,5561,5560,5559,5558,5557,5556,5555,5554,5553,5552,5551,5550,5549,5548,5547,5546,5545,5544,5543,5542,5541,5540,5539,5538,5537,5536,5535,5534,5533,5532,5531,5530,5529,5528,5527,5526,5525,5524,5523,5522,5521,5520,5519,5518,5517,5516,5515,5514,5513,5512,5511,5510,5509,5508,5507,5506,5505,5504,5503,5502,5501,5500,5499,5498,5497,5496,5495,5494,5493,5492,5491,5490,5489,5488,5487,5486,5485,5484,5483,5482,5481,5480,5479,5478,5477,5476,5475,5474,5473,5472,5471,5470,5469,5468,5467,5466,5465,5464,5463,5462,5461,5460,5459,5458,5457,5456,5455,5454,5453,5452,5451,5450,5449,5448,5447,5446,5445,5444,5443,5442,5441,5440,5439,5438,5437,5436,5435,5434,5433,5432,5431,5430,5429,5428,5427,5426,5425,5424,5423,5422,5421,5420,5419,5418,5417,5416,5415,5414,5413,5412,5411,5410,5409,5408,5407,5406,5405,5404,5403,5402,5401,5400,5399,5398,5397,5396,5395,5394,5393,5392,5391,5390,5389,5388,5387,5386,5385,5384,5383,5382,5381,5380,5379,5378,5377,5376,5375,5374,5373,5372,5371,5370,5369,5368,5367,5366,5365,5364,5363,5362,5361,5360,5359,5358,5357,5356,5355,5354,5353,5352,5351,5350,5349,5348,5347,5346,5345,5344,5343,5342,5341,5340,5339,5338,5337,5336,5335,5334,5333,5332,5331,5330,5329,5328,5327,5326,5325,5324,5323,5322,5321,5320,5319,5318,5317,5316,5315,5314,5313,5312,5311,5310,5309,5308,5307,5306,5305,5304,5303,5302,5301,5300,5299,5298,5297,5296,5295,5294,5293,5292,5291,5290,5289,5288,5287,5286,5285,5284,5283,5282,5281,5280,5279,5278,5277,5276,5275,5274,5273,5272,5271,5270,5269,5268,5267,5266,5265,5264,5263,5262,5261,5260,5259,5258,5257,5256,5255,5254,5253,5252,5251,5250,5249,5248,5247,5246,5245,5244,5243,5242,5241,5240,5239,5238,5237,5236,5235,5234,5233,5232,5231,5230,5229,5228,5227,5226,5225,5224,5223,5222,5221,5220,5219,5218,5217,5216,5215,5214,5213,5212,5211,5210,5209,5208,5207,5206,5205,5204,5203,5202,5201,5200,5199,5198,5197,5196,5195,5194,5193,5192,5191,5190,5189,5188,5187,5186,5185,5184,5183,5182,5181,5180,5179,5178,5177,5176,5175,5174,5173,5172,5171,5170,5169,5168,5167,5166,5165,5164,5163,5162,5161,5160,5159,5158,5157,5156,5155,5154,5153,5152,5151,5150,5149,5148,5147,5146,5145,5144,5143,5142,5141,5140,5139,5138,5137,5136,5135,5134,5133,5132,5131,5130,5129,5128,5127,5126,5125,5124,5123,5122,5121,5120,5119,5118,5117,5116,5115,5114,5113,5112,5111,5110,5109,5108,5107,5106,5105,5104,5103,5102,5101,5100,5099,5098,5097,5096,5095,5094,5093,5092,5091,5090,5089,5088,5087,5086,5085,5084,5083,5082,5081,5080,5079,5078,5077,5076,5075,5074,5073,5072,5071,5070,5069,5068,5067,5066,5065,5064,5063,5062,5061,5060,5059,5058,5057,5056,5055,5054,5053,5052,5051,5050,5049,5048,5047,5046,5045,5044,5043,5042,5041,5040,5039,5038,5037,5036,5035,5034,5033,5032,5031,5030,5029,5028,5027,5026,5025,5024,5023,5022,5021,5020,5019,5018,5017,5016,5015,5014,5013,5012,5011,5010,5009,5008,5007,5006,5005,5004,5003,5002,5001,5000,4999,4998,4997,4996,4995,4994,4993,4992,4991,4990,4989,4988,4987,4986,4985,4984,4983,4982,4981,4980,4979,4978,4977,4976,4975,4974,4973,4972,4971,4970,4969,4968,4967,4966,4965,4964,4963,4962,4961,4960,4959,4958,4957,4956,4955,4954,4953,4952,4951,4950,4949,4948,4947,4946,4945,4944,4943,4942,4941,4940,4939,4938,4937,4936,4935,4934,4933,4932,4931,4930,4929,4928,4927,4926,4925,4924,4923,4922,4921,4920,4919,4918,4917,4916,4915,4914,4913,4912,4911,4910,4909,4908,4907,4906,4905,4904,4903,4902,4901,4900,4899,4898,4897,4896,4895,4894,4893,4892,4891,4890,4889,4888,4887,4886,4885,4884,4883,4882,4881,4880,4879,4878,4877,4876,4875,4874,4873,4872,4871,4870,4869,4868,4867,4866,4865,4864,4863,4862,4861,4860,4859,4858,4857,4856,4855,4854,4853,4852,4851,4850,4849,4848,4847,4846,4845,4844,4843,4842,4841,4840,4839,4838,4837,4836,4835,4834,4833,4832,4831,4830,4829,4828,4827,4826,4825,4824,4823,4822,4821,4820,4819,4818,4817,4816,4815,4814,4813,4812,4811,4810,4809,4808,4807,4806,4805,4804,4803,4802,4801,4800,4799,4798,4797,4796,4795,4794,4793,4792,4791,4790,4789,4788,4787,4786,4785,4784,4783,4782,4781,4780,4779,4778,4777,4776,4775,4774,4773,4772,4771,4770,4769,4768,4767,4766,4765,4764,4763,4762,4761,4760,4759,4758,4757,4756,4755,4754,4753,4752,4751,4750,4749,4748,4747,4746,4745,4744,4743,4742,4741,4740,4739,4738,4737,4736,4735,4734,4733,4732,4731,4730,4729,4728,4727,4726,4725,4724,4723,4722,4721,4720,4719,4718,4717,4716,4715,4714,4713,4712,4711,4710,4709,4708,4707,4706,4705,4704,4703,4702,4701,4700,4699,4698,4697,4696,4695,4694,4693,4692,4691,4690,4689,4688,4687,4686,4685,4684,4683,4682,4681,4680,4679,4678,4677,4676,4675,4674,4673,4672,4671,4670,4669,4668,4667,4666,4665,4664,4663,4662,4661,4660,4659,4658,4657,4656,4655,4654,4653,4652,4651,4650,4649,4648,4647,4646,4645,4644,4643,4642,4641,4640,4639,4638,4637,4636,4635,4634,4633,4632,4631,4630,4629,4628,4627,4626,4625,4624,4623,4622,4621,4620,4619,4618,4617,4616,4615,4614,4613,4612,4611,4610,4609,4608,4607,4606,4605,4604,4603,4602,4601,4600,4599,4598,4597,4596,4595,4594,4593,4592,4591,4590,4589,4588,4587,4586,4585,4584,4583,4582,4581,4580,4579,4578,4577,4576,4575,4574,4573,4572,4571,4570,4569,4568,4567,4566,4565,4564,4563,4562,4561,4560,4559,4558,4557,4556,4555,4554,4553,4552,4551,4550,4549,4548,4547,4546,4545,4544,4543,4542,4541,4540,4539,4538,4537,4536,4535,4534,4533,4532,4531,4530,4529,4528,4527,4526,4525,4524,4523,4522,4521,4520,4519,4518,4517,4516,4515,4514,4513,4512,4511,4510,4509,4508,4507,4506,4505,4504,4503,4502,4501,4500,4499,4498,4497,4496,4495,4494,4493,4492,4491,4490,4489,4488,4487,4486,4485,4484,4483,4482,4481,4480,4479,4478,4477,4476,4475,4474,4473,4472,4471,4470,4469,4468,4467,4466,4465,4464,4463,4462,4461,4460,4459,4458,4457,4456,4455,4454,4453,4452,4451,4450,4449,4448,4447,4446,4445,4444,4443,4442,4441,4440,4439,4438,4437,4436,4435,4434,4433,4432,4431,4430,4429,4428,4427,4426,4425,4424,4423,4422,4421,4420,4419,4418,4417,4416,4415,4414,4413,4412,4411,4410,4409,4408,4407,4406,4405,4404,4403,4402,4401,4400,4399,4398,4397,4396,4395,4394,4393,4392,4391,4390,4389,4388,4387,4386,4385,4384,4383,4382,4381,4380,4379,4378,4377,4376,4375,4374,4373,4372,4371,4370,4369,4368,4367,4366,4365,4364,4363,4362,4361,4360,4359,4358,4357,4356,4355,4354,4353,4352,4351,4350,4349,4348,4347,4346,4345,4344,4343,4342,4341,4340,4339,4338,4337,4336,4335,4334,4333,4332,4331,4330,4329,4328,4327,4326,4325,4324,4323,4322,4321,4320,4319,4318,4317,4316,4315,4314,4313,4312,4311,4310,4309,4308,4307,4306,4305,4304,4303,4302,4301,4300,4299,4298,4297,4296,4295,4294,4293,4292,4291,4290,4289,4288,4287,4286,4285,4284,4283,4282,4281,4280,4279,4278,4277,4276,4275,4274,4273,4272,4271,4270,4269,4268,4267,4266,4265,4264,4263,4262,4261,4260,4259,4258,4257,4256,4255,4254,4253,4252,4251,4250,4249,4248,4247,4246,4245,4244,4243,4242,4241,4240,4239,4238,4237,4236,4235,4234,4233,4232,4231,4230,4229,4228,4227,4226,4225,4224,4223,4222,4221,4220,4219,4218,4217,4216,4215,4214,4213,4212,4211,4210,4209,4208,4207,4206,4205,4204,4203,4202,4201,4200,4199,4198,4197,4196,4195,4194,4193,4192,4191,4190,4189,4188,4187,4186,4185,4184,4183,4182,4181,4180,4179,4178,4177,4176,4175,4174,4173,4172,4171,4170,4169,4168,4167,4166,4165,4164,4163,4162,4161,4160,4159,4158,4157,4156,4155,4154,4153,4152,4151,4150,4149,4148,4147,4146,4145,4144,4143,4142,4141,4140,4139,4138,4137,4136,4135,4134,4133,4132,4131,4130,4129,4128,4127,4126,4125,4124,4123,4122,4121,4120,4119,4118,4117,4116,4115,4114,4113,4112,4111,4110,4109,4108,4107,4106,4105,4104,4103,4102,4101,4100,4099,4098,4097,4096,4095,4094,4093,4092,4091,4090,4089,4088,4087,4086,4085,4084,4083,4082,4081,4080,4079,4078,4077,4076,4075,4074,4073,4072,4071,4070,4069,4068,4067,4066,4065,4064,4063,4062,4061,4060,4059,4058,4057,4056,4055,4054,4053,4052,4051,4050,4049,4048,4047,4046,4045,4044,4043,4042,4041,4040,4039,4038,4037,4036,4035,4034,4033,4032,4031,4030,4029,4028,4027,4026,4025,4024,4023,4022,4021,4020,4019,4018,4017,4016,4015,4014,4013,4012,4011,4010,4009,4008,4007,4006,4005,4004,4003,4002,4001,4000,3999,3998,3997,3996,3995,3994,3993,3992,3991,3990,3989,3988,3987,3986,3985,3984,3983,3982,3981,3980,3979,3978,3977,3976,3975,3974,3973,3972,3971,3970,3969,3968,3967,3966,3965,3964,3963,3962,3961,3960,3959,3958,3957,3956,3955,3954,3953,3952,3951,3950,3949,3948,3947,3946,3945,3944,3943,3942,3941,3940,3939,3938,3937,3936,3935,3934,3933,3932,3931,3930,3929,3928,3927,3926,3925,3924,3923,3922,3921,3920,3919,3918,3917,3916,3915,3914,3913,3912,3911,3910,3909,3908,3907,3906,3905,3904,3903,3902,3901,3900,3899,3898,3897,3896,3895,3894,3893,3892,3891,3890,3889,3888,3887,3886,3885,3884,3883,3882,3881,3880,3879,3878,3877,3876,3875,3874,3873,3872,3871,3870,3869,3868,3867,3866,3865,3864,3863,3862,3861,3860,3859,3858,3857,3856,3855,3854,3853,3852,3851,3850,3849,3848,3847,3846,3845,3844,3843,3842,3841,3840,3839,3838,3837,3836,3835,3834,3833,3832,3831,3830,3829,3828,3827,3826,3825,3824,3823,3822,3821,3820,3819,3818,3817,3816,3815,3814,3813,3812,3811,3810,3809,3808,3807,3806,3805,3804,3803,3802,3801,3800,3799,3798,3797,3796,3795,3794,3793,3792,3791,3790,3789,3788,3787,3786,3785,3784,3783,3782,3781,3780,3779,3778,3777,3776,3775,3774,3773,3772,3771,3770,3769,3768,3767,3766,3765,3764,3763,3762,3761,3760,3759,3758,3757,3756,3755,3754,3753,3752,3751,3750,3749,3748,3747,3746,3745,3744,3743,3742,3741,3740,3739,3738,3737,3736,3735,3734,3733,3732,3731,3730,3729,3728,3727,3726,3725,3724,3723,3722,3721,3720,3719,3718,3717,3716,3715,3714,3713,3712,3711,3710,3709,3708,3707,3706,3705,3704,3703,3702,3701,3700,3699,3698,3697,3696,3695,3694,3693,3692,3691,3690,3689,3688,3687,3686,3685,3684,3683,3682,3681,3680,3679,3678,3677,3676,3675,3674,3673,3672,3671,3670,3669,3668,3667,3666,3665,3664,3663,3662,3661,3660,3659,3658,3657,3656,3655,3654,3653,3652,3651,3650,3649,3648,3647,3646,3645,3644,3643,3642,3641,3640,3639,3638,3637,3636,3635,3634,3633,3632,3631,3630,3629,3628,3627,3626,3625,3624,3623,3622,3621,3620,3619,3618,3617,3616,3615,3614,3613,3612,3611,3610,3609,3608,3607,3606,3605,3604,3603,3602,3601,3600,3599,3598,3597,3596,3595,3594,3593,3592,3591,3590,3589,3588,3587,3586,3585,3584,3583,3582,3581,3580,3579,3578,3577,3576,3575,3574,3573,3572,3571,3570,3569,3568,3567,3566,3565,3564,3563,3562,3561,3560,3559,3558,3557,3556,3555,3554,3553,3552,3551,3550,3549,3548,3547,3546,3545,3544,3543,3542,3541,3540,3539,3538,3537,3536,3535,3534,3533,3532,3531,3530,3529,3528,3527,3526,3525,3524,3523,3522,3521,3520,3519,3518,3517,3516,3515,3514,3513,3512,3511,3510,3509,3508,3507,3506,3505,3504,3503,3502,3501,3500,3499,3498,3497,3496,3495,3494,3493,3492,3491,3490,3489,3488,3487,3486,3485,3484,3483,3482,3481,3480,3479,3478,3477,3476,3475,3474,3473,3472,3471,3470,3469,3468,3467,3466,3465,3464,3463,3462,3461,3460,3459,3458,3457,3456,3455,3454,3453,3452,3451,3450,3449,3448,3447,3446,3445,3444,3443,3442,3441,3440,3439,3438,3437,3436,3435,3434,3433,3432,3431,3430,3429,3428,3427,3426,3425,3424,3423,3422,3421,3420,3419,3418,3417,3416,3415,3414,3413,3412,3411,3410,3409,3408,3407,3406,3405,3404,3403,3402,3401,3400,3399,3398,3397,3396,3395,3394,3393,3392,3391,3390,3389,3388,3387,3386,3385,3384,3383,3382,3381,3380,3379,3378,3377,3376,3375,3374,3373,3372,3371,3370,3369,3368,3367,3366,3365,3364,3363,3362,3361,3360,3359,3358,3357,3356,3355,3354,3353,3352,3351,3350,3349,3348,3347,3346,3345,3344,3343,3342,3341,3340,3339,3338,3337,3336,3335,3334,3333,3332,3331,3330,3329,3328,3327,3326,3325,3324,3323,3322,3321,3320,3319,3318,3317,3316,3315,3314,3313,3312,3311,3310,3309,3308,3307,3306,3305,3304,3303,3302,3301,3300,3299,3298,3297,3296,3295,3294,3293,3292,3291,3290,3289,3288,3287,3286,3285,3284,3283,3282,3281,3280,3279,3278,3277,3276,3275,3274,3273,3272,3271,3270,3269,3268,3267,3266,3265,3264,3263,3262,3261,3260,3259,3258,3257,3256,3255,3254,3253,3252,3251,3250,3249,3248,3247,3246,3245,3244,3243,3242,3241,3240,3239,3238,3237,3236,3235,3234,3233,3232,3231,3230,3229,3228,3227,3226,3225,3224,3223,3222,3221,3220,3219,3218,3217,3216,3215,3214,3213,3212,3211,3210,3209,3208,3207,3206,3205,3204,3203,3202,3201,3200,3199,3198,3197,3196,3195,3194,3193,3192,3191,3190,3189,3188,3187,3186,3185,3184,3183,3182,3181,3180,3179,3178,3177,3176,3175,3174,3173,3172,3171,3170,3169,3168,3167,3166,3165,3164,3163,3162,3161,3160,3159,3158,3157,3156,3155,3154,3153,3152,3151,3150,3149,3148,3147,3146,3145,3144,3143,3142,3141,3140,3139,3138,3137,3136,3135,3134,3133,3132,3131,3130,3129,3128,3127,3126,3125,3124,3123,3122,3121,3120,3119,3118,3117,3116,3115,3114,3113,3112,3111,3110,3109,3108,3107,3106,3105,3104,3103,3102,3101,3100,3099,3098,3097,3096,3095,3094,3093,3092,3091,3090,3089,3088,3087,3086,3085,3084,3083,3082,3081,3080,3079,3078,3077,3076,3075,3074,3073,3072,3071,3070,3069,3068,3067,3066,3065,3064,3063,3062,3061,3060,3059,3058,3057,3056,3055,3054,3053,3052,3051,3050,3049,3048,3047,3046,3045,3044,3043,3042,3041,3040,3039,3038,3037,3036,3035,3034,3033,3032,3031,3030,3029,3028,3027,3026,3025,3024,3023,3022,3021,3020,3019,3018,3017,3016,3015,3014,3013,3012,3011,3010,3009,3008,3007,3006,3005,3004,3003,3002,3001,3000,2999,2998,2997,2996,2995,2994,2993,2992,2991,2990,2989,2988,2987,2986,2985,2984,2983,2982,2981,2980,2979,2978,2977,2976,2975,2974,2973,2972,2971,2970,2969,2968,2967,2966,2965,2964,2963,2962,2961,2960,2959,2958,2957,2956,2955,2954,2953,2952,2951,2950,2949,2948,2947,2946,2945,2944,2943,2942,2941,2940,2939,2938,2937,2936,2935,2934,2933,2932,2931,2930,2929,2928,2927,2926,2925,2924,2923,2922,2921,2920,2919,2918,2917,2916,2915,2914,2913,2912,2911,2910,2909,2908,2907,2906,2905,2904,2903,2902,2901,2900,2899,2898,2897,2896,2895,2894,2893,2892,2891,2890,2889,2888,2887,2886,2885,2884,2883,2882,2881,2880,2879,2878,2877,2876,2875,2874,2873,2872,2871,2870,2869,2868,2867,2866,2865,2864,2863,2862,2861,2860,2859,2858,2857,2856,2855,2854,2853,2852,2851,2850,2849,2848,2847,2846,2845,2844,2843,2842,2841,2840,2839,2838,2837,2836,2835,2834,2833,2832,2831,2830,2829,2828,2827,2826,2825,2824,2823,2822,2821,2820,2819,2818,2817,2816,2815,2814,2813,2812,2811,2810,2809,2808,2807,2806,2805,2804,2803,2802,2801,2800,2799,2798,2797,2796,2795,2794,2793,2792,2791,2790,2789,2788,2787,2786,2785,2784,2783,2782,2781,2780,2779,2778,2777,2776,2775,2774,2773,2772,2771,2770,2769,2768,2767,2766,2765,2764,2763,2762,2761,2760,2759,2758,2757,2756,2755,2754,2753,2752,2751,2750,2749,2748,2747,2746,2745,2744,2743,2742,2741,2740,2739,2738,2737,2736,2735,2734,2733,2732,2731,2730,2729,2728,2727,2726,2725,2724,2723,2722,2721,2720,2719,2718,2717,2716,2715,2714,2713,2712,2711,2710,2709,2708,2707,2706,2705,2704,2703,2702,2701,2700,2699,2698,2697,2696,2695,2694,2693,2692,2691,2690,2689,2688,2687,2686,2685,2684,2683,2682,2681,2680,2679,2678,2677,2676,2675,2674,2673,2672,2671,2670,2669,2668,2667,2666,2665,2664,2663,2662,2661,2660,2659,2658,2657,2656,2655,2654,2653,2652,2651,2650,2649,2648,2647,2646,2645,2644,2643,2642,2641,2640,2639,2638,2637,2636,2635,2634,2633,2632,2631,2630,2629,2628,2627,2626,2625,2624,2623,2622,2621,2620,2619,2618,2617,2616,2615,2614,2613,2612,2611,2610,2609,2608,2607,2606,2605,2604,2603,2602,2601,2600,2599,2598,2597,2596,2595,2594,2593,2592,2591,2590,2589,2588,2587,2586,2585,2584,2583,2582,2581,2580,2579,2578,2577,2576,2575,2574,2573,2572,2571,2570,2569,2568,2567,2566,2565,2564,2563,2562,2561,2560,2559,2558,2557,2556,2555,2554,2553,2552,2551,2550,2549,2548,2547,2546,2545,2544,2543,2542,2541,2540,2539,2538,2537,2536,2535,2534,2533,2532,2531,2530,2529,2528,2527,2526,2525,2524,2523,2522,2521,2520,2519,2518,2517,2516,2515,2514,2513,2512,2511,2510,2509,2508,2507,2506,2505,2504,2503,2502,2501,2500,2499,2498,2497,2496,2495,2494,2493,2492,2491,2490,2489,2488,2487,2486,2485,2484,2483,2482,2481,2480,2479,2478,2477,2476,2475,2474,2473,2472,2471,2470,2469,2468,2467,2466,2465,2464,2463,2462,2461,2460,2459,2458,2457,2456,2455,2454,2453,2452,2451,2450,2449,2448,2447,2446,2445,2444,2443,2442,2441,2440,2439,2438,2437,2436,2435,2434,2433,2432,2431,2430,2429,2428,2427,2426,2425,2424,2423,2422,2421,2420,2419,2418,2417,2416,2415,2414,2413,2412,2411,2410,2409,2408,2407,2406,2405,2404,2403,2402,2401,2400,2399,2398,2397,2396,2395,2394,2393,2392,2391,2390,2389,2388,2387,2386,2385,2384,2383,2382,2381,2380,2379,2378,2377,2376,2375,2374,2373,2372,2371,2370,2369,2368,2367,2366,2365,2364,2363,2362,2361,2360,2359,2358,2357,2356,2355,2354,2353,2352,2351,2350,2349,2348,2347,2346,2345,2344,2343,2342,2341,2340,2339,2338,2337,2336,2335,2334,2333,2332,2331,2330,2329,2328,2327,2326,2325,2324,2323,2322,2321,2320,2319,2318,2317,2316,2315,2314,2313,2312,2311,2310,2309,2308,2307,2306,2305,2304,2303,2302,2301,2300,2299,2298,2297,2296,2295,2294,2293,2292,2291,2290,2289,2288,2287,2286,2285,2284,2283,2282,2281,2280,2279,2278,2277,2276,2275,2274,2273,2272,2271,2270,2269,2268,2267,2266,2265,2264,2263,2262,2261,2260,2259,2258,2257,2256,2255,2254,2253,2252,2251,2250,2249,2248,2247,2246,2245,2244,2243,2242,2241,2240,2239,2238,2237,2236,2235,2234,2233,2232,2231,2230,2229,2228,2227,2226,2225,2224,2223,2222,2221,2220,2219,2218,2217,2216,2215,2214,2213,2212,2211,2210,2209,2208,2207,2206,2205,2204,2203,2202,2201,2200,2199,2198,2197,2196,2195,2194,2193,2192,2191,2190,2189,2188,2187,2186,2185,2184,2183,2182,2181,2180,2179,2178,2177,2176,2175,2174,2173,2172,2171,2170,2169,2168,2167,2166,2165,2164,2163,2162,2161,2160,2159,2158,2157,2156,2155,2154,2153,2152,2151,2150,2149,2148,2147,2146,2145,2144,2143,2142,2141,2140,2139,2138,2137,2136,2135,2134,2133,2132,2131,2130,2129,2128,2127,2126,2125,2124,2123,2122,2121,2120,2119,2118,2117,2116,2115,2114,2113,2112,2111,2110,2109,2108,2107,2106,2105,2104,2103,2102,2101,2100,2099,2098,2097,2096,2095,2094,2093,2092,2091,2090,2089,2088,2087,2086,2085,2084,2083,2082,2081,2080,2079,2078,2077,2076,2075,2074,2073,2072,2071,2070,2069,2068,2067,2066,2065,2064,2063,2062,2061,2060,2059,2058,2057,2056,2055,2054,2053,2052,2051,2050,2049,2048,2047,2046,2045,2044,2043,2042,2041,2040,2039,2038,2037,2036,2035,2034,2033,2032,2031,2030,2029,2028,2027,2026,2025,2024,2023,2022,2021,2020,2019,2018,2017,2016,2015,2014,2013,2012,2011,2010,2009,2008,2007,2006,2005,2004,2003,2002,2001,2000,1999,1998,1997,1996,1995,1994,1993,1992,1991,1990,1989,1988,1987,1986,1985,1984,1983,1982,1981,1980,1979,1978,1977,1976,1975,1974,1973,1972,1971,1970,1969,1968,1967,1966,1965,1964,1963,1962,1961,1960,1959,1958,1957,1956,1955,1954,1953,1952,1951,1950,1949,1948,1947,1946,1945,1944,1943,1942,1941,1940,1939,1938,1937,1936,1935,1934,1933,1932,1931,1930,1929,1928,1927,1926,1925,1924,1923,1922,1921,1920,1919,1918,1917,1916,1915,1914,1913,1912,1911,1910,1909,1908,1907,1906,1905,1904,1903,1902,1901,1900,1899,1898,1897,1896,1895,1894,1893,1892,1891,1890,1889,1888,1887,1886,1885,1884,1883,1882,1881,1880,1879,1878,1877,1876,1875,1874,1873,1872,1871,1870,1869,1868,1867,1866,1865,1864,1863,1862,1861,1860,1859,1858,1857,1856,1855,1854,1853,1852,1851,1850,1849,1848,1847,1846,1845,1844,1843,1842,1841,1840,1839,1838,1837,1836,1835,1834,1833,1832,1831,1830,1829,1828,1827,1826,1825,1824,1823,1822,1821,1820,1819,1818,1817,1816,1815,1814,1813,1812,1811,1810,1809,1808,1807,1806,1805,1804,1803,1802,1801,1800,1799,1798,1797,1796,1795,1794,1793,1792,1791,1790,1789,1788,1787,1786,1785,1784,1783,1782,1781,1780,1779,1778,1777,1776,1775,1774,1773,1772,1771,1770,1769,1768,1767,1766,1765,1764,1763,1762,1761,1760,1759,1758,1757,1756,1755,1754,1753,1752,1751,1750,1749,1748,1747,1746,1745,1744,1743,1742,1741,1740,1739,1738,1737,1736,1735,1734,1733,1732,1731,1730,1729,1728,1727,1726,1725,1724,1723,1722,1721,1720,1719,1718,1717,1716,1715,1714,1713,1712,1711,1710,1709,1708,1707,1706,1705,1704,1703,1702,1701,1700,1699,1698,1697,1696,1695,1694,1693,1692,1691,1690,1689,1688,1687,1686,1685,1684,1683,1682,1681,1680,1679,1678,1677,1676,1675,1674,1673,1672,1671,1670,1669,1668,1667,1666,1665,1664,1663,1662,1661,1660,1659,1658,1657,1656,1655,1654,1653,1652,1651,1650,1649,1648,1647,1646,1645,1644,1643,1642,1641,1640,1639,1638,1637,1636,1635,1634,1633,1632,1631,1630,1629,1628,1627,1626,1625,1624,1623,1622,1621,1620,1619,1618,1617,1616,1615,1614,1613,1612,1611,1610,1609,1608,1607,1606,1605,1604,1603,1602,1601,1600,1599,1598,1597,1596,1595,1594,1593,1592,1591,1590,1589,1588,1587,1586,1585,1584,1583,1582,1581,1580,1579,1578,1577,1576,1575,1574,1573,1572,1571,1570,1569,1568,1567,1566,1565,1564,1563,1562,1561,1560,1559,1558,1557,1556,1555,1554,1553,1552,1551,1550,1549,1548,1547,1546,1545,1544,1543,1542,1541,1540,1539,1538,1537,1536,1535,1534,1533,1532,1531,1530,1529,1528,1527,1526,1525,1524,1523,1522,1521,1520,1519,1518,1517,1516,1515,1514,1513,1512,1511,1510,1509,1508,1507,1506,1505,1504,1503,1502,1501,1500,1499,1498,1497,1496,1495,1494,1493,1492,1491,1490,1489,1488,1487,1486,1485,1484,1483,1482,1481,1480,1479,1478,1477,1476,1475,1474,1473,1472,1471,1470,1469,1468,1467,1466,1465,1464,1463,1462,1461,1460,1459,1458,1457,1456,1455,1454,1453,1452,1451,1450,1449,1448,1447,1446,1445,1444,1443,1442,1441,1440,1439,1438,1437,1436,1435,1434,1433,1432,1431,1430,1429,1428,1427,1426,1425,1424,1423,1422,1421,1420,1419,1418,1417,1416,1415,1414,1413,1412,1411,1410,1409,1408,1407,1406,1405,1404,1403,1402,1401,1400,1399,1398,1397,1396,1395,1394,1393,1392,1391,1390,1389,1388,1387,1386,1385,1384,1383,1382,1381,1380,1379,1378,1377,1376,1375,1374,1373,1372,1371,1370,1369,1368,1367,1366,1365,1364,1363,1362,1361,1360,1359,1358,1357,1356,1355,1354,1353,1352,1351,1350,1349,1348,1347,1346,1345,1344,1343,1342,1341,1340,1339,1338,1337,1336,1335,1334,1333,1332,1331,1330,1329,1328,1327,1326,1325,1324,1323,1322,1321,1320,1319,1318,1317,1316,1315,1314,1313,1312,1311,1310,1309,1308,1307,1306,1305,1304,1303,1302,1301,1300,1299,1298,1297,1296,1295,1294,1293,1292,1291,1290,1289,1288,1287,1286,1285,1284,1283,1282,1281,1280,1279,1278,1277,1276,1275,1274,1273,1272,1271,1270,1269,1268,1267,1266,1265,1264,1263,1262,1261,1260,1259,1258,1257,1256,1255,1254,1253,1252,1251,1250,1249,1248,1247,1246,1245,1244,1243,1242,1241,1240,1239,1238,1237,1236,1235,1234,1233,1232,1231,1230,1229,1228,1227,1226,1225,1224,1223,1222,1221,1220,1219,1218,1217,1216,1215,1214,1213,1212,1211,1210,1209,1208,1207,1206,1205,1204,1203,1202,1201,1200,1199,1198,1197,1196,1195,1194,1193,1192,1191,1190,1189,1188,1187,1186,1185,1184,1183,1182,1181,1180,1179,1178,1177,1176,1175,1174,1173,1172,1171,1170,1169,1168,1167,1166,1165,1164,1163,1162,1161,1160,1159,1158,1157,1156,1155,1154,1153,1152,1151,1150,1149,1148,1147,1146,1145,1144,1143,1142,1141,1140,1139,1138,1137,1136,1135,1134,1133,1132,1131,1130,1129,1128,1127,1126,1125,1124,1123,1122,1121,1120,1119,1118,1117,1116,1115,1114,1113,1112,1111,1110,1109,1108,1107,1106,1105,1104,1103,1102,1101,1100,1099,1098,1097,1096,1095,1094,1093,1092,1091,1090,1089,1088,1087,1086,1085,1084,1083,1082,1081,1080,1079,1078,1077,1076,1075,1074,1073,1072,1071,1070,1069,1068,1067,1066,1065,1064,1063,1062,1061,1060,1059,1058,1057,1056,1055,1054,1053,1052,1051,1050,1049,1048,1047,1046,1045,1044,1043,1042,1041,1040,1039,1038,1037,1036,1035,1034,1033,1032,1031,1030,1029,1028,1027,1026,1025,1024,1023,1022,1021,1020,1019,1018,1017,1016,1015,1014,1013,1012,1011,1010,1009,1008,1007,1006,1005,1004,1003,1002,1001,1000,999,998,997,996,995,994,993,992,991,990,989,988,987,986,985,984,983,982,981,980,979,978,977,976,975,974,973,972,971,970,969,968,967,966,965,964,963,962,961,960,959,958,957,956,955,954,953,952,951,950,949,948,947,946,945,944,943,942,941,940,939,938,937,936,935,934,933,932,931,930,929,928,927,926,925,924,923,922,921,920,919,918,917,916,915,914,913,912,911,910,909,908,907,906,905,904,903,902,901,900,899,898,897,896,895,894,893,892,891,890,889,888,887,886,885,884,883,882,881,880,879,878,877,876,875,874,873,872,871,870,869,868,867,866,865,864,863,862,861,860,859,858,857,856,855,854,853,852,851,850,849,848,847,846,845,844,843,842,841,840,839,838,837,836,835,834,833,832,831,830,829,828,827,826,825,824,823,822,821,820,819,818,817,816,815,814,813,812,811,810,809,808,807,806,805,804,803,802,801,800,799,798,797,796,795,794,793,792,791,790,789,788,787,786,785,784,783,782,781,780,779,778,777,776,775,774,773,772,771,770,769,768,767,766,765,764,763,762,761,760,759,758,757,756,755,754,753,752,751,750,749,748,747,746,745,744,743,742,741,740,739,738,737,736,735,734,733,732,731,730,729,728,727,726,725,724,723,722,721,720,719,718,717,716,715,714,713,712,711,710,709,708,707,706,705,704,703,702,701,700,699,698,697,696,695,694,693,692,691,690,689,688,687,686,685,684,683,682,681,680,679,678,677,676,675,674,673,672,671,670,669,668,667,666,665,664,663,662,661,660,659,658,657,656,655,654,653,652,651,650,649,648,647,646,645,644,643,642,641,640,639,638,637,636,635,634,633,632,631,630,629,628,627,626,625,624,623,622,621,620,619,618,617,616,615,614,613,612,611,610,609,608,607,606,605,604,603,602,601,600,599,598,597,596,595,594,593,592,591,590,589,588,587,586,585,584,583,582,581,580,579,578,577,576,575,574,573,572,571,570,569,568,567,566,565,564,563,562,561,560,559,558,557,556,555,554,553,552,551,550,549,548,547,546,545,544,543,542,541,540,539,538,537,536,535,534,533,532,531,530,529,528,527,526,525,524,523,522,521,520,519,518,517,516,515,514,513,512,511,510,509,508,507,506,505,504,503,502,501,500,499,498,497,496,495,494,493,492,491,490,489,488,487,486,485,484,483,482,481,480,479,478,477,476,475,474,473,472,471,470,469,468,467,466,465,464,463,462,461,460,459,458,457,456,455,454,453,452,451,450,449,448,447,446,445,444,443,442,441,440,439,438,437,436,435,434,433,432,431,430,429,428,427,426,425,424,423,422,421,420,419,418,417,416,415,414,413,412,411,410,409,408,407,406,405,404,403,402,401,400,399,398,397,396,395,394,393,392,391,390,389,388,387,386,385,384,383,382,381,380,379,378,377,376,375,374,373,372,371,370,369,368,367,366,365,364,363,362,361,360,359,358,357,356,355,354,353,352,351,350,349,348,347,346,345,344,343,342,341,340,339,338,337,336,335,334,333,332,331,330,329,328,327,326,325,324,323,322,321,320,319,318,317,316,315,314,313,312,311,310,309,308,307,306,305,304,303,302,301,300,299,298,297,296,295,294,293,292,291,290,289,288,287,286,285,284,283,282,281,280,279,278,277,276,275,274,273,272,271,270,269,268,267,266,265,264,263,262,261,260,259,258,257,256,255,254,253,252,251,250,249,248,247,246,245,244,243,242,241,240,239,238,237,236,235,234,233,232,231,230,229,228,227,226,225,224,223,222,221,220,219,218,217,216,215,214,213,212,211,210,209,208,207,206,205,204,203,202,201,200,199,198,197,196,195,194,193,192,191,190,189,188,187,186,185,184,183,182,181,180,179,178,177,176,175,174,173,172,171,170,169,168,167,166,165,164,163,162,161,160,159,158,157,156,155,154,153,152,151,150,149,148,147,146,145,144,143,142,141,140,139,138,137,136,135,134,133,132,131,130,129,128,127,126,125,124,123,122,121,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,100,99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63,62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,0,0], False),
]
for nums, expected in data:
real = s.canJump(nums)
if 10 <= len(nums):
print('{}...{}, expected {}, real {}, result {}'.format(nums[:5], nums[-5:], expected, real, expected == real))
else:
print('{}, expected {}, real {}, result {}'.format(nums, expected, real, expected == real))
|
[
"agapelover4u@yahoo.co.kr"
] |
agapelover4u@yahoo.co.kr
|
871dd366f3cab995150d2469f9261cd3a22f2c52
|
01ec1578126240ec8fb300de5290d02e0a8335dc
|
/books/admin.py
|
76c5517d3ab5b7de09b89a56d1bc40e923304746
|
[] |
no_license
|
mitun94/MyBooks
|
3f10852ebb532c0ae10b0ca7f852be802ed6cc9e
|
ba5e1a37e1d1f1d63495db75fd97b154f4eefbcb
|
refs/heads/master
| 2020-03-08T22:23:49.454677
| 2018-04-08T06:51:21
| 2018-04-08T06:51:21
| 128,429,643
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 161
|
py
|
from django.contrib import admin
from .models import Category,BookItem
# Register your models here.
admin.site.register(Category)
admin.site.register(BookItem)
|
[
"tohidulalammitun@gmail.com"
] |
tohidulalammitun@gmail.com
|
2cfe58bb9928d5ecdf0e6bbb00070b0faf7c1d78
|
85a718eca22f79c7b140615c9c8643bc148a5ba8
|
/manage.py
|
d23ac384e0efb49303bc802e24c58092a43c4b60
|
[
"CC-BY-NC-SA-4.0",
"CC-BY-NC-4.0",
"CC-BY-NC-SA-3.0",
"CC0-1.0"
] |
permissive
|
CircleCI-Public/circleci-demo-python-django
|
9298b8167fe1b3a10c91cabe540ab5759cd2c130
|
2bbf84b270e6de0888ea7f551a749b938f6194ba
|
refs/heads/master
| 2023-04-30T02:24:06.716277
| 2022-01-14T19:49:12
| 2022-01-14T19:49:12
| 89,367,810
| 127
| 428
|
CC0-1.0
| 2023-04-21T20:53:14
| 2017-04-25T14:07:09
|
Python
|
UTF-8
|
Python
| false
| false
| 810
|
py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locallibrary.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
[
"hamishwillee@gmail.com"
] |
hamishwillee@gmail.com
|
2f1cacdc9741a25f7bee9438d600cb9411fc01a8
|
79536b68be2785c1ccc49daddc38fec986315360
|
/guardianapi/fetchers.py
|
766ea398ea7acf7ca8db525852db916465106e53
|
[] |
no_license
|
tsmarsh/guardianmobile
|
fca20a86f365b9019cbf9a5f90883b0b14de228e
|
76e11f7b8a3645a999c08596ea8d61c6e1b9b30a
|
refs/heads/master
| 2016-09-10T01:34:06.506503
| 2009-08-18T14:27:46
| 2009-08-18T14:27:46
| 148,282
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,824
|
py
|
import urllib2, pickle
try:
import httplib2
except ImportError:
httplib2 = None
from errors import HTTPError
def best_fetcher():
if httplib2:
return CacheFetcher() # Uses an in-memory cache
else:
return Fetcher()
class Fetcher(object):
"Default implementation, using urllib2"
def get(self, url):
try:
u = urllib2.urlopen(url)
except urllib2.HTTPError, e:
raise HTTPError(e.code, e)
headers = u.headers.dict
return headers, u.read()
class InMemoryCache(object):
def __init__(self):
self._cache = {}
def get(self, key):
return self._cache.get(key)
def set(self, key, value):
self._cache[key] = value
def delete(key):
if key in self._cache[key]:
del self._cache[key]
class CacheFetcher(object):
"Uses httplib2 to cache based on the max-age header. Requires httplib2."
def __init__(self, cache=None):
if cache is None:
cache = InMemoryCache()
self.http = httplib2.Http(cache)
def get(self, url):
headers, response = self.http.request(url)
if headers['status'] != '200':
raise HTTPError(int(headers['status']), headers)
return headers, response
class ForceCacheFetcher(object):
"Caches every response forever, ignoring the max-age header"
def __init__(self, fetcher=None, cache=None):
self.fetcher = fetcher or Fetcher()
self.cache = cache or InMemoryCache()
def get(self, url):
cached_value = self.cache.get(url)
if cached_value:
return pickle.loads(cached_value)
headers, response = self.fetcher.get(url)
self.cache.set(url, pickle.dumps((headers, response)))
return headers, response
|
[
"ts.marsh@gmail.com"
] |
ts.marsh@gmail.com
|
0b5e32768ed6868c934b8e5ec4cba959792d7629
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-lts/huaweicloudsdklts/v2/model/update_log_group_response.py
|
88d154cc80b2f35af312418104e51138729d3714
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318
| 2023-08-31T08:28:59
| 2023-08-31T08:28:59
| 262,207,814
| 103
| 44
|
NOASSERTION
| 2023-06-22T14:50:48
| 2020-05-08T02:28:43
|
Python
|
UTF-8
|
Python
| false
| false
| 6,117
|
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class UpdateLogGroupResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'creation_time': 'int',
'log_group_name': 'str',
'log_group_id': 'str',
'ttl_in_days': 'int'
}
attribute_map = {
'creation_time': 'creation_time',
'log_group_name': 'log_group_name',
'log_group_id': 'log_group_id',
'ttl_in_days': 'ttl_in_days'
}
def __init__(self, creation_time=None, log_group_name=None, log_group_id=None, ttl_in_days=None):
"""UpdateLogGroupResponse
The model defined in huaweicloud sdk
:param creation_time: 创建该日志组的时间, 毫秒级。
:type creation_time: int
:param log_group_name: 日志组的名称。
:type log_group_name: str
:param log_group_id: 日志组ID。
:type log_group_id: str
:param ttl_in_days: 日志存储时间(天)。
:type ttl_in_days: int
"""
super(UpdateLogGroupResponse, self).__init__()
self._creation_time = None
self._log_group_name = None
self._log_group_id = None
self._ttl_in_days = None
self.discriminator = None
if creation_time is not None:
self.creation_time = creation_time
if log_group_name is not None:
self.log_group_name = log_group_name
if log_group_id is not None:
self.log_group_id = log_group_id
if ttl_in_days is not None:
self.ttl_in_days = ttl_in_days
@property
def creation_time(self):
"""Gets the creation_time of this UpdateLogGroupResponse.
创建该日志组的时间, 毫秒级。
:return: The creation_time of this UpdateLogGroupResponse.
:rtype: int
"""
return self._creation_time
@creation_time.setter
def creation_time(self, creation_time):
"""Sets the creation_time of this UpdateLogGroupResponse.
创建该日志组的时间, 毫秒级。
:param creation_time: The creation_time of this UpdateLogGroupResponse.
:type creation_time: int
"""
self._creation_time = creation_time
@property
def log_group_name(self):
"""Gets the log_group_name of this UpdateLogGroupResponse.
日志组的名称。
:return: The log_group_name of this UpdateLogGroupResponse.
:rtype: str
"""
return self._log_group_name
@log_group_name.setter
def log_group_name(self, log_group_name):
"""Sets the log_group_name of this UpdateLogGroupResponse.
日志组的名称。
:param log_group_name: The log_group_name of this UpdateLogGroupResponse.
:type log_group_name: str
"""
self._log_group_name = log_group_name
@property
def log_group_id(self):
"""Gets the log_group_id of this UpdateLogGroupResponse.
日志组ID。
:return: The log_group_id of this UpdateLogGroupResponse.
:rtype: str
"""
return self._log_group_id
@log_group_id.setter
def log_group_id(self, log_group_id):
"""Sets the log_group_id of this UpdateLogGroupResponse.
日志组ID。
:param log_group_id: The log_group_id of this UpdateLogGroupResponse.
:type log_group_id: str
"""
self._log_group_id = log_group_id
@property
def ttl_in_days(self):
"""Gets the ttl_in_days of this UpdateLogGroupResponse.
日志存储时间(天)。
:return: The ttl_in_days of this UpdateLogGroupResponse.
:rtype: int
"""
return self._ttl_in_days
@ttl_in_days.setter
def ttl_in_days(self, ttl_in_days):
"""Sets the ttl_in_days of this UpdateLogGroupResponse.
日志存储时间(天)。
:param ttl_in_days: The ttl_in_days of this UpdateLogGroupResponse.
:type ttl_in_days: int
"""
self._ttl_in_days = ttl_in_days
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UpdateLogGroupResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
8106fafdb5ec6258491ec9ff4ac9cf282149f318
|
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
|
/Gauss_v45r9/Gen/DecFiles/options/15966000.py
|
e27a25452c4fbe673648adb9fa2006914a890e86
|
[] |
no_license
|
Sally27/backup_cmtuser_full
|
34782102ed23c6335c48650a6eaa901137355d00
|
8924bebb935b96d438ce85b384cfc132d9af90f6
|
refs/heads/master
| 2020-05-21T09:27:04.370765
| 2018-12-12T14:41:07
| 2018-12-12T14:41:07
| 185,989,173
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 776
|
py
|
# file /home/hep/ss4314/cmtuser/Gauss_v45r9/Gen/DecFiles/options/15966000.py generated: Fri, 27 Mar 2015 16:10:12
#
# Event Type: 15966000
#
# ASCII decay Descriptor: [Lb => (D0 -> K+ K- pi+ pi-) X]cc
#
from Configurables import Generation
Generation().EventType = 15966000
Generation().SampleGenerationTool = "SignalPlain"
from Configurables import SignalPlain
Generation().addTool( SignalPlain )
Generation().SignalPlain.ProductionTool = "PythiaProduction"
from Configurables import ToolSvc
from Configurables import EvtGenDecay
ToolSvc().addTool( EvtGenDecay )
ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Lb_D0X,X=cocktail,D0=MINT,DecProdCut.dec"
Generation().SignalPlain.CutTool = "DaughtersInLHCb"
Generation().SignalPlain.SignalPIDList = [ 5122,-5122 ]
|
[
"slavomirastefkova@b2pcx39016.desy.de"
] |
slavomirastefkova@b2pcx39016.desy.de
|
ecb5033566867cb000d040c50eafc4011199a97e
|
21aa0289a371504992ae234f7f2cfe3a508804ec
|
/lab3/main.py
|
6a6ed68e2c566a771184c00838af88b9a1c89158
|
[] |
no_license
|
markporoshin/mathstat
|
434fa72dd55b33e8b2523c6f346ea978fccac4f2
|
e4fca53986c0ac84f986326de2fae47af873cae2
|
refs/heads/master
| 2021-04-20T12:52:51.634558
| 2020-07-12T18:38:41
| 2020-07-12T18:38:41
| 249,685,258
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,959
|
py
|
import numpy as np
from math import sqrt, pi, exp, pow, factorial, fabs, ceil
import matplotlib.pyplot as plt
distributions = [
{
'name': 'normal',
'func': lambda size: np.random.normal(size=size),
'destiny': lambda x: 1 / sqrt(2 * pi) * exp(-x * x / 2)
},
{
'name': 'poisson',
'func': lambda size: np.random.poisson(10, size=size),
'destiny': lambda x: (pow(10, round(x)) / factorial(round(x))) * exp(-10)
},
{
'name': 'cauchy',
'func': lambda size: np.random.standard_cauchy(size=size),
'destiny': lambda x: 1 / pi * (1 / (x * x + 1))
},
{
'name': 'laplace',
'func': lambda size: np.random.laplace(0, 1 / sqrt(2), size=size),
'destiny': lambda x: (1 / sqrt(2)) * exp(-sqrt(2) * fabs(x))
},
{
'name': 'uniform',
'func': lambda size: np.random.uniform(-sqrt(3), sqrt(3), size=size),
'destiny': lambda x: 1 / (2 * sqrt(3)) if (fabs(x) <= sqrt(3)) else 0
},
]
capacities = [20, 1000]
for dis in distributions:
# _,ax = plt.subplots()
# ax.boxplot([dis['func'](20), dis['func'](1000)], vert=False, showfliers=False)
# ax.set_title("%s" % (dis["name"]))
# ax.set_yticklabels(['20', '1000'])
# plt.show()
for cap in capacities:
sum = 0
samples = []
for _ in range(1000):
sample = sorted(dis['func'](cap))
l = len(sample)
Q1 = sample[int(1 / 4 * l)]
Q3 = sample[int(3 / 4 * l)]
X1 = Q1 - 3 / 2 * (Q3 - Q1)
X2 = Q3 + 3 / 2 * (Q3 - Q1)
discharge = list(filter(lambda x: x < X1 or x > X2, sample))
discharges = len(list(filter(lambda x: x < X1 or x > X2, sample)))
sum += discharges
samples.append(discharges)
print("%s-%s average discharges proportion %s; var %s" % (dis['name'], cap, sum / 1000 / cap, np.var(samples) / cap))
|
[
"mark.poroshin@yandex.ru"
] |
mark.poroshin@yandex.ru
|
6a5a73bb8bebce97725c37554303abc4ba6939d4
|
d5160ebcb62307f08e729c38c17d53eb4ddbfa7a
|
/Face-Recognition/frame_extraction.py
|
b38cd437cba9d81745483460ef45518a60a7fa31
|
[
"MIT"
] |
permissive
|
huylv69/Face-Recognition
|
4a1ccd35885c5a79abbedc160d281e66a9b7b30c
|
6235d707a20562f4b06d6a0980a2c07e69b83a74
|
refs/heads/master
| 2020-03-17T12:47:11.448580
| 2018-05-31T15:38:23
| 2018-05-31T15:38:23
| 133,602,987
| 5
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,224
|
py
|
import numpy as np
import cv2
#function to detect face using OpenCV
def detect_face(img):
#convert the test image to gray image as opencv face detector expects gray images
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#load OpenCV face detector use LBP more accurate but slow Haar classifier
face_cascade = cv2.CascadeClassifier('opencv-files/haarcascade_frontalface_alt.xml')
# detect multiscale images
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=1,minSize=(20,20)) #result is a list of faces
#if no faces are detected then return original img
if (len(faces) == 0):
return None, None
(x, y, w, h) = faces[0] # assumption that there will be only one face,
#return only the face part of the image
return gray[y:y+w, x:x+h], faces[0]
def predict(test_img):
#make a copy of the image
img = test_img.copy()
#detect face from the image
face, rect = detect_face(img)
if face is None:
print (" Can not detect face from file!")
return None
#predict the image using face recognizer
label, confidence = face_recognizer.predict(face)
# label_text = subjects[label]
print (label , confidence)
return confidence
cap = cv2.VideoCapture(0)
images = []
print ("Capturing image.....")
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
face, rect = detect_face(frame)
if face is None:
pass
else :
images.append(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print ("Capture done.")
# When everything done, release the capture
cap.release()
cv2.destroyWindow('frame')
# Load face recognizer
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.read("trained_model/trained_model.xml")
print ("Choosing the best frame...")
print len(images)
best_image = images[0]
best_score = predict(best_image)
for image in images:
if (predict(image)<best_score):
best_score = predict(image)
best_image = image
cv2.imshow('Best frame',best_image)
cv2.imwrite('best_frame.png',best_image)
cv2.waitKey(1)
cv2.destroyAllWindows()
|
[
"levanhuy96@gmail.com"
] |
levanhuy96@gmail.com
|
b97d143ad661ee089527547470fea808e5cb764d
|
99572bef8a2371a71f1414d4aa0a48764bbcc2c3
|
/manage.py
|
98b4971841df1a1003514267d92630b8f8d53802
|
[] |
no_license
|
solarflare626/IITOverflowWeb
|
c4e7784f0e056d8f74503f77fc37fdae44d3b37b
|
390fa4370d741b03f2083b59f49c98ef58ad5148
|
refs/heads/master
| 2021-04-06T02:48:20.648507
| 2018-08-09T12:39:28
| 2018-08-09T12:39:28
| 124,879,533
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,833
|
py
|
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db, models
from app.models import User, Bucket, BucketItem
import unittest
import coverage
import os
import forgery_py as faker
from random import randint
from sqlalchemy.exc import IntegrityError
# Initializing the manager
manager = Manager(app)
# Initialize Flask Migrate
migrate = Migrate(app, db)
# Add the flask migrate
manager.add_command('db', MigrateCommand)
# Test coverage configuration
COV = coverage.coverage(
branch=True,
include='app/*',
omit=[
'app/auth/__init__.py',
'app/bucket/__init__.py',
'app/bucketitems/__init__.py'
]
)
COV.start()
# Add test command
@manager.command
def test():
"""
Run tests without coverage
:return:
"""
tests = unittest.TestLoader().discover('tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1
@manager.command
def dummy():
# Create a user if they do not exist.
user = User.query.filter_by(email="example@bucketmail.com").first()
if not user:
user = User("example@bucketmail.com", "123456")
user.save()
for i in range(100):
# Add buckets to the database
bucket = Bucket(faker.name.industry(), user.id)
bucket.save()
for buck in range(1000):
# Add items to the bucket
buckt = Bucket.query.filter_by(id=randint(1, Bucket.query.count() - 1)).first()
item = BucketItem(faker.name.company_name(), faker.lorem_ipsum.word(), buckt.id)
db.session.add(item)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
# Run the manager
if __name__ == '__main__':
manager.run()
|
[
"johnkagga@gmail.com"
] |
johnkagga@gmail.com
|
0a6a43b54aeecd180ee3e7ec5e7e6177d82472fe
|
a76dc1b81d802401721d51b7ab7d2f88562bc05a
|
/ce/python3.6_windows_gpu_models/variational_seq2seq/_ce.py
|
c1fc10b968a52272d6f0aea0d83c19a7dfde4502
|
[] |
no_license
|
PaddlePaddle/paddle-ce-latest-kpis
|
353a132d1c4c31305ebd4eeeb1a729c025a2fffc
|
f9a9ca792c4c7b659b8fa4cdf07cacb063db4f11
|
refs/heads/develop
| 2021-12-22T08:36:52.083618
| 2021-12-13T11:27:18
| 2021-12-13T11:27:18
| 127,693,333
| 29
| 128
| null | 2023-05-05T06:26:26
| 2018-04-02T02:40:42
|
Python
|
UTF-8
|
Python
| false
| false
| 1,244
|
py
|
# this file is only used for continuous evaluation test!
import os
import sys
sys.path.append(os.environ['ceroot'])
from kpi import CostKpi
from kpi import DurationKpi
test_nll_kpis = CostKpi('test_nll', 0.02, 0, actived=True)
test_ppl_kpis = CostKpi('test_ppl', 0.02, 0, actived=True)
tracking_kpis = [
test_nll_kpis,
test_ppl_kpis,
]
def parse_log(log):
'''
This method should be implemented by model developers.
The suggestion:
each line in the log should be key, value, for example:
"
train_cost\t1.0
test_cost\t1.0
train_cost\t1.0
train_cost\t1.0
train_acc\t1.2
"
'''
for line in log.split('\n'):
fs = line.strip().split('\t')
print(fs)
if len(fs) == 3 and fs[0] == 'kpis':
kpi_name = fs[1]
kpi_value = float(fs[2])
yield kpi_name, kpi_value
def log_to_ce(log):
kpi_tracker = {}
for kpi in tracking_kpis:
kpi_tracker[kpi.name] = kpi
for (kpi_name, kpi_value) in parse_log(log):
print(kpi_name, kpi_value)
kpi_tracker[kpi_name].add_record(kpi_value)
kpi_tracker[kpi_name].persist()
if __name__ == '__main__':
log = sys.stdin.read()
log_to_ce(log)
|
[
"jiaxiao243@126.com"
] |
jiaxiao243@126.com
|
e156d6f45f221cee8eb82b24e63a2092d4185d22
|
1f613d0e8a0603128b3c44ae20f2a88b7bd1fd0f
|
/manage.py
|
9d1ad7e5f90442bc51d334d7db18fe5c5b55d540
|
[] |
no_license
|
Korek-F/Django-WordsApp
|
55bb64ee1137fb1bdb31f46b196407cbcfc36922
|
97ede8ac6499538929544232c084dd285f67a553
|
refs/heads/master
| 2023-03-20T21:07:41.834896
| 2021-03-09T11:19:22
| 2021-03-09T11:19:22
| 344,179,025
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 625
|
py
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'words.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
|
[
"filip.korycki2222@gmail.com"
] |
filip.korycki2222@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.