hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f729a81a37da84730d76d2a4dea5568aaaf90938 | 17,919 | py | Python | src/support.py | M2rsho/PyBot-v5 | 450acff1ecf331ef53e56c916f8336b92509ea7e | [
"MIT"
] | null | null | null | src/support.py | M2rsho/PyBot-v5 | 450acff1ecf331ef53e56c916f8336b92509ea7e | [
"MIT"
] | null | null | null | src/support.py | M2rsho/PyBot-v5 | 450acff1ecf331ef53e56c916f8336b92509ea7e | [
"MIT"
] | 2 | 2022-03-29T12:10:59.000Z | 2022-03-30T02:11:09.000Z | """
Discord Pybot Support
~~~~~~~~~~~~~~~~~
Support File with stuff
:copyright: (c) 2021-2021 M2rsho
:license: MIT, see LICENSE for more details.
"""
if __name__ == "__main__":
print("Huh?")
exit
from datetime import datetime
from colorama import *
import yaml
from random import choice
from PIL import Image, ImageFont, ImageDraw
from gtts import gTTS
from datetime import datetime
import requests
from io import BytesIO
import os
from pathlib import Path
from werkzeug.utils import secure_filename
time = datetime.utcnow()
startup_date = f"{time.day}_{time.month}_{time.year}-{time.hour:02d}-{time.minute:02d}.{time.second:02d}.{time.microsecond:03d}"
startup_timestamp = time.timestamp()
path = f"{__file__}".replace("\\", "/")
path = path.replace("/support.py", "")
config = open(f"{path}/config.yaml")
config = yaml.load(config, Loader=yaml.FullLoader)
prefix = config.get("prefix")
cooldown = config.get("cooldown")
with open(f"{path}/data/alts.txt") as file:
alts = file.readlines()
async def getAlt():
return choice(alts)
debug = not config.get("debug")
def log(date, type, arg1, arg2):
time = f"{date.hour:02d}:{date.minute:02d}:{date.second:02d}"
if type == "COMMAND":
print(
f"""{Back.BLACK}{Fore.LIGHTYELLOW_EX}{time}{Style.RESET_ALL} [{Fore.LIGHTGREEN_EX}INFO{Style.RESET_ALL}] {Fore.LIGHTYELLOW_EX}{arg1}{Style.RESET_ALL}: {Fore.LIGHTGREEN_EX}Invoked Command{Style.RESET_ALL}: '{Fore.LIGHTWHITE_EX}{Back.LIGHTBLACK_EX}{arg2}{Style.RESET_ALL}'{Style.RESET_ALL}""")
else:
print(
f"""{Back.BLACK}{Fore.LIGHTYELLOW_EX}{time}{Style.RESET_ALL} [{Fore.LIGHTGREEN_EX}{type}{Style.RESET_ALL}] {Fore.LIGHTYELLOW_EX}{arg1}{Style.RESET_ALL}: {Fore.LIGHTGREEN_EX}{arg2}{Style.RESET_ALL}""")
if debug:
with open(f"{path}/logs/{startup_date}.log", "a+") as file:
type = type if type != "COMMAND" else "INFO"
file.write(f"{time} [{type}] {arg1}: {arg2}\n")
class colours:
default = 0x7842ff
red = 0xff7777
green = 0x77dd77
yellow = 0xeb9226
class processing:
async def GENERATE_CAN(name, text, bottom_text=""):
if len(text) > 90 or len(bottom_text) > 90:
return False
def add_n(text, after: int):
x = ""
for i, letter in enumerate(text):
if i % after == 0:
x += '\n'
x += letter
x = x[1:]
return x
text = add_n(text, 20)
bottom_text = add_n(bottom_text, 30)
W, H = (582, 975)
font_ = ImageFont.truetype(
f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
font__ = ImageFont.truetype(
f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 30)
img = Image.open(f"{path}/data/resources/templates/can_template.png")
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font_)
w2, h2 = draw.textsize(bottom_text, font=font__)
draw.text(((W-w)/2, 300-(h/2)), text, (255, 255, 0), font=font_)
draw.text(((W-w2)/2, 700-(h2/2)), bottom_text, (0, 0, 0), font=font__)
img.save(f"{path}/data/temp/{name}.png")
return(f"{path}/data/temp/{name}.png")
async def tts(txt, languag):
date = str(datetime.utcnow()).replace(":", "-")
speech = gTTS(text=u'{}'.format(txt), lang=languag, slow=False)
speech.save(f"{path}/data/temp/{date}.mp3")
return(f"{path}/data/temp/{date}.mp3")
async def overlay(background_url, foreground, user_id):
response=requests.get(background_url)
background = Image.open(BytesIO(response.content)).resize((1024, 1024), Image.ANTIALIAS).convert("RGBA")
foreground = Image.open(foreground).resize((1024, 1024), Image.ANTIALIAS).convert("RGBA")
background.paste(foreground, (0, 0), foreground)
background.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
async def overlay_position(background_url, foreground, xy, xsys, user_id, image_size):
img = Image.new('RGBA', image_size, (255, 0, 0, 0))
response=requests.get(background_url)
background = Image.open(BytesIO(response.content)).resize(xsys, Image.ANTIALIAS).convert("RGBA")
foreground = Image.open(foreground).convert("RGBA")
img.paste(background, xy, background)
img.paste(foreground, (0, 0), foreground)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
async def generate_social_credit(value, user_id):
if value > 0:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/10.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 35)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
elif -15 < value <= 0:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-15.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
elif -30 <= value <= -15:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-30.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
else:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-100.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
from requests import Session
import json
sfa_url = 'https://api.mojang.com/user/security/challenges'
class check():
def __init__(self, loginpassword):
self.result = self.check_alt(loginpassword)
def secure_check(self, token):
session = Session()
headers = {'Pragma': 'no-cache', "Authorization": f"Bearer {token}"}
z = session.get(url=sfa_url, headers=headers).text
return z == '[]'
def check_alt(self, loginpassword):
session = Session()
alt = loginpassword.split(":", 1)
jsonheaders = {"Content-Type": "application/json", 'Pragma': 'no-cache'}
email = str(alt[0]).replace("\n", "")
password = str(alt[1]).replace("\n", "")
payload = ({
"agent": {
"name": "Minecraft",
"version": 1
},
"username": f"{email}",
"password": f"{password}",
"requestUser": True
})
bad = 'Invalid credentials'
answer = session.post(url="https://authserver.mojang.com/authenticate", json=payload, headers=jsonheaders, timeout=10000)
if (
bad in answer.text
or 'Client sent too many requests too fast.' in answer.text
):
return json.loads(answer.text)["errorMessage"]
ajson = answer.json()
username = ajson['availableProfiles'][0]['name']
token = ajson['accessToken']
uuid = ajson['availableProfiles'][0]["id"]
securec = self.secure_check(token)
return f'''
Original Combo: `{loginpassword}`
Username: `{username}`
UUID: `{uuid}`
Email: `{email}`
Password: `{password}`
Sfa: `{securec}`
'''
import sqlite3
class database:
def __init__(self, path):
self.con = sqlite3.connect(path)
self.cur = self.con.cursor()
self.cur.execute('''CREATE TABLE IF NOT EXISTS users (id integer, username text, balance integer, banned integer, admin integer, reason text, banned_by text, date text, duration integer, socialCredit integer)''')
self.cur.execute('''CREATE TABLE IF NOT EXISTS guilds (id integer, name text, language text, prefix text)''')
async def getUser(self, user):
u = self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO users VALUES (?, ?, 10000, 0, 0, "None", "None", "None", 0, 1000)', (user.id, str(user), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
def getUserSync(self, user):
u = self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO users VALUES (?, ?, 10000, 0, 0, "None", "None", "None", 0, 1000)', (user.id, str(user), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
async def getAllUsers(self):
return self.cur.execute(f'''SELECT * FROM users''').fetchall()
def getAllUsers_sync(self):
return self.cur.execute(f'''SELECT * FROM users''').fetchall()
async def setBalance(self, user, balance: int):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def addBalance(self, user, balance: int):
balance = await self.getBalance(user) + balance
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def addEveryoneBalance(self, balance: int):
self.cur.execute(f'''UPDATE users SET balance=balance+?''', (balance, ))
self.con.commit()
async def setEveryoneBalance(self, balance: int):
self.cur.execute(f'''UPDATE users SET balance=?''', (balance, ))
self.con.commit()
async def removebalance(self, user, balance: int):
balance = await self.getBalance(user) - balance
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def getBalance(self, user):
balance = (await self.getUser(user))[2]
return balance
async def banUser(self, user , reason, date, author):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET banned=1, reason=?, date=?, banned_by=? WHERE id=?''', (str(reason), str(date), str(author), user.id))
self.con.commit()
async def unbanUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET banned=0, reason="None", date="None", banned_by="None" WHERE id=?''', (user.id,))
self.con.commit()
async def opUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET admin=1 WHERE id=?''', (user.id,))
self.con.commit()
async def deopUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET admin=0 WHERE id=?''', (user.id,))
self.con.commit()
async def getBanned(self):
u = list(self.cur.execute(f'''SELECT id FROM users WHERE banned="1"''').fetchall())
banned = [list(item) for item in u]
return banned
async def getOps(self):
u = list(self.cur.execute(f'''SELECT id FROM users WHERE admin="1"''').fetchall())
ops = [list(item) for item in u]
return ops
async def getGuild(self, guild):
u = self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO guilds VALUES (?, ?, "en.json", "!")', (guild.id, str(guild), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
def getGuildSync(self, guild):
u = self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO guilds VALUES (?, ?, "en.json", "!")', (guild.id, str(guild), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
def getLanguage(self, guild):
try:
guild = self.getGuildSync(guild)
return guild[2]
except:
return 'en.json'
def getPrefix(self, guild):
try:
guild = self.getGuildSync(guild)
return guild[3]
except:
return '!'
def setPrefix(self, guild, prefix):
self.getGuildSync(guild)
self.cur.execute(f'''UPDATE guilds SET prefix=? WHERE id=?''', (prefix, guild.id))
self.con.commit()
return self.getGuildSync(guild)[3]
async def setLanguage(self, guild, language):
await self.getGuild(guild)
self.cur.execute(f'''UPDATE guilds SET language=? WHERE id=?''', (language, guild.id))
self.con.commit()
async def setSocialCredit(self, user, credit: int):
if credit < 0:
credit = 0
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET socialCredit=? WHERE id=?''', (credit, user.id))
self.con.commit()
return credit
async def addSocialCredit(self, user, credit: int):
if await self.getSocialCredit(user) + credit <= 0:
self.cur.execute(f'''UPDATE users SET socialCredit=0 WHERE id=?''', (user.id, ))
self.con.commit()
elif await self.getSocialCredit(user) + credit >= 3000:
self.cur.execute(f'''UPDATE users SET socialCredit=3000 WHERE id=?''', (user.id, ))
self.con.commit()
else:
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit+? WHERE id=?''', (credit, user.id, ))
self.con.commit()
async def addEveryoneSocialCredit(self, credit: int):
if credit < 0:
credit = 0
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit+credit''', (credit, ))
self.con.commit()
return credit
async def setEveryoneSocialCredit(self, credit: int):
if credit < 0:
credit = 0
self.cur.execute(f'''UPDATE users SET socialCredit=?''', (credit, ))
self.con.commit()
return credit
async def removeSocialCredit(self, user, credit: int):
if credit < 0:
credit = 0
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit-? WHERE id=?''', (credit, user.id))
self.con.commit()
return credit
async def getSocialCredit(self, user):
credit = (await self.getUser(user))[9]
return credit
def getSocialCreditSync(self, user):
credit = (self.getUserSync(user))[9]
return credit
globalData = database(path=f"{path}/data/database.db")
languages = [item for item in os.listdir(f"{path}/data/languages/")]
def convertToBitcoin(amount, currency):
data = requests.get("http://api.bitcoincharts.com/v1/weighted_prices.json")
bitcoins = data.json()
converted = amount / float(bitcoins[currency]["24h"])
return converted
def getPrefix(client, ctx):
try:
if config.get("debug") is True:
return ["b!", f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
return [globalData.getPrefix(ctx.guild), f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
except:
return ['!', f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
def getLanguage(guild):
try:
return globalData.getLanguage(guild)
except:
return 'en.json'
def getLanguageFile(language):
if Path(f"{path}/data/languages/{secure_filename(language)}").exists():
with open(f"{path}/data/languages/{secure_filename(language)}") as lang:
data = json.load(lang)
return data
else:
return 'en.json'
def getLanguageFileG(guild):
try:
language = getLanguage(guild)
return getLanguageFile(language)
except:
return 'en.json'
def getDescription(language, command):
try:
with open(f"{path}/data/languages/{language}") as lang:
data = json.load(lang)
return data["commands"][command]["description"]
except:
return '🔴 Description Not Found'
| 39.908686 | 304 | 0.581841 |
if __name__ == "__main__":
print("Huh?")
exit
from datetime import datetime
from colorama import *
import yaml
from random import choice
from PIL import Image, ImageFont, ImageDraw
from gtts import gTTS
from datetime import datetime
import requests
from io import BytesIO
import os
from pathlib import Path
from werkzeug.utils import secure_filename
time = datetime.utcnow()
startup_date = f"{time.day}_{time.month}_{time.year}-{time.hour:02d}-{time.minute:02d}.{time.second:02d}.{time.microsecond:03d}"
startup_timestamp = time.timestamp()
path = f"{__file__}".replace("\\", "/")
path = path.replace("/support.py", "")
config = open(f"{path}/config.yaml")
config = yaml.load(config, Loader=yaml.FullLoader)
prefix = config.get("prefix")
cooldown = config.get("cooldown")
with open(f"{path}/data/alts.txt") as file:
alts = file.readlines()
async def getAlt():
return choice(alts)
debug = not config.get("debug")
def log(date, type, arg1, arg2):
time = f"{date.hour:02d}:{date.minute:02d}:{date.second:02d}"
if type == "COMMAND":
print(
f"""{Back.BLACK}{Fore.LIGHTYELLOW_EX}{time}{Style.RESET_ALL} [{Fore.LIGHTGREEN_EX}INFO{Style.RESET_ALL}] {Fore.LIGHTYELLOW_EX}{arg1}{Style.RESET_ALL}: {Fore.LIGHTGREEN_EX}Invoked Command{Style.RESET_ALL}: '{Fore.LIGHTWHITE_EX}{Back.LIGHTBLACK_EX}{arg2}{Style.RESET_ALL}'{Style.RESET_ALL}""")
else:
print(
f"""{Back.BLACK}{Fore.LIGHTYELLOW_EX}{time}{Style.RESET_ALL} [{Fore.LIGHTGREEN_EX}{type}{Style.RESET_ALL}] {Fore.LIGHTYELLOW_EX}{arg1}{Style.RESET_ALL}: {Fore.LIGHTGREEN_EX}{arg2}{Style.RESET_ALL}""")
if debug:
with open(f"{path}/logs/{startup_date}.log", "a+") as file:
type = type if type != "COMMAND" else "INFO"
file.write(f"{time} [{type}] {arg1}: {arg2}\n")
class colours:
default = 0x7842ff
red = 0xff7777
green = 0x77dd77
yellow = 0xeb9226
class processing:
async def GENERATE_CAN(name, text, bottom_text=""):
if len(text) > 90 or len(bottom_text) > 90:
return False
def add_n(text, after: int):
x = ""
for i, letter in enumerate(text):
if i % after == 0:
x += '\n'
x += letter
x = x[1:]
return x
text = add_n(text, 20)
bottom_text = add_n(bottom_text, 30)
W, H = (582, 975)
font_ = ImageFont.truetype(
f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
font__ = ImageFont.truetype(
f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 30)
img = Image.open(f"{path}/data/resources/templates/can_template.png")
draw = ImageDraw.Draw(img)
w, h = draw.textsize(text, font=font_)
w2, h2 = draw.textsize(bottom_text, font=font__)
draw.text(((W-w)/2, 300-(h/2)), text, (255, 255, 0), font=font_)
draw.text(((W-w2)/2, 700-(h2/2)), bottom_text, (0, 0, 0), font=font__)
img.save(f"{path}/data/temp/{name}.png")
return(f"{path}/data/temp/{name}.png")
async def tts(txt, languag):
date = str(datetime.utcnow()).replace(":", "-")
speech = gTTS(text=u'{}'.format(txt), lang=languag, slow=False)
speech.save(f"{path}/data/temp/{date}.mp3")
return(f"{path}/data/temp/{date}.mp3")
async def overlay(background_url, foreground, user_id):
response=requests.get(background_url)
background = Image.open(BytesIO(response.content)).resize((1024, 1024), Image.ANTIALIAS).convert("RGBA")
foreground = Image.open(foreground).resize((1024, 1024), Image.ANTIALIAS).convert("RGBA")
background.paste(foreground, (0, 0), foreground)
background.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
async def overlay_position(background_url, foreground, xy, xsys, user_id, image_size):
img = Image.new('RGBA', image_size, (255, 0, 0, 0))
response=requests.get(background_url)
background = Image.open(BytesIO(response.content)).resize(xsys, Image.ANTIALIAS).convert("RGBA")
foreground = Image.open(foreground).convert("RGBA")
img.paste(background, xy, background)
img.paste(foreground, (0, 0), foreground)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
async def generate_social_credit(value, user_id):
if value > 0:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/10.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 35)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
elif -15 < value <= 0:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-15.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
elif -30 <= value <= -15:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-30.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
else:
value = str(value)
img = Image.open(f"{path}/data/resources/templates/socialcredit/-100.jpg").resize((287, 175), Image.ANTIALIAS).convert("RGBA")
font = ImageFont.truetype(f"{path}/data/resources/fonts/NotoSansJP-Medium.otf", 50)
draw = ImageDraw.Draw(img)
w, h = draw.textsize(value, font=font)
draw.text(((220-w)/2, 50-(h/2)), value, (255, 255, 255), font=font)
img.save(f"{path}/data/temp/{user_id}.png")
return(f"{path}/data/temp/{user_id}.png")
from requests import Session
import json
sfa_url = 'https://api.mojang.com/user/security/challenges'
class check():
def __init__(self, loginpassword):
self.result = self.check_alt(loginpassword)
def secure_check(self, token):
session = Session()
headers = {'Pragma': 'no-cache', "Authorization": f"Bearer {token}"}
z = session.get(url=sfa_url, headers=headers).text
return z == '[]'
def check_alt(self, loginpassword):
session = Session()
alt = loginpassword.split(":", 1)
jsonheaders = {"Content-Type": "application/json", 'Pragma': 'no-cache'}
email = str(alt[0]).replace("\n", "")
password = str(alt[1]).replace("\n", "")
payload = ({
"agent": {
"name": "Minecraft",
"version": 1
},
"username": f"{email}",
"password": f"{password}",
"requestUser": True
})
bad = 'Invalid credentials'
answer = session.post(url="https://authserver.mojang.com/authenticate", json=payload, headers=jsonheaders, timeout=10000)
if (
bad in answer.text
or 'Client sent too many requests too fast.' in answer.text
):
return json.loads(answer.text)["errorMessage"]
ajson = answer.json()
username = ajson['availableProfiles'][0]['name']
token = ajson['accessToken']
uuid = ajson['availableProfiles'][0]["id"]
securec = self.secure_check(token)
return f'''
Original Combo: `{loginpassword}`
Username: `{username}`
UUID: `{uuid}`
Email: `{email}`
Password: `{password}`
Sfa: `{securec}`
'''
import sqlite3
class database:
def __init__(self, path):
self.con = sqlite3.connect(path)
self.cur = self.con.cursor()
self.cur.execute('''CREATE TABLE IF NOT EXISTS users (id integer, username text, balance integer, banned integer, admin integer, reason text, banned_by text, date text, duration integer, socialCredit integer)''')
self.cur.execute('''CREATE TABLE IF NOT EXISTS guilds (id integer, name text, language text, prefix text)''')
async def getUser(self, user):
u = self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO users VALUES (?, ?, 10000, 0, 0, "None", "None", "None", 0, 1000)', (user.id, str(user), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
def getUserSync(self, user):
u = self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO users VALUES (?, ?, 10000, 0, 0, "None", "None", "None", 0, 1000)', (user.id, str(user), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM users WHERE id=?''', (user.id, )).fetchone()
async def getAllUsers(self):
return self.cur.execute(f'''SELECT * FROM users''').fetchall()
def getAllUsers_sync(self):
return self.cur.execute(f'''SELECT * FROM users''').fetchall()
async def setBalance(self, user, balance: int):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def addBalance(self, user, balance: int):
balance = await self.getBalance(user) + balance
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def addEveryoneBalance(self, balance: int):
self.cur.execute(f'''UPDATE users SET balance=balance+?''', (balance, ))
self.con.commit()
async def setEveryoneBalance(self, balance: int):
self.cur.execute(f'''UPDATE users SET balance=?''', (balance, ))
self.con.commit()
async def removebalance(self, user, balance: int):
balance = await self.getBalance(user) - balance
self.cur.execute(f'''UPDATE users SET balance=? WHERE id=?''', (balance, user.id))
self.con.commit()
async def getBalance(self, user):
balance = (await self.getUser(user))[2]
return balance
async def banUser(self, user , reason, date, author):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET banned=1, reason=?, date=?, banned_by=? WHERE id=?''', (str(reason), str(date), str(author), user.id))
self.con.commit()
async def unbanUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET banned=0, reason="None", date="None", banned_by="None" WHERE id=?''', (user.id,))
self.con.commit()
async def opUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET admin=1 WHERE id=?''', (user.id,))
self.con.commit()
async def deopUser(self, user):
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET admin=0 WHERE id=?''', (user.id,))
self.con.commit()
async def getBanned(self):
u = list(self.cur.execute(f'''SELECT id FROM users WHERE banned="1"''').fetchall())
banned = [list(item) for item in u]
return banned
async def getOps(self):
u = list(self.cur.execute(f'''SELECT id FROM users WHERE admin="1"''').fetchall())
ops = [list(item) for item in u]
return ops
async def getGuild(self, guild):
u = self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO guilds VALUES (?, ?, "en.json", "!")', (guild.id, str(guild), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
def getGuildSync(self, guild):
u = self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
if u is None:
self.cur.execute(f'INSERT INTO guilds VALUES (?, ?, "en.json", "!")', (guild.id, str(guild), ))
self.con.commit()
return self.cur.execute(f'''SELECT * FROM guilds WHERE id=?''', (guild.id, )).fetchone()
def getLanguage(self, guild):
try:
guild = self.getGuildSync(guild)
return guild[2]
except:
return 'en.json'
def getPrefix(self, guild):
try:
guild = self.getGuildSync(guild)
return guild[3]
except:
return '!'
def setPrefix(self, guild, prefix):
self.getGuildSync(guild)
self.cur.execute(f'''UPDATE guilds SET prefix=? WHERE id=?''', (prefix, guild.id))
self.con.commit()
return self.getGuildSync(guild)[3]
async def setLanguage(self, guild, language):
await self.getGuild(guild)
self.cur.execute(f'''UPDATE guilds SET language=? WHERE id=?''', (language, guild.id))
self.con.commit()
async def setSocialCredit(self, user, credit: int):
if credit < 0:
credit = 0
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET socialCredit=? WHERE id=?''', (credit, user.id))
self.con.commit()
return credit
async def addSocialCredit(self, user, credit: int):
if await self.getSocialCredit(user) + credit <= 0:
self.cur.execute(f'''UPDATE users SET socialCredit=0 WHERE id=?''', (user.id, ))
self.con.commit()
elif await self.getSocialCredit(user) + credit >= 3000:
self.cur.execute(f'''UPDATE users SET socialCredit=3000 WHERE id=?''', (user.id, ))
self.con.commit()
else:
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit+? WHERE id=?''', (credit, user.id, ))
self.con.commit()
async def addEveryoneSocialCredit(self, credit: int):
if credit < 0:
credit = 0
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit+credit''', (credit, ))
self.con.commit()
return credit
async def setEveryoneSocialCredit(self, credit: int):
if credit < 0:
credit = 0
self.cur.execute(f'''UPDATE users SET socialCredit=?''', (credit, ))
self.con.commit()
return credit
async def removeSocialCredit(self, user, credit: int):
if credit < 0:
credit = 0
await self.getUser(user)
self.cur.execute(f'''UPDATE users SET socialCredit=socialCredit-? WHERE id=?''', (credit, user.id))
self.con.commit()
return credit
async def getSocialCredit(self, user):
credit = (await self.getUser(user))[9]
return credit
def getSocialCreditSync(self, user):
credit = (self.getUserSync(user))[9]
return credit
globalData = database(path=f"{path}/data/database.db")
languages = [item for item in os.listdir(f"{path}/data/languages/")]
def convertToBitcoin(amount, currency):
data = requests.get("http://api.bitcoincharts.com/v1/weighted_prices.json")
bitcoins = data.json()
converted = amount / float(bitcoins[currency]["24h"])
return converted
def getPrefix(client, ctx):
try:
if config.get("debug") is True:
return ["b!", f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
return [globalData.getPrefix(ctx.guild), f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
except:
return ['!', f'<@{client.user.id}> ', f'<@!{client.user.id}> ']
def getLanguage(guild):
try:
return globalData.getLanguage(guild)
except:
return 'en.json'
def getLanguageFile(language):
if Path(f"{path}/data/languages/{secure_filename(language)}").exists():
with open(f"{path}/data/languages/{secure_filename(language)}") as lang:
data = json.load(lang)
return data
else:
return 'en.json'
def getLanguageFileG(guild):
try:
language = getLanguage(guild)
return getLanguageFile(language)
except:
return 'en.json'
def getDescription(language, command):
try:
with open(f"{path}/data/languages/{language}") as lang:
data = json.load(lang)
return data["commands"][command]["description"]
except:
return '🔴 Description Not Found'
| true | true |
f729abae5fa086287f5c38105ba1a0a9774ec6b7 | 19,369 | py | Python | python_modules/dagster/dagster/core/execution/plan/plan.py | nikie/dagster | 90ece239149bf255138ba2aaa8a3b4ce6f7d57ec | [
"Apache-2.0"
] | null | null | null | python_modules/dagster/dagster/core/execution/plan/plan.py | nikie/dagster | 90ece239149bf255138ba2aaa8a3b4ce6f7d57ec | [
"Apache-2.0"
] | null | null | null | python_modules/dagster/dagster/core/execution/plan/plan.py | nikie/dagster | 90ece239149bf255138ba2aaa8a3b4ce6f7d57ec | [
"Apache-2.0"
] | null | null | null | from collections import OrderedDict, namedtuple
from dagster import check
from dagster.core.definitions import (
CompositeSolidDefinition,
InputDefinition,
PipelineDefinition,
Solid,
SolidDefinition,
SolidHandle,
SolidOutputHandle,
solids_in_topological_order,
)
from dagster.core.definitions.dependency import DependencyStructure
from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvariantViolationError
from dagster.core.events import DagsterEvent
from dagster.core.execution.config import IRunConfig
from dagster.core.system_config.objects import EnvironmentConfig
from dagster.core.utils import toposort
from .compute import create_compute_step
from .objects import ExecutionStep, StepInput, StepInputSourceType, StepOutputHandle
class _PlanBuilder(object):
'''_PlanBuilder. This is the state that is built up during the execution plan build process.
steps List[ExecutionStep]: a list of the execution steps that have been created.
step_output_map Dict[SolidOutputHandle, StepOutputHandle]: maps logical solid outputs
(solid_name, output_name) to particular step outputs. This covers the case where a solid maps to
multiple steps and one wants to be able to attach to the logical output of a solid during
execution.
'''
def __init__(self, pipeline_def, environment_config, run_config):
self.pipeline_def = check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition)
self.environment_config = check.inst_param(
environment_config, 'environment_config', EnvironmentConfig
)
self.run_config = check.inst_param(run_config, 'run_config', IRunConfig)
self.mode_definition = pipeline_def.get_mode_definition(run_config.mode)
self._steps = OrderedDict()
self.step_output_map = dict()
self._seen_keys = set()
@property
def pipeline_name(self):
return self.pipeline_def.name
def add_step(self, step):
# Keep track of the step keys we've seen so far to ensure we don't add duplicates
if step.key in self._seen_keys:
keys = [s.key for s in self._steps]
check.failed(
'Duplicated key {key}. Full list seen so far: {key_list}.'.format(
key=step.key, key_list=keys
)
)
self._seen_keys.add(step.key)
self._steps[step.solid_handle.to_string()] = step
def add_steps(self, steps):
for step in steps:
self.add_step(step)
def get_step_by_handle(self, handle):
check.inst_param(handle, 'handle', SolidHandle)
return self._steps[handle.to_string()]
def get_output_handle(self, key):
check.inst_param(key, 'key', SolidOutputHandle)
return self.step_output_map[key]
def set_output_handle(self, key, val):
check.inst_param(key, 'key', SolidOutputHandle)
check.inst_param(val, 'val', StepOutputHandle)
self.step_output_map[key] = val
def build(self):
'''Builds the execution plan.
'''
# Recursively build the exeuction plan starting at the root pipeline
self._build_from_sorted_solids(
solids_in_topological_order(self.pipeline_def), self.pipeline_def.dependency_structure
)
# Construct dependency dictionary
deps = {step.key: set() for step in self._steps.values()}
for step in self._steps.values():
for step_input in step.step_inputs:
deps[step.key].update(step_input.dependency_keys)
step_dict = {step.key: step for step in self._steps.values()}
system_storage_def = self.mode_definition.get_system_storage_def(
self.environment_config.storage.system_storage_name
)
previous_run_id = self.run_config.previous_run_id
step_keys_to_execute = self.run_config.step_keys_to_execute or [
step.key for step in self._steps.values()
]
return ExecutionPlan(
self.pipeline_def,
step_dict,
deps,
system_storage_def.is_persistent,
previous_run_id,
step_keys_to_execute,
)
def _build_from_sorted_solids(
self, solids, dependency_structure, parent_handle=None, parent_step_inputs=None
):
for solid in solids:
handle = SolidHandle(solid.name, solid.definition.name, parent_handle)
### 1. INPUTS
# Create and add execution plan steps for solid inputs
step_inputs = []
for input_name, input_def in solid.definition.input_dict.items():
step_input = get_step_input(
self,
solid,
input_name,
input_def,
dependency_structure,
handle,
parent_step_inputs,
)
# If an input with runtime_type "Nothing" doesnt have a value
# we don't create a StepInput
if step_input is None:
continue
check.inst_param(step_input, 'step_input', StepInput)
step_inputs.append(step_input)
### 2a. COMPUTE FUNCTION
# Create and add execution plan step for the solid compute function
if isinstance(solid.definition, SolidDefinition):
solid_compute_step = create_compute_step(
self.pipeline_name, self.environment_config, solid, step_inputs, handle
)
self.add_step(solid_compute_step)
### 2b. RECURSE
# Recurse over the solids contained in an instance of CompositeSolidDefinition
elif isinstance(solid.definition, CompositeSolidDefinition):
self._build_from_sorted_solids(
solids_in_topological_order(solid.definition),
solid.definition.dependency_structure,
parent_handle=handle,
parent_step_inputs=step_inputs,
)
else:
check.invariant(
False,
'Unexpected solid type {type} encountered during execution planning'.format(
type=type(solid.definition)
),
)
### 3. OUTPUTS
# Create output handles for solid outputs
for name, output_def in solid.definition.output_dict.items():
output_handle = solid.output_handle(name)
# Punch through layers of composition scope to map to the output of the
# actual compute step
resolved_output_def, resolved_handle = solid.definition.resolve_output_to_origin(
output_def.name, handle
)
compute_step = self.get_step_by_handle(resolved_handle)
self.set_output_handle(
output_handle,
StepOutputHandle.from_step(compute_step, resolved_output_def.name),
)
def get_step_input(
plan_builder, solid, input_name, input_def, dependency_structure, handle, parent_step_inputs
):
check.inst_param(plan_builder, 'plan_builder', _PlanBuilder)
check.inst_param(solid, 'solid', Solid)
check.str_param(input_name, 'input_name')
check.inst_param(input_def, 'input_def', InputDefinition)
check.inst_param(dependency_structure, 'dependency_structure', DependencyStructure)
check.opt_inst_param(handle, 'handle', SolidHandle)
check.opt_list_param(parent_step_inputs, 'parent_step_inputs', of_type=StepInput)
solid_config = plan_builder.environment_config.solids.get(str(handle))
if solid_config and input_name in solid_config.inputs:
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.CONFIG,
config_data=solid_config.inputs[input_name],
)
input_handle = solid.input_handle(input_name)
if dependency_structure.has_singular_dep(input_handle):
solid_output_handle = dependency_structure.get_singular_dep(input_handle)
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.SINGLE_OUTPUT,
[plan_builder.get_output_handle(solid_output_handle)],
)
if dependency_structure.has_multi_deps(input_handle):
solid_output_handles = dependency_structure.get_multi_deps(input_handle)
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.MULTIPLE_OUTPUTS,
[
plan_builder.get_output_handle(solid_output_handle)
for solid_output_handle in solid_output_handles
],
)
if solid.container_maps_input(input_name):
parent_name = solid.container_mapped_input(input_name).definition.name
parent_inputs = {step_input.name: step_input for step_input in parent_step_inputs}
if parent_name in parent_inputs:
parent_input = parent_inputs[parent_name]
return StepInput(
input_name,
input_def.runtime_type,
parent_input.source_type,
parent_input.source_handles,
parent_input.config_data,
)
# At this point we have an input that is not hooked up to
# the output of another solid or provided via environment config.
# We will allow this for "Nothing" type inputs and continue.
if input_def.runtime_type.is_nothing:
return None
# Otherwise we throw an error.
raise DagsterInvariantViolationError(
(
'In pipeline {pipeline_name} solid {solid_name}, input {input_name} '
'must get a value either (a) from a dependency or (b) from the '
'inputs section of its configuration.'
).format(
pipeline_name=plan_builder.pipeline_name, solid_name=solid.name, input_name=input_name
)
)
class ExecutionPlan(
namedtuple(
'_ExecutionPlan',
'pipeline_def step_dict deps steps artifacts_persisted previous_run_id step_keys_to_execute',
)
):
def __new__(
cls,
pipeline_def,
step_dict,
deps,
artifacts_persisted,
previous_run_id,
step_keys_to_execute,
):
missing_steps = [step_key for step_key in step_keys_to_execute if step_key not in step_dict]
if missing_steps:
raise DagsterExecutionStepNotFoundError(
'Execution plan does not contain step{plural}: {steps}'.format(
plural='s' if len(missing_steps) > 1 else '', steps=', '.join(missing_steps)
),
step_keys=missing_steps,
)
return super(ExecutionPlan, cls).__new__(
cls,
pipeline_def=check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition),
step_dict=check.dict_param(
step_dict, 'step_dict', key_type=str, value_type=ExecutionStep
),
deps=check.dict_param(deps, 'deps', key_type=str, value_type=set),
steps=list(step_dict.values()),
artifacts_persisted=check.bool_param(artifacts_persisted, 'artifacts_persisted'),
previous_run_id=check.opt_str_param(previous_run_id, 'previous_run_id'),
step_keys_to_execute=check.list_param(
step_keys_to_execute, 'step_keys_to_execute', of_type=str
),
)
def get_step_output(self, step_output_handle):
check.inst_param(step_output_handle, 'step_output_handle', StepOutputHandle)
step = self.get_step_by_key(step_output_handle.step_key)
return step.step_output_named(step_output_handle.output_name)
def has_step(self, key):
check.str_param(key, 'key')
return key in self.step_dict
def get_step_by_key(self, key):
check.str_param(key, 'key')
return self.step_dict[key]
def topological_steps(self):
return [step for step_level in self.topological_step_levels() for step in step_level]
def topological_step_levels(self):
return [
[self.step_dict[step_key] for step_key in sorted(step_key_level)]
for step_key_level in toposort(self.deps)
]
def execution_step_levels(self):
return [
[self.step_dict[step_key] for step_key in sorted(step_key_level)]
for step_key_level in toposort(self.execution_deps())
]
def missing_steps(self):
return [step_key for step_key in self.step_keys_to_execute if not self.has_step(step_key)]
def execution_deps(self):
deps = OrderedDict()
for key in self.step_keys_to_execute:
deps[key] = set()
for key in self.step_keys_to_execute:
step = self.step_dict[key]
for step_input in step.step_inputs:
deps[step.key].update(
step_input.dependency_keys.intersection(self.step_keys_to_execute)
)
return deps
def build_subset_plan(self, step_keys_to_execute):
check.list_param(step_keys_to_execute, 'step_keys_to_execute', of_type=str)
return ExecutionPlan(
self.pipeline_def,
self.step_dict,
self.deps,
self.artifacts_persisted,
self.previous_run_id,
step_keys_to_execute,
)
def start(self, sort_key_fn=None):
return ActiveExecution(self, sort_key_fn)
@staticmethod
def build(pipeline_def, environment_config, run_config):
'''Here we build a new ExecutionPlan from a pipeline definition and the environment config.
To do this, we iterate through the pipeline's solids in topological order, and hand off the
execution steps for each solid to a companion _PlanBuilder object.
Once we've processed the entire pipeline, we invoke _PlanBuilder.build() to construct the
ExecutionPlan object.
'''
check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition)
check.inst_param(environment_config, 'environment_config', EnvironmentConfig)
check.inst_param(run_config, 'run_config', IRunConfig)
plan_builder = _PlanBuilder(pipeline_def, environment_config, run_config)
# Finally, we build and return the execution plan
return plan_builder.build()
def _default_sort_key(step):
return int(step.tags.get('dagster/priority', 0)) * -1
class ActiveExecution(object):
def __init__(self, execution_plan, sort_key_fn=None):
self._plan = check.inst_param(execution_plan, 'execution_plan', ExecutionPlan)
self._sort_key_fn = check.opt_callable_param(sort_key_fn, 'sort_key_fn', _default_sort_key)
self._pending = self._plan.execution_deps()
self._completed = set()
self._success = set()
self._failed = set()
self._skipped = set()
self._in_flight = set()
self._executable = []
self._to_skip = []
self._update()
def _update(self):
new_steps_to_execute = []
new_steps_to_skip = []
for step_key, requirements in self._pending.items():
if requirements.issubset(self._completed):
if requirements.issubset(self._success):
new_steps_to_execute.append(step_key)
else:
new_steps_to_skip.append(step_key)
for key in new_steps_to_execute:
self._executable.append(key)
del self._pending[key]
for key in new_steps_to_skip:
self._to_skip.append(key)
del self._pending[key]
def get_steps_to_execute(self, limit=None):
check.opt_int_param(limit, 'limit')
steps = sorted(
[self._plan.get_step_by_key(key) for key in self._executable], key=self._sort_key_fn
)
if limit:
steps = steps[:limit]
for step in steps:
self._in_flight.add(step.key)
self._executable.remove(step.key)
return steps
def get_steps_to_skip(self):
steps = []
steps_to_skip = list(self._to_skip)
for key in steps_to_skip:
steps.append(self._plan.get_step_by_key(key))
self._in_flight.add(key)
self._to_skip.remove(key)
return sorted(steps, key=self._sort_key_fn)
def skipped_step_events_iterator(self, pipeline_context):
failed_or_skipped_steps = self._skipped.union(self._failed)
steps_to_skip = self.get_steps_to_skip()
while steps_to_skip:
for step in steps_to_skip:
step_context = pipeline_context.for_step(step)
failed_inputs = []
for step_input in step.step_inputs:
failed_inputs.extend(
failed_or_skipped_steps.intersection(step_input.dependency_keys)
)
step_context.log.info(
'Dependencies for step {step} failed: {failed_inputs}. Not executing.'.format(
step=step.key, failed_inputs=failed_inputs
)
)
yield DagsterEvent.step_skipped_event(step_context)
self.mark_skipped(step.key)
steps_to_skip = self.get_steps_to_skip()
def mark_failed(self, step_key):
self._failed.add(step_key)
self._mark_complete(step_key)
def mark_success(self, step_key):
self._success.add(step_key)
self._mark_complete(step_key)
def mark_skipped(self, step_key):
self._skipped.add(step_key)
self._mark_complete(step_key)
def _mark_complete(self, step_key):
check.invariant(
step_key not in self._completed,
'Attempted to mark step {} as complete that was already completed'.format(step_key),
)
check.invariant(
step_key in self._in_flight,
'Attempted to mark step {} as complete that was not known to be in flight'.format(
step_key
),
)
self._in_flight.remove(step_key)
self._completed.add(step_key)
self._update()
def handle_event(self, dagster_event):
check.inst_param(dagster_event, 'dagster_event', DagsterEvent)
if dagster_event.is_step_failure:
self.mark_failed(dagster_event.step_key)
elif dagster_event.is_step_success:
self.mark_success(dagster_event.step_key)
def verify_complete(self, pipeline_context, step_key):
if step_key in self._in_flight:
pipeline_context.log.error(
'Step {key} finished without success or failure event, assuming failure.'.format(
key=step_key
)
)
self.mark_failed(step_key)
@property
def is_complete(self):
return (
len(self._pending) == 0
and len(self._in_flight) == 0
and len(self._executable) == 0
and len(self._to_skip) == 0
)
| 37.105364 | 101 | 0.637978 | from collections import OrderedDict, namedtuple
from dagster import check
from dagster.core.definitions import (
CompositeSolidDefinition,
InputDefinition,
PipelineDefinition,
Solid,
SolidDefinition,
SolidHandle,
SolidOutputHandle,
solids_in_topological_order,
)
from dagster.core.definitions.dependency import DependencyStructure
from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvariantViolationError
from dagster.core.events import DagsterEvent
from dagster.core.execution.config import IRunConfig
from dagster.core.system_config.objects import EnvironmentConfig
from dagster.core.utils import toposort
from .compute import create_compute_step
from .objects import ExecutionStep, StepInput, StepInputSourceType, StepOutputHandle
class _PlanBuilder(object):
def __init__(self, pipeline_def, environment_config, run_config):
self.pipeline_def = check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition)
self.environment_config = check.inst_param(
environment_config, 'environment_config', EnvironmentConfig
)
self.run_config = check.inst_param(run_config, 'run_config', IRunConfig)
self.mode_definition = pipeline_def.get_mode_definition(run_config.mode)
self._steps = OrderedDict()
self.step_output_map = dict()
self._seen_keys = set()
@property
def pipeline_name(self):
return self.pipeline_def.name
def add_step(self, step):
if step.key in self._seen_keys:
keys = [s.key for s in self._steps]
check.failed(
'Duplicated key {key}. Full list seen so far: {key_list}.'.format(
key=step.key, key_list=keys
)
)
self._seen_keys.add(step.key)
self._steps[step.solid_handle.to_string()] = step
def add_steps(self, steps):
for step in steps:
self.add_step(step)
def get_step_by_handle(self, handle):
check.inst_param(handle, 'handle', SolidHandle)
return self._steps[handle.to_string()]
def get_output_handle(self, key):
check.inst_param(key, 'key', SolidOutputHandle)
return self.step_output_map[key]
def set_output_handle(self, key, val):
check.inst_param(key, 'key', SolidOutputHandle)
check.inst_param(val, 'val', StepOutputHandle)
self.step_output_map[key] = val
def build(self):
self._build_from_sorted_solids(
solids_in_topological_order(self.pipeline_def), self.pipeline_def.dependency_structure
)
deps = {step.key: set() for step in self._steps.values()}
for step in self._steps.values():
for step_input in step.step_inputs:
deps[step.key].update(step_input.dependency_keys)
step_dict = {step.key: step for step in self._steps.values()}
system_storage_def = self.mode_definition.get_system_storage_def(
self.environment_config.storage.system_storage_name
)
previous_run_id = self.run_config.previous_run_id
step_keys_to_execute = self.run_config.step_keys_to_execute or [
step.key for step in self._steps.values()
]
return ExecutionPlan(
self.pipeline_def,
step_dict,
deps,
system_storage_def.is_persistent,
previous_run_id,
step_keys_to_execute,
)
def _build_from_sorted_solids(
self, solids, dependency_structure, parent_handle=None, parent_step_inputs=None
):
for solid in solids:
handle = SolidHandle(solid.name, solid.definition.name, parent_handle)
step_inputs = []
for input_name, input_def in solid.definition.input_dict.items():
step_input = get_step_input(
self,
solid,
input_name,
input_def,
dependency_structure,
handle,
parent_step_inputs,
)
if step_input is None:
continue
check.inst_param(step_input, 'step_input', StepInput)
step_inputs.append(step_input)
### 2a. COMPUTE FUNCTION
# Create and add execution plan step for the solid compute function
if isinstance(solid.definition, SolidDefinition):
solid_compute_step = create_compute_step(
self.pipeline_name, self.environment_config, solid, step_inputs, handle
)
self.add_step(solid_compute_step)
### 2b. RECURSE
# Recurse over the solids contained in an instance of CompositeSolidDefinition
elif isinstance(solid.definition, CompositeSolidDefinition):
self._build_from_sorted_solids(
solids_in_topological_order(solid.definition),
solid.definition.dependency_structure,
parent_handle=handle,
parent_step_inputs=step_inputs,
)
else:
check.invariant(
False,
'Unexpected solid type {type} encountered during execution planning'.format(
type=type(solid.definition)
),
)
### 3. OUTPUTS
# Create output handles for solid outputs
for name, output_def in solid.definition.output_dict.items():
output_handle = solid.output_handle(name)
# Punch through layers of composition scope to map to the output of the
# actual compute step
resolved_output_def, resolved_handle = solid.definition.resolve_output_to_origin(
output_def.name, handle
)
compute_step = self.get_step_by_handle(resolved_handle)
self.set_output_handle(
output_handle,
StepOutputHandle.from_step(compute_step, resolved_output_def.name),
)
def get_step_input(
plan_builder, solid, input_name, input_def, dependency_structure, handle, parent_step_inputs
):
check.inst_param(plan_builder, 'plan_builder', _PlanBuilder)
check.inst_param(solid, 'solid', Solid)
check.str_param(input_name, 'input_name')
check.inst_param(input_def, 'input_def', InputDefinition)
check.inst_param(dependency_structure, 'dependency_structure', DependencyStructure)
check.opt_inst_param(handle, 'handle', SolidHandle)
check.opt_list_param(parent_step_inputs, 'parent_step_inputs', of_type=StepInput)
solid_config = plan_builder.environment_config.solids.get(str(handle))
if solid_config and input_name in solid_config.inputs:
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.CONFIG,
config_data=solid_config.inputs[input_name],
)
input_handle = solid.input_handle(input_name)
if dependency_structure.has_singular_dep(input_handle):
solid_output_handle = dependency_structure.get_singular_dep(input_handle)
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.SINGLE_OUTPUT,
[plan_builder.get_output_handle(solid_output_handle)],
)
if dependency_structure.has_multi_deps(input_handle):
solid_output_handles = dependency_structure.get_multi_deps(input_handle)
return StepInput(
input_name,
input_def.runtime_type,
StepInputSourceType.MULTIPLE_OUTPUTS,
[
plan_builder.get_output_handle(solid_output_handle)
for solid_output_handle in solid_output_handles
],
)
if solid.container_maps_input(input_name):
parent_name = solid.container_mapped_input(input_name).definition.name
parent_inputs = {step_input.name: step_input for step_input in parent_step_inputs}
if parent_name in parent_inputs:
parent_input = parent_inputs[parent_name]
return StepInput(
input_name,
input_def.runtime_type,
parent_input.source_type,
parent_input.source_handles,
parent_input.config_data,
)
# At this point we have an input that is not hooked up to
# the output of another solid or provided via environment config.
# We will allow this for "Nothing" type inputs and continue.
if input_def.runtime_type.is_nothing:
return None
# Otherwise we throw an error.
raise DagsterInvariantViolationError(
(
'In pipeline {pipeline_name} solid {solid_name}, input {input_name} '
'must get a value either (a) from a dependency or (b) from the '
'inputs section of its configuration.'
).format(
pipeline_name=plan_builder.pipeline_name, solid_name=solid.name, input_name=input_name
)
)
class ExecutionPlan(
namedtuple(
'_ExecutionPlan',
'pipeline_def step_dict deps steps artifacts_persisted previous_run_id step_keys_to_execute',
)
):
def __new__(
cls,
pipeline_def,
step_dict,
deps,
artifacts_persisted,
previous_run_id,
step_keys_to_execute,
):
missing_steps = [step_key for step_key in step_keys_to_execute if step_key not in step_dict]
if missing_steps:
raise DagsterExecutionStepNotFoundError(
'Execution plan does not contain step{plural}: {steps}'.format(
plural='s' if len(missing_steps) > 1 else '', steps=', '.join(missing_steps)
),
step_keys=missing_steps,
)
return super(ExecutionPlan, cls).__new__(
cls,
pipeline_def=check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition),
step_dict=check.dict_param(
step_dict, 'step_dict', key_type=str, value_type=ExecutionStep
),
deps=check.dict_param(deps, 'deps', key_type=str, value_type=set),
steps=list(step_dict.values()),
artifacts_persisted=check.bool_param(artifacts_persisted, 'artifacts_persisted'),
previous_run_id=check.opt_str_param(previous_run_id, 'previous_run_id'),
step_keys_to_execute=check.list_param(
step_keys_to_execute, 'step_keys_to_execute', of_type=str
),
)
def get_step_output(self, step_output_handle):
check.inst_param(step_output_handle, 'step_output_handle', StepOutputHandle)
step = self.get_step_by_key(step_output_handle.step_key)
return step.step_output_named(step_output_handle.output_name)
def has_step(self, key):
check.str_param(key, 'key')
return key in self.step_dict
def get_step_by_key(self, key):
check.str_param(key, 'key')
return self.step_dict[key]
def topological_steps(self):
return [step for step_level in self.topological_step_levels() for step in step_level]
def topological_step_levels(self):
return [
[self.step_dict[step_key] for step_key in sorted(step_key_level)]
for step_key_level in toposort(self.deps)
]
def execution_step_levels(self):
return [
[self.step_dict[step_key] for step_key in sorted(step_key_level)]
for step_key_level in toposort(self.execution_deps())
]
def missing_steps(self):
return [step_key for step_key in self.step_keys_to_execute if not self.has_step(step_key)]
def execution_deps(self):
deps = OrderedDict()
for key in self.step_keys_to_execute:
deps[key] = set()
for key in self.step_keys_to_execute:
step = self.step_dict[key]
for step_input in step.step_inputs:
deps[step.key].update(
step_input.dependency_keys.intersection(self.step_keys_to_execute)
)
return deps
def build_subset_plan(self, step_keys_to_execute):
check.list_param(step_keys_to_execute, 'step_keys_to_execute', of_type=str)
return ExecutionPlan(
self.pipeline_def,
self.step_dict,
self.deps,
self.artifacts_persisted,
self.previous_run_id,
step_keys_to_execute,
)
def start(self, sort_key_fn=None):
return ActiveExecution(self, sort_key_fn)
@staticmethod
def build(pipeline_def, environment_config, run_config):
check.inst_param(pipeline_def, 'pipeline_def', PipelineDefinition)
check.inst_param(environment_config, 'environment_config', EnvironmentConfig)
check.inst_param(run_config, 'run_config', IRunConfig)
plan_builder = _PlanBuilder(pipeline_def, environment_config, run_config)
# Finally, we build and return the execution plan
return plan_builder.build()
def _default_sort_key(step):
return int(step.tags.get('dagster/priority', 0)) * -1
class ActiveExecution(object):
def __init__(self, execution_plan, sort_key_fn=None):
self._plan = check.inst_param(execution_plan, 'execution_plan', ExecutionPlan)
self._sort_key_fn = check.opt_callable_param(sort_key_fn, 'sort_key_fn', _default_sort_key)
self._pending = self._plan.execution_deps()
self._completed = set()
self._success = set()
self._failed = set()
self._skipped = set()
self._in_flight = set()
self._executable = []
self._to_skip = []
self._update()
def _update(self):
new_steps_to_execute = []
new_steps_to_skip = []
for step_key, requirements in self._pending.items():
if requirements.issubset(self._completed):
if requirements.issubset(self._success):
new_steps_to_execute.append(step_key)
else:
new_steps_to_skip.append(step_key)
for key in new_steps_to_execute:
self._executable.append(key)
del self._pending[key]
for key in new_steps_to_skip:
self._to_skip.append(key)
del self._pending[key]
def get_steps_to_execute(self, limit=None):
check.opt_int_param(limit, 'limit')
steps = sorted(
[self._plan.get_step_by_key(key) for key in self._executable], key=self._sort_key_fn
)
if limit:
steps = steps[:limit]
for step in steps:
self._in_flight.add(step.key)
self._executable.remove(step.key)
return steps
def get_steps_to_skip(self):
steps = []
steps_to_skip = list(self._to_skip)
for key in steps_to_skip:
steps.append(self._plan.get_step_by_key(key))
self._in_flight.add(key)
self._to_skip.remove(key)
return sorted(steps, key=self._sort_key_fn)
def skipped_step_events_iterator(self, pipeline_context):
failed_or_skipped_steps = self._skipped.union(self._failed)
steps_to_skip = self.get_steps_to_skip()
while steps_to_skip:
for step in steps_to_skip:
step_context = pipeline_context.for_step(step)
failed_inputs = []
for step_input in step.step_inputs:
failed_inputs.extend(
failed_or_skipped_steps.intersection(step_input.dependency_keys)
)
step_context.log.info(
'Dependencies for step {step} failed: {failed_inputs}. Not executing.'.format(
step=step.key, failed_inputs=failed_inputs
)
)
yield DagsterEvent.step_skipped_event(step_context)
self.mark_skipped(step.key)
steps_to_skip = self.get_steps_to_skip()
def mark_failed(self, step_key):
self._failed.add(step_key)
self._mark_complete(step_key)
def mark_success(self, step_key):
self._success.add(step_key)
self._mark_complete(step_key)
def mark_skipped(self, step_key):
self._skipped.add(step_key)
self._mark_complete(step_key)
def _mark_complete(self, step_key):
check.invariant(
step_key not in self._completed,
'Attempted to mark step {} as complete that was already completed'.format(step_key),
)
check.invariant(
step_key in self._in_flight,
'Attempted to mark step {} as complete that was not known to be in flight'.format(
step_key
),
)
self._in_flight.remove(step_key)
self._completed.add(step_key)
self._update()
def handle_event(self, dagster_event):
check.inst_param(dagster_event, 'dagster_event', DagsterEvent)
if dagster_event.is_step_failure:
self.mark_failed(dagster_event.step_key)
elif dagster_event.is_step_success:
self.mark_success(dagster_event.step_key)
def verify_complete(self, pipeline_context, step_key):
if step_key in self._in_flight:
pipeline_context.log.error(
'Step {key} finished without success or failure event, assuming failure.'.format(
key=step_key
)
)
self.mark_failed(step_key)
@property
def is_complete(self):
return (
len(self._pending) == 0
and len(self._in_flight) == 0
and len(self._executable) == 0
and len(self._to_skip) == 0
)
| true | true |
f729abb2c37355f319be5ae669bdd8b7a80e4d4d | 319 | py | Python | abc/abc071/abc071c.py | c-yan/atcoder | 940e49d576e6a2d734288fadaf368e486480a948 | [
"MIT"
] | 1 | 2019-08-21T00:49:34.000Z | 2019-08-21T00:49:34.000Z | abc/abc071/abc071c.py | c-yan/atcoder | 940e49d576e6a2d734288fadaf368e486480a948 | [
"MIT"
] | null | null | null | abc/abc071/abc071c.py | c-yan/atcoder | 940e49d576e6a2d734288fadaf368e486480a948 | [
"MIT"
] | null | null | null | N = int(input())
A = list(map(int, input().split()))
d = {}
for a in A:
if a in d:
d[a] += 1
else:
d[a] = 1
l = [k for k in d if d[k] >= 2]
l.sort(reverse=True)
if len(l) == 0:
print(0)
elif d[l[0]] >= 4:
print(l[0] * l[0])
elif len(l) == 1:
print(0)
else:
print(l[0] * l[1])
| 14.5 | 35 | 0.445141 | N = int(input())
A = list(map(int, input().split()))
d = {}
for a in A:
if a in d:
d[a] += 1
else:
d[a] = 1
l = [k for k in d if d[k] >= 2]
l.sort(reverse=True)
if len(l) == 0:
print(0)
elif d[l[0]] >= 4:
print(l[0] * l[0])
elif len(l) == 1:
print(0)
else:
print(l[0] * l[1])
| true | true |
f729ac1de2fc1a7a1e1b398358b94fb1a3d086d6 | 426 | py | Python | connection.py | TheSecEng/sublime-plugin | 8e43a175c7a282eb280e25ce73ddf2350a9adce7 | [
"MIT"
] | null | null | null | connection.py | TheSecEng/sublime-plugin | 8e43a175c7a282eb280e25ce73ddf2350a9adce7 | [
"MIT"
] | null | null | null | connection.py | TheSecEng/sublime-plugin | 8e43a175c7a282eb280e25ce73ddf2350a9adce7 | [
"MIT"
] | null | null | null | import socket
def is_connected_to_internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
return True
except socket.error:
return False
| 25.058824 | 68 | 0.615023 | import socket
def is_connected_to_internet(host="8.8.8.8", port=53, timeout=3):
try:
socket.setdefaulttimeout(timeout)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
return True
except socket.error:
return False
| true | true |
f729ac421d7edd47d6be3e8d0273f0f1e4a9da15 | 2,514 | py | Python | setup.py | e-kwsm/pycparser | 6a7edee64c13d06e02b5eef554d9d6d10dcb71c0 | [
"BSD-3-Clause"
] | 1 | 2021-12-17T18:09:48.000Z | 2021-12-17T18:09:48.000Z | setup.py | e-kwsm/pycparser | 6a7edee64c13d06e02b5eef554d9d6d10dcb71c0 | [
"BSD-3-Clause"
] | null | null | null | setup.py | e-kwsm/pycparser | 6a7edee64c13d06e02b5eef554d9d6d10dcb71c0 | [
"BSD-3-Clause"
] | null | null | null | import os, sys
try:
from setuptools import setup
from setuptools.command.install import install as _install
from setuptools.command.sdist import sdist as _sdist
except ImportError:
from distutils.core import setup
from distutils.command.install import install as _install
from distutils.command.sdist import sdist as _sdist
def _run_build_tables(dir):
from subprocess import check_call
# This is run inside the install staging directory (that had no .pyc files)
# We don't want to generate any.
# https://github.com/eliben/pycparser/pull/135
check_call([sys.executable, '-B', '_build_tables.py'],
cwd=os.path.join(dir, 'pycparser'))
class install(_install):
def run(self):
_install.run(self)
self.execute(_run_build_tables, (self.install_lib,),
msg="Build the lexing/parsing tables")
class sdist(_sdist):
def make_release_tree(self, basedir, files):
_sdist.make_release_tree(self, basedir, files)
self.execute(_run_build_tables, (basedir,),
msg="Build the lexing/parsing tables")
setup(
# metadata
name='pycparser',
description='C parser in Python',
long_description="""
pycparser is a complete parser of the C language, written in
pure Python using the PLY parsing library.
It parses C code into an AST and can serve as a front-end for
C compilers or analysis tools.
""",
license='BSD',
version='2.21',
author='Eli Bendersky',
maintainer='Eli Bendersky',
author_email='eliben@gmail.com',
url='https://github.com/eliben/pycparser',
platforms='Cross Platform',
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
packages=['pycparser', 'pycparser.ply'],
package_data={'pycparser': ['*.cfg']},
cmdclass={'install': install, 'sdist': sdist},
)
| 35.408451 | 79 | 0.63564 | import os, sys
try:
from setuptools import setup
from setuptools.command.install import install as _install
from setuptools.command.sdist import sdist as _sdist
except ImportError:
from distutils.core import setup
from distutils.command.install import install as _install
from distutils.command.sdist import sdist as _sdist
def _run_build_tables(dir):
from subprocess import check_call
# https://github.com/eliben/pycparser/pull/135
check_call([sys.executable, '-B', '_build_tables.py'],
cwd=os.path.join(dir, 'pycparser'))
class install(_install):
def run(self):
_install.run(self)
self.execute(_run_build_tables, (self.install_lib,),
msg="Build the lexing/parsing tables")
class sdist(_sdist):
def make_release_tree(self, basedir, files):
_sdist.make_release_tree(self, basedir, files)
self.execute(_run_build_tables, (basedir,),
msg="Build the lexing/parsing tables")
setup(
# metadata
name='pycparser',
description='C parser in Python',
long_description="""
pycparser is a complete parser of the C language, written in
pure Python using the PLY parsing library.
It parses C code into an AST and can serve as a front-end for
C compilers or analysis tools.
""",
license='BSD',
version='2.21',
author='Eli Bendersky',
maintainer='Eli Bendersky',
author_email='eliben@gmail.com',
url='https://github.com/eliben/pycparser',
platforms='Cross Platform',
classifiers = [
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
packages=['pycparser', 'pycparser.ply'],
package_data={'pycparser': ['*.cfg']},
cmdclass={'install': install, 'sdist': sdist},
)
| true | true |
f729ad89a37e5cbad0f081cfbdab0db516548f03 | 2,116 | py | Python | app/demo-loop/simple-driver.py | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | app/demo-loop/simple-driver.py | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | app/demo-loop/simple-driver.py | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 UT-Battelle, LLC and other Celeritas Developers.
# See the top-level COPYRIGHT file for details.
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""
"""
import json
import subprocess
from os import environ, path
from sys import exit, argv
try:
geometry_filename = argv[1]
hepmc3_filename = argv[2]
except (IndexError, TypeError):
print("usage: {} inp.gdml inp.hepmc3".format(argv[0]))
exit(2)
geant_exp_exe = environ.get('CELERITAS_GEANT_EXPORTER_EXE', './geant-exporter')
physics_filename = path.basename(geometry_filename) + ".root"
result_ge = subprocess.run([geant_exp_exe,
geometry_filename,
physics_filename])
if result_ge.returncode:
print("fatal: geant-exporter failed with error", result_ge.returncode)
exit(result_ge.returncode)
inp = {
'run': {
'geometry_filename': geometry_filename,
'physics_filename': physics_filename,
'hepmc3_filename': hepmc3_filename,
'seed': 12345,
'max_num_tracks': 128 * 32,
'max_steps': 128,
'storage_factor': 10
}
}
exe = environ.get('CELERITAS_DEMO_EXE', './demo-loop')
print("Input:")
with open(f'{exe}.inp.json', 'w') as f:
json.dump(inp, f, indent=1)
print(json.dumps(inp, indent=1))
print("Running", exe)
result = subprocess.run([exe, '-'],
input=json.dumps(inp).encode(),
stdout=subprocess.PIPE)
if result.returncode:
print("fatal: run failed with error", result.returncode)
exit(result.returncode)
print("Received {} bytes of data".format(len(result.stdout)))
out_text = result.stdout.decode()
# Filter out spurious HepMC3 output
out_text = out_text[out_text.find('\n{') + 1:]
try:
result = json.loads(out_text)
except json.decoder.JSONDecodeError as e:
print("error: expected a JSON object but got the following stdout:")
print(out_text)
print("fatal:", str(e))
exit(1)
print(json.dumps(result, indent=1))
with open(f'{exe}.out.json', 'w') as f:
json.dump(result, f)
| 28.986301 | 79 | 0.6569 |
import json
import subprocess
from os import environ, path
from sys import exit, argv
try:
geometry_filename = argv[1]
hepmc3_filename = argv[2]
except (IndexError, TypeError):
print("usage: {} inp.gdml inp.hepmc3".format(argv[0]))
exit(2)
geant_exp_exe = environ.get('CELERITAS_GEANT_EXPORTER_EXE', './geant-exporter')
physics_filename = path.basename(geometry_filename) + ".root"
result_ge = subprocess.run([geant_exp_exe,
geometry_filename,
physics_filename])
if result_ge.returncode:
print("fatal: geant-exporter failed with error", result_ge.returncode)
exit(result_ge.returncode)
inp = {
'run': {
'geometry_filename': geometry_filename,
'physics_filename': physics_filename,
'hepmc3_filename': hepmc3_filename,
'seed': 12345,
'max_num_tracks': 128 * 32,
'max_steps': 128,
'storage_factor': 10
}
}
exe = environ.get('CELERITAS_DEMO_EXE', './demo-loop')
print("Input:")
with open(f'{exe}.inp.json', 'w') as f:
json.dump(inp, f, indent=1)
print(json.dumps(inp, indent=1))
print("Running", exe)
result = subprocess.run([exe, '-'],
input=json.dumps(inp).encode(),
stdout=subprocess.PIPE)
if result.returncode:
print("fatal: run failed with error", result.returncode)
exit(result.returncode)
print("Received {} bytes of data".format(len(result.stdout)))
out_text = result.stdout.decode()
out_text = out_text[out_text.find('\n{') + 1:]
try:
result = json.loads(out_text)
except json.decoder.JSONDecodeError as e:
print("error: expected a JSON object but got the following stdout:")
print(out_text)
print("fatal:", str(e))
exit(1)
print(json.dumps(result, indent=1))
with open(f'{exe}.out.json', 'w') as f:
json.dump(result, f)
| true | true |
f729ada05669b3054ed1527cbed4b6ad46e8f79c | 2,233 | py | Python | pysnark/zkinterface/Witness.py | gxavier38/pysnark | 8a2a571bef430783adf8fe28cb8bb0b0bf8a7c94 | [
"Cube"
] | 94 | 2019-05-21T09:36:58.000Z | 2022-03-25T12:27:54.000Z | pysnark/zkinterface/Witness.py | gxavier38/pysnark | 8a2a571bef430783adf8fe28cb8bb0b0bf8a7c94 | [
"Cube"
] | 32 | 2019-11-12T09:59:46.000Z | 2021-12-04T17:53:14.000Z | pysnark/zkinterface/Witness.py | gxavier38/pysnark | 8a2a571bef430783adf8fe28cb8bb0b0bf8a7c94 | [
"Cube"
] | 13 | 2020-01-02T11:01:17.000Z | 2021-10-02T11:07:11.000Z | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: zkinterface
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
# Witness represents an assignment of values to variables.
#
# - Does not include variables already given in `CircuitHeader.instance_variables`.
# - Does not include the constant one variable.
# - Multiple such messages are equivalent to the concatenation of `Variables` arrays.
class Witness(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Witness()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsWitness(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
@classmethod
def WitnessBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x7A\x6B\x69\x66", size_prefixed=size_prefixed)
# Witness
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# Witness
def AssignedVariables(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from zkinterface.Variables import Variables
obj = Variables()
obj.Init(self._tab.Bytes, x)
return obj
return None
def Start(builder): builder.StartObject(1)
def WitnessStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder)
def AddAssignedVariables(builder, assignedVariables): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(assignedVariables), 0)
def WitnessAddAssignedVariables(builder, assignedVariables):
"""This method is deprecated. Please switch to AddAssignedVariables."""
return AddAssignedVariables(builder, assignedVariables)
def End(builder): return builder.EndObject()
def WitnessEnd(builder):
"""This method is deprecated. Please switch to End."""
return End(builder) | 38.5 | 162 | 0.712942 |
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class Witness(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Witness()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsWitness(cls, buf, offset=0):
return cls.GetRootAs(buf, offset)
@classmethod
def WitnessBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x7A\x6B\x69\x66", size_prefixed=size_prefixed)
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
def AssignedVariables(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
from zkinterface.Variables import Variables
obj = Variables()
obj.Init(self._tab.Bytes, x)
return obj
return None
def Start(builder): builder.StartObject(1)
def WitnessStart(builder):
return Start(builder)
def AddAssignedVariables(builder, assignedVariables): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(assignedVariables), 0)
def WitnessAddAssignedVariables(builder, assignedVariables):
return AddAssignedVariables(builder, assignedVariables)
def End(builder): return builder.EndObject()
def WitnessEnd(builder):
return End(builder) | true | true |
f729addb6dfc9ae31296930efdcf62790ae8656f | 9,337 | py | Python | demos/smartlab_demo/python/segmentor.py | AlexKoff88/open_model_zoo | 8944a46653427cfa53db10fa91d677826adf31e1 | [
"Apache-2.0"
] | null | null | null | demos/smartlab_demo/python/segmentor.py | AlexKoff88/open_model_zoo | 8944a46653427cfa53db10fa91d677826adf31e1 | [
"Apache-2.0"
] | null | null | null | demos/smartlab_demo/python/segmentor.py | AlexKoff88/open_model_zoo | 8944a46653427cfa53db10fa91d677826adf31e1 | [
"Apache-2.0"
] | null | null | null | """
Copyright (C) 2021-2022 Intel Corporation
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 cv2
import numpy as np
import logging as log
from pathlib import Path
from scipy.special import softmax
from openvino.runtime import PartialShape
class SegmentorMstcn:
def __init__(self, ie, device, i3d_path, mstcn_path):
self.ActionTerms = [
"background",
"noise_action",
"remove_support_sleeve",
"remove_pointer_sleeve",
"adjust_rider",
"adjust_nut",
"adjust_balancing",
"open_box",
"close_box",
"choose_weight",
"put_left",
"put_right",
"take_left",
"take_right",
"install_support_sleeve",
"install_pointer_sleeve",
]
self.EmbedBufferTop = np.zeros((1024, 0))
self.EmbedBufferFront = np.zeros((1024, 0))
self.ImgSizeHeight = 224
self.ImgSizeWidth = 224
self.EmbedBatchSize = 1
self.SegBatchSize = 24
self.EmbedWindowLength = 16
self.EmbedWindowStride = 1
self.EmbedWindowAtrous = 3
self.TemporalLogits = np.zeros((0, len(self.ActionTerms)))
net = ie.read_model(i3d_path)
net.reshape({net.inputs[0]: PartialShape(
[self.EmbedBatchSize, self.EmbedWindowLength, self.ImgSizeHeight, self.ImgSizeWidth, 3])})
nodes = net.get_ops()
net.add_outputs(nodes[13].output(0))
self.i3d = ie.compile_model(model=net, device_name=device)
self.mstcn_net = ie.read_model(mstcn_path)
self.mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)
self.mstcn_input_keys = self.mstcn.inputs
self.mstcn_output_key = self.mstcn.outputs
self.mstcn_net.reshape({'input': PartialShape([1, 2048, 1])})
self.reshape_mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)
file_path = Path(__file__).parent / 'init_his.npz'
init_his_feature = np.load(file_path)
self.his_fea = {f'fhis_in_{i}': init_his_feature[f'arr_{i}'] for i in range(4)}
def inference(self, buffer_top, buffer_front, frame_index):
"""
Args:
buffer_top: buffers of the input image arrays for the top view
buffer_front: buffers of the input image arrays for the front view
frame_index: frame index of the latest frame
Returns: the temporal prediction results for each frame (including the historical predictions),
length of predictions == frame_index()
"""
### run encoder ###
self.EmbedBufferTop = self.feature_embedding(
img_buffer=buffer_top,
embedding_buffer=self.EmbedBufferTop,
frame_index=frame_index)
self.EmbedBufferFront = self.feature_embedding(
img_buffer=buffer_front,
embedding_buffer=self.EmbedBufferFront,
frame_index=frame_index)
### run mstcn++ only batch size 1###
if min(self.EmbedBufferTop.shape[-1], self.EmbedBufferFront.shape[-1]) > 0:
self.action_segmentation()
# ### get label ###
valid_index = self.TemporalLogits.shape[0]
if valid_index == 0:
return []
else:
frame_predictions = [self.ActionTerms[i] for i in np.argmax(self.TemporalLogits, axis=1)]
frame_predictions = ["background" for i in range(self.EmbedWindowLength - 1)] + frame_predictions
return frame_predictions[-1]
def feature_embedding(self, img_buffer, embedding_buffer, frame_index):
# minimal temporal length for processor
min_t = (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous
infer_request = self.i3d.create_infer_request()
if frame_index > min_t:
num_embedding = embedding_buffer.shape[-1]
img_buffer = list(img_buffer)
curr_t = self.EmbedWindowStride * num_embedding + (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous
while curr_t < frame_index:
# absolute index in temporal shaft
start_index = self.EmbedWindowStride * num_embedding
if frame_index > len(img_buffer):
# absolute index in buffer shaft
start_index = start_index - (frame_index - len(img_buffer))
input_data = [
[cv2.resize(img_buffer[start_index + i * self.EmbedWindowAtrous],
(self.ImgSizeHeight, self.ImgSizeWidth)) for i in range(self.EmbedWindowLength)]
for j in range(self.EmbedBatchSize)]
input_data = np.asarray(input_data).transpose((0, 4, 1, 2, 3))
input_data = input_data * 127.5 + 127.5
input_dict = {self.i3d.inputs[0]: input_data}
out_logits = infer_request.infer(input_dict)[self.i3d.outputs[1]]
out_logits = out_logits.squeeze((0, 3, 4))
# ndarray: C x num_embedding
embedding_buffer = np.concatenate((embedding_buffer, out_logits), axis=1)
curr_t += self.EmbedWindowStride
return embedding_buffer
def action_segmentation(self):
# read buffer
embed_buffer_top = self.EmbedBufferTop
embed_buffer_front = self.EmbedBufferFront
batch_size = self.SegBatchSize
start_index = self.TemporalLogits.shape[0]
end_index = min(embed_buffer_top.shape[-1], embed_buffer_front.shape[-1])
num_batch = (end_index - start_index) // batch_size
infer_request = self.reshape_mstcn.create_infer_request()
if num_batch < 0:
log.debug("Waiting for the next frame ...")
elif num_batch == 0:
log.debug(f"start_index: {start_index} end_index: {end_index}")
unit1 = embed_buffer_top[:, start_index:end_index]
unit2 = embed_buffer_front[:, start_index:end_index]
feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)
input_mstcn = np.expand_dims(feature_unit, 0)
feed_dict = {}
if len(self.his_fea) != 0:
for key in self.mstcn_input_keys:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
feed_dict[string] = self.his_fea[string]
feed_dict['input'] = input_mstcn
if input_mstcn.shape == (1, 2048, 1):
out = infer_request.infer(feed_dict)
predictions = out[list(out.keys())[-1]]
for key in self.mstcn_output_key:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
self.his_fea[string] = out[string]
"""
predictions --> 4x1x64x24
his_fea --> [12*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048]]
"""
temporal_logits = predictions[:, :, :len(self.ActionTerms), :] # 4x1x16xN
temporal_logits = softmax(temporal_logits[-1], 1) # 1x16xN
temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)
self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)
else:
for batch_idx in range(num_batch):
unit1 = embed_buffer_top[:,
start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]
unit2 = embed_buffer_front[:,
start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]
feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)
feed_dict = {}
if len(self.his_fea) != 0:
for key in self.mstcn_input_keys:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
feed_dict[key] = self.his_fea[string]
feed_dict['input'] = feature_unit
out = infer_request.infer(feed_dict)
predictions = out[list(out.keys())[-1]]
for key in self.mstcn_output_key:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
self.his_fea[string] = out[string]
temporal_logits = predictions[:, :, :len(self.ActionTerms), :] # 4x1x16xN
temporal_logits = softmax(temporal_logits[-1], 1) # 1x16xN
temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)
self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)
| 44.674641 | 115 | 0.601264 |
import cv2
import numpy as np
import logging as log
from pathlib import Path
from scipy.special import softmax
from openvino.runtime import PartialShape
class SegmentorMstcn:
def __init__(self, ie, device, i3d_path, mstcn_path):
self.ActionTerms = [
"background",
"noise_action",
"remove_support_sleeve",
"remove_pointer_sleeve",
"adjust_rider",
"adjust_nut",
"adjust_balancing",
"open_box",
"close_box",
"choose_weight",
"put_left",
"put_right",
"take_left",
"take_right",
"install_support_sleeve",
"install_pointer_sleeve",
]
self.EmbedBufferTop = np.zeros((1024, 0))
self.EmbedBufferFront = np.zeros((1024, 0))
self.ImgSizeHeight = 224
self.ImgSizeWidth = 224
self.EmbedBatchSize = 1
self.SegBatchSize = 24
self.EmbedWindowLength = 16
self.EmbedWindowStride = 1
self.EmbedWindowAtrous = 3
self.TemporalLogits = np.zeros((0, len(self.ActionTerms)))
net = ie.read_model(i3d_path)
net.reshape({net.inputs[0]: PartialShape(
[self.EmbedBatchSize, self.EmbedWindowLength, self.ImgSizeHeight, self.ImgSizeWidth, 3])})
nodes = net.get_ops()
net.add_outputs(nodes[13].output(0))
self.i3d = ie.compile_model(model=net, device_name=device)
self.mstcn_net = ie.read_model(mstcn_path)
self.mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)
self.mstcn_input_keys = self.mstcn.inputs
self.mstcn_output_key = self.mstcn.outputs
self.mstcn_net.reshape({'input': PartialShape([1, 2048, 1])})
self.reshape_mstcn = ie.compile_model(model=self.mstcn_net, device_name=device)
file_path = Path(__file__).parent / 'init_his.npz'
init_his_feature = np.load(file_path)
self.his_fea = {f'fhis_in_{i}': init_his_feature[f'arr_{i}'] for i in range(4)}
def inference(self, buffer_top, buffer_front, frame_index):
re_embedding(
img_buffer=buffer_top,
embedding_buffer=self.EmbedBufferTop,
frame_index=frame_index)
self.EmbedBufferFront = self.feature_embedding(
img_buffer=buffer_front,
embedding_buffer=self.EmbedBufferFront,
frame_index=frame_index)
-1]) > 0:
self.action_segmentation()
if valid_index == 0:
return []
else:
frame_predictions = [self.ActionTerms[i] for i in np.argmax(self.TemporalLogits, axis=1)]
frame_predictions = ["background" for i in range(self.EmbedWindowLength - 1)] + frame_predictions
return frame_predictions[-1]
def feature_embedding(self, img_buffer, embedding_buffer, frame_index):
min_t = (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous
infer_request = self.i3d.create_infer_request()
if frame_index > min_t:
num_embedding = embedding_buffer.shape[-1]
img_buffer = list(img_buffer)
curr_t = self.EmbedWindowStride * num_embedding + (self.EmbedWindowLength - 1) * self.EmbedWindowAtrous
while curr_t < frame_index:
start_index = self.EmbedWindowStride * num_embedding
if frame_index > len(img_buffer):
start_index = start_index - (frame_index - len(img_buffer))
input_data = [
[cv2.resize(img_buffer[start_index + i * self.EmbedWindowAtrous],
(self.ImgSizeHeight, self.ImgSizeWidth)) for i in range(self.EmbedWindowLength)]
for j in range(self.EmbedBatchSize)]
input_data = np.asarray(input_data).transpose((0, 4, 1, 2, 3))
input_data = input_data * 127.5 + 127.5
input_dict = {self.i3d.inputs[0]: input_data}
out_logits = infer_request.infer(input_dict)[self.i3d.outputs[1]]
out_logits = out_logits.squeeze((0, 3, 4))
embedding_buffer = np.concatenate((embedding_buffer, out_logits), axis=1)
curr_t += self.EmbedWindowStride
return embedding_buffer
def action_segmentation(self):
embed_buffer_top = self.EmbedBufferTop
embed_buffer_front = self.EmbedBufferFront
batch_size = self.SegBatchSize
start_index = self.TemporalLogits.shape[0]
end_index = min(embed_buffer_top.shape[-1], embed_buffer_front.shape[-1])
num_batch = (end_index - start_index) // batch_size
infer_request = self.reshape_mstcn.create_infer_request()
if num_batch < 0:
log.debug("Waiting for the next frame ...")
elif num_batch == 0:
log.debug(f"start_index: {start_index} end_index: {end_index}")
unit1 = embed_buffer_top[:, start_index:end_index]
unit2 = embed_buffer_front[:, start_index:end_index]
feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)
input_mstcn = np.expand_dims(feature_unit, 0)
feed_dict = {}
if len(self.his_fea) != 0:
for key in self.mstcn_input_keys:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
feed_dict[string] = self.his_fea[string]
feed_dict['input'] = input_mstcn
if input_mstcn.shape == (1, 2048, 1):
out = infer_request.infer(feed_dict)
predictions = out[list(out.keys())[-1]]
for key in self.mstcn_output_key:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
self.his_fea[string] = out[string]
"""
predictions --> 4x1x64x24
his_fea --> [12*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048], 11*[1x64x2048]]
"""
temporal_logits = predictions[:, :, :len(self.ActionTerms), :]
temporal_logits = softmax(temporal_logits[-1], 1)
temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)
self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)
else:
for batch_idx in range(num_batch):
unit1 = embed_buffer_top[:,
start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]
unit2 = embed_buffer_front[:,
start_index + batch_idx * batch_size:start_index + batch_idx * batch_size + batch_size]
feature_unit = np.concatenate([unit1[:, ], unit2[:, ]], axis=0)
feed_dict = {}
if len(self.his_fea) != 0:
for key in self.mstcn_input_keys:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
feed_dict[key] = self.his_fea[string]
feed_dict['input'] = feature_unit
out = infer_request.infer(feed_dict)
predictions = out[list(out.keys())[-1]]
for key in self.mstcn_output_key:
if 'fhis_in_' in str(key.names):
string = list(key.names)[0]
self.his_fea[string] = out[string]
temporal_logits = predictions[:, :, :len(self.ActionTerms), :]
temporal_logits = softmax(temporal_logits[-1], 1)
temporal_logits = temporal_logits.transpose((0, 2, 1)).squeeze(axis=0)
self.TemporalLogits = np.concatenate([self.TemporalLogits, temporal_logits], axis=0)
| true | true |
f729addec90d3392c1ecdd2278fb87d1a7dffa03 | 7,460 | py | Python | CichyWanderers/dataloader.py | eduardojdiniz/CompNeuro | 20269e66540dc4e802273735c97323020ee37406 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | CichyWanderers/dataloader.py | eduardojdiniz/CompNeuro | 20269e66540dc4e802273735c97323020ee37406 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | CichyWanderers/dataloader.py | eduardojdiniz/CompNeuro | 20269e66540dc4e802273735c97323020ee37406 | [
"CC-BY-4.0",
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# coding=utf-8
# Imports
import h5py
import scipy.io as sio
import os
import requests
import zipfile
import numpy as np
import glob
import shutil
import pickle
def loadmat(matfile):
"""Function to load .mat files.
Parameters
----------
matfile : str
path to `matfile` containing fMRI data for a given trial.
Returns
-------
dict
dictionary containing data in key 'vol' for a given trial.
"""
try:
f = h5py.File(matfile)
except (IOError, OSError):
return sio.loadmat(matfile)
else:
return {name: np.transpose(f.get(name)) for name in f.keys()}
def download_Cichy(**kwargs):
"""Function to download data from Cichy et al, 2014.
Parameters
----------
kwargs: dict
'data_dirpath': str, data directory path. Default: ./data
'data_url' : str, data url. Default: https://osf.io/7vpyh/download'
'label_url' : str, visual stimuli labels url. Default:
http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat
Returns
-------
path_dict: dict
'fMRI' : str, fMRI filepath
'MEG' : str, MEG filepath
'label': str, visual stimuli filepath
'image': str, jpeg images dirpath
'tmp' : str, temporary data dirpath
"""
cwd = os.getcwd()
data_dirpath = kwargs.pop('data_dirpath', os.path.join(cwd, "data"))
if not os.path.exists(data_dirpath):
os.makedirs(data_dirpath)
tmp_dirpath = os.path.join(cwd, "tmp")
if not os.path.exists(tmp_dirpath):
os.makedirs(tmp_dirpath)
data_url = kwargs.pop('data_url', 'https://osf.io/7vpyh/download')
label_url = kwargs.pop(
'label_url',
'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat')
data_filepath = os.path.join(tmp_dirpath, 'data.zip')
label_filepath = os.path.join(tmp_dirpath, 'visual_stimuli.mat')
if not os.path.exists(tmp_dirpath):
os.makedirs(tmp_dirpath)
# Download MEG and fMRI RDMs
r = requests.get(data_url)
with open(data_filepath, 'wb') as f:
f.write(r.content)
# Download visual stimuli
r = requests.get(label_url)
with open(label_filepath, 'wb') as f:
f.write(r.content)
# Extract directory '92_Image_Set' and 'MEG_decoding_RDMs.mat'
with zipfile.ZipFile(data_filepath, 'r') as zip_file:
zip_file.extractall(tmp_dirpath)
# Move image files to permanent directory
tmp_image_dirpath = os.path.join(tmp_dirpath, '92_Image_Set', '92images')
image_dirpath = os.path.join(cwd, 'data', 'images')
if not os.path.exists(image_dirpath):
os.makedirs(image_dirpath)
for f in os.listdir(tmp_image_dirpath):
shutil.move(tmp_image_dirpath + f, image_dirpath)
path_dict = {}
fMRI_filepath = os.path.join(
data_dirpath,
'92_Image_Set',
'target_fmri.mat')
path_dict['fMRI'] = fMRI_filepath
path_dict['MEG'] = os.path.join(data_dirpath, 'MEG_decoding_RDMs')
path_dict['label'] = label_filepath
path_dict['image'] = image_dirpath
path_dict['tmp'] = tmp_dirpath
return path_dict
def get_stim_dict(**kwargs):
"""Get category names and binary features describing the Cichy dataset
Parameters
----------
kwargs: dict
'fMRI' : str, fMRI filepath
'MEG' : str, MEG filepath
'label': str, visual stimuli filepath
'image': str, jpeg images dirpath
'tmp' : str, temporary data dirpath
Returns
-------
stim_dict: dict
'category' : list[str], indicating category
'human' : list[int], indicating membership (0=not a member, 1=member)
'face' : list[int], indicating membership (0=not a member, 1=member)
'animate' : list[int], indicating membership (0=not a member, 1=member)
'natural' : list[int], indicating membership (0=not a member, 1=member)
'imagepath' : list[str], jpeg image filepath
"""
stimuli_filepath = kwargs.pop('label', '')
image_dirpath = kwargs.pop('image', '')
stim_dat = loadmat(stimuli_filepath)['visual_stimuli']
fields = ['category', 'human', 'face', 'animate', 'natural']
stim_dict = {field: [] for field in fields}
for ii in range(92):
for jj, field in enumerate(fields):
stim_dict[field].append(stim_dat[0, ii][jj][0])
for field in fields[1:]:
stim_dict[field] = np.array(stim_dict[field]).squeeze()
stim_dict['imagepath'] = glob.glob(image_dirpath + '/*.jpg').sort()
return stim_dict
def get_RDM_dict(**kwargs):
"""Get MEG and fMRI RDMs from the Cichy dataset
Parameters
----------
kwargs: dict
'fMRI' : str, fMRI filepath
'MEG' : str, MEG filepath
'label': str, visual stimuli filepath
'image': str, jpeg images dirpath
'tmp' : str, temporary data dirpath
Returns
-------
RDM_dict: dict
'MEG' : ndarray, (16, 2, 1301, 92, 92)
16 subjects, 2 sessions, 1301 time points (from -100 ms to 1200 ms
wrt to stimulus onset at 0 ms), 92 conditions by 92 conditions.
The last 2 dimensions form representational dissimilarity matrices of
decoding accuracies, symmetric accross the diagonal, with the diagonal
undefined (NaN).
'fMRI_EVC': ndarray, (15, 92, 92)
15 subjects, 92 conditions by 92 conditions.
The last 2 dimensions form a representational dissimilarity matrix of
spearman correlation for the EVC cortex, symmetric accross the diagonal,
with the diagonal undefined (NaN).
'fMRI_IT' : ndarray, (15, 92, 92)
15 subjects, 92 conditions by 92 conditions.
The last 2 dimensions form a representational dissimilarity matrix of
spearman correlation for the IT cortex, symmetric accross the diagonal,
with the diagonal undefined (NaN).
"""
fMRI_filepath = kwargs.pop('fMRI', '')
MEG_filepath = kwargs.pop('MEG', '')
RDM_dict = {}
RDM_dict['MEG'] = loadmat(MEG_filepath)['MEG_decoding_RDMs']
fMRI_RDMs = loadmat(fMRI_filepath)
RDM_dict['fMRI_EVC'] = fMRI_RDMs['EVC_RDMs']
RDM_dict['fMRI_IT'] = fMRI_RDMs['IT_RDMs']
return RDM_dict
def main():
"""Download and organize Cichy et al, 2014 dataset
Parameters
----------
None
Returns
-------
data_dirpath: str, data directory containing an image directory with the 92
visual stimuli and a pickle files containing the two dictionaries,
stim_dict.pkl and RDM_dict.pkl. See help(get_stim_dict) and
help(get_RDM_dict) for details.
"""
url_dict = {
'data_url': 'https://osf.io/7vpyh/download',
'label_url': 'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat'}
# Download Cichy et al, 2014 dataset
path_dict = download_Cichy(**url_dict)
# Get stimuli dictionary
stim_dict = get_stim_dict(**path_dict)
# Get RDM dictionary
RDM_dict = get_RDM_dict(**path_dict)
data_dirpath = path_dict['data_dirpath']
stim_dict_pickle = os.path.join(data_dirpath, 'stim_dict.pkl')
RDM_dict_pickle = os.path.join(data_dirpath, 'RDM_dict.pkl')
with open(stim_dict_pickle, 'wb') as pkl:
pickle.dump(stim_dict, pkl)
with open(RDM_dict_pickle, 'wb') as pkl:
pickle.dump(RDM_dict, pkl)
# Clean temporary directory
shutil.rmtree(url_dict['tmp'])
return data_dirpath
if __name__ == "__main__":
data_dirpath = main()
| 30.44898 | 93 | 0.65429 |
import h5py
import scipy.io as sio
import os
import requests
import zipfile
import numpy as np
import glob
import shutil
import pickle
def loadmat(matfile):
try:
f = h5py.File(matfile)
except (IOError, OSError):
return sio.loadmat(matfile)
else:
return {name: np.transpose(f.get(name)) for name in f.keys()}
def download_Cichy(**kwargs):
cwd = os.getcwd()
data_dirpath = kwargs.pop('data_dirpath', os.path.join(cwd, "data"))
if not os.path.exists(data_dirpath):
os.makedirs(data_dirpath)
tmp_dirpath = os.path.join(cwd, "tmp")
if not os.path.exists(tmp_dirpath):
os.makedirs(tmp_dirpath)
data_url = kwargs.pop('data_url', 'https://osf.io/7vpyh/download')
label_url = kwargs.pop(
'label_url',
'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat')
data_filepath = os.path.join(tmp_dirpath, 'data.zip')
label_filepath = os.path.join(tmp_dirpath, 'visual_stimuli.mat')
if not os.path.exists(tmp_dirpath):
os.makedirs(tmp_dirpath)
r = requests.get(data_url)
with open(data_filepath, 'wb') as f:
f.write(r.content)
r = requests.get(label_url)
with open(label_filepath, 'wb') as f:
f.write(r.content)
with zipfile.ZipFile(data_filepath, 'r') as zip_file:
zip_file.extractall(tmp_dirpath)
tmp_image_dirpath = os.path.join(tmp_dirpath, '92_Image_Set', '92images')
image_dirpath = os.path.join(cwd, 'data', 'images')
if not os.path.exists(image_dirpath):
os.makedirs(image_dirpath)
for f in os.listdir(tmp_image_dirpath):
shutil.move(tmp_image_dirpath + f, image_dirpath)
path_dict = {}
fMRI_filepath = os.path.join(
data_dirpath,
'92_Image_Set',
'target_fmri.mat')
path_dict['fMRI'] = fMRI_filepath
path_dict['MEG'] = os.path.join(data_dirpath, 'MEG_decoding_RDMs')
path_dict['label'] = label_filepath
path_dict['image'] = image_dirpath
path_dict['tmp'] = tmp_dirpath
return path_dict
def get_stim_dict(**kwargs):
stimuli_filepath = kwargs.pop('label', '')
image_dirpath = kwargs.pop('image', '')
stim_dat = loadmat(stimuli_filepath)['visual_stimuli']
fields = ['category', 'human', 'face', 'animate', 'natural']
stim_dict = {field: [] for field in fields}
for ii in range(92):
for jj, field in enumerate(fields):
stim_dict[field].append(stim_dat[0, ii][jj][0])
for field in fields[1:]:
stim_dict[field] = np.array(stim_dict[field]).squeeze()
stim_dict['imagepath'] = glob.glob(image_dirpath + '/*.jpg').sort()
return stim_dict
def get_RDM_dict(**kwargs):
fMRI_filepath = kwargs.pop('fMRI', '')
MEG_filepath = kwargs.pop('MEG', '')
RDM_dict = {}
RDM_dict['MEG'] = loadmat(MEG_filepath)['MEG_decoding_RDMs']
fMRI_RDMs = loadmat(fMRI_filepath)
RDM_dict['fMRI_EVC'] = fMRI_RDMs['EVC_RDMs']
RDM_dict['fMRI_IT'] = fMRI_RDMs['IT_RDMs']
return RDM_dict
def main():
url_dict = {
'data_url': 'https://osf.io/7vpyh/download',
'label_url': 'http://wednesday.csail.mit.edu/MEG1_MEG_Clear_Data/visual_stimuli.mat'}
path_dict = download_Cichy(**url_dict)
stim_dict = get_stim_dict(**path_dict)
RDM_dict = get_RDM_dict(**path_dict)
data_dirpath = path_dict['data_dirpath']
stim_dict_pickle = os.path.join(data_dirpath, 'stim_dict.pkl')
RDM_dict_pickle = os.path.join(data_dirpath, 'RDM_dict.pkl')
with open(stim_dict_pickle, 'wb') as pkl:
pickle.dump(stim_dict, pkl)
with open(RDM_dict_pickle, 'wb') as pkl:
pickle.dump(RDM_dict, pkl)
shutil.rmtree(url_dict['tmp'])
return data_dirpath
if __name__ == "__main__":
data_dirpath = main()
| true | true |
f729adff411c08326f2854fc947ba36427d1bbb2 | 2,940 | py | Python | nipy/testing/decorators.py | yarikoptic/nipy | 749302c7ffa8ea714cc32d405f0df521102bbc6f | [
"BSD-3-Clause"
] | null | null | null | nipy/testing/decorators.py | yarikoptic/nipy | 749302c7ffa8ea714cc32d405f0df521102bbc6f | [
"BSD-3-Clause"
] | 1 | 2015-09-09T07:49:57.000Z | 2015-09-25T01:50:40.000Z | nipy/testing/decorators.py | matthew-brett/nipy | 5a3f080f2504f8b2c326677ea2e3101344b3f579 | [
"BSD-3-Clause"
] | null | null | null | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Extend numpy's decorators to use nipy's gui and data labels.
"""
from numpy.testing.decorators import *
from nipy.utils import templates, example_data, DataError
def make_label_dec(label, ds=None):
"""Factory function to create a decorator that applies one or more labels.
Parameters
----------
label : str or sequence
One or more labels that will be applied by the decorator to the
functions it decorates. Labels are attributes of the decorated function
with their value set to True.
ds : str
An optional docstring for the resulting decorator. If not given, a
default docstring is auto-generated.
Returns
-------
ldec : function
A decorator.
Examples
--------
>>> slow = make_label_dec('slow')
>>> print slow.__doc__
Labels a test as 'slow'
>>> rare = make_label_dec(['slow','hard'],
... "Mix labels 'slow' and 'hard' for rare tests")
>>> @rare
... def f(): pass
...
>>>
>>> f.slow
True
>>> f.hard
True
"""
if isinstance(label,basestring):
labels = [label]
else:
labels = label
# Validate that the given label(s) are OK for use in setattr() by doing a
# dry run on a dummy function.
tmp = lambda : None
for label in labels:
setattr(tmp,label,True)
# This is the actual decorator we'll return
def decor(f):
for label in labels:
setattr(f,label,True)
return f
# Apply the user's docstring
if ds is None:
ds = "Labels a test as %r" % label
decor.__doc__ = ds
return decor
# Nipy specific labels
gui = make_label_dec('gui')
data = make_label_dec('data')
# For tests that need further review
def needs_review(msg):
""" Skip a test that needs further review.
Parameters
----------
msg : string
msg regarding the review that needs to be done
"""
def skip_func(func):
return skipif(True, msg)(func)
return skip_func
# Easier version of the numpy knownfailure
def knownfailure(f):
return knownfailureif(True)(f)
def if_datasource(ds, msg):
try:
ds.get_filename()
except DataError:
return skipif(True, msg)
return lambda f : f
def if_templates(f):
return if_datasource(templates, 'Cannot find template data')(f)
def if_example_data(f):
return if_datasource(example_data, 'Cannot find example data')(f)
def skip_doctest_if(condition):
"""Decorator - mark a function or method for skipping its doctest.
This decorator allows you to mark a function whose docstring you wish to
omit from testing, while preserving the docstring for introspection, help,
etc."""
if not condition:
return lambda f : f
return make_label_dec('skip_doctest')
| 25.128205 | 80 | 0.636735 |
from numpy.testing.decorators import *
from nipy.utils import templates, example_data, DataError
def make_label_dec(label, ds=None):
if isinstance(label,basestring):
labels = [label]
else:
labels = label
tmp = lambda : None
for label in labels:
setattr(tmp,label,True)
def decor(f):
for label in labels:
setattr(f,label,True)
return f
# Apply the user's docstring
if ds is None:
ds = "Labels a test as %r" % label
decor.__doc__ = ds
return decor
gui = make_label_dec('gui')
data = make_label_dec('data')
def needs_review(msg):
def skip_func(func):
return skipif(True, msg)(func)
return skip_func
def knownfailure(f):
return knownfailureif(True)(f)
def if_datasource(ds, msg):
try:
ds.get_filename()
except DataError:
return skipif(True, msg)
return lambda f : f
def if_templates(f):
return if_datasource(templates, 'Cannot find template data')(f)
def if_example_data(f):
return if_datasource(example_data, 'Cannot find example data')(f)
def skip_doctest_if(condition):
if not condition:
return lambda f : f
return make_label_dec('skip_doctest')
| true | true |
f729af50f3a41d400e5f6a7b289255fe107c35b4 | 8,282 | py | Python | topic/contrib/kcv_x1.py | mobarski/sandbox | 64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c | [
"MIT"
] | null | null | null | topic/contrib/kcv_x1.py | mobarski/sandbox | 64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c | [
"MIT"
] | null | null | null | topic/contrib/kcv_x1.py | mobarski/sandbox | 64ac79143750d5dcbd4d0f3abdab6efeb9bdf50c | [
"MIT"
] | null | null | null | # encoding: UTF-8
# Wide Column Store (Key-Column-Value database) built on top of SQLite
# (c) 2017 by mobarski (at) gmail (dot) com
# licence: MIT
# version: x1m3 (x-experimental, p-preview, r-release, m-modification)
# x1m6 - better test coverage
# x1m5 - tests, limit_str, some comments, set_items<-store, scan_items(cast=
# x1m4 - delete as scan(), __enter__
# x1m3 - col_store in external file, col_store order, ser/de as args, where_str, scan_col_store
# x1m2 - incr_many,benchmark,limit,delete,sync,to_col_store(x2),from_col_store(x2)
from __future__ import print_function
import sqlite3
from itertools import groupby
class KCV:
"Wide Column Store built on top of SQLite"
def __init__(self, path=':memory:', tab='main'):
# TODO readonly mode
self.path = path
self.tab = tab
self.conn = sqlite3.connect(path)
self.create()
def create(self,index=True):
self.conn.execute('create table if not exists {0} (k,c,v)'.format(self.tab))
if index:
self.conn.execute('create unique index if not exists i_{0} on {0} (k,c)'.format(self.tab))
def execute(self,*a,**kw):
"execute sql statement - for debugging"
print('EXECUTE',*a,**kw)
return self.conn.execute(*a,**kw)
def __enter__(self):
return self
def __exit__(self, ex_type, ex_val, ex_tb):
if ex_type is None:
self.sync()
### WRITE ###
def sync(self,compact=False):
if compact:
self.conn.execute('vacuum')
self.conn.commit()
def set(self,k,c,v):
self.conn.execute('insert or replace into {0} values (?,?,?)'.format(self.tab),(k,c,v))
def set_items(self,k,items):
self.conn.executemany('insert or replace into {0} values (?,?,?)'.format(self.tab),((k,c,v) for c,v in items))
def incr(self,k,c,v=1):
self.conn.execute('insert or replace into {0} values (?,?,?+coalesce((select v from {0} where k=? and c=?),0))'.format(self.tab),(k,c,v,k,c))
def incr_items(self,k,items):
self.conn.executemany('insert or replace into {0} values (?,?,?+coalesce((select v from {0} where k=? and c=?),0))'.format(self.tab),((k,c,v,k,c) for c,v in items))
def delete(self,k,c='*',**kw):
list(self.scan(mode='delete',k=k,c=c,**kw)) # list() required as scan is an iterator
def drop(self,tab=None):
self.conn.execute('drop table if exists {0}'.format(tab or self.tab))
### READ ###
def get(self,k,c,default=None):
x = self.conn.execute('select v from {0} where k=? and c=?'.format(self.tab),(k,c)).fetchone()
return x[0] if x else default
def items(self,k):
return {c:v for k,c,v in self.scan(k=k)}
def scan_items(self,k='*',c='*',order='',cast=list,**kw):
it = self.scan(k=k,c=c,order=order,**kw)
for k,g in groupby(it,key=lambda x:x[0]):
yield k,cast(((x[1],x[2]) for x in g))
def scan(self,k='*',c='*',order='',limit=None,mode='kcv',**kw):
select_str,select_cnt = self.get_select_str(mode)
where_str,where_vals = self.get_where_str(k,c,kw)
order_str = self.get_order_str(order)
limit_str,limit_vals = self.get_limit_str(limit)
sql = '{0} from {1} {2} {3} {4}'.format(select_str, self.tab, where_str, order_str, limit_str)
if select_cnt>1:
for row in self.conn.execute(sql, where_vals+limit_vals):
yield row
else:
for [row] in self.conn.execute(sql, where_vals+limit_vals):
yield row
def join(self): pass # TODO (LATER: x2) JOIN left,inner sum,min,max,mul,?prod
def agg(self): pass # TODO (LATER: x3) AGG sum,max,min,count,count distinct,count null,count range
### SQL CODE GENERATION UTILS ###
def get_limit_str(self,limit):
if limit is None: return '',[]
else: return 'limit ?',[limit]
def get_order_str(self,order):
out = []
if 'ka' in order: out += ['k asc']
if 'kd' in order: out += ['k desc']
if 'va' in order: out += ['v asc']
if 'vd' in order: out += ['v desc']
if 'ca' in order: out += ['c asc']
if 'cd' in order: out += ['c desc']
if out: return 'order by '+','.join(out)
else: return ''
def get_select_str(self,mode):
if mode=='kcv': return 'select k,c,v',3
if mode=='kc': return 'select distinct k,c',2
if mode=='k': return 'select distinct k',1
if mode=='c': return 'select distinct c',1
if mode=='delete': return 'delete',0
def get_where_str(self,k,c,kw):
# TODO - better arg names
# TODO - like (case insensitive)
# TODO - regexp (custom function)
# TODO - match (custom function)
sql,val = [],[]
if k!='*':
try:
if '*' in k or '?' in k or '[' in k:
sql.append('k glob ?'); val.append(k)
else:
sql.append('k=?'); val.append(k)
except TypeError:
sql.append('k=?'); val.append(k)
if c!='*':
try:
if '*' in c or '?' in c or '[' in c:
sql.append('c glob ?'); val.append(c)
else:
sql.append('c=?'); val.append(c)
except TypeError:
sql.append('c=?'); val.append(c)
if 'klt' in kw: sql.append('k<?'); val.append(kw['klt'])
if 'clt' in kw: sql.append('c<?'); val.append(kw['clt'])
if 'vlt' in kw: sql.append('v<?'); val.append(kw['vlt'])
if 'kgt' in kw: sql.append('k>?'); val.append(kw['kgt'])
if 'cgt' in kw: sql.append('c>?'); val.append(kw['cgt'])
if 'vgt' in kw: sql.append('v>?'); val.append(kw['vgt'])
if 'kle' in kw: sql.append('k<=?'); val.append(kw['kle'])
if 'cle' in kw: sql.append('c<=?'); val.append(kw['cle'])
if 'vle' in kw: sql.append('v<=?'); val.append(kw['vle'])
if 'kge' in kw: sql.append('k>=?'); val.append(kw['kge'])
if 'cge' in kw: sql.append('c>=?'); val.append(kw['cge'])
if 'vge' in kw: sql.append('v>=?'); val.append(kw['vge'])
# LIMIT - sqlite3 limits queries to 999 variables ('?' placeholders)
if 'kin' in kw: sql.append('k in ({0})'.format((',?'*len(kw['kin']))[1:])); val.extend(kw['kin'])
if 'cin' in kw: sql.append('c in ({0})'.format((',?'*len(kw['cin']))[1:])); val.extend(kw['cin'])
if 'vin' in kw: sql.append('v in ({0})'.format((',?'*len(kw['vin']))[1:])); val.extend(kw['vin'])
if sql:
return 'where '+' and '.join(sql),val
else:
return '',[]
### ADVANCED - COLUMNAR ARCHIVE ###
def to_col_store(self,path,batch=1000,tab='arch',order='',ser=None,move=False,k='*',c='*',**kw):
"archive table into compressed, columnar storage in external file"
if ser is None:
import marshal
from zlib import compress
def ser(x): return buffer(compress(marshal.dumps(x,2)))
arch_conn = sqlite3.connect(path)
arch_conn.execute("drop table if exists {0}".format(tab))
arch_conn.execute("create table {0} (c,k,v)".format(tab))
where_str,where_vals = self.get_where_str(k,c,kw)
order_str = self.get_order_str(order)
cols = []
keys = []
vals = []
for k,c,v in self.conn.execute('select k,c,v from {0} {1} {2}'.format(self.tab, where_str, order_str),where_vals):
if len(keys)>=batch:
arch_conn.execute("insert into {0} values (?,?,?)".format(tab),(ser(cols),ser(keys),ser(vals)))
if move:
self.conn.executemany("delete from {0} where k=? and c=?".format(self.tab),zip(keys,cols))
cols = []
keys = []
vals = []
cols.append(c)
keys.append(k)
vals.append(v)
if keys:
arch_conn.execute("insert into {0} values (?,?,?)".format(tab),(ser(cols),ser(keys),ser(vals)))
arch_conn.execute('vacuum')
arch_conn.commit()
arch_conn.close()
def from_col_store(self, path, tab='arch', de=None, merge=False):
"restore table from archive kept in external file"
if de is None:
import marshal
from zlib import decompress
def de(x): return marshal.loads(decompress(x))
arch_conn = sqlite3.connect(path)
if not merge:
self.drop()
self.create(index=False)
for ser_cols,ser_keys,ser_vals in arch_conn.execute('select c,k,v from {0}'.format(tab)):
cols = de(ser_cols)
keys = de(ser_keys)
vals = de(ser_vals)
self.conn.executemany('insert into {0} values (?,?,?)'.format(self.tab),zip(keys,cols,vals))
if not merge:
self.create()
def scan_col_store(self,path,tab='arch',de=None):
"iterate over table in external archive file"
if de is None:
import marshal
from zlib import decompress
def de(x): return marshal.loads(decompress(x))
arch_conn = sqlite3.connect(path)
for ser_cols,ser_keys,ser_vals in arch_conn.execute('select c,k,v from {0}'.format(tab)):
cols = de(ser_cols)
keys = de(ser_keys)
vals = de(ser_vals)
for k,c,v in zip(keys,cols,vals):
yield k,c,v
| 34.65272 | 166 | 0.637286 |
from __future__ import print_function
import sqlite3
from itertools import groupby
class KCV:
def __init__(self, path=':memory:', tab='main'):
self.path = path
self.tab = tab
self.conn = sqlite3.connect(path)
self.create()
def create(self,index=True):
self.conn.execute('create table if not exists {0} (k,c,v)'.format(self.tab))
if index:
self.conn.execute('create unique index if not exists i_{0} on {0} (k,c)'.format(self.tab))
def execute(self,*a,**kw):
print('EXECUTE',*a,**kw)
return self.conn.execute(*a,**kw)
def __enter__(self):
return self
def __exit__(self, ex_type, ex_val, ex_tb):
if ex_type is None:
self.sync()
se):
if compact:
self.conn.execute('vacuum')
self.conn.commit()
def set(self,k,c,v):
self.conn.execute('insert or replace into {0} values (?,?,?)'.format(self.tab),(k,c,v))
def set_items(self,k,items):
self.conn.executemany('insert or replace into {0} values (?,?,?)'.format(self.tab),((k,c,v) for c,v in items))
def incr(self,k,c,v=1):
self.conn.execute('insert or replace into {0} values (?,?,?+coalesce((select v from {0} where k=? and c=?),0))'.format(self.tab),(k,c,v,k,c))
def incr_items(self,k,items):
self.conn.executemany('insert or replace into {0} values (?,?,?+coalesce((select v from {0} where k=? and c=?),0))'.format(self.tab),((k,c,v,k,c) for c,v in items))
def delete(self,k,c='*',**kw):
list(self.scan(mode='delete',k=k,c=c,**kw))
def drop(self,tab=None):
self.conn.execute('drop table if exists {0}'.format(tab or self.tab))
t=None):
x = self.conn.execute('select v from {0} where k=? and c=?'.format(self.tab),(k,c)).fetchone()
return x[0] if x else default
def items(self,k):
return {c:v for k,c,v in self.scan(k=k)}
def scan_items(self,k='*',c='*',order='',cast=list,**kw):
it = self.scan(k=k,c=c,order=order,**kw)
for k,g in groupby(it,key=lambda x:x[0]):
yield k,cast(((x[1],x[2]) for x in g))
def scan(self,k='*',c='*',order='',limit=None,mode='kcv',**kw):
select_str,select_cnt = self.get_select_str(mode)
where_str,where_vals = self.get_where_str(k,c,kw)
order_str = self.get_order_str(order)
limit_str,limit_vals = self.get_limit_str(limit)
sql = '{0} from {1} {2} {3} {4}'.format(select_str, self.tab, where_str, order_str, limit_str)
if select_cnt>1:
for row in self.conn.execute(sql, where_vals+limit_vals):
yield row
else:
for [row] in self.conn.execute(sql, where_vals+limit_vals):
yield row
def join(self): pass
def agg(self): pass
else: return 'limit ?',[limit]
def get_order_str(self,order):
out = []
if 'ka' in order: out += ['k asc']
if 'kd' in order: out += ['k desc']
if 'va' in order: out += ['v asc']
if 'vd' in order: out += ['v desc']
if 'ca' in order: out += ['c asc']
if 'cd' in order: out += ['c desc']
if out: return 'order by '+','.join(out)
else: return ''
def get_select_str(self,mode):
if mode=='kcv': return 'select k,c,v',3
if mode=='kc': return 'select distinct k,c',2
if mode=='k': return 'select distinct k',1
if mode=='c': return 'select distinct c',1
if mode=='delete': return 'delete',0
def get_where_str(self,k,c,kw):
sql,val = [],[]
if k!='*':
try:
if '*' in k or '?' in k or '[' in k:
sql.append('k glob ?'); val.append(k)
else:
sql.append('k=?'); val.append(k)
except TypeError:
sql.append('k=?'); val.append(k)
if c!='*':
try:
if '*' in c or '?' in c or '[' in c:
sql.append('c glob ?'); val.append(c)
else:
sql.append('c=?'); val.append(c)
except TypeError:
sql.append('c=?'); val.append(c)
if 'klt' in kw: sql.append('k<?'); val.append(kw['klt'])
if 'clt' in kw: sql.append('c<?'); val.append(kw['clt'])
if 'vlt' in kw: sql.append('v<?'); val.append(kw['vlt'])
if 'kgt' in kw: sql.append('k>?'); val.append(kw['kgt'])
if 'cgt' in kw: sql.append('c>?'); val.append(kw['cgt'])
if 'vgt' in kw: sql.append('v>?'); val.append(kw['vgt'])
if 'kle' in kw: sql.append('k<=?'); val.append(kw['kle'])
if 'cle' in kw: sql.append('c<=?'); val.append(kw['cle'])
if 'vle' in kw: sql.append('v<=?'); val.append(kw['vle'])
if 'kge' in kw: sql.append('k>=?'); val.append(kw['kge'])
if 'cge' in kw: sql.append('c>=?'); val.append(kw['cge'])
if 'vge' in kw: sql.append('v>=?'); val.append(kw['vge'])
if 'kin' in kw: sql.append('k in ({0})'.format((',?'*len(kw['kin']))[1:])); val.extend(kw['kin'])
if 'cin' in kw: sql.append('c in ({0})'.format((',?'*len(kw['cin']))[1:])); val.extend(kw['cin'])
if 'vin' in kw: sql.append('v in ({0})'.format((',?'*len(kw['vin']))[1:])); val.extend(kw['vin'])
if sql:
return 'where '+' and '.join(sql),val
else:
return '',[]
ve=False,k='*',c='*',**kw):
if ser is None:
import marshal
from zlib import compress
def ser(x): return buffer(compress(marshal.dumps(x,2)))
arch_conn = sqlite3.connect(path)
arch_conn.execute("drop table if exists {0}".format(tab))
arch_conn.execute("create table {0} (c,k,v)".format(tab))
where_str,where_vals = self.get_where_str(k,c,kw)
order_str = self.get_order_str(order)
cols = []
keys = []
vals = []
for k,c,v in self.conn.execute('select k,c,v from {0} {1} {2}'.format(self.tab, where_str, order_str),where_vals):
if len(keys)>=batch:
arch_conn.execute("insert into {0} values (?,?,?)".format(tab),(ser(cols),ser(keys),ser(vals)))
if move:
self.conn.executemany("delete from {0} where k=? and c=?".format(self.tab),zip(keys,cols))
cols = []
keys = []
vals = []
cols.append(c)
keys.append(k)
vals.append(v)
if keys:
arch_conn.execute("insert into {0} values (?,?,?)".format(tab),(ser(cols),ser(keys),ser(vals)))
arch_conn.execute('vacuum')
arch_conn.commit()
arch_conn.close()
def from_col_store(self, path, tab='arch', de=None, merge=False):
if de is None:
import marshal
from zlib import decompress
def de(x): return marshal.loads(decompress(x))
arch_conn = sqlite3.connect(path)
if not merge:
self.drop()
self.create(index=False)
for ser_cols,ser_keys,ser_vals in arch_conn.execute('select c,k,v from {0}'.format(tab)):
cols = de(ser_cols)
keys = de(ser_keys)
vals = de(ser_vals)
self.conn.executemany('insert into {0} values (?,?,?)'.format(self.tab),zip(keys,cols,vals))
if not merge:
self.create()
def scan_col_store(self,path,tab='arch',de=None):
if de is None:
import marshal
from zlib import decompress
def de(x): return marshal.loads(decompress(x))
arch_conn = sqlite3.connect(path)
for ser_cols,ser_keys,ser_vals in arch_conn.execute('select c,k,v from {0}'.format(tab)):
cols = de(ser_cols)
keys = de(ser_keys)
vals = de(ser_vals)
for k,c,v in zip(keys,cols,vals):
yield k,c,v
| true | true |
f729af98b0a5790aff0129b503e5e9432c4eabaf | 501 | py | Python | setup.py | Maharacha/cat_chaser | c92e2f66aa8d774a57939692a0747597e8362d6f | [
"BSD-2-Clause"
] | null | null | null | setup.py | Maharacha/cat_chaser | c92e2f66aa8d774a57939692a0747597e8362d6f | [
"BSD-2-Clause"
] | null | null | null | setup.py | Maharacha/cat_chaser | c92e2f66aa8d774a57939692a0747597e8362d6f | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='Cat chaser',
version='0.1.0',
description='Code for the cat chaser.',
long_description=readme,
author='Joakim Nyman',
author_email='joakim.nyman86@gmail.com',
url='https://github.com/Maharacha/cat_chaser',
license=license,
packages=find_packages(exclude=('tests', 'docs'))
)
| 20.04 | 53 | 0.650699 |
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='Cat chaser',
version='0.1.0',
description='Code for the cat chaser.',
long_description=readme,
author='Joakim Nyman',
author_email='joakim.nyman86@gmail.com',
url='https://github.com/Maharacha/cat_chaser',
license=license,
packages=find_packages(exclude=('tests', 'docs'))
)
| true | true |
f729b14ec3cb4268bb54ac293ffc4e486ecea87b | 54,648 | py | Python | scripts/retrain.py | gengkunling/tensorflow_poet | 5ef36da08ee0f50cdaa2d08753393c549c2e75b3 | [
"Apache-2.0"
] | null | null | null | scripts/retrain.py | gengkunling/tensorflow_poet | 5ef36da08ee0f50cdaa2d08753393c549c2e75b3 | [
"Apache-2.0"
] | null | null | null | scripts/retrain.py | gengkunling/tensorflow_poet | 5ef36da08ee0f50cdaa2d08753393c549c2e75b3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable 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.
# ==============================================================================
r"""Simple transfer learning with Inception v3 or Mobilenet models.
With support for TensorBoard.
This example shows how to take a Inception v3 or Mobilenet model trained on
ImageNet images, and train a new top layer that can recognize other classes of
images.
The top layer receives as input a 2048-dimensional vector (1001-dimensional for
Mobilenet) for each image. We train a softmax layer on top of this
representation. Assuming the softmax layer contains N labels, this corresponds
to learning N + 2048*N (or 1001*N) model parameters corresponding to the
learned biases and weights.
Here's an example, which assumes you have a folder containing class-named
subfolders, each full of images for each label. The example folder flower_photos
should have a structure like this:
~/flower_photos/daisy/photo1.jpg
~/flower_photos/daisy/photo2.jpg
...
~/flower_photos/rose/anotherphoto77.jpg
...
~/flower_photos/sunflower/somepicture.jpg
The subfolder names are important, since they define what label is applied to
each image, but the filenames themselves don't matter. Once your images are
prepared, you can run the training with a command like this:
```bash
bazel build tensorflow/examples/image_retraining:retrain && \
bazel-bin/tensorflow/examples/image_retraining/retrain \
--image_dir ~/flower_photos
```
Or, if you have a pip installation of tensorflow, `retrain.py` can be run
without bazel:
```bash
python tensorflow/examples/image_retraining/retrain.py \
--image_dir ~/flower_photos
```
You can replace the image_dir argument with any folder containing subfolders of
images. The label for each image is taken from the name of the subfolder it's
in.
This produces a new model file that can be loaded and run by any TensorFlow
program, for example the label_image sample code.
By default this script will use the high accuracy, but comparatively large and
slow Inception v3 model architecture. It's recommended that you start with this
to validate that you have gathered good training data, but if you want to deploy
on resource-limited platforms, you can try the `--architecture` flag with a
Mobilenet model. For example:
```bash
python tensorflow/examples/image_retraining/retrain.py \
--image_dir ~/flower_photos --architecture mobilenet_1.0_224
```
There are 32 different Mobilenet models to choose from, with a variety of file
size and latency options. The first number can be '1.0', '0.75', '0.50', or
'0.25' to control the size, and the second controls the input image size, either
'224', '192', '160', or '128', with smaller sizes running faster. See
https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html
for more information on Mobilenet.
To use with TensorBoard:
By default, this script will log summaries to /tmp/retrain_logs directory
Visualize the summaries with this command:
tensorboard --logdir /tmp/retrain_logs
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import hashlib
import os.path
import random
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import tensor_shape
from tensorflow.python.platform import gfile
from tensorflow.python.util import compat
FLAGS = None
# These are all parameters that are tied to the particular model architecture
# we're using for Inception v3. These include things like tensor names and their
# sizes. If you want to adapt this script to work with another model, you will
# need to update these to reflect the values in the network you're using.
MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1 # ~134M
def create_image_lists(image_dir, testing_percentage, validation_percentage):
"""Builds a list of training images from the file system.
Analyzes the sub folders in the image directory, splits them into stable
training, testing, and validation sets, and returns a data structure
describing the lists of images for each label and their paths.
Args:
image_dir: String path to a folder containing subfolders of images.
testing_percentage: Integer percentage of the images to reserve for tests.
validation_percentage: Integer percentage of images reserved for validation.
Returns:
A dictionary containing an entry for each label subfolder, with images split
into training, testing, and validation sets within each label.
"""
if not gfile.Exists(image_dir):
tf.logging.error("Image directory '" + image_dir + "' not found.")
return None
result = {}
sub_dirs = [x[0] for x in gfile.Walk(image_dir)]
# The root directory comes first, so skip it.
is_root_dir = True
for sub_dir in sub_dirs:
if is_root_dir:
is_root_dir = False
continue
extensions = ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG']
file_list = []
dir_name = os.path.basename(sub_dir)
if dir_name == image_dir:
continue
tf.logging.info("Looking for images in '" + dir_name + "'")
for extension in extensions:
file_glob = os.path.join(image_dir, dir_name, '*.' + extension)
file_list.extend(gfile.Glob(file_glob))
if not file_list:
tf.logging.warning('No files found')
continue
if len(file_list) < 20:
tf.logging.warning(
'WARNING: Folder has less than 20 images, which may cause issues.')
elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:
tf.logging.warning(
'WARNING: Folder {} has more than {} images. Some images will '
'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))
label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())
training_images = []
testing_images = []
validation_images = []
for file_name in file_list:
base_name = os.path.basename(file_name)
# We want to ignore anything after '_nohash_' in the file name when
# deciding which set to put an image in, the data set creator has a way of
# grouping photos that are close variations of each other. For example
# this is used in the plant disease data set to group multiple pictures of
# the same leaf.
hash_name = re.sub(r'_nohash_.*$', '', file_name)
# This looks a bit magical, but we need to decide whether this file should
# go into the training, testing, or validation sets, and we want to keep
# existing files in the same set even if more files are subsequently
# added.
# To do that, we need a stable way of deciding based on just the file name
# itself, so we do a hash of that and then use that to generate a
# probability value that we use to assign it.
hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest()
percentage_hash = ((int(hash_name_hashed, 16) %
(MAX_NUM_IMAGES_PER_CLASS + 1)) *
(100.0 / MAX_NUM_IMAGES_PER_CLASS))
if percentage_hash < validation_percentage:
validation_images.append(base_name)
elif percentage_hash < (testing_percentage + validation_percentage):
testing_images.append(base_name)
else:
training_images.append(base_name)
result[label_name] = {
'dir': dir_name,
'training': training_images,
'testing': testing_images,
'validation': validation_images,
}
return result
def get_image_path(image_lists, label_name, index, image_dir, category):
""""Returns a path to an image for a label at the given index.
Args:
image_lists: Dictionary of training images for each label.
label_name: Label string we want to get an image for.
index: Int offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of set to pull images from - training, testing, or
validation.
Returns:
File system path string to an image that meets the requested parameters.
"""
if label_name not in image_lists:
tf.logging.fatal('Label does not exist %s.', label_name)
label_lists = image_lists[label_name]
if category not in label_lists:
tf.logging.fatal('Category does not exist %s.', category)
category_list = label_lists[category]
if not category_list:
tf.logging.fatal('Label %s has no images in the category %s.',
label_name, category)
mod_index = index % len(category_list)
base_name = category_list[mod_index]
sub_dir = label_lists['dir']
full_path = os.path.join(image_dir, sub_dir, base_name)
return full_path
def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, architecture):
""""Returns a path to a bottleneck file for a label at the given index.
Args:
image_lists: Dictionary of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be moduloed by the
available number of images for the label, so it can be arbitrarily large.
bottleneck_dir: Folder string holding cached files of bottleneck values.
category: Name string of set to pull images from - training, testing, or
validation.
architecture: The name of the model architecture.
Returns:
File system path string to an image that meets the requested parameters.
"""
return get_image_path(image_lists, label_name, index, bottleneck_dir,
category) + '_' + architecture + '.txt'
def create_model_graph(model_info):
""""Creates a graph from saved GraphDef file and returns a Graph object.
Args:
model_info: Dictionary containing information about the model architecture.
Returns:
Graph holding the trained Inception network, and various tensors we'll be
manipulating.
"""
with tf.Graph().as_default() as graph:
model_path = os.path.join(FLAGS.model_dir, model_info['model_file_name'])
with gfile.FastGFile(model_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
bottleneck_tensor, resized_input_tensor = (tf.import_graph_def(
graph_def,
name='',
return_elements=[
model_info['bottleneck_tensor_name'],
model_info['resized_input_tensor_name'],
]))
return graph, bottleneck_tensor, resized_input_tensor
def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Runs inference on an image to extract the 'bottleneck' summary layer.
Args:
sess: Current active TensorFlow Session.
image_data: String of raw JPEG data.
image_data_tensor: Input data layer in the graph.
decoded_image_tensor: Output of initial image resizing and preprocessing.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: Layer before the final softmax.
Returns:
Numpy array of bottleneck values.
"""
# First decode the JPEG image, resize it, and rescale the pixel values.
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
# Then run it through the recognition network.
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values
def maybe_download_and_extract(data_url):
"""Download and extract model tar file.
If the pretrained model we're using doesn't already exist, this function
downloads it from the TensorFlow.org website and unpacks it into a directory.
Args:
data_url: Web location of the tar file containing the pretrained model.
"""
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = data_url.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' %
(filename,
float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(data_url, filepath, _progress)
print()
statinfo = os.stat(filepath)
tf.logging.info('Successfully downloaded', filename, statinfo.st_size,
'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
def ensure_dir_exists(dir_name):
"""Makes sure the folder exists on disk.
Args:
dir_name: Path string to the folder we want to create.
"""
if not os.path.exists(dir_name):
os.makedirs(dir_name)
bottleneck_path_2_bottleneck_values = {}
def create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
"""Create a single bottleneck file."""
tf.logging.info('Creating bottleneck at ' + bottleneck_path)
image_path = get_image_path(image_lists, label_name, index,
image_dir, category)
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
image_data = gfile.FastGFile(image_path, 'rb').read()
try:
bottleneck_values = run_bottleneck_on_image(
sess, image_data, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor)
except Exception as e:
raise RuntimeError('Error during processing file %s (%s)' % (image_path,
str(e)))
bottleneck_string = ','.join(str(x) for x in bottleneck_values)
with open(bottleneck_path, 'w') as bottleneck_file:
bottleneck_file.write(bottleneck_string)
def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, architecture):
"""Retrieves or calculates bottleneck values for an image.
If a cached version of the bottleneck data exists on-disk, return that,
otherwise calculate the data and save it to disk for future use.
Args:
sess: The current active TensorFlow Session.
image_lists: Dictionary of training images for each label.
label_name: Label string we want to get an image for.
index: Integer offset of the image we want. This will be modulo-ed by the
available number of images for the label, so it can be arbitrarily large.
image_dir: Root folder string of the subfolders containing the training
images.
category: Name string of which set to pull images from - training, testing,
or validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: The tensor to feed loaded jpeg data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The output tensor for the bottleneck values.
architecture: The name of the model architecture.
Returns:
Numpy array of values produced by the bottleneck layer for the image.
"""
label_lists = image_lists[label_name]
sub_dir = label_lists['dir']
sub_dir_path = os.path.join(bottleneck_dir, sub_dir)
ensure_dir_exists(sub_dir_path)
bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
bottleneck_dir, category, architecture)
if not os.path.exists(bottleneck_path):
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
did_hit_error = False
try:
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
except ValueError:
tf.logging.warning('Invalid float found, recreating bottleneck')
did_hit_error = True
if did_hit_error:
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
# Allow exceptions to propagate here, since they shouldn't happen after a
# fresh creation
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
return bottleneck_values
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture):
"""Ensures all the training, testing, and validation bottlenecks are cached.
Because we're likely to read the same image multiple times (if there are no
distortions applied during training) it can speed things up a lot if we
calculate the bottleneck layer values once for each image during
preprocessing, and then just read those cached values repeatedly during
training. Here we go through all the images we've found, calculate those
values, and save them off.
Args:
sess: The current active TensorFlow Session.
image_lists: Dictionary of training images for each label.
image_dir: Root folder string of the subfolders containing the training
images.
bottleneck_dir: Folder string holding cached files of bottleneck values.
jpeg_data_tensor: Input tensor for jpeg data from file.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The penultimate output layer of the graph.
architecture: The name of the model architecture.
Returns:
Nothing.
"""
how_many_bottlenecks = 0
ensure_dir_exists(bottleneck_dir)
for label_name, label_lists in image_lists.items():
for category in ['training', 'testing', 'validation']:
category_list = label_lists[category]
for index, unused_base_name in enumerate(category_list):
get_or_create_bottleneck(
sess, image_lists, label_name, index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
how_many_bottlenecks += 1
if how_many_bottlenecks % 100 == 0:
tf.logging.info(
str(how_many_bottlenecks) + ' bottleneck files created.')
def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, architecture):
"""Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: If positive, a random sample of this size will be chosen.
If negative, all bottlenecks will be retrieved.
category: Name string of which set to pull from - training, testing, or
validation.
bottleneck_dir: Folder string holding cached files of bottleneck values.
image_dir: Root folder string of the subfolders containing the training
images.
jpeg_data_tensor: The layer to feed jpeg image data into.
decoded_image_tensor: The output of decoding and resizing the image.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
architecture: The name of the model architecture.
Returns:
List of bottleneck arrays, their corresponding ground truths, and the
relevant filenames.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
filenames = []
if how_many >= 0:
# Retrieve a random sample of bottlenecks.
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
filenames.append(image_name)
else:
# Retrieve all bottlenecks.
for label_index, label_name in enumerate(image_lists.keys()):
for image_index, image_name in enumerate(
image_lists[label_name][category]):
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
filenames.append(image_name)
return bottlenecks, ground_truths, filenames
def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
recalculate the full model for every image, and so we can't use cached
bottleneck values. Instead we find random images for the requested category,
run them through the distortion graph, and then the full graph to get the
bottleneck results for each.
Args:
sess: Current TensorFlow Session.
image_lists: Dictionary of training images for each label.
how_many: The integer number of bottleneck values to return.
category: Name string of which set of images to fetch - training, testing,
or validation.
image_dir: Root folder string of the subfolders containing the training
images.
input_jpeg_tensor: The input layer we feed the image data to.
distorted_image: The output node of the distortion graph.
resized_input_tensor: The input node of the recognition graph.
bottleneck_tensor: The bottleneck output layer of the CNN graph.
Returns:
List of bottleneck arrays and their corresponding ground truths.
"""
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_path = get_image_path(image_lists, label_name, image_index, image_dir,
category)
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
jpeg_data = gfile.FastGFile(image_path, 'rb').read()
# Note that we materialize the distorted_image_data as a numpy array before
# sending running inference on the image. This involves 2 memory copies and
# might be optimized in other implementations.
distorted_image_data = sess.run(distorted_image,
{input_jpeg_tensor: jpeg_data})
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: distorted_image_data})
bottleneck_values = np.squeeze(bottleneck_values)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck_values)
ground_truths.append(ground_truth)
return bottlenecks, ground_truths
def should_distort_images(flip_left_right, random_crop, random_scale,
random_brightness):
"""Whether any distortions are enabled, from the input flags.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total margin used around the
crop box.
random_scale: Integer percentage of how much to vary the scale by.
random_brightness: Integer range to randomly multiply the pixel values by.
Returns:
Boolean value indicating whether any distortions should be applied.
"""
return (flip_left_right or (random_crop != 0) or (random_scale != 0) or
(random_brightness != 0))
def add_input_distortions(flip_left_right, random_crop, random_scale,
random_brightness, input_width, input_height,
input_depth, input_mean, input_std):
"""Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and flips. These reflect the
kind of variations we expect in the real world, and so can help train the
model to cope with natural data more effectively. Here we take the supplied
parameters and construct a network of operations to apply them to an image.
Cropping
~~~~~~~~
Cropping is done by placing a bounding box at a random position in the full
image. The cropping parameter controls the size of that box relative to the
input image. If it's zero, then the box is the same size as the input and no
cropping is performed. If the value is 50%, then the crop box will be half the
width and height of the input. In a diagram it looks like this:
< width >
+---------------------+
| |
| width - crop% |
| < > |
| +------+ |
| | | |
| | | |
| | | |
| +------+ |
| |
| |
+---------------------+
Scaling
~~~~~~~
Scaling is a lot like cropping, except that the bounding box is always
centered and its size varies randomly within the given range. For example if
the scale percentage is zero, then the bounding box is the same size as the
input and no scaling is applied. If it's 50%, then the bounding box will be in
a random range between half the width and height and full size.
Args:
flip_left_right: Boolean whether to randomly mirror images horizontally.
random_crop: Integer percentage setting the total margin used around the
crop box.
random_scale: Integer percentage of how much to vary the scale by.
random_brightness: Integer range to randomly multiply the pixel values by.
graph.
input_width: Horizontal size of expected input image to model.
input_height: Vertical size of expected input image to model.
input_depth: How many channels the expected input image should have.
input_mean: Pixel value that should be zero in the image for the graph.
input_std: How much to divide the pixel values by before recognition.
Returns:
The jpeg input layer and the distorted result tensor.
"""
jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
margin_scale = 1.0 + (random_crop / 100.0)
resize_scale = 1.0 + (random_scale / 100.0)
margin_scale_value = tf.constant(margin_scale)
resize_scale_value = tf.random_uniform(tensor_shape.scalar(),
minval=1.0,
maxval=resize_scale)
scale_value = tf.multiply(margin_scale_value, resize_scale_value)
precrop_width = tf.multiply(scale_value, input_width)
precrop_height = tf.multiply(scale_value, input_height)
precrop_shape = tf.stack([precrop_height, precrop_width])
precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)
precropped_image = tf.image.resize_bilinear(decoded_image_4d,
precrop_shape_as_int)
precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0])
cropped_image = tf.random_crop(precropped_image_3d,
[input_height, input_width, input_depth])
if flip_left_right:
flipped_image = tf.image.random_flip_left_right(cropped_image)
else:
flipped_image = cropped_image
brightness_min = 1.0 - (random_brightness / 100.0)
brightness_max = 1.0 + (random_brightness / 100.0)
brightness_value = tf.random_uniform(tensor_shape.scalar(),
minval=brightness_min,
maxval=brightness_max)
brightened_image = tf.multiply(flipped_image, brightness_value)
offset_image = tf.subtract(brightened_image, input_mean)
mul_image = tf.multiply(offset_image, 1.0 / input_std)
distort_result = tf.expand_dims(mul_image, 0, name='DistortResult')
return jpeg_data, distort_result
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var)
def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor,
bottleneck_tensor_size):
"""Adds a new softmax and fully-connected layer for training.
We need to retrain the top layer to identify our new classes, so this function
adds the right operations to the graph, along with some variables to hold the
weights, and then sets up all the gradients for the backward pass.
The set up for the softmax and fully-connected layers is based on:
https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html
Args:
class_count: Integer of how many categories of things we're trying to
recognize.
final_tensor_name: Name string for the new final node that produces results.
bottleneck_tensor: The output of the main CNN graph.
bottleneck_tensor_size: How many entries in the bottleneck vector.
Returns:
The tensors for the training and cross entropy results, and tensors for the
bottleneck input and ground truth input.
"""
with tf.name_scope('input'):
bottleneck_input = tf.placeholder_with_default(
bottleneck_tensor,
shape=[None, bottleneck_tensor_size],
name='BottleneckInputPlaceholder')
ground_truth_input = tf.placeholder(tf.float32,
[None, class_count],
name='GroundTruthInput')
# Organizing the following ops as `final_training_ops` so they're easier
# to see in TensorBoard
layer_name = 'final_training_ops'
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
initial_value = tf.truncated_normal(
[bottleneck_tensor_size, class_count], stddev=0.001)
layer_weights = tf.Variable(initial_value, name='final_weights')
variable_summaries(layer_weights)
with tf.name_scope('biases'):
layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
variable_summaries(layer_biases)
with tf.name_scope('Wx_plus_b'):
logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases
tf.summary.histogram('pre_activations', logits)
final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
tf.summary.histogram('activations', final_tensor)
with tf.name_scope('cross_entropy'):
#cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
# labels=ground_truth_input, logits=logits)
cross_entropy = tf.nn.weighted_cross_entropy_with_logits(targets=ground_truth_input, logits=logits, pos_weight=4)
with tf.name_scope('total'):
cross_entropy_mean = tf.reduce_mean(cross_entropy)
tf.summary.scalar('cross_entropy', cross_entropy_mean)
with tf.name_scope('train'):
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
train_step = optimizer.minimize(cross_entropy_mean)
return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
final_tensor)
def add_evaluation_step(result_tensor, ground_truth_tensor):
"""Inserts the operations we need to evaluate the accuracy of our results.
Args:
result_tensor: The new final node that produces results.
ground_truth_tensor: The node we feed ground truth data
into.
Returns:
Tuple of (evaluation step, prediction).
"""
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
prediction = tf.argmax(result_tensor, 1)
correct_prediction = tf.equal(
prediction, tf.argmax(ground_truth_tensor, 1))
with tf.name_scope('accuracy'):
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
return evaluation_step, prediction
def save_graph_to_file(sess, graph, graph_file_name):
output_graph_def = graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with gfile.FastGFile(graph_file_name, 'wb') as f:
f.write(output_graph_def.SerializeToString())
return
def prepare_file_system():
# Setup the directory we'll write summaries to for TensorBoard
if tf.gfile.Exists(FLAGS.summaries_dir):
tf.gfile.DeleteRecursively(FLAGS.summaries_dir)
tf.gfile.MakeDirs(FLAGS.summaries_dir)
if FLAGS.intermediate_store_frequency > 0:
ensure_dir_exists(FLAGS.intermediate_output_graphs_dir)
return
def create_model_info(architecture):
"""Given the name of a model architecture, returns information about it.
There are different base image recognition pretrained models that can be
retrained using transfer learning, and this function translates from the name
of a model to the attributes that are needed to download and train with it.
Args:
architecture: Name of a model architecture.
Returns:
Dictionary of information about the model, or None if the name isn't
recognized
Raises:
ValueError: If architecture name is unknown.
"""
architecture = architecture.lower()
if architecture == 'inception_v3':
# pylint: disable=line-too-long
data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long
bottleneck_tensor_name = 'pool_3/_reshape:0'
bottleneck_tensor_size = 2048
input_width = 299
input_height = 299
input_depth = 3
resized_input_tensor_name = 'Mul:0'
model_file_name = 'classify_image_graph_def.pb'
input_mean = 128
input_std = 128
elif architecture.startswith('mobilenet_'):
parts = architecture.split('_')
if len(parts) != 3 and len(parts) != 4:
tf.logging.error("Couldn't understand architecture name '%s'",
architecture)
return None
version_string = parts[1]
if (version_string != '1.0' and version_string != '0.75' and
version_string != '0.50' and version_string != '0.25'):
tf.logging.error(
""""The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',
but found '%s' for architecture '%s'""",
version_string, architecture)
return None
size_string = parts[2]
if (size_string != '224' and size_string != '192' and
size_string != '160' and size_string != '128'):
tf.logging.error(
"""The Mobilenet input size should be '224', '192', '160', or '128',
but found '%s' for architecture '%s'""",
size_string, architecture)
return None
if len(parts) == 3:
is_quantized = False
else:
if parts[3] != 'quantized':
tf.logging.error(
"Couldn't understand architecture suffix '%s' for '%s'", parts[3],
architecture)
return None
is_quantized = True
data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
data_url += version_string + '_' + size_string + '_frozen.tgz'
bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
bottleneck_tensor_size = 1001
input_width = int(size_string)
input_height = int(size_string)
input_depth = 3
resized_input_tensor_name = 'input:0'
if is_quantized:
model_base_name = 'quantized_graph.pb'
else:
model_base_name = 'frozen_graph.pb'
model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string
model_file_name = os.path.join(model_dir_name, model_base_name)
input_mean = 127.5
input_std = 127.5
else:
tf.logging.error("Couldn't understand architecture name '%s'", architecture)
raise ValueError('Unknown architecture', architecture)
return {
'data_url': data_url,
'bottleneck_tensor_name': bottleneck_tensor_name,
'bottleneck_tensor_size': bottleneck_tensor_size,
'input_width': input_width,
'input_height': input_height,
'input_depth': input_depth,
'resized_input_tensor_name': resized_input_tensor_name,
'model_file_name': model_file_name,
'input_mean': input_mean,
'input_std': input_std,
}
def add_jpeg_decoding(input_width, input_height, input_depth, input_mean,
input_std):
"""Adds operations that perform JPEG decoding and resizing to the graph..
Args:
input_width: Desired width of the image fed into the recognizer graph.
input_height: Desired width of the image fed into the recognizer graph.
input_depth: Desired channels of the image fed into the recognizer graph.
input_mean: Pixel value that should be zero in the image for the graph.
input_std: How much to divide the pixel values by before recognition.
Returns:
Tensors for the node to feed JPEG data into, and the output of the
preprocessing steps.
"""
jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
resize_shape = tf.stack([input_height, input_width])
resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32)
resized_image = tf.image.resize_bilinear(decoded_image_4d,
resize_shape_as_int)
offset_image = tf.subtract(resized_image, input_mean)
mul_image = tf.multiply(offset_image, 1.0 / input_std)
return jpeg_data, mul_image
def main(_):
# Needed to make sure the logging output is visible.
# See https://github.com/tensorflow/tensorflow/issues/3047
tf.logging.set_verbosity(tf.logging.INFO)
# Prepare necessary directories that can be used during training
prepare_file_system()
# Gather information about the model architecture we'll be using.
model_info = create_model_info(FLAGS.architecture)
if not model_info:
tf.logging.error('Did not recognize architecture flag')
return -1
# Set up the pre-trained graph.
maybe_download_and_extract(model_info['data_url'])
graph, bottleneck_tensor, resized_image_tensor = (
create_model_graph(model_info))
# Look at the folder structure, and create lists of all the images.
image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,
FLAGS.validation_percentage)
class_count = len(image_lists.keys())
if class_count == 0:
tf.logging.error('No valid folders of images found at ' + FLAGS.image_dir)
return -1
if class_count == 1:
tf.logging.error('Only one valid folder of images found at ' +
FLAGS.image_dir +
' - multiple classes are needed for classification.')
return -1
# See if the command-line flags mean we're applying any distortions.
do_distort_images = should_distort_images(
FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
FLAGS.random_brightness)
with tf.Session(graph=graph) as sess:
# Set up the image decoding sub-graph.
jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(
model_info['input_width'], model_info['input_height'],
model_info['input_depth'], model_info['input_mean'],
model_info['input_std'])
if do_distort_images:
# We will be applying distortions, so setup the operations we'll need.
(distorted_jpeg_data_tensor,
distorted_image_tensor) = add_input_distortions(
FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
FLAGS.random_brightness, model_info['input_width'],
model_info['input_height'], model_info['input_depth'],
model_info['input_mean'], model_info['input_std'])
else:
# We'll make sure we've calculated the 'bottleneck' image summaries and
# cached them on disk.
cache_bottlenecks(sess, image_lists, FLAGS.image_dir,
FLAGS.bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor,
bottleneck_tensor, FLAGS.architecture)
# Add the new layer that we'll be training.
(train_step, cross_entropy, bottleneck_input, ground_truth_input,
final_tensor) = add_final_training_ops(
len(image_lists.keys()), FLAGS.final_tensor_name, bottleneck_tensor,
model_info['bottleneck_tensor_size'])
# Create the operations we need to evaluate the accuracy of our new layer.
evaluation_step, prediction = add_evaluation_step(
final_tensor, ground_truth_input)
# Merge all the summaries and write them out to the summaries_dir
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
sess.graph)
validation_writer = tf.summary.FileWriter(
FLAGS.summaries_dir + '/validation')
# Set up all our weights to their initial default values.
init = tf.global_variables_initializer()
sess.run(init)
# Run the training for as many cycles as requested on the command line.
for i in range(FLAGS.how_many_training_steps):
# Get a batch of input bottleneck values, either calculated fresh every
# time with distortions applied, or from the cache stored on disk.
if do_distort_images:
(train_bottlenecks,
train_ground_truth) = get_random_distorted_bottlenecks(
sess, image_lists, FLAGS.train_batch_size, 'training',
FLAGS.image_dir, distorted_jpeg_data_tensor,
distorted_image_tensor, resized_image_tensor, bottleneck_tensor)
else:
(train_bottlenecks,
train_ground_truth, _) = get_random_cached_bottlenecks(
sess, image_lists, FLAGS.train_batch_size, 'training',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture)
# Feed the bottlenecks and ground truth into the graph, and run a training
# step. Capture training summaries for TensorBoard with the `merged` op.
train_summary, _ = sess.run(
[merged, train_step],
feed_dict={bottleneck_input: train_bottlenecks,
ground_truth_input: train_ground_truth})
train_writer.add_summary(train_summary, i)
# Every so often, print out how well the graph is training.
is_last_step = (i + 1 == FLAGS.how_many_training_steps)
if (i % FLAGS.eval_step_interval) == 0 or is_last_step:
train_accuracy, cross_entropy_value = sess.run(
[evaluation_step, cross_entropy],
feed_dict={bottleneck_input: train_bottlenecks,
ground_truth_input: train_ground_truth})
tf.logging.info('%s: Step %d: Train accuracy = %.1f%%' %
(datetime.now(), i, train_accuracy * 100))
tf.logging.info('%s: Step %d: Cross entropy = %f' %
(datetime.now(), i, cross_entropy_value))
validation_bottlenecks, validation_ground_truth, _ = (
get_random_cached_bottlenecks(
sess, image_lists, FLAGS.validation_batch_size, 'validation',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture))
# Run a validation step and capture training summaries for TensorBoard
# with the `merged` op.
validation_summary, validation_accuracy = sess.run(
[merged, evaluation_step],
feed_dict={bottleneck_input: validation_bottlenecks,
ground_truth_input: validation_ground_truth})
validation_writer.add_summary(validation_summary, i)
tf.logging.info('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' %
(datetime.now(), i, validation_accuracy * 100,
len(validation_bottlenecks)))
# Store intermediate results
intermediate_frequency = FLAGS.intermediate_store_frequency
if (intermediate_frequency > 0 and (i % intermediate_frequency == 0)
and i > 0):
intermediate_file_name = (FLAGS.intermediate_output_graphs_dir +
'intermediate_' + str(i) + '.pb')
tf.logging.info('Save intermediate result to : ' +
intermediate_file_name)
save_graph_to_file(sess, graph, intermediate_file_name)
# We've completed all our training, so run a final test evaluation on
# some new images we haven't used before.
test_bottlenecks, test_ground_truth, test_filenames = (
get_random_cached_bottlenecks(
sess, image_lists, FLAGS.test_batch_size, 'testing',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture))
test_accuracy, predictions = sess.run(
[evaluation_step, prediction],
feed_dict={bottleneck_input: test_bottlenecks,
ground_truth_input: test_ground_truth})
tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %
(test_accuracy * 100, len(test_bottlenecks)))
if FLAGS.print_misclassified_test_images:
tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')
for i, test_filename in enumerate(test_filenames):
if predictions[i] != test_ground_truth[i].argmax():
tf.logging.info('%70s %s' %
(test_filename,
list(image_lists.keys())[predictions[i]]))
# Write out the trained graph and labels with the weights stored as
# constants.
save_graph_to_file(sess, graph, FLAGS.output_graph)
with gfile.FastGFile(FLAGS.output_labels, 'w') as f:
f.write('\n'.join(image_lists.keys()) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--image_dir',
type=str,
default='',
help='Path to folders of labeled images.'
)
parser.add_argument(
'--output_graph',
type=str,
default='/tmp/output_graph.pb',
help='Where to save the trained graph.'
)
parser.add_argument(
'--intermediate_output_graphs_dir',
type=str,
default='/tmp/intermediate_graph/',
help='Where to save the intermediate graphs.'
)
parser.add_argument(
'--intermediate_store_frequency',
type=int,
default=0,
help="""\
How many steps to store intermediate graph. If "0" then will not
store.\
"""
)
parser.add_argument(
'--output_labels',
type=str,
default='/tmp/output_labels.txt',
help='Where to save the trained graph\'s labels.'
)
parser.add_argument(
'--summaries_dir',
type=str,
default='/tmp/retrain_logs',
help='Where to save summary logs for TensorBoard.'
)
parser.add_argument(
'--how_many_training_steps',
type=int,
default=4000,
help='How many training steps to run before ending.'
)
parser.add_argument(
'--learning_rate',
type=float,
default=0.01,
help='How large a learning rate to use when training.'
)
parser.add_argument(
'--testing_percentage',
type=int,
default=10,
help='What percentage of images to use as a test set.'
)
parser.add_argument(
'--validation_percentage',
type=int,
default=10,
help='What percentage of images to use as a validation set.'
)
parser.add_argument(
'--eval_step_interval',
type=int,
default=10,
help='How often to evaluate the training results.'
)
parser.add_argument(
'--train_batch_size',
type=int,
default=100,
help='How many images to train on at a time.'
)
parser.add_argument(
'--test_batch_size',
type=int,
default=-1,
help="""\
How many images to test on. This test set is only used once, to evaluate
the final accuracy of the model after training completes.
A value of -1 causes the entire test set to be used, which leads to more
stable results across runs.\
"""
)
parser.add_argument(
'--validation_batch_size',
type=int,
default=100,
help="""\
How many images to use in an evaluation batch. This validation set is
used much more often than the test set, and is an early indicator of how
accurate the model is during training.
A value of -1 causes the entire validation set to be used, which leads to
more stable results across training iterations, but may be slower on large
training sets.\
"""
)
parser.add_argument(
'--print_misclassified_test_images',
default=False,
help="""\
Whether to print out a list of all misclassified test images.\
""",
action='store_true'
)
parser.add_argument(
'--model_dir',
type=str,
default='/tmp/imagenet',
help="""\
Path to classify_image_graph_def.pb,
imagenet_synset_to_human_label_map.txt, and
imagenet_2012_challenge_label_map_proto.pbtxt.\
"""
)
parser.add_argument(
'--bottleneck_dir',
type=str,
default='/tmp/bottleneck',
help='Path to cache bottleneck layer values as files.'
)
parser.add_argument(
'--final_tensor_name',
type=str,
default='final_result',
help="""\
The name of the output classification layer in the retrained graph.\
"""
)
parser.add_argument(
'--flip_left_right',
default=False,
help="""\
Whether to randomly flip half of the training images horizontally.\
""",
action='store_true'
)
parser.add_argument(
'--random_crop',
type=int,
default=0,
help="""\
A percentage determining how much of a margin to randomly crop off the
training images.\
"""
)
parser.add_argument(
'--random_scale',
type=int,
default=0,
help="""\
A percentage determining how much to randomly scale up the size of the
training images by.\
"""
)
parser.add_argument(
'--random_brightness',
type=int,
default=0,
help="""\
A percentage determining how much to randomly multiply the training image
input pixels up or down by.\
"""
)
parser.add_argument(
'--architecture',
type=str,
default='inception_v3',
help="""\
Which model architecture to use. 'inception_v3' is the most accurate, but
also the slowest. For faster or smaller models, chose a MobileNet with the
form 'mobilenet_<parameter size>_<input_size>[_quantized]'. For example,
'mobilenet_1.0_224' will pick a model that is 17 MB in size and takes 224
pixel input images, while 'mobilenet_0.25_128_quantized' will choose a much
less accurate, but smaller and faster network that's 920 KB on disk and
takes 128x128 images. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html
for more information on Mobilenet.\
""")
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| 41.150602 | 117 | 0.695414 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import hashlib
import os.path
import random
import re
import sys
import tarfile
import numpy as np
from six.moves import urllib
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import tensor_shape
from tensorflow.python.platform import gfile
from tensorflow.python.util import compat
FLAGS = None
# sizes. If you want to adapt this script to work with another model, you will
# need to update these to reflect the values in the network you're using.
MAX_NUM_IMAGES_PER_CLASS = 2 ** 27 - 1
def create_image_lists(image_dir, testing_percentage, validation_percentage):
if not gfile.Exists(image_dir):
tf.logging.error("Image directory '" + image_dir + "' not found.")
return None
result = {}
sub_dirs = [x[0] for x in gfile.Walk(image_dir)]
is_root_dir = True
for sub_dir in sub_dirs:
if is_root_dir:
is_root_dir = False
continue
extensions = ['jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG']
file_list = []
dir_name = os.path.basename(sub_dir)
if dir_name == image_dir:
continue
tf.logging.info("Looking for images in '" + dir_name + "'")
for extension in extensions:
file_glob = os.path.join(image_dir, dir_name, '*.' + extension)
file_list.extend(gfile.Glob(file_glob))
if not file_list:
tf.logging.warning('No files found')
continue
if len(file_list) < 20:
tf.logging.warning(
'WARNING: Folder has less than 20 images, which may cause issues.')
elif len(file_list) > MAX_NUM_IMAGES_PER_CLASS:
tf.logging.warning(
'WARNING: Folder {} has more than {} images. Some images will '
'never be selected.'.format(dir_name, MAX_NUM_IMAGES_PER_CLASS))
label_name = re.sub(r'[^a-z0-9]+', ' ', dir_name.lower())
training_images = []
testing_images = []
validation_images = []
for file_name in file_list:
base_name = os.path.basename(file_name)
hash_name = re.sub(r'_nohash_.*$', '', file_name)
hash_name_hashed = hashlib.sha1(compat.as_bytes(hash_name)).hexdigest()
percentage_hash = ((int(hash_name_hashed, 16) %
(MAX_NUM_IMAGES_PER_CLASS + 1)) *
(100.0 / MAX_NUM_IMAGES_PER_CLASS))
if percentage_hash < validation_percentage:
validation_images.append(base_name)
elif percentage_hash < (testing_percentage + validation_percentage):
testing_images.append(base_name)
else:
training_images.append(base_name)
result[label_name] = {
'dir': dir_name,
'training': training_images,
'testing': testing_images,
'validation': validation_images,
}
return result
def get_image_path(image_lists, label_name, index, image_dir, category):
if label_name not in image_lists:
tf.logging.fatal('Label does not exist %s.', label_name)
label_lists = image_lists[label_name]
if category not in label_lists:
tf.logging.fatal('Category does not exist %s.', category)
category_list = label_lists[category]
if not category_list:
tf.logging.fatal('Label %s has no images in the category %s.',
label_name, category)
mod_index = index % len(category_list)
base_name = category_list[mod_index]
sub_dir = label_lists['dir']
full_path = os.path.join(image_dir, sub_dir, base_name)
return full_path
def get_bottleneck_path(image_lists, label_name, index, bottleneck_dir,
category, architecture):
return get_image_path(image_lists, label_name, index, bottleneck_dir,
category) + '_' + architecture + '.txt'
def create_model_graph(model_info):
with tf.Graph().as_default() as graph:
model_path = os.path.join(FLAGS.model_dir, model_info['model_file_name'])
with gfile.FastGFile(model_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
bottleneck_tensor, resized_input_tensor = (tf.import_graph_def(
graph_def,
name='',
return_elements=[
model_info['bottleneck_tensor_name'],
model_info['resized_input_tensor_name'],
]))
return graph, bottleneck_tensor, resized_input_tensor
def run_bottleneck_on_image(sess, image_data, image_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
resized_input_values = sess.run(decoded_image_tensor,
{image_data_tensor: image_data})
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: resized_input_values})
bottleneck_values = np.squeeze(bottleneck_values)
return bottleneck_values
def maybe_download_and_extract(data_url):
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = data_url.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' %
(filename,
float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(data_url, filepath, _progress)
print()
statinfo = os.stat(filepath)
tf.logging.info('Successfully downloaded', filename, statinfo.st_size,
'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
def ensure_dir_exists(dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name)
bottleneck_path_2_bottleneck_values = {}
def create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor):
tf.logging.info('Creating bottleneck at ' + bottleneck_path)
image_path = get_image_path(image_lists, label_name, index,
image_dir, category)
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
image_data = gfile.FastGFile(image_path, 'rb').read()
try:
bottleneck_values = run_bottleneck_on_image(
sess, image_data, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor)
except Exception as e:
raise RuntimeError('Error during processing file %s (%s)' % (image_path,
str(e)))
bottleneck_string = ','.join(str(x) for x in bottleneck_values)
with open(bottleneck_path, 'w') as bottleneck_file:
bottleneck_file.write(bottleneck_string)
def get_or_create_bottleneck(sess, image_lists, label_name, index, image_dir,
category, bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, architecture):
label_lists = image_lists[label_name]
sub_dir = label_lists['dir']
sub_dir_path = os.path.join(bottleneck_dir, sub_dir)
ensure_dir_exists(sub_dir_path)
bottleneck_path = get_bottleneck_path(image_lists, label_name, index,
bottleneck_dir, category, architecture)
if not os.path.exists(bottleneck_path):
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
did_hit_error = False
try:
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
except ValueError:
tf.logging.warning('Invalid float found, recreating bottleneck')
did_hit_error = True
if did_hit_error:
create_bottleneck_file(bottleneck_path, image_lists, label_name, index,
image_dir, category, sess, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor)
with open(bottleneck_path, 'r') as bottleneck_file:
bottleneck_string = bottleneck_file.read()
# fresh creation
bottleneck_values = [float(x) for x in bottleneck_string.split(',')]
return bottleneck_values
def cache_bottlenecks(sess, image_lists, image_dir, bottleneck_dir,
jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture):
how_many_bottlenecks = 0
ensure_dir_exists(bottleneck_dir)
for label_name, label_lists in image_lists.items():
for category in ['training', 'testing', 'validation']:
category_list = label_lists[category]
for index, unused_base_name in enumerate(category_list):
get_or_create_bottleneck(
sess, image_lists, label_name, index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
how_many_bottlenecks += 1
if how_many_bottlenecks % 100 == 0:
tf.logging.info(
str(how_many_bottlenecks) + ' bottleneck files created.')
def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, architecture):
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
filenames = []
if how_many >= 0:
# Retrieve a random sample of bottlenecks.
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
filenames.append(image_name)
else:
# Retrieve all bottlenecks.
for label_index, label_name in enumerate(image_lists.keys()):
for image_index, image_name in enumerate(
image_lists[label_name][category]):
image_name = get_image_path(image_lists, label_name, image_index,
image_dir, category)
bottleneck = get_or_create_bottleneck(
sess, image_lists, label_name, image_index, image_dir, category,
bottleneck_dir, jpeg_data_tensor, decoded_image_tensor,
resized_input_tensor, bottleneck_tensor, architecture)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck)
ground_truths.append(ground_truth)
filenames.append(image_name)
return bottlenecks, ground_truths, filenames
def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
class_count = len(image_lists.keys())
bottlenecks = []
ground_truths = []
for unused_i in range(how_many):
label_index = random.randrange(class_count)
label_name = list(image_lists.keys())[label_index]
image_index = random.randrange(MAX_NUM_IMAGES_PER_CLASS + 1)
image_path = get_image_path(image_lists, label_name, image_index, image_dir,
category)
if not gfile.Exists(image_path):
tf.logging.fatal('File does not exist %s', image_path)
jpeg_data = gfile.FastGFile(image_path, 'rb').read()
# Note that we materialize the distorted_image_data as a numpy array before
# sending running inference on the image. This involves 2 memory copies and
# might be optimized in other implementations.
distorted_image_data = sess.run(distorted_image,
{input_jpeg_tensor: jpeg_data})
bottleneck_values = sess.run(bottleneck_tensor,
{resized_input_tensor: distorted_image_data})
bottleneck_values = np.squeeze(bottleneck_values)
ground_truth = np.zeros(class_count, dtype=np.float32)
ground_truth[label_index] = 1.0
bottlenecks.append(bottleneck_values)
ground_truths.append(ground_truth)
return bottlenecks, ground_truths
def should_distort_images(flip_left_right, random_crop, random_scale,
random_brightness):
return (flip_left_right or (random_crop != 0) or (random_scale != 0) or
(random_brightness != 0))
def add_input_distortions(flip_left_right, random_crop, random_scale,
random_brightness, input_width, input_height,
input_depth, input_mean, input_std):
jpeg_data = tf.placeholder(tf.string, name='DistortJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
margin_scale = 1.0 + (random_crop / 100.0)
resize_scale = 1.0 + (random_scale / 100.0)
margin_scale_value = tf.constant(margin_scale)
resize_scale_value = tf.random_uniform(tensor_shape.scalar(),
minval=1.0,
maxval=resize_scale)
scale_value = tf.multiply(margin_scale_value, resize_scale_value)
precrop_width = tf.multiply(scale_value, input_width)
precrop_height = tf.multiply(scale_value, input_height)
precrop_shape = tf.stack([precrop_height, precrop_width])
precrop_shape_as_int = tf.cast(precrop_shape, dtype=tf.int32)
precropped_image = tf.image.resize_bilinear(decoded_image_4d,
precrop_shape_as_int)
precropped_image_3d = tf.squeeze(precropped_image, squeeze_dims=[0])
cropped_image = tf.random_crop(precropped_image_3d,
[input_height, input_width, input_depth])
if flip_left_right:
flipped_image = tf.image.random_flip_left_right(cropped_image)
else:
flipped_image = cropped_image
brightness_min = 1.0 - (random_brightness / 100.0)
brightness_max = 1.0 + (random_brightness / 100.0)
brightness_value = tf.random_uniform(tensor_shape.scalar(),
minval=brightness_min,
maxval=brightness_max)
brightened_image = tf.multiply(flipped_image, brightness_value)
offset_image = tf.subtract(brightened_image, input_mean)
mul_image = tf.multiply(offset_image, 1.0 / input_std)
distort_result = tf.expand_dims(mul_image, 0, name='DistortResult')
return jpeg_data, distort_result
def variable_summaries(var):
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var)
def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor,
bottleneck_tensor_size):
with tf.name_scope('input'):
bottleneck_input = tf.placeholder_with_default(
bottleneck_tensor,
shape=[None, bottleneck_tensor_size],
name='BottleneckInputPlaceholder')
ground_truth_input = tf.placeholder(tf.float32,
[None, class_count],
name='GroundTruthInput')
# Organizing the following ops as `final_training_ops` so they're easier
layer_name = 'final_training_ops'
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
initial_value = tf.truncated_normal(
[bottleneck_tensor_size, class_count], stddev=0.001)
layer_weights = tf.Variable(initial_value, name='final_weights')
variable_summaries(layer_weights)
with tf.name_scope('biases'):
layer_biases = tf.Variable(tf.zeros([class_count]), name='final_biases')
variable_summaries(layer_biases)
with tf.name_scope('Wx_plus_b'):
logits = tf.matmul(bottleneck_input, layer_weights) + layer_biases
tf.summary.histogram('pre_activations', logits)
final_tensor = tf.nn.softmax(logits, name=final_tensor_name)
tf.summary.histogram('activations', final_tensor)
with tf.name_scope('cross_entropy'):
cross_entropy = tf.nn.weighted_cross_entropy_with_logits(targets=ground_truth_input, logits=logits, pos_weight=4)
with tf.name_scope('total'):
cross_entropy_mean = tf.reduce_mean(cross_entropy)
tf.summary.scalar('cross_entropy', cross_entropy_mean)
with tf.name_scope('train'):
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
train_step = optimizer.minimize(cross_entropy_mean)
return (train_step, cross_entropy_mean, bottleneck_input, ground_truth_input,
final_tensor)
def add_evaluation_step(result_tensor, ground_truth_tensor):
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
prediction = tf.argmax(result_tensor, 1)
correct_prediction = tf.equal(
prediction, tf.argmax(ground_truth_tensor, 1))
with tf.name_scope('accuracy'):
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
return evaluation_step, prediction
def save_graph_to_file(sess, graph, graph_file_name):
output_graph_def = graph_util.convert_variables_to_constants(
sess, graph.as_graph_def(), [FLAGS.final_tensor_name])
with gfile.FastGFile(graph_file_name, 'wb') as f:
f.write(output_graph_def.SerializeToString())
return
def prepare_file_system():
if tf.gfile.Exists(FLAGS.summaries_dir):
tf.gfile.DeleteRecursively(FLAGS.summaries_dir)
tf.gfile.MakeDirs(FLAGS.summaries_dir)
if FLAGS.intermediate_store_frequency > 0:
ensure_dir_exists(FLAGS.intermediate_output_graphs_dir)
return
def create_model_info(architecture):
architecture = architecture.lower()
if architecture == 'inception_v3':
# pylint: disable=line-too-long
data_url = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long
bottleneck_tensor_name = 'pool_3/_reshape:0'
bottleneck_tensor_size = 2048
input_width = 299
input_height = 299
input_depth = 3
resized_input_tensor_name = 'Mul:0'
model_file_name = 'classify_image_graph_def.pb'
input_mean = 128
input_std = 128
elif architecture.startswith('mobilenet_'):
parts = architecture.split('_')
if len(parts) != 3 and len(parts) != 4:
tf.logging.error("Couldn't understand architecture name '%s'",
architecture)
return None
version_string = parts[1]
if (version_string != '1.0' and version_string != '0.75' and
version_string != '0.50' and version_string != '0.25'):
tf.logging.error(
""""The Mobilenet version should be '1.0', '0.75', '0.50', or '0.25',
but found '%s' for architecture '%s'""",
version_string, architecture)
return None
size_string = parts[2]
if (size_string != '224' and size_string != '192' and
size_string != '160' and size_string != '128'):
tf.logging.error(
"""The Mobilenet input size should be '224', '192', '160', or '128',
but found '%s' for architecture '%s'""",
size_string, architecture)
return None
if len(parts) == 3:
is_quantized = False
else:
if parts[3] != 'quantized':
tf.logging.error(
"Couldn't understand architecture suffix '%s' for '%s'", parts[3],
architecture)
return None
is_quantized = True
data_url = 'http://download.tensorflow.org/models/mobilenet_v1_'
data_url += version_string + '_' + size_string + '_frozen.tgz'
bottleneck_tensor_name = 'MobilenetV1/Predictions/Reshape:0'
bottleneck_tensor_size = 1001
input_width = int(size_string)
input_height = int(size_string)
input_depth = 3
resized_input_tensor_name = 'input:0'
if is_quantized:
model_base_name = 'quantized_graph.pb'
else:
model_base_name = 'frozen_graph.pb'
model_dir_name = 'mobilenet_v1_' + version_string + '_' + size_string
model_file_name = os.path.join(model_dir_name, model_base_name)
input_mean = 127.5
input_std = 127.5
else:
tf.logging.error("Couldn't understand architecture name '%s'", architecture)
raise ValueError('Unknown architecture', architecture)
return {
'data_url': data_url,
'bottleneck_tensor_name': bottleneck_tensor_name,
'bottleneck_tensor_size': bottleneck_tensor_size,
'input_width': input_width,
'input_height': input_height,
'input_depth': input_depth,
'resized_input_tensor_name': resized_input_tensor_name,
'model_file_name': model_file_name,
'input_mean': input_mean,
'input_std': input_std,
}
def add_jpeg_decoding(input_width, input_height, input_depth, input_mean,
input_std):
jpeg_data = tf.placeholder(tf.string, name='DecodeJPGInput')
decoded_image = tf.image.decode_jpeg(jpeg_data, channels=input_depth)
decoded_image_as_float = tf.cast(decoded_image, dtype=tf.float32)
decoded_image_4d = tf.expand_dims(decoded_image_as_float, 0)
resize_shape = tf.stack([input_height, input_width])
resize_shape_as_int = tf.cast(resize_shape, dtype=tf.int32)
resized_image = tf.image.resize_bilinear(decoded_image_4d,
resize_shape_as_int)
offset_image = tf.subtract(resized_image, input_mean)
mul_image = tf.multiply(offset_image, 1.0 / input_std)
return jpeg_data, mul_image
def main(_):
# Needed to make sure the logging output is visible.
# See https://github.com/tensorflow/tensorflow/issues/3047
tf.logging.set_verbosity(tf.logging.INFO)
# Prepare necessary directories that can be used during training
prepare_file_system()
# Gather information about the model architecture we'll be using.
model_info = create_model_info(FLAGS.architecture)
if not model_info:
tf.logging.error('Did not recognize architecture flag')
return -1
# Set up the pre-trained graph.
maybe_download_and_extract(model_info['data_url'])
graph, bottleneck_tensor, resized_image_tensor = (
create_model_graph(model_info))
# Look at the folder structure, and create lists of all the images.
image_lists = create_image_lists(FLAGS.image_dir, FLAGS.testing_percentage,
FLAGS.validation_percentage)
class_count = len(image_lists.keys())
if class_count == 0:
tf.logging.error('No valid folders of images found at ' + FLAGS.image_dir)
return -1
if class_count == 1:
tf.logging.error('Only one valid folder of images found at ' +
FLAGS.image_dir +
' - multiple classes are needed for classification.')
return -1
# See if the command-line flags mean we're applying any distortions.
do_distort_images = should_distort_images(
FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
FLAGS.random_brightness)
with tf.Session(graph=graph) as sess:
# Set up the image decoding sub-graph.
jpeg_data_tensor, decoded_image_tensor = add_jpeg_decoding(
model_info['input_width'], model_info['input_height'],
model_info['input_depth'], model_info['input_mean'],
model_info['input_std'])
if do_distort_images:
# We will be applying distortions, so setup the operations we'll need.
(distorted_jpeg_data_tensor,
distorted_image_tensor) = add_input_distortions(
FLAGS.flip_left_right, FLAGS.random_crop, FLAGS.random_scale,
FLAGS.random_brightness, model_info['input_width'],
model_info['input_height'], model_info['input_depth'],
model_info['input_mean'], model_info['input_std'])
else:
# We'll make sure we've calculated the 'bottleneck' image summaries and
# cached them on disk.
cache_bottlenecks(sess, image_lists, FLAGS.image_dir,
FLAGS.bottleneck_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor,
bottleneck_tensor, FLAGS.architecture)
# Add the new layer that we'll be training.
(train_step, cross_entropy, bottleneck_input, ground_truth_input,
final_tensor) = add_final_training_ops(
len(image_lists.keys()), FLAGS.final_tensor_name, bottleneck_tensor,
model_info['bottleneck_tensor_size'])
# Create the operations we need to evaluate the accuracy of our new layer.
evaluation_step, prediction = add_evaluation_step(
final_tensor, ground_truth_input)
# Merge all the summaries and write them out to the summaries_dir
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train',
sess.graph)
validation_writer = tf.summary.FileWriter(
FLAGS.summaries_dir + '/validation')
# Set up all our weights to their initial default values.
init = tf.global_variables_initializer()
sess.run(init)
# Run the training for as many cycles as requested on the command line.
for i in range(FLAGS.how_many_training_steps):
# Get a batch of input bottleneck values, either calculated fresh every
# time with distortions applied, or from the cache stored on disk.
if do_distort_images:
(train_bottlenecks,
train_ground_truth) = get_random_distorted_bottlenecks(
sess, image_lists, FLAGS.train_batch_size, 'training',
FLAGS.image_dir, distorted_jpeg_data_tensor,
distorted_image_tensor, resized_image_tensor, bottleneck_tensor)
else:
(train_bottlenecks,
train_ground_truth, _) = get_random_cached_bottlenecks(
sess, image_lists, FLAGS.train_batch_size, 'training',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture)
# Feed the bottlenecks and ground truth into the graph, and run a training
# step. Capture training summaries for TensorBoard with the `merged` op.
train_summary, _ = sess.run(
[merged, train_step],
feed_dict={bottleneck_input: train_bottlenecks,
ground_truth_input: train_ground_truth})
train_writer.add_summary(train_summary, i)
# Every so often, print out how well the graph is training.
is_last_step = (i + 1 == FLAGS.how_many_training_steps)
if (i % FLAGS.eval_step_interval) == 0 or is_last_step:
train_accuracy, cross_entropy_value = sess.run(
[evaluation_step, cross_entropy],
feed_dict={bottleneck_input: train_bottlenecks,
ground_truth_input: train_ground_truth})
tf.logging.info('%s: Step %d: Train accuracy = %.1f%%' %
(datetime.now(), i, train_accuracy * 100))
tf.logging.info('%s: Step %d: Cross entropy = %f' %
(datetime.now(), i, cross_entropy_value))
validation_bottlenecks, validation_ground_truth, _ = (
get_random_cached_bottlenecks(
sess, image_lists, FLAGS.validation_batch_size, 'validation',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture))
# Run a validation step and capture training summaries for TensorBoard
# with the `merged` op.
validation_summary, validation_accuracy = sess.run(
[merged, evaluation_step],
feed_dict={bottleneck_input: validation_bottlenecks,
ground_truth_input: validation_ground_truth})
validation_writer.add_summary(validation_summary, i)
tf.logging.info('%s: Step %d: Validation accuracy = %.1f%% (N=%d)' %
(datetime.now(), i, validation_accuracy * 100,
len(validation_bottlenecks)))
# Store intermediate results
intermediate_frequency = FLAGS.intermediate_store_frequency
if (intermediate_frequency > 0 and (i % intermediate_frequency == 0)
and i > 0):
intermediate_file_name = (FLAGS.intermediate_output_graphs_dir +
'intermediate_' + str(i) + '.pb')
tf.logging.info('Save intermediate result to : ' +
intermediate_file_name)
save_graph_to_file(sess, graph, intermediate_file_name)
# We've completed all our training, so run a final test evaluation on
# some new images we haven't used before.
test_bottlenecks, test_ground_truth, test_filenames = (
get_random_cached_bottlenecks(
sess, image_lists, FLAGS.test_batch_size, 'testing',
FLAGS.bottleneck_dir, FLAGS.image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_image_tensor, bottleneck_tensor,
FLAGS.architecture))
test_accuracy, predictions = sess.run(
[evaluation_step, prediction],
feed_dict={bottleneck_input: test_bottlenecks,
ground_truth_input: test_ground_truth})
tf.logging.info('Final test accuracy = %.1f%% (N=%d)' %
(test_accuracy * 100, len(test_bottlenecks)))
if FLAGS.print_misclassified_test_images:
tf.logging.info('=== MISCLASSIFIED TEST IMAGES ===')
for i, test_filename in enumerate(test_filenames):
if predictions[i] != test_ground_truth[i].argmax():
tf.logging.info('%70s %s' %
(test_filename,
list(image_lists.keys())[predictions[i]]))
# Write out the trained graph and labels with the weights stored as
# constants.
save_graph_to_file(sess, graph, FLAGS.output_graph)
with gfile.FastGFile(FLAGS.output_labels, 'w') as f:
f.write('\n'.join(image_lists.keys()) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--image_dir',
type=str,
default='',
help='Path to folders of labeled images.'
)
parser.add_argument(
'--output_graph',
type=str,
default='/tmp/output_graph.pb',
help='Where to save the trained graph.'
)
parser.add_argument(
'--intermediate_output_graphs_dir',
type=str,
default='/tmp/intermediate_graph/',
help='Where to save the intermediate graphs.'
)
parser.add_argument(
'--intermediate_store_frequency',
type=int,
default=0,
help="""\
How many steps to store intermediate graph. If "0" then will not
store.\
"""
)
parser.add_argument(
'--output_labels',
type=str,
default='/tmp/output_labels.txt',
help='Where to save the trained graph\'s labels.'
)
parser.add_argument(
'--summaries_dir',
type=str,
default='/tmp/retrain_logs',
help='Where to save summary logs for TensorBoard.'
)
parser.add_argument(
'--how_many_training_steps',
type=int,
default=4000,
help='How many training steps to run before ending.'
)
parser.add_argument(
'--learning_rate',
type=float,
default=0.01,
help='How large a learning rate to use when training.'
)
parser.add_argument(
'--testing_percentage',
type=int,
default=10,
help='What percentage of images to use as a test set.'
)
parser.add_argument(
'--validation_percentage',
type=int,
default=10,
help='What percentage of images to use as a validation set.'
)
parser.add_argument(
'--eval_step_interval',
type=int,
default=10,
help='How often to evaluate the training results.'
)
parser.add_argument(
'--train_batch_size',
type=int,
default=100,
help='How many images to train on at a time.'
)
parser.add_argument(
'--test_batch_size',
type=int,
default=-1,
help="""\
How many images to test on. This test set is only used once, to evaluate
the final accuracy of the model after training completes.
A value of -1 causes the entire test set to be used, which leads to more
stable results across runs.\
"""
)
parser.add_argument(
'--validation_batch_size',
type=int,
default=100,
help="""\
How many images to use in an evaluation batch. This validation set is
used much more often than the test set, and is an early indicator of how
accurate the model is during training.
A value of -1 causes the entire validation set to be used, which leads to
more stable results across training iterations, but may be slower on large
training sets.\
"""
)
parser.add_argument(
'--print_misclassified_test_images',
default=False,
help="""\
Whether to print out a list of all misclassified test images.\
""",
action='store_true'
)
parser.add_argument(
'--model_dir',
type=str,
default='/tmp/imagenet',
help="""\
Path to classify_image_graph_def.pb,
imagenet_synset_to_human_label_map.txt, and
imagenet_2012_challenge_label_map_proto.pbtxt.\
"""
)
parser.add_argument(
'--bottleneck_dir',
type=str,
default='/tmp/bottleneck',
help='Path to cache bottleneck layer values as files.'
)
parser.add_argument(
'--final_tensor_name',
type=str,
default='final_result',
help="""\
The name of the output classification layer in the retrained graph.\
"""
)
parser.add_argument(
'--flip_left_right',
default=False,
help="""\
Whether to randomly flip half of the training images horizontally.\
""",
action='store_true'
)
parser.add_argument(
'--random_crop',
type=int,
default=0,
help="""\
A percentage determining how much of a margin to randomly crop off the
training images.\
"""
)
parser.add_argument(
'--random_scale',
type=int,
default=0,
help="""\
A percentage determining how much to randomly scale up the size of the
training images by.\
"""
)
parser.add_argument(
'--random_brightness',
type=int,
default=0,
help="""\
A percentage determining how much to randomly multiply the training image
input pixels up or down by.\
"""
)
parser.add_argument(
'--architecture',
type=str,
default='inception_v3',
help="""\
Which model architecture to use. 'inception_v3' is the most accurate, but
also the slowest. For faster or smaller models, chose a MobileNet with the
form 'mobilenet_<parameter size>_<input_size>[_quantized]'. For example,
'mobilenet_1.0_224' will pick a model that is 17 MB in size and takes 224
pixel input images, while 'mobilenet_0.25_128_quantized' will choose a much
less accurate, but smaller and faster network that's 920 KB on disk and
takes 128x128 images. See https://research.googleblog.com/2017/06/mobilenets-open-source-models-for.html
for more information on Mobilenet.\
""")
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| true | true |
f729b16d943dfdb4f2468565aeed0996583d5e50 | 8,458 | py | Python | test/test_petstore.py | gluhar2006/schemathesis | 3cb6b0b4f5d93242da1f2e79575b6b7b3b7a63d1 | [
"MIT"
] | 563 | 2019-08-26T05:22:12.000Z | 2020-09-02T11:54:17.000Z | test/test_petstore.py | gluhar2006/schemathesis | 3cb6b0b4f5d93242da1f2e79575b6b7b3b7a63d1 | [
"MIT"
] | 651 | 2019-08-23T09:16:35.000Z | 2020-09-02T08:30:10.000Z | test/test_petstore.py | gluhar2006/schemathesis | 3cb6b0b4f5d93242da1f2e79575b6b7b3b7a63d1 | [
"MIT"
] | 43 | 2019-09-10T09:25:17.000Z | 2020-07-06T10:00:38.000Z | import pytest
from hypothesis import settings
@pytest.fixture(params=["petstore_v2.yaml", "petstore_v3.yaml"])
def testdir(request, testdir):
def make_petstore_test(*args, **kwargs):
kwargs["schema_name"] = request.param
testdir.make_test(*args, **kwargs)
testdir.make_petstore_test = make_petstore_test
def assert_petstore(passed=1, tests_num=5, skipped=0):
result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=passed, skipped=skipped)
result.stdout.re_match_lines([rf"Hypothesis calls: {tests_num}"])
testdir.assert_petstore = assert_petstore
testdir.param = request.param # `request.param` is not available in test for some reason
return testdir
@pytest.fixture
def reload_profile():
# Setting Hypothesis profile in a pytester-style test leads to overriding it globally
yield
settings.load_profile("default")
@pytest.mark.usefixtures("reload_profile")
def test_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet$")
@settings(max_examples=5, deadline=None, suppress_health_check=HealthCheck.all())
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.body["name"])
assert_list(case.body["photoUrls"])
assert_requests_call(case)
"""
)
result = testdir.runpytest("-v", "-s", "--hypothesis-verbosity=verbose")
result.assert_outcomes(passed=2)
result.stdout.re_match_lines(["Can't serialize data to"])
def test_find_by_status(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/findByStatus$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.query["status"])
for item in case.query["status"]:
assert item in ("available", "pending", "sold")
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_find_by_tag(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/findByTags$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.query["tags"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_get_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_update_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="POST", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None, suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow])
def test_(request, case):
assume(case.body is not NOT_SET)
assume("name" in case.body)
assume("status" in case.body)
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_str(case.body["name"])
assert_str(case.body["status"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_str(case.headers["api_key"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_upload_image(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/{petId}/uploadImage$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
assume(case.body is not NOT_SET)
assert_int(case.path_parameters["petId"])
if case.operation.schema.spec_version == "2.0":
assume("additionalMetadata" in case.body)
assert_str(case.body["additionalMetadata"])
assert_requests_call(case)
request.config.HYPOTHESIS_CASES += 1
"""
)
testdir.assert_petstore()
def test_get_inventory(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/store/inventory$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert not case.path_parameters
assert case.body is NOT_SET
assert not case.query
assert_requests_call(case)
"""
)
testdir.assert_petstore(tests_num=5)
def test_create_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/store/order$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_get_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/store/order/{orderId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["orderId"])
assert case.path_parameters["orderId"] in range(1, 11)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/store/order/{orderId}$")
@settings(max_examples=5, suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["orderId"])
assert case.path_parameters["orderId"] >= 1
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_create_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert isinstance(case.body, dict)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_create_multiple_users(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/createWith")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.body)
assert_requests_call(case)
"""
)
testdir.assert_petstore(2, 10)
def test_login(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/login")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.query["username"])
assert_str(case.query["password"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_logout(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/logout")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert not case.path_parameters
assert case.body is NOT_SET
assert not case.query
assert_requests_call(case)
"""
)
testdir.assert_petstore(tests_num=1)
def test_get_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_update_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="PUT", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert isinstance(case.body, dict)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
| 27.822368 | 115 | 0.712107 | import pytest
from hypothesis import settings
@pytest.fixture(params=["petstore_v2.yaml", "petstore_v3.yaml"])
def testdir(request, testdir):
def make_petstore_test(*args, **kwargs):
kwargs["schema_name"] = request.param
testdir.make_test(*args, **kwargs)
testdir.make_petstore_test = make_petstore_test
def assert_petstore(passed=1, tests_num=5, skipped=0):
result = testdir.runpytest("-v", "-s")
result.assert_outcomes(passed=passed, skipped=skipped)
result.stdout.re_match_lines([rf"Hypothesis calls: {tests_num}"])
testdir.assert_petstore = assert_petstore
testdir.param = request.param
return testdir
@pytest.fixture
def reload_profile():
yield
settings.load_profile("default")
@pytest.mark.usefixtures("reload_profile")
def test_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet$")
@settings(max_examples=5, deadline=None, suppress_health_check=HealthCheck.all())
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.body["name"])
assert_list(case.body["photoUrls"])
assert_requests_call(case)
"""
)
result = testdir.runpytest("-v", "-s", "--hypothesis-verbosity=verbose")
result.assert_outcomes(passed=2)
result.stdout.re_match_lines(["Can't serialize data to"])
def test_find_by_status(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/findByStatus$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.query["status"])
for item in case.query["status"]:
assert item in ("available", "pending", "sold")
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_find_by_tag(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/findByTags$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.query["tags"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_get_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_update_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="POST", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None, suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow])
def test_(request, case):
assume(case.body is not NOT_SET)
assume("name" in case.body)
assume("status" in case.body)
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_str(case.body["name"])
assert_str(case.body["status"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_pet(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/pet/{petId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["petId"])
assert_str(case.headers["api_key"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_upload_image(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/pet/{petId}/uploadImage$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
assume(case.body is not NOT_SET)
assert_int(case.path_parameters["petId"])
if case.operation.schema.spec_version == "2.0":
assume("additionalMetadata" in case.body)
assert_str(case.body["additionalMetadata"])
assert_requests_call(case)
request.config.HYPOTHESIS_CASES += 1
"""
)
testdir.assert_petstore()
def test_get_inventory(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/store/inventory$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert not case.path_parameters
assert case.body is NOT_SET
assert not case.query
assert_requests_call(case)
"""
)
testdir.assert_petstore(tests_num=5)
def test_create_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/store/order$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_get_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/store/order/{orderId}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["orderId"])
assert case.path_parameters["orderId"] in range(1, 11)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_order(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/store/order/{orderId}$")
@settings(max_examples=5, suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.too_slow], deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_int(case.path_parameters["orderId"])
assert case.path_parameters["orderId"] >= 1
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_create_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert isinstance(case.body, dict)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_create_multiple_users(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/createWith")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_list(case.body)
assert_requests_call(case)
"""
)
testdir.assert_petstore(2, 10)
def test_login(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/login")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.query["username"])
assert_str(case.query["password"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_logout(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(endpoint="/user/logout")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert not case.path_parameters
assert case.body is NOT_SET
assert not case.query
assert_requests_call(case)
"""
)
testdir.assert_petstore(tests_num=1)
def test_get_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="GET", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_update_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="PUT", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert isinstance(case.body, dict)
assert_requests_call(case)
"""
)
testdir.assert_petstore()
def test_delete_user(testdir):
testdir.make_petstore_test(
"""
@schema.parametrize(method="DELETE", endpoint="/user/{username}$")
@settings(max_examples=5, deadline=None)
def test_(request, case):
request.config.HYPOTHESIS_CASES += 1
assert_str(case.path_parameters["username"])
assert_requests_call(case)
"""
)
testdir.assert_petstore()
| true | true |
f729b1b311c9f11041cb2ea4a3e55a3ec73a5e4b | 244 | py | Python | server/schema/types.py | kfields/django-arcade | 24df3d43dde2d69df333529d8790507fb1f5fcf1 | [
"MIT"
] | 1 | 2021-10-03T05:44:32.000Z | 2021-10-03T05:44:32.000Z | server/schema/types.py | kfields/django-arcade | 24df3d43dde2d69df333529d8790507fb1f5fcf1 | [
"MIT"
] | null | null | null | server/schema/types.py | kfields/django-arcade | 24df3d43dde2d69df333529d8790507fb1f5fcf1 | [
"MIT"
] | null | null | null | from ariadne import ObjectType
user = ObjectType("User")
game = ObjectType("Game")
#game_event = ObjectType("GameEvent")
#join_game_event = ObjectType("JoinEvent")
object_types = [
user,
game,
#game_event,
#join_game_event,
]
| 17.428571 | 42 | 0.70082 | from ariadne import ObjectType
user = ObjectType("User")
game = ObjectType("Game")
object_types = [
user,
game,
]
| true | true |
f729b27bfcd1b92623618c962f8fb8b8a2d0626a | 9,496 | py | Python | models/Deeplab.py | iriszero/DepthAwareCNNplus | 5dcc0a9279d53a2826d76631f097959d52982f8b | [
"MIT"
] | 4 | 2019-08-22T14:34:23.000Z | 2020-09-28T10:14:09.000Z | models/Deeplab.py | jshuhnow/DepthAwareCNNplus | 5dcc0a9279d53a2826d76631f097959d52982f8b | [
"MIT"
] | 2 | 2019-03-29T02:34:44.000Z | 2020-11-14T01:56:07.000Z | models/Deeplab.py | jshuhnow/DepthAwareCNNplus | 5dcc0a9279d53a2826d76631f097959d52982f8b | [
"MIT"
] | 5 | 2019-03-13T02:30:16.000Z | 2020-04-01T02:41:28.000Z | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from .base_model import BaseModel
import numpy as np
from . import losses
import shutil
from utils.util import *
from torch.autograd import Variable
from collections import OrderedDict
from tensorboardX import SummaryWriter
import os
from . import VGG_Deeplab
class Deeplab_VGG(nn.Module):
def __init__(self, num_classes, depthconv=False):
super(Deeplab_VGG,self).__init__()
self.Scale = VGG_Deeplab.vgg16(num_classes=num_classes,depthconv=depthconv)
def forward(self,x, depth=None):
output = self.Scale(x,depth) # for original scale
return output
#------------------------------------------------------#
class Deeplab_Solver(BaseModel):
def __init__(self, opt, dataset=None, encoder='VGG'):
BaseModel.initialize(self, opt)
self.encoder = encoder
if encoder == 'VGG':
self.model = Deeplab_VGG(self.opt.label_nc, self.opt.depthconv)
if self.opt.isTrain:
self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()
# self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()
# self.criterionSeg = nn.NLLLoss2d(ignore_index=255)#.cuda()
if encoder == 'VGG':
self.optimizer = torch.optim.SGD([{'params': self.model.Scale.get_1x_lr_params_NOscale(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_10x_lr_params(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_2x_lr_params_NOscale(), 'lr': self.opt.lr, 'weight_decay': 0.},
{'params': self.model.Scale.get_20x_lr_params(), 'lr': self.opt.lr, 'weight_decay': 0.}
],
lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)
# self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)
self.old_lr = self.opt.lr
self.averageloss = []
# copy scripts
self.model_path = './models' #os.path.dirname(os.path.realpath(__file__))
self.data_path = './data' #os.path.dirname(os.path.realpath(__file__))
shutil.copyfile(os.path.join(self.model_path, 'Deeplab.py'), os.path.join(self.model_dir, 'Deeplab.py'))
if encoder == 'VGG':
shutil.copyfile(os.path.join(self.model_path, 'VGG_Deeplab.py'), os.path.join(self.model_dir, 'VGG_Deeplab.py'))
shutil.copyfile(os.path.join(self.model_path, 'model_utils.py'), os.path.join(self.model_dir, 'model_utils.py'))
shutil.copyfile(os.path.join(self.data_path, dataset.datafile), os.path.join(self.model_dir, dataset.datafile))
shutil.copyfile(os.path.join(self.data_path, 'base_dataset.py'), os.path.join(self.model_dir, 'base_dataset.py'))
self.writer = SummaryWriter(self.tensorborad_dir)
self.counter = 0
if not self.isTrain or self.opt.continue_train:
if self.opt.pretrained_model!='':
self.load_pretrained_network(self.model, self.opt.pretrained_model, self.opt.which_epoch, strict=False)
print("Successfully loaded from pretrained model with given path!")
else:
self.load()
print("Successfully loaded model, continue training....!")
self.model.cuda()
self.normweightgrad=0.
# if len(opt.gpu_ids):#opt.isTrain and
# self.model = torch.nn.DataParallel(self.model, device_ids=opt.gpu_ids)
def forward(self, data, isTrain=True):
self.model.zero_grad()
self.image = Variable(data['image'], volatile=not isTrain).cuda()
if 'depth' in data.keys():
self.depth = Variable(data['depth'], volatile=not isTrain).cuda()
else:
self.depth = None
if data['seg'] is not None:
self.seggt = Variable(data['seg'], volatile=not isTrain).cuda()
else:
self.seggt = None
input_size = self.image.size()
self.segpred = self.model(self.image,self.depth)
self.segpred = nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear')
# self.segpred = nn.functional.log_softmax(nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear'))
if self.opt.isTrain:
self.loss = self.criterionSeg(self.segpred, torch.squeeze(self.seggt,1).long())
self.averageloss += [self.loss.data[0]]
# self.averageloss += [self.loss.item()]
segpred = self.segpred.max(1, keepdim=True)[1]
return self.seggt, segpred
def backward(self, step, total_step):
self.loss.backward()
self.optimizer.step()
# print self.model.Scale.classifier.fc6_2.weight.grad.mean().data.cpu().numpy()
# self.normweightgrad +=self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()
# print self.normweightgrad#self.model.Scale.classifier.norm.scale.grad.mean().data.cpu().numpy()
if step % self.opt.iterSize == 0:
self.update_learning_rate(step, total_step)
trainingavgloss = np.mean(self.averageloss)
if self.opt.verbose:
print (' Iter: %d, Loss: %f' % (step, trainingavgloss) )
def get_visuals(self, step):
############## Display results and errors ############
if self.opt.isTrain:
self.trainingavgloss = np.mean(self.averageloss)
if self.opt.verbose:
print (' Iter: %d, Loss: %f' % (step, self.trainingavgloss) )
self.writer.add_scalar(self.opt.name+'/trainingloss/', self.trainingavgloss, step)
self.averageloss = []
if self.depth is not None:
return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),
('depth', tensor2im(self.depth.data[0], inputmode='divstd-mean')),
('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
else:
return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),
('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
def update_tensorboard(self, data, step):
if self.opt.isTrain:
self.writer.add_scalar(self.opt.name+'/Accuracy/', data[0], step)
self.writer.add_scalar(self.opt.name+'/Accuracy_Class/', data[1], step)
self.writer.add_scalar(self.opt.name+'/Mean_IoU/', data[2], step)
self.writer.add_scalar(self.opt.name+'/FWAV_Accuracy/', data[3], step)
self.trainingavgloss = np.mean(self.averageloss)
self.writer.add_scalars(self.opt.name+'/loss', {"train": self.trainingavgloss,
"val": np.mean(self.averageloss)}, step)
self.writer.add_scalars('trainingavgloss/', {self.opt.name: self.trainingavgloss}, step)
self.writer.add_scalars('valloss/', {self.opt.name: np.mean(self.averageloss)}, step)
self.writer.add_scalars('val_MeanIoU/', {self.opt.name: data[2]}, step)
file_name = os.path.join(self.save_dir, 'MIoU.txt')
with open(file_name, 'wt') as opt_file:
opt_file.write('%f\n' % (data[2]))
# self.writer.add_scalars('losses/'+self.opt.name, {"train": self.trainingavgloss,
# "val": np.mean(self.averageloss)}, step)
self.averageloss = []
def save(self, which_epoch):
# self.save_network(self.netG, 'G', which_epoch, self.gpu_ids)
self.save_network(self.model, 'net', which_epoch, self.gpu_ids)
def load(self):
self.load_network(self.model, 'net',self.opt.which_epoch)
def update_learning_rate(self, step, total_step):
lr = max(self.opt.lr * ((1 - float(step) / total_step) ** (self.opt.lr_power)), 1e-6)
# drop_ratio = (1. * float(total_step - step) / (total_step - step + 1)) ** self.opt.lr_power
# lr = self.old_lr * drop_ratio
self.writer.add_scalar(self.opt.name+'/Learning_Rate/', lr, step)
self.optimizer.param_groups[0]['lr'] = lr
self.optimizer.param_groups[1]['lr'] = lr
self.optimizer.param_groups[2]['lr'] = lr
self.optimizer.param_groups[3]['lr'] = lr
# self.optimizer.param_groups[0]['lr'] = lr
# self.optimizer.param_groups[1]['lr'] = lr*10
# self.optimizer.param_groups[2]['lr'] = lr*2 #* 100
# self.optimizer.param_groups[3]['lr'] = lr*20
# self.optimizer.param_groups[4]['lr'] = lr*100
# torch.nn.utils.clip_grad_norm(self.model.Scale.get_1x_lr_params_NOscale(), 1.)
# torch.nn.utils.clip_grad_norm(self.model.Scale.get_10x_lr_params(), 1.)
if self.opt.verbose:
print(' update learning rate: %f -> %f' % (self.old_lr, lr))
self.old_lr = lr
| 49.458333 | 144 | 0.600253 | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from .base_model import BaseModel
import numpy as np
from . import losses
import shutil
from utils.util import *
from torch.autograd import Variable
from collections import OrderedDict
from tensorboardX import SummaryWriter
import os
from . import VGG_Deeplab
class Deeplab_VGG(nn.Module):
def __init__(self, num_classes, depthconv=False):
super(Deeplab_VGG,self).__init__()
self.Scale = VGG_Deeplab.vgg16(num_classes=num_classes,depthconv=depthconv)
def forward(self,x, depth=None):
output = self.Scale(x,depth)
return output
class Deeplab_Solver(BaseModel):
def __init__(self, opt, dataset=None, encoder='VGG'):
BaseModel.initialize(self, opt)
self.encoder = encoder
if encoder == 'VGG':
self.model = Deeplab_VGG(self.opt.label_nc, self.opt.depthconv)
if self.opt.isTrain:
self.criterionSeg = torch.nn.CrossEntropyLoss(ignore_index=255).cuda()
if encoder == 'VGG':
self.optimizer = torch.optim.SGD([{'params': self.model.Scale.get_1x_lr_params_NOscale(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_10x_lr_params(), 'lr': self.opt.lr},
{'params': self.model.Scale.get_2x_lr_params_NOscale(), 'lr': self.opt.lr, 'weight_decay': 0.},
{'params': self.model.Scale.get_20x_lr_params(), 'lr': self.opt.lr, 'weight_decay': 0.}
],
lr=self.opt.lr, momentum=self.opt.momentum, weight_decay=self.opt.wd)
self.old_lr = self.opt.lr
self.averageloss = []
self.model_path = './models'
self.data_path = './data'
shutil.copyfile(os.path.join(self.model_path, 'Deeplab.py'), os.path.join(self.model_dir, 'Deeplab.py'))
if encoder == 'VGG':
shutil.copyfile(os.path.join(self.model_path, 'VGG_Deeplab.py'), os.path.join(self.model_dir, 'VGG_Deeplab.py'))
shutil.copyfile(os.path.join(self.model_path, 'model_utils.py'), os.path.join(self.model_dir, 'model_utils.py'))
shutil.copyfile(os.path.join(self.data_path, dataset.datafile), os.path.join(self.model_dir, dataset.datafile))
shutil.copyfile(os.path.join(self.data_path, 'base_dataset.py'), os.path.join(self.model_dir, 'base_dataset.py'))
self.writer = SummaryWriter(self.tensorborad_dir)
self.counter = 0
if not self.isTrain or self.opt.continue_train:
if self.opt.pretrained_model!='':
self.load_pretrained_network(self.model, self.opt.pretrained_model, self.opt.which_epoch, strict=False)
print("Successfully loaded from pretrained model with given path!")
else:
self.load()
print("Successfully loaded model, continue training....!")
self.model.cuda()
self.normweightgrad=0.
ef forward(self, data, isTrain=True):
self.model.zero_grad()
self.image = Variable(data['image'], volatile=not isTrain).cuda()
if 'depth' in data.keys():
self.depth = Variable(data['depth'], volatile=not isTrain).cuda()
else:
self.depth = None
if data['seg'] is not None:
self.seggt = Variable(data['seg'], volatile=not isTrain).cuda()
else:
self.seggt = None
input_size = self.image.size()
self.segpred = self.model(self.image,self.depth)
self.segpred = nn.functional.upsample(self.segpred, size=(input_size[2], input_size[3]), mode='bilinear')
if self.opt.isTrain:
self.loss = self.criterionSeg(self.segpred, torch.squeeze(self.seggt,1).long())
self.averageloss += [self.loss.data[0]]
segpred = self.segpred.max(1, keepdim=True)[1]
return self.seggt, segpred
def backward(self, step, total_step):
self.loss.backward()
self.optimizer.step()
arning_rate(step, total_step)
trainingavgloss = np.mean(self.averageloss)
if self.opt.verbose:
print (' Iter: %d, Loss: %f' % (step, trainingavgloss) )
def get_visuals(self, step):
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
else:
return OrderedDict([('image', tensor2im(self.image.data[0], inputmode=self.opt.inputmode)),
('segpred', tensor2label(self.segpred.data[0], self.opt.label_nc)),
('seggt', tensor2label(self.seggt.data[0], self.opt.label_nc))])
def update_tensorboard(self, data, step):
if self.opt.isTrain:
self.writer.add_scalar(self.opt.name+'/Accuracy/', data[0], step)
self.writer.add_scalar(self.opt.name+'/Accuracy_Class/', data[1], step)
self.writer.add_scalar(self.opt.name+'/Mean_IoU/', data[2], step)
self.writer.add_scalar(self.opt.name+'/FWAV_Accuracy/', data[3], step)
self.trainingavgloss = np.mean(self.averageloss)
self.writer.add_scalars(self.opt.name+'/loss', {"train": self.trainingavgloss,
"val": np.mean(self.averageloss)}, step)
self.writer.add_scalars('trainingavgloss/', {self.opt.name: self.trainingavgloss}, step)
self.writer.add_scalars('valloss/', {self.opt.name: np.mean(self.averageloss)}, step)
self.writer.add_scalars('val_MeanIoU/', {self.opt.name: data[2]}, step)
file_name = os.path.join(self.save_dir, 'MIoU.txt')
with open(file_name, 'wt') as opt_file:
opt_file.write('%f\n' % (data[2]))
self.averageloss = []
def save(self, which_epoch):
self.save_network(self.model, 'net', which_epoch, self.gpu_ids)
def load(self):
self.load_network(self.model, 'net',self.opt.which_epoch)
def update_learning_rate(self, step, total_step):
lr = max(self.opt.lr * ((1 - float(step) / total_step) ** (self.opt.lr_power)), 1e-6)
self.writer.add_scalar(self.opt.name+'/Learning_Rate/', lr, step)
self.optimizer.param_groups[0]['lr'] = lr
self.optimizer.param_groups[1]['lr'] = lr
self.optimizer.param_groups[2]['lr'] = lr
self.optimizer.param_groups[3]['lr'] = lr
if self.opt.verbose:
print(' update learning rate: %f -> %f' % (self.old_lr, lr))
self.old_lr = lr
| true | true |
f729b2a189248b2a268f31e57ac04212b4b32678 | 2,051 | py | Python | aydin/it/demo/n2s/cb/3D_royer_hcr_transform.py | AhmetCanSolak/aydin | e8bc81ee88c96e0f34986df30a63c96468a45f70 | [
"BSD-3-Clause"
] | 78 | 2021-11-08T16:11:23.000Z | 2022-03-27T17:51:04.000Z | aydin/it/demo/n2s/cb/3D_royer_hcr_transform.py | AhmetCanSolak/aydin | e8bc81ee88c96e0f34986df30a63c96468a45f70 | [
"BSD-3-Clause"
] | 19 | 2021-11-08T17:15:40.000Z | 2022-03-30T17:46:55.000Z | aydin/it/demo/n2s/cb/3D_royer_hcr_transform.py | AhmetCanSolak/aydin | e8bc81ee88c96e0f34986df30a63c96468a45f70 | [
"BSD-3-Clause"
] | 7 | 2021-11-09T17:42:32.000Z | 2022-03-09T00:37:57.000Z | # flake8: noqa
from aydin.features.standard_features import StandardFeatureGenerator
from aydin.io.datasets import examples_single
from aydin.it.fgr import ImageTranslatorFGR
from aydin.it.transforms.attenuation import AttenuationTransform
from aydin.regression.cb import CBRegressor
from aydin.util.log.log import Log
def demo(image):
"""
In some cases it might be usefull to append a compression transform (sqrt) after normalisation,
something akin to a VST transform but without the exact variance stabilisation, and more as a way
to deskew the histogram. There are only a few situations where this truly helps, and there are not many.
So by default this is off.
"""
Log.enable_output = True
# Log.set_log_max_depth(5)
generator = StandardFeatureGenerator(
# include_scale_one=True,
# include_fine_features=True,
# include_corner_features=True,
# include_line_features=True,
# decimate_large_scale_features=False,
# extend_large_scale_features=True,
include_corner_features=True,
include_scale_one=True,
include_fine_features=True,
# include_spatial_features=True,
)
regressor = CBRegressor(patience=20, gpu=True)
it = ImageTranslatorFGR(
feature_generator=generator, regressor=regressor, normaliser_transform='sqrt'
)
it.train(image, image)
denoised = it.translate(image)
ac = AttenuationTransform(axes=0)
corrected = ac.preprocess(image)
it.train(corrected, corrected)
denoised_corrected = it.translate(corrected)
import napari
with napari.gui_qt():
viewer = napari.Viewer()
viewer.add_image(image, name='image')
viewer.add_image(corrected, name='noisy')
viewer.add_image(denoised, name='denoised')
viewer.add_image(denoised_corrected, name='denoised_corrected')
if __name__ == "__main__":
hcr = examples_single.royerlab_hcr.get_array().squeeze()
hcr = hcr[2, :20, 400 : 400 + 256, 700 : 700 + 256]
demo(hcr)
| 32.555556 | 108 | 0.714286 |
from aydin.features.standard_features import StandardFeatureGenerator
from aydin.io.datasets import examples_single
from aydin.it.fgr import ImageTranslatorFGR
from aydin.it.transforms.attenuation import AttenuationTransform
from aydin.regression.cb import CBRegressor
from aydin.util.log.log import Log
def demo(image):
Log.enable_output = True
generator = StandardFeatureGenerator(
include_corner_features=True,
include_scale_one=True,
include_fine_features=True,
)
regressor = CBRegressor(patience=20, gpu=True)
it = ImageTranslatorFGR(
feature_generator=generator, regressor=regressor, normaliser_transform='sqrt'
)
it.train(image, image)
denoised = it.translate(image)
ac = AttenuationTransform(axes=0)
corrected = ac.preprocess(image)
it.train(corrected, corrected)
denoised_corrected = it.translate(corrected)
import napari
with napari.gui_qt():
viewer = napari.Viewer()
viewer.add_image(image, name='image')
viewer.add_image(corrected, name='noisy')
viewer.add_image(denoised, name='denoised')
viewer.add_image(denoised_corrected, name='denoised_corrected')
if __name__ == "__main__":
hcr = examples_single.royerlab_hcr.get_array().squeeze()
hcr = hcr[2, :20, 400 : 400 + 256, 700 : 700 + 256]
demo(hcr)
| true | true |
f729b38b81f333c6d871fc2e21c1cea988d78437 | 3,426 | py | Python | python/paddle/incubate/hapi/tests/test_loss.py | laipaang/Paddle | d7f35434b761707a8479b75636546a624399369a | [
"Apache-2.0"
] | 1 | 2020-06-24T14:53:24.000Z | 2020-06-24T14:53:24.000Z | python/paddle/incubate/hapi/tests/test_loss.py | MaJun-cn/Paddle | 0ec3a42e9740a5f5066053bb49a923d538eba24a | [
"Apache-2.0"
] | null | null | null | python/paddle/incubate/hapi/tests/test_loss.py | MaJun-cn/Paddle | 0ec3a42e9740a5f5066053bb49a923d538eba24a | [
"Apache-2.0"
] | 4 | 2020-07-27T13:24:03.000Z | 2020-08-06T08:20:32.000Z | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable 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 __future__ import division
from __future__ import print_function
import unittest
import os
import six
import numpy as np
import shutil
import copy
import paddle
from paddle import fluid
from paddle.incubate.hapi.model import Model, Input
from paddle.incubate.hapi.loss import CrossEntropy, SoftmaxWithCrossEntropy
def stable_softmax(x):
"""Compute the softmax of vector x in a numerically stable way."""
# clip to shiftx, otherwise, when calc loss with
# log(exp(shiftx)), may get log(0)=INF
shiftx = (x - np.max(x)).clip(-64.)
exps = np.exp(shiftx)
return exps / np.sum(exps)
def randomize_probability(batch_size, class_num, dtype='float32'):
prob = np.random.uniform(
0.1, 1.0, size=(batch_size, class_num)).astype(dtype)
prob_sum = prob.sum(axis=1)
for i in six.moves.xrange(len(prob)):
prob[i] /= prob_sum[i]
return prob
def numpy_ce(x, label):
return np.asmatrix(
[[-np.log(x[i][label[i][0]])] for i in range(x.shape[0])],
dtype="float32").mean()
class TestLoss(unittest.TestCase):
def test_cross_entropy(self):
class_num = 100
batch_size = 128
inputs = [randomize_probability(128, class_num) for _ in range(2)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64") for _ in range(2)
]
gt_out = [numpy_ce(inputs[i], labels[i]) for i in range(2)]
fluid.enable_dygraph()
cross_entropy = CrossEntropy()
out = cross_entropy(
[fluid.dygraph.to_variable(x) for x in inputs],
[fluid.dygraph.to_variable(label) for label in labels])
out = [o.numpy() for o in out]
for o, g in zip(out, gt_out):
np.testing.assert_allclose(o, g, atol=1e-5)
def test_soft_cross_entronpy(self):
class_num = 100
batch_size = 128
inputs = [randomize_probability(128, class_num) for _ in range(2)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64") for _ in range(2)
]
fluid.enable_dygraph()
softmax_cross_entropy = SoftmaxWithCrossEntropy()
softmax_cross_entropy(
[fluid.dygraph.to_variable(x) for x in inputs],
[fluid.dygraph.to_variable(label) for label in labels])
softmax_cross_entropy = SoftmaxWithCrossEntropy(average=False)
inputs = [randomize_probability(128, class_num)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64")
]
softmax_cross_entropy([fluid.dygraph.to_variable(x) for x in inputs],
fluid.dygraph.to_variable(labels[0]))
if __name__ == '__main__':
unittest.main()
| 30.589286 | 79 | 0.650321 |
from __future__ import division
from __future__ import print_function
import unittest
import os
import six
import numpy as np
import shutil
import copy
import paddle
from paddle import fluid
from paddle.incubate.hapi.model import Model, Input
from paddle.incubate.hapi.loss import CrossEntropy, SoftmaxWithCrossEntropy
def stable_softmax(x):
shiftx = (x - np.max(x)).clip(-64.)
exps = np.exp(shiftx)
return exps / np.sum(exps)
def randomize_probability(batch_size, class_num, dtype='float32'):
prob = np.random.uniform(
0.1, 1.0, size=(batch_size, class_num)).astype(dtype)
prob_sum = prob.sum(axis=1)
for i in six.moves.xrange(len(prob)):
prob[i] /= prob_sum[i]
return prob
def numpy_ce(x, label):
return np.asmatrix(
[[-np.log(x[i][label[i][0]])] for i in range(x.shape[0])],
dtype="float32").mean()
class TestLoss(unittest.TestCase):
def test_cross_entropy(self):
class_num = 100
batch_size = 128
inputs = [randomize_probability(128, class_num) for _ in range(2)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64") for _ in range(2)
]
gt_out = [numpy_ce(inputs[i], labels[i]) for i in range(2)]
fluid.enable_dygraph()
cross_entropy = CrossEntropy()
out = cross_entropy(
[fluid.dygraph.to_variable(x) for x in inputs],
[fluid.dygraph.to_variable(label) for label in labels])
out = [o.numpy() for o in out]
for o, g in zip(out, gt_out):
np.testing.assert_allclose(o, g, atol=1e-5)
def test_soft_cross_entronpy(self):
class_num = 100
batch_size = 128
inputs = [randomize_probability(128, class_num) for _ in range(2)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64") for _ in range(2)
]
fluid.enable_dygraph()
softmax_cross_entropy = SoftmaxWithCrossEntropy()
softmax_cross_entropy(
[fluid.dygraph.to_variable(x) for x in inputs],
[fluid.dygraph.to_variable(label) for label in labels])
softmax_cross_entropy = SoftmaxWithCrossEntropy(average=False)
inputs = [randomize_probability(128, class_num)]
labels = [
np.random.randint(
0, class_num, (batch_size, 1), dtype="int64")
]
softmax_cross_entropy([fluid.dygraph.to_variable(x) for x in inputs],
fluid.dygraph.to_variable(labels[0]))
if __name__ == '__main__':
unittest.main()
| true | true |
f729b3ca19cae7056f3d95bc664a6a3571f625ef | 219 | py | Python | caesar_code/rot13.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 117 | 2015-12-18T07:18:27.000Z | 2022-03-28T00:25:54.000Z | caesar_code/rot13.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 8 | 2018-10-03T09:38:46.000Z | 2021-12-13T19:51:09.000Z | caesar_code/rot13.py | DazEB2/SimplePyScripts | 1dde0a42ba93fe89609855d6db8af1c63b1ab7cc | [
"CC-BY-4.0"
] | 28 | 2016-08-02T17:43:47.000Z | 2022-03-21T08:31:12.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def rot13(message):
import codecs
return codecs.encode(message, 'rot13')
assert rot13("test") == "grfg"
assert rot13("Test") == "Grfg"
| 15.642857 | 42 | 0.634703 |
__author__ = 'ipetrash'
def rot13(message):
import codecs
return codecs.encode(message, 'rot13')
assert rot13("test") == "grfg"
assert rot13("Test") == "Grfg"
| true | true |
f729b49bfd8cbe1cbbefb9437d4d85fd35f3612f | 12,491 | py | Python | models/embedding.py | YexuZhou/TimeSeriesClassification_Transformer | c20e00cfac4cfdb849e57e14c184f7d424257409 | [
"MIT"
] | 1 | 2022-02-26T02:45:45.000Z | 2022-02-26T02:45:45.000Z | models/embedding.py | YexuZhou/TimeSeriesClassification_Transformer | c20e00cfac4cfdb849e57e14c184f7d424257409 | [
"MIT"
] | 1 | 2021-09-04T06:41:51.000Z | 2021-09-04T06:41:51.000Z | models/embedding.py | YexuZhou/TimeSeriesClassification_Transformer | c20e00cfac4cfdb849e57e14c184f7d424257409 | [
"MIT"
] | 1 | 2022-03-18T16:57:43.000Z | 2022-03-18T16:57:43.000Z | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
# TODO 所有循环结构应该呈现灵活性,每一层都不能一样!
activation_dict = {"relu" : nn.ReLU,
"leakyrelu" : nn.LeakyReLU,
"prelu" : nn.PReLU,
"rrelu" : nn.RReLU,
"elu" : nn.ELU,
"gelu" : nn.GELU,
"hardswish" : nn.Hardswish,
"mish" : nn.Mish}
Norm_dict = {"layer" : nn.LayerNorm,
"batch" : nn.BatchNorm1d}
class DW_PW_projection(nn.Module):
def __init__(self, c_in, c_out, kernel_size, stride=1, bias = False, padding_mode = "replicate"):
super(DW_PW_projection, self).__init__()
self.dw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_in,
kernel_size = kernel_size,
padding = int(kernel_size/2),
groups = c_in,
stride = stride,
bias = bias,
padding_mode = padding_mode)
self.pw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = 1,
padding = 0,
groups = 1,
bias = bias,
padding_mode = padding_mode)
def forward(self, x):
x = self.dw_conv1d(x)
x = self.pw_conv1d(x)
return x
class Forward_block(nn.Module):
def __init__(self,
c_in,
c_out,
kernel_size,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
"""
embedding的block 由 conv --> norm --> activation --> maxpooling组成
"""
super(Forward_block, self).__init__()
if light_weight:
self.conv = DW_PW_projection(c_in = c_in,
c_out = c_out,
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
else:
self.conv = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
self.norm_type = norm_type
self.norm = Norm_dict[norm_type](c_out)
self.activation = activation_dict[activation]()
self.max_pool = max_pool
if max_pool:
self.maxpooling = nn.MaxPool1d(kernel_size = pooling_kernel_size,
stride = pooling_stride,
padding = pooling_padding)
def forward(self, x):
x = self.conv(x.permute(0, 2, 1)).permute(0, 2, 1)
if self.norm_type == "layer":
x = self.activation(self.norm(x))
else :
x = self.activation(self.norm(x.permute(0, 2, 1)).permute(0, 2, 1))
if self.max_pool:
x = self.maxpooling(x.permute(0, 2, 1)).permute(0, 2, 1)
return x
class Freq_Forward_block(nn.Module):
def __init__(self,
c_in,
c_out, # 主要是把channel的dim压平
kernel_size,
stride=1,
bias = False,
padding_mode = "replicate"):
super(Freq_Forward_block, self).__init__()
# depthwise
self.dw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_in,
kernel_size = [kernel_size,kernel_size],
padding = [int(kernel_size/2),int(kernel_size/2)],
groups = c_in,
stride = [1,stride], #缩短长度
bias = bias,
padding_mode = padding_mode)
self.batch_norm_1 = nn.BatchNorm2d(c_in)
self.act_1 = nn.ReLU()
# pointwise
self.pw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_out, # 压平
kernel_size = 1,
padding = 0,
stride = 1,
bias = bias,
padding_mode = padding_mode)
self.batch_norm_2 = nn.BatchNorm2d(c_out)
self.act_2 = nn.ReLU()
def forward(self, x):
x = self.dw_conv(x)
x = self.batch_norm_1(x)
x = self.act_1(x)
x = self.pw_conv(x)
x = self.batch_norm_2(x)
x = self.act_2(x)
return x
class TokenEmbedding(nn.Module):
def __init__(self,
c_in,
token_d_model,
kernel_size = 3,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
n_conv_layers = 1,
in_planes = None,
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
"""
c_in : 模型输入的维度
token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat
kernel_size : 每一层conv的kernel大小
"""
super(TokenEmbedding, self).__init__()
in_planes = in_planes or int(token_d_model/2)
n_filter_list = [c_in] + [in_planes for _ in range(n_conv_layers - 1)] + [token_d_model]
padding = int(kernel_size/2)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1],
kernel_size = kernel_size,
stride = stride,
conv_bias = conv_bias,
activation = activation,
norm_type = norm_type,
max_pool = max_pool,
pooling_kernel_size = pooling_kernel_size,
pooling_stride = pooling_stride,
pooling_padding = pooling_padding,
padding_mode = padding_mode,
light_weight = light_weight))
self.conv_layers = nn.ModuleList(self.conv_layers)
#for m in self.modules():
# if isinstance(m, nn.Conv1d):
# nn.init.kaiming_normal_(m.weight)
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
return x
def sequence_length(self, length=100, n_channels=3):
return self.forward(torch.zeros((1, length,n_channels))).shape[1]
class Freq_TokenEmbedding(nn.Module):
def __init__(self,
c_in,
token_d_model,
kernel_size = 3,
stride = 1, #横向方向缩短距离
conv_bias = False,
n_conv_layers = 1,
f_max = 100,
padding_mode = 'replicate',
light_weight = False):
"""
c_in : 模型输入的维度
token_d_model : embedding的维度 TODO看看后面是需要被相加还是被cat
kernel_size : 每一层conv的kernel大小
"""
super(Freq_TokenEmbedding, self).__init__()
n_filter_list = [c_in] + [max(1,int(c_in/2**(i+1))) for i in range(n_conv_layers - 1)] + [1]
print(n_filter_list)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Freq_Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1], # 主要是把channel的dim压平
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode))
self.conv_layers = nn.ModuleList(self.conv_layers)
self.conv = nn.Conv1d(in_channels = self.channel(c_in = c_in, freq = int(f_max/2), length=100),
out_channels = token_d_model,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = 1,
bias = conv_bias,
padding_mode = padding_mode)
self.norm = nn.LayerNorm(token_d_model)
self.activation = nn.ReLU()
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
x = torch.squeeze(x, 1)
x = self.conv(x) # B C L
x = self.activation(self.norm(x.permute(0, 2, 1)))
return x
def sequence_length(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
return x.shape[3]
def channel(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
print("channel ,", x.shape[2])
return x.shape[2]
class PositionalEmbedding(nn.Module):
"""
input shape should be (batch, seq_length, feature_channel)
"""
def __init__(self, pos_d_model, max_len=5000):
super(PositionalEmbedding, self).__init__()
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, pos_d_model).float()
pe.require_grad = False
position = torch.arange(0, max_len).float().unsqueeze(1)
div_term = (torch.arange(0, pos_d_model, 2).float() * -(math.log(10000.0) / pos_d_model)).exp()
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)# [1, max_len, pos_d_model]
self.register_buffer('pe', pe)
def forward(self, x):
return self.pe[:, :x.size(1)] # select the the length same as input
def vis_pos_heat(self, length):
heat = self.pe[:, :length]
plt.figure(figsize=(15,5))
sns.heatmap(heat.detach().numpy()[0], linewidth=0)
plt.ylabel("length")
plt.xlabel("embedding")
| 39.403785 | 114 | 0.429029 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import seaborn as sns
import matplotlib.pylab as plt
import numpy as np
activation_dict = {"relu" : nn.ReLU,
"leakyrelu" : nn.LeakyReLU,
"prelu" : nn.PReLU,
"rrelu" : nn.RReLU,
"elu" : nn.ELU,
"gelu" : nn.GELU,
"hardswish" : nn.Hardswish,
"mish" : nn.Mish}
Norm_dict = {"layer" : nn.LayerNorm,
"batch" : nn.BatchNorm1d}
class DW_PW_projection(nn.Module):
def __init__(self, c_in, c_out, kernel_size, stride=1, bias = False, padding_mode = "replicate"):
super(DW_PW_projection, self).__init__()
self.dw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_in,
kernel_size = kernel_size,
padding = int(kernel_size/2),
groups = c_in,
stride = stride,
bias = bias,
padding_mode = padding_mode)
self.pw_conv1d = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = 1,
padding = 0,
groups = 1,
bias = bias,
padding_mode = padding_mode)
def forward(self, x):
x = self.dw_conv1d(x)
x = self.pw_conv1d(x)
return x
class Forward_block(nn.Module):
def __init__(self,
c_in,
c_out,
kernel_size,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
super(Forward_block, self).__init__()
if light_weight:
self.conv = DW_PW_projection(c_in = c_in,
c_out = c_out,
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
else:
self.conv = nn.Conv1d(in_channels = c_in,
out_channels = c_out,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = stride,
bias = conv_bias,
padding_mode = padding_mode)
self.norm_type = norm_type
self.norm = Norm_dict[norm_type](c_out)
self.activation = activation_dict[activation]()
self.max_pool = max_pool
if max_pool:
self.maxpooling = nn.MaxPool1d(kernel_size = pooling_kernel_size,
stride = pooling_stride,
padding = pooling_padding)
def forward(self, x):
x = self.conv(x.permute(0, 2, 1)).permute(0, 2, 1)
if self.norm_type == "layer":
x = self.activation(self.norm(x))
else :
x = self.activation(self.norm(x.permute(0, 2, 1)).permute(0, 2, 1))
if self.max_pool:
x = self.maxpooling(x.permute(0, 2, 1)).permute(0, 2, 1)
return x
class Freq_Forward_block(nn.Module):
def __init__(self,
c_in,
c_out,
kernel_size,
stride=1,
bias = False,
padding_mode = "replicate"):
super(Freq_Forward_block, self).__init__()
self.dw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_in,
kernel_size = [kernel_size,kernel_size],
padding = [int(kernel_size/2),int(kernel_size/2)],
groups = c_in,
stride = [1,stride],
bias = bias,
padding_mode = padding_mode)
self.batch_norm_1 = nn.BatchNorm2d(c_in)
self.act_1 = nn.ReLU()
self.pw_conv = nn.Conv2d(in_channels = c_in,
out_channels = c_out,
kernel_size = 1,
padding = 0,
stride = 1,
bias = bias,
padding_mode = padding_mode)
self.batch_norm_2 = nn.BatchNorm2d(c_out)
self.act_2 = nn.ReLU()
def forward(self, x):
x = self.dw_conv(x)
x = self.batch_norm_1(x)
x = self.act_1(x)
x = self.pw_conv(x)
x = self.batch_norm_2(x)
x = self.act_2(x)
return x
class TokenEmbedding(nn.Module):
def __init__(self,
c_in,
token_d_model,
kernel_size = 3,
stride = 1,
conv_bias = False,
activation = "relu",
norm_type = "batch",
n_conv_layers = 1,
in_planes = None,
max_pool = False,
pooling_kernel_size = 3,
pooling_stride = 2,
pooling_padding = 1,
padding_mode = 'replicate',
light_weight = False):
super(TokenEmbedding, self).__init__()
in_planes = in_planes or int(token_d_model/2)
n_filter_list = [c_in] + [in_planes for _ in range(n_conv_layers - 1)] + [token_d_model]
padding = int(kernel_size/2)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1],
kernel_size = kernel_size,
stride = stride,
conv_bias = conv_bias,
activation = activation,
norm_type = norm_type,
max_pool = max_pool,
pooling_kernel_size = pooling_kernel_size,
pooling_stride = pooling_stride,
pooling_padding = pooling_padding,
padding_mode = padding_mode,
light_weight = light_weight))
self.conv_layers = nn.ModuleList(self.conv_layers)
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
return x
def sequence_length(self, length=100, n_channels=3):
return self.forward(torch.zeros((1, length,n_channels))).shape[1]
class Freq_TokenEmbedding(nn.Module):
def __init__(self,
c_in,
token_d_model,
kernel_size = 3,
stride = 1,
conv_bias = False,
n_conv_layers = 1,
f_max = 100,
padding_mode = 'replicate',
light_weight = False):
super(Freq_TokenEmbedding, self).__init__()
n_filter_list = [c_in] + [max(1,int(c_in/2**(i+1))) for i in range(n_conv_layers - 1)] + [1]
print(n_filter_list)
self.conv_layers = []
for i in range(n_conv_layers):
self.conv_layers.append(Freq_Forward_block(c_in = n_filter_list[i],
c_out = n_filter_list[i + 1],
kernel_size = kernel_size,
stride = stride,
bias = conv_bias,
padding_mode = padding_mode))
self.conv_layers = nn.ModuleList(self.conv_layers)
self.conv = nn.Conv1d(in_channels = self.channel(c_in = c_in, freq = int(f_max/2), length=100),
out_channels = token_d_model,
kernel_size = kernel_size,
padding = int(kernel_size/2),
stride = 1,
bias = conv_bias,
padding_mode = padding_mode)
self.norm = nn.LayerNorm(token_d_model)
self.activation = nn.ReLU()
def forward(self, x):
for layer in self.conv_layers:
x = layer(x)
x = torch.squeeze(x, 1)
x = self.conv(x)
x = self.activation(self.norm(x.permute(0, 2, 1)))
return x
def sequence_length(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
return x.shape[3]
def channel(self, c_in = 100, freq = 50, length=100):
x = torch.rand(1,c_in,freq,length).float()
for layer in self.conv_layers:
x = layer(x)
print("channel ,", x.shape[2])
return x.shape[2]
class PositionalEmbedding(nn.Module):
def __init__(self, pos_d_model, max_len=5000):
super(PositionalEmbedding, self).__init__()
pe = torch.zeros(max_len, pos_d_model).float()
pe.require_grad = False
position = torch.arange(0, max_len).float().unsqueeze(1)
div_term = (torch.arange(0, pos_d_model, 2).float() * -(math.log(10000.0) / pos_d_model)).exp()
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x):
return self.pe[:, :x.size(1)]
def vis_pos_heat(self, length):
heat = self.pe[:, :length]
plt.figure(figsize=(15,5))
sns.heatmap(heat.detach().numpy()[0], linewidth=0)
plt.ylabel("length")
plt.xlabel("embedding")
| true | true |
f729b4c88db7c35c8b6b27dfe5dd6b5a077f57b8 | 10,000 | py | Python | python/ray/workers/setup_runtime_env.py | tmct/ray | 53206dd4401665ec599118241c236ac9e6f4852a | [
"Apache-2.0"
] | 5 | 2019-12-23T07:48:13.000Z | 2020-01-03T12:42:38.000Z | python/ray/workers/setup_runtime_env.py | tmct/ray | 53206dd4401665ec599118241c236ac9e6f4852a | [
"Apache-2.0"
] | 70 | 2019-03-13T05:25:48.000Z | 2022-03-26T07:05:19.000Z | python/ray/workers/setup_runtime_env.py | tmct/ray | 53206dd4401665ec599118241c236ac9e6f4852a | [
"Apache-2.0"
] | null | null | null | import os
import sys
import argparse
import json
import logging
import yaml
import hashlib
from filelock import FileLock
from typing import Optional, List, Dict, Any
from pathlib import Path
import ray
from ray._private.conda import (get_conda_activate_commands,
get_or_create_conda_env)
from ray._private.utils import try_to_create_directory
from ray._private.utils import (get_wheel_filename, get_master_wheel_url,
get_release_wheel_url)
from ray.workers.pluggable_runtime_env import RuntimeEnvContext
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
parser.add_argument(
"--serialized-runtime-env",
type=str,
help="the serialized parsed runtime env dict")
parser.add_argument(
"--serialized-runtime-env-context",
type=str,
help="the serialized runtime env context")
# The worker is not set up yet, so we can't get session_dir from the worker.
parser.add_argument(
"--session-dir", type=str, help="the directory for the current session")
def setup_runtime_env(runtime_env: dict, session_dir):
if runtime_env.get("conda") or runtime_env.get("pip"):
conda_dict = get_conda_dict(runtime_env, session_dir)
if isinstance(runtime_env.get("conda"), str):
conda_env_name = runtime_env["conda"]
else:
assert conda_dict is not None
py_version = ".".join(map(str,
sys.version_info[:3])) # like 3.6.10
ray_pip = current_ray_pip_specifier()
if ray_pip and not runtime_env.get("_skip_inject_ray"):
extra_pip_dependencies = [ray_pip, "ray[default]"]
else:
extra_pip_dependencies = []
conda_dict = inject_dependencies(conda_dict, py_version,
extra_pip_dependencies)
# Locking to avoid multiple processes installing concurrently
conda_hash = hashlib.sha1(
json.dumps(conda_dict,
sort_keys=True).encode("utf-8")).hexdigest()
conda_hash_str = f"conda-generated-{conda_hash}"
file_lock_name = f"ray-{conda_hash_str}.lock"
with FileLock(os.path.join(session_dir, file_lock_name)):
conda_dir = os.path.join(session_dir, "runtime_resources",
"conda")
try_to_create_directory(conda_dir)
conda_yaml_path = os.path.join(conda_dir, "environment.yml")
with open(conda_yaml_path, "w") as file:
# Sort keys because we hash based on the file contents,
# and we don't want the hash to depend on the order
# of the dependencies.
yaml.dump(conda_dict, file, sort_keys=True)
conda_env_name = get_or_create_conda_env(
conda_yaml_path, conda_dir)
return RuntimeEnvContext(conda_env_name)
return RuntimeEnvContext()
def setup_worker(input_args):
# remaining_args contains the arguments to the original worker command,
# minus the python executable, e.g. default_worker.py --node-ip-address=...
args, remaining_args = parser.parse_known_args(args=input_args)
commands = []
py_executable: str = sys.executable
runtime_env: dict = json.loads(args.serialized_runtime_env or "{}")
runtime_env_context: RuntimeEnvContext = None
# Ray client server setups runtime env by itself instead of agent.
if runtime_env.get("conda") or runtime_env.get("pip"):
if not args.serialized_runtime_env_context:
runtime_env_context = setup_runtime_env(runtime_env,
args.session_dir)
else:
runtime_env_context = RuntimeEnvContext.deserialize(
args.serialized_runtime_env_context)
# activate conda
if runtime_env_context and runtime_env_context.conda_env_name:
py_executable = "python"
conda_activate_commands = get_conda_activate_commands(
runtime_env_context.conda_env_name)
if (conda_activate_commands):
commands += conda_activate_commands
elif runtime_env.get("conda"):
logger.warning(
"Conda env name is not found in context, "
"but conda exists in runtime env. The runtime env %s, "
"the context %s.", args.serialized_runtime_env,
args.serialized_runtime_env_context)
commands += [" ".join([f"exec {py_executable}"] + remaining_args)]
command_separator = " && "
command_str = command_separator.join(commands)
# update env vars
if runtime_env.get("env_vars"):
env_vars = runtime_env["env_vars"]
os.environ.update(env_vars)
os.execvp("bash", ["bash", "-c", command_str])
def get_conda_dict(runtime_env, runtime_env_dir) -> Optional[Dict[Any, Any]]:
""" Construct a conda dependencies dict from a runtime env.
This function does not inject Ray or Python into the conda dict.
If the runtime env does not specify pip or conda, or if it specifies
the name of a preinstalled conda environment, this function returns
None. If pip is specified, a conda dict is created containing the
pip dependencies. If conda is already given as a dict, this function
is the identity function.
"""
if runtime_env.get("conda"):
if isinstance(runtime_env["conda"], dict):
return runtime_env["conda"]
else:
return None
if runtime_env.get("pip"):
requirements_txt = runtime_env["pip"]
pip_hash = hashlib.sha1(requirements_txt.encode("utf-8")).hexdigest()
pip_hash_str = f"pip-generated-{pip_hash}"
conda_dir = os.path.join(runtime_env_dir, "conda")
requirements_txt_path = os.path.join(
conda_dir, f"requirements-{pip_hash_str}.txt")
conda_dict = {
"name": pip_hash_str,
"dependencies": ["pip", {
"pip": [f"-r {requirements_txt_path}"]
}]
}
file_lock_name = f"ray-{pip_hash_str}.lock"
with FileLock(os.path.join(runtime_env_dir, file_lock_name)):
try_to_create_directory(conda_dir)
with open(requirements_txt_path, "w") as file:
file.write(requirements_txt)
return conda_dict
return None
def current_ray_pip_specifier() -> Optional[str]:
"""The pip requirement specifier for the running version of Ray.
Returns:
A string which can be passed to `pip install` to install the
currently running Ray version, or None if running on a version
built from source locally (likely if you are developing Ray).
Examples:
Returns "ray[all]==1.4.0" if running the stable release
Returns "https://s3-us-west-2.amazonaws.com/ray-wheels/master/[..].whl"
if running the nightly or a specific commit
"""
if os.environ.get("RAY_CI_POST_WHEEL_TESTS"):
# Running in Buildkite CI after the wheel has been built.
# Wheels are at in the ray/.whl directory, and the present file is
# at ray/python/ray/workers. Use relative paths to allow for
# testing locally if needed.
return os.path.join(
Path(__file__).resolve().parents[3], ".whl", get_wheel_filename())
elif ray.__commit__ == "{{RAY_COMMIT_SHA}}":
# Running on a version built from source locally.
logger.warning(
"Current Ray version could not be detected, most likely "
"because you are using a version of Ray "
"built from source. If you wish to use runtime_env, "
"you can try building a wheel and including the wheel "
"explicitly as a pip dependency.")
return None
elif "dev" in ray.__version__:
# Running on a nightly wheel.
return get_master_wheel_url()
else:
return get_release_wheel_url()
def inject_dependencies(
conda_dict: Dict[Any, Any],
py_version: str,
pip_dependencies: Optional[List[str]] = None) -> Dict[Any, Any]:
"""Add Ray, Python and (optionally) extra pip dependencies to a conda dict.
Args:
conda_dict (dict): A dict representing the JSON-serialized conda
environment YAML file. This dict will be modified and returned.
py_version (str): A string representing a Python version to inject
into the conda dependencies, e.g. "3.7.7"
pip_dependencies (List[str]): A list of pip dependencies that
will be prepended to the list of pip dependencies in
the conda dict. If the conda dict does not already have a "pip"
field, one will be created.
Returns:
The modified dict. (Note: the input argument conda_dict is modified
and returned.)
"""
if pip_dependencies is None:
pip_dependencies = []
if conda_dict.get("dependencies") is None:
conda_dict["dependencies"] = []
# Inject Python dependency.
deps = conda_dict["dependencies"]
# Add current python dependency. If the user has already included a
# python version dependency, conda will raise a readable error if the two
# are incompatible, e.g:
# ResolvePackageNotFound: - python[version='3.5.*,>=3.6']
deps.append(f"python={py_version}")
if "pip" not in deps:
deps.append("pip")
# Insert pip dependencies.
found_pip_dict = False
for dep in deps:
if isinstance(dep, dict) and dep.get("pip") and isinstance(
dep["pip"], list):
dep["pip"] = pip_dependencies + dep["pip"]
found_pip_dict = True
break
if not found_pip_dict:
deps.append({"pip": pip_dependencies})
return conda_dict
if __name__ == "__main__":
setup_worker(sys.argv[1:])
| 40.160643 | 79 | 0.6393 | import os
import sys
import argparse
import json
import logging
import yaml
import hashlib
from filelock import FileLock
from typing import Optional, List, Dict, Any
from pathlib import Path
import ray
from ray._private.conda import (get_conda_activate_commands,
get_or_create_conda_env)
from ray._private.utils import try_to_create_directory
from ray._private.utils import (get_wheel_filename, get_master_wheel_url,
get_release_wheel_url)
from ray.workers.pluggable_runtime_env import RuntimeEnvContext
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser()
parser.add_argument(
"--serialized-runtime-env",
type=str,
help="the serialized parsed runtime env dict")
parser.add_argument(
"--serialized-runtime-env-context",
type=str,
help="the serialized runtime env context")
parser.add_argument(
"--session-dir", type=str, help="the directory for the current session")
def setup_runtime_env(runtime_env: dict, session_dir):
if runtime_env.get("conda") or runtime_env.get("pip"):
conda_dict = get_conda_dict(runtime_env, session_dir)
if isinstance(runtime_env.get("conda"), str):
conda_env_name = runtime_env["conda"]
else:
assert conda_dict is not None
py_version = ".".join(map(str,
sys.version_info[:3])) # like 3.6.10
ray_pip = current_ray_pip_specifier()
if ray_pip and not runtime_env.get("_skip_inject_ray"):
extra_pip_dependencies = [ray_pip, "ray[default]"]
else:
extra_pip_dependencies = []
conda_dict = inject_dependencies(conda_dict, py_version,
extra_pip_dependencies)
# Locking to avoid multiple processes installing concurrently
conda_hash = hashlib.sha1(
json.dumps(conda_dict,
sort_keys=True).encode("utf-8")).hexdigest()
conda_hash_str = f"conda-generated-{conda_hash}"
file_lock_name = f"ray-{conda_hash_str}.lock"
with FileLock(os.path.join(session_dir, file_lock_name)):
conda_dir = os.path.join(session_dir, "runtime_resources",
"conda")
try_to_create_directory(conda_dir)
conda_yaml_path = os.path.join(conda_dir, "environment.yml")
with open(conda_yaml_path, "w") as file:
# Sort keys because we hash based on the file contents,
# and we don't want the hash to depend on the order
yaml.dump(conda_dict, file, sort_keys=True)
conda_env_name = get_or_create_conda_env(
conda_yaml_path, conda_dir)
return RuntimeEnvContext(conda_env_name)
return RuntimeEnvContext()
def setup_worker(input_args):
args, remaining_args = parser.parse_known_args(args=input_args)
commands = []
py_executable: str = sys.executable
runtime_env: dict = json.loads(args.serialized_runtime_env or "{}")
runtime_env_context: RuntimeEnvContext = None
if runtime_env.get("conda") or runtime_env.get("pip"):
if not args.serialized_runtime_env_context:
runtime_env_context = setup_runtime_env(runtime_env,
args.session_dir)
else:
runtime_env_context = RuntimeEnvContext.deserialize(
args.serialized_runtime_env_context)
if runtime_env_context and runtime_env_context.conda_env_name:
py_executable = "python"
conda_activate_commands = get_conda_activate_commands(
runtime_env_context.conda_env_name)
if (conda_activate_commands):
commands += conda_activate_commands
elif runtime_env.get("conda"):
logger.warning(
"Conda env name is not found in context, "
"but conda exists in runtime env. The runtime env %s, "
"the context %s.", args.serialized_runtime_env,
args.serialized_runtime_env_context)
commands += [" ".join([f"exec {py_executable}"] + remaining_args)]
command_separator = " && "
command_str = command_separator.join(commands)
if runtime_env.get("env_vars"):
env_vars = runtime_env["env_vars"]
os.environ.update(env_vars)
os.execvp("bash", ["bash", "-c", command_str])
def get_conda_dict(runtime_env, runtime_env_dir) -> Optional[Dict[Any, Any]]:
if runtime_env.get("conda"):
if isinstance(runtime_env["conda"], dict):
return runtime_env["conda"]
else:
return None
if runtime_env.get("pip"):
requirements_txt = runtime_env["pip"]
pip_hash = hashlib.sha1(requirements_txt.encode("utf-8")).hexdigest()
pip_hash_str = f"pip-generated-{pip_hash}"
conda_dir = os.path.join(runtime_env_dir, "conda")
requirements_txt_path = os.path.join(
conda_dir, f"requirements-{pip_hash_str}.txt")
conda_dict = {
"name": pip_hash_str,
"dependencies": ["pip", {
"pip": [f"-r {requirements_txt_path}"]
}]
}
file_lock_name = f"ray-{pip_hash_str}.lock"
with FileLock(os.path.join(runtime_env_dir, file_lock_name)):
try_to_create_directory(conda_dir)
with open(requirements_txt_path, "w") as file:
file.write(requirements_txt)
return conda_dict
return None
def current_ray_pip_specifier() -> Optional[str]:
if os.environ.get("RAY_CI_POST_WHEEL_TESTS"):
return os.path.join(
Path(__file__).resolve().parents[3], ".whl", get_wheel_filename())
elif ray.__commit__ == "{{RAY_COMMIT_SHA}}":
logger.warning(
"Current Ray version could not be detected, most likely "
"because you are using a version of Ray "
"built from source. If you wish to use runtime_env, "
"you can try building a wheel and including the wheel "
"explicitly as a pip dependency.")
return None
elif "dev" in ray.__version__:
return get_master_wheel_url()
else:
return get_release_wheel_url()
def inject_dependencies(
conda_dict: Dict[Any, Any],
py_version: str,
pip_dependencies: Optional[List[str]] = None) -> Dict[Any, Any]:
if pip_dependencies is None:
pip_dependencies = []
if conda_dict.get("dependencies") is None:
conda_dict["dependencies"] = []
deps = conda_dict["dependencies"]
deps.append(f"python={py_version}")
if "pip" not in deps:
deps.append("pip")
found_pip_dict = False
for dep in deps:
if isinstance(dep, dict) and dep.get("pip") and isinstance(
dep["pip"], list):
dep["pip"] = pip_dependencies + dep["pip"]
found_pip_dict = True
break
if not found_pip_dict:
deps.append({"pip": pip_dependencies})
return conda_dict
if __name__ == "__main__":
setup_worker(sys.argv[1:])
| true | true |
f729b552fffba49814a0370ecbde17b2c80a1622 | 72,305 | py | Python | openstackclient/tests/unit/network/v2/test_port.py | tanmayks1999/python-openstackclient | 6a40910c3a4c0e00c3dcd0a9223772b6f03c4002 | [
"Apache-2.0"
] | null | null | null | openstackclient/tests/unit/network/v2/test_port.py | tanmayks1999/python-openstackclient | 6a40910c3a4c0e00c3dcd0a9223772b6f03c4002 | [
"Apache-2.0"
] | null | null | null | openstackclient/tests/unit/network/v2/test_port.py | tanmayks1999/python-openstackclient | 6a40910c3a4c0e00c3dcd0a9223772b6f03c4002 | [
"Apache-2.0"
] | null | null | null | # 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 argparse
from unittest import mock
from unittest.mock import call
from osc_lib.cli import format_columns
from osc_lib import exceptions
from osc_lib import utils
from openstackclient.network.v2 import port
from openstackclient.tests.unit.compute.v2 import fakes as compute_fakes
from openstackclient.tests.unit.identity.v3 import fakes as identity_fakes
from openstackclient.tests.unit.network.v2 import fakes as network_fakes
from openstackclient.tests.unit import utils as tests_utils
class TestPort(network_fakes.TestNetworkV2):
def setUp(self):
super(TestPort, self).setUp()
# Get a shortcut to the network client
self.network = self.app.client_manager.network
# Get a shortcut to the ProjectManager Mock
self.projects_mock = self.app.client_manager.identity.projects
@staticmethod
def _get_common_cols_data(fake_port):
columns = (
'admin_state_up',
'allowed_address_pairs',
'binding_host_id',
'binding_profile',
'binding_vif_details',
'binding_vif_type',
'binding_vnic_type',
'data_plane_status',
'description',
'device_id',
'device_owner',
'dns_assignment',
'dns_domain',
'dns_name',
'extra_dhcp_opts',
'fixed_ips',
'id',
'mac_address',
'name',
'network_id',
'numa_affinity_policy',
'port_security_enabled',
'project_id',
'qos_network_policy_id',
'qos_policy_id',
'security_group_ids',
'status',
'tags',
'uplink_status_propagation',
)
data = (
port.AdminStateColumn(fake_port.admin_state_up),
format_columns.ListDictColumn(fake_port.allowed_address_pairs),
fake_port.binding_host_id,
format_columns.DictColumn(fake_port.binding_profile),
format_columns.DictColumn(fake_port.binding_vif_details),
fake_port.binding_vif_type,
fake_port.binding_vnic_type,
fake_port.data_plane_status,
fake_port.description,
fake_port.device_id,
fake_port.device_owner,
format_columns.ListDictColumn(fake_port.dns_assignment),
fake_port.dns_domain,
fake_port.dns_name,
format_columns.ListDictColumn(fake_port.extra_dhcp_opts),
format_columns.ListDictColumn(fake_port.fixed_ips),
fake_port.id,
fake_port.mac_address,
fake_port.name,
fake_port.network_id,
fake_port.numa_affinity_policy,
fake_port.port_security_enabled,
fake_port.project_id,
fake_port.qos_network_policy_id,
fake_port.qos_policy_id,
format_columns.ListColumn(fake_port.security_group_ids),
fake_port.status,
format_columns.ListColumn(fake_port.tags),
fake_port.uplink_status_propagation,
)
return columns, data
class TestCreatePort(TestPort):
_port = network_fakes.FakePort.create_one_port()
columns, data = TestPort._get_common_cols_data(_port)
def setUp(self):
super(TestCreatePort, self).setUp()
self.network.create_port = mock.Mock(return_value=self._port)
self.network.set_tags = mock.Mock(return_value=None)
fake_net = network_fakes.FakeNetwork.create_one_network({
'id': self._port.network_id,
})
self.network.find_network = mock.Mock(return_value=fake_net)
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet()
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_extension = mock.Mock(return_value=[])
# Get the command object to test
self.cmd = port.CreatePort(self.app, self.namespace)
def test_create_default_options(self):
arglist = [
'--network', self._port.network_id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
})
self.assertFalse(self.network.set_tags.called)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_full_options(self):
arglist = [
'--mac-address', 'aa:aa:aa:aa:aa:aa',
'--fixed-ip', 'subnet=%s,ip-address=10.0.0.2'
% self.fake_subnet.id,
'--description', self._port.description,
'--device', 'deviceid',
'--device-owner', 'fakeowner',
'--disable',
'--vnic-type', 'macvtap',
'--binding-profile', 'foo=bar',
'--binding-profile', 'foo2=bar2',
'--network', self._port.network_id,
'--dns-domain', 'example.org',
'--dns-name', '8.8.8.8',
'test-port',
]
verifylist = [
('mac_address', 'aa:aa:aa:aa:aa:aa'),
(
'fixed_ip',
[{'subnet': self.fake_subnet.id, 'ip-address': '10.0.0.2'}]
),
('description', self._port.description),
('device', 'deviceid'),
('device_owner', 'fakeowner'),
('disable', True),
('vnic_type', 'macvtap'),
('binding_profile', {'foo': 'bar', 'foo2': 'bar2'}),
('network', self._port.network_id),
('dns_domain', 'example.org'),
('dns_name', '8.8.8.8'),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'mac_address': 'aa:aa:aa:aa:aa:aa',
'fixed_ips': [{'subnet_id': self.fake_subnet.id,
'ip_address': '10.0.0.2'}],
'description': self._port.description,
'device_id': 'deviceid',
'device_owner': 'fakeowner',
'admin_state_up': False,
'binding:vnic_type': 'macvtap',
'binding:profile': {'foo': 'bar', 'foo2': 'bar2'},
'network_id': self._port.network_id,
'dns_domain': 'example.org',
'dns_name': '8.8.8.8',
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_invalid_json_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', '{"parent_name":"fake_parent"',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_create_invalid_key_value_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', 'key',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_create_json_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', '{"parent_name":"fake_parent"}',
'--binding-profile', '{"tag":42}',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('binding_profile', {'parent_name': 'fake_parent', 'tag': 42}),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'binding:profile': {'parent_name': 'fake_parent', 'tag': 42},
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_security_group(self):
secgroup = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(return_value=secgroup)
arglist = [
'--network', self._port.network_id,
'--security-group', secgroup.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('security_group', [secgroup.id]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [secgroup.id],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_dns_name(self):
arglist = [
'--network', self._port.network_id,
'--dns-name', '8.8.8.8',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('dns_name', '8.8.8.8'),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'dns_name': '8.8.8.8',
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_security_groups(self):
sg_1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_2 = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(side_effect=[sg_1, sg_2])
arglist = [
'--network', self._port.network_id,
'--security-group', sg_1.id,
'--security-group', sg_2.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('security_group', [sg_1.id, sg_2.id]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [sg_1.id, sg_2.id],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_no_security_groups(self):
arglist = [
'--network', self._port.network_id,
'--no-security-group',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('no_security_group', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_no_fixed_ips(self):
arglist = [
'--network', self._port.network_id,
'--no-fixed-ip',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('no_fixed_ip', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'fixed_ips': [],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_allowed_address_pair_ipaddr(self):
pairs = [{'ip_address': '192.168.1.123'},
{'ip_address': '192.168.1.45'}]
arglist = [
'--network', self._port.network_id,
'--allowed-address', 'ip-address=192.168.1.123',
'--allowed-address', 'ip-address=192.168.1.45',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('allowed_address_pairs', [{'ip-address': '192.168.1.123'},
{'ip-address': '192.168.1.45'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'allowed_address_pairs': pairs,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_allowed_address_pair(self):
pairs = [{'ip_address': '192.168.1.123',
'mac_address': 'aa:aa:aa:aa:aa:aa'},
{'ip_address': '192.168.1.45',
'mac_address': 'aa:aa:aa:aa:aa:b1'}]
arglist = [
'--network', self._port.network_id,
'--allowed-address',
'ip-address=192.168.1.123,mac-address=aa:aa:aa:aa:aa:aa',
'--allowed-address',
'ip-address=192.168.1.45,mac-address=aa:aa:aa:aa:aa:b1',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('allowed_address_pairs', [{'ip-address': '192.168.1.123',
'mac-address': 'aa:aa:aa:aa:aa:aa'},
{'ip-address': '192.168.1.45',
'mac-address': 'aa:aa:aa:aa:aa:b1'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'allowed_address_pairs': pairs,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_qos(self):
qos_policy = network_fakes.FakeNetworkQosPolicy.create_one_qos_policy()
self.network.find_qos_policy = mock.Mock(return_value=qos_policy)
arglist = [
'--network', self._port.network_id,
'--qos-policy', qos_policy.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('qos_policy', qos_policy.id),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'qos_policy_id': qos_policy.id,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_security_enabled(self):
arglist = [
'--network', self._port.network_id,
'--enable-port-security',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('enable_port_security', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'port_security_enabled': True,
'name': 'test-port',
})
def test_create_port_security_disabled(self):
arglist = [
'--network', self._port.network_id,
'--disable-port-security',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('disable_port_security', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'port_security_enabled': False,
'name': 'test-port',
})
def _test_create_with_tag(self, add_tags=True, add_tags_in_post=True):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if add_tags:
arglist += ['--tag', 'red', '--tag', 'blue']
else:
arglist += ['--no-tag']
verifylist = [
('network', self._port.network_id,),
('enable', True),
('name', 'test-port'),
]
if add_tags:
verifylist.append(('tags', ['red', 'blue']))
else:
verifylist.append(('no_tag', True))
self.network.find_extension = mock.Mock(return_value=add_tags_in_post)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
args = {
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
}
if add_tags_in_post:
if add_tags:
args['tags'] = sorted(['red', 'blue'])
else:
args['tags'] = []
self.network.create_port.assert_called_once()
# Now we need to verify if arguments to call create_port are as
# expected,
# But we can't simply use assert_called_once_with() method because
# duplicates from 'tags' are removed with
# list(set(parsed_args.tags)) and that don't quarantee order of
# tags list which is used to call create_port().
create_port_call_kwargs = self.network.create_port.call_args[1]
create_port_call_kwargs['tags'] = sorted(
create_port_call_kwargs['tags'])
self.assertDictEqual(args, create_port_call_kwargs)
else:
self.network.create_port.assert_called_once_with(
admin_state_up=True,
network_id=self._port.network_id,
name='test-port'
)
if add_tags:
self.network.set_tags.assert_called_once_with(
self._port,
tests_utils.CompareBySet(['red', 'blue']))
else:
self.assertFalse(self.network.set_tags.called)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_tags(self):
self._test_create_with_tag(add_tags=True, add_tags_in_post=True)
def test_create_with_no_tag(self):
self._test_create_with_tag(add_tags=False, add_tags_in_post=True)
def test_create_with_tags_using_put(self):
self._test_create_with_tag(add_tags=True, add_tags_in_post=False)
def test_create_with_no_tag_using_put(self):
self._test_create_with_tag(add_tags=False, add_tags_in_post=False)
def _test_create_with_uplink_status_propagation(self, enable=True):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if enable:
arglist += ['--enable-uplink-status-propagation']
else:
arglist += ['--disable-uplink-status-propagation']
verifylist = [
('network', self._port.network_id,),
('name', 'test-port'),
]
if enable:
verifylist.append(('enable_uplink_status_propagation', True))
else:
verifylist.append(('disable_uplink_status_propagation', True))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'propagate_uplink_status': enable,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_uplink_status_propagation_enabled(self):
self._test_create_with_uplink_status_propagation(enable=True)
def test_create_with_uplink_status_propagation_disabled(self):
self._test_create_with_uplink_status_propagation(enable=False)
def test_create_port_with_extra_dhcp_option(self):
extra_dhcp_options = [{'opt_name': 'classless-static-route',
'opt_value': '169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1',
'ip_version': '4'},
{'opt_name': 'dns-server',
'opt_value': '240C::6666',
'ip_version': '6'}]
arglist = [
'--network', self._port.network_id,
'--extra-dhcp-option', 'name=classless-static-route,'
'value=169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1,'
'ip-version=4',
'--extra-dhcp-option', 'name=dns-server,value=240C::6666,'
'ip-version=6',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('extra_dhcp_options', [{'name': 'classless-static-route',
'value': '169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1',
'ip-version': '4'},
{'name': 'dns-server',
'value': '240C::6666',
'ip-version': '6'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'extra_dhcp_opts': extra_dhcp_options,
'name': 'test-port',
})
def _test_create_with_numa_affinity_policy(self, policy=None):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if policy:
arglist += ['--numa-policy-%s' % policy]
numa_affinity_policy = None if not policy else policy
verifylist = [
('network', self._port.network_id,),
('name', 'test-port'),
]
if policy:
verifylist.append(('numa_policy_%s' % policy, True))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
create_args = {
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
}
if numa_affinity_policy:
create_args['numa_affinity_policy'] = numa_affinity_policy
self.network.create_port.assert_called_once_with(**create_args)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_numa_affinity_policy_required(self):
self._test_create_with_numa_affinity_policy(policy='required')
def test_create_with_numa_affinity_policy_preferred(self):
self._test_create_with_numa_affinity_policy(policy='preferred')
def test_create_with_numa_affinity_policy_legacy(self):
self._test_create_with_numa_affinity_policy(policy='legacy')
def test_create_with_numa_affinity_policy_null(self):
self._test_create_with_numa_affinity_policy()
class TestDeletePort(TestPort):
# Ports to delete.
_ports = network_fakes.FakePort.create_ports(count=2)
def setUp(self):
super(TestDeletePort, self).setUp()
self.network.delete_port = mock.Mock(return_value=None)
self.network.find_port = network_fakes.FakePort.get_ports(
ports=self._ports)
# Get the command object to test
self.cmd = port.DeletePort(self.app, self.namespace)
def test_port_delete(self):
arglist = [
self._ports[0].name,
]
verifylist = [
('port', [self._ports[0].name]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.network.find_port.assert_called_once_with(
self._ports[0].name, ignore_missing=False)
self.network.delete_port.assert_called_once_with(self._ports[0])
self.assertIsNone(result)
def test_multi_ports_delete(self):
arglist = []
verifylist = []
for p in self._ports:
arglist.append(p.name)
verifylist = [
('port', arglist),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
calls = []
for p in self._ports:
calls.append(call(p))
self.network.delete_port.assert_has_calls(calls)
self.assertIsNone(result)
def test_multi_ports_delete_with_exception(self):
arglist = [
self._ports[0].name,
'unexist_port',
]
verifylist = [
('port',
[self._ports[0].name, 'unexist_port']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
find_mock_result = [self._ports[0], exceptions.CommandError]
self.network.find_port = (
mock.Mock(side_effect=find_mock_result)
)
try:
self.cmd.take_action(parsed_args)
self.fail('CommandError should be raised.')
except exceptions.CommandError as e:
self.assertEqual('1 of 2 ports failed to delete.', str(e))
self.network.find_port.assert_any_call(
self._ports[0].name, ignore_missing=False)
self.network.find_port.assert_any_call(
'unexist_port', ignore_missing=False)
self.network.delete_port.assert_called_once_with(
self._ports[0]
)
class TestListPort(TestPort):
_ports = network_fakes.FakePort.create_ports(count=3)
columns = (
'ID',
'Name',
'MAC Address',
'Fixed IP Addresses',
'Status',
)
columns_long = (
'ID',
'Name',
'MAC Address',
'Fixed IP Addresses',
'Status',
'Security Groups',
'Device Owner',
'Tags',
)
data = []
for prt in _ports:
data.append((
prt.id,
prt.name,
prt.mac_address,
format_columns.ListDictColumn(prt.fixed_ips),
prt.status,
))
data_long = []
for prt in _ports:
data_long.append((
prt.id,
prt.name,
prt.mac_address,
format_columns.ListDictColumn(prt.fixed_ips),
prt.status,
format_columns.ListColumn(prt.security_group_ids),
prt.device_owner,
format_columns.ListColumn(prt.tags),
))
def setUp(self):
super(TestListPort, self).setUp()
# Get the command object to test
self.cmd = port.ListPort(self.app, self.namespace)
self.network.ports = mock.Mock(return_value=self._ports)
fake_router = network_fakes.FakeRouter.create_one_router({
'id': 'fake-router-id',
})
fake_network = network_fakes.FakeNetwork.create_one_network({
'id': 'fake-network-id',
})
self.network.find_router = mock.Mock(return_value=fake_router)
self.network.find_network = mock.Mock(return_value=fake_network)
self.app.client_manager.compute = mock.Mock()
def test_port_list_no_options(self):
arglist = []
verifylist = []
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with()
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_router_opt(self):
arglist = [
'--router', 'fake-router-name',
]
verifylist = [
('router', 'fake-router-name')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_id': 'fake-router-id'
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
@mock.patch.object(utils, 'find_resource')
def test_port_list_with_server_option(self, mock_find):
fake_server = compute_fakes.FakeServer.create_one_server()
mock_find.return_value = fake_server
arglist = [
'--server', 'fake-server-name',
]
verifylist = [
('server', 'fake-server-name'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(
device_id=fake_server.id)
mock_find.assert_called_once_with(mock.ANY, 'fake-server-name')
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_device_id_opt(self):
arglist = [
'--device-id', self._ports[0].device_id,
]
verifylist = [
('device_id', self._ports[0].device_id)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_id': self._ports[0].device_id
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_device_owner_opt(self):
arglist = [
'--device-owner', self._ports[0].device_owner,
]
verifylist = [
('device_owner', self._ports[0].device_owner)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_owner': self._ports[0].device_owner
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_all_opt(self):
arglist = [
'--device-owner', self._ports[0].device_owner,
'--router', 'fake-router-name',
'--network', 'fake-network-name',
'--mac-address', self._ports[0].mac_address,
]
verifylist = [
('device_owner', self._ports[0].device_owner),
('router', 'fake-router-name'),
('network', 'fake-network-name'),
('mac_address', self._ports[0].mac_address)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_owner': self._ports[0].device_owner,
'device_id': 'fake-router-id',
'network_id': 'fake-network-id',
'mac_address': self._ports[0].mac_address
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_mac_address_opt(self):
arglist = [
'--mac-address', self._ports[0].mac_address,
]
verifylist = [
('mac_address', self._ports[0].mac_address)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'mac_address': self._ports[0].mac_address
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_ip_address(self):
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "ip-address=%s" % ip_address,
]
verifylist = [
('fixed_ip', [{'ip-address': ip_address}])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_ip_address_substr(self):
ip_address_ss = self._ports[0].fixed_ips[0]['ip_address'][:-1]
arglist = [
'--fixed-ip', "ip-substring=%s" % ip_address_ss,
]
verifylist = [
('fixed_ip', [{'ip-substring': ip_address_ss}])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['ip_address_substr=%s' % ip_address_ss]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_subnet_id(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
arglist = [
'--fixed-ip', "subnet=%s" % subnet_id,
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opts(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "subnet=%s,ip-address=%s" % (subnet_id,
ip_address)
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id,
'ip-address': ip_address}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id,
'ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ips(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "subnet=%s" % subnet_id,
'--fixed-ip', "ip-address=%s" % ip_address,
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id},
{'ip-address': ip_address}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id,
'ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_list_port_with_long(self):
arglist = [
'--long',
]
verifylist = [
('long', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with()
self.assertEqual(self.columns_long, columns)
self.assertListItemEqual(self.data_long, list(data))
def test_port_list_host(self):
arglist = [
'--host', 'foobar',
]
verifylist = [
('host', 'foobar'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'binding:host_id': 'foobar'}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_project(self):
project = identity_fakes.FakeProject.create_one_project()
self.projects_mock.get.return_value = project
arglist = [
'--project', project.id,
]
verifylist = [
('project', project.id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'tenant_id': project.id, 'project_id': project.id}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_project_domain(self):
project = identity_fakes.FakeProject.create_one_project()
self.projects_mock.get.return_value = project
arglist = [
'--project', project.id,
'--project-domain', project.domain_id,
]
verifylist = [
('project', project.id),
('project_domain', project.domain_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'tenant_id': project.id, 'project_id': project.id}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_list_with_tag_options(self):
arglist = [
'--tags', 'red,blue',
'--any-tags', 'red,green',
'--not-tags', 'orange,yellow',
'--not-any-tags', 'black,white',
]
verifylist = [
('tags', ['red', 'blue']),
('any_tags', ['red', 'green']),
('not_tags', ['orange', 'yellow']),
('not_any_tags', ['black', 'white']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(
**{'tags': 'red,blue',
'any_tags': 'red,green',
'not_tags': 'orange,yellow',
'not_any_tags': 'black,white'}
)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
class TestSetPort(TestPort):
_port = network_fakes.FakePort.create_one_port({'tags': ['green', 'red']})
def setUp(self):
super(TestSetPort, self).setUp()
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet()
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_port = mock.Mock(return_value=self._port)
self.network.update_port = mock.Mock(return_value=None)
self.network.set_tags = mock.Mock(return_value=None)
# Get the command object to test
self.cmd = port.SetPort(self.app, self.namespace)
def test_set_port_defaults(self):
arglist = [
self._port.name,
]
verifylist = [
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.assertFalse(self.network.set_tags.called)
self.assertIsNone(result)
def test_set_port_fixed_ip(self):
_testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'ip_address': '0.0.0.1'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--fixed-ip', 'ip-address=10.0.0.12',
_testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '10.0.0.12'}]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [
{'ip_address': '0.0.0.1'},
{'ip_address': '10.0.0.12'},
],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_fixed_ip_clear(self):
_testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'ip_address': '0.0.0.1'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--fixed-ip', 'ip-address=10.0.0.12',
'--no-fixed-ip',
_testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '10.0.0.12'}]),
('no_fixed_ip', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [
{'ip_address': '10.0.0.12'},
],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_dns_name(self):
arglist = [
'--dns-name', '8.8.8.8',
self._port.name,
]
verifylist = [
('dns_name', '8.8.8.8'),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'dns_name': '8.8.8.8',
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_overwrite_binding_profile(self):
_testport = network_fakes.FakePort.create_one_port(
{'binding_profile': {'lok_i': 'visi_on'}})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--binding-profile', 'lok_i=than_os',
'--no-binding-profile',
_testport.name,
]
verifylist = [
('binding_profile', {'lok_i': 'than_os'}),
('no_binding_profile', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'binding:profile':
{'lok_i': 'than_os'},
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_overwrite_mac_address(self):
_testport = network_fakes.FakePort.create_one_port(
{'mac_address': '11:22:33:44:55:66'})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--mac-address', '66:55:44:33:22:11',
_testport.name,
]
verifylist = [
('mac_address', '66:55:44:33:22:11'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'mac_address': '66:55:44:33:22:11',
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_this(self):
arglist = [
'--disable',
'--no-fixed-ip',
'--no-binding-profile',
self._port.name,
]
verifylist = [
('disable', True),
('no_binding_profile', True),
('no_fixed_ip', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'admin_state_up': False,
'binding:profile': {},
'fixed_ips': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_that(self):
arglist = [
'--description', 'newDescription',
'--enable',
'--vnic-type', 'macvtap',
'--binding-profile', 'foo=bar',
'--host', 'binding-host-id-xxxx',
'--name', 'newName',
self._port.name,
]
verifylist = [
('description', 'newDescription'),
('enable', True),
('vnic_type', 'macvtap'),
('binding_profile', {'foo': 'bar'}),
('host', 'binding-host-id-xxxx'),
('name', 'newName'),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'admin_state_up': True,
'binding:vnic_type': 'macvtap',
'binding:profile': {'foo': 'bar'},
'binding:host_id': 'binding-host-id-xxxx',
'description': 'newDescription',
'name': 'newName',
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_invalid_json_binding_profile(self):
arglist = [
'--binding-profile', '{"parent_name"}',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_set_port_invalid_key_value_binding_profile(self):
arglist = [
'--binding-profile', 'key',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_set_port_mixed_binding_profile(self):
arglist = [
'--binding-profile', 'foo=bar',
'--binding-profile', '{"foo2": "bar2"}',
self._port.name,
]
verifylist = [
('binding_profile', {'foo': 'bar', 'foo2': 'bar2'}),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'binding:profile': {'foo': 'bar', 'foo2': 'bar2'},
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group(self):
sg = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(return_value=sg)
arglist = [
'--security-group', sg.id,
self._port.name,
]
verifylist = [
('security_group', [sg.id]),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg.id],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_append(self):
sg_1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_2 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_3 = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(side_effect=[sg_2, sg_3])
_testport = network_fakes.FakePort.create_one_port(
{'security_group_ids': [sg_1.id]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--security-group', sg_2.id,
'--security-group', sg_3.id,
_testport.name,
]
verifylist = [
('security_group', [sg_2.id, sg_3.id]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg_1.id, sg_2.id, sg_3.id],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_clear(self):
arglist = [
'--no-security-group',
self._port.name,
]
verifylist = [
('no_security_group', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_replace(self):
sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_testport = network_fakes.FakePort.create_one_port(
{'security_group_ids': [sg1.id]})
self.network.find_port = mock.Mock(return_value=_testport)
self.network.find_security_group = mock.Mock(return_value=sg2)
arglist = [
'--security-group', sg2.id,
'--no-security-group',
_testport.name,
]
verifylist = [
('security_group', [sg2.id]),
('no_security_group', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg2.id],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_allowed_address_pair(self):
arglist = [
'--allowed-address', 'ip-address=192.168.1.123',
self._port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.123'}]),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.123'}],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_append_allowed_address_pair(self):
_testport = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
_testport.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.123'},
{'ip_address': '192.168.1.45'}],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_overwrite_allowed_address_pair(self):
_testport = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
'--no-allowed-address',
_testport.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
('no_allowed_address_pair', True),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.45'}],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_no_allowed_address_pairs(self):
arglist = [
'--no-allowed-address',
self._port.name,
]
verifylist = [
('no_allowed_address_pair', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_enabled(self):
arglist = [
'--enable-port-security',
self._port.id,
]
verifylist = [
('enable_port_security', True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(self._port, **{
'port_security_enabled': True,
})
def test_set_port_security_disabled(self):
arglist = [
'--disable-port-security',
self._port.id,
]
verifylist = [
('disable_port_security', True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(self._port, **{
'port_security_enabled': False,
})
def test_set_port_with_qos(self):
qos_policy = network_fakes.FakeNetworkQosPolicy.create_one_qos_policy()
self.network.find_qos_policy = mock.Mock(return_value=qos_policy)
_testport = network_fakes.FakePort.create_one_port(
{'qos_policy_id': None})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--qos-policy', qos_policy.id,
_testport.name,
]
verifylist = [
('qos_policy', qos_policy.id),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'qos_policy_id': qos_policy.id,
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_data_plane_status(self):
_testport = network_fakes.FakePort.create_one_port(
{'data_plane_status': None})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--data-plane-status', 'ACTIVE',
_testport.name,
]
verifylist = [
('data_plane_status', 'ACTIVE'),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'data_plane_status': 'ACTIVE',
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_invalid_data_plane_status_value(self):
arglist = [
'--data-plane-status', 'Spider-Man',
'test-port',
]
self.assertRaises(tests_utils.ParserException,
self.check_parser,
self.cmd,
arglist,
None)
def _test_set_tags(self, with_tags=True):
if with_tags:
arglist = ['--tag', 'red', '--tag', 'blue']
verifylist = [('tags', ['red', 'blue'])]
expected_args = ['red', 'blue', 'green']
else:
arglist = ['--no-tag']
verifylist = [('no_tag', True)]
expected_args = []
arglist.append(self._port.name)
verifylist.append(
('port', self._port.name))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.network.set_tags.assert_called_once_with(
self._port,
tests_utils.CompareBySet(expected_args))
self.assertIsNone(result)
def test_set_with_tags(self):
self._test_set_tags(with_tags=True)
def test_set_with_no_tag(self):
self._test_set_tags(with_tags=False)
def _test_create_with_numa_affinity_policy(self, policy):
arglist = [
'--numa-policy-%s' % policy,
self._port.id,
]
verifylist = [
('numa_policy_%s' % policy, True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(
self._port, **{'numa_affinity_policy': policy})
def test_create_with_numa_affinity_policy_required(self):
self._test_create_with_numa_affinity_policy('required')
def test_create_with_numa_affinity_policy_preferred(self):
self._test_create_with_numa_affinity_policy('preferred')
def test_create_with_numa_affinity_policy_legacy(self):
self._test_create_with_numa_affinity_policy('legacy')
class TestShowPort(TestPort):
# The port to show.
_port = network_fakes.FakePort.create_one_port()
columns, data = TestPort._get_common_cols_data(_port)
def setUp(self):
super(TestShowPort, self).setUp()
self.network.find_port = mock.Mock(return_value=self._port)
# Get the command object to test
self.cmd = port.ShowPort(self.app, self.namespace)
def test_show_no_options(self):
arglist = []
verifylist = []
self.assertRaises(tests_utils.ParserException,
self.check_parser, self.cmd, arglist, verifylist)
def test_show_all_options(self):
arglist = [
self._port.name,
]
verifylist = [
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.find_port.assert_called_once_with(
self._port.name, ignore_missing=False)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
class TestUnsetPort(TestPort):
def setUp(self):
super(TestUnsetPort, self).setUp()
self._testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '0.0.0.1'},
{'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '1.0.0.0'}],
'binding:profile': {'batman': 'Joker', 'Superman': 'LexLuthor'},
'tags': ['green', 'red'], })
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': '042eb10a-3a18-4658-ab-cf47c8d03152'})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_port = mock.Mock(return_value=self._testport)
self.network.update_port = mock.Mock(return_value=None)
self.network.set_tags = mock.Mock(return_value=None)
# Get the command object to test
self.cmd = port.UnsetPort(self.app, self.namespace)
def test_unset_port_parameters(self):
arglist = [
'--fixed-ip',
'subnet=042eb10a-3a18-4658-ab-cf47c8d03152,ip-address=1.0.0.0',
'--binding-profile', 'Superman',
'--qos-policy',
self._testport.name,
]
verifylist = [
('fixed_ip', [{
'subnet': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip-address': '1.0.0.0'}]),
('binding_profile', ['Superman']),
('qos_policy', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [{
'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '0.0.0.1'}],
'binding:profile': {'batman': 'Joker'},
'qos_policy_id': None
}
self.network.update_port.assert_called_once_with(
self._testport, **attrs)
self.assertIsNone(result)
def test_unset_port_fixed_ip_not_existent(self):
arglist = [
'--fixed-ip', 'ip-address=1.0.0.1',
'--binding-profile', 'Superman',
self._testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '1.0.0.1'}]),
('binding_profile', ['Superman']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_binding_profile_not_existent(self):
arglist = [
'--fixed-ip', 'ip-address=1.0.0.0',
'--binding-profile', 'Neo',
self._testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '1.0.0.0'}]),
('binding_profile', ['Neo']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_security_group(self):
_fake_sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_port = network_fakes.FakePort.create_one_port(
{'security_group_ids': [_fake_sg1.id, _fake_sg2.id]})
self.network.find_port = mock.Mock(return_value=_fake_port)
self.network.find_security_group = mock.Mock(return_value=_fake_sg2)
arglist = [
'--security-group', _fake_sg2.id,
_fake_port.name,
]
verifylist = [
('security_group_ids', [_fake_sg2.id]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [_fake_sg1.id]
}
self.network.update_port.assert_called_once_with(
_fake_port, **attrs)
self.assertIsNone(result)
def test_unset_port_security_group_not_existent(self):
_fake_sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_port = network_fakes.FakePort.create_one_port(
{'security_group_ids': [_fake_sg1.id]})
self.network.find_security_group = mock.Mock(return_value=_fake_sg2)
arglist = [
'--security-group', _fake_sg2.id,
_fake_port.name,
]
verifylist = [
('security_group_ids', [_fake_sg2.id]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_allowed_address_pair(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--allowed-address', 'ip-address=192.168.1.123',
_fake_port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.123'}]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [],
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
def test_unset_port_allowed_address_pair_not_existent(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
_fake_port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_data_plane_status(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'data_plane_status': 'ACTIVE'})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--data-plane-status',
_fake_port.name,
]
verifylist = [
('data_plane_status', True),
('port', _fake_port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'data_plane_status': None,
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
def _test_unset_tags(self, with_tags=True):
if with_tags:
arglist = ['--tag', 'red', '--tag', 'blue']
verifylist = [('tags', ['red', 'blue'])]
expected_args = ['green']
else:
arglist = ['--all-tag']
verifylist = [('all_tag', True)]
expected_args = []
arglist.append(self._testport.name)
verifylist.append(
('port', self._testport.name))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.network.set_tags.assert_called_once_with(
self._testport,
tests_utils.CompareBySet(expected_args))
self.assertIsNone(result)
def test_unset_with_tags(self):
self._test_unset_tags(with_tags=True)
def test_unset_with_all_tag(self):
self._test_unset_tags(with_tags=False)
def test_unset_numa_affinity_policy(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'numa_affinity_policy': 'required'})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--numa-policy',
_fake_port.name,
]
verifylist = [
('numa_policy', True),
('port', _fake_port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'numa_affinity_policy': None,
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
| 35.219191 | 79 | 0.575963 |
import argparse
from unittest import mock
from unittest.mock import call
from osc_lib.cli import format_columns
from osc_lib import exceptions
from osc_lib import utils
from openstackclient.network.v2 import port
from openstackclient.tests.unit.compute.v2 import fakes as compute_fakes
from openstackclient.tests.unit.identity.v3 import fakes as identity_fakes
from openstackclient.tests.unit.network.v2 import fakes as network_fakes
from openstackclient.tests.unit import utils as tests_utils
class TestPort(network_fakes.TestNetworkV2):
def setUp(self):
super(TestPort, self).setUp()
self.network = self.app.client_manager.network
self.projects_mock = self.app.client_manager.identity.projects
@staticmethod
def _get_common_cols_data(fake_port):
columns = (
'admin_state_up',
'allowed_address_pairs',
'binding_host_id',
'binding_profile',
'binding_vif_details',
'binding_vif_type',
'binding_vnic_type',
'data_plane_status',
'description',
'device_id',
'device_owner',
'dns_assignment',
'dns_domain',
'dns_name',
'extra_dhcp_opts',
'fixed_ips',
'id',
'mac_address',
'name',
'network_id',
'numa_affinity_policy',
'port_security_enabled',
'project_id',
'qos_network_policy_id',
'qos_policy_id',
'security_group_ids',
'status',
'tags',
'uplink_status_propagation',
)
data = (
port.AdminStateColumn(fake_port.admin_state_up),
format_columns.ListDictColumn(fake_port.allowed_address_pairs),
fake_port.binding_host_id,
format_columns.DictColumn(fake_port.binding_profile),
format_columns.DictColumn(fake_port.binding_vif_details),
fake_port.binding_vif_type,
fake_port.binding_vnic_type,
fake_port.data_plane_status,
fake_port.description,
fake_port.device_id,
fake_port.device_owner,
format_columns.ListDictColumn(fake_port.dns_assignment),
fake_port.dns_domain,
fake_port.dns_name,
format_columns.ListDictColumn(fake_port.extra_dhcp_opts),
format_columns.ListDictColumn(fake_port.fixed_ips),
fake_port.id,
fake_port.mac_address,
fake_port.name,
fake_port.network_id,
fake_port.numa_affinity_policy,
fake_port.port_security_enabled,
fake_port.project_id,
fake_port.qos_network_policy_id,
fake_port.qos_policy_id,
format_columns.ListColumn(fake_port.security_group_ids),
fake_port.status,
format_columns.ListColumn(fake_port.tags),
fake_port.uplink_status_propagation,
)
return columns, data
class TestCreatePort(TestPort):
_port = network_fakes.FakePort.create_one_port()
columns, data = TestPort._get_common_cols_data(_port)
def setUp(self):
super(TestCreatePort, self).setUp()
self.network.create_port = mock.Mock(return_value=self._port)
self.network.set_tags = mock.Mock(return_value=None)
fake_net = network_fakes.FakeNetwork.create_one_network({
'id': self._port.network_id,
})
self.network.find_network = mock.Mock(return_value=fake_net)
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet()
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_extension = mock.Mock(return_value=[])
self.cmd = port.CreatePort(self.app, self.namespace)
def test_create_default_options(self):
arglist = [
'--network', self._port.network_id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
})
self.assertFalse(self.network.set_tags.called)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_full_options(self):
arglist = [
'--mac-address', 'aa:aa:aa:aa:aa:aa',
'--fixed-ip', 'subnet=%s,ip-address=10.0.0.2'
% self.fake_subnet.id,
'--description', self._port.description,
'--device', 'deviceid',
'--device-owner', 'fakeowner',
'--disable',
'--vnic-type', 'macvtap',
'--binding-profile', 'foo=bar',
'--binding-profile', 'foo2=bar2',
'--network', self._port.network_id,
'--dns-domain', 'example.org',
'--dns-name', '8.8.8.8',
'test-port',
]
verifylist = [
('mac_address', 'aa:aa:aa:aa:aa:aa'),
(
'fixed_ip',
[{'subnet': self.fake_subnet.id, 'ip-address': '10.0.0.2'}]
),
('description', self._port.description),
('device', 'deviceid'),
('device_owner', 'fakeowner'),
('disable', True),
('vnic_type', 'macvtap'),
('binding_profile', {'foo': 'bar', 'foo2': 'bar2'}),
('network', self._port.network_id),
('dns_domain', 'example.org'),
('dns_name', '8.8.8.8'),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'mac_address': 'aa:aa:aa:aa:aa:aa',
'fixed_ips': [{'subnet_id': self.fake_subnet.id,
'ip_address': '10.0.0.2'}],
'description': self._port.description,
'device_id': 'deviceid',
'device_owner': 'fakeowner',
'admin_state_up': False,
'binding:vnic_type': 'macvtap',
'binding:profile': {'foo': 'bar', 'foo2': 'bar2'},
'network_id': self._port.network_id,
'dns_domain': 'example.org',
'dns_name': '8.8.8.8',
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_invalid_json_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', '{"parent_name":"fake_parent"',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_create_invalid_key_value_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', 'key',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_create_json_binding_profile(self):
arglist = [
'--network', self._port.network_id,
'--binding-profile', '{"parent_name":"fake_parent"}',
'--binding-profile', '{"tag":42}',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('binding_profile', {'parent_name': 'fake_parent', 'tag': 42}),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'binding:profile': {'parent_name': 'fake_parent', 'tag': 42},
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_security_group(self):
secgroup = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(return_value=secgroup)
arglist = [
'--network', self._port.network_id,
'--security-group', secgroup.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('security_group', [secgroup.id]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [secgroup.id],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_dns_name(self):
arglist = [
'--network', self._port.network_id,
'--dns-name', '8.8.8.8',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('dns_name', '8.8.8.8'),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'dns_name': '8.8.8.8',
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_security_groups(self):
sg_1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_2 = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(side_effect=[sg_1, sg_2])
arglist = [
'--network', self._port.network_id,
'--security-group', sg_1.id,
'--security-group', sg_2.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('security_group', [sg_1.id, sg_2.id]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [sg_1.id, sg_2.id],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_no_security_groups(self):
arglist = [
'--network', self._port.network_id,
'--no-security-group',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('no_security_group', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'security_group_ids': [],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_no_fixed_ips(self):
arglist = [
'--network', self._port.network_id,
'--no-fixed-ip',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('no_fixed_ip', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'fixed_ips': [],
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_allowed_address_pair_ipaddr(self):
pairs = [{'ip_address': '192.168.1.123'},
{'ip_address': '192.168.1.45'}]
arglist = [
'--network', self._port.network_id,
'--allowed-address', 'ip-address=192.168.1.123',
'--allowed-address', 'ip-address=192.168.1.45',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('allowed_address_pairs', [{'ip-address': '192.168.1.123'},
{'ip-address': '192.168.1.45'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'allowed_address_pairs': pairs,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_allowed_address_pair(self):
pairs = [{'ip_address': '192.168.1.123',
'mac_address': 'aa:aa:aa:aa:aa:aa'},
{'ip_address': '192.168.1.45',
'mac_address': 'aa:aa:aa:aa:aa:b1'}]
arglist = [
'--network', self._port.network_id,
'--allowed-address',
'ip-address=192.168.1.123,mac-address=aa:aa:aa:aa:aa:aa',
'--allowed-address',
'ip-address=192.168.1.45,mac-address=aa:aa:aa:aa:aa:b1',
'test-port',
]
verifylist = [
('network', self._port.network_id),
('enable', True),
('allowed_address_pairs', [{'ip-address': '192.168.1.123',
'mac-address': 'aa:aa:aa:aa:aa:aa'},
{'ip-address': '192.168.1.45',
'mac-address': 'aa:aa:aa:aa:aa:b1'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'allowed_address_pairs': pairs,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_with_qos(self):
qos_policy = network_fakes.FakeNetworkQosPolicy.create_one_qos_policy()
self.network.find_qos_policy = mock.Mock(return_value=qos_policy)
arglist = [
'--network', self._port.network_id,
'--qos-policy', qos_policy.id,
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('qos_policy', qos_policy.id),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'qos_policy_id': qos_policy.id,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_port_security_enabled(self):
arglist = [
'--network', self._port.network_id,
'--enable-port-security',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('enable_port_security', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'port_security_enabled': True,
'name': 'test-port',
})
def test_create_port_security_disabled(self):
arglist = [
'--network', self._port.network_id,
'--disable-port-security',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('enable', True),
('disable_port_security', True),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'port_security_enabled': False,
'name': 'test-port',
})
def _test_create_with_tag(self, add_tags=True, add_tags_in_post=True):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if add_tags:
arglist += ['--tag', 'red', '--tag', 'blue']
else:
arglist += ['--no-tag']
verifylist = [
('network', self._port.network_id,),
('enable', True),
('name', 'test-port'),
]
if add_tags:
verifylist.append(('tags', ['red', 'blue']))
else:
verifylist.append(('no_tag', True))
self.network.find_extension = mock.Mock(return_value=add_tags_in_post)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
args = {
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
}
if add_tags_in_post:
if add_tags:
args['tags'] = sorted(['red', 'blue'])
else:
args['tags'] = []
self.network.create_port.assert_called_once()
# duplicates from 'tags' are removed with
# list(set(parsed_args.tags)) and that don't quarantee order of
create_port_call_kwargs = self.network.create_port.call_args[1]
create_port_call_kwargs['tags'] = sorted(
create_port_call_kwargs['tags'])
self.assertDictEqual(args, create_port_call_kwargs)
else:
self.network.create_port.assert_called_once_with(
admin_state_up=True,
network_id=self._port.network_id,
name='test-port'
)
if add_tags:
self.network.set_tags.assert_called_once_with(
self._port,
tests_utils.CompareBySet(['red', 'blue']))
else:
self.assertFalse(self.network.set_tags.called)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_tags(self):
self._test_create_with_tag(add_tags=True, add_tags_in_post=True)
def test_create_with_no_tag(self):
self._test_create_with_tag(add_tags=False, add_tags_in_post=True)
def test_create_with_tags_using_put(self):
self._test_create_with_tag(add_tags=True, add_tags_in_post=False)
def test_create_with_no_tag_using_put(self):
self._test_create_with_tag(add_tags=False, add_tags_in_post=False)
def _test_create_with_uplink_status_propagation(self, enable=True):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if enable:
arglist += ['--enable-uplink-status-propagation']
else:
arglist += ['--disable-uplink-status-propagation']
verifylist = [
('network', self._port.network_id,),
('name', 'test-port'),
]
if enable:
verifylist.append(('enable_uplink_status_propagation', True))
else:
verifylist.append(('disable_uplink_status_propagation', True))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'propagate_uplink_status': enable,
'name': 'test-port',
})
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_uplink_status_propagation_enabled(self):
self._test_create_with_uplink_status_propagation(enable=True)
def test_create_with_uplink_status_propagation_disabled(self):
self._test_create_with_uplink_status_propagation(enable=False)
def test_create_port_with_extra_dhcp_option(self):
extra_dhcp_options = [{'opt_name': 'classless-static-route',
'opt_value': '169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1',
'ip_version': '4'},
{'opt_name': 'dns-server',
'opt_value': '240C::6666',
'ip_version': '6'}]
arglist = [
'--network', self._port.network_id,
'--extra-dhcp-option', 'name=classless-static-route,'
'value=169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1,'
'ip-version=4',
'--extra-dhcp-option', 'name=dns-server,value=240C::6666,'
'ip-version=6',
'test-port',
]
verifylist = [
('network', self._port.network_id,),
('extra_dhcp_options', [{'name': 'classless-static-route',
'value': '169.254.169.254/32,22.2.0.2,'
'0.0.0.0/0,22.2.0.1',
'ip-version': '4'},
{'name': 'dns-server',
'value': '240C::6666',
'ip-version': '6'}]),
('name', 'test-port'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.create_port.assert_called_once_with(**{
'admin_state_up': True,
'network_id': self._port.network_id,
'extra_dhcp_opts': extra_dhcp_options,
'name': 'test-port',
})
def _test_create_with_numa_affinity_policy(self, policy=None):
arglist = [
'--network', self._port.network_id,
'test-port',
]
if policy:
arglist += ['--numa-policy-%s' % policy]
numa_affinity_policy = None if not policy else policy
verifylist = [
('network', self._port.network_id,),
('name', 'test-port'),
]
if policy:
verifylist.append(('numa_policy_%s' % policy, True))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = (self.cmd.take_action(parsed_args))
create_args = {
'admin_state_up': True,
'network_id': self._port.network_id,
'name': 'test-port',
}
if numa_affinity_policy:
create_args['numa_affinity_policy'] = numa_affinity_policy
self.network.create_port.assert_called_once_with(**create_args)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
def test_create_with_numa_affinity_policy_required(self):
self._test_create_with_numa_affinity_policy(policy='required')
def test_create_with_numa_affinity_policy_preferred(self):
self._test_create_with_numa_affinity_policy(policy='preferred')
def test_create_with_numa_affinity_policy_legacy(self):
self._test_create_with_numa_affinity_policy(policy='legacy')
def test_create_with_numa_affinity_policy_null(self):
self._test_create_with_numa_affinity_policy()
class TestDeletePort(TestPort):
_ports = network_fakes.FakePort.create_ports(count=2)
def setUp(self):
super(TestDeletePort, self).setUp()
self.network.delete_port = mock.Mock(return_value=None)
self.network.find_port = network_fakes.FakePort.get_ports(
ports=self._ports)
self.cmd = port.DeletePort(self.app, self.namespace)
def test_port_delete(self):
arglist = [
self._ports[0].name,
]
verifylist = [
('port', [self._ports[0].name]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.network.find_port.assert_called_once_with(
self._ports[0].name, ignore_missing=False)
self.network.delete_port.assert_called_once_with(self._ports[0])
self.assertIsNone(result)
def test_multi_ports_delete(self):
arglist = []
verifylist = []
for p in self._ports:
arglist.append(p.name)
verifylist = [
('port', arglist),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
calls = []
for p in self._ports:
calls.append(call(p))
self.network.delete_port.assert_has_calls(calls)
self.assertIsNone(result)
def test_multi_ports_delete_with_exception(self):
arglist = [
self._ports[0].name,
'unexist_port',
]
verifylist = [
('port',
[self._ports[0].name, 'unexist_port']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
find_mock_result = [self._ports[0], exceptions.CommandError]
self.network.find_port = (
mock.Mock(side_effect=find_mock_result)
)
try:
self.cmd.take_action(parsed_args)
self.fail('CommandError should be raised.')
except exceptions.CommandError as e:
self.assertEqual('1 of 2 ports failed to delete.', str(e))
self.network.find_port.assert_any_call(
self._ports[0].name, ignore_missing=False)
self.network.find_port.assert_any_call(
'unexist_port', ignore_missing=False)
self.network.delete_port.assert_called_once_with(
self._ports[0]
)
class TestListPort(TestPort):
_ports = network_fakes.FakePort.create_ports(count=3)
columns = (
'ID',
'Name',
'MAC Address',
'Fixed IP Addresses',
'Status',
)
columns_long = (
'ID',
'Name',
'MAC Address',
'Fixed IP Addresses',
'Status',
'Security Groups',
'Device Owner',
'Tags',
)
data = []
for prt in _ports:
data.append((
prt.id,
prt.name,
prt.mac_address,
format_columns.ListDictColumn(prt.fixed_ips),
prt.status,
))
data_long = []
for prt in _ports:
data_long.append((
prt.id,
prt.name,
prt.mac_address,
format_columns.ListDictColumn(prt.fixed_ips),
prt.status,
format_columns.ListColumn(prt.security_group_ids),
prt.device_owner,
format_columns.ListColumn(prt.tags),
))
def setUp(self):
super(TestListPort, self).setUp()
self.cmd = port.ListPort(self.app, self.namespace)
self.network.ports = mock.Mock(return_value=self._ports)
fake_router = network_fakes.FakeRouter.create_one_router({
'id': 'fake-router-id',
})
fake_network = network_fakes.FakeNetwork.create_one_network({
'id': 'fake-network-id',
})
self.network.find_router = mock.Mock(return_value=fake_router)
self.network.find_network = mock.Mock(return_value=fake_network)
self.app.client_manager.compute = mock.Mock()
def test_port_list_no_options(self):
arglist = []
verifylist = []
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with()
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_router_opt(self):
arglist = [
'--router', 'fake-router-name',
]
verifylist = [
('router', 'fake-router-name')
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_id': 'fake-router-id'
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
@mock.patch.object(utils, 'find_resource')
def test_port_list_with_server_option(self, mock_find):
fake_server = compute_fakes.FakeServer.create_one_server()
mock_find.return_value = fake_server
arglist = [
'--server', 'fake-server-name',
]
verifylist = [
('server', 'fake-server-name'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(
device_id=fake_server.id)
mock_find.assert_called_once_with(mock.ANY, 'fake-server-name')
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_device_id_opt(self):
arglist = [
'--device-id', self._ports[0].device_id,
]
verifylist = [
('device_id', self._ports[0].device_id)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_id': self._ports[0].device_id
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_device_owner_opt(self):
arglist = [
'--device-owner', self._ports[0].device_owner,
]
verifylist = [
('device_owner', self._ports[0].device_owner)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_owner': self._ports[0].device_owner
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_all_opt(self):
arglist = [
'--device-owner', self._ports[0].device_owner,
'--router', 'fake-router-name',
'--network', 'fake-network-name',
'--mac-address', self._ports[0].mac_address,
]
verifylist = [
('device_owner', self._ports[0].device_owner),
('router', 'fake-router-name'),
('network', 'fake-network-name'),
('mac_address', self._ports[0].mac_address)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'device_owner': self._ports[0].device_owner,
'device_id': 'fake-router-id',
'network_id': 'fake-network-id',
'mac_address': self._ports[0].mac_address
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_mac_address_opt(self):
arglist = [
'--mac-address', self._ports[0].mac_address,
]
verifylist = [
('mac_address', self._ports[0].mac_address)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'mac_address': self._ports[0].mac_address
})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_ip_address(self):
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "ip-address=%s" % ip_address,
]
verifylist = [
('fixed_ip', [{'ip-address': ip_address}])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_ip_address_substr(self):
ip_address_ss = self._ports[0].fixed_ips[0]['ip_address'][:-1]
arglist = [
'--fixed-ip', "ip-substring=%s" % ip_address_ss,
]
verifylist = [
('fixed_ip', [{'ip-substring': ip_address_ss}])
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['ip_address_substr=%s' % ip_address_ss]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opt_subnet_id(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
arglist = [
'--fixed-ip', "subnet=%s" % subnet_id,
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ip_opts(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "subnet=%s,ip-address=%s" % (subnet_id,
ip_address)
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id,
'ip-address': ip_address}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id,
'ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_fixed_ips(self):
subnet_id = self._ports[0].fixed_ips[0]['subnet_id']
ip_address = self._ports[0].fixed_ips[0]['ip_address']
arglist = [
'--fixed-ip', "subnet=%s" % subnet_id,
'--fixed-ip', "ip-address=%s" % ip_address,
]
verifylist = [
('fixed_ip', [{'subnet': subnet_id},
{'ip-address': ip_address}])
]
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': subnet_id})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(**{
'fixed_ips': ['subnet_id=%s' % subnet_id,
'ip_address=%s' % ip_address]})
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_list_port_with_long(self):
arglist = [
'--long',
]
verifylist = [
('long', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with()
self.assertEqual(self.columns_long, columns)
self.assertListItemEqual(self.data_long, list(data))
def test_port_list_host(self):
arglist = [
'--host', 'foobar',
]
verifylist = [
('host', 'foobar'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'binding:host_id': 'foobar'}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_project(self):
project = identity_fakes.FakeProject.create_one_project()
self.projects_mock.get.return_value = project
arglist = [
'--project', project.id,
]
verifylist = [
('project', project.id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'tenant_id': project.id, 'project_id': project.id}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_port_list_project_domain(self):
project = identity_fakes.FakeProject.create_one_project()
self.projects_mock.get.return_value = project
arglist = [
'--project', project.id,
'--project-domain', project.domain_id,
]
verifylist = [
('project', project.id),
('project_domain', project.domain_id),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
filters = {'tenant_id': project.id, 'project_id': project.id}
self.network.ports.assert_called_once_with(**filters)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
def test_list_with_tag_options(self):
arglist = [
'--tags', 'red,blue',
'--any-tags', 'red,green',
'--not-tags', 'orange,yellow',
'--not-any-tags', 'black,white',
]
verifylist = [
('tags', ['red', 'blue']),
('any_tags', ['red', 'green']),
('not_tags', ['orange', 'yellow']),
('not_any_tags', ['black', 'white']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.ports.assert_called_once_with(
**{'tags': 'red,blue',
'any_tags': 'red,green',
'not_tags': 'orange,yellow',
'not_any_tags': 'black,white'}
)
self.assertEqual(self.columns, columns)
self.assertListItemEqual(self.data, list(data))
class TestSetPort(TestPort):
_port = network_fakes.FakePort.create_one_port({'tags': ['green', 'red']})
def setUp(self):
super(TestSetPort, self).setUp()
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet()
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_port = mock.Mock(return_value=self._port)
self.network.update_port = mock.Mock(return_value=None)
self.network.set_tags = mock.Mock(return_value=None)
self.cmd = port.SetPort(self.app, self.namespace)
def test_set_port_defaults(self):
arglist = [
self._port.name,
]
verifylist = [
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.assertFalse(self.network.set_tags.called)
self.assertIsNone(result)
def test_set_port_fixed_ip(self):
_testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'ip_address': '0.0.0.1'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--fixed-ip', 'ip-address=10.0.0.12',
_testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '10.0.0.12'}]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [
{'ip_address': '0.0.0.1'},
{'ip_address': '10.0.0.12'},
],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_fixed_ip_clear(self):
_testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'ip_address': '0.0.0.1'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--fixed-ip', 'ip-address=10.0.0.12',
'--no-fixed-ip',
_testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '10.0.0.12'}]),
('no_fixed_ip', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [
{'ip_address': '10.0.0.12'},
],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_dns_name(self):
arglist = [
'--dns-name', '8.8.8.8',
self._port.name,
]
verifylist = [
('dns_name', '8.8.8.8'),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'dns_name': '8.8.8.8',
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_overwrite_binding_profile(self):
_testport = network_fakes.FakePort.create_one_port(
{'binding_profile': {'lok_i': 'visi_on'}})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--binding-profile', 'lok_i=than_os',
'--no-binding-profile',
_testport.name,
]
verifylist = [
('binding_profile', {'lok_i': 'than_os'}),
('no_binding_profile', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'binding:profile':
{'lok_i': 'than_os'},
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_overwrite_mac_address(self):
_testport = network_fakes.FakePort.create_one_port(
{'mac_address': '11:22:33:44:55:66'})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--mac-address', '66:55:44:33:22:11',
_testport.name,
]
verifylist = [
('mac_address', '66:55:44:33:22:11'),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'mac_address': '66:55:44:33:22:11',
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_this(self):
arglist = [
'--disable',
'--no-fixed-ip',
'--no-binding-profile',
self._port.name,
]
verifylist = [
('disable', True),
('no_binding_profile', True),
('no_fixed_ip', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'admin_state_up': False,
'binding:profile': {},
'fixed_ips': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_that(self):
arglist = [
'--description', 'newDescription',
'--enable',
'--vnic-type', 'macvtap',
'--binding-profile', 'foo=bar',
'--host', 'binding-host-id-xxxx',
'--name', 'newName',
self._port.name,
]
verifylist = [
('description', 'newDescription'),
('enable', True),
('vnic_type', 'macvtap'),
('binding_profile', {'foo': 'bar'}),
('host', 'binding-host-id-xxxx'),
('name', 'newName'),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'admin_state_up': True,
'binding:vnic_type': 'macvtap',
'binding:profile': {'foo': 'bar'},
'binding:host_id': 'binding-host-id-xxxx',
'description': 'newDescription',
'name': 'newName',
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_invalid_json_binding_profile(self):
arglist = [
'--binding-profile', '{"parent_name"}',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_set_port_invalid_key_value_binding_profile(self):
arglist = [
'--binding-profile', 'key',
'test-port',
]
self.assertRaises(argparse.ArgumentTypeError,
self.check_parser,
self.cmd,
arglist,
None)
def test_set_port_mixed_binding_profile(self):
arglist = [
'--binding-profile', 'foo=bar',
'--binding-profile', '{"foo2": "bar2"}',
self._port.name,
]
verifylist = [
('binding_profile', {'foo': 'bar', 'foo2': 'bar2'}),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'binding:profile': {'foo': 'bar', 'foo2': 'bar2'},
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group(self):
sg = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(return_value=sg)
arglist = [
'--security-group', sg.id,
self._port.name,
]
verifylist = [
('security_group', [sg.id]),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg.id],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_append(self):
sg_1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_2 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg_3 = network_fakes.FakeSecurityGroup.create_one_security_group()
self.network.find_security_group = mock.Mock(side_effect=[sg_2, sg_3])
_testport = network_fakes.FakePort.create_one_port(
{'security_group_ids': [sg_1.id]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--security-group', sg_2.id,
'--security-group', sg_3.id,
_testport.name,
]
verifylist = [
('security_group', [sg_2.id, sg_3.id]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg_1.id, sg_2.id, sg_3.id],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_clear(self):
arglist = [
'--no-security-group',
self._port.name,
]
verifylist = [
('no_security_group', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_group_replace(self):
sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_testport = network_fakes.FakePort.create_one_port(
{'security_group_ids': [sg1.id]})
self.network.find_port = mock.Mock(return_value=_testport)
self.network.find_security_group = mock.Mock(return_value=sg2)
arglist = [
'--security-group', sg2.id,
'--no-security-group',
_testport.name,
]
verifylist = [
('security_group', [sg2.id]),
('no_security_group', True)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [sg2.id],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_allowed_address_pair(self):
arglist = [
'--allowed-address', 'ip-address=192.168.1.123',
self._port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.123'}]),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.123'}],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_append_allowed_address_pair(self):
_testport = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
_testport.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.123'},
{'ip_address': '192.168.1.45'}],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_overwrite_allowed_address_pair(self):
_testport = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
'--no-allowed-address',
_testport.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
('no_allowed_address_pair', True),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [{'ip_address': '192.168.1.45'}],
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_no_allowed_address_pairs(self):
arglist = [
'--no-allowed-address',
self._port.name,
]
verifylist = [
('no_allowed_address_pair', True),
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [],
}
self.network.update_port.assert_called_once_with(self._port, **attrs)
self.assertIsNone(result)
def test_set_port_security_enabled(self):
arglist = [
'--enable-port-security',
self._port.id,
]
verifylist = [
('enable_port_security', True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(self._port, **{
'port_security_enabled': True,
})
def test_set_port_security_disabled(self):
arglist = [
'--disable-port-security',
self._port.id,
]
verifylist = [
('disable_port_security', True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(self._port, **{
'port_security_enabled': False,
})
def test_set_port_with_qos(self):
qos_policy = network_fakes.FakeNetworkQosPolicy.create_one_qos_policy()
self.network.find_qos_policy = mock.Mock(return_value=qos_policy)
_testport = network_fakes.FakePort.create_one_port(
{'qos_policy_id': None})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--qos-policy', qos_policy.id,
_testport.name,
]
verifylist = [
('qos_policy', qos_policy.id),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'qos_policy_id': qos_policy.id,
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_data_plane_status(self):
_testport = network_fakes.FakePort.create_one_port(
{'data_plane_status': None})
self.network.find_port = mock.Mock(return_value=_testport)
arglist = [
'--data-plane-status', 'ACTIVE',
_testport.name,
]
verifylist = [
('data_plane_status', 'ACTIVE'),
('port', _testport.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'data_plane_status': 'ACTIVE',
}
self.network.update_port.assert_called_once_with(_testport, **attrs)
self.assertIsNone(result)
def test_set_port_invalid_data_plane_status_value(self):
arglist = [
'--data-plane-status', 'Spider-Man',
'test-port',
]
self.assertRaises(tests_utils.ParserException,
self.check_parser,
self.cmd,
arglist,
None)
def _test_set_tags(self, with_tags=True):
if with_tags:
arglist = ['--tag', 'red', '--tag', 'blue']
verifylist = [('tags', ['red', 'blue'])]
expected_args = ['red', 'blue', 'green']
else:
arglist = ['--no-tag']
verifylist = [('no_tag', True)]
expected_args = []
arglist.append(self._port.name)
verifylist.append(
('port', self._port.name))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.network.set_tags.assert_called_once_with(
self._port,
tests_utils.CompareBySet(expected_args))
self.assertIsNone(result)
def test_set_with_tags(self):
self._test_set_tags(with_tags=True)
def test_set_with_no_tag(self):
self._test_set_tags(with_tags=False)
def _test_create_with_numa_affinity_policy(self, policy):
arglist = [
'--numa-policy-%s' % policy,
self._port.id,
]
verifylist = [
('numa_policy_%s' % policy, True),
('port', self._port.id,)
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.cmd.take_action(parsed_args)
self.network.update_port.assert_called_once_with(
self._port, **{'numa_affinity_policy': policy})
def test_create_with_numa_affinity_policy_required(self):
self._test_create_with_numa_affinity_policy('required')
def test_create_with_numa_affinity_policy_preferred(self):
self._test_create_with_numa_affinity_policy('preferred')
def test_create_with_numa_affinity_policy_legacy(self):
self._test_create_with_numa_affinity_policy('legacy')
class TestShowPort(TestPort):
_port = network_fakes.FakePort.create_one_port()
columns, data = TestPort._get_common_cols_data(_port)
def setUp(self):
super(TestShowPort, self).setUp()
self.network.find_port = mock.Mock(return_value=self._port)
self.cmd = port.ShowPort(self.app, self.namespace)
def test_show_no_options(self):
arglist = []
verifylist = []
self.assertRaises(tests_utils.ParserException,
self.check_parser, self.cmd, arglist, verifylist)
def test_show_all_options(self):
arglist = [
self._port.name,
]
verifylist = [
('port', self._port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
columns, data = self.cmd.take_action(parsed_args)
self.network.find_port.assert_called_once_with(
self._port.name, ignore_missing=False)
self.assertEqual(self.columns, columns)
self.assertItemEqual(self.data, data)
class TestUnsetPort(TestPort):
def setUp(self):
super(TestUnsetPort, self).setUp()
self._testport = network_fakes.FakePort.create_one_port(
{'fixed_ips': [{'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '0.0.0.1'},
{'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '1.0.0.0'}],
'binding:profile': {'batman': 'Joker', 'Superman': 'LexLuthor'},
'tags': ['green', 'red'], })
self.fake_subnet = network_fakes.FakeSubnet.create_one_subnet(
{'id': '042eb10a-3a18-4658-ab-cf47c8d03152'})
self.network.find_subnet = mock.Mock(return_value=self.fake_subnet)
self.network.find_port = mock.Mock(return_value=self._testport)
self.network.update_port = mock.Mock(return_value=None)
self.network.set_tags = mock.Mock(return_value=None)
self.cmd = port.UnsetPort(self.app, self.namespace)
def test_unset_port_parameters(self):
arglist = [
'--fixed-ip',
'subnet=042eb10a-3a18-4658-ab-cf47c8d03152,ip-address=1.0.0.0',
'--binding-profile', 'Superman',
'--qos-policy',
self._testport.name,
]
verifylist = [
('fixed_ip', [{
'subnet': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip-address': '1.0.0.0'}]),
('binding_profile', ['Superman']),
('qos_policy', True),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'fixed_ips': [{
'subnet_id': '042eb10a-3a18-4658-ab-cf47c8d03152',
'ip_address': '0.0.0.1'}],
'binding:profile': {'batman': 'Joker'},
'qos_policy_id': None
}
self.network.update_port.assert_called_once_with(
self._testport, **attrs)
self.assertIsNone(result)
def test_unset_port_fixed_ip_not_existent(self):
arglist = [
'--fixed-ip', 'ip-address=1.0.0.1',
'--binding-profile', 'Superman',
self._testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '1.0.0.1'}]),
('binding_profile', ['Superman']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_binding_profile_not_existent(self):
arglist = [
'--fixed-ip', 'ip-address=1.0.0.0',
'--binding-profile', 'Neo',
self._testport.name,
]
verifylist = [
('fixed_ip', [{'ip-address': '1.0.0.0'}]),
('binding_profile', ['Neo']),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_security_group(self):
_fake_sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_port = network_fakes.FakePort.create_one_port(
{'security_group_ids': [_fake_sg1.id, _fake_sg2.id]})
self.network.find_port = mock.Mock(return_value=_fake_port)
self.network.find_security_group = mock.Mock(return_value=_fake_sg2)
arglist = [
'--security-group', _fake_sg2.id,
_fake_port.name,
]
verifylist = [
('security_group_ids', [_fake_sg2.id]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'security_group_ids': [_fake_sg1.id]
}
self.network.update_port.assert_called_once_with(
_fake_port, **attrs)
self.assertIsNone(result)
def test_unset_port_security_group_not_existent(self):
_fake_sg1 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_sg2 = network_fakes.FakeSecurityGroup.create_one_security_group()
_fake_port = network_fakes.FakePort.create_one_port(
{'security_group_ids': [_fake_sg1.id]})
self.network.find_security_group = mock.Mock(return_value=_fake_sg2)
arglist = [
'--security-group', _fake_sg2.id,
_fake_port.name,
]
verifylist = [
('security_group_ids', [_fake_sg2.id]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_allowed_address_pair(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--allowed-address', 'ip-address=192.168.1.123',
_fake_port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.123'}]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'allowed_address_pairs': [],
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
def test_unset_port_allowed_address_pair_not_existent(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'allowed_address_pairs': [{'ip_address': '192.168.1.123'}]})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--allowed-address', 'ip-address=192.168.1.45',
_fake_port.name,
]
verifylist = [
('allowed_address_pairs', [{'ip-address': '192.168.1.45'}]),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
self.assertRaises(exceptions.CommandError,
self.cmd.take_action,
parsed_args)
def test_unset_port_data_plane_status(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'data_plane_status': 'ACTIVE'})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--data-plane-status',
_fake_port.name,
]
verifylist = [
('data_plane_status', True),
('port', _fake_port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'data_plane_status': None,
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
def _test_unset_tags(self, with_tags=True):
if with_tags:
arglist = ['--tag', 'red', '--tag', 'blue']
verifylist = [('tags', ['red', 'blue'])]
expected_args = ['green']
else:
arglist = ['--all-tag']
verifylist = [('all_tag', True)]
expected_args = []
arglist.append(self._testport.name)
verifylist.append(
('port', self._testport.name))
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
self.assertFalse(self.network.update_port.called)
self.network.set_tags.assert_called_once_with(
self._testport,
tests_utils.CompareBySet(expected_args))
self.assertIsNone(result)
def test_unset_with_tags(self):
self._test_unset_tags(with_tags=True)
def test_unset_with_all_tag(self):
self._test_unset_tags(with_tags=False)
def test_unset_numa_affinity_policy(self):
_fake_port = network_fakes.FakePort.create_one_port(
{'numa_affinity_policy': 'required'})
self.network.find_port = mock.Mock(return_value=_fake_port)
arglist = [
'--numa-policy',
_fake_port.name,
]
verifylist = [
('numa_policy', True),
('port', _fake_port.name),
]
parsed_args = self.check_parser(self.cmd, arglist, verifylist)
result = self.cmd.take_action(parsed_args)
attrs = {
'numa_affinity_policy': None,
}
self.network.update_port.assert_called_once_with(_fake_port, **attrs)
self.assertIsNone(result)
| true | true |
f729b6b0ac12628966abd0799969cfe496c9a34c | 78,317 | py | Python | tests/core/full_node/test_full_node.py | grayfallstown/taco-blockchain | 6196d73af7a982301a0a1ad5c1bed836b2f95a8d | [
"Apache-2.0"
] | null | null | null | tests/core/full_node/test_full_node.py | grayfallstown/taco-blockchain | 6196d73af7a982301a0a1ad5c1bed836b2f95a8d | [
"Apache-2.0"
] | null | null | null | tests/core/full_node/test_full_node.py | grayfallstown/taco-blockchain | 6196d73af7a982301a0a1ad5c1bed836b2f95a8d | [
"Apache-2.0"
] | null | null | null | # flake8: noqa: F811, F401
import asyncio
import dataclasses
import logging
import random
import time
from secrets import token_bytes
from typing import Dict, Optional, List
import pytest
from taco.consensus.pot_iterations import is_overflow_block
from taco.full_node.bundle_tools import detect_potential_template_generator
from taco.full_node.full_node_api import FullNodeAPI
from taco.full_node.signage_point import SignagePoint
from taco.protocols import full_node_protocol as fnp, full_node_protocol
from taco.protocols import timelord_protocol
from taco.protocols.full_node_protocol import RespondTransaction
from taco.protocols.protocol_message_types import ProtocolMessageTypes
from taco.server.address_manager import AddressManager
from taco.server.outbound_message import Message
from taco.simulator.simulator_protocol import FarmNewBlockProtocol
from taco.types.blockchain_format.classgroup import ClassgroupElement
from taco.types.blockchain_format.program import SerializedProgram
from taco.types.blockchain_format.vdf import CompressibleVDFField, VDFProof
from taco.types.condition_opcodes import ConditionOpcode
from taco.types.condition_with_args import ConditionWithArgs
from taco.types.full_block import FullBlock
from taco.types.mempool_inclusion_status import MempoolInclusionStatus
from taco.types.peer_info import PeerInfo, TimestampedPeerInfo
from taco.types.spend_bundle import SpendBundle
from taco.types.unfinished_block import UnfinishedBlock
from tests.block_tools import get_signage_point
from taco.util.clvm import int_to_bytes
from taco.util.errors import Err
from taco.util.hash import std_hash
from taco.util.ints import uint8, uint16, uint32, uint64
from taco.util.recursive_replace import recursive_replace
from taco.util.vdf_prover import get_vdf_info_and_proof
from tests.wallet_tools import WalletTool
from tests.core.fixtures import empty_blockchain # noqa: F401
from taco.wallet.cc_wallet.cc_wallet import CCWallet
from taco.wallet.transaction_record import TransactionRecord
from tests.connection_utils import add_dummy_connection, connect_and_get_peer
from tests.core.full_node.test_coin_store import get_future_reward_coins
from tests.core.full_node.test_mempool_performance import wallet_height_at_least
from tests.core.make_block_generator import make_spend_bundle
from tests.core.node_height import node_height_at_least
from tests.core.fixtures import empty_blockchain # noqa: F401
from tests.setup_nodes import bt, self_hostname, setup_simulators_and_wallets, test_constants
from tests.time_out_assert import time_out_assert, time_out_assert_custom_interval, time_out_messages
log = logging.getLogger(__name__)
async def new_transaction_not_requested(incoming, new_spend):
await asyncio.sleep(3)
while not incoming.empty():
response, peer = await incoming.get()
if (
response is not None
and isinstance(response, Message)
and response.type == ProtocolMessageTypes.request_transaction.value
):
request = full_node_protocol.RequestTransaction.from_bytes(response.data)
if request.transaction_id == new_spend.transaction_id:
return False
return True
async def new_transaction_requested(incoming, new_spend):
await asyncio.sleep(1)
while not incoming.empty():
response, peer = await incoming.get()
if (
response is not None
and isinstance(response, Message)
and response.type == ProtocolMessageTypes.request_transaction.value
):
request = full_node_protocol.RequestTransaction.from_bytes(response.data)
if request.transaction_id == new_spend.transaction_id:
return True
return False
async def get_block_path(full_node: FullNodeAPI):
blocks_list = [await full_node.full_node.blockchain.get_full_peak()]
assert blocks_list[0] is not None
while blocks_list[0].height != 0:
b = await full_node.full_node.block_store.get_full_block(blocks_list[0].prev_header_hash)
assert b is not None
blocks_list.insert(0, b)
return blocks_list
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
@pytest.fixture(scope="module")
async def wallet_nodes():
async_gen = setup_simulators_and_wallets(2, 1, {"MEMPOOL_BLOCK_BUFFER": 2, "MAX_BLOCK_COST_CLVM": 400000000})
nodes, wallets = await async_gen.__anext__()
full_node_1 = nodes[0]
full_node_2 = nodes[1]
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
wallet_a = bt.get_pool_wallet_tool()
wallet_receiver = WalletTool(full_node_1.full_node.constants)
yield full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver
async for _ in async_gen:
yield _
@pytest.fixture(scope="function")
async def setup_four_nodes():
async for _ in setup_simulators_and_wallets(5, 0, {}, starting_port=51000):
yield _
@pytest.fixture(scope="function")
async def setup_two_nodes():
async for _ in setup_simulators_and_wallets(2, 0, {}, starting_port=51100):
yield _
@pytest.fixture(scope="function")
async def setup_two_nodes_and_wallet():
async for _ in setup_simulators_and_wallets(2, 1, {}, starting_port=51200):
yield _
@pytest.fixture(scope="function")
async def wallet_nodes_mainnet():
async_gen = setup_simulators_and_wallets(2, 1, {"NETWORK_TYPE": 0}, starting_port=40000)
nodes, wallets = await async_gen.__anext__()
full_node_1 = nodes[0]
full_node_2 = nodes[1]
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
wallet_a = bt.get_pool_wallet_tool()
wallet_receiver = WalletTool(full_node_1.full_node.constants)
yield full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver
async for _ in async_gen:
yield _
class TestFullNodeBlockCompression:
@pytest.mark.asyncio
async def do_test_block_compression(self, setup_two_nodes_and_wallet, empty_blockchain, tx_size, test_reorgs):
nodes, wallets = setup_two_nodes_and_wallet
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
server_3 = wallets[0][1]
full_node_1 = nodes[0]
full_node_2 = nodes[1]
wallet_node_1 = wallets[0][0]
wallet = wallet_node_1.wallet_state_manager.main_wallet
_ = await connect_and_get_peer(server_1, server_2)
_ = await connect_and_get_peer(server_1, server_3)
ph = await wallet.get_new_puzzlehash()
for i in range(4):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 4)
await time_out_assert(10, node_height_at_least, True, full_node_1, 4)
await time_out_assert(10, node_height_at_least, True, full_node_2, 4)
# Send a transaction to mempool
tr: TransactionRecord = await wallet.generate_signed_transaction(
tx_size,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Farm a block
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 5)
await time_out_assert(10, node_height_at_least, True, full_node_2, 5)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 5)
# Confirm generator is not compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(5), program) is not None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0
# Send another tx
tr: TransactionRecord = await wallet.generate_signed_transaction(
20000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Farm a block
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 6)
await time_out_assert(10, node_height_at_least, True, full_node_2, 6)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 6)
# Confirm generator is compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(6), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
# Farm two empty blocks
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 8)
await time_out_assert(10, node_height_at_least, True, full_node_2, 8)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 8)
# Send another 2 tx
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
40000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
50000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
3000000000000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Farm a block
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 9)
await time_out_assert(10, node_height_at_least, True, full_node_2, 9)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 9)
# Confirm generator is compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(9), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
# Creates a cc wallet
cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node_1.wallet_state_manager, wallet, uint64(100))
tx_queue: List[TransactionRecord] = await wallet_node_1.wallet_state_manager.tx_store.get_not_sent()
tr = tx_queue[0]
await time_out_assert(
10,
full_node_1.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.spend_bundle.name(),
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Farm a block
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 10)
await time_out_assert(10, node_height_at_least, True, full_node_2, 10)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 10)
# Confirm generator is compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(10), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
# Make a cc transaction
tr: TransactionRecord = await cc_wallet.generate_signed_transaction([uint64(60)], [ph])
await wallet.wallet_state_manager.add_pending_transaction(tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Make a standard transaction
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
# Farm a block
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 11)
await time_out_assert(10, node_height_at_least, True, full_node_2, 11)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 11)
# Confirm generator is not compressed
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(11), program) is not None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0
height = full_node_1.full_node.blockchain.get_peak().height
blockchain = empty_blockchain
all_blocks: List[FullBlock] = await full_node_1.get_all_full_blocks()
assert height == len(all_blocks) - 1
assert full_node_1.full_node.full_node_store.previous_generator is not None
if test_reorgs:
reog_blocks = bt.get_consecutive_blocks(14)
for r in range(0, len(reog_blocks), 3):
for reorg_block in reog_blocks[:r]:
assert (await blockchain.receive_block(reorg_block))[1] is None
for i in range(1, height):
for batch_size in range(1, height):
results = await blockchain.pre_validate_blocks_multiprocessing(all_blocks[:i], {}, batch_size)
assert results is not None
for result in results:
assert result.error is None
for r in range(0, len(all_blocks), 3):
for block in all_blocks[:r]:
assert (await blockchain.receive_block(block))[1] is None
for i in range(1, height):
for batch_size in range(1, height):
results = await blockchain.pre_validate_blocks_multiprocessing(all_blocks[:i], {}, batch_size)
assert results is not None
for result in results:
assert result.error is None
# Test revert previous_generator
for block in reog_blocks:
await full_node_1.full_node.respond_block(full_node_protocol.RespondBlock(block))
assert full_node_1.full_node.full_node_store.previous_generator is None
@pytest.mark.asyncio
async def test_block_compression(self, setup_two_nodes_and_wallet, empty_blockchain):
await self.do_test_block_compression(setup_two_nodes_and_wallet, empty_blockchain, 10000, True)
@pytest.mark.asyncio
async def test_block_compression_2(self, setup_two_nodes_and_wallet, empty_blockchain):
await self.do_test_block_compression(setup_two_nodes_and_wallet, empty_blockchain, 3000000000000, False)
class TestFullNodeProtocol:
@pytest.mark.asyncio
async def test_spendbundle_serialization(self):
sb: SpendBundle = make_spend_bundle(1)
protocol_message = RespondTransaction(sb)
assert bytes(sb) == bytes(protocol_message)
@pytest.mark.asyncio
async def test_inbound_connection_limit(self, setup_four_nodes):
nodes, _ = setup_four_nodes
server_1 = nodes[0].full_node.server
server_1.config["target_peer_count"] = 2
server_1.config["target_outbound_peer_count"] = 0
for i in range(1, 4):
full_node_i = nodes[i]
server_i = full_node_i.full_node.server
await server_i.start_client(PeerInfo(self_hostname, uint16(server_1._port)))
assert len(server_1.get_full_node_connections()) == 2
@pytest.mark.asyncio
async def test_request_peers(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
full_node_2.full_node.full_node_peers.address_manager.make_private_subnets_valid()
await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)))
async def have_msgs():
await full_node_2.full_node.full_node_peers.address_manager.add_to_new_table(
[TimestampedPeerInfo("127.0.0.1", uint16(1000), uint64(int(time.time())) - 1000)],
None,
)
msg_bytes = await full_node_2.full_node.full_node_peers.request_peers(PeerInfo("[::1]", server_2._port))
msg = fnp.RespondPeers.from_bytes(msg_bytes.data)
if msg is not None and not (len(msg.peer_list) == 1):
return False
peer = msg.peer_list[0]
return (peer.host == self_hostname or peer.host == "127.0.0.1") and peer.port == 1000
await time_out_assert_custom_interval(10, 1, have_msgs, True)
full_node_1.full_node.full_node_peers.address_manager = AddressManager()
@pytest.mark.asyncio
async def test_basic_chain(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, _ = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(1)
for block in blocks[:1]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 1))
assert full_node_1.full_node.blockchain.get_peak().height == 0
for block in bt.get_consecutive_blocks(30):
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
assert full_node_1.full_node.blockchain.get_peak().height == 29
@pytest.mark.asyncio
async def test_respond_end_of_sub_slot(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
# Create empty slots
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=6)
# Add empty slots successful
for slot in blocks[-1].finished_sub_slots[:-2]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
num_sub_slots_added = len(blocks[-1].finished_sub_slots[:-2])
await time_out_assert(
10,
time_out_messages(
incoming_queue,
"new_signage_point_or_end_of_sub_slot",
num_sub_slots_added,
),
)
# Already have sub slot
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(blocks[-1].finished_sub_slots[-3]), peer)
await asyncio.sleep(2)
assert incoming_queue.qsize() == 0
# Add empty slots unsuccessful
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(blocks[-1].finished_sub_slots[-1]), peer)
await asyncio.sleep(2)
assert incoming_queue.qsize() == 0
# Add some blocks
blocks = bt.get_consecutive_blocks(4, block_list_input=blocks)
for block in blocks[-5:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 5))
blocks = bt.get_consecutive_blocks(1, skip_slots=2, block_list_input=blocks)
# Add empty slots successful
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
num_sub_slots_added = len(blocks[-1].finished_sub_slots)
await time_out_assert(
10,
time_out_messages(
incoming_queue,
"new_signage_point_or_end_of_sub_slot",
num_sub_slots_added,
),
)
@pytest.mark.asyncio
async def test_respond_unfinished(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = await full_node_1.get_all_full_blocks()
# Create empty slots
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=6)
block = blocks[-1]
if is_overflow_block(test_constants, block.reward_chain_block.signage_point_index):
finished_ss = block.finished_sub_slots[:-1]
else:
finished_ss = block.finished_sub_slots
unf = UnfinishedBlock(
finished_ss,
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
# Can't add because no sub slots
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
# Add empty slots successful
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# Do the same thing but with non-genesis
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=3)
block = blocks[-1]
if is_overflow_block(test_constants, block.reward_chain_block.signage_point_index):
finished_ss = block.finished_sub_slots[:-1]
else:
finished_ss = block.finished_sub_slots
unf = UnfinishedBlock(
finished_ss,
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# Do the same thing one more time, with overflow
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=3, force_overflow=True)
block = blocks[-1]
unf = UnfinishedBlock(
block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# This next section tests making unfinished block with transactions, and then submitting the finished block
ph = wallet_a.get_new_puzzlehash()
ph_receiver = wallet_receiver.get_new_puzzlehash()
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=ph,
pool_reward_puzzle_hash=ph,
)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
coin_to_spend = list(blocks[-1].get_included_reward_coins())[0]
spend_bundle = wallet_a.generate_signed_transaction(coin_to_spend.amount, ph_receiver, coin_to_spend)
blocks = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
force_overflow=True,
seed=b"random seed",
)
block = blocks[-1]
unf = UnfinishedBlock(
block.finished_sub_slots[:-1], # Since it's overflow
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
result = full_node_1.full_node.full_node_store.get_unfinished_block_result(unf.partial_hash)
assert result is not None
assert result.npc_result is not None and result.npc_result.clvm_cost > 0
assert not full_node_1.full_node.blockchain.contains_block(block.header_hash)
assert block.transactions_generator is not None
block_no_transactions = dataclasses.replace(block, transactions_generator=None)
assert block_no_transactions.transactions_generator is None
await full_node_1.full_node.respond_block(fnp.RespondBlock(block_no_transactions))
assert full_node_1.full_node.blockchain.contains_block(block.header_hash)
@pytest.mark.asyncio
async def test_new_peak(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
dummy_peer = server_1.all_connections[dummy_node_id]
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks) # Alternate chain
blocks_reorg = bt.get_consecutive_blocks(3, block_list_input=blocks[:-1], seed=b"214") # Alternate chain
for block in blocks[-3:]:
new_peak = fnp.NewPeak(
block.header_hash,
block.height,
block.weight,
uint32(0),
block.reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
# Ignores, already have
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 0))
# Ignores low weight
new_peak = fnp.NewPeak(
blocks_reorg[-2].header_hash,
blocks_reorg[-2].height,
blocks_reorg[-2].weight,
uint32(0),
blocks_reorg[-2].reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 0))
# Does not ignore equal weight
new_peak = fnp.NewPeak(
blocks_reorg[-1].header_hash,
blocks_reorg[-1].height,
blocks_reorg[-1].weight,
uint32(0),
blocks_reorg[-1].reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
@pytest.mark.asyncio
async def test_new_transaction_and_mempool(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = bt.get_consecutive_blocks(
10,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
for block in blocks:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
start_height = (
full_node_1.full_node.blockchain.get_peak().height
if full_node_1.full_node.blockchain.get_peak() is not None
else -1
)
peer = await connect_and_get_peer(server_1, server_2)
incoming_queue, node_id = await add_dummy_connection(server_1, 12312)
fake_peer = server_1.all_connections[node_id]
# Mempool has capacity of 100, make 110 unspents that we can use
puzzle_hashes = []
block_buffer_count = full_node_1.full_node.constants.MEMPOOL_BLOCK_BUFFER
# Makes a bunch of coins
for i in range(5):
conditions_dict: Dict = {ConditionOpcode.CREATE_COIN: []}
# This should fit in one transaction
for _ in range(100):
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
puzzle_hashes.append(receiver_puzzlehash)
output = ConditionWithArgs(ConditionOpcode.CREATE_COIN, [receiver_puzzlehash, int_to_bytes(100000000)])
conditions_dict[ConditionOpcode.CREATE_COIN].append(output)
spend_bundle = wallet_a.generate_signed_transaction(
100,
puzzle_hashes[0],
get_future_reward_coins(blocks[1 + i])[0],
condition_dic=conditions_dict,
)
assert spend_bundle is not None
cost_result = await full_node_1.full_node.mempool_manager.pre_validate_spendbundle(spend_bundle)
log.info(f"Cost result: {cost_result.clvm_cost}")
new_transaction = fnp.NewTransaction(spend_bundle.get_hash(), uint64(100), uint64(100))
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_requested, True, incoming_queue, new_transaction)
respond_transaction_2 = fnp.RespondTransaction(spend_bundle)
await full_node_1.respond_transaction(respond_transaction_2, peer)
blocks = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]), peer)
# Already seen
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_not_requested, True, incoming_queue, new_transaction)
await time_out_assert(10, node_height_at_least, True, full_node_1, start_height + 5)
spend_bundles = []
included_tx = 0
not_included_tx = 0
seen_bigger_transaction_has_high_fee = False
successful_bundle: Optional[SpendBundle] = None
# Fill mempool
for puzzle_hash in puzzle_hashes[1:]:
coin_record = (await full_node_1.full_node.coin_store.get_coin_records_by_puzzle_hash(True, puzzle_hash))[0]
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
if puzzle_hash == puzzle_hashes[-1]:
force_high_fee = True
fee = 100000000 # 100 million (20 fee per cost)
else:
force_high_fee = False
fee = random.randint(1, 100000000)
spend_bundle = wallet_receiver.generate_signed_transaction(
uint64(500), receiver_puzzlehash, coin_record.coin, fee=fee
)
respond_transaction = fnp.RespondTransaction(spend_bundle)
await full_node_1.respond_transaction(respond_transaction, peer)
request = fnp.RequestTransaction(spend_bundle.get_hash())
req = await full_node_1.request_transaction(request)
fee_rate_for_small = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(10)
fee_rate_for_med = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(5000000)
fee_rate_for_large = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(50000000)
log.info(f"Min fee rate (10): {fee_rate_for_small}")
log.info(f"Min fee rate (5000000): {fee_rate_for_med}")
log.info(f"Min fee rate (50000000): {fee_rate_for_large}")
if fee_rate_for_large > fee_rate_for_med:
seen_bigger_transaction_has_high_fee = True
if req is not None and req.data == bytes(fnp.RespondTransaction(spend_bundle)):
included_tx += 1
spend_bundles.append(spend_bundle)
assert not full_node_1.full_node.mempool_manager.mempool.at_full_capacity(0)
assert full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(0) == 0
if force_high_fee:
successful_bundle = spend_bundle
else:
assert full_node_1.full_node.mempool_manager.mempool.at_full_capacity(10000000)
assert full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(10000000) > 0
assert not force_high_fee
not_included_tx += 1
log.info(f"Included: {included_tx}, not included: {not_included_tx}")
assert included_tx > 0
assert not_included_tx > 0
assert seen_bigger_transaction_has_high_fee
# Mempool is full
new_transaction = fnp.NewTransaction(token_bytes(32), 10000000, uint64(1))
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_not_requested, True, incoming_queue, new_transaction)
# Cannot resubmit transaction
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert status == MempoolInclusionStatus.FAILED
assert err == Err.ALREADY_INCLUDING_TRANSACTION
# Farm one block to clear mempool
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(receiver_puzzlehash))
# No longer full
new_transaction = fnp.NewTransaction(token_bytes(32), uint64(1000000), uint64(1))
await full_node_1.new_transaction(new_transaction, fake_peer)
# Cannot resubmit transaction, but not because of ALREADY_INCLUDING
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert status == MempoolInclusionStatus.FAILED
assert err != Err.ALREADY_INCLUDING_TRANSACTION
await time_out_assert(10, new_transaction_requested, True, incoming_queue, new_transaction)
# Reorg the blockchain
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks[:-1],
guarantee_transaction_block=True,
)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
# Can now resubmit a transaction after the reorg
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert err is None
assert status == MempoolInclusionStatus.SUCCESS
@pytest.mark.asyncio
async def test_request_respond_transaction(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
peer = await connect_and_get_peer(server_1, server_2)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await full_node_2.full_node.respond_block(fnp.RespondBlock(block), peer)
# Farm another block to clear mempool
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(wallet_ph))
tx_id = token_bytes(32)
request_transaction = fnp.RequestTransaction(tx_id)
msg = await full_node_1.request_transaction(request_transaction)
assert msg is None
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
spend_bundle = wallet_a.generate_signed_transaction(
100, receiver_puzzlehash, list(blocks[-1].get_included_reward_coins())[0]
)
assert spend_bundle is not None
respond_transaction = fnp.RespondTransaction(spend_bundle)
res = await full_node_1.respond_transaction(respond_transaction, peer)
assert res is None
# Check broadcast
await time_out_assert(10, time_out_messages(incoming_queue, "new_transaction"))
request_transaction = fnp.RequestTransaction(spend_bundle.get_hash())
msg = await full_node_1.request_transaction(request_transaction)
assert msg is not None
assert msg.data == bytes(fnp.RespondTransaction(spend_bundle))
@pytest.mark.asyncio
async def test_respond_transaction_fail(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
cb_ph = wallet_a.get_new_puzzlehash()
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
peer = await connect_and_get_peer(server_1, server_2)
tx_id = token_bytes(32)
request_transaction = fnp.RequestTransaction(tx_id)
msg = await full_node_1.request_transaction(request_transaction)
assert msg is None
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
blocks_new = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=cb_ph,
pool_reward_puzzle_hash=cb_ph,
)
await asyncio.sleep(1)
while incoming_queue.qsize() > 0:
await incoming_queue.get()
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks_new[-2]), peer)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks_new[-1]), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 2))
# Invalid transaction does not propagate
spend_bundle = wallet_a.generate_signed_transaction(
100000000000000,
receiver_puzzlehash,
list(blocks_new[-1].get_included_reward_coins())[0],
)
assert spend_bundle is not None
respond_transaction = fnp.RespondTransaction(spend_bundle)
msg = await full_node_1.respond_transaction(respond_transaction, peer)
assert msg is None
await asyncio.sleep(1)
assert incoming_queue.qsize() == 0
@pytest.mark.asyncio
async def test_request_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
pool_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
)
spend_bundle = wallet_a.generate_signed_transaction(
1123,
wallet_receiver.get_new_puzzlehash(),
list(blocks[-1].get_included_reward_coins())[0],
)
blocks = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=spend_bundle
)
for block in blocks:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
# Don't have height
res = await full_node_1.request_block(fnp.RequestBlock(uint32(1248921), False))
assert res.type == ProtocolMessageTypes.reject_block.value
# Ask without transactions
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height, False))
assert res.type != ProtocolMessageTypes.reject_block.value
assert fnp.RespondBlock.from_bytes(res.data).block.transactions_generator is None
# Ask with transactions
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height, True))
assert res.type != ProtocolMessageTypes.reject_block.value
assert fnp.RespondBlock.from_bytes(res.data).block.transactions_generator is not None
# Ask for another one
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height - 1, True))
assert res.type != ProtocolMessageTypes.reject_block.value
@pytest.mark.asyncio
async def test_request_blocks(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
# create more blocks than constants.MAX_BLOCK_COUNT_PER_REQUEST (32)
blocks = bt.get_consecutive_blocks(
33,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
pool_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
)
spend_bundle = wallet_a.generate_signed_transaction(
1123,
wallet_receiver.get_new_puzzlehash(),
list(blocks[-1].get_included_reward_coins())[0],
)
blocks_t = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=spend_bundle
)
for block in blocks_t:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
peak_height = blocks_t[-1].height
# Start >= End
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(4), uint32(4), False))
assert res is not None
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 1
assert fetched_blocks[0].header_hash == blocks[4].header_hash
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(5), uint32(4), False))
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Invalid range
res = await full_node_1.request_blocks(
fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height + 5), False)
)
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Try fetching more blocks than constants.MAX_BLOCK_COUNT_PER_REQUESTS
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(0), uint32(33), False))
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Ask without transactions
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height), False))
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 6
for b in fetched_blocks:
assert b.transactions_generator is None
# Ask with transactions
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height), True))
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 6
assert fetched_blocks[-1].transactions_generator is not None
assert std_hash(fetched_blocks[-1]) == std_hash(blocks_t[-1])
@pytest.mark.asyncio
async def test_new_unfinished_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks)
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
# Don't have
res = await full_node_1.new_unfinished_block(fnp.NewUnfinishedBlock(unf.partial_hash))
assert res is not None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), peer)
# Have
res = await full_node_1.new_unfinished_block(fnp.NewUnfinishedBlock(unf.partial_hash))
assert res is None
@pytest.mark.asyncio
async def test_double_blocks_same_pospace(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
_ = await connect_and_get_peer(server_1, server_2)
ph = wallet_a.get_new_puzzlehash()
for i in range(2):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
blocks: List[FullBlock] = await full_node_1.get_all_full_blocks()
coin = list(blocks[-1].get_included_reward_coins())[0]
tx: SpendBundle = wallet_a.generate_signed_transaction(10000, wallet_receiver.get_new_puzzlehash(), coin)
blocks = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=tx
)
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf: UnfinishedBlock = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), dummy_peer)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash)
block_2 = recursive_replace(
blocks[-1], "foliage_transaction_block.timestamp", unf.foliage_transaction_block.timestamp + 1
)
new_m = block_2.foliage.foliage_transaction_block_hash
new_fbh_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_block.proof_of_space.plot_public_key)
block_2 = recursive_replace(block_2, "foliage.foliage_transaction_block_signature", new_fbh_sig)
block_2 = recursive_replace(block_2, "transactions_generator", None)
await full_node_2.full_node.respond_block(fnp.RespondBlock(block_2), dummy_peer)
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
@pytest.mark.asyncio
async def test_request_unfinished_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(10, block_list_input=blocks, seed=b"12345")
for block in blocks[:-1]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
# Don't have
res = await full_node_1.request_unfinished_block(fnp.RequestUnfinishedBlock(unf.partial_hash))
assert res is None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), peer)
# Have
res = await full_node_1.request_unfinished_block(fnp.RequestUnfinishedBlock(unf.partial_hash))
assert res is not None
@pytest.mark.asyncio
async def test_new_signage_point_or_end_of_sub_slot(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks, skip_slots=2)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-3]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
blockchain = full_node_1.full_node.blockchain
peak = blockchain.get_peak()
sp = get_signage_point(
test_constants,
blockchain,
peak,
peak.ip_sub_slot_total_iters(test_constants),
uint8(11),
[],
peak.sub_slot_iters,
)
peer = await connect_and_get_peer(server_1, server_2)
res = await full_node_1.new_signage_point_or_end_of_sub_slot(
fnp.NewSignagePointOrEndOfSubSlot(None, sp.cc_vdf.challenge, uint8(11), sp.rc_vdf.challenge), peer
)
assert res.type == ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot.value
assert fnp.RequestSignagePointOrEndOfSubSlot.from_bytes(res.data).index_from_challenge == uint8(11)
for block in blocks:
await full_node_2.full_node.respond_block(fnp.RespondBlock(block))
num_slots = 20
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=num_slots)
slots = blocks[-1].finished_sub_slots
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
for slot in slots[:-1]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots
def caught_up_slots():
return len(full_node_2.full_node.full_node_store.finished_sub_slots) >= num_slots
await time_out_assert(20, caught_up_slots)
@pytest.mark.asyncio
async def test_new_signage_point_caching(self, wallet_nodes, empty_blockchain):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks, skip_slots=2)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-3]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
blockchain = full_node_1.full_node.blockchain
# Submit the sub slot, but not the last block
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=1, force_overflow=True)
for ss in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(ss), peer)
second_blockchain = empty_blockchain
for block in blocks:
await second_blockchain.receive_block(block)
# Creates a signage point based on the last block
peak_2 = second_blockchain.get_peak()
sp: SignagePoint = get_signage_point(
test_constants,
blockchain,
peak_2,
peak_2.ip_sub_slot_total_iters(test_constants),
uint8(4),
[],
peak_2.sub_slot_iters,
)
# Submits the signage point, cannot add because don't have block
await full_node_1.respond_signage_point(
fnp.RespondSignagePoint(4, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer
)
# Should not add duplicates to cache though
await full_node_1.respond_signage_point(
fnp.RespondSignagePoint(4, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer
)
assert full_node_1.full_node.full_node_store.get_signage_point(sp.cc_vdf.output.get_hash()) is None
assert len(full_node_1.full_node.full_node_store.future_sp_cache[sp.rc_vdf.challenge]) == 1
# Add block
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]), peer)
# Now signage point should be added
assert full_node_1.full_node.full_node_store.get_signage_point(sp.cc_vdf.output.get_hash()) is not None
@pytest.mark.asyncio
async def test_slot_catch_up_genesis(self, setup_two_nodes):
nodes, _ = setup_two_nodes
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
full_node_1 = nodes[0]
full_node_2 = nodes[1]
peer = await connect_and_get_peer(server_1, server_2)
num_slots = 20
blocks = bt.get_consecutive_blocks(1, skip_slots=num_slots)
slots = blocks[-1].finished_sub_slots
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
for slot in slots[:-1]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots
def caught_up_slots():
return len(full_node_2.full_node.full_node_store.finished_sub_slots) >= num_slots
await time_out_assert(20, caught_up_slots)
@pytest.mark.skip("a timebomb causes mainnet to stop after transactions start, so this test doesn't work yet")
@pytest.mark.asyncio
async def test_mainnet_softfork(self, wallet_nodes_mainnet):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes_mainnet
blocks = await full_node_1.get_all_full_blocks()
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
conditions_dict: Dict = {ConditionOpcode.CREATE_COIN: []}
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
output = ConditionWithArgs(ConditionOpcode.CREATE_COIN, [receiver_puzzlehash, int_to_bytes(1000)])
conditions_dict[ConditionOpcode.CREATE_COIN].append(output)
spend_bundle: SpendBundle = wallet_a.generate_signed_transaction(
100,
32 * b"0",
get_future_reward_coins(blocks[1])[0],
condition_dic=conditions_dict,
)
assert spend_bundle is not None
max_size = test_constants.MAX_GENERATOR_SIZE
large_puzzle_reveal = (max_size + 1) * b"0"
under_sized = max_size * b"0"
blocks_new = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
invalid_block: FullBlock = blocks_new[-1]
invalid_program = SerializedProgram.from_bytes(large_puzzle_reveal)
invalid_block = dataclasses.replace(invalid_block, transactions_generator=invalid_program)
result, error, fork_h = await full_node_1.full_node.blockchain.receive_block(invalid_block)
assert error is not None
assert error == Err.PRE_SOFT_FORK_MAX_GENERATOR_SIZE
blocks_new = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
valid_block = blocks_new[-1]
valid_program = SerializedProgram.from_bytes(under_sized)
valid_block = dataclasses.replace(valid_block, transactions_generator=valid_program)
result, error, fork_h = await full_node_1.full_node.blockchain.receive_block(valid_block)
assert error is None
@pytest.mark.asyncio
async def test_compact_protocol(self, setup_two_nodes):
nodes, _ = setup_two_nodes
full_node_1 = nodes[0]
full_node_2 = nodes[1]
blocks = bt.get_consecutive_blocks(num_blocks=1, skip_slots=3)
block = blocks[0]
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
timelord_protocol_finished = []
cc_eos_count = 0
for sub_slot in block.finished_sub_slots:
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
cc_eos_count += 1
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
blocks_2 = bt.get_consecutive_blocks(num_blocks=2, block_list_input=blocks, skip_slots=3)
block = blocks_2[1]
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
icc_eos_count = 0
for sub_slot in block.finished_sub_slots:
if sub_slot.infused_challenge_chain is not None:
icc_eos_count += 1
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.challenge,
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
assert block.reward_chain_block.challenge_chain_sp_vdf is not None
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_sp_vdf.challenge,
block.reward_chain_block.challenge_chain_sp_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
# Note: the below numbers depend on the block cache, so might need to be updated
assert cc_eos_count == 4 and icc_eos_count == 3
for compact_proof in timelord_protocol_finished:
await full_node_1.full_node.respond_compact_proof_of_time(compact_proof)
stored_blocks = await full_node_1.get_all_full_blocks()
cc_eos_compact_count = 0
icc_eos_compact_count = 0
has_compact_cc_sp_vdf = False
has_compact_cc_ip_vdf = False
for block in stored_blocks:
for sub_slot in block.finished_sub_slots:
if sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity:
cc_eos_compact_count += 1
if (
sub_slot.proofs.infused_challenge_chain_slot_proof is not None
and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
icc_eos_compact_count += 1
if block.challenge_chain_sp_proof is not None and block.challenge_chain_sp_proof.normalized_to_identity:
has_compact_cc_sp_vdf = True
if block.challenge_chain_ip_proof.normalized_to_identity:
has_compact_cc_ip_vdf = True
# Note: the below numbers depend on the block cache, so might need to be updated
assert cc_eos_compact_count == 4
assert icc_eos_compact_count == 3
assert has_compact_cc_sp_vdf
assert has_compact_cc_ip_vdf
for height, block in enumerate(stored_blocks):
await full_node_2.full_node.respond_block(fnp.RespondBlock(block))
assert full_node_2.full_node.blockchain.get_peak().height == height
@pytest.mark.asyncio
async def test_compact_protocol_invalid_messages(self, setup_two_nodes):
nodes, _ = setup_two_nodes
full_node_1 = nodes[0]
full_node_2 = nodes[1]
blocks = bt.get_consecutive_blocks(num_blocks=1, skip_slots=3)
blocks_2 = bt.get_consecutive_blocks(num_blocks=3, block_list_input=blocks, skip_slots=3)
for block in blocks_2[:2]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
assert full_node_1.full_node.blockchain.get_peak().height == 1
# (wrong_vdf_info, wrong_vdf_proof) pair verifies, but it's not present in the blockchain at all.
block = blocks_2[2]
wrong_vdf_info, wrong_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
timelord_protocol_invalid_messages = []
full_node_protocol_invalid_messaages = []
for block in blocks_2[:2]:
for sub_slot in block.finished_sub_slots:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
assert wrong_vdf_proof != correct_vdf_proof
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_EOS_VDF,
vdf_info,
wrong_vdf_proof,
)
)
if sub_slot.infused_challenge_chain is not None:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.challenge,
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
assert wrong_vdf_proof != correct_vdf_proof
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.ICC_EOS_VDF,
vdf_info,
wrong_vdf_proof,
)
)
if block.reward_chain_block.challenge_chain_sp_vdf is not None:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_sp_vdf.challenge,
block.reward_chain_block.challenge_chain_sp_vdf.number_of_iterations,
True,
)
sp_vdf_proof = wrong_vdf_proof
if wrong_vdf_proof == correct_vdf_proof:
# This can actually happen...
sp_vdf_proof = VDFProof(uint8(0), b"1239819023890", True)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
sp_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_SP_VDF,
vdf_info,
sp_vdf_proof,
)
)
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
ip_vdf_proof = wrong_vdf_proof
if wrong_vdf_proof == correct_vdf_proof:
# This can actually happen...
ip_vdf_proof = VDFProof(uint8(0), b"1239819023890", True)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
ip_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_IP_VDF,
vdf_info,
ip_vdf_proof,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_EOS_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.ICC_EOS_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_SP_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_IP_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
peer = await connect_and_get_peer(server_1, server_2)
for invalid_compact_proof in timelord_protocol_invalid_messages:
await full_node_1.full_node.respond_compact_proof_of_time(invalid_compact_proof)
for invalid_compact_proof in full_node_protocol_invalid_messaages:
await full_node_1.full_node.respond_compact_vdf(invalid_compact_proof, peer)
stored_blocks = await full_node_1.get_all_full_blocks()
for block in stored_blocks:
for sub_slot in block.finished_sub_slots:
assert not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
if sub_slot.proofs.infused_challenge_chain_slot_proof is not None:
assert not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
if block.challenge_chain_sp_proof is not None:
assert not block.challenge_chain_sp_proof.normalized_to_identity
assert not block.challenge_chain_ip_proof.normalized_to_identity
| 44.829422 | 120 | 0.667582 |
import asyncio
import dataclasses
import logging
import random
import time
from secrets import token_bytes
from typing import Dict, Optional, List
import pytest
from taco.consensus.pot_iterations import is_overflow_block
from taco.full_node.bundle_tools import detect_potential_template_generator
from taco.full_node.full_node_api import FullNodeAPI
from taco.full_node.signage_point import SignagePoint
from taco.protocols import full_node_protocol as fnp, full_node_protocol
from taco.protocols import timelord_protocol
from taco.protocols.full_node_protocol import RespondTransaction
from taco.protocols.protocol_message_types import ProtocolMessageTypes
from taco.server.address_manager import AddressManager
from taco.server.outbound_message import Message
from taco.simulator.simulator_protocol import FarmNewBlockProtocol
from taco.types.blockchain_format.classgroup import ClassgroupElement
from taco.types.blockchain_format.program import SerializedProgram
from taco.types.blockchain_format.vdf import CompressibleVDFField, VDFProof
from taco.types.condition_opcodes import ConditionOpcode
from taco.types.condition_with_args import ConditionWithArgs
from taco.types.full_block import FullBlock
from taco.types.mempool_inclusion_status import MempoolInclusionStatus
from taco.types.peer_info import PeerInfo, TimestampedPeerInfo
from taco.types.spend_bundle import SpendBundle
from taco.types.unfinished_block import UnfinishedBlock
from tests.block_tools import get_signage_point
from taco.util.clvm import int_to_bytes
from taco.util.errors import Err
from taco.util.hash import std_hash
from taco.util.ints import uint8, uint16, uint32, uint64
from taco.util.recursive_replace import recursive_replace
from taco.util.vdf_prover import get_vdf_info_and_proof
from tests.wallet_tools import WalletTool
from tests.core.fixtures import empty_blockchain
from taco.wallet.cc_wallet.cc_wallet import CCWallet
from taco.wallet.transaction_record import TransactionRecord
from tests.connection_utils import add_dummy_connection, connect_and_get_peer
from tests.core.full_node.test_coin_store import get_future_reward_coins
from tests.core.full_node.test_mempool_performance import wallet_height_at_least
from tests.core.make_block_generator import make_spend_bundle
from tests.core.node_height import node_height_at_least
from tests.core.fixtures import empty_blockchain
from tests.setup_nodes import bt, self_hostname, setup_simulators_and_wallets, test_constants
from tests.time_out_assert import time_out_assert, time_out_assert_custom_interval, time_out_messages
log = logging.getLogger(__name__)
async def new_transaction_not_requested(incoming, new_spend):
await asyncio.sleep(3)
while not incoming.empty():
response, peer = await incoming.get()
if (
response is not None
and isinstance(response, Message)
and response.type == ProtocolMessageTypes.request_transaction.value
):
request = full_node_protocol.RequestTransaction.from_bytes(response.data)
if request.transaction_id == new_spend.transaction_id:
return False
return True
async def new_transaction_requested(incoming, new_spend):
await asyncio.sleep(1)
while not incoming.empty():
response, peer = await incoming.get()
if (
response is not None
and isinstance(response, Message)
and response.type == ProtocolMessageTypes.request_transaction.value
):
request = full_node_protocol.RequestTransaction.from_bytes(response.data)
if request.transaction_id == new_spend.transaction_id:
return True
return False
async def get_block_path(full_node: FullNodeAPI):
blocks_list = [await full_node.full_node.blockchain.get_full_peak()]
assert blocks_list[0] is not None
while blocks_list[0].height != 0:
b = await full_node.full_node.block_store.get_full_block(blocks_list[0].prev_header_hash)
assert b is not None
blocks_list.insert(0, b)
return blocks_list
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
@pytest.fixture(scope="module")
async def wallet_nodes():
async_gen = setup_simulators_and_wallets(2, 1, {"MEMPOOL_BLOCK_BUFFER": 2, "MAX_BLOCK_COST_CLVM": 400000000})
nodes, wallets = await async_gen.__anext__()
full_node_1 = nodes[0]
full_node_2 = nodes[1]
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
wallet_a = bt.get_pool_wallet_tool()
wallet_receiver = WalletTool(full_node_1.full_node.constants)
yield full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver
async for _ in async_gen:
yield _
@pytest.fixture(scope="function")
async def setup_four_nodes():
async for _ in setup_simulators_and_wallets(5, 0, {}, starting_port=51000):
yield _
@pytest.fixture(scope="function")
async def setup_two_nodes():
async for _ in setup_simulators_and_wallets(2, 0, {}, starting_port=51100):
yield _
@pytest.fixture(scope="function")
async def setup_two_nodes_and_wallet():
async for _ in setup_simulators_and_wallets(2, 1, {}, starting_port=51200):
yield _
@pytest.fixture(scope="function")
async def wallet_nodes_mainnet():
async_gen = setup_simulators_and_wallets(2, 1, {"NETWORK_TYPE": 0}, starting_port=40000)
nodes, wallets = await async_gen.__anext__()
full_node_1 = nodes[0]
full_node_2 = nodes[1]
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
wallet_a = bt.get_pool_wallet_tool()
wallet_receiver = WalletTool(full_node_1.full_node.constants)
yield full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver
async for _ in async_gen:
yield _
class TestFullNodeBlockCompression:
@pytest.mark.asyncio
async def do_test_block_compression(self, setup_two_nodes_and_wallet, empty_blockchain, tx_size, test_reorgs):
nodes, wallets = setup_two_nodes_and_wallet
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
server_3 = wallets[0][1]
full_node_1 = nodes[0]
full_node_2 = nodes[1]
wallet_node_1 = wallets[0][0]
wallet = wallet_node_1.wallet_state_manager.main_wallet
_ = await connect_and_get_peer(server_1, server_2)
_ = await connect_and_get_peer(server_1, server_3)
ph = await wallet.get_new_puzzlehash()
for i in range(4):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 4)
await time_out_assert(10, node_height_at_least, True, full_node_1, 4)
await time_out_assert(10, node_height_at_least, True, full_node_2, 4)
tr: TransactionRecord = await wallet.generate_signed_transaction(
tx_size,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 5)
await time_out_assert(10, node_height_at_least, True, full_node_2, 5)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 5)
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(5), program) is not None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0
tr: TransactionRecord = await wallet.generate_signed_transaction(
20000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 6)
await time_out_assert(10, node_height_at_least, True, full_node_2, 6)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 6)
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(6), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 8)
await time_out_assert(10, node_height_at_least, True, full_node_2, 8)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 8)
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
40000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
50000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
3000000000000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 9)
await time_out_assert(10, node_height_at_least, True, full_node_2, 9)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 9)
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(9), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
cc_wallet: CCWallet = await CCWallet.create_new_cc(wallet_node_1.wallet_state_manager, wallet, uint64(100))
tx_queue: List[TransactionRecord] = await wallet_node_1.wallet_state_manager.tx_store.get_not_sent()
tr = tx_queue[0]
await time_out_assert(
10,
full_node_1.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.spend_bundle.name(),
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 10)
await time_out_assert(10, node_height_at_least, True, full_node_2, 10)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 10)
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(10), program) is None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) > 0
tr: TransactionRecord = await cc_wallet.generate_signed_transaction([uint64(60)], [ph])
await wallet.wallet_state_manager.add_pending_transaction(tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
tr: TransactionRecord = await wallet.generate_signed_transaction(
30000,
ph,
)
await wallet.push_transaction(tx=tr)
await time_out_assert(
10,
full_node_2.full_node.mempool_manager.get_spendbundle,
tr.spend_bundle,
tr.name,
)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
await time_out_assert(10, node_height_at_least, True, full_node_1, 11)
await time_out_assert(10, node_height_at_least, True, full_node_2, 11)
await time_out_assert(10, wallet_height_at_least, True, wallet_node_1, 11)
program: Optional[SerializedProgram] = (await full_node_1.get_all_full_blocks())[-1].transactions_generator
assert program is not None
assert detect_potential_template_generator(uint32(11), program) is not None
assert len((await full_node_1.get_all_full_blocks())[-1].transactions_generator_ref_list) == 0
height = full_node_1.full_node.blockchain.get_peak().height
blockchain = empty_blockchain
all_blocks: List[FullBlock] = await full_node_1.get_all_full_blocks()
assert height == len(all_blocks) - 1
assert full_node_1.full_node.full_node_store.previous_generator is not None
if test_reorgs:
reog_blocks = bt.get_consecutive_blocks(14)
for r in range(0, len(reog_blocks), 3):
for reorg_block in reog_blocks[:r]:
assert (await blockchain.receive_block(reorg_block))[1] is None
for i in range(1, height):
for batch_size in range(1, height):
results = await blockchain.pre_validate_blocks_multiprocessing(all_blocks[:i], {}, batch_size)
assert results is not None
for result in results:
assert result.error is None
for r in range(0, len(all_blocks), 3):
for block in all_blocks[:r]:
assert (await blockchain.receive_block(block))[1] is None
for i in range(1, height):
for batch_size in range(1, height):
results = await blockchain.pre_validate_blocks_multiprocessing(all_blocks[:i], {}, batch_size)
assert results is not None
for result in results:
assert result.error is None
for block in reog_blocks:
await full_node_1.full_node.respond_block(full_node_protocol.RespondBlock(block))
assert full_node_1.full_node.full_node_store.previous_generator is None
@pytest.mark.asyncio
async def test_block_compression(self, setup_two_nodes_and_wallet, empty_blockchain):
await self.do_test_block_compression(setup_two_nodes_and_wallet, empty_blockchain, 10000, True)
@pytest.mark.asyncio
async def test_block_compression_2(self, setup_two_nodes_and_wallet, empty_blockchain):
await self.do_test_block_compression(setup_two_nodes_and_wallet, empty_blockchain, 3000000000000, False)
class TestFullNodeProtocol:
@pytest.mark.asyncio
async def test_spendbundle_serialization(self):
sb: SpendBundle = make_spend_bundle(1)
protocol_message = RespondTransaction(sb)
assert bytes(sb) == bytes(protocol_message)
@pytest.mark.asyncio
async def test_inbound_connection_limit(self, setup_four_nodes):
nodes, _ = setup_four_nodes
server_1 = nodes[0].full_node.server
server_1.config["target_peer_count"] = 2
server_1.config["target_outbound_peer_count"] = 0
for i in range(1, 4):
full_node_i = nodes[i]
server_i = full_node_i.full_node.server
await server_i.start_client(PeerInfo(self_hostname, uint16(server_1._port)))
assert len(server_1.get_full_node_connections()) == 2
@pytest.mark.asyncio
async def test_request_peers(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
full_node_2.full_node.full_node_peers.address_manager.make_private_subnets_valid()
await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)))
async def have_msgs():
await full_node_2.full_node.full_node_peers.address_manager.add_to_new_table(
[TimestampedPeerInfo("127.0.0.1", uint16(1000), uint64(int(time.time())) - 1000)],
None,
)
msg_bytes = await full_node_2.full_node.full_node_peers.request_peers(PeerInfo("[::1]", server_2._port))
msg = fnp.RespondPeers.from_bytes(msg_bytes.data)
if msg is not None and not (len(msg.peer_list) == 1):
return False
peer = msg.peer_list[0]
return (peer.host == self_hostname or peer.host == "127.0.0.1") and peer.port == 1000
await time_out_assert_custom_interval(10, 1, have_msgs, True)
full_node_1.full_node.full_node_peers.address_manager = AddressManager()
@pytest.mark.asyncio
async def test_basic_chain(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, _ = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(1)
for block in blocks[:1]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 1))
assert full_node_1.full_node.blockchain.get_peak().height == 0
for block in bt.get_consecutive_blocks(30):
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
assert full_node_1.full_node.blockchain.get_peak().height == 29
@pytest.mark.asyncio
async def test_respond_end_of_sub_slot(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=6)
for slot in blocks[-1].finished_sub_slots[:-2]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
num_sub_slots_added = len(blocks[-1].finished_sub_slots[:-2])
await time_out_assert(
10,
time_out_messages(
incoming_queue,
"new_signage_point_or_end_of_sub_slot",
num_sub_slots_added,
),
)
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(blocks[-1].finished_sub_slots[-3]), peer)
await asyncio.sleep(2)
assert incoming_queue.qsize() == 0
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(blocks[-1].finished_sub_slots[-1]), peer)
await asyncio.sleep(2)
assert incoming_queue.qsize() == 0
blocks = bt.get_consecutive_blocks(4, block_list_input=blocks)
for block in blocks[-5:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 5))
blocks = bt.get_consecutive_blocks(1, skip_slots=2, block_list_input=blocks)
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
num_sub_slots_added = len(blocks[-1].finished_sub_slots)
await time_out_assert(
10,
time_out_messages(
incoming_queue,
"new_signage_point_or_end_of_sub_slot",
num_sub_slots_added,
),
)
@pytest.mark.asyncio
async def test_respond_unfinished(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=6)
block = blocks[-1]
if is_overflow_block(test_constants, block.reward_chain_block.signage_point_index):
finished_ss = block.finished_sub_slots[:-1]
else:
finished_ss = block.finished_sub_slots
unf = UnfinishedBlock(
finished_ss,
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
# Add empty slots successful
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# Do the same thing but with non-genesis
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=3)
block = blocks[-1]
if is_overflow_block(test_constants, block.reward_chain_block.signage_point_index):
finished_ss = block.finished_sub_slots[:-1]
else:
finished_ss = block.finished_sub_slots
unf = UnfinishedBlock(
finished_ss,
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# Do the same thing one more time, with overflow
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=3, force_overflow=True)
block = blocks[-1]
unf = UnfinishedBlock(
block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
for slot in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
# This next section tests making unfinished block with transactions, and then submitting the finished block
ph = wallet_a.get_new_puzzlehash()
ph_receiver = wallet_receiver.get_new_puzzlehash()
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=ph,
pool_reward_puzzle_hash=ph,
)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
coin_to_spend = list(blocks[-1].get_included_reward_coins())[0]
spend_bundle = wallet_a.generate_signed_transaction(coin_to_spend.amount, ph_receiver, coin_to_spend)
blocks = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
force_overflow=True,
seed=b"random seed",
)
block = blocks[-1]
unf = UnfinishedBlock(
block.finished_sub_slots[:-1], # Since it's overflow
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), None)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash) is not None
result = full_node_1.full_node.full_node_store.get_unfinished_block_result(unf.partial_hash)
assert result is not None
assert result.npc_result is not None and result.npc_result.clvm_cost > 0
assert not full_node_1.full_node.blockchain.contains_block(block.header_hash)
assert block.transactions_generator is not None
block_no_transactions = dataclasses.replace(block, transactions_generator=None)
assert block_no_transactions.transactions_generator is None
await full_node_1.full_node.respond_block(fnp.RespondBlock(block_no_transactions))
assert full_node_1.full_node.blockchain.contains_block(block.header_hash)
@pytest.mark.asyncio
async def test_new_peak(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
dummy_peer = server_1.all_connections[dummy_node_id]
expected_requests = 0
if await full_node_1.full_node.synced():
expected_requests = 1
await time_out_assert(10, time_out_messages(incoming_queue, "request_mempool_transactions", expected_requests))
peer = await connect_and_get_peer(server_1, server_2)
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks)
blocks_reorg = bt.get_consecutive_blocks(3, block_list_input=blocks[:-1], seed=b"214")
for block in blocks[-3:]:
new_peak = fnp.NewPeak(
block.header_hash,
block.height,
block.weight,
uint32(0),
block.reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 0))
new_peak = fnp.NewPeak(
blocks_reorg[-2].header_hash,
blocks_reorg[-2].height,
blocks_reorg[-2].weight,
uint32(0),
blocks_reorg[-2].reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 0))
new_peak = fnp.NewPeak(
blocks_reorg[-1].header_hash,
blocks_reorg[-1].height,
blocks_reorg[-1].weight,
uint32(0),
blocks_reorg[-1].reward_chain_block.get_unfinished().get_hash(),
)
asyncio.create_task(full_node_1.new_peak(new_peak, dummy_peer))
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
@pytest.mark.asyncio
async def test_new_transaction_and_mempool(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = bt.get_consecutive_blocks(
10,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
for block in blocks:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
start_height = (
full_node_1.full_node.blockchain.get_peak().height
if full_node_1.full_node.blockchain.get_peak() is not None
else -1
)
peer = await connect_and_get_peer(server_1, server_2)
incoming_queue, node_id = await add_dummy_connection(server_1, 12312)
fake_peer = server_1.all_connections[node_id]
puzzle_hashes = []
block_buffer_count = full_node_1.full_node.constants.MEMPOOL_BLOCK_BUFFER
for i in range(5):
conditions_dict: Dict = {ConditionOpcode.CREATE_COIN: []}
for _ in range(100):
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
puzzle_hashes.append(receiver_puzzlehash)
output = ConditionWithArgs(ConditionOpcode.CREATE_COIN, [receiver_puzzlehash, int_to_bytes(100000000)])
conditions_dict[ConditionOpcode.CREATE_COIN].append(output)
spend_bundle = wallet_a.generate_signed_transaction(
100,
puzzle_hashes[0],
get_future_reward_coins(blocks[1 + i])[0],
condition_dic=conditions_dict,
)
assert spend_bundle is not None
cost_result = await full_node_1.full_node.mempool_manager.pre_validate_spendbundle(spend_bundle)
log.info(f"Cost result: {cost_result.clvm_cost}")
new_transaction = fnp.NewTransaction(spend_bundle.get_hash(), uint64(100), uint64(100))
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_requested, True, incoming_queue, new_transaction)
respond_transaction_2 = fnp.RespondTransaction(spend_bundle)
await full_node_1.respond_transaction(respond_transaction_2, peer)
blocks = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]), peer)
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_not_requested, True, incoming_queue, new_transaction)
await time_out_assert(10, node_height_at_least, True, full_node_1, start_height + 5)
spend_bundles = []
included_tx = 0
not_included_tx = 0
seen_bigger_transaction_has_high_fee = False
successful_bundle: Optional[SpendBundle] = None
for puzzle_hash in puzzle_hashes[1:]:
coin_record = (await full_node_1.full_node.coin_store.get_coin_records_by_puzzle_hash(True, puzzle_hash))[0]
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
if puzzle_hash == puzzle_hashes[-1]:
force_high_fee = True
fee = 100000000
else:
force_high_fee = False
fee = random.randint(1, 100000000)
spend_bundle = wallet_receiver.generate_signed_transaction(
uint64(500), receiver_puzzlehash, coin_record.coin, fee=fee
)
respond_transaction = fnp.RespondTransaction(spend_bundle)
await full_node_1.respond_transaction(respond_transaction, peer)
request = fnp.RequestTransaction(spend_bundle.get_hash())
req = await full_node_1.request_transaction(request)
fee_rate_for_small = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(10)
fee_rate_for_med = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(5000000)
fee_rate_for_large = full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(50000000)
log.info(f"Min fee rate (10): {fee_rate_for_small}")
log.info(f"Min fee rate (5000000): {fee_rate_for_med}")
log.info(f"Min fee rate (50000000): {fee_rate_for_large}")
if fee_rate_for_large > fee_rate_for_med:
seen_bigger_transaction_has_high_fee = True
if req is not None and req.data == bytes(fnp.RespondTransaction(spend_bundle)):
included_tx += 1
spend_bundles.append(spend_bundle)
assert not full_node_1.full_node.mempool_manager.mempool.at_full_capacity(0)
assert full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(0) == 0
if force_high_fee:
successful_bundle = spend_bundle
else:
assert full_node_1.full_node.mempool_manager.mempool.at_full_capacity(10000000)
assert full_node_1.full_node.mempool_manager.mempool.get_min_fee_rate(10000000) > 0
assert not force_high_fee
not_included_tx += 1
log.info(f"Included: {included_tx}, not included: {not_included_tx}")
assert included_tx > 0
assert not_included_tx > 0
assert seen_bigger_transaction_has_high_fee
new_transaction = fnp.NewTransaction(token_bytes(32), 10000000, uint64(1))
await full_node_1.new_transaction(new_transaction, fake_peer)
await time_out_assert(10, new_transaction_not_requested, True, incoming_queue, new_transaction)
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert status == MempoolInclusionStatus.FAILED
assert err == Err.ALREADY_INCLUDING_TRANSACTION
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(receiver_puzzlehash))
new_transaction = fnp.NewTransaction(token_bytes(32), uint64(1000000), uint64(1))
await full_node_1.new_transaction(new_transaction, fake_peer)
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert status == MempoolInclusionStatus.FAILED
assert err != Err.ALREADY_INCLUDING_TRANSACTION
await time_out_assert(10, new_transaction_requested, True, incoming_queue, new_transaction)
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks[:-1],
guarantee_transaction_block=True,
)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
status, err = await full_node_1.full_node.respond_transaction(
successful_bundle, successful_bundle.name(), peer, test=True
)
assert err is None
assert status == MempoolInclusionStatus.SUCCESS
@pytest.mark.asyncio
async def test_request_respond_transaction(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
peer = await connect_and_get_peer(server_1, server_2)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block), peer)
await full_node_2.full_node.respond_block(fnp.RespondBlock(block), peer)
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(wallet_ph))
tx_id = token_bytes(32)
request_transaction = fnp.RequestTransaction(tx_id)
msg = await full_node_1.request_transaction(request_transaction)
assert msg is None
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
spend_bundle = wallet_a.generate_signed_transaction(
100, receiver_puzzlehash, list(blocks[-1].get_included_reward_coins())[0]
)
assert spend_bundle is not None
respond_transaction = fnp.RespondTransaction(spend_bundle)
res = await full_node_1.respond_transaction(respond_transaction, peer)
assert res is None
await time_out_assert(10, time_out_messages(incoming_queue, "new_transaction"))
request_transaction = fnp.RequestTransaction(spend_bundle.get_hash())
msg = await full_node_1.request_transaction(request_transaction)
assert msg is not None
assert msg.data == bytes(fnp.RespondTransaction(spend_bundle))
@pytest.mark.asyncio
async def test_respond_transaction_fail(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
cb_ph = wallet_a.get_new_puzzlehash()
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12312)
peer = await connect_and_get_peer(server_1, server_2)
tx_id = token_bytes(32)
request_transaction = fnp.RequestTransaction(tx_id)
msg = await full_node_1.request_transaction(request_transaction)
assert msg is None
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
blocks_new = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=cb_ph,
pool_reward_puzzle_hash=cb_ph,
)
await asyncio.sleep(1)
while incoming_queue.qsize() > 0:
await incoming_queue.get()
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks_new[-2]), peer)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks_new[-1]), peer)
await time_out_assert(10, time_out_messages(incoming_queue, "new_peak", 2))
spend_bundle = wallet_a.generate_signed_transaction(
100000000000000,
receiver_puzzlehash,
list(blocks_new[-1].get_included_reward_coins())[0],
)
assert spend_bundle is not None
respond_transaction = fnp.RespondTransaction(spend_bundle)
msg = await full_node_1.respond_transaction(respond_transaction, peer)
assert msg is None
await asyncio.sleep(1)
assert incoming_queue.qsize() == 0
@pytest.mark.asyncio
async def test_request_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(
2,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
pool_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
)
spend_bundle = wallet_a.generate_signed_transaction(
1123,
wallet_receiver.get_new_puzzlehash(),
list(blocks[-1].get_included_reward_coins())[0],
)
blocks = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=spend_bundle
)
for block in blocks:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
res = await full_node_1.request_block(fnp.RequestBlock(uint32(1248921), False))
assert res.type == ProtocolMessageTypes.reject_block.value
# Ask without transactions
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height, False))
assert res.type != ProtocolMessageTypes.reject_block.value
assert fnp.RespondBlock.from_bytes(res.data).block.transactions_generator is None
# Ask with transactions
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height, True))
assert res.type != ProtocolMessageTypes.reject_block.value
assert fnp.RespondBlock.from_bytes(res.data).block.transactions_generator is not None
# Ask for another one
res = await full_node_1.request_block(fnp.RequestBlock(blocks[-1].height - 1, True))
assert res.type != ProtocolMessageTypes.reject_block.value
@pytest.mark.asyncio
async def test_request_blocks(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
# create more blocks than constants.MAX_BLOCK_COUNT_PER_REQUEST (32)
blocks = bt.get_consecutive_blocks(
33,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
pool_reward_puzzle_hash=wallet_a.get_new_puzzlehash(),
)
spend_bundle = wallet_a.generate_signed_transaction(
1123,
wallet_receiver.get_new_puzzlehash(),
list(blocks[-1].get_included_reward_coins())[0],
)
blocks_t = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=spend_bundle
)
for block in blocks_t:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
peak_height = blocks_t[-1].height
# Start >= End
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(4), uint32(4), False))
assert res is not None
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 1
assert fetched_blocks[0].header_hash == blocks[4].header_hash
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(5), uint32(4), False))
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Invalid range
res = await full_node_1.request_blocks(
fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height + 5), False)
)
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Try fetching more blocks than constants.MAX_BLOCK_COUNT_PER_REQUESTS
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(0), uint32(33), False))
assert res.type == ProtocolMessageTypes.reject_blocks.value
# Ask without transactions
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height), False))
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 6
for b in fetched_blocks:
assert b.transactions_generator is None
# Ask with transactions
res = await full_node_1.request_blocks(fnp.RequestBlocks(uint32(peak_height - 5), uint32(peak_height), True))
fetched_blocks = fnp.RespondBlocks.from_bytes(res.data).blocks
assert len(fetched_blocks) == 6
assert fetched_blocks[-1].transactions_generator is not None
assert std_hash(fetched_blocks[-1]) == std_hash(blocks_t[-1])
@pytest.mark.asyncio
async def test_new_unfinished_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks)
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
# Don't have
res = await full_node_1.new_unfinished_block(fnp.NewUnfinishedBlock(unf.partial_hash))
assert res is not None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), peer)
res = await full_node_1.new_unfinished_block(fnp.NewUnfinishedBlock(unf.partial_hash))
assert res is None
@pytest.mark.asyncio
async def test_double_blocks_same_pospace(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
_ = await connect_and_get_peer(server_1, server_2)
ph = wallet_a.get_new_puzzlehash()
for i in range(2):
await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph))
blocks: List[FullBlock] = await full_node_1.get_all_full_blocks()
coin = list(blocks[-1].get_included_reward_coins())[0]
tx: SpendBundle = wallet_a.generate_signed_transaction(10000, wallet_receiver.get_new_puzzlehash(), coin)
blocks = bt.get_consecutive_blocks(
1, block_list_input=blocks, guarantee_transaction_block=True, transaction_data=tx
)
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf: UnfinishedBlock = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), dummy_peer)
assert full_node_1.full_node.full_node_store.get_unfinished_block(unf.partial_hash)
block_2 = recursive_replace(
blocks[-1], "foliage_transaction_block.timestamp", unf.foliage_transaction_block.timestamp + 1
)
new_m = block_2.foliage.foliage_transaction_block_hash
new_fbh_sig = bt.get_plot_signature(new_m, blocks[-1].reward_chain_block.proof_of_space.plot_public_key)
block_2 = recursive_replace(block_2, "foliage.foliage_transaction_block_signature", new_fbh_sig)
block_2 = recursive_replace(block_2, "transactions_generator", None)
await full_node_2.full_node.respond_block(fnp.RespondBlock(block_2), dummy_peer)
await time_out_assert(10, time_out_messages(incoming_queue, "request_block", 1))
@pytest.mark.asyncio
async def test_request_unfinished_block(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(10, block_list_input=blocks, seed=b"12345")
for block in blocks[:-1]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
block: FullBlock = blocks[-1]
overflow = is_overflow_block(test_constants, block.reward_chain_block.signage_point_index)
unf = UnfinishedBlock(
block.finished_sub_slots[:] if not overflow else block.finished_sub_slots[:-1],
block.reward_chain_block.get_unfinished(),
block.challenge_chain_sp_proof,
block.reward_chain_sp_proof,
block.foliage,
block.foliage_transaction_block,
block.transactions_info,
block.transactions_generator,
[],
)
res = await full_node_1.request_unfinished_block(fnp.RequestUnfinishedBlock(unf.partial_hash))
assert res is None
await full_node_1.full_node.respond_unfinished_block(fnp.RespondUnfinishedBlock(unf), peer)
# Have
res = await full_node_1.request_unfinished_block(fnp.RequestUnfinishedBlock(unf.partial_hash))
assert res is not None
@pytest.mark.asyncio
async def test_new_signage_point_or_end_of_sub_slot(self, wallet_nodes):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks, skip_slots=2)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-3]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
blockchain = full_node_1.full_node.blockchain
peak = blockchain.get_peak()
sp = get_signage_point(
test_constants,
blockchain,
peak,
peak.ip_sub_slot_total_iters(test_constants),
uint8(11),
[],
peak.sub_slot_iters,
)
peer = await connect_and_get_peer(server_1, server_2)
res = await full_node_1.new_signage_point_or_end_of_sub_slot(
fnp.NewSignagePointOrEndOfSubSlot(None, sp.cc_vdf.challenge, uint8(11), sp.rc_vdf.challenge), peer
)
assert res.type == ProtocolMessageTypes.request_signage_point_or_end_of_sub_slot.value
assert fnp.RequestSignagePointOrEndOfSubSlot.from_bytes(res.data).index_from_challenge == uint8(11)
for block in blocks:
await full_node_2.full_node.respond_block(fnp.RespondBlock(block))
num_slots = 20
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=num_slots)
slots = blocks[-1].finished_sub_slots
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
for slot in slots[:-1]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots
def caught_up_slots():
return len(full_node_2.full_node.full_node_store.finished_sub_slots) >= num_slots
await time_out_assert(20, caught_up_slots)
@pytest.mark.asyncio
async def test_new_signage_point_caching(self, wallet_nodes, empty_blockchain):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes
blocks = await full_node_1.get_all_full_blocks()
peer = await connect_and_get_peer(server_1, server_2)
blocks = bt.get_consecutive_blocks(3, block_list_input=blocks, skip_slots=2)
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-3]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-2]))
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]))
blockchain = full_node_1.full_node.blockchain
# Submit the sub slot, but not the last block
blocks = bt.get_consecutive_blocks(1, block_list_input=blocks, skip_slots=1, force_overflow=True)
for ss in blocks[-1].finished_sub_slots:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(ss), peer)
second_blockchain = empty_blockchain
for block in blocks:
await second_blockchain.receive_block(block)
# Creates a signage point based on the last block
peak_2 = second_blockchain.get_peak()
sp: SignagePoint = get_signage_point(
test_constants,
blockchain,
peak_2,
peak_2.ip_sub_slot_total_iters(test_constants),
uint8(4),
[],
peak_2.sub_slot_iters,
)
# Submits the signage point, cannot add because don't have block
await full_node_1.respond_signage_point(
fnp.RespondSignagePoint(4, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer
)
await full_node_1.respond_signage_point(
fnp.RespondSignagePoint(4, sp.cc_vdf, sp.cc_proof, sp.rc_vdf, sp.rc_proof), peer
)
assert full_node_1.full_node.full_node_store.get_signage_point(sp.cc_vdf.output.get_hash()) is None
assert len(full_node_1.full_node.full_node_store.future_sp_cache[sp.rc_vdf.challenge]) == 1
await full_node_1.full_node.respond_block(fnp.RespondBlock(blocks[-1]), peer)
assert full_node_1.full_node.full_node_store.get_signage_point(sp.cc_vdf.output.get_hash()) is not None
@pytest.mark.asyncio
async def test_slot_catch_up_genesis(self, setup_two_nodes):
nodes, _ = setup_two_nodes
server_1 = nodes[0].full_node.server
server_2 = nodes[1].full_node.server
full_node_1 = nodes[0]
full_node_2 = nodes[1]
peer = await connect_and_get_peer(server_1, server_2)
num_slots = 20
blocks = bt.get_consecutive_blocks(1, skip_slots=num_slots)
slots = blocks[-1].finished_sub_slots
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
assert len(full_node_2.full_node.full_node_store.finished_sub_slots) <= 2
for slot in slots[:-1]:
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slot), peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots - 1
incoming_queue, dummy_node_id = await add_dummy_connection(server_1, 12315)
dummy_peer = server_1.all_connections[dummy_node_id]
await full_node_1.respond_end_of_sub_slot(fnp.RespondEndOfSubSlot(slots[-1]), dummy_peer)
assert len(full_node_1.full_node.full_node_store.finished_sub_slots) >= num_slots
def caught_up_slots():
return len(full_node_2.full_node.full_node_store.finished_sub_slots) >= num_slots
await time_out_assert(20, caught_up_slots)
@pytest.mark.skip("a timebomb causes mainnet to stop after transactions start, so this test doesn't work yet")
@pytest.mark.asyncio
async def test_mainnet_softfork(self, wallet_nodes_mainnet):
full_node_1, full_node_2, server_1, server_2, wallet_a, wallet_receiver = wallet_nodes_mainnet
blocks = await full_node_1.get_all_full_blocks()
wallet_ph = wallet_a.get_new_puzzlehash()
blocks = bt.get_consecutive_blocks(
3,
block_list_input=blocks,
guarantee_transaction_block=True,
farmer_reward_puzzle_hash=wallet_ph,
pool_reward_puzzle_hash=wallet_ph,
)
for block in blocks[-3:]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
conditions_dict: Dict = {ConditionOpcode.CREATE_COIN: []}
receiver_puzzlehash = wallet_receiver.get_new_puzzlehash()
output = ConditionWithArgs(ConditionOpcode.CREATE_COIN, [receiver_puzzlehash, int_to_bytes(1000)])
conditions_dict[ConditionOpcode.CREATE_COIN].append(output)
spend_bundle: SpendBundle = wallet_a.generate_signed_transaction(
100,
32 * b"0",
get_future_reward_coins(blocks[1])[0],
condition_dic=conditions_dict,
)
assert spend_bundle is not None
max_size = test_constants.MAX_GENERATOR_SIZE
large_puzzle_reveal = (max_size + 1) * b"0"
under_sized = max_size * b"0"
blocks_new = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
invalid_block: FullBlock = blocks_new[-1]
invalid_program = SerializedProgram.from_bytes(large_puzzle_reveal)
invalid_block = dataclasses.replace(invalid_block, transactions_generator=invalid_program)
result, error, fork_h = await full_node_1.full_node.blockchain.receive_block(invalid_block)
assert error is not None
assert error == Err.PRE_SOFT_FORK_MAX_GENERATOR_SIZE
blocks_new = bt.get_consecutive_blocks(
1,
block_list_input=blocks,
guarantee_transaction_block=True,
transaction_data=spend_bundle,
)
valid_block = blocks_new[-1]
valid_program = SerializedProgram.from_bytes(under_sized)
valid_block = dataclasses.replace(valid_block, transactions_generator=valid_program)
result, error, fork_h = await full_node_1.full_node.blockchain.receive_block(valid_block)
assert error is None
@pytest.mark.asyncio
async def test_compact_protocol(self, setup_two_nodes):
nodes, _ = setup_two_nodes
full_node_1 = nodes[0]
full_node_2 = nodes[1]
blocks = bt.get_consecutive_blocks(num_blocks=1, skip_slots=3)
block = blocks[0]
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
timelord_protocol_finished = []
cc_eos_count = 0
for sub_slot in block.finished_sub_slots:
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
cc_eos_count += 1
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
blocks_2 = bt.get_consecutive_blocks(num_blocks=2, block_list_input=blocks, skip_slots=3)
block = blocks_2[1]
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
icc_eos_count = 0
for sub_slot in block.finished_sub_slots:
if sub_slot.infused_challenge_chain is not None:
icc_eos_count += 1
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.challenge,
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
assert block.reward_chain_block.challenge_chain_sp_vdf is not None
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_sp_vdf.challenge,
block.reward_chain_block.challenge_chain_sp_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
vdf_info, vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
timelord_protocol_finished.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
# Note: the below numbers depend on the block cache, so might need to be updated
assert cc_eos_count == 4 and icc_eos_count == 3
for compact_proof in timelord_protocol_finished:
await full_node_1.full_node.respond_compact_proof_of_time(compact_proof)
stored_blocks = await full_node_1.get_all_full_blocks()
cc_eos_compact_count = 0
icc_eos_compact_count = 0
has_compact_cc_sp_vdf = False
has_compact_cc_ip_vdf = False
for block in stored_blocks:
for sub_slot in block.finished_sub_slots:
if sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity:
cc_eos_compact_count += 1
if (
sub_slot.proofs.infused_challenge_chain_slot_proof is not None
and sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
):
icc_eos_compact_count += 1
if block.challenge_chain_sp_proof is not None and block.challenge_chain_sp_proof.normalized_to_identity:
has_compact_cc_sp_vdf = True
if block.challenge_chain_ip_proof.normalized_to_identity:
has_compact_cc_ip_vdf = True
# Note: the below numbers depend on the block cache, so might need to be updated
assert cc_eos_compact_count == 4
assert icc_eos_compact_count == 3
assert has_compact_cc_sp_vdf
assert has_compact_cc_ip_vdf
for height, block in enumerate(stored_blocks):
await full_node_2.full_node.respond_block(fnp.RespondBlock(block))
assert full_node_2.full_node.blockchain.get_peak().height == height
@pytest.mark.asyncio
async def test_compact_protocol_invalid_messages(self, setup_two_nodes):
nodes, _ = setup_two_nodes
full_node_1 = nodes[0]
full_node_2 = nodes[1]
blocks = bt.get_consecutive_blocks(num_blocks=1, skip_slots=3)
blocks_2 = bt.get_consecutive_blocks(num_blocks=3, block_list_input=blocks, skip_slots=3)
for block in blocks_2[:2]:
await full_node_1.full_node.respond_block(fnp.RespondBlock(block))
assert full_node_1.full_node.blockchain.get_peak().height == 1
# (wrong_vdf_info, wrong_vdf_proof) pair verifies, but it's not present in the blockchain at all.
block = blocks_2[2]
wrong_vdf_info, wrong_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
timelord_protocol_invalid_messages = []
full_node_protocol_invalid_messaages = []
for block in blocks_2[:2]:
for sub_slot in block.finished_sub_slots:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.challenge,
sub_slot.challenge_chain.challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
assert wrong_vdf_proof != correct_vdf_proof
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_EOS_VDF,
vdf_info,
wrong_vdf_proof,
)
)
if sub_slot.infused_challenge_chain is not None:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.challenge,
sub_slot.infused_challenge_chain.infused_challenge_chain_end_of_slot_vdf.number_of_iterations,
True,
)
assert wrong_vdf_proof != correct_vdf_proof
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.ICC_EOS_VDF,
vdf_info,
wrong_vdf_proof,
)
)
if block.reward_chain_block.challenge_chain_sp_vdf is not None:
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_sp_vdf.challenge,
block.reward_chain_block.challenge_chain_sp_vdf.number_of_iterations,
True,
)
sp_vdf_proof = wrong_vdf_proof
if wrong_vdf_proof == correct_vdf_proof:
sp_vdf_proof = VDFProof(uint8(0), b"1239819023890", True)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
sp_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_SP_VDF,
vdf_info,
sp_vdf_proof,
)
)
vdf_info, correct_vdf_proof = get_vdf_info_and_proof(
test_constants,
ClassgroupElement.get_default_element(),
block.reward_chain_block.challenge_chain_ip_vdf.challenge,
block.reward_chain_block.challenge_chain_ip_vdf.number_of_iterations,
True,
)
ip_vdf_proof = wrong_vdf_proof
if wrong_vdf_proof == correct_vdf_proof:
ip_vdf_proof = VDFProof(uint8(0), b"1239819023890", True)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
vdf_info,
ip_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_IP_VDF,
vdf_info,
ip_vdf_proof,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_EOS_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.ICC_EOS_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_SP_VDF,
)
)
timelord_protocol_invalid_messages.append(
timelord_protocol.RespondCompactProofOfTime(
wrong_vdf_info,
wrong_vdf_proof,
block.header_hash,
block.height,
CompressibleVDFField.CC_IP_VDF,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_EOS_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.ICC_EOS_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_SP_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
full_node_protocol_invalid_messaages.append(
fnp.RespondCompactVDF(
block.height,
block.header_hash,
CompressibleVDFField.CC_IP_VDF,
wrong_vdf_info,
wrong_vdf_proof,
)
)
server_1 = full_node_1.full_node.server
server_2 = full_node_2.full_node.server
peer = await connect_and_get_peer(server_1, server_2)
for invalid_compact_proof in timelord_protocol_invalid_messages:
await full_node_1.full_node.respond_compact_proof_of_time(invalid_compact_proof)
for invalid_compact_proof in full_node_protocol_invalid_messaages:
await full_node_1.full_node.respond_compact_vdf(invalid_compact_proof, peer)
stored_blocks = await full_node_1.get_all_full_blocks()
for block in stored_blocks:
for sub_slot in block.finished_sub_slots:
assert not sub_slot.proofs.challenge_chain_slot_proof.normalized_to_identity
if sub_slot.proofs.infused_challenge_chain_slot_proof is not None:
assert not sub_slot.proofs.infused_challenge_chain_slot_proof.normalized_to_identity
if block.challenge_chain_sp_proof is not None:
assert not block.challenge_chain_sp_proof.normalized_to_identity
assert not block.challenge_chain_ip_proof.normalized_to_identity
| true | true |
f729b71c9375ae910c971e5666346597293a4808 | 1,009 | py | Python | setup.py | 9b/pynetinfo | 06889a803b783d3e6480b535bdb9488158d17f2e | [
"MIT"
] | 3 | 2019-02-15T12:58:19.000Z | 2020-04-19T11:11:15.000Z | setup.py | 9b/pynetinfo | 06889a803b783d3e6480b535bdb9488158d17f2e | [
"MIT"
] | 3 | 2020-03-24T16:40:44.000Z | 2021-06-01T23:25:45.000Z | setup.py | 9b/pynetinfo | 06889a803b783d3e6480b535bdb9488158d17f2e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='netinfo',
version='0.0.2',
description='Client to interact with Netinfo services.',
author="Brandon Dixon",
author_email="brandon@backscatter.io",
license="MIT",
packages=find_packages(),
install_requires=['requests'],
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries',
'Topic :: Security'
],
entry_points={
'console_scripts': [
'netinfo = netinfo.cli.client:main'
]
},
zip_safe=False,
keywords=['internet scanning', 'cybersecurity', 'defense', 'intelligence']
)
| 28.027778 | 78 | 0.626363 |
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='netinfo',
version='0.0.2',
description='Client to interact with Netinfo services.',
author="Brandon Dixon",
author_email="brandon@backscatter.io",
license="MIT",
packages=find_packages(),
install_requires=['requests'],
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries',
'Topic :: Security'
],
entry_points={
'console_scripts': [
'netinfo = netinfo.cli.client:main'
]
},
zip_safe=False,
keywords=['internet scanning', 'cybersecurity', 'defense', 'intelligence']
)
| true | true |
f729b75b3711477caa260018d62c0c6df569bbd7 | 123 | py | Python | distint-languaje/index.py | abelcq/FP-2021-G3-UpeU | 5d2596044414a8d295d4fda040abe281fbd5dbae | [
"Apache-2.0"
] | 1 | 2021-05-11T19:46:58.000Z | 2021-05-11T19:46:58.000Z | distint-languaje/index.py | abelcq/FP-2021-G3-UpeU | 5d2596044414a8d295d4fda040abe281fbd5dbae | [
"Apache-2.0"
] | null | null | null | distint-languaje/index.py | abelcq/FP-2021-G3-UpeU | 5d2596044414a8d295d4fda040abe281fbd5dbae | [
"Apache-2.0"
] | null | null | null | print("Hola Mundooo")
a=20
b=10
print("Suma:",a+b)
print("Resta:",a-b)
print("Division:",a/b)
print("Multiplicacion:",a*b)
| 15.375 | 28 | 0.658537 | print("Hola Mundooo")
a=20
b=10
print("Suma:",a+b)
print("Resta:",a-b)
print("Division:",a/b)
print("Multiplicacion:",a*b)
| true | true |
f729b7bba4aa0803df14326f38b9ee5b1d94ee72 | 287 | py | Python | dev/ideas/cython/conversion.py | achilleas-k/brian2 | 906563b6b1321585b082f79f74f1b4ab386347ec | [
"BSD-2-Clause"
] | null | null | null | dev/ideas/cython/conversion.py | achilleas-k/brian2 | 906563b6b1321585b082f79f74f1b4ab386347ec | [
"BSD-2-Clause"
] | null | null | null | dev/ideas/cython/conversion.py | achilleas-k/brian2 | 906563b6b1321585b082f79f74f1b4ab386347ec | [
"BSD-2-Clause"
] | null | null | null | from brian2.codegen.runtime.cython_rt.extension_manager import cython_extension_manager
code = '''
def f(ns):
#cdef int n = <int> ns['n']
cdef int n = ns['n']
print n
'''
ns = {
'n':3,
}
mod = cython_extension_manager.create_extension(code)
mod.f(ns) | 19.133333 | 88 | 0.620209 | from brian2.codegen.runtime.cython_rt.extension_manager import cython_extension_manager
code = '''
def f(ns):
#cdef int n = <int> ns['n']
cdef int n = ns['n']
print n
'''
ns = {
'n':3,
}
mod = cython_extension_manager.create_extension(code)
mod.f(ns) | true | true |
f729b90bebf9d7bbb43017a0e27c50b10745b70e | 931 | py | Python | analyzer/darwin/lib/dtrace/common.py | Yuanmessi/Bold-Falcon | 00fcaba0b3d9c462b9d20ecb256ff85db5d119e2 | [
"BSD-3-Clause"
] | 41 | 2018-03-23T07:51:17.000Z | 2021-04-07T08:26:25.000Z | data/analyzer/darwin/lib/dtrace/common.py | iswenhao/Panda-Sandbox | a04069d404cb4326ff459e703f14625dc45759ed | [
"MIT"
] | 7 | 2018-04-09T13:38:11.000Z | 2020-10-17T08:04:59.000Z | data/analyzer/darwin/lib/dtrace/common.py | iswenhao/Panda-Sandbox | a04069d404cb4326ff459e703f14625dc45759ed | [
"MIT"
] | 8 | 2018-03-22T20:07:33.000Z | 2020-07-27T08:49:11.000Z | #!/usr/bin/env python
# Copyright (C) 2015 Dmitry Rodionov
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
from os import path
from time import sleep
def sanitize_path(raw_path):
""" Replace spaces with backslashes+spaces """
return raw_path.replace(" ", "\\ ")
def path_for_script(script):
""" Return the full path for the given script """
return path.join(current_directory(), script)
def current_directory():
return path.dirname(path.abspath(__file__))
def filelines(source_file):
""" A generator that returns lines of the file.
If there're no new lines it waits until the file is updated.
"""
# Go to the end of the file
source_file.seek(0, 2)
while True:
line = source_file.readline()
if not line:
# Sleep briefly
sleep(0.1)
continue
yield line
| 28.212121 | 64 | 0.665951 |
from os import path
from time import sleep
def sanitize_path(raw_path):
return raw_path.replace(" ", "\\ ")
def path_for_script(script):
return path.join(current_directory(), script)
def current_directory():
return path.dirname(path.abspath(__file__))
def filelines(source_file):
source_file.seek(0, 2)
while True:
line = source_file.readline()
if not line:
sleep(0.1)
continue
yield line
| true | true |
f729b912a6705b22a13bbd97b19a0dfa9d68295a | 711 | py | Python | com.zdl.blog/www/testGgtrans.py | zdlgithub/DougScraper | 452b4567aec3acd1a77e8c4157c9597fdadebe81 | [
"Apache-2.0"
] | null | null | null | com.zdl.blog/www/testGgtrans.py | zdlgithub/DougScraper | 452b4567aec3acd1a77e8c4157c9597fdadebe81 | [
"Apache-2.0"
] | null | null | null | com.zdl.blog/www/testGgtrans.py | zdlgithub/DougScraper | 452b4567aec3acd1a77e8c4157c9597fdadebe81 | [
"Apache-2.0"
] | null | null | null | from urllib import request
from bs4 import BeautifulSoup
from selenium import webdriver
import os
import time
def get_trans_text():
url = 'https://translate.google.cn/#view=home&op=translate&sl=zh-CN&tl=en&text=%3Cdiv%20class%3D%22dpl-box-title%22%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%E8%B4%A7%E5%93%81%E7%B1%BB%E5%9E%8B%0A%20%20%20%20%20%20%20%20%3C%2Fdiv%3E'
# req = request.urlopen(url)
wd = webdriver.Chrome(executable_path=os.path.join(os.path.dirname(__file__),'library/chromedriver.exe'))
wd.get(url)
time.sleep(10)
html_text = wd.page_source
wd.quit()
print(html_text)
soup=BeautifulSoup(html_text,features="html.parser")
print(soup.string())
if __name__=='__main__':
get_trans_text() | 33.857143 | 234 | 0.751055 | from urllib import request
from bs4 import BeautifulSoup
from selenium import webdriver
import os
import time
def get_trans_text():
url = 'https://translate.google.cn/#view=home&op=translate&sl=zh-CN&tl=en&text=%3Cdiv%20class%3D%22dpl-box-title%22%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%E8%B4%A7%E5%93%81%E7%B1%BB%E5%9E%8B%0A%20%20%20%20%20%20%20%20%3C%2Fdiv%3E'
wd = webdriver.Chrome(executable_path=os.path.join(os.path.dirname(__file__),'library/chromedriver.exe'))
wd.get(url)
time.sleep(10)
html_text = wd.page_source
wd.quit()
print(html_text)
soup=BeautifulSoup(html_text,features="html.parser")
print(soup.string())
if __name__=='__main__':
get_trans_text() | true | true |
f729b92f95afdd8c53b9704c211571d744eaddf8 | 630 | py | Python | website/plugins/neighbors/neighbors.py | brandonjflannery/data-analysis-template | 178a088c15956331b59b16b4b05b9b3ba58d41b5 | [
"MIT"
] | 1 | 2020-08-14T16:13:47.000Z | 2020-08-14T16:13:47.000Z | website/plugins/neighbors/neighbors.py | johnjdailey/data-analysis-template | 178a088c15956331b59b16b4b05b9b3ba58d41b5 | [
"MIT"
] | null | null | null | website/plugins/neighbors/neighbors.py | johnjdailey/data-analysis-template | 178a088c15956331b59b16b4b05b9b3ba58d41b5 | [
"MIT"
] | 1 | 2020-07-23T05:09:07.000Z | 2020-07-23T05:09:07.000Z | # -*- coding: utf-8 -*-
"""
Neighbor Articles Plugin for Pelican
====================================
This plugin adds ``next_article`` (newer) and ``prev_article`` (older)
variables to the article's context
"""
from pelican import signals
def iter3(seq):
it = iter(seq)
nxt = None
cur = next(it)
for prv in it:
yield nxt, cur, prv
nxt, cur = cur, prv
yield nxt, cur, None
def neighbors(generator):
for nxt, cur, prv in iter3(generator.articles):
cur.next_article = nxt
cur.prev_article = prv
def register():
signals.article_generator_finalized.connect(neighbors)
| 22.5 | 71 | 0.614286 |
from pelican import signals
def iter3(seq):
it = iter(seq)
nxt = None
cur = next(it)
for prv in it:
yield nxt, cur, prv
nxt, cur = cur, prv
yield nxt, cur, None
def neighbors(generator):
for nxt, cur, prv in iter3(generator.articles):
cur.next_article = nxt
cur.prev_article = prv
def register():
signals.article_generator_finalized.connect(neighbors)
| true | true |
f729bb4f6cb1a63385d76911829228c2bbf80511 | 1,176 | py | Python | profiles_unused/profile_calibration.py | s-light/reflow_controller | 34caa1a37c57751189042c6e720517b059deb56e | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | profiles_unused/profile_calibration.py | s-light/reflow_controller | 34caa1a37c57751189042c6e720517b059deb56e | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | profiles_unused/profile_calibration.py | s-light/reflow_controller | 34caa1a37c57751189042c6e720517b059deb56e | [
"Unlicense",
"MIT-0",
"MIT"
] | null | null | null | import profiles
"""Calibration Profile"""
class ProfileCalibration(profiles.Profile):
"""Calibration Profile"""
def config(self):
# __name__ msut be the same as the class name
self.__name__ = "ProfileCalibration"
self.title = "Calibration Profile"
self.title_short = "Calibration Profile"
self.alloy = "-"
self.melting_point = 220
self.reference = "-"
self.steps = [
{
"name": "set40",
"duration": 0,
"temp_target": 40,
},
{
"name": "hold40",
"duration": 60,
"temp_target": 40,
},
# {
# "name": "heatup100",
# "duration": 10,
# "temp_target": 100,
# },
# {
# "name": "hold100",
# "duration": 10,
# "temp_target": 100,
# },
# {
# "name": "cool",
# "duration": 5,
# "temp_target": 0,
# },
]
| 26.727273 | 54 | 0.37585 | import profiles
class ProfileCalibration(profiles.Profile):
def config(self):
self.__name__ = "ProfileCalibration"
self.title = "Calibration Profile"
self.title_short = "Calibration Profile"
self.alloy = "-"
self.melting_point = 220
self.reference = "-"
self.steps = [
{
"name": "set40",
"duration": 0,
"temp_target": 40,
},
{
"name": "hold40",
"duration": 60,
"temp_target": 40,
},
]
| true | true |
f729bb8a9a77c5cf0f374dfaefd296525d2e86f5 | 10,260 | py | Python | pyswagger/tests/v2_0/test_prim.py | adborden/pyswagger | 65e3401d2dd1b24e345c4f51ea402a1f7419afcd | [
"MIT"
] | null | null | null | pyswagger/tests/v2_0/test_prim.py | adborden/pyswagger | 65e3401d2dd1b24e345c4f51ea402a1f7419afcd | [
"MIT"
] | null | null | null | pyswagger/tests/v2_0/test_prim.py | adborden/pyswagger | 65e3401d2dd1b24e345c4f51ea402a1f7419afcd | [
"MIT"
] | 1 | 2020-03-04T00:22:24.000Z | 2020-03-04T00:22:24.000Z | from pyswagger import SwaggerApp, primitives, errs
from ..utils import get_test_data_folder
from pyswagger.spec.v2_0 import objects
from pyswagger.utils import jp_compose
import os
import unittest
import datetime
import six
class SchemaTestCase(unittest.TestCase):
""" test for Schema object """
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_model_tag(self):
""" test basic model """
t = self.app.resolve('#/definitions/Tag')
self.assertTrue(isinstance(t, objects.Schema))
v = t._prim_(dict(id=1, name='Hairy'))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.name, 'Hairy')
def test_model_pet(self):
""" test complex model, including
model inheritance
"""
p = self.app.resolve('#/definitions/Pet')
self.assertTrue(isinstance(p, objects.Schema))
v = p._prim_(dict(
name='Buf',
photoUrls=['http://flickr.com', 'http://www.google.com'],
id=10,
category=dict(
id=1,
name='dog'
),
tags=[
dict(id=1, name='Hairy'),
dict(id=2, name='south'),
]
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.name, 'Buf')
self.assertEqual(v.photoUrls[0], 'http://flickr.com')
self.assertEqual(v.photoUrls[1], 'http://www.google.com')
self.assertEqual(v.id, 10)
self.assertTrue(isinstance(v.tags[0], primitives.Model))
self.assertTrue(v.tags[0].id, 1)
self.assertTrue(v.tags[0].name, 'Hairy')
self.assertTrue(isinstance(v.category, primitives.Model))
self.assertTrue(v.category.id, 1)
self.assertTrue(v.category.name, 'dog')
def test_model_employee(self):
""" test model with allOf only
"""
e = self.app.resolve("#/definitions/Employee")
self.assertTrue(isinstance(e, objects.Schema))
v = e._prim_(dict(
id=1,
skill_id=2,
location="home",
skill_name="coding"
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.skill_id, 2)
self.assertEqual(v.location, "home")
self.assertEqual(v.skill_name, "coding")
def test_model_boss(self):
""" test model with allOf and properties
"""
b = self.app.resolve("#/definitions/Boss")
self.assertTrue(isinstance(b, objects.Schema))
v = b._prim_(dict(
id=1,
location="office",
boss_name="not you"
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.location, "office")
self.assertEqual(v.boss_name, "not you")
def test_int(self):
""" test integer,
schema is separated into parts
"""
i = self.app.resolve("#/definitions/int")
self.assertRaises(errs.ValidationError, i._prim_, 200)
self.assertRaises(errs.ValidationError, i._prim_, 99)
def test_array_of_int(self):
""" test array of integer """
i = self.app.resolve('#/definitions/array_int')
# pass
i._prim_([1, 1, 1, 1, 1])
i._prim_([1, 1])
# failed
self.assertRaises(errs.ValidationError, i._prim_, [1, 1, 1, 1, 1, 1])
self.assertRaises(errs.ValidationError, i._prim_, [1])
def test_num_multiple_of(self):
""" test multipleOf """
i = self.app.resolve("#/definitions/num_multipleOf")
self.assertRaises(errs.ValidationError, i._prim_, 4)
i._prim_(5) # should raise nothing
def test_str_enum(self):
""" test str enum """
e = self.app.resolve("#/definitions/str_enum")
self.assertRaises(errs.ValidationError, e._prim_, "yellow")
e._prim_("green") # should raise nothing
def test_byte(self):
""" test byte """
b = self.app.resolve("#/definitions/byte")
bv = b._prim_("BBBBB")
self.assertEqual(str(bv), "BBBBB")
self.assertEqual(bv.to_json(), six.b("QkJCQkI="))
def test_date(self):
""" test date """
d = self.app.resolve("#/definitions/date")
# test input of constructor
self.assertEqual(str(d._prim_(float(0))), "1970-01-01")
self.assertEqual(str(d._prim_(datetime.date.fromtimestamp(0))), "1970-01-01")
self.assertEqual(str(d._prim_(datetime.date.fromtimestamp(0).isoformat())), "1970-01-01")
# to_json
dv = d._prim_(float(0))
self.assertEqual(dv.to_json(), "1970-01-01")
def test_date_time(self):
""" test date-time """
d = self.app.resolve("#/definitions/date-time")
# test input of constructor
self.assertEqual(str(d._prim_(float(0))), "1970-01-01T00:00:00")
self.assertEqual(str(d._prim_(datetime.datetime.utcfromtimestamp(0))), "1970-01-01T00:00:00")
self.assertEqual(str(d._prim_(datetime.datetime.utcfromtimestamp(0).isoformat())), "1970-01-01T00:00:00")
# to_json
dv = d._prim_(float(0))
self.assertEqual(dv.to_json(), "1970-01-01T00:00:00")
def test_model_bool(self):
""" test a model containing boolean """
d = self.app.resolve("#/definitions/model_bool")
dv = d._prim_(dict(bool_val=True))
# try to access it
self.assertEqual(dv.bool_val, True)
class HeaderTestCase(unittest.TestCase):
""" test for Header object """
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_simple_array(self):
""" header in array """
p1 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '0']))
self.assertTrue(isinstance(p1, objects.Parameter))
v = p1._prim_([1, 2, 3, 4, 5])
self.assertTrue(isinstance(v, primitives.Array))
self.assertEqual(str(v), '1,2,3,4,5')
def test_integer_limit(self):
""" header in integer """
p2 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '1']))
self.assertTrue(isinstance(p2, objects.Parameter))
self.assertRaises(errs.ValidationError, p2._prim_, 101)
self.assertRaises(errs.ValidationError, p2._prim_, -1)
def test_multi_level_array(self):
""" header in array of array """
p3 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '2']))
self.assertTrue(isinstance(p3, objects.Parameter))
self.assertEqual(str(p3._prim_(
[
[
[1,2],
[3,4],
[5,6]
],
[
[7,8],
[9,10]
],
[
[11,12],
[13,14]
]
]
)), '1|2,3|4,5|6 7|8,9|10 11|12,13|14')
class AdditionalPropertiesTestCase(unittest.TestCase):
""" test case for additionalProperties """
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'additionalProperties')))
def test_with_schema(self):
m = primitives.prim_factory(
self.app.resolve('#/definitions/add_prop'),
dict(
name_of_map='test',
category1=dict(
id=1,
name='cat'
),
category2=dict(
id=2,
name='dog'
),
category3=dict(
id=3,
name='fish'
)
))
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name_of_map, 'test')
self.assertEqual(m.category1.id, 1)
self.assertEqual(m.category1.name, 'cat')
self.assertEqual(m.category2.id, 2)
self.assertEqual(m.category2.name, 'dog')
self.assertEqual(m.category3.id, 3)
self.assertEqual(m.category3.name, 'fish')
def test_with_bool(self):
d = self.app.resolve('#/definitions/add_prop_bool')
m = primitives.prim_factory(
d,
dict(
name='test_bool',
category1=1,
category2='test_qoo'
)
)
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name, 'test_bool')
self.assertEqual(m.category1, 1)
self.assertEqual(m.category2, 'test_qoo')
def test_with_bool_false(self):
d = self.app.resolve('#/definitions/add_prop_false')
m = primitives.prim_factory(
d,
dict(
name='test_bool',
category1=1,
category2='test_qoo'
)
)
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name, 'test_bool')
self.assertTrue('category1' not in m)
self.assertTrue('category2' not in m)
def test_with_allof_limitation(self):
""" additionalProperties would accept all keys,
we need to make sure nested model process those keys before
additionalProperties intecept all keys
"""
d = self.app.resolve('#/definitions/add_prop_nested')
self.assertRaises(errs.ValidationError, primitives.prim_factory,
d,
dict(
my_int=99
)
)
class ParameterTestCase(unittest.TestCase):
""" test for Parameter object """
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_unknown(self):
p = self.app.resolve('#/paths/~1t/put')
self.assertRaises(ValueError, p, p1='tom', p2='mary', p3='qoo', p4='unknown')
| 32.884615 | 128 | 0.566569 | from pyswagger import SwaggerApp, primitives, errs
from ..utils import get_test_data_folder
from pyswagger.spec.v2_0 import objects
from pyswagger.utils import jp_compose
import os
import unittest
import datetime
import six
class SchemaTestCase(unittest.TestCase):
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_model_tag(self):
t = self.app.resolve('#/definitions/Tag')
self.assertTrue(isinstance(t, objects.Schema))
v = t._prim_(dict(id=1, name='Hairy'))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.name, 'Hairy')
def test_model_pet(self):
p = self.app.resolve('#/definitions/Pet')
self.assertTrue(isinstance(p, objects.Schema))
v = p._prim_(dict(
name='Buf',
photoUrls=['http://flickr.com', 'http://www.google.com'],
id=10,
category=dict(
id=1,
name='dog'
),
tags=[
dict(id=1, name='Hairy'),
dict(id=2, name='south'),
]
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.name, 'Buf')
self.assertEqual(v.photoUrls[0], 'http://flickr.com')
self.assertEqual(v.photoUrls[1], 'http://www.google.com')
self.assertEqual(v.id, 10)
self.assertTrue(isinstance(v.tags[0], primitives.Model))
self.assertTrue(v.tags[0].id, 1)
self.assertTrue(v.tags[0].name, 'Hairy')
self.assertTrue(isinstance(v.category, primitives.Model))
self.assertTrue(v.category.id, 1)
self.assertTrue(v.category.name, 'dog')
def test_model_employee(self):
e = self.app.resolve("#/definitions/Employee")
self.assertTrue(isinstance(e, objects.Schema))
v = e._prim_(dict(
id=1,
skill_id=2,
location="home",
skill_name="coding"
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.skill_id, 2)
self.assertEqual(v.location, "home")
self.assertEqual(v.skill_name, "coding")
def test_model_boss(self):
b = self.app.resolve("#/definitions/Boss")
self.assertTrue(isinstance(b, objects.Schema))
v = b._prim_(dict(
id=1,
location="office",
boss_name="not you"
))
self.assertTrue(isinstance(v, primitives.Model))
self.assertEqual(v.id, 1)
self.assertEqual(v.location, "office")
self.assertEqual(v.boss_name, "not you")
def test_int(self):
i = self.app.resolve("#/definitions/int")
self.assertRaises(errs.ValidationError, i._prim_, 200)
self.assertRaises(errs.ValidationError, i._prim_, 99)
def test_array_of_int(self):
i = self.app.resolve('#/definitions/array_int')
i._prim_([1, 1, 1, 1, 1])
i._prim_([1, 1])
self.assertRaises(errs.ValidationError, i._prim_, [1, 1, 1, 1, 1, 1])
self.assertRaises(errs.ValidationError, i._prim_, [1])
def test_num_multiple_of(self):
i = self.app.resolve("#/definitions/num_multipleOf")
self.assertRaises(errs.ValidationError, i._prim_, 4)
i._prim_(5)
def test_str_enum(self):
e = self.app.resolve("#/definitions/str_enum")
self.assertRaises(errs.ValidationError, e._prim_, "yellow")
e._prim_("green")
def test_byte(self):
b = self.app.resolve("#/definitions/byte")
bv = b._prim_("BBBBB")
self.assertEqual(str(bv), "BBBBB")
self.assertEqual(bv.to_json(), six.b("QkJCQkI="))
def test_date(self):
d = self.app.resolve("#/definitions/date")
self.assertEqual(str(d._prim_(float(0))), "1970-01-01")
self.assertEqual(str(d._prim_(datetime.date.fromtimestamp(0))), "1970-01-01")
self.assertEqual(str(d._prim_(datetime.date.fromtimestamp(0).isoformat())), "1970-01-01")
dv = d._prim_(float(0))
self.assertEqual(dv.to_json(), "1970-01-01")
def test_date_time(self):
d = self.app.resolve("#/definitions/date-time")
self.assertEqual(str(d._prim_(float(0))), "1970-01-01T00:00:00")
self.assertEqual(str(d._prim_(datetime.datetime.utcfromtimestamp(0))), "1970-01-01T00:00:00")
self.assertEqual(str(d._prim_(datetime.datetime.utcfromtimestamp(0).isoformat())), "1970-01-01T00:00:00")
dv = d._prim_(float(0))
self.assertEqual(dv.to_json(), "1970-01-01T00:00:00")
def test_model_bool(self):
d = self.app.resolve("#/definitions/model_bool")
dv = d._prim_(dict(bool_val=True))
self.assertEqual(dv.bool_val, True)
class HeaderTestCase(unittest.TestCase):
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_simple_array(self):
p1 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '0']))
self.assertTrue(isinstance(p1, objects.Parameter))
v = p1._prim_([1, 2, 3, 4, 5])
self.assertTrue(isinstance(v, primitives.Array))
self.assertEqual(str(v), '1,2,3,4,5')
def test_integer_limit(self):
p2 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '1']))
self.assertTrue(isinstance(p2, objects.Parameter))
self.assertRaises(errs.ValidationError, p2._prim_, 101)
self.assertRaises(errs.ValidationError, p2._prim_, -1)
def test_multi_level_array(self):
p3 = self.app.resolve(jp_compose(['#', 'paths', '/t', 'get', 'parameters', '2']))
self.assertTrue(isinstance(p3, objects.Parameter))
self.assertEqual(str(p3._prim_(
[
[
[1,2],
[3,4],
[5,6]
],
[
[7,8],
[9,10]
],
[
[11,12],
[13,14]
]
]
)), '1|2,3|4,5|6 7|8,9|10 11|12,13|14')
class AdditionalPropertiesTestCase(unittest.TestCase):
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'additionalProperties')))
def test_with_schema(self):
m = primitives.prim_factory(
self.app.resolve('#/definitions/add_prop'),
dict(
name_of_map='test',
category1=dict(
id=1,
name='cat'
),
category2=dict(
id=2,
name='dog'
),
category3=dict(
id=3,
name='fish'
)
))
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name_of_map, 'test')
self.assertEqual(m.category1.id, 1)
self.assertEqual(m.category1.name, 'cat')
self.assertEqual(m.category2.id, 2)
self.assertEqual(m.category2.name, 'dog')
self.assertEqual(m.category3.id, 3)
self.assertEqual(m.category3.name, 'fish')
def test_with_bool(self):
d = self.app.resolve('#/definitions/add_prop_bool')
m = primitives.prim_factory(
d,
dict(
name='test_bool',
category1=1,
category2='test_qoo'
)
)
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name, 'test_bool')
self.assertEqual(m.category1, 1)
self.assertEqual(m.category2, 'test_qoo')
def test_with_bool_false(self):
d = self.app.resolve('#/definitions/add_prop_false')
m = primitives.prim_factory(
d,
dict(
name='test_bool',
category1=1,
category2='test_qoo'
)
)
self.assertTrue(isinstance(m, primitives.Model))
self.assertEqual(m.name, 'test_bool')
self.assertTrue('category1' not in m)
self.assertTrue('category2' not in m)
def test_with_allof_limitation(self):
d = self.app.resolve('#/definitions/add_prop_nested')
self.assertRaises(errs.ValidationError, primitives.prim_factory,
d,
dict(
my_int=99
)
)
class ParameterTestCase(unittest.TestCase):
@classmethod
def setUpClass(kls):
kls.app = SwaggerApp._create_(get_test_data_folder(version='2.0', which=os.path.join('schema', 'model')))
def test_unknown(self):
p = self.app.resolve('#/paths/~1t/put')
self.assertRaises(ValueError, p, p1='tom', p2='mary', p3='qoo', p4='unknown')
| true | true |
f729bc1e4c85a8d55d4ed9f745c3184f07432d23 | 3,296 | py | Python | onlinepayments/sdk/domain/create_hosted_tokenization_request.py | wl-online-payments-direct/sdk-python3 | 99fca127334520cde4ffa3a34cbea3b3a0d3fbff | [
"Apache-2.0"
] | null | null | null | onlinepayments/sdk/domain/create_hosted_tokenization_request.py | wl-online-payments-direct/sdk-python3 | 99fca127334520cde4ffa3a34cbea3b3a0d3fbff | [
"Apache-2.0"
] | null | null | null | onlinepayments/sdk/domain/create_hosted_tokenization_request.py | wl-online-payments-direct/sdk-python3 | 99fca127334520cde4ffa3a34cbea3b3a0d3fbff | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
#
# This class was auto-generated.
#
from onlinepayments.sdk.data_object import DataObject
class CreateHostedTokenizationRequest(DataObject):
__ask_consumer_consent = None
__locale = None
__tokens = None
__variant = None
@property
def ask_consumer_consent(self) -> bool:
"""
| Indicate if the tokenization form should contain a prompt asking the user to give consent for storing their information for future payments.
| If this parameter is false, you should ask the user yourself and provide the answer when submitting the Tokenizer in your javascript code.
Type: bool
"""
return self.__ask_consumer_consent
@ask_consumer_consent.setter
def ask_consumer_consent(self, value: bool):
self.__ask_consumer_consent = value
@property
def locale(self) -> str:
"""
| Locale used in the GUI towards the consumer.
Type: str
"""
return self.__locale
@locale.setter
def locale(self, value: str):
self.__locale = value
@property
def tokens(self) -> str:
"""
| String containing comma separated tokens (no spaces) associated with the customer of this hosted session. Valid tokens will be used to present the customer the option to re-use previously used payment details. This means the customer for instance does not have to re-enter their card details again, which a big plus when the customer is using their mobile phone to complete the operation.
Type: str
"""
return self.__tokens
@tokens.setter
def tokens(self, value: str):
self.__tokens = value
@property
def variant(self) -> str:
"""
| Using the Back-Office it is possible to upload multiple templates of your HostedCheckout payment pages. You can force the use of another template by specifying it in the variant field. This allows you to test out the effect of certain changes to your hostedcheckout pages in a controlled manner. Please note that you need to specify the filename of the template.
Type: str
"""
return self.__variant
@variant.setter
def variant(self, value: str):
self.__variant = value
def to_dictionary(self):
dictionary = super(CreateHostedTokenizationRequest, self).to_dictionary()
if self.ask_consumer_consent is not None:
dictionary['askConsumerConsent'] = self.ask_consumer_consent
if self.locale is not None:
dictionary['locale'] = self.locale
if self.tokens is not None:
dictionary['tokens'] = self.tokens
if self.variant is not None:
dictionary['variant'] = self.variant
return dictionary
def from_dictionary(self, dictionary):
super(CreateHostedTokenizationRequest, self).from_dictionary(dictionary)
if 'askConsumerConsent' in dictionary:
self.ask_consumer_consent = dictionary['askConsumerConsent']
if 'locale' in dictionary:
self.locale = dictionary['locale']
if 'tokens' in dictionary:
self.tokens = dictionary['tokens']
if 'variant' in dictionary:
self.variant = dictionary['variant']
return self
| 36.622222 | 398 | 0.670813 |
from onlinepayments.sdk.data_object import DataObject
class CreateHostedTokenizationRequest(DataObject):
__ask_consumer_consent = None
__locale = None
__tokens = None
__variant = None
@property
def ask_consumer_consent(self) -> bool:
return self.__ask_consumer_consent
@ask_consumer_consent.setter
def ask_consumer_consent(self, value: bool):
self.__ask_consumer_consent = value
@property
def locale(self) -> str:
return self.__locale
@locale.setter
def locale(self, value: str):
self.__locale = value
@property
def tokens(self) -> str:
return self.__tokens
@tokens.setter
def tokens(self, value: str):
self.__tokens = value
@property
def variant(self) -> str:
return self.__variant
@variant.setter
def variant(self, value: str):
self.__variant = value
def to_dictionary(self):
dictionary = super(CreateHostedTokenizationRequest, self).to_dictionary()
if self.ask_consumer_consent is not None:
dictionary['askConsumerConsent'] = self.ask_consumer_consent
if self.locale is not None:
dictionary['locale'] = self.locale
if self.tokens is not None:
dictionary['tokens'] = self.tokens
if self.variant is not None:
dictionary['variant'] = self.variant
return dictionary
def from_dictionary(self, dictionary):
super(CreateHostedTokenizationRequest, self).from_dictionary(dictionary)
if 'askConsumerConsent' in dictionary:
self.ask_consumer_consent = dictionary['askConsumerConsent']
if 'locale' in dictionary:
self.locale = dictionary['locale']
if 'tokens' in dictionary:
self.tokens = dictionary['tokens']
if 'variant' in dictionary:
self.variant = dictionary['variant']
return self
| true | true |
f729bc993bebdfdb8e44c949199670aad4e16244 | 2,714 | py | Python | test/kernels/test_rbf_kernel_grad.py | techshot25/gpytorch | b4aee6f81a3428172d4914e7e0fef0e71cd1f519 | [
"MIT"
] | 1 | 2019-11-08T11:25:56.000Z | 2019-11-08T11:25:56.000Z | test/kernels/test_rbf_kernel_grad.py | VonRosenchild/gpytorch | 092d523027a844939ba85d7ea8c8c7b7511843d5 | [
"MIT"
] | null | null | null | test/kernels/test_rbf_kernel_grad.py | VonRosenchild/gpytorch | 092d523027a844939ba85d7ea8c8c7b7511843d5 | [
"MIT"
] | 1 | 2021-07-02T19:40:07.000Z | 2021-07-02T19:40:07.000Z | #!/usr/bin/env python3
import torch
import unittest
from gpytorch.kernels import RBFKernelGrad
from gpytorch.test.base_kernel_test_case import BaseKernelTestCase
class TestRBFKernelGrad(unittest.TestCase, BaseKernelTestCase):
def create_kernel_no_ard(self, **kwargs):
return RBFKernelGrad(**kwargs)
def create_kernel_ard(self, num_dims, **kwargs):
return RBFKernelGrad(ard_num_dims=num_dims, **kwargs)
def test_kernel(self, cuda=False):
a = torch.tensor([[[1, 2], [2, 4]]], dtype=torch.float)
b = torch.tensor([[[1, 3], [0, 4]]], dtype=torch.float)
actual = torch.tensor(
[
[0.35321, 0, -0.73517, 0.0054977, 0.011443, -0.022886],
[0, 0.73517, 0, -0.011443, -0.012374, 0.047633],
[0.73517, 0, -0.79499, 0.022886, 0.047633, -0.083824],
[0.12476, 0.25967, 0.25967, 0.015565, 0.064793, 0],
[-0.25967, -0.2808, -0.54047, -0.064793, -0.23732, 0],
[-0.25967, -0.54047, -0.2808, 0, 0, 0.032396],
]
)
kernel = RBFKernelGrad()
if cuda:
a = a.cuda()
b = b.cuda()
actual = actual.cuda()
kernel = kernel.cuda()
res = kernel(a, b).evaluate()
self.assertLess(torch.norm(res - actual), 1e-5)
def test_kernel_cuda(self):
if torch.cuda.is_available():
self.test_kernel(cuda=True)
def test_kernel_batch(self):
a = torch.tensor([[[1, 2, 3], [2, 4, 0]], [[-1, 1, 2], [2, 1, 4]]], dtype=torch.float)
b = torch.tensor([[[1, 3, 1]], [[2, -1, 0]]], dtype=torch.float).repeat(1, 2, 1)
kernel = RBFKernelGrad()
res = kernel(a, b).evaluate()
# Compute each batch separately
actual = torch.zeros(2, 8, 8)
actual[0, :, :] = kernel(a[0, :, :].squeeze(), b[0, :, :].squeeze()).evaluate()
actual[1, :, :] = kernel(a[1, :, :].squeeze(), b[1, :, :].squeeze()).evaluate()
self.assertLess(torch.norm(res - actual), 1e-5)
def test_initialize_lengthscale(self):
kernel = RBFKernelGrad()
kernel.initialize(lengthscale=3.14)
actual_value = torch.tensor(3.14).view_as(kernel.lengthscale)
self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)
def test_initialize_lengthscale_batch(self):
kernel = RBFKernelGrad(batch_shape=torch.Size([2]))
ls_init = torch.tensor([3.14, 4.13])
kernel.initialize(lengthscale=ls_init)
actual_value = ls_init.view_as(kernel.lengthscale)
self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)
if __name__ == "__main__":
unittest.main()
| 35.246753 | 94 | 0.58143 |
import torch
import unittest
from gpytorch.kernels import RBFKernelGrad
from gpytorch.test.base_kernel_test_case import BaseKernelTestCase
class TestRBFKernelGrad(unittest.TestCase, BaseKernelTestCase):
def create_kernel_no_ard(self, **kwargs):
return RBFKernelGrad(**kwargs)
def create_kernel_ard(self, num_dims, **kwargs):
return RBFKernelGrad(ard_num_dims=num_dims, **kwargs)
def test_kernel(self, cuda=False):
a = torch.tensor([[[1, 2], [2, 4]]], dtype=torch.float)
b = torch.tensor([[[1, 3], [0, 4]]], dtype=torch.float)
actual = torch.tensor(
[
[0.35321, 0, -0.73517, 0.0054977, 0.011443, -0.022886],
[0, 0.73517, 0, -0.011443, -0.012374, 0.047633],
[0.73517, 0, -0.79499, 0.022886, 0.047633, -0.083824],
[0.12476, 0.25967, 0.25967, 0.015565, 0.064793, 0],
[-0.25967, -0.2808, -0.54047, -0.064793, -0.23732, 0],
[-0.25967, -0.54047, -0.2808, 0, 0, 0.032396],
]
)
kernel = RBFKernelGrad()
if cuda:
a = a.cuda()
b = b.cuda()
actual = actual.cuda()
kernel = kernel.cuda()
res = kernel(a, b).evaluate()
self.assertLess(torch.norm(res - actual), 1e-5)
def test_kernel_cuda(self):
if torch.cuda.is_available():
self.test_kernel(cuda=True)
def test_kernel_batch(self):
a = torch.tensor([[[1, 2, 3], [2, 4, 0]], [[-1, 1, 2], [2, 1, 4]]], dtype=torch.float)
b = torch.tensor([[[1, 3, 1]], [[2, -1, 0]]], dtype=torch.float).repeat(1, 2, 1)
kernel = RBFKernelGrad()
res = kernel(a, b).evaluate()
actual = torch.zeros(2, 8, 8)
actual[0, :, :] = kernel(a[0, :, :].squeeze(), b[0, :, :].squeeze()).evaluate()
actual[1, :, :] = kernel(a[1, :, :].squeeze(), b[1, :, :].squeeze()).evaluate()
self.assertLess(torch.norm(res - actual), 1e-5)
def test_initialize_lengthscale(self):
kernel = RBFKernelGrad()
kernel.initialize(lengthscale=3.14)
actual_value = torch.tensor(3.14).view_as(kernel.lengthscale)
self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)
def test_initialize_lengthscale_batch(self):
kernel = RBFKernelGrad(batch_shape=torch.Size([2]))
ls_init = torch.tensor([3.14, 4.13])
kernel.initialize(lengthscale=ls_init)
actual_value = ls_init.view_as(kernel.lengthscale)
self.assertLess(torch.norm(kernel.lengthscale - actual_value), 1e-5)
if __name__ == "__main__":
unittest.main()
| true | true |
f729bd00900c30a0ff62eef900fa67fb11dea09b | 22,514 | py | Python | aldryn_newsblog/models.py | GabrielDumbrava/aldryn-newsblog | f3be5ff78e88fde532ce4c45e5eeb88d98fa6d93 | [
"BSD-3-Clause"
] | null | null | null | aldryn_newsblog/models.py | GabrielDumbrava/aldryn-newsblog | f3be5ff78e88fde532ce4c45e5eeb88d98fa6d93 | [
"BSD-3-Clause"
] | null | null | null | aldryn_newsblog/models.py | GabrielDumbrava/aldryn-newsblog | f3be5ff78e88fde532ce4c45e5eeb88d98fa6d93 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from aldryn_apphooks_config.fields import AppHookConfigField
from aldryn_categories.fields import CategoryManyToManyField
from aldryn_categories.models import Category
from aldryn_newsblog.utils.utilities import get_valid_languages_from_request
from aldryn_people.models import Person
from aldryn_translation_tools.models import TranslatedAutoSlugifyMixin, TranslationHelperMixin
from cms.models.fields import PlaceholderField
from cms.models.pluginmodel import CMSPlugin
from cms.utils.i18n import get_current_language, get_redirect_on_fallback
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import connection, models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import override, ugettext
from djangocms_text_ckeditor.fields import HTMLField
from filer.fields.image import FilerImageField
from parler.models import TranslatableModel, TranslatedFields
from sortedm2m.fields import SortedManyToManyField
from taggit.managers import TaggableManager
from taggit.models import Tag
from .cms_appconfig import NewsBlogConfig
from .managers import RelatedManager
from .settings import ENABLE_REVERSION
from .utils import get_plugin_index_data, get_request, strip_tags
try:
from django.utils.encoding import force_unicode
except ImportError:
from django.utils.encoding import force_text as force_unicode
if settings.LANGUAGES:
LANGUAGE_CODES = [language[0] for language in settings.LANGUAGES]
elif settings.LANGUAGE:
LANGUAGE_CODES = [settings.LANGUAGE]
else:
raise ImproperlyConfigured(
'Neither LANGUAGES nor LANGUAGE was found in settings.')
# At startup time, SQL_NOW_FUNC will contain the database-appropriate SQL to
# obtain the CURRENT_TIMESTAMP.
SQL_NOW_FUNC = {
'mssql': 'GetDate()', 'mysql': 'NOW()', 'postgresql': 'now()',
'sqlite': 'CURRENT_TIMESTAMP', 'oracle': 'CURRENT_TIMESTAMP'
}[connection.vendor]
SQL_IS_TRUE = {
'mssql': '== TRUE', 'mysql': '= 1', 'postgresql': 'IS TRUE',
'sqlite': '== 1', 'oracle': 'IS TRUE'
}[connection.vendor]
class Article(TranslatedAutoSlugifyMixin,
TranslationHelperMixin,
TranslatableModel):
# TranslatedAutoSlugifyMixin options
slug_source_field_name = 'title'
slug_default = _('untitled-article')
# when True, updates the article's search_data field
# whenever the article is saved or a plugin is saved
# on the article's content placeholder.
update_search_on_save = getattr(
settings,
'ALDRYN_NEWSBLOG_UPDATE_SEARCH_DATA_ON_SAVE',
False
)
translations = TranslatedFields(
title=models.CharField(_('title'), max_length=234),
slug=models.SlugField(
verbose_name=_('slug'),
max_length=255,
db_index=True,
blank=True,
help_text=_(
'Used in the URL. If changed, the URL will change. '
'Clear it to have it re-created automatically.'),
),
lead_in=HTMLField(
verbose_name=_('lead'), default='',
help_text=_(
'The lead gives the reader the main idea of the story, this '
'is useful in overviews, lists or as an introduction to your '
'article.'
),
blank=True,
),
meta_title=models.CharField(
max_length=255, verbose_name=_('meta title'),
blank=True, default=''),
meta_description=models.TextField(
verbose_name=_('meta description'), blank=True, default=''),
meta_keywords=models.TextField(
verbose_name=_('meta keywords'), blank=True, default=''),
meta={'unique_together': (('language_code', 'slug', ), )},
search_data=models.TextField(blank=True, editable=False)
)
content = PlaceholderField('newsblog_article_content',
related_name='newsblog_article_content')
author = models.ForeignKey(Person, null=True, blank=True,
verbose_name=_('author'), on_delete=models.SET_NULL)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('owner'), on_delete=models.PROTECT)
app_config = AppHookConfigField(NewsBlogConfig,
verbose_name=_('Apphook configuration'))
categories = CategoryManyToManyField('aldryn_categories.Category',
verbose_name=_('categories'),
blank=True)
publishing_date = models.DateTimeField(_('publishing date'),
default=now)
is_published = models.BooleanField(_('is published'), default=False,
db_index=True)
is_featured = models.BooleanField(_('is featured'), default=False,
db_index=True)
featured_image = FilerImageField(
verbose_name=_('featured image'),
null=True,
blank=True,
on_delete=models.SET_NULL,
)
tags = TaggableManager(blank=True)
# Setting "symmetrical" to False since it's a bit unexpected that if you
# set "B relates to A" you immediately have also "A relates to B". It have
# to be forced to False because by default it's True if rel.to is "self":
#
# https://github.com/django/django/blob/1.8.4/django/db/models/fields/related.py#L2144
#
# which in the end causes to add reversed releted-to entry as well:
#
# https://github.com/django/django/blob/1.8.4/django/db/models/fields/related.py#L977
related = SortedManyToManyField('self', verbose_name=_('related articles'),
blank=True, symmetrical=False)
objects = RelatedManager()
class Meta:
ordering = ['-publishing_date']
@property
def published(self):
"""
Returns True only if the article (is_published == True) AND has a
published_date that has passed.
"""
return (self.is_published and self.publishing_date <= now())
@property
def future(self):
"""
Returns True if the article is published but is scheduled for a
future date/time.
"""
return (self.is_published and self.publishing_date > now())
def get_absolute_url(self, language=None):
"""Returns the url for this Article in the selected permalink format."""
if not language:
language = get_current_language()
kwargs = {}
permalink_type = self.app_config.permalink_type
if 'y' in permalink_type:
kwargs.update(year=self.publishing_date.year)
if 'm' in permalink_type:
kwargs.update(month="%02d" % self.publishing_date.month)
if 'd' in permalink_type:
kwargs.update(day="%02d" % self.publishing_date.day)
if 'i' in permalink_type:
kwargs.update(pk=self.pk)
if 's' in permalink_type:
slug, lang = self.known_translation_getter(
'slug', default=None, language_code=language)
if slug and lang:
site_id = getattr(settings, 'SITE_ID', None)
if get_redirect_on_fallback(language, site_id):
language = lang
kwargs.update(slug=slug)
if self.app_config and self.app_config.namespace:
namespace = '{0}:'.format(self.app_config.namespace)
else:
namespace = ''
with override(language):
return reverse('{0}article-detail'.format(namespace), kwargs=kwargs)
def get_search_data(self, language=None, request=None):
"""
Provides an index for use with Haystack, or, for populating
Article.translations.search_data.
"""
if not self.pk:
return ''
if language is None:
language = get_current_language()
if request is None:
request = get_request(language=language)
description = self.safe_translation_getter('lead_in', '')
text_bits = [strip_tags(description)]
for category in self.categories.all():
text_bits.append(
force_unicode(category.safe_translation_getter('name')))
for tag in self.tags.all():
text_bits.append(force_unicode(tag.name))
if self.content:
plugins = self.content.cmsplugin_set.filter(language=language)
for base_plugin in plugins:
plugin_text_content = ' '.join(
get_plugin_index_data(base_plugin, request))
text_bits.append(plugin_text_content)
return ' '.join(text_bits)
def save(self, *args, **kwargs):
# Update the search index
if self.update_search_on_save:
self.search_data = self.get_search_data()
# Ensure there is an owner.
if self.app_config.create_authors and self.author is None:
# TODO: With django-parler 1.8 and Django 1.11 get_or_create() is
# not working with translated fields yet:
# https://github.com/django-parler/django-parler/issues/189
self.author = Person.objects.get_or_create(
user=self.owner,
defaults={
'name': ' '.join((
self.owner.first_name,
self.owner.last_name,
)),
})[0]
# slug would be generated by TranslatedAutoSlugifyMixin
super(Article, self).save(*args, **kwargs)
def __str__(self):
return self.safe_translation_getter('title', any_language=True)
class PluginEditModeMixin(object):
def get_edit_mode(self, request):
"""
Returns True only if an operator is logged-into the CMS and is in
edit mode.
"""
return (
hasattr(request, 'toolbar') and request.toolbar and
request.toolbar.edit_mode)
class AdjustableCacheModelMixin(models.Model):
# NOTE: This field shouldn't even be displayed in the plugin's change form
# if using django CMS < 3.3.0
cache_duration = models.PositiveSmallIntegerField(
default=0, # not the most sensible, but consistent with older versions
blank=False,
help_text=_(
"The maximum duration (in seconds) that this plugin's content "
"should be cached.")
)
class Meta:
abstract = True
class NewsBlogCMSPlugin(CMSPlugin):
"""AppHookConfig aware abstract CMSPlugin class for Aldryn Newsblog"""
# avoid reverse relation name clashes by not adding a related_name
# to the parent plugin
cmsplugin_ptr = models.OneToOneField(
CMSPlugin, related_name='+', parent_link=True, on_delete=models.CASCADE)
app_config = models.ForeignKey(NewsBlogConfig, verbose_name=_('Apphook configuration'), on_delete=models.PROTECT)
class Meta:
abstract = True
def copy_relations(self, old_instance):
self.app_config = old_instance.app_config
class NewsBlogArchivePlugin(PluginEditModeMixin, AdjustableCacheModelMixin,
NewsBlogCMSPlugin):
# NOTE: the PluginEditModeMixin is eventually used in the cmsplugin, not
# here in the model.
def __str__(self):
return ugettext('%s archive') % (self.app_config.get_app_title(), )
class NewsBlogArticleSearchPlugin(NewsBlogCMSPlugin):
max_articles = models.PositiveIntegerField(
_('max articles'), default=10,
validators=[django.core.validators.MinValueValidator(1)],
help_text=_('The maximum number of found articles display.')
)
def __str__(self):
return ugettext('%s archive') % (self.app_config.get_app_title(), )
class NewsBlogAuthorsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def get_authors(self, request):
"""
Returns a queryset of authors (people who have published an article),
annotated by the number of articles (article_count) that are visible to
the current user. If this user is anonymous, then this will be all
articles that are published and whose publishing_date has passed. If the
user is a logged-in cms operator, then it will be all articles.
"""
# The basic subquery (for logged-in content managers in edit mode)
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article
WHERE
aldryn_newsblog_article.author_id =
aldryn_people_person.id AND
aldryn_newsblog_article.app_config_id = %d"""
# For other users, limit subquery to published articles
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
# Now, use this subquery in the construction of the main query.
query = """
SELECT (%s) as article_count, aldryn_people_person.*
FROM aldryn_people_person
""" % (subquery % (self.app_config.pk, ), )
raw_authors = list(Person.objects.raw(query))
authors = [author for author in raw_authors if author.article_count]
return sorted(authors, key=lambda x: x.article_count, reverse=True)
def __str__(self):
return ugettext('%s authors') % (self.app_config.get_app_title(), )
class NewsBlogCategoriesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def __str__(self):
return ugettext('%s categories') % (self.app_config.get_app_title(), )
def get_categories(self, request):
"""
Returns a list of categories, annotated by the number of articles
(article_count) that are visible to the current user. If this user is
anonymous, then this will be all articles that are published and whose
publishing_date has passed. If the user is a logged-in cms operator,
then it will be all articles.
"""
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article, aldryn_newsblog_article_categories
WHERE
aldryn_newsblog_article_categories.category_id =
aldryn_categories_category.id AND
aldryn_newsblog_article_categories.article_id =
aldryn_newsblog_article.id AND
aldryn_newsblog_article.app_config_id = %d
""" % (self.app_config.pk, )
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
query = """
SELECT (%s) as article_count, aldryn_categories_category.*
FROM aldryn_categories_category
""" % (subquery, )
raw_categories = list(Category.objects.raw(query))
categories = [
category for category in raw_categories if category.article_count]
return sorted(categories, key=lambda x: x.article_count, reverse=True)
class NewsBlogFeaturedArticlesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
article_count = models.PositiveIntegerField(
default=1,
validators=[django.core.validators.MinValueValidator(1)],
help_text=_('The maximum number of featured articles display.')
)
def get_articles(self, request):
if not self.article_count:
return Article.objects.none()
queryset = Article.objects
if not self.get_edit_mode(request):
queryset = queryset.published()
languages = get_valid_languages_from_request(
self.app_config.namespace, request)
if self.language not in languages:
return queryset.none()
queryset = queryset.translated(*languages).filter(
app_config=self.app_config,
is_featured=True)
return queryset[:self.article_count]
def __str__(self):
if not self.pk:
return 'featured articles'
prefix = self.app_config.get_app_title()
if self.article_count == 1:
title = ugettext('featured article')
else:
title = ugettext('featured articles: %(count)s') % {
'count': self.article_count,
}
return '{0} {1}'.format(prefix, title)
class NewsBlogLatestArticlesPlugin(PluginEditModeMixin,
AdjustableCacheModelMixin,
NewsBlogCMSPlugin):
latest_articles = models.IntegerField(
default=5,
help_text=_('The maximum number of latest articles to display.')
)
exclude_featured = models.PositiveSmallIntegerField(
default=0,
blank=True,
help_text=_(
'The maximum number of featured articles to exclude from display. '
'E.g. for uses in combination with featured articles plugin.')
)
def get_articles(self, request):
"""
Returns a queryset of the latest N articles. N is the plugin setting:
latest_articles.
"""
queryset = Article.objects
featured_qs = Article.objects.all().filter(is_featured=True)
if not self.get_edit_mode(request):
queryset = queryset.published()
featured_qs = featured_qs.published()
languages = get_valid_languages_from_request(
self.app_config.namespace, request)
if self.language not in languages:
return queryset.none()
queryset = queryset.translated(*languages).filter(
app_config=self.app_config)
featured_qs = featured_qs.translated(*languages).filter(
app_config=self.app_config)
exclude_featured = featured_qs.values_list(
'pk', flat=True)[:self.exclude_featured]
queryset = queryset.exclude(pk__in=list(exclude_featured))
return queryset[:self.latest_articles]
def __str__(self):
return ugettext('%(app_title)s latest articles: %(latest_articles)s') % {
'app_title': self.app_config.get_app_title(),
'latest_articles': self.latest_articles,
}
class NewsBlogRelatedPlugin(PluginEditModeMixin, AdjustableCacheModelMixin,
CMSPlugin):
# NOTE: This one does NOT subclass NewsBlogCMSPlugin. This is because this
# plugin can really only be placed on the article detail view in an apphook.
cmsplugin_ptr = models.OneToOneField(
CMSPlugin, related_name='+', parent_link=True, on_delete=models.CASCADE)
def get_articles(self, article, request):
"""
Returns a queryset of articles that are related to the given article.
"""
languages = get_valid_languages_from_request(
article.app_config.namespace, request)
if self.language not in languages:
return Article.objects.none()
qs = article.related.translated(*languages)
if not self.get_edit_mode(request):
qs = qs.published()
return qs
def __str__(self):
return ugettext('Related articles')
class NewsBlogTagsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def get_tags(self, request):
"""
Returns a queryset of tags, annotated by the number of articles
(article_count) that are visible to the current user. If this user is
anonymous, then this will be all articles that are published and whose
publishing_date has passed. If the user is a logged-in cms operator,
then it will be all articles.
"""
article_content_type = ContentType.objects.get_for_model(Article)
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article, taggit_taggeditem
WHERE
taggit_taggeditem.tag_id = taggit_tag.id AND
taggit_taggeditem.content_type_id = %d AND
taggit_taggeditem.object_id = aldryn_newsblog_article.id AND
aldryn_newsblog_article.app_config_id = %d"""
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
query = """
SELECT (%s) as article_count, taggit_tag.*
FROM taggit_tag
""" % (subquery % (article_content_type.id, self.app_config.pk), )
raw_tags = list(Tag.objects.raw(query))
tags = [tag for tag in raw_tags if tag.article_count]
return sorted(tags, key=lambda x: x.article_count, reverse=True)
def __str__(self):
return ugettext('%s tags') % (self.app_config.get_app_title(), )
@receiver(post_save, dispatch_uid='article_update_search_data')
def update_search_data(sender, instance, **kwargs):
"""
Upon detecting changes in a plugin used in an Article's content
(PlaceholderField), update the article's search_index so that we can
perform simple searches even without Haystack, etc.
"""
is_cms_plugin = issubclass(instance.__class__, CMSPlugin)
if Article.update_search_on_save and is_cms_plugin:
placeholder = (getattr(instance, '_placeholder_cache', None) or
instance.placeholder)
if hasattr(placeholder, '_attached_model_cache'):
if placeholder._attached_model_cache == Article:
article = placeholder._attached_model_cache.objects.language(
instance.language).get(content=placeholder.pk)
article.search_data = article.get_search_data(instance.language)
article.save()
if ENABLE_REVERSION:
from aldryn_reversion.core import version_controlled_content
Article = version_controlled_content(Article, follow=['app_config'])
| 39.777385 | 117 | 0.647908 |
from __future__ import unicode_literals
import django.core.validators
from aldryn_apphooks_config.fields import AppHookConfigField
from aldryn_categories.fields import CategoryManyToManyField
from aldryn_categories.models import Category
from aldryn_newsblog.utils.utilities import get_valid_languages_from_request
from aldryn_people.models import Person
from aldryn_translation_tools.models import TranslatedAutoSlugifyMixin, TranslationHelperMixin
from cms.models.fields import PlaceholderField
from cms.models.pluginmodel import CMSPlugin
from cms.utils.i18n import get_current_language, get_redirect_on_fallback
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import connection, models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import override, ugettext
from djangocms_text_ckeditor.fields import HTMLField
from filer.fields.image import FilerImageField
from parler.models import TranslatableModel, TranslatedFields
from sortedm2m.fields import SortedManyToManyField
from taggit.managers import TaggableManager
from taggit.models import Tag
from .cms_appconfig import NewsBlogConfig
from .managers import RelatedManager
from .settings import ENABLE_REVERSION
from .utils import get_plugin_index_data, get_request, strip_tags
try:
from django.utils.encoding import force_unicode
except ImportError:
from django.utils.encoding import force_text as force_unicode
if settings.LANGUAGES:
LANGUAGE_CODES = [language[0] for language in settings.LANGUAGES]
elif settings.LANGUAGE:
LANGUAGE_CODES = [settings.LANGUAGE]
else:
raise ImproperlyConfigured(
'Neither LANGUAGES nor LANGUAGE was found in settings.')
SQL_NOW_FUNC = {
'mssql': 'GetDate()', 'mysql': 'NOW()', 'postgresql': 'now()',
'sqlite': 'CURRENT_TIMESTAMP', 'oracle': 'CURRENT_TIMESTAMP'
}[connection.vendor]
SQL_IS_TRUE = {
'mssql': '== TRUE', 'mysql': '= 1', 'postgresql': 'IS TRUE',
'sqlite': '== 1', 'oracle': 'IS TRUE'
}[connection.vendor]
class Article(TranslatedAutoSlugifyMixin,
TranslationHelperMixin,
TranslatableModel):
slug_source_field_name = 'title'
slug_default = _('untitled-article')
# whenever the article is saved or a plugin is saved
# on the article's content placeholder.
update_search_on_save = getattr(
settings,
'ALDRYN_NEWSBLOG_UPDATE_SEARCH_DATA_ON_SAVE',
False
)
translations = TranslatedFields(
title=models.CharField(_('title'), max_length=234),
slug=models.SlugField(
verbose_name=_('slug'),
max_length=255,
db_index=True,
blank=True,
help_text=_(
'Used in the URL. If changed, the URL will change. '
'Clear it to have it re-created automatically.'),
),
lead_in=HTMLField(
verbose_name=_('lead'), default='',
help_text=_(
'The lead gives the reader the main idea of the story, this '
'is useful in overviews, lists or as an introduction to your '
'article.'
),
blank=True,
),
meta_title=models.CharField(
max_length=255, verbose_name=_('meta title'),
blank=True, default=''),
meta_description=models.TextField(
verbose_name=_('meta description'), blank=True, default=''),
meta_keywords=models.TextField(
verbose_name=_('meta keywords'), blank=True, default=''),
meta={'unique_together': (('language_code', 'slug', ), )},
search_data=models.TextField(blank=True, editable=False)
)
content = PlaceholderField('newsblog_article_content',
related_name='newsblog_article_content')
author = models.ForeignKey(Person, null=True, blank=True,
verbose_name=_('author'), on_delete=models.SET_NULL)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('owner'), on_delete=models.PROTECT)
app_config = AppHookConfigField(NewsBlogConfig,
verbose_name=_('Apphook configuration'))
categories = CategoryManyToManyField('aldryn_categories.Category',
verbose_name=_('categories'),
blank=True)
publishing_date = models.DateTimeField(_('publishing date'),
default=now)
is_published = models.BooleanField(_('is published'), default=False,
db_index=True)
is_featured = models.BooleanField(_('is featured'), default=False,
db_index=True)
featured_image = FilerImageField(
verbose_name=_('featured image'),
null=True,
blank=True,
on_delete=models.SET_NULL,
)
tags = TaggableManager(blank=True)
# set "B relates to A" you immediately have also "A relates to B". It have
# to be forced to False because by default it's True if rel.to is "self":
related = SortedManyToManyField('self', verbose_name=_('related articles'),
blank=True, symmetrical=False)
objects = RelatedManager()
class Meta:
ordering = ['-publishing_date']
@property
def published(self):
return (self.is_published and self.publishing_date <= now())
@property
def future(self):
return (self.is_published and self.publishing_date > now())
def get_absolute_url(self, language=None):
if not language:
language = get_current_language()
kwargs = {}
permalink_type = self.app_config.permalink_type
if 'y' in permalink_type:
kwargs.update(year=self.publishing_date.year)
if 'm' in permalink_type:
kwargs.update(month="%02d" % self.publishing_date.month)
if 'd' in permalink_type:
kwargs.update(day="%02d" % self.publishing_date.day)
if 'i' in permalink_type:
kwargs.update(pk=self.pk)
if 's' in permalink_type:
slug, lang = self.known_translation_getter(
'slug', default=None, language_code=language)
if slug and lang:
site_id = getattr(settings, 'SITE_ID', None)
if get_redirect_on_fallback(language, site_id):
language = lang
kwargs.update(slug=slug)
if self.app_config and self.app_config.namespace:
namespace = '{0}:'.format(self.app_config.namespace)
else:
namespace = ''
with override(language):
return reverse('{0}article-detail'.format(namespace), kwargs=kwargs)
def get_search_data(self, language=None, request=None):
if not self.pk:
return ''
if language is None:
language = get_current_language()
if request is None:
request = get_request(language=language)
description = self.safe_translation_getter('lead_in', '')
text_bits = [strip_tags(description)]
for category in self.categories.all():
text_bits.append(
force_unicode(category.safe_translation_getter('name')))
for tag in self.tags.all():
text_bits.append(force_unicode(tag.name))
if self.content:
plugins = self.content.cmsplugin_set.filter(language=language)
for base_plugin in plugins:
plugin_text_content = ' '.join(
get_plugin_index_data(base_plugin, request))
text_bits.append(plugin_text_content)
return ' '.join(text_bits)
def save(self, *args, **kwargs):
if self.update_search_on_save:
self.search_data = self.get_search_data()
if self.app_config.create_authors and self.author is None:
self.author = Person.objects.get_or_create(
user=self.owner,
defaults={
'name': ' '.join((
self.owner.first_name,
self.owner.last_name,
)),
})[0]
super(Article, self).save(*args, **kwargs)
def __str__(self):
return self.safe_translation_getter('title', any_language=True)
class PluginEditModeMixin(object):
def get_edit_mode(self, request):
return (
hasattr(request, 'toolbar') and request.toolbar and
request.toolbar.edit_mode)
class AdjustableCacheModelMixin(models.Model):
cache_duration = models.PositiveSmallIntegerField(
default=0,
blank=False,
help_text=_(
"The maximum duration (in seconds) that this plugin's content "
"should be cached.")
)
class Meta:
abstract = True
class NewsBlogCMSPlugin(CMSPlugin):
# avoid reverse relation name clashes by not adding a related_name
# to the parent plugin
cmsplugin_ptr = models.OneToOneField(
CMSPlugin, related_name='+', parent_link=True, on_delete=models.CASCADE)
app_config = models.ForeignKey(NewsBlogConfig, verbose_name=_('Apphook configuration'), on_delete=models.PROTECT)
class Meta:
abstract = True
def copy_relations(self, old_instance):
self.app_config = old_instance.app_config
class NewsBlogArchivePlugin(PluginEditModeMixin, AdjustableCacheModelMixin,
NewsBlogCMSPlugin):
# NOTE: the PluginEditModeMixin is eventually used in the cmsplugin, not
# here in the model.
def __str__(self):
return ugettext('%s archive') % (self.app_config.get_app_title(), )
class NewsBlogArticleSearchPlugin(NewsBlogCMSPlugin):
max_articles = models.PositiveIntegerField(
_('max articles'), default=10,
validators=[django.core.validators.MinValueValidator(1)],
help_text=_('The maximum number of found articles display.')
)
def __str__(self):
return ugettext('%s archive') % (self.app_config.get_app_title(), )
class NewsBlogAuthorsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def get_authors(self, request):
# The basic subquery (for logged-in content managers in edit mode)
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article
WHERE
aldryn_newsblog_article.author_id =
aldryn_people_person.id AND
aldryn_newsblog_article.app_config_id = %d"""
# For other users, limit subquery to published articles
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
# Now, use this subquery in the construction of the main query.
query = """
SELECT (%s) as article_count, aldryn_people_person.*
FROM aldryn_people_person
""" % (subquery % (self.app_config.pk, ), )
raw_authors = list(Person.objects.raw(query))
authors = [author for author in raw_authors if author.article_count]
return sorted(authors, key=lambda x: x.article_count, reverse=True)
def __str__(self):
return ugettext('%s authors') % (self.app_config.get_app_title(), )
class NewsBlogCategoriesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def __str__(self):
return ugettext('%s categories') % (self.app_config.get_app_title(), )
def get_categories(self, request):
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article, aldryn_newsblog_article_categories
WHERE
aldryn_newsblog_article_categories.category_id =
aldryn_categories_category.id AND
aldryn_newsblog_article_categories.article_id =
aldryn_newsblog_article.id AND
aldryn_newsblog_article.app_config_id = %d
""" % (self.app_config.pk, )
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
query = """
SELECT (%s) as article_count, aldryn_categories_category.*
FROM aldryn_categories_category
""" % (subquery, )
raw_categories = list(Category.objects.raw(query))
categories = [
category for category in raw_categories if category.article_count]
return sorted(categories, key=lambda x: x.article_count, reverse=True)
class NewsBlogFeaturedArticlesPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
article_count = models.PositiveIntegerField(
default=1,
validators=[django.core.validators.MinValueValidator(1)],
help_text=_('The maximum number of featured articles display.')
)
def get_articles(self, request):
if not self.article_count:
return Article.objects.none()
queryset = Article.objects
if not self.get_edit_mode(request):
queryset = queryset.published()
languages = get_valid_languages_from_request(
self.app_config.namespace, request)
if self.language not in languages:
return queryset.none()
queryset = queryset.translated(*languages).filter(
app_config=self.app_config,
is_featured=True)
return queryset[:self.article_count]
def __str__(self):
if not self.pk:
return 'featured articles'
prefix = self.app_config.get_app_title()
if self.article_count == 1:
title = ugettext('featured article')
else:
title = ugettext('featured articles: %(count)s') % {
'count': self.article_count,
}
return '{0} {1}'.format(prefix, title)
class NewsBlogLatestArticlesPlugin(PluginEditModeMixin,
AdjustableCacheModelMixin,
NewsBlogCMSPlugin):
latest_articles = models.IntegerField(
default=5,
help_text=_('The maximum number of latest articles to display.')
)
exclude_featured = models.PositiveSmallIntegerField(
default=0,
blank=True,
help_text=_(
'The maximum number of featured articles to exclude from display. '
'E.g. for uses in combination with featured articles plugin.')
)
def get_articles(self, request):
queryset = Article.objects
featured_qs = Article.objects.all().filter(is_featured=True)
if not self.get_edit_mode(request):
queryset = queryset.published()
featured_qs = featured_qs.published()
languages = get_valid_languages_from_request(
self.app_config.namespace, request)
if self.language not in languages:
return queryset.none()
queryset = queryset.translated(*languages).filter(
app_config=self.app_config)
featured_qs = featured_qs.translated(*languages).filter(
app_config=self.app_config)
exclude_featured = featured_qs.values_list(
'pk', flat=True)[:self.exclude_featured]
queryset = queryset.exclude(pk__in=list(exclude_featured))
return queryset[:self.latest_articles]
def __str__(self):
return ugettext('%(app_title)s latest articles: %(latest_articles)s') % {
'app_title': self.app_config.get_app_title(),
'latest_articles': self.latest_articles,
}
class NewsBlogRelatedPlugin(PluginEditModeMixin, AdjustableCacheModelMixin,
CMSPlugin):
# NOTE: This one does NOT subclass NewsBlogCMSPlugin. This is because this
# plugin can really only be placed on the article detail view in an apphook.
cmsplugin_ptr = models.OneToOneField(
CMSPlugin, related_name='+', parent_link=True, on_delete=models.CASCADE)
def get_articles(self, article, request):
languages = get_valid_languages_from_request(
article.app_config.namespace, request)
if self.language not in languages:
return Article.objects.none()
qs = article.related.translated(*languages)
if not self.get_edit_mode(request):
qs = qs.published()
return qs
def __str__(self):
return ugettext('Related articles')
class NewsBlogTagsPlugin(PluginEditModeMixin, NewsBlogCMSPlugin):
def get_tags(self, request):
article_content_type = ContentType.objects.get_for_model(Article)
subquery = """
SELECT COUNT(*)
FROM aldryn_newsblog_article, taggit_taggeditem
WHERE
taggit_taggeditem.tag_id = taggit_tag.id AND
taggit_taggeditem.content_type_id = %d AND
taggit_taggeditem.object_id = aldryn_newsblog_article.id AND
aldryn_newsblog_article.app_config_id = %d"""
if not self.get_edit_mode(request):
subquery += """ AND
aldryn_newsblog_article.is_published %s AND
aldryn_newsblog_article.publishing_date <= %s
""" % (SQL_IS_TRUE, SQL_NOW_FUNC, )
query = """
SELECT (%s) as article_count, taggit_tag.*
FROM taggit_tag
""" % (subquery % (article_content_type.id, self.app_config.pk), )
raw_tags = list(Tag.objects.raw(query))
tags = [tag for tag in raw_tags if tag.article_count]
return sorted(tags, key=lambda x: x.article_count, reverse=True)
def __str__(self):
return ugettext('%s tags') % (self.app_config.get_app_title(), )
@receiver(post_save, dispatch_uid='article_update_search_data')
def update_search_data(sender, instance, **kwargs):
is_cms_plugin = issubclass(instance.__class__, CMSPlugin)
if Article.update_search_on_save and is_cms_plugin:
placeholder = (getattr(instance, '_placeholder_cache', None) or
instance.placeholder)
if hasattr(placeholder, '_attached_model_cache'):
if placeholder._attached_model_cache == Article:
article = placeholder._attached_model_cache.objects.language(
instance.language).get(content=placeholder.pk)
article.search_data = article.get_search_data(instance.language)
article.save()
if ENABLE_REVERSION:
from aldryn_reversion.core import version_controlled_content
Article = version_controlled_content(Article, follow=['app_config'])
| true | true |
f729bdf98d041be17618159f1292cff87ad80dce | 23,247 | py | Python | Application/ryu-lagopus-ext-lagopus-general-tunnel-ext/ryu/ofproto/nx_actions.py | okinawaopenlabs/SD-WAN | 5d8ed92620f07907b89f373f2d93f41e1a265268 | [
"Apache-2.0"
] | 9 | 2019-12-12T06:57:51.000Z | 2022-01-10T04:01:49.000Z | Application/ryu-lagopus-ext-lagopus-general-tunnel-ext/ryu/ofproto/nx_actions.py | okinawaopenlabs/SD-WAN | 5d8ed92620f07907b89f373f2d93f41e1a265268 | [
"Apache-2.0"
] | null | null | null | Application/ryu-lagopus-ext-lagopus-general-tunnel-ext/ryu/ofproto/nx_actions.py | okinawaopenlabs/SD-WAN | 5d8ed92620f07907b89f373f2d93f41e1a265268 | [
"Apache-2.0"
] | 1 | 2020-03-26T17:58:28.000Z | 2020-03-26T17:58:28.000Z | # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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 struct
from ryu import utils
from ryu.lib import type_desc
from ryu.ofproto import nicira_ext
from ryu.ofproto import ofproto_common
from ryu.lib.pack_utils import msg_pack_into
from ryu.ofproto.ofproto_parser import StringifyMixin
def generate(ofp_name, ofpp_name):
import sys
import string
import functools
ofp = sys.modules[ofp_name]
ofpp = sys.modules[ofpp_name]
class _NXFlowSpec(StringifyMixin):
_hdr_fmt_str = '!H' # 2 bit 0s, 1 bit src, 2 bit dst, 11 bit n_bits
_dst_type = None
_subclasses = {}
_TYPE = {
'nx-flow-spec-field': [
'src',
'dst',
]
}
def __init__(self, src, dst, n_bits):
self.src = src
self.dst = dst
self.n_bits = n_bits
@classmethod
def register(cls, subcls):
assert issubclass(subcls, cls)
assert subcls._dst_type not in cls._subclasses
cls._subclasses[subcls._dst_type] = subcls
@classmethod
def parse(cls, buf):
(hdr,) = struct.unpack_from(cls._hdr_fmt_str, buf, 0)
rest = buf[struct.calcsize(cls._hdr_fmt_str):]
if hdr == 0:
return None, rest # all-0 header is no-op for padding
src_type = (hdr >> 13) & 0x1
dst_type = (hdr >> 11) & 0x3
n_bits = hdr & 0x3ff
subcls = cls._subclasses[dst_type]
if src_type == 0: # subfield
src = cls._parse_subfield(rest)
rest = rest[6:]
elif src_type == 1: # immediate
src_len = (n_bits + 15) // 16 * 2
src_bin = rest[:src_len]
src = type_desc.IntDescr(size=src_len).to_user(src_bin)
rest = rest[src_len:]
if dst_type == 0: # match
dst = cls._parse_subfield(rest)
rest = rest[6:]
elif dst_type == 1: # load
dst = cls._parse_subfield(rest)
rest = rest[6:]
elif dst_type == 2: # output
dst = '' # empty
return subcls(src=src, dst=dst, n_bits=n_bits), rest
def serialize(self):
buf = bytearray()
if isinstance(self.src, tuple):
src_type = 0 # subfield
else:
src_type = 1 # immediate
# header
val = (src_type << 13) | (self._dst_type << 11) | self.n_bits
msg_pack_into(self._hdr_fmt_str, buf, 0, val)
# src
if src_type == 0: # subfield
buf += self._serialize_subfield(self.src)
elif src_type == 1: # immediate
src_len = (self.n_bits + 15) // 16 * 2
buf += type_desc.IntDescr(size=src_len).from_user(self.src)
# dst
if self._dst_type == 0: # match
buf += self._serialize_subfield(self.dst)
elif self._dst_type == 1: # load
buf += self._serialize_subfield(self.dst)
elif self._dst_type == 2: # output
pass # empty
return buf
@staticmethod
def _parse_subfield(buf):
(n, len) = ofp.oxm_parse_header(buf, 0)
assert len == 4 # only 4-bytes NXM/OXM are defined
field = ofp.oxm_to_user_header(n)
rest = buf[len:]
(ofs,) = struct.unpack_from('!H', rest, 0)
return (field, ofs)
@staticmethod
def _serialize_subfield(subfield):
(field, ofs) = subfield
buf = bytearray()
n = ofp.oxm_from_user_header(field)
ofp.oxm_serialize_header(n, buf, 0)
assert len(buf) == 4 # only 4-bytes NXM/OXM are defined
msg_pack_into('!H', buf, 4, ofs)
return buf
class NXFlowSpecMatch(_NXFlowSpec):
# Add a match criteria
# an example of the corresponding ovs-ofctl syntax:
# NXM_OF_VLAN_TCI[0..11]
_dst_type = 0
class NXFlowSpecLoad(_NXFlowSpec):
# Add NXAST_REG_LOAD actions
# an example of the corresponding ovs-ofctl syntax:
# NXM_OF_ETH_DST[]=NXM_OF_ETH_SRC[]
_dst_type = 1
class NXFlowSpecOutput(_NXFlowSpec):
# Add an OFPAT_OUTPUT action
# an example of the corresponding ovs-ofctl syntax:
# output:NXM_OF_IN_PORT[]
_dst_type = 2
def __init__(self, src, n_bits, dst=''):
assert dst == ''
super(NXFlowSpecOutput, self).__init__(src=src, dst=dst,
n_bits=n_bits)
class NXAction(ofpp.OFPActionExperimenter):
_fmt_str = '!H' # subtype
_subtypes = {}
_experimenter = ofproto_common.NX_EXPERIMENTER_ID
def __init__(self):
super(NXAction, self).__init__(experimenter=self._experimenter)
self.subtype = self._subtype
@classmethod
def parse(cls, buf):
fmt_str = NXAction._fmt_str
(subtype,) = struct.unpack_from(fmt_str, buf, 0)
subtype_cls = cls._subtypes.get(subtype)
rest = buf[struct.calcsize(fmt_str):]
if subtype_cls is None:
return NXActionUnknown(subtype, rest)
return subtype_cls.parse(rest)
def serialize(self, buf, offset):
super(NXAction, self).serialize(buf, offset)
msg_pack_into(NXAction._fmt_str,
buf,
offset + ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE,
self.subtype)
@classmethod
def register(cls, subtype_cls):
assert subtype_cls._subtype is not cls._subtypes
cls._subtypes[subtype_cls._subtype] = subtype_cls
class NXActionUnknown(NXAction):
def __init__(self, subtype, data=None,
type_=None, len_=None, experimenter=None):
self._subtype = subtype
super(NXActionUnknown, self).__init__()
self.data = data
@classmethod
def parse(cls, subtype, buf):
return cls(data=buf)
def serialize(self, buf, offset):
# fixup
data = self.data
if data is None:
data = bytearray()
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionUnknown, self).serialize(buf, offset)
buf += data
class NXActionRegMove(NXAction):
_subtype = nicira_ext.NXAST_REG_MOVE
_fmt_str = '!HHH' # n_bits, src_ofs, dst_ofs
# Followed by OXM fields (src, dst) and padding to 8 bytes boundary
_TYPE = {
'ascii': [
'src_field',
'dst_field',
]
}
def __init__(self, src_field, dst_field, n_bits, src_ofs=0, dst_ofs=0,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionRegMove, self).__init__()
self.n_bits = n_bits
self.src_ofs = src_ofs
self.dst_ofs = dst_ofs
self.src_field = src_field
self.dst_field = dst_field
@classmethod
def parse(cls, buf):
(n_bits, src_ofs, dst_ofs,) = struct.unpack_from(
NXActionRegMove._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionRegMove._fmt_str):]
# src field
(n, len) = ofp.oxm_parse_header(rest, 0)
src_field = ofp.oxm_to_user_header(n)
rest = rest[len:]
# dst field
(n, len) = ofp.oxm_parse_header(rest, 0)
dst_field = ofp.oxm_to_user_header(n)
rest = rest[len:]
# ignore padding
return cls(src_field, dst_field=dst_field, n_bits=n_bits,
src_ofs=src_ofs, dst_ofs=dst_ofs)
def serialize(self, buf, offset):
# fixup
data = bytearray()
msg_pack_into(NXActionRegMove._fmt_str, data, 0,
self.n_bits, self.src_ofs, self.dst_ofs)
# src field
n = ofp.oxm_from_user_header(self.src_field)
ofp.oxm_serialize_header(n, data, len(data))
# dst field
n = ofp.oxm_from_user_header(self.dst_field)
ofp.oxm_serialize_header(n, data, len(data))
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionRegMove, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionLearn(NXAction):
_subtype = nicira_ext.NXAST_LEARN
# idle_timeout, hard_timeout, priority, cookie, flags,
# table_id, pad, fin_idle_timeout, fin_hard_timeout
_fmt_str = '!HHHQHBxHH'
# Followed by flow_mod_specs
def __init__(self,
table_id,
specs,
idle_timeout=0,
hard_timeout=0,
priority=ofp.OFP_DEFAULT_PRIORITY,
cookie=0,
flags=0,
fin_idle_timeout=0,
fin_hard_timeout=0,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionLearn, self).__init__()
self.idle_timeout = idle_timeout
self.hard_timeout = hard_timeout
self.priority = priority
self.cookie = cookie
self.flags = flags
self.table_id = table_id
self.fin_idle_timeout = fin_idle_timeout
self.fin_hard_timeout = fin_hard_timeout
self.specs = specs
@classmethod
def parse(cls, buf):
(idle_timeout,
hard_timeout,
priority,
cookie,
flags,
table_id,
fin_idle_timeout,
fin_hard_timeout,) = struct.unpack_from(
NXActionLearn._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionLearn._fmt_str):]
# specs
specs = []
while len(rest) > 0:
spec, rest = _NXFlowSpec.parse(rest)
if spec is None:
continue
specs.append(spec)
return cls(idle_timeout=idle_timeout,
hard_timeout=hard_timeout,
priority=priority,
cookie=cookie,
flags=flags,
table_id=table_id,
fin_idle_timeout=fin_idle_timeout,
fin_hard_timeout=fin_hard_timeout,
specs=specs)
def serialize(self, buf, offset):
# fixup
data = bytearray()
msg_pack_into(NXActionLearn._fmt_str, data, 0,
self.idle_timeout,
self.hard_timeout,
self.priority,
self.cookie,
self.flags,
self.table_id,
self.fin_idle_timeout,
self.fin_hard_timeout)
for spec in self.specs:
data += spec.serialize()
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionLearn, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionConjunction(NXAction):
_subtype = nicira_ext.NXAST_CONJUNCTION
# clause, n_clauses, id
_fmt_str = '!BBI'
def __init__(self,
clause,
n_clauses,
id_,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionConjunction, self).__init__()
self.clause = clause
self.n_clauses = n_clauses
self.id = id_
@classmethod
def parse(cls, buf):
(clause,
n_clauses,
id_,) = struct.unpack_from(
NXActionConjunction._fmt_str, buf, 0)
return cls(clause, n_clauses, id_)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionConjunction._fmt_str, data, 0,
self.clause,
self.n_clauses,
self.id)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionConjunction, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionResubmitTable(NXAction):
_subtype = nicira_ext.NXAST_RESUBMIT_TABLE
# in_port, table_id
_fmt_str = '!HB3x'
def __init__(self,
in_port,
table_id,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionResubmitTable, self).__init__()
self.in_port = in_port
self.table_id = table_id
@classmethod
def parse(cls, buf):
(in_port,
table_id) = struct.unpack_from(
NXActionResubmitTable._fmt_str, buf, 0)
return cls(in_port, table_id)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionResubmitTable._fmt_str, data, 0,
self.in_port,
self.table_id)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionResubmitTable, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionCT(NXAction):
_subtype = nicira_ext.NXAST_CT
# flags, zone_src, zone_ofs_nbits (zone_imm), recirc_table,
# pad, alg
_fmt_str = '!HIHB3xH'
# Followed by actions
def __init__(self,
flags,
zone_src,
zone_ofs_nbits, # is zone_imm if zone_src == 0
recirc_table,
alg,
actions,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionCT, self).__init__()
self.flags = flags
self.zone_src = zone_src
self.zone_ofs_nbits = zone_ofs_nbits
self.recirc_table = recirc_table
self.alg = alg
self.actions = actions
@classmethod
def parse(cls, buf):
(flags,
zone_src,
zone_ofs_nbits,
recirc_table,
alg,) = struct.unpack_from(
NXActionCT._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionCT._fmt_str):]
# actions
actions = []
while len(rest) > 0:
action = ofpp.OFPAction.parser(rest, 0)
actions.append(action)
rest = rest[action.len:]
return cls(flags, zone_src, zone_ofs_nbits, recirc_table,
alg, actions)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionCT._fmt_str, data, 0,
self.flags,
self.zone_src,
self.zone_ofs_nbits,
self.recirc_table,
self.alg)
for a in self.actions:
a.serialize(data, len(data))
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionCT, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionNAT(NXAction):
_subtype = nicira_ext.NXAST_NAT
# pad, flags, range_present
_fmt_str = '!2xHH'
# Followed by optional parameters
_TYPE = {
'ascii': [
'range_ipv4_max',
'range_ipv4_min',
'range_ipv6_max',
'range_ipv6_min',
]
}
def __init__(self,
flags,
range_ipv4_min='',
range_ipv4_max='',
range_ipv6_min='',
range_ipv6_max='',
range_proto_min=None,
range_proto_max=None,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionNAT, self).__init__()
self.flags = flags
self.range_ipv4_min = range_ipv4_min
self.range_ipv4_max = range_ipv4_max
self.range_ipv6_min = range_ipv6_min
self.range_ipv6_max = range_ipv6_max
self.range_proto_min = range_proto_min
self.range_proto_max = range_proto_max
@classmethod
def parse(cls, buf):
(flags,
range_present) = struct.unpack_from(
NXActionNAT._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionNAT._fmt_str):]
# optional parameters
kwargs = dict()
if range_present & nicira_ext.NX_NAT_RANGE_IPV4_MIN:
kwargs['range_ipv4_min'] = type_desc.IPv4Addr.to_user(rest[:4])
rest = rest[4:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV4_MAX:
kwargs['range_ipv4_max'] = type_desc.IPv4Addr.to_user(rest[:4])
rest = rest[4:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV6_MIN:
kwargs['range_ipv6_min'] = (
type_desc.IPv6Addr.to_user(rest[:16]))
rest = rest[16:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV6_MAX:
kwargs['range_ipv6_max'] = (
type_desc.IPv6Addr.to_user(rest[:16]))
rest = rest[16:]
if range_present & NX_NAT_RANGE_PROTO_MIN:
kwargs['range_proto_min'] = type_desc.Int2.to_user(rest[:2])
rest = rest[2:]
if range_present & NX_NAT_RANGE_PROTO_MAX:
kwargs['range_proto_max'] = type_desc.Int2.to_user(rest[:2])
return cls(flags, **kwargs)
def serialize(self, buf, offset):
# Pack optional parameters first, as range_present needs
# to be calculated.
optional_data = b''
range_present = 0
if self.range_ipv4_min != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV4_MIN
optional_data += type_desc.IPv4Addr.from_user(
self.range_ipv4_min)
if self.range_ipv4_max != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV4_MAX
optional_data += type_desc.IPv4Addr.from_user(
self.range_ipv4_max)
if self.range_ipv6_min != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV6_MIN
optional_data += type_desc.IPv6Addr.from_user(
self.range_ipv6_min)
if self.range_ipv6_max != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV6_MAX
optional_data += type_desc.IPv6Addr.from_user(
self.range_ipv6_max)
if self.range_proto_min is not None:
range_present |= nicira_ext.NX_NAT_RANGE_PROTO_MIN
optional_data += type_desc.Int2.from_user(
self.range_proto_min)
if self.range_proto_max is not None:
range_present |= nicira_ext.NX_NAT_RANGE_PROTO_MAX
optional_data += type_desc.Int2.from_user(
self.range_proto_max)
data = bytearray()
msg_pack_into(NXActionNAT._fmt_str, data, 0,
self.flags,
range_present)
msg_pack_into('!%ds' % len(optional_data), data, len(data),
optional_data)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionNAT, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
def add_attr(k, v):
v.__module__ = ofpp.__name__ # Necessary for stringify stuff
setattr(ofpp, k, v)
add_attr('NXAction', NXAction)
add_attr('NXActionUnknown', NXActionUnknown)
classes = [
'NXActionRegMove',
'NXActionLearn',
'NXActionConjunction',
'NXActionResubmitTable',
'NXActionCT',
'NXActionNAT',
'_NXFlowSpec', # exported for testing
'NXFlowSpecMatch',
'NXFlowSpecLoad',
'NXFlowSpecOutput',
]
vars = locals()
for name in classes:
cls = vars[name]
add_attr(name, cls)
if issubclass(cls, NXAction):
NXAction.register(cls)
if issubclass(cls, _NXFlowSpec):
_NXFlowSpec.register(cls)
| 37.616505 | 79 | 0.534392 |
import struct
from ryu import utils
from ryu.lib import type_desc
from ryu.ofproto import nicira_ext
from ryu.ofproto import ofproto_common
from ryu.lib.pack_utils import msg_pack_into
from ryu.ofproto.ofproto_parser import StringifyMixin
def generate(ofp_name, ofpp_name):
import sys
import string
import functools
ofp = sys.modules[ofp_name]
ofpp = sys.modules[ofpp_name]
class _NXFlowSpec(StringifyMixin):
_hdr_fmt_str = '!H'
_dst_type = None
_subclasses = {}
_TYPE = {
'nx-flow-spec-field': [
'src',
'dst',
]
}
def __init__(self, src, dst, n_bits):
self.src = src
self.dst = dst
self.n_bits = n_bits
@classmethod
def register(cls, subcls):
assert issubclass(subcls, cls)
assert subcls._dst_type not in cls._subclasses
cls._subclasses[subcls._dst_type] = subcls
@classmethod
def parse(cls, buf):
(hdr,) = struct.unpack_from(cls._hdr_fmt_str, buf, 0)
rest = buf[struct.calcsize(cls._hdr_fmt_str):]
if hdr == 0:
return None, rest
src_type = (hdr >> 13) & 0x1
dst_type = (hdr >> 11) & 0x3
n_bits = hdr & 0x3ff
subcls = cls._subclasses[dst_type]
if src_type == 0:
src = cls._parse_subfield(rest)
rest = rest[6:]
elif src_type == 1:
src_len = (n_bits + 15) // 16 * 2
src_bin = rest[:src_len]
src = type_desc.IntDescr(size=src_len).to_user(src_bin)
rest = rest[src_len:]
if dst_type == 0:
dst = cls._parse_subfield(rest)
rest = rest[6:]
elif dst_type == 1:
dst = cls._parse_subfield(rest)
rest = rest[6:]
elif dst_type == 2:
dst = ''
return subcls(src=src, dst=dst, n_bits=n_bits), rest
def serialize(self):
buf = bytearray()
if isinstance(self.src, tuple):
src_type = 0
else:
src_type = 1
val = (src_type << 13) | (self._dst_type << 11) | self.n_bits
msg_pack_into(self._hdr_fmt_str, buf, 0, val)
if src_type == 0:
buf += self._serialize_subfield(self.src)
elif src_type == 1:
src_len = (self.n_bits + 15) // 16 * 2
buf += type_desc.IntDescr(size=src_len).from_user(self.src)
if self._dst_type == 0:
buf += self._serialize_subfield(self.dst)
elif self._dst_type == 1:
buf += self._serialize_subfield(self.dst)
elif self._dst_type == 2:
pass
return buf
@staticmethod
def _parse_subfield(buf):
(n, len) = ofp.oxm_parse_header(buf, 0)
assert len == 4
field = ofp.oxm_to_user_header(n)
rest = buf[len:]
(ofs,) = struct.unpack_from('!H', rest, 0)
return (field, ofs)
@staticmethod
def _serialize_subfield(subfield):
(field, ofs) = subfield
buf = bytearray()
n = ofp.oxm_from_user_header(field)
ofp.oxm_serialize_header(n, buf, 0)
assert len(buf) == 4
msg_pack_into('!H', buf, 4, ofs)
return buf
class NXFlowSpecMatch(_NXFlowSpec):
_dst_type = 0
class NXFlowSpecLoad(_NXFlowSpec):
_dst_type = 1
class NXFlowSpecOutput(_NXFlowSpec):
_dst_type = 2
def __init__(self, src, n_bits, dst=''):
assert dst == ''
super(NXFlowSpecOutput, self).__init__(src=src, dst=dst,
n_bits=n_bits)
class NXAction(ofpp.OFPActionExperimenter):
_fmt_str = '!H'
_subtypes = {}
_experimenter = ofproto_common.NX_EXPERIMENTER_ID
def __init__(self):
super(NXAction, self).__init__(experimenter=self._experimenter)
self.subtype = self._subtype
@classmethod
def parse(cls, buf):
fmt_str = NXAction._fmt_str
(subtype,) = struct.unpack_from(fmt_str, buf, 0)
subtype_cls = cls._subtypes.get(subtype)
rest = buf[struct.calcsize(fmt_str):]
if subtype_cls is None:
return NXActionUnknown(subtype, rest)
return subtype_cls.parse(rest)
def serialize(self, buf, offset):
super(NXAction, self).serialize(buf, offset)
msg_pack_into(NXAction._fmt_str,
buf,
offset + ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE,
self.subtype)
@classmethod
def register(cls, subtype_cls):
assert subtype_cls._subtype is not cls._subtypes
cls._subtypes[subtype_cls._subtype] = subtype_cls
class NXActionUnknown(NXAction):
def __init__(self, subtype, data=None,
type_=None, len_=None, experimenter=None):
self._subtype = subtype
super(NXActionUnknown, self).__init__()
self.data = data
@classmethod
def parse(cls, subtype, buf):
return cls(data=buf)
def serialize(self, buf, offset):
data = self.data
if data is None:
data = bytearray()
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionUnknown, self).serialize(buf, offset)
buf += data
class NXActionRegMove(NXAction):
_subtype = nicira_ext.NXAST_REG_MOVE
_fmt_str = '!HHH'
_TYPE = {
'ascii': [
'src_field',
'dst_field',
]
}
def __init__(self, src_field, dst_field, n_bits, src_ofs=0, dst_ofs=0,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionRegMove, self).__init__()
self.n_bits = n_bits
self.src_ofs = src_ofs
self.dst_ofs = dst_ofs
self.src_field = src_field
self.dst_field = dst_field
@classmethod
def parse(cls, buf):
(n_bits, src_ofs, dst_ofs,) = struct.unpack_from(
NXActionRegMove._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionRegMove._fmt_str):]
(n, len) = ofp.oxm_parse_header(rest, 0)
src_field = ofp.oxm_to_user_header(n)
rest = rest[len:]
(n, len) = ofp.oxm_parse_header(rest, 0)
dst_field = ofp.oxm_to_user_header(n)
rest = rest[len:]
return cls(src_field, dst_field=dst_field, n_bits=n_bits,
src_ofs=src_ofs, dst_ofs=dst_ofs)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionRegMove._fmt_str, data, 0,
self.n_bits, self.src_ofs, self.dst_ofs)
n = ofp.oxm_from_user_header(self.src_field)
ofp.oxm_serialize_header(n, data, len(data))
n = ofp.oxm_from_user_header(self.dst_field)
ofp.oxm_serialize_header(n, data, len(data))
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionRegMove, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionLearn(NXAction):
_subtype = nicira_ext.NXAST_LEARN
_fmt_str = '!HHHQHBxHH'
def __init__(self,
table_id,
specs,
idle_timeout=0,
hard_timeout=0,
priority=ofp.OFP_DEFAULT_PRIORITY,
cookie=0,
flags=0,
fin_idle_timeout=0,
fin_hard_timeout=0,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionLearn, self).__init__()
self.idle_timeout = idle_timeout
self.hard_timeout = hard_timeout
self.priority = priority
self.cookie = cookie
self.flags = flags
self.table_id = table_id
self.fin_idle_timeout = fin_idle_timeout
self.fin_hard_timeout = fin_hard_timeout
self.specs = specs
@classmethod
def parse(cls, buf):
(idle_timeout,
hard_timeout,
priority,
cookie,
flags,
table_id,
fin_idle_timeout,
fin_hard_timeout,) = struct.unpack_from(
NXActionLearn._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionLearn._fmt_str):]
specs = []
while len(rest) > 0:
spec, rest = _NXFlowSpec.parse(rest)
if spec is None:
continue
specs.append(spec)
return cls(idle_timeout=idle_timeout,
hard_timeout=hard_timeout,
priority=priority,
cookie=cookie,
flags=flags,
table_id=table_id,
fin_idle_timeout=fin_idle_timeout,
fin_hard_timeout=fin_hard_timeout,
specs=specs)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionLearn._fmt_str, data, 0,
self.idle_timeout,
self.hard_timeout,
self.priority,
self.cookie,
self.flags,
self.table_id,
self.fin_idle_timeout,
self.fin_hard_timeout)
for spec in self.specs:
data += spec.serialize()
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionLearn, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionConjunction(NXAction):
_subtype = nicira_ext.NXAST_CONJUNCTION
_fmt_str = '!BBI'
def __init__(self,
clause,
n_clauses,
id_,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionConjunction, self).__init__()
self.clause = clause
self.n_clauses = n_clauses
self.id = id_
@classmethod
def parse(cls, buf):
(clause,
n_clauses,
id_,) = struct.unpack_from(
NXActionConjunction._fmt_str, buf, 0)
return cls(clause, n_clauses, id_)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionConjunction._fmt_str, data, 0,
self.clause,
self.n_clauses,
self.id)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionConjunction, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionResubmitTable(NXAction):
_subtype = nicira_ext.NXAST_RESUBMIT_TABLE
_fmt_str = '!HB3x'
def __init__(self,
in_port,
table_id,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionResubmitTable, self).__init__()
self.in_port = in_port
self.table_id = table_id
@classmethod
def parse(cls, buf):
(in_port,
table_id) = struct.unpack_from(
NXActionResubmitTable._fmt_str, buf, 0)
return cls(in_port, table_id)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionResubmitTable._fmt_str, data, 0,
self.in_port,
self.table_id)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionResubmitTable, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionCT(NXAction):
_subtype = nicira_ext.NXAST_CT
_fmt_str = '!HIHB3xH'
def __init__(self,
flags,
zone_src,
zone_ofs_nbits,
recirc_table,
alg,
actions,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionCT, self).__init__()
self.flags = flags
self.zone_src = zone_src
self.zone_ofs_nbits = zone_ofs_nbits
self.recirc_table = recirc_table
self.alg = alg
self.actions = actions
@classmethod
def parse(cls, buf):
(flags,
zone_src,
zone_ofs_nbits,
recirc_table,
alg,) = struct.unpack_from(
NXActionCT._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionCT._fmt_str):]
actions = []
while len(rest) > 0:
action = ofpp.OFPAction.parser(rest, 0)
actions.append(action)
rest = rest[action.len:]
return cls(flags, zone_src, zone_ofs_nbits, recirc_table,
alg, actions)
def serialize(self, buf, offset):
data = bytearray()
msg_pack_into(NXActionCT._fmt_str, data, 0,
self.flags,
self.zone_src,
self.zone_ofs_nbits,
self.recirc_table,
self.alg)
for a in self.actions:
a.serialize(data, len(data))
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionCT, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
class NXActionNAT(NXAction):
_subtype = nicira_ext.NXAST_NAT
_fmt_str = '!2xHH'
_TYPE = {
'ascii': [
'range_ipv4_max',
'range_ipv4_min',
'range_ipv6_max',
'range_ipv6_min',
]
}
def __init__(self,
flags,
range_ipv4_min='',
range_ipv4_max='',
range_ipv6_min='',
range_ipv6_max='',
range_proto_min=None,
range_proto_max=None,
type_=None, len_=None, experimenter=None, subtype=None):
super(NXActionNAT, self).__init__()
self.flags = flags
self.range_ipv4_min = range_ipv4_min
self.range_ipv4_max = range_ipv4_max
self.range_ipv6_min = range_ipv6_min
self.range_ipv6_max = range_ipv6_max
self.range_proto_min = range_proto_min
self.range_proto_max = range_proto_max
@classmethod
def parse(cls, buf):
(flags,
range_present) = struct.unpack_from(
NXActionNAT._fmt_str, buf, 0)
rest = buf[struct.calcsize(NXActionNAT._fmt_str):]
kwargs = dict()
if range_present & nicira_ext.NX_NAT_RANGE_IPV4_MIN:
kwargs['range_ipv4_min'] = type_desc.IPv4Addr.to_user(rest[:4])
rest = rest[4:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV4_MAX:
kwargs['range_ipv4_max'] = type_desc.IPv4Addr.to_user(rest[:4])
rest = rest[4:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV6_MIN:
kwargs['range_ipv6_min'] = (
type_desc.IPv6Addr.to_user(rest[:16]))
rest = rest[16:]
if range_present & nicira_ext.NX_NAT_RANGE_IPV6_MAX:
kwargs['range_ipv6_max'] = (
type_desc.IPv6Addr.to_user(rest[:16]))
rest = rest[16:]
if range_present & NX_NAT_RANGE_PROTO_MIN:
kwargs['range_proto_min'] = type_desc.Int2.to_user(rest[:2])
rest = rest[2:]
if range_present & NX_NAT_RANGE_PROTO_MAX:
kwargs['range_proto_max'] = type_desc.Int2.to_user(rest[:2])
return cls(flags, **kwargs)
def serialize(self, buf, offset):
optional_data = b''
range_present = 0
if self.range_ipv4_min != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV4_MIN
optional_data += type_desc.IPv4Addr.from_user(
self.range_ipv4_min)
if self.range_ipv4_max != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV4_MAX
optional_data += type_desc.IPv4Addr.from_user(
self.range_ipv4_max)
if self.range_ipv6_min != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV6_MIN
optional_data += type_desc.IPv6Addr.from_user(
self.range_ipv6_min)
if self.range_ipv6_max != '':
range_present |= nicira_ext.NX_NAT_RANGE_IPV6_MAX
optional_data += type_desc.IPv6Addr.from_user(
self.range_ipv6_max)
if self.range_proto_min is not None:
range_present |= nicira_ext.NX_NAT_RANGE_PROTO_MIN
optional_data += type_desc.Int2.from_user(
self.range_proto_min)
if self.range_proto_max is not None:
range_present |= nicira_ext.NX_NAT_RANGE_PROTO_MAX
optional_data += type_desc.Int2.from_user(
self.range_proto_max)
data = bytearray()
msg_pack_into(NXActionNAT._fmt_str, data, 0,
self.flags,
range_present)
msg_pack_into('!%ds' % len(optional_data), data, len(data),
optional_data)
payload_offset = (
ofp.OFP_ACTION_EXPERIMENTER_HEADER_SIZE +
struct.calcsize(NXAction._fmt_str)
)
self.len = utils.round_up(payload_offset + len(data), 8)
super(NXActionNAT, self).serialize(buf, offset)
msg_pack_into('!%ds' % len(data), buf, offset + payload_offset,
bytes(data))
def add_attr(k, v):
v.__module__ = ofpp.__name__
setattr(ofpp, k, v)
add_attr('NXAction', NXAction)
add_attr('NXActionUnknown', NXActionUnknown)
classes = [
'NXActionRegMove',
'NXActionLearn',
'NXActionConjunction',
'NXActionResubmitTable',
'NXActionCT',
'NXActionNAT',
'_NXFlowSpec',
'NXFlowSpecMatch',
'NXFlowSpecLoad',
'NXFlowSpecOutput',
]
vars = locals()
for name in classes:
cls = vars[name]
add_attr(name, cls)
if issubclass(cls, NXAction):
NXAction.register(cls)
if issubclass(cls, _NXFlowSpec):
_NXFlowSpec.register(cls)
| true | true |
f729be0517618aa568e3a9d14afc7493ca0dffac | 669 | py | Python | socialviz.py | pgimalac/socialviz | 51555b2c18751c6a3f678ef78a1bbfb9c462a438 | [
"MIT"
] | null | null | null | socialviz.py | pgimalac/socialviz | 51555b2c18751c6a3f678ef78a1bbfb9c462a438 | [
"MIT"
] | null | null | null | socialviz.py | pgimalac/socialviz | 51555b2c18751c6a3f678ef78a1bbfb9c462a438 | [
"MIT"
] | null | null | null | import argparse
from readers import generics, facebook, telegram, discord
from visualization import visualization as viz
parser = argparse.ArgumentParser(
description='Reads messages from various social medias and generates plots.'
)
# Add command line parameters
generics.init(parser)
facebook.init(parser)
telegram.init(parser)
discord.init(parser)
viz.init(parser)
# Parse
args = parser.parse_args()
values = vars(args)
# Init message list
msgs = []
# Run
facebook.parse(msgs, values)
telegram.parse(msgs, values)
discord.parse(msgs, values)
# Generate full dataframe with helper columns
df = generics.df_from_list(msgs)
# Display
viz.display(df, values)
| 20.272727 | 80 | 0.778774 | import argparse
from readers import generics, facebook, telegram, discord
from visualization import visualization as viz
parser = argparse.ArgumentParser(
description='Reads messages from various social medias and generates plots.'
)
generics.init(parser)
facebook.init(parser)
telegram.init(parser)
discord.init(parser)
viz.init(parser)
args = parser.parse_args()
values = vars(args)
msgs = []
facebook.parse(msgs, values)
telegram.parse(msgs, values)
discord.parse(msgs, values)
df = generics.df_from_list(msgs)
viz.display(df, values)
| true | true |
f729bf9dd75a0bd3e39cba554a42ce2e0be1da96 | 6,616 | py | Python | python/comparatist/utils/gsl.py | tkf/comparatist | 44f30077857fc96cb77539f3fe0a7e8112f86c82 | [
"MIT"
] | null | null | null | python/comparatist/utils/gsl.py | tkf/comparatist | 44f30077857fc96cb77539f3fe0a7e8112f86c82 | [
"MIT"
] | null | null | null | python/comparatist/utils/gsl.py | tkf/comparatist | 44f30077857fc96cb77539f3fe0a7e8112f86c82 | [
"MIT"
] | null | null | null | import ctypes
from ctypes import (POINTER, c_char_p, c_size_t, c_int, c_long, c_ulong,
c_double, c_void_p)
from ctypes.util import find_library
class _c_gsl_rng_type(ctypes.Structure):
_fields_ = [('name', c_char_p),
('max', c_long),
('min', c_size_t),
('__set', c_void_p),
('__get', c_void_p),
('__get_double', c_void_p),
]
_c_gsl_rng_type_p = POINTER(_c_gsl_rng_type)
class _c_gsl_rng(ctypes.Structure):
_fields_ = [('type', _c_gsl_rng_type_p),
('state', c_void_p)]
_c_gsl_rng_p = POINTER(_c_gsl_rng)
class _GSLFuncLoader(object):
# see: http://code.activestate.com/recipes/576549-gsl-with-python3/
gslcblas = ctypes.CDLL(find_library('gslcblas'), mode=ctypes.RTLD_GLOBAL)
gsl = ctypes.CDLL(find_library('gsl'))
def _load_1(self, name, argtypes=None, restype=None):
func = getattr(self.gsl, name)
if argtypes is not None:
func.argtypes = argtypes
if restype is not None:
func.restype = restype
setattr(self, name, func)
return func
def _load(self, name, argtypes=None, restype=None):
if isinstance(name, str):
return self._load_1(name, argtypes, restype)
else:
try:
return [self._load_1(n, argtypes, restype) for n in name]
except TypeError:
raise ValueError('name=%r should be a string or iterative '
'of string' % name)
func = _GSLFuncLoader()
func._load('gsl_strerror', [c_int], c_char_p)
func._load('gsl_rng_alloc', [_c_gsl_rng_type_p], _c_gsl_rng_p)
func._load('gsl_rng_set', [_c_gsl_rng_p, c_ulong])
func._load('gsl_rng_free', [_c_gsl_rng_p])
func._load('gsl_rng_types_setup',
restype=c_void_p) # POINTER(_c_gsl_rng_p)
func._load('gsl_rng_state', [_c_gsl_rng_p], c_void_p)
func._load('gsl_rng_size', [_c_gsl_rng_p], c_size_t)
func._load(['gsl_ran_gaussian',
'gsl_ran_gaussian_ziggurat',
'gsl_ran_gaussian_ratio_method'],
[_c_gsl_rng_p, c_double],
c_double)
gsl_strerror = func.gsl_strerror
def _get_gsl_rng_type_p_dict():
"""
Get all ``gsl_rng_type`` as dict which has pointer to each object
This is equivalent to C code bellow which is from GSL document:
.. sourcecode:: c
const gsl_rng_type **t, **t0;
t0 = gsl_rng_types_setup ();
for (t = t0; *t != 0; t++)
{
printf ("%s\n", (*t)->name); /* instead, store t to dict */
}
"""
t = func.gsl_rng_types_setup()
dt = ctypes.sizeof(c_void_p)
dct = {}
while True:
a = c_void_p.from_address(t)
if a.value is None:
break
name = c_char_p.from_address(a.value).value
name = name.decode() # for Python 3 (bytes to str)
dct[name] = ctypes.cast(a, _c_gsl_rng_type_p)
t += dt
return dct
class gsl_rng(object):
_gsl_rng_alloc = func.gsl_rng_alloc
_gsl_rng_set = func.gsl_rng_set
_gsl_rng_free = func.gsl_rng_free
_gsl_rng_type_p_dict = _get_gsl_rng_type_p_dict()
_ctype_ = _c_gsl_rng_p # for railgun
def __init__(self, seed=None, name='mt19937'):
self._gsl_rng_name = name
self._gsl_rng_type_p = self._gsl_rng_type_p_dict[name]
self._cdata_ = self._gsl_rng_alloc(self._gsl_rng_type_p)
# the name '_cdata_' is for railgun
if seed is not None:
self.set(seed)
def __setstate__(self, data):
(attrs, state) = data
self.__init__(name=attrs.pop('_gsl_rng_name'))
self.__dict__.update(attrs)
self.set_state(state)
def __getstate__(self):
attrs = self.__dict__.copy()
del attrs['_gsl_rng_type_p']
del attrs['_cdata_']
return (attrs, self.get_state())
def __copy__(self):
clone = self.__class__.__new__(self.__class__)
clone.__dict__.update(self.__dict__)
return clone
def __del__(self):
self._gsl_rng_free(self._cdata_)
def set(self, seed):
self._gsl_rng_set(self._cdata_, seed)
_gsl_ran_gaussian = {
'': func.gsl_ran_gaussian,
'ziggurat': func.gsl_ran_gaussian_ziggurat,
'ratio_method': func.gsl_ran_gaussian_ratio_method,
}
def ran_gaussian(self, sigma=1.0, method=''):
return self._gsl_ran_gaussian[method](self._cdata_, sigma)
def get_state(self):
"""
Return state of the random number generator as a byte string.
"""
ptr = func.gsl_rng_state(self._cdata_)
size = func.gsl_rng_size(self._cdata_)
buf = ctypes.create_string_buffer(size)
ctypes.memmove(buf, ptr, size)
return buf.raw
def set_state(self, state):
"""
Set state returned by :meth:`get_state`.
"""
ptr = func.gsl_rng_state(self._cdata_)
size = func.gsl_rng_size(self._cdata_)
given_size = len(state)
# Pass size explicitly, otherwise it will create a buffer with
# extra NULL terminator in it:
buf = ctypes.create_string_buffer(state, given_size)
if given_size != size:
raise ValueError(
'Trying to set incompatible length of state. '
'Size of the given state is {0} while {1} is required. '
.format(given_size, size))
ctypes.memmove(ptr, buf, size)
def plot_gaussian(method='', sigma=1, show=True):
import pylab
rng = gsl_rng()
pylab.hist(
[rng.ran_gaussian(method=method, sigma=sigma) for i in range(10000)],
bins=100, normed=True)
if show:
pylab.show()
def print_error_codes():
for i in range(1000):
error_message = gsl_strerror(i)
if error_message != 'unknown error code':
print('% 4d: "%s"' % (i, error_message))
def main():
import sys
cmd2func = dict(
print_error_codes=print_error_codes,
plot_gaussian=plot_gaussian,
)
if len(sys.argv) == 0:
print('Please specify command or code to execute\n')
for name in sorted(cmd2func):
print(name)
else:
(cmd,) = sys.argv[1:]
if cmd in cmd2func:
print("Calling function: %s" % cmd)
cmd2func[cmd]()
else:
print("Executing code: %s" % cmd)
ret = eval(cmd, globals())
if ret is not None:
print("Returned %r" % ret)
if __name__ == '__main__':
main()
| 30.62963 | 77 | 0.603083 | import ctypes
from ctypes import (POINTER, c_char_p, c_size_t, c_int, c_long, c_ulong,
c_double, c_void_p)
from ctypes.util import find_library
class _c_gsl_rng_type(ctypes.Structure):
_fields_ = [('name', c_char_p),
('max', c_long),
('min', c_size_t),
('__set', c_void_p),
('__get', c_void_p),
('__get_double', c_void_p),
]
_c_gsl_rng_type_p = POINTER(_c_gsl_rng_type)
class _c_gsl_rng(ctypes.Structure):
_fields_ = [('type', _c_gsl_rng_type_p),
('state', c_void_p)]
_c_gsl_rng_p = POINTER(_c_gsl_rng)
class _GSLFuncLoader(object):
gslcblas = ctypes.CDLL(find_library('gslcblas'), mode=ctypes.RTLD_GLOBAL)
gsl = ctypes.CDLL(find_library('gsl'))
def _load_1(self, name, argtypes=None, restype=None):
func = getattr(self.gsl, name)
if argtypes is not None:
func.argtypes = argtypes
if restype is not None:
func.restype = restype
setattr(self, name, func)
return func
def _load(self, name, argtypes=None, restype=None):
if isinstance(name, str):
return self._load_1(name, argtypes, restype)
else:
try:
return [self._load_1(n, argtypes, restype) for n in name]
except TypeError:
raise ValueError('name=%r should be a string or iterative '
'of string' % name)
func = _GSLFuncLoader()
func._load('gsl_strerror', [c_int], c_char_p)
func._load('gsl_rng_alloc', [_c_gsl_rng_type_p], _c_gsl_rng_p)
func._load('gsl_rng_set', [_c_gsl_rng_p, c_ulong])
func._load('gsl_rng_free', [_c_gsl_rng_p])
func._load('gsl_rng_types_setup',
restype=c_void_p)
func._load('gsl_rng_state', [_c_gsl_rng_p], c_void_p)
func._load('gsl_rng_size', [_c_gsl_rng_p], c_size_t)
func._load(['gsl_ran_gaussian',
'gsl_ran_gaussian_ziggurat',
'gsl_ran_gaussian_ratio_method'],
[_c_gsl_rng_p, c_double],
c_double)
gsl_strerror = func.gsl_strerror
def _get_gsl_rng_type_p_dict():
t = func.gsl_rng_types_setup()
dt = ctypes.sizeof(c_void_p)
dct = {}
while True:
a = c_void_p.from_address(t)
if a.value is None:
break
name = c_char_p.from_address(a.value).value
name = name.decode()
dct[name] = ctypes.cast(a, _c_gsl_rng_type_p)
t += dt
return dct
class gsl_rng(object):
_gsl_rng_alloc = func.gsl_rng_alloc
_gsl_rng_set = func.gsl_rng_set
_gsl_rng_free = func.gsl_rng_free
_gsl_rng_type_p_dict = _get_gsl_rng_type_p_dict()
_ctype_ = _c_gsl_rng_p
def __init__(self, seed=None, name='mt19937'):
self._gsl_rng_name = name
self._gsl_rng_type_p = self._gsl_rng_type_p_dict[name]
self._cdata_ = self._gsl_rng_alloc(self._gsl_rng_type_p)
if seed is not None:
self.set(seed)
def __setstate__(self, data):
(attrs, state) = data
self.__init__(name=attrs.pop('_gsl_rng_name'))
self.__dict__.update(attrs)
self.set_state(state)
def __getstate__(self):
attrs = self.__dict__.copy()
del attrs['_gsl_rng_type_p']
del attrs['_cdata_']
return (attrs, self.get_state())
def __copy__(self):
clone = self.__class__.__new__(self.__class__)
clone.__dict__.update(self.__dict__)
return clone
def __del__(self):
self._gsl_rng_free(self._cdata_)
def set(self, seed):
self._gsl_rng_set(self._cdata_, seed)
_gsl_ran_gaussian = {
'': func.gsl_ran_gaussian,
'ziggurat': func.gsl_ran_gaussian_ziggurat,
'ratio_method': func.gsl_ran_gaussian_ratio_method,
}
def ran_gaussian(self, sigma=1.0, method=''):
return self._gsl_ran_gaussian[method](self._cdata_, sigma)
def get_state(self):
ptr = func.gsl_rng_state(self._cdata_)
size = func.gsl_rng_size(self._cdata_)
buf = ctypes.create_string_buffer(size)
ctypes.memmove(buf, ptr, size)
return buf.raw
def set_state(self, state):
ptr = func.gsl_rng_state(self._cdata_)
size = func.gsl_rng_size(self._cdata_)
given_size = len(state)
buf = ctypes.create_string_buffer(state, given_size)
if given_size != size:
raise ValueError(
'Trying to set incompatible length of state. '
'Size of the given state is {0} while {1} is required. '
.format(given_size, size))
ctypes.memmove(ptr, buf, size)
def plot_gaussian(method='', sigma=1, show=True):
import pylab
rng = gsl_rng()
pylab.hist(
[rng.ran_gaussian(method=method, sigma=sigma) for i in range(10000)],
bins=100, normed=True)
if show:
pylab.show()
def print_error_codes():
for i in range(1000):
error_message = gsl_strerror(i)
if error_message != 'unknown error code':
print('% 4d: "%s"' % (i, error_message))
def main():
import sys
cmd2func = dict(
print_error_codes=print_error_codes,
plot_gaussian=plot_gaussian,
)
if len(sys.argv) == 0:
print('Please specify command or code to execute\n')
for name in sorted(cmd2func):
print(name)
else:
(cmd,) = sys.argv[1:]
if cmd in cmd2func:
print("Calling function: %s" % cmd)
cmd2func[cmd]()
else:
print("Executing code: %s" % cmd)
ret = eval(cmd, globals())
if ret is not None:
print("Returned %r" % ret)
if __name__ == '__main__':
main()
| true | true |
f729c050da4de0e6ccf5e72bd5c5b29a4dc7c52f | 1,194 | py | Python | backend/__init__.py | fdgogogo/fangs | bfad4423893f0f1d9793ff6402d63c65e1d88d66 | [
"MIT"
] | 1 | 2015-09-05T10:16:48.000Z | 2015-09-05T10:16:48.000Z | backend/__init__.py | fdgogogo/fangs | bfad4423893f0f1d9793ff6402d63c65e1d88d66 | [
"MIT"
] | null | null | null | backend/__init__.py | fdgogogo/fangs | bfad4423893f0f1d9793ff6402d63c65e1d88d66 | [
"MIT"
] | null | null | null | from flask.ext.restless import APIManager
from flask.ext.security import SQLAlchemyUserDatastore, Security
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
from flask.ext.cors import CORS
app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)
import backend.auth.models
user_datastore = SQLAlchemyUserDatastore(
db,
backend.auth.models.User,
backend.auth.models.Role)
security = Security(app, user_datastore)
import backend.blog
import backend.blog.models
blog_post_api_blueprint = api_manager.create_api(
backend.blog.models.BlogPost,
primary_key='slug',
results_per_page=10,
url_prefix='/api/v1',
methods=['GET'])
blog_comment_api_blueprint = api_manager.create_api(
backend.blog.models.BlogComment,
results_per_page=10,
url_prefix='/api/v1',
methods=['GET', 'POST', ])
blog_category_api_blueprint = api_manager.create_api(
backend.blog.models.BlogCategory,
results_per_page=100,
primary_key='slug',
exclude_columns=['posts'],
url_prefix='/api/v1',
methods=['GET', ])
app.register_blueprint(blog.blog)
| 24.367347 | 64 | 0.752931 | from flask.ext.restless import APIManager
from flask.ext.security import SQLAlchemyUserDatastore, Security
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
from flask.ext.cors import CORS
app = Flask(__name__)
app.config.from_pyfile('config.py')
CORS(app)
db = SQLAlchemy(app)
api_manager = APIManager(app, flask_sqlalchemy_db=db)
import backend.auth.models
user_datastore = SQLAlchemyUserDatastore(
db,
backend.auth.models.User,
backend.auth.models.Role)
security = Security(app, user_datastore)
import backend.blog
import backend.blog.models
blog_post_api_blueprint = api_manager.create_api(
backend.blog.models.BlogPost,
primary_key='slug',
results_per_page=10,
url_prefix='/api/v1',
methods=['GET'])
blog_comment_api_blueprint = api_manager.create_api(
backend.blog.models.BlogComment,
results_per_page=10,
url_prefix='/api/v1',
methods=['GET', 'POST', ])
blog_category_api_blueprint = api_manager.create_api(
backend.blog.models.BlogCategory,
results_per_page=100,
primary_key='slug',
exclude_columns=['posts'],
url_prefix='/api/v1',
methods=['GET', ])
app.register_blueprint(blog.blog)
| true | true |
f729c187761bac06850de8bf92eac1e4f1ab8bca | 236 | py | Python | Numeric Patterns/numericpattern13.py | Daksh777/Python-PatternHouse | ab801631c2e1f5ed3cc12a26c959d41a5e51273d | [
"MIT"
] | 8 | 2021-03-20T11:26:35.000Z | 2022-01-05T02:39:15.000Z | Numeric Patterns/numericpattern13.py | Daksh777/Python-PatternHouse | ab801631c2e1f5ed3cc12a26c959d41a5e51273d | [
"MIT"
] | 851 | 2021-04-02T09:08:15.000Z | 2022-01-12T11:26:57.000Z | Numeric Patterns/numericpattern13.py | Daksh777/Python-PatternHouse | ab801631c2e1f5ed3cc12a26c959d41a5e51273d | [
"MIT"
] | 15 | 2021-04-13T06:10:17.000Z | 2022-01-08T05:07:21.000Z | # Numeric Pattern 12
"""
Desired Output:
5 10 15 20 25
4 9 14 19 24
3 8 13 18 23
2 7 12 17 22
1 6 11 16 21
"""
x = 5
for i in range(5, 0, -1):
j = i
for _ in range(5):
print(j, end=" ")
j += x
print()
| 11.8 | 25 | 0.491525 |
x = 5
for i in range(5, 0, -1):
j = i
for _ in range(5):
print(j, end=" ")
j += x
print()
| true | true |
f729c2f5bc2a95ac241b9a3afada133a82467079 | 306 | py | Python | files_manager/urls.py | alias454/saltshaker | d32cdd0aa13098bdc77bb3abd4a92c10fa517dd1 | [
"Apache-2.0"
] | 343 | 2015-12-31T06:33:03.000Z | 2022-02-18T17:56:30.000Z | files_manager/urls.py | whistle-china/OneOps-zgd | 2c06eed517dc05d2cc530064e744a92f04c7d063 | [
"Apache-2.0"
] | 35 | 2015-12-08T02:51:19.000Z | 2020-06-08T08:56:52.000Z | files_manager/urls.py | whistle-china/OneOps-zgd | 2c06eed517dc05d2cc530064e744a92f04c7d063 | [
"Apache-2.0"
] | 175 | 2016-01-20T10:06:37.000Z | 2022-01-07T03:27:17.000Z | # -*- coding:utf-8 -*-
#!/bin/env python
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^manage_file', views.manage_file,name='manage_file'),
url(r'^del_file', views.del_file,name='del_file'),
url(r'^upload_file', views.upload_file,name='upload_file'),
]
| 25.5 | 63 | 0.689542 |
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^manage_file', views.manage_file,name='manage_file'),
url(r'^del_file', views.del_file,name='del_file'),
url(r'^upload_file', views.upload_file,name='upload_file'),
]
| true | true |
f729c3450b30a9dead4c1eeb84b8ddfbdc2de0ab | 3,216 | py | Python | cloudify_azure/resources/network/networksecurityrule.py | ahmadiesa-abu/cloudify-azure-plugin | b2ac5a246335ff45ce0cdd332ea9c8e74e7c8552 | [
"Apache-2.0"
] | null | null | null | cloudify_azure/resources/network/networksecurityrule.py | ahmadiesa-abu/cloudify-azure-plugin | b2ac5a246335ff45ce0cdd332ea9c8e74e7c8552 | [
"Apache-2.0"
] | null | null | null | cloudify_azure/resources/network/networksecurityrule.py | ahmadiesa-abu/cloudify-azure-plugin | b2ac5a246335ff45ce0cdd332ea9c8e74e7c8552 | [
"Apache-2.0"
] | null | null | null | # #######
# Copyright (c) 2016-2020 Cloudify Platform Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
resources.network.NetworkSecurityRule
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Microsoft Azure Network Security Rule interface
"""
# Node properties and logger
from cloudify import ctx
# Base resource class
from cloudify_azure.resources.base import Resource
# Lifecycle operation decorator
from cloudify.decorators import operation
# Logger, API version
from cloudify_azure import (constants, utils)
class NetworkSecurityRule(Resource):
"""
Microsoft Azure Network Security Rule interface
.. warning::
This interface should only be instantiated from
within a Cloudify Lifecycle Operation
:param string resource_group: Name of the parent Resource Group
:param string virtual_network: Name of the parent Virtual Network
:param string api_version: API version to use for all requests
:param `logging.Logger` logger:
Parent logger for the class to use. Defaults to `ctx.logger`
"""
def __init__(self,
resource_group=None,
network_security_group=None,
api_version=constants.API_VER_NETWORK,
logger=None,
_ctx=ctx):
resource_group = resource_group or \
utils.get_resource_group(_ctx=_ctx)
network_security_group = network_security_group or \
utils.get_network_security_group(_ctx=_ctx)
Resource.__init__(
self,
'Network Security Rule',
'/{0}/{1}/{2}/{3}'.format(
'resourceGroups/{0}'.format(resource_group),
'providers/Microsoft.Network',
'networkSecurityGroups/{0}'.format(network_security_group),
'securityRules'
),
api_version=api_version,
logger=logger,
_ctx=_ctx)
@operation(resumable=True)
def create(**_):
"""Uses an existing, or creates a new, Network Security Rule"""
# Create a resource (if necessary)
utils.task_resource_create(
NetworkSecurityRule(api_version=ctx.node.properties.get(
'api_version', constants.API_VER_NETWORK)),
{
'location': ctx.node.properties.get('location'),
'tags': ctx.node.properties.get('tags'),
'properties': utils.get_resource_config()
})
@operation(resumable=True)
def delete(**_):
"""Deletes a Network Security Rule"""
# Delete the resource
utils.task_resource_delete(
NetworkSecurityRule(api_version=ctx.node.properties.get(
'api_version', constants.API_VER_NETWORK)))
| 35.733333 | 75 | 0.660759 | y import ctx
from cloudify_azure.resources.base import Resource
from cloudify.decorators import operation
from cloudify_azure import (constants, utils)
class NetworkSecurityRule(Resource):
def __init__(self,
resource_group=None,
network_security_group=None,
api_version=constants.API_VER_NETWORK,
logger=None,
_ctx=ctx):
resource_group = resource_group or \
utils.get_resource_group(_ctx=_ctx)
network_security_group = network_security_group or \
utils.get_network_security_group(_ctx=_ctx)
Resource.__init__(
self,
'Network Security Rule',
'/{0}/{1}/{2}/{3}'.format(
'resourceGroups/{0}'.format(resource_group),
'providers/Microsoft.Network',
'networkSecurityGroups/{0}'.format(network_security_group),
'securityRules'
),
api_version=api_version,
logger=logger,
_ctx=_ctx)
@operation(resumable=True)
def create(**_):
utils.task_resource_create(
NetworkSecurityRule(api_version=ctx.node.properties.get(
'api_version', constants.API_VER_NETWORK)),
{
'location': ctx.node.properties.get('location'),
'tags': ctx.node.properties.get('tags'),
'properties': utils.get_resource_config()
})
@operation(resumable=True)
def delete(**_):
utils.task_resource_delete(
NetworkSecurityRule(api_version=ctx.node.properties.get(
'api_version', constants.API_VER_NETWORK)))
| true | true |
f729c44ac1640031f9fa2ae3fc807ed6e7f45f6a | 2,565 | py | Python | lib/wyw2s_lib/make_facebank_tools/make_facebank.py | JamesFengi/handPose_Eric | 3e329181930ebc7ef0fed2abb9a9d092a8541f9c | [
"Apache-2.0"
] | null | null | null | lib/wyw2s_lib/make_facebank_tools/make_facebank.py | JamesFengi/handPose_Eric | 3e329181930ebc7ef0fed2abb9a9d092a8541f9c | [
"Apache-2.0"
] | null | null | null | lib/wyw2s_lib/make_facebank_tools/make_facebank.py | JamesFengi/handPose_Eric | 3e329181930ebc7ef0fed2abb9a9d092a8541f9c | [
"Apache-2.0"
] | null | null | null | # make facebank
import warnings
warnings.filterwarnings("ignore")
import os
import torch
from model import Backbone
import argparse
from pathlib import Path
from torchvision import transforms as trans
from PIL import Image
import numpy as np
def prepare_facebank(path_images,facebank_path, model, mtcnn, device , tta = True):
#
test_transform_ = trans.Compose([
trans.ToTensor(),
trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
#
model.eval()
embeddings = []
names = ['Unknown']
idx = 0
for path in path_images.iterdir():
if path.is_file():
continue
else:
idx += 1
print("idx {} : {}".format(idx,path))
embs = []
for file in path.iterdir():
# print(file)
if not file.is_file():
continue
else:
try:
# print("---------------------------")
img = Image.open(file)
print(" {}) {}".format(idx,file))
except:
continue
with torch.no_grad():
if tta:
mirror = trans.functional.hflip(img)
emb = model(test_transform_(img).to(device).unsqueeze(0))
emb_mirror = model(test_transform_(mirror).to(device).unsqueeze(0))
embs.append(l2_norm(emb + emb_mirror))
else:
embs.append(model(test_transform_(img).to(device).unsqueeze(0)))
if len(embs) == 0:
continue
embedding = torch.cat(embs).mean(0,keepdim=True)
embeddings.append(embedding)
names.append(path.name)
embeddings = torch.cat(embeddings)
names = np.array(names)
torch.save(embeddings, facebank_path+'/facebank.pth')
np.save(facebank_path + '/names', names)
return embeddings, names
if __name__ == '__main__':
# 需要制作人脸库对应的 图片地址
path_images = "./images/"
# 定义模型
device_ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_ = Backbone(50, 1., "ir_se").to(device_)
# 加载模型
if os.access("./model_ir_se50.pth",os.F_OK):
model_.load_state_dict(torch.load("./model_ir_se50.pth"))
model_.eval()
facebank_path = "./facebank/" # 人脸库对应地址
targets, names = prepare_facebank(Path(path_images), facebank_path,model_, "" ,device_, tta = False) # 构建 人脸 底库
| 33.311688 | 115 | 0.535283 |
import warnings
warnings.filterwarnings("ignore")
import os
import torch
from model import Backbone
import argparse
from pathlib import Path
from torchvision import transforms as trans
from PIL import Image
import numpy as np
def prepare_facebank(path_images,facebank_path, model, mtcnn, device , tta = True):
test_transform_ = trans.Compose([
trans.ToTensor(),
trans.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])
model.eval()
embeddings = []
names = ['Unknown']
idx = 0
for path in path_images.iterdir():
if path.is_file():
continue
else:
idx += 1
print("idx {} : {}".format(idx,path))
embs = []
for file in path.iterdir():
if not file.is_file():
continue
else:
try:
img = Image.open(file)
print(" {}) {}".format(idx,file))
except:
continue
with torch.no_grad():
if tta:
mirror = trans.functional.hflip(img)
emb = model(test_transform_(img).to(device).unsqueeze(0))
emb_mirror = model(test_transform_(mirror).to(device).unsqueeze(0))
embs.append(l2_norm(emb + emb_mirror))
else:
embs.append(model(test_transform_(img).to(device).unsqueeze(0)))
if len(embs) == 0:
continue
embedding = torch.cat(embs).mean(0,keepdim=True)
embeddings.append(embedding)
names.append(path.name)
embeddings = torch.cat(embeddings)
names = np.array(names)
torch.save(embeddings, facebank_path+'/facebank.pth')
np.save(facebank_path + '/names', names)
return embeddings, names
if __name__ == '__main__':
path_images = "./images/"
device_ = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_ = Backbone(50, 1., "ir_se").to(device_)
if os.access("./model_ir_se50.pth",os.F_OK):
model_.load_state_dict(torch.load("./model_ir_se50.pth"))
model_.eval()
facebank_path = "./facebank/"
targets, names = prepare_facebank(Path(path_images), facebank_path,model_, "" ,device_, tta = False)
| true | true |
f729c48d7065946b20b2e2dc9ba72d301fe58164 | 8,819 | py | Python | petibmpy/createxdmf.py | mesnardo/petibmpy | 3ab67cba8d170dcffb4ac7b6b35abd04145dbaf9 | [
"BSD-3-Clause"
] | 1 | 2020-08-08T13:37:28.000Z | 2020-08-08T13:37:28.000Z | petibmpy/createxdmf.py | mesnardo/petibmpy | 3ab67cba8d170dcffb4ac7b6b35abd04145dbaf9 | [
"BSD-3-Clause"
] | null | null | null | petibmpy/createxdmf.py | mesnardo/petibmpy | 3ab67cba8d170dcffb4ac7b6b35abd04145dbaf9 | [
"BSD-3-Clause"
] | null | null | null | """Module to create a XDMF file for a PetIBM field variable."""
import sys
import pathlib
from lxml import etree
from .grid import read_grid_hdf5
def write_xdmf(outpath, datadir, gridpath, name,
nstart=None, nt=None, nsave=None,
states=None, times=None):
"""Write a XDMF file to read the solution of a PetIBM variable.
Parameters
----------
outpath : pathlib.Path object
Path of the XDMF file to create.
datadir : pathlib.Path object
Data directory.
gridpath : pathlib.Path object
Path of the file containing the gridline coordinates.
name : string
Name of the field variable.
nstart : integer (optional)
Starting time step; default: None.
nt : integer (optional)
Number of time steps; default: None.
nsave : integer (optional)
Frequency of saving in number of time steps; default: None.
states : list of integers (optional)
The list of time-step indices to consider in the XDMF file;
default: None.
times : list of floats (optional)
The list of time values; default: None.
"""
# Initialize XDMF file.
xdmf = etree.Element('Xdmf', Version='2.2')
info = etree.SubElement(xdmf, 'Information',
Name='MetaData',
Value='ID-23454')
domain = etree.SubElement(xdmf, 'Domain')
grid_time_series = etree.SubElement(domain, 'Grid',
Name='TimeSeries',
GridType='Collection',
CollectionType='Temporal')
# Read grid to get dimension and number of points.
grid = read_grid_hdf5(gridpath, name)
dim = len(grid)
topology_type = '{}DRectMesh'.format(dim)
geometry_type = 'VXVY' + (dim == 3) * 'VZ'
components = ('x', 'y', 'z')[:dim]
gridsize = [len(line) for line in grid]
number_of_elements = ' '.join(str(n) for n in gridsize[::-1])
precision = '8'
# Get time-step indices and time values.
if states is None:
states = list(range(nstart, nstart + nt + 1, nsave))
# Generate the time series.
for i, state in enumerate(states):
grid = etree.SubElement(grid_time_series, 'Grid',
Name='Grid',
GridType='Uniform')
if times is not None:
time_value = '{:.6f}'.format(times[i])
else:
time_value = '{:0>7}'.format(state)
time = etree.SubElement(grid, 'Time',
Value=time_value)
topology = etree.SubElement(grid, 'Topology',
TopologyType=topology_type,
NumberOfElements=number_of_elements)
geometry = etree.SubElement(grid, 'Geometry',
GeometryType=geometry_type)
# Create XDMF block for the grid. (Use of loop for code-reuse.)
for component, n in zip(components, gridsize):
dataitem = etree.SubElement(geometry, 'DataItem',
Dimensions=str(n),
NumberType='Float',
Precision=precision,
Format='HDF')
dataitem.text = ':/'.join([str(gridpath), name + '/' + component])
# Create XDMF block for the scalar field variable.
attribute = etree.SubElement(grid, 'Attribute',
Name=name,
AttributeType='Scalar',
Center='Node')
dataitem = etree.SubElement(attribute, 'DataItem',
Dimensions=number_of_elements,
NumberType='Float',
Precision=precision,
Format='HDF')
filepath = datadir / '{:0>7}.h5'.format(state)
dataitem.text = ':/'.join([str(filepath), name])
# Write XDMF file.
tree = etree.ElementTree(xdmf)
tree.write(str(outpath), pretty_print=True, xml_declaration=True)
return
def write_xdmf_multi(outpath, config,
nstart=None, nt=None, nsave=None,
states=None, times=None):
"""Write a XDMF file to read the solution of multiple PetIBM variables.
Parameters
----------
outpath : pathlib.Path object
Path of the XDMF file to create.
config : dictionary
Should contains two keys: 'grid' and 'data'.
The value mapped to 'grid' is the path of the HDF5 grid file.
The value mapped to 'data' is a dictionary.
Each item of the 'data' dictionary is labeled with the name
of the variable to add to the XDMF file that is mapped to
the path of the directory that contains the numerical solution
for that variable.
nstart : integer (optional)
Starting time step; default: None.
nt : integer (optional)
Number of time steps; default: None.
nsave : integer (optional)
Frequency of saving in number of time steps; default: None.
states : list of integers (optional)
The list of time-step indices to consider in the XDMF file;
default: None.
times : list of floats (optional)
The list of time values; default: None.
"""
# Initialize XDMF file.
xdmf = etree.Element('Xdmf', Version='2.2')
info = etree.SubElement(xdmf, 'Information',
Name='MetaData',
Value='ID-23454')
domain = etree.SubElement(xdmf, 'Domain')
grid_time_series = etree.SubElement(domain, 'Grid',
Name='TimeSeries',
GridType='Collection',
CollectionType='Temporal')
# Read grid to get dimension and number of points.
master_name = list(config['data'].keys())[0]
gridpath = config['grid']
grid = read_grid_hdf5(gridpath, master_name)
dim = len(grid)
topology_type = '{}DRectMesh'.format(dim)
geometry_type = 'VXVY' + (dim == 3) * 'VZ'
components = ('x', 'y', 'z')[:dim]
gridsize = [len(line) for line in grid]
number_of_elements = ' '.join(str(n) for n in gridsize[::-1])
precision = '8'
# Get time-step indices and time values.
if states is None:
states = list(range(nstart, nstart + nt + 1, nsave))
# Generate the time series.
for i, state in enumerate(states):
grid = etree.SubElement(grid_time_series, 'Grid',
Name='Grid',
GridType='Uniform')
if times is not None:
time_value = '{:.6f}'.format(times[i])
else:
time_value = '{:0>7}'.format(state)
time = etree.SubElement(grid, 'Time',
Value=time_value)
topology = etree.SubElement(grid, 'Topology',
TopologyType=topology_type,
NumberOfElements=number_of_elements)
geometry = etree.SubElement(grid, 'Geometry',
GeometryType=geometry_type)
# Create XDMF block for the grid. (Use of loop for code-reuse.)
for component, n in zip(components, gridsize):
dataitem = etree.SubElement(geometry, 'DataItem',
Dimensions=str(n),
NumberType='Float',
Precision=precision,
Format='HDF')
dataitem.text = ':/'.join([str(gridpath),
master_name + '/' + component])
# Create XDMF block for each scalar field variable.
for name, datadir in config['data'].items():
attribute = etree.SubElement(grid, 'Attribute',
Name=name,
AttributeType='Scalar',
Center='Node')
dataitem = etree.SubElement(attribute, 'DataItem',
Dimensions=number_of_elements,
NumberType='Float',
Precision=precision,
Format='HDF')
filepath = datadir / '{:0>7}.h5'.format(state)
dataitem.text = ':/'.join([str(filepath), name])
# Write XDMF file.
tree = etree.ElementTree(xdmf)
tree.write(str(outpath), pretty_print=True, xml_declaration=True)
return
| 44.540404 | 78 | 0.52591 |
import sys
import pathlib
from lxml import etree
from .grid import read_grid_hdf5
def write_xdmf(outpath, datadir, gridpath, name,
nstart=None, nt=None, nsave=None,
states=None, times=None):
xdmf = etree.Element('Xdmf', Version='2.2')
info = etree.SubElement(xdmf, 'Information',
Name='MetaData',
Value='ID-23454')
domain = etree.SubElement(xdmf, 'Domain')
grid_time_series = etree.SubElement(domain, 'Grid',
Name='TimeSeries',
GridType='Collection',
CollectionType='Temporal')
grid = read_grid_hdf5(gridpath, name)
dim = len(grid)
topology_type = '{}DRectMesh'.format(dim)
geometry_type = 'VXVY' + (dim == 3) * 'VZ'
components = ('x', 'y', 'z')[:dim]
gridsize = [len(line) for line in grid]
number_of_elements = ' '.join(str(n) for n in gridsize[::-1])
precision = '8'
if states is None:
states = list(range(nstart, nstart + nt + 1, nsave))
for i, state in enumerate(states):
grid = etree.SubElement(grid_time_series, 'Grid',
Name='Grid',
GridType='Uniform')
if times is not None:
time_value = '{:.6f}'.format(times[i])
else:
time_value = '{:0>7}'.format(state)
time = etree.SubElement(grid, 'Time',
Value=time_value)
topology = etree.SubElement(grid, 'Topology',
TopologyType=topology_type,
NumberOfElements=number_of_elements)
geometry = etree.SubElement(grid, 'Geometry',
GeometryType=geometry_type)
for component, n in zip(components, gridsize):
dataitem = etree.SubElement(geometry, 'DataItem',
Dimensions=str(n),
NumberType='Float',
Precision=precision,
Format='HDF')
dataitem.text = ':/'.join([str(gridpath), name + '/' + component])
attribute = etree.SubElement(grid, 'Attribute',
Name=name,
AttributeType='Scalar',
Center='Node')
dataitem = etree.SubElement(attribute, 'DataItem',
Dimensions=number_of_elements,
NumberType='Float',
Precision=precision,
Format='HDF')
filepath = datadir / '{:0>7}.h5'.format(state)
dataitem.text = ':/'.join([str(filepath), name])
tree = etree.ElementTree(xdmf)
tree.write(str(outpath), pretty_print=True, xml_declaration=True)
return
def write_xdmf_multi(outpath, config,
nstart=None, nt=None, nsave=None,
states=None, times=None):
xdmf = etree.Element('Xdmf', Version='2.2')
info = etree.SubElement(xdmf, 'Information',
Name='MetaData',
Value='ID-23454')
domain = etree.SubElement(xdmf, 'Domain')
grid_time_series = etree.SubElement(domain, 'Grid',
Name='TimeSeries',
GridType='Collection',
CollectionType='Temporal')
master_name = list(config['data'].keys())[0]
gridpath = config['grid']
grid = read_grid_hdf5(gridpath, master_name)
dim = len(grid)
topology_type = '{}DRectMesh'.format(dim)
geometry_type = 'VXVY' + (dim == 3) * 'VZ'
components = ('x', 'y', 'z')[:dim]
gridsize = [len(line) for line in grid]
number_of_elements = ' '.join(str(n) for n in gridsize[::-1])
precision = '8'
if states is None:
states = list(range(nstart, nstart + nt + 1, nsave))
for i, state in enumerate(states):
grid = etree.SubElement(grid_time_series, 'Grid',
Name='Grid',
GridType='Uniform')
if times is not None:
time_value = '{:.6f}'.format(times[i])
else:
time_value = '{:0>7}'.format(state)
time = etree.SubElement(grid, 'Time',
Value=time_value)
topology = etree.SubElement(grid, 'Topology',
TopologyType=topology_type,
NumberOfElements=number_of_elements)
geometry = etree.SubElement(grid, 'Geometry',
GeometryType=geometry_type)
for component, n in zip(components, gridsize):
dataitem = etree.SubElement(geometry, 'DataItem',
Dimensions=str(n),
NumberType='Float',
Precision=precision,
Format='HDF')
dataitem.text = ':/'.join([str(gridpath),
master_name + '/' + component])
for name, datadir in config['data'].items():
attribute = etree.SubElement(grid, 'Attribute',
Name=name,
AttributeType='Scalar',
Center='Node')
dataitem = etree.SubElement(attribute, 'DataItem',
Dimensions=number_of_elements,
NumberType='Float',
Precision=precision,
Format='HDF')
filepath = datadir / '{:0>7}.h5'.format(state)
dataitem.text = ':/'.join([str(filepath), name])
tree = etree.ElementTree(xdmf)
tree.write(str(outpath), pretty_print=True, xml_declaration=True)
return
| true | true |
f729c49e405ab727bdd961f7cad9ea1e6de7bd96 | 11,663 | py | Python | universal/algo.py | firmai/universal-portfolios | b1d99d6dbcf553582d399cf3851ac4ba35a93d3e | [
"MIT"
] | 6 | 2019-08-06T06:18:40.000Z | 2020-12-02T12:49:16.000Z | universal/algo.py | firmai/universal-portfolios | b1d99d6dbcf553582d399cf3851ac4ba35a93d3e | [
"MIT"
] | null | null | null | universal/algo.py | firmai/universal-portfolios | b1d99d6dbcf553582d399cf3851ac4ba35a93d3e | [
"MIT"
] | 6 | 2019-07-18T22:42:20.000Z | 2021-12-20T22:51:01.000Z | import sys
import numpy as np
import pandas as pd
import itertools
import logging
import inspect
import copy
from .result import AlgoResult, ListResult
from scipy.misc import comb
from . import tools
class Algo(object):
""" Base class for algorithm calculating weights for online portfolio.
You have to subclass either step method to calculate weights sequentially
or weights method, which does it at once. weights method might be useful
for better performance when using matrix calculation, but be careful about
look-ahead bias.
Upper case letters stand for matrix and lower case for vectors (such as
B and b for weights).
"""
# if true, replace missing values by last values
REPLACE_MISSING = False
# type of prices going into weights or step function
# ratio: pt / pt-1
# log: log(pt / pt-1)
# raw: pt
PRICE_TYPE = 'ratio'
def __init__(self, min_history=None, frequency=1):
""" Subclass to define algo specific parameters here.
:param min_history: If not None, use initial weights for first min_window days. Use
this if the algo needs some history for proper parameter estimation.
:param frequency: algorithm should trade every `frequency` periods
"""
self.min_history = min_history or 0
self.frequency = frequency
def init_weights(self, m):
""" Set initial weights.
:param m: Number of assets.
"""
return np.zeros(m)
def init_step(self, X):
""" Called before step method. Use to initialize persistent variables.
:param X: Entire stock returns history.
"""
pass
def step(self, x, last_b, history):
""" Calculate new portfolio weights. If history parameter is omited, step
method gets passed just parameters `x` and `last_b`. This significantly
increases performance.
:param x: Last returns.
:param last_b: Last weights.
:param history: All returns up to now. You can omit this parameter to increase
performance.
"""
raise NotImplementedError('Subclass must implement this!')
def _use_history_step(self):
""" Use history parameter in step method? """
step_args = inspect.getargspec(self.step)[0]
return len(step_args) >= 4
def weights(self, X, min_history=None, log_progress=True):
""" Return weights. Call step method to update portfolio sequentially. Subclass
this method only at your own risk. """
min_history = self.min_history if min_history is None else min_history
# init
B = X.copy() * 0.
last_b = self.init_weights(X.shape[1])
if isinstance(last_b, np.ndarray):
last_b = pd.Series(last_b, X.columns)
# use history in step method?
use_history = self._use_history_step()
# run algo
self.init_step(X)
for t, (_, x) in enumerate(X.iterrows()):
# save weights
B.ix[t] = last_b
# keep initial weights for min_history
if t < min_history:
continue
# trade each `frequency` periods
if (t + 1) % self.frequency != 0:
continue
# predict for t+1
if use_history:
history = X.iloc[:t+1]
last_b = self.step(x, last_b, history)
else:
last_b = self.step(x, last_b)
# convert last_b to suitable format if needed
if type(last_b) == np.matrix:
# remove dimension
last_b = np.squeeze(np.array(last_b))
# show progress by 10 pcts
if log_progress:
tools.log_progress(t, len(X), by=10)
return B
def _split_index(self, ix, nr_chunks, freq):
""" Split index into chunks so that each chunk except of the last has length
divisible by freq. """
chunksize = int(len(ix) / freq / nr_chunks + 1) * freq
return [ix[i*chunksize:(i+1)*chunksize] for i in range(len(ix) / chunksize + 1)]
def run(self, S, n_jobs=1, log_progress=True):
""" Run algorithm and get weights.
:params S: Absolute stock prices. DataFrame with stocks in columns.
:param show_progress: Log computation progress. Works only for algos with
defined step method.
:param n_jobs: run step method in parallel (step method can't depend on last weights)
"""
if log_progress:
logging.debug('Running {}...'.format(self.__class__.__name__))
if isinstance(S, ListResult):
P = S.to_dataframe()
else:
P = S
# convert prices to proper format
X = self._convert_prices(P, self.PRICE_TYPE, self.REPLACE_MISSING)
# get weights
if n_jobs == 1:
try:
B = self.weights(X, log_progress=log_progress)
except TypeError: # weights are missing log_progress parameter
B = self.weights(X)
else:
with tools.mp_pool(n_jobs) as pool:
ix_blocks = self._split_index(X.index, pool._processes * 2, self.frequency)
min_histories = np.maximum(np.cumsum([0] + map(len, ix_blocks[:-1])) - 1, self.min_history)
B_blocks = pool.map(_parallel_weights, [(self, X.ix[:ix_block[-1]], min_history, log_progress)
for ix_block, min_history in zip(ix_blocks, min_histories)])
# join weights to one dataframe
B = pd.concat([B_blocks[i].ix[ix] for i, ix in enumerate(ix_blocks)])
# cast to dataframe if weights return numpy array
if not isinstance(B, pd.DataFrame):
B = pd.DataFrame(B, index=P.index, columns=P.columns)
if log_progress:
logging.debug('{} finished successfully.'.format(self.__class__.__name__))
# if we are aggregating strategies, combine weights from strategies
# and use original assets
if isinstance(S, ListResult):
B = sum(result.B.mul(B[col], axis=0) for result, col in zip(S, B.columns))
return AlgoResult(S[0].X, B)
else:
return AlgoResult(self._convert_prices(S, 'ratio'), B)
def next_weights(self, S, last_b, **kwargs):
""" Calculate weights for next day. """
# use history in step method?
use_history = self._use_history_step()
history = self._convert_prices(S, self.PRICE_TYPE, self.REPLACE_MISSING)
x = history.iloc[-1]
if use_history:
b = self.step(x, last_b, history, **kwargs)
else:
b = self.step(x, last_b, **kwargs)
return pd.Series(b, index=S.columns)
def run_subsets(self, S, r, generator=False):
""" Run algorithm on all stock subsets of length r. Note that number of such tests can be
very large.
:param S: stock prices
:param r: number of stocks in a subset
:param generator: yield results
"""
def subset_generator():
total_subsets = comb(S.shape[1], r)
for i, S_sub in enumerate(tools.combinations(S, r)):
# run algorithm on given subset
result = self.run(S_sub, log_progress=False)
name = ', '.join(S_sub.columns.astype(str))
# log progress by 1 pcts
tools.log_progress(i, total_subsets, by=1)
yield result, name
raise StopIteration
if generator:
return subset_generator()
else:
results = []
names = []
for result, name in subset_generator():
results.append(result)
names.append(name)
return ListResult(results, names)
@classmethod
def _convert_prices(self, S, method, replace_missing=False):
""" Convert prices to format suitable for weight or step function.
Available price types are:
ratio: pt / pt_1
log: log(pt / pt_1)
raw: pt (normalized to start with 1)
"""
if method == 'raw':
# normalize prices so that they start with 1.
r = {}
for name, s in S.iteritems():
init_val = s.ix[s.first_valid_index()]
r[name] = s / init_val
X = pd.DataFrame(r)
if replace_missing:
X.ix[0] = 1.
X = X.fillna(method='ffill')
return X
elif method == 'absolute':
return S
elif method in ('ratio', 'log'):
# be careful about NaN values
X = S / S.shift(1).fillna(method='ffill')
for name, s in X.iteritems():
X[name].iloc[s.index.get_loc(s.first_valid_index()) - 1] = 1.
if replace_missing:
X = X.fillna(1.)
return np.log(X) if method == 'log' else X
else:
raise ValueError('invalid price conversion method')
@classmethod
def run_combination(cls, S, **kwargs):
""" Get equity of algo using all combinations of parameters. All
values in lists specified in kwargs will be optimized. Other types
will be passed as they are to algo __init__ (like numbers, strings,
tuples).
Return ListResult object, which is basically a wrapper of list of AlgoResult objects.
It is possible to pass ListResult to Algo or run_combination again
to get AlgoResult. This is useful for chaining of Algos.
Example:
S = ...load data...
list_results = Anticor.run_combination(S, alpha=[0.01, 0.1, 1.])
result = CRP().run(list_results)
:param S: Stock prices.
:param kwargs: Additional arguments to algo.
:param n_jobs: Use multiprocessing (-1 = use all cores). Use all cores by default.
"""
if isinstance(S, ListResult):
S = S.to_dataframe()
n_jobs = kwargs.pop('n_jobs', -1)
# extract simple parameters
simple_params = {k: kwargs.pop(k) for k, v in kwargs.items()
if not isinstance(v, list)}
# iterate over all combinations
names = []
params_to_try = []
for seq in itertools.product(*kwargs.values()):
params = dict(zip(kwargs.keys(), seq))
# run algo
all_params = dict(params.items() + simple_params.items())
params_to_try.append(all_params)
# create name with format param:value
name = ','.join([str(k) + '=' + str(v) for k, v in params.items()])
names.append(name)
# try all combinations in parallel
with tools.mp_pool(n_jobs) as pool:
results = pool.map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])
results = map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])
return ListResult(results, names)
def copy(self):
return copy.deepcopy(self)
def _parallel_weights(tuple_args):
self, X, min_history, log_progress = tuple_args
try:
return self.weights(X, min_history=min_history, log_progress=log_progress)
except TypeError: # weights are missing log_progress parameter
return self.weights(X, min_history=min_history)
def _run_algo_params(tuple_args):
S, cls, params = tuple_args
logging.debug('Run combination of parameters: {}'.format(params))
return cls(**params).run(S)
| 36.446875 | 110 | 0.592729 | import sys
import numpy as np
import pandas as pd
import itertools
import logging
import inspect
import copy
from .result import AlgoResult, ListResult
from scipy.misc import comb
from . import tools
class Algo(object):
REPLACE_MISSING = False
PRICE_TYPE = 'ratio'
def __init__(self, min_history=None, frequency=1):
self.min_history = min_history or 0
self.frequency = frequency
def init_weights(self, m):
return np.zeros(m)
def init_step(self, X):
pass
def step(self, x, last_b, history):
raise NotImplementedError('Subclass must implement this!')
def _use_history_step(self):
step_args = inspect.getargspec(self.step)[0]
return len(step_args) >= 4
def weights(self, X, min_history=None, log_progress=True):
min_history = self.min_history if min_history is None else min_history
B = X.copy() * 0.
last_b = self.init_weights(X.shape[1])
if isinstance(last_b, np.ndarray):
last_b = pd.Series(last_b, X.columns)
use_history = self._use_history_step()
self.init_step(X)
for t, (_, x) in enumerate(X.iterrows()):
B.ix[t] = last_b
if t < min_history:
continue
if (t + 1) % self.frequency != 0:
continue
if use_history:
history = X.iloc[:t+1]
last_b = self.step(x, last_b, history)
else:
last_b = self.step(x, last_b)
if type(last_b) == np.matrix:
last_b = np.squeeze(np.array(last_b))
if log_progress:
tools.log_progress(t, len(X), by=10)
return B
def _split_index(self, ix, nr_chunks, freq):
chunksize = int(len(ix) / freq / nr_chunks + 1) * freq
return [ix[i*chunksize:(i+1)*chunksize] for i in range(len(ix) / chunksize + 1)]
def run(self, S, n_jobs=1, log_progress=True):
if log_progress:
logging.debug('Running {}...'.format(self.__class__.__name__))
if isinstance(S, ListResult):
P = S.to_dataframe()
else:
P = S
X = self._convert_prices(P, self.PRICE_TYPE, self.REPLACE_MISSING)
if n_jobs == 1:
try:
B = self.weights(X, log_progress=log_progress)
except TypeError:
B = self.weights(X)
else:
with tools.mp_pool(n_jobs) as pool:
ix_blocks = self._split_index(X.index, pool._processes * 2, self.frequency)
min_histories = np.maximum(np.cumsum([0] + map(len, ix_blocks[:-1])) - 1, self.min_history)
B_blocks = pool.map(_parallel_weights, [(self, X.ix[:ix_block[-1]], min_history, log_progress)
for ix_block, min_history in zip(ix_blocks, min_histories)])
B = pd.concat([B_blocks[i].ix[ix] for i, ix in enumerate(ix_blocks)])
if not isinstance(B, pd.DataFrame):
B = pd.DataFrame(B, index=P.index, columns=P.columns)
if log_progress:
logging.debug('{} finished successfully.'.format(self.__class__.__name__))
if isinstance(S, ListResult):
B = sum(result.B.mul(B[col], axis=0) for result, col in zip(S, B.columns))
return AlgoResult(S[0].X, B)
else:
return AlgoResult(self._convert_prices(S, 'ratio'), B)
def next_weights(self, S, last_b, **kwargs):
use_history = self._use_history_step()
history = self._convert_prices(S, self.PRICE_TYPE, self.REPLACE_MISSING)
x = history.iloc[-1]
if use_history:
b = self.step(x, last_b, history, **kwargs)
else:
b = self.step(x, last_b, **kwargs)
return pd.Series(b, index=S.columns)
def run_subsets(self, S, r, generator=False):
def subset_generator():
total_subsets = comb(S.shape[1], r)
for i, S_sub in enumerate(tools.combinations(S, r)):
result = self.run(S_sub, log_progress=False)
name = ', '.join(S_sub.columns.astype(str))
tools.log_progress(i, total_subsets, by=1)
yield result, name
raise StopIteration
if generator:
return subset_generator()
else:
results = []
names = []
for result, name in subset_generator():
results.append(result)
names.append(name)
return ListResult(results, names)
@classmethod
def _convert_prices(self, S, method, replace_missing=False):
if method == 'raw':
r = {}
for name, s in S.iteritems():
init_val = s.ix[s.first_valid_index()]
r[name] = s / init_val
X = pd.DataFrame(r)
if replace_missing:
X.ix[0] = 1.
X = X.fillna(method='ffill')
return X
elif method == 'absolute':
return S
elif method in ('ratio', 'log'):
X = S / S.shift(1).fillna(method='ffill')
for name, s in X.iteritems():
X[name].iloc[s.index.get_loc(s.first_valid_index()) - 1] = 1.
if replace_missing:
X = X.fillna(1.)
return np.log(X) if method == 'log' else X
else:
raise ValueError('invalid price conversion method')
@classmethod
def run_combination(cls, S, **kwargs):
if isinstance(S, ListResult):
S = S.to_dataframe()
n_jobs = kwargs.pop('n_jobs', -1)
simple_params = {k: kwargs.pop(k) for k, v in kwargs.items()
if not isinstance(v, list)}
names = []
params_to_try = []
for seq in itertools.product(*kwargs.values()):
params = dict(zip(kwargs.keys(), seq))
all_params = dict(params.items() + simple_params.items())
params_to_try.append(all_params)
name = ','.join([str(k) + '=' + str(v) for k, v in params.items()])
names.append(name)
with tools.mp_pool(n_jobs) as pool:
results = pool.map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])
results = map(_run_algo_params, [(S, cls, all_params) for all_params in params_to_try])
return ListResult(results, names)
def copy(self):
return copy.deepcopy(self)
def _parallel_weights(tuple_args):
self, X, min_history, log_progress = tuple_args
try:
return self.weights(X, min_history=min_history, log_progress=log_progress)
except TypeError:
return self.weights(X, min_history=min_history)
def _run_algo_params(tuple_args):
S, cls, params = tuple_args
logging.debug('Run combination of parameters: {}'.format(params))
return cls(**params).run(S)
| true | true |
f729c4fab9f3476a5ae49483670be2f99da1ac97 | 9,712 | py | Python | userbot/modules/ping.py | zerosquad13/Zero-Ubot | 94f8d6d4c715a3d28c9c1e9481d42e3fe8252cab | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 4 | 2021-07-03T20:02:14.000Z | 2021-09-26T13:47:12.000Z | userbot/modules/ping.py | zYxDevs/Man-Userbot | 109cc5ccf11ca22bec289892a853db90cca679ff | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | userbot/modules/ping.py | zYxDevs/Man-Userbot | 109cc5ccf11ca22bec289892a853db90cca679ff | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2022-03-02T09:51:22.000Z | 2022-03-02T09:59:25.000Z | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
# ReCode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de
import random
import time
from datetime import datetime
from speedtest import Speedtest
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP, StartTime, bot
from userbot.events import man_cmd, register
from userbot.utils import humanbytes
absen = [
"**Hadir bang** 😁",
"**Hadir kak** 😉",
"**Hadir dong** 😁",
"**Hadir ganteng** 🥵",
"**Hadir bro** 😎",
"**Hadir kak maap telat** 🥺",
]
async def get_readable_time(seconds: int) -> str:
count = 0
up_time = ""
time_list = []
time_suffix_list = ["s", "m", "Jam", "Hari"]
while count < 4:
count += 1
remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
seconds = int(remainder)
for x in range(len(time_list)):
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
up_time += time_list.pop() + ", "
time_list.reverse()
up_time += ":".join(time_list)
return up_time
@bot.on(man_cmd(outgoing=True, pattern=r"ping$"))
async def _(ping):
"""For .ping command, ping the userbot from any chat."""
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("**✣**")
await ping.edit("**✣✣**")
await ping.edit("**✣✣✣**")
await ping.edit("**✣✣✣✣**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await ping.edit(
f"**PONG!!🏓**\n"
f"✣ **Pinger** - `%sms`\n"
f"✣ **Uptime -** `{uptime}` \n"
f"**✦҈͜͡Owner :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"xping$"))
async def _(ping):
"""For .ping command, ping the userbot from any chat."""
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("`Pinging....`")
end = datetime.now()
duration = (end - start).microseconds / 1000
await ping.edit(
f"**PONG!! 🍭**\n**Pinger** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"lping$"))
async def _(ping):
"""For .ping command, ping the userbot from any chat."""
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("**★ PING ★**")
await ping.edit("**★★ PING ★★**")
await ping.edit("**★★★ PING ★★★**")
await ping.edit("**★★★★ PING ★★★★**")
await ping.edit("**✦҈͜͡➳ PONG!**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await ping.edit(
f"❃ **Ping !!** "
f"`%sms` \n"
f"❃ **Uptime -** "
f"`{uptime}` \n"
f"**✦҈͜͡➳ Master :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"fping$"))
async def _(f):
"""For .ping command, ping the userbot from any chat."""
await get_readable_time((time.time() - StartTime))
start = datetime.now()
await f.edit(". /¯ )")
await f.edit(". /¯ )\n /¯ /")
await f.edit(
". /¯ )\n /¯ /\n / /"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ "
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´\n \\ ("
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´\n \\ (\n \\ "
)
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await f.edit(
f"**PONG!!🏓**\n"
f"✣ **Pinger** - `%sms`\n"
f"✣ **Uptime -** `{uptime}` \n"
f"**✦҈͜͡Owner :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"keping$"))
async def _(pong):
await get_readable_time((time.time() - StartTime))
start = datetime.now()
await pong.edit("**『⍟𝐊𝐎𝐍𝐓𝐎𝐋』**")
await pong.edit("**◆◈𝐊𝐀𝐌𝐏𝐀𝐍𝐆◈◆**")
await pong.edit("**𝐏𝐄𝐂𝐀𝐇𝐊𝐀𝐍 𝐁𝐈𝐉𝐈 𝐊𝐀𝐔 𝐀𝐒𝐔**")
await pong.edit("**☬𝐒𝐈𝐀𝐏 𝐊𝐀𝐌𝐏𝐀𝐍𝐆 𝐌𝐄𝐍𝐔𝐌𝐁𝐔𝐊 𝐀𝐒𝐔☬**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await pong.edit(
f"**✲ 𝙺𝙾𝙽𝚃𝙾𝙻 𝙼𝙴𝙻𝙴𝙳𝚄𝙶** "
f"\n ⫸ ᴷᵒⁿᵗᵒˡ `%sms` \n"
f"**✲ 𝙱𝙸𝙹𝙸 𝙿𝙴𝙻𝙴𝚁** "
f"\n ⫸ ᴷᵃᵐᵖᵃⁿᵍ『[{user.first_name}](tg://user?id={user.id})』 \n" % (duration)
)
# .keping & kping Coded by Koala
@bot.on(man_cmd(outgoing=True, pattern=r"kping$"))
async def _(pong):
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8==✊=D")
await pong.edit("8=✊==D")
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8==✊=D")
await pong.edit("8=✊==D")
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8===✊D💦")
await pong.edit("8====D💦💦")
await pong.edit("**CROOTTTT PINGGGG!**")
end = datetime.now()
duration = (end - start).microseconds / 1000
await pong.edit(
f"**NGENTOT!! 🐨**\n**KAMPANG** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"speedtest$"))
async def _(speed):
"""For .speedtest command, use SpeedTest to check server speeds."""
await speed.edit("`Running speed test...`")
test = Speedtest()
test.get_best_server()
test.download()
test.upload()
test.results.share()
result = test.results.dict()
msg = (
f"**Started at {result['timestamp']}**\n\n"
"**Client**\n"
f"**ISP :** `{result['client']['isp']}`\n"
f"**Country :** `{result['client']['country']}`\n\n"
"**Server**\n"
f"**Name :** `{result['server']['name']}`\n"
f"**Country :** `{result['server']['country']}`\n"
f"**Sponsor :** `{result['server']['sponsor']}`\n\n"
f"**Ping :** `{result['ping']}`\n"
f"**Upload :** `{humanbytes(result['upload'])}/s`\n"
f"**Download :** `{humanbytes(result['download'])}/s`"
)
await speed.delete()
await speed.client.send_file(
speed.chat_id,
result["share"],
caption=msg,
force_document=False,
)
@bot.on(man_cmd(outgoing=True, pattern=r"pong$"))
async def _(pong):
"""For .ping command, ping the userbot from any chat."""
start = datetime.now()
await pong.edit("`Sepong.....🏓`")
end = datetime.now()
duration = (end - start).microseconds / 9000
await pong.edit("🏓 **Ping!**\n`%sms`" % (duration))
# KALO NGEFORK absen ini GA USAH DI HAPUS YA GOBLOK 😡
@register(incoming=True, from_users=844432220, pattern=r"^.absen$")
async def risman(ganteng):
await ganteng.reply(random.choice(absen))
# JANGAN DI HAPUS GOBLOK 😡 LU COPY AJA TINGGAL TAMBAHIN
# DI HAPUS GUA GBAN YA 🥴 GUA TANDAIN LU AKUN TELENYA 😡
CMD_HELP.update(
{
"ping": f"**Plugin : **`ping`\
\n\n • **Syntax :** `{cmd}ping` ; `{cmd}lping` ; `{cmd}xping` ; `{cmd}kping` ; `{cmd}fping`\
\n • **Function : **Untuk menunjukkan ping userbot.\
\n\n • **Syntax :** `{cmd}pong`\
\n • **Function : **Sama seperti perintah ping\
"
}
)
CMD_HELP.update(
{
"speedtest": f"**Plugin : **`speedtest`\
\n\n • **Syntax :** `{cmd}speedtest`\
\n • **Function : **Untuk Mengetes kecepatan server userbot.\
"
}
)
| 35.061372 | 322 | 0.464271 |
import random
import time
from datetime import datetime
from speedtest import Speedtest
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP, StartTime, bot
from userbot.events import man_cmd, register
from userbot.utils import humanbytes
absen = [
"**Hadir bang** 😁",
"**Hadir kak** 😉",
"**Hadir dong** 😁",
"**Hadir ganteng** 🥵",
"**Hadir bro** 😎",
"**Hadir kak maap telat** 🥺",
]
async def get_readable_time(seconds: int) -> str:
count = 0
up_time = ""
time_list = []
time_suffix_list = ["s", "m", "Jam", "Hari"]
while count < 4:
count += 1
remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24)
if seconds == 0 and remainder == 0:
break
time_list.append(int(result))
seconds = int(remainder)
for x in range(len(time_list)):
time_list[x] = str(time_list[x]) + time_suffix_list[x]
if len(time_list) == 4:
up_time += time_list.pop() + ", "
time_list.reverse()
up_time += ":".join(time_list)
return up_time
@bot.on(man_cmd(outgoing=True, pattern=r"ping$"))
async def _(ping):
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("**✣**")
await ping.edit("**✣✣**")
await ping.edit("**✣✣✣**")
await ping.edit("**✣✣✣✣**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await ping.edit(
f"**PONG!!🏓**\n"
f"✣ **Pinger** - `%sms`\n"
f"✣ **Uptime -** `{uptime}` \n"
f"**✦҈͜͡Owner :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"xping$"))
async def _(ping):
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("`Pinging....`")
end = datetime.now()
duration = (end - start).microseconds / 1000
await ping.edit(
f"**PONG!! 🍭**\n**Pinger** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"lping$"))
async def _(ping):
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await ping.edit("**★ PING ★**")
await ping.edit("**★★ PING ★★**")
await ping.edit("**★★★ PING ★★★**")
await ping.edit("**★★★★ PING ★★★★**")
await ping.edit("**✦҈͜͡➳ PONG!**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await ping.edit(
f"❃ **Ping !!** "
f"`%sms` \n"
f"❃ **Uptime -** "
f"`{uptime}` \n"
f"**✦҈͜͡➳ Master :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"fping$"))
async def _(f):
await get_readable_time((time.time() - StartTime))
start = datetime.now()
await f.edit(". /¯ )")
await f.edit(". /¯ )\n /¯ /")
await f.edit(
". /¯ )\n /¯ /\n / /"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ "
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´"
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´\n \\ ("
)
await f.edit(
". /¯ )\n /¯ /\n / /\n /´¯/' '/´¯¯`•¸\n /'/ / / /¨¯\\ \n ('( ( ( ( ¯~/' ')\n \\ /\n \\ _.•´\n \\ (\n \\ "
)
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await f.edit(
f"**PONG!!🏓**\n"
f"✣ **Pinger** - `%sms`\n"
f"✣ **Uptime -** `{uptime}` \n"
f"**✦҈͜͡Owner :** [{user.first_name}](tg://user?id={user.id})" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"keping$"))
async def _(pong):
await get_readable_time((time.time() - StartTime))
start = datetime.now()
await pong.edit("**『⍟𝐊𝐎𝐍𝐓𝐎𝐋』**")
await pong.edit("**◆◈𝐊𝐀𝐌𝐏𝐀𝐍𝐆◈◆**")
await pong.edit("**𝐏𝐄𝐂𝐀𝐇𝐊𝐀𝐍 𝐁𝐈𝐉𝐈 𝐊𝐀𝐔 𝐀𝐒𝐔**")
await pong.edit("**☬𝐒𝐈𝐀𝐏 𝐊𝐀𝐌𝐏𝐀𝐍𝐆 𝐌𝐄𝐍𝐔𝐌𝐁𝐔𝐊 𝐀𝐒𝐔☬**")
end = datetime.now()
duration = (end - start).microseconds / 1000
user = await bot.get_me()
await pong.edit(
f"**✲ 𝙺𝙾𝙽𝚃𝙾𝙻 𝙼𝙴𝙻𝙴𝙳𝚄𝙶** "
f"\n ⫸ ᴷᵒⁿᵗᵒˡ `%sms` \n"
f"**✲ 𝙱𝙸𝙹𝙸 𝙿𝙴𝙻𝙴𝚁** "
f"\n ⫸ ᴷᵃᵐᵖᵃⁿᵍ『[{user.first_name}](tg://user?id={user.id})』 \n" % (duration)
)
# .keping & kping Coded by Koala
@bot.on(man_cmd(outgoing=True, pattern=r"kping$"))
async def _(pong):
uptime = await get_readable_time((time.time() - StartTime))
start = datetime.now()
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8==✊=D")
await pong.edit("8=✊==D")
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8==✊=D")
await pong.edit("8=✊==D")
await pong.edit("8✊===D")
await pong.edit("8=✊==D")
await pong.edit("8==✊=D")
await pong.edit("8===✊D")
await pong.edit("8===✊D💦")
await pong.edit("8====D💦💦")
await pong.edit("**CROOTTTT PINGGGG!**")
end = datetime.now()
duration = (end - start).microseconds / 1000
await pong.edit(
f"**NGENTOT!! 🐨**\n**KAMPANG** : %sms\n**Bot Uptime** : {uptime}🕛" % (duration)
)
@bot.on(man_cmd(outgoing=True, pattern=r"speedtest$"))
async def _(speed):
await speed.edit("`Running speed test...`")
test = Speedtest()
test.get_best_server()
test.download()
test.upload()
test.results.share()
result = test.results.dict()
msg = (
f"**Started at {result['timestamp']}**\n\n"
"**Client**\n"
f"**ISP :** `{result['client']['isp']}`\n"
f"**Country :** `{result['client']['country']}`\n\n"
"**Server**\n"
f"**Name :** `{result['server']['name']}`\n"
f"**Country :** `{result['server']['country']}`\n"
f"**Sponsor :** `{result['server']['sponsor']}`\n\n"
f"**Ping :** `{result['ping']}`\n"
f"**Upload :** `{humanbytes(result['upload'])}/s`\n"
f"**Download :** `{humanbytes(result['download'])}/s`"
)
await speed.delete()
await speed.client.send_file(
speed.chat_id,
result["share"],
caption=msg,
force_document=False,
)
@bot.on(man_cmd(outgoing=True, pattern=r"pong$"))
async def _(pong):
start = datetime.now()
await pong.edit("`Sepong.....🏓`")
end = datetime.now()
duration = (end - start).microseconds / 9000
await pong.edit("🏓 **Ping!**\n`%sms`" % (duration))
# KALO NGEFORK absen ini GA USAH DI HAPUS YA GOBLOK 😡
@register(incoming=True, from_users=844432220, pattern=r"^.absen$")
async def risman(ganteng):
await ganteng.reply(random.choice(absen))
# JANGAN DI HAPUS GOBLOK 😡 LU COPY AJA TINGGAL TAMBAHIN
# DI HAPUS GUA GBAN YA 🥴 GUA TANDAIN LU AKUN TELENYA 😡
CMD_HELP.update(
{
"ping": f"**Plugin : **`ping`\
\n\n • **Syntax :** `{cmd}ping` ; `{cmd}lping` ; `{cmd}xping` ; `{cmd}kping` ; `{cmd}fping`\
\n • **Function : **Untuk menunjukkan ping userbot.\
\n\n • **Syntax :** `{cmd}pong`\
\n • **Function : **Sama seperti perintah ping\
"
}
)
CMD_HELP.update(
{
"speedtest": f"**Plugin : **`speedtest`\
\n\n • **Syntax :** `{cmd}speedtest`\
\n • **Function : **Untuk Mengetes kecepatan server userbot.\
"
}
)
| true | true |
f729c51ebf79c20390fd5bd358e6ac05649eef6e | 3,582 | py | Python | trainCode/Source/reid/models/resmap.py | Pandinosaurus/RandPerson | 7dd503cc1d063d95b8cf6b43d40bb93452192d6d | [
"Apache-2.0"
] | 83 | 2020-06-24T11:25:46.000Z | 2022-02-17T16:07:25.000Z | trainCode/Source/reid/models/resmap.py | XrosLiang/RandPerson | 1c6e935d64d8210ee4cddbf803da054016090675 | [
"Apache-2.0"
] | 7 | 2020-06-28T05:00:58.000Z | 2021-09-22T06:57:26.000Z | trainCode/Source/reid/models/resmap.py | XrosLiang/RandPerson | 1c6e935d64d8210ee4cddbf803da054016090675 | [
"Apache-2.0"
] | 16 | 2020-06-28T00:38:42.000Z | 2022-02-05T06:01:41.000Z | from __future__ import absolute_import
from torch import nn
import torchvision
fea_dims_small = {'layer2': 128, 'layer3': 256, 'layer4': 512}
fea_dims = {'layer2': 512, 'layer3': 1024, 'layer4': 2048}
class ResNet(nn.Module):
__factory = {
18: torchvision.models.resnet18,
34: torchvision.models.resnet34,
50: torchvision.models.resnet50,
101: torchvision.models.resnet101,
152: torchvision.models.resnet152,
}
def __init__(self, depth, final_layer='layer3', neck=128, pretrained=True):
super(ResNet, self).__init__()
self.depth = depth
self.final_layer = final_layer
self.neck = neck
self.pretrained = pretrained
# Construct base (pretrained) resnet
if depth not in ResNet.__factory:
raise KeyError("Unsupported depth:", depth)
self.base = ResNet.__factory[depth](pretrained=pretrained)
if depth < 50:
out_planes = fea_dims_small[final_layer]
else:
out_planes = fea_dims[final_layer]
if neck > 0:
self.neck_conv = nn.Conv2d(out_planes, neck, kernel_size=3, padding=1, bias=False)
out_planes = neck
self.neck_bn = nn.BatchNorm2d(out_planes)
self.num_features = out_planes
def forward(self, inputs):
x = inputs
for name, module in self.base._modules.items():
x = module(x)
if name == self.final_layer:
break
if self.neck > 0:
x = self.neck_conv(x)
x = self.neck_bn(x)
return x
def resnet18(**kwargs):
return ResNet(18, **kwargs)
def resnet34(**kwargs):
return ResNet(34, **kwargs)
def resnet50(**kwargs):
return ResNet(50, **kwargs)
def resnet101(**kwargs):
return ResNet(101, **kwargs)
def resnet152(**kwargs):
return ResNet(152, **kwargs)
__factory = {
'resnet18': resnet18,
'resnet34': resnet34,
'resnet50': resnet50,
'resnet101': resnet101,
'resnet152': resnet152,
}
def names():
return sorted(__factory.keys())
def create(name, *args, **kwargs):
"""
Create a model instance.
Parameters
----------
name : str
Model name. Can be one of 'inception', 'resnet18', 'resnet34',
'resnet50', 'resnet101', and 'resnet152'.
pretrained : bool, optional
Only applied for 'resnet*' models. If True, will use ImageNet pretrained
model. Default: True
cut_at_pooling : bool, optional
If True, will cut the model before the last global pooling layer and
ignore the remaining kwargs. Default: False
num_features : int, optional
If positive, will append a Linear layer after the global pooling layer,
with this number of output units, followed by a BatchNorm layer.
Otherwise these layers will not be appended. Default: 256 for
'inception', 0 for 'resnet*'
norm : bool, optional
If True, will normalize the feature to be unit L2-norm for each sample.
Otherwise will append a ReLU layer after the above Linear layer if
num_features > 0. Default: False
dropout : float, optional
If positive, will append a Dropout layer with this dropout rate.
Default: 0
num_classes : int, optional
If positive, will append a Linear layer at the end as the classifier
with this number of output units. Default: 0
"""
if name not in __factory:
raise KeyError("Unknown model:", name)
return __factory[name](*args, **kwargs)
| 28.656 | 94 | 0.630374 | from __future__ import absolute_import
from torch import nn
import torchvision
fea_dims_small = {'layer2': 128, 'layer3': 256, 'layer4': 512}
fea_dims = {'layer2': 512, 'layer3': 1024, 'layer4': 2048}
class ResNet(nn.Module):
__factory = {
18: torchvision.models.resnet18,
34: torchvision.models.resnet34,
50: torchvision.models.resnet50,
101: torchvision.models.resnet101,
152: torchvision.models.resnet152,
}
def __init__(self, depth, final_layer='layer3', neck=128, pretrained=True):
super(ResNet, self).__init__()
self.depth = depth
self.final_layer = final_layer
self.neck = neck
self.pretrained = pretrained
if depth not in ResNet.__factory:
raise KeyError("Unsupported depth:", depth)
self.base = ResNet.__factory[depth](pretrained=pretrained)
if depth < 50:
out_planes = fea_dims_small[final_layer]
else:
out_planes = fea_dims[final_layer]
if neck > 0:
self.neck_conv = nn.Conv2d(out_planes, neck, kernel_size=3, padding=1, bias=False)
out_planes = neck
self.neck_bn = nn.BatchNorm2d(out_planes)
self.num_features = out_planes
def forward(self, inputs):
x = inputs
for name, module in self.base._modules.items():
x = module(x)
if name == self.final_layer:
break
if self.neck > 0:
x = self.neck_conv(x)
x = self.neck_bn(x)
return x
def resnet18(**kwargs):
return ResNet(18, **kwargs)
def resnet34(**kwargs):
return ResNet(34, **kwargs)
def resnet50(**kwargs):
return ResNet(50, **kwargs)
def resnet101(**kwargs):
return ResNet(101, **kwargs)
def resnet152(**kwargs):
return ResNet(152, **kwargs)
__factory = {
'resnet18': resnet18,
'resnet34': resnet34,
'resnet50': resnet50,
'resnet101': resnet101,
'resnet152': resnet152,
}
def names():
return sorted(__factory.keys())
def create(name, *args, **kwargs):
if name not in __factory:
raise KeyError("Unknown model:", name)
return __factory[name](*args, **kwargs)
| true | true |
f729c51fa2b001db60af7a3c0837c3d149678ad5 | 2,474 | py | Python | neurosynth/analysis/reduce.py | wanirepo/Neurosynth | 5b770ec31c5095c16e27ebe664fa5d515c662298 | [
"MIT"
] | 2 | 2016-12-26T15:29:18.000Z | 2017-04-22T20:10:37.000Z | neurosynth/analysis/reduce.py | wanirepo/Neurosynth | 5b770ec31c5095c16e27ebe664fa5d515c662298 | [
"MIT"
] | null | null | null | neurosynth/analysis/reduce.py | wanirepo/Neurosynth | 5b770ec31c5095c16e27ebe664fa5d515c662298 | [
"MIT"
] | null | null | null | import numpy as np
""" Dimensional/data reduction methods. """
def average_within_regions(dataset, img, threshold=None, remove_zero=True):
""" Averages over all voxels within each ROI in the input image.
Takes a Dataset and a Nifti image that defines distinct regions, and
returns a numpy matrix of ROIs x mappables, where the value at each ROI is
the proportion of active voxels in that ROI. Each distinct ROI must have a
unique value in the image; non-contiguous voxels with the same value will
be assigned to the same ROI.
Args:
dataset: A Dataset instance
img: A NIFTI or Analyze-format image that provides the ROI definitions
threshold: An optional float in the range of 0 - 1. If passed, the array
will be binarized, with ROI values above the threshold assigned to True
and values below the threshold assigned to False. (E.g., if threshold =
0.05, only ROIs in which more than 5% of voxels are active will be
considered active.).
remove_zero: An optional boolean; when True, assume that voxels with value
of 0 should not be considered as a separate ROI, and will be ignored.
Returns:
If replace == True, nothing is returned (the Dataset is modified in-place).
Otherwise, returns a 2D numpy array with ROIs in rows and mappables in columns.
"""
regions = dataset.volume.mask(img)
labels = np.unique(regions)
if remove_zero: labels = labels[np.nonzero(labels)]
n_regions = labels.size
m = np.zeros((regions.size, n_regions))
for i in range(n_regions):
m[regions==labels[i],i] = 1.0/np.sum(regions==labels[i])
# produces roi x study matrix
result = np.transpose(m) * dataset.get_image_data(ids=None, dense=False)
if threshold is not None:
result[result < threshold] = 0.0
result = result.astype(bool)
return result
def get_random_voxels(dataset, n_voxels):
""" Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare performance
of a more principled feature selection method with simple random selection.
Args:
dataset: A Dataset instance
n_voxels: An integer specifying the number of random voxels to select.
Returns:
A 2D numpy array with (randomly-selected) voxels in rows and mappables in columns.
"""
voxels = np.range(dataset.volume.num_vox_in_mask)
selected = np.random.shuffle(voxels)[0:n_voxels]
return dataset.get_image_data(voxels=selected)
| 41.932203 | 86 | 0.7308 | import numpy as np
def average_within_regions(dataset, img, threshold=None, remove_zero=True):
regions = dataset.volume.mask(img)
labels = np.unique(regions)
if remove_zero: labels = labels[np.nonzero(labels)]
n_regions = labels.size
m = np.zeros((regions.size, n_regions))
for i in range(n_regions):
m[regions==labels[i],i] = 1.0/np.sum(regions==labels[i])
result = np.transpose(m) * dataset.get_image_data(ids=None, dense=False)
if threshold is not None:
result[result < threshold] = 0.0
result = result.astype(bool)
return result
def get_random_voxels(dataset, n_voxels):
voxels = np.range(dataset.volume.num_vox_in_mask)
selected = np.random.shuffle(voxels)[0:n_voxels]
return dataset.get_image_data(voxels=selected)
| true | true |
f729c6a3bf40c4409e5dca6df0ff3fc814bfd2ee | 590 | py | Python | tests/test_processor.py | Tmw/edward | 0a58022d0bbf1f80abecb880f7565acaa5cebfde | [
"MIT"
] | 20 | 2019-01-07T08:36:57.000Z | 2021-06-15T09:21:37.000Z | tests/test_processor.py | Tmw/edward | 0a58022d0bbf1f80abecb880f7565acaa5cebfde | [
"MIT"
] | 1 | 2019-01-17T12:34:29.000Z | 2019-01-17T12:34:29.000Z | tests/test_processor.py | Tmw/edward | 0a58022d0bbf1f80abecb880f7565acaa5cebfde | [
"MIT"
] | 2 | 2020-01-14T07:30:01.000Z | 2020-03-03T17:13:16.000Z | import unittest
from unittest.mock import patch
from PIL import Image
import processor
class ProcessorTest(unittest.TestCase):
def test_normalize_input(self):
img = Image.new("RGB", (400, 400), "#ff0000")
normalized = processor.normalize_input(img)
assert normalized.shape == (224, 224, 3), "Incorrect shape"
@patch('processor.load_model', return_value="OK")
def test_prepare(self, MockLoadModel):
processor.prepare()
assert MockLoadModel.called, "load_model not called"
assert processor.model == "OK", "model not assigned"
| 28.095238 | 67 | 0.691525 | import unittest
from unittest.mock import patch
from PIL import Image
import processor
class ProcessorTest(unittest.TestCase):
def test_normalize_input(self):
img = Image.new("RGB", (400, 400), "#ff0000")
normalized = processor.normalize_input(img)
assert normalized.shape == (224, 224, 3), "Incorrect shape"
@patch('processor.load_model', return_value="OK")
def test_prepare(self, MockLoadModel):
processor.prepare()
assert MockLoadModel.called, "load_model not called"
assert processor.model == "OK", "model not assigned"
| true | true |
f729c7b895ae69fca2de4c915ddd8a78950b4f94 | 4,705 | py | Python | Review_2/main.py | ant-6112/Image_Encryption_Using_Steganography_And_AES | c3bc6a220561037ed6d3b66d4519075ec4d37170 | [
"MIT"
] | null | null | null | Review_2/main.py | ant-6112/Image_Encryption_Using_Steganography_And_AES | c3bc6a220561037ed6d3b66d4519075ec4d37170 | [
"MIT"
] | null | null | null | Review_2/main.py | ant-6112/Image_Encryption_Using_Steganography_And_AES | c3bc6a220561037ed6d3b66d4519075ec4d37170 | [
"MIT"
] | null | null | null | from AES import AES
from AES import unpad
from EncodeDecode import encode
from EncodeDecode import decode
from ImageInsideImage import *
from PIL import Image
if __name__ == '__main__':
print("Enter 1 to Ecrypt a Message Using AES Encryption\nEnter 2 to Decrypt a Message\nEnter 3 to Encrypt a Message and Hide It In Image Using LSB\nEnter 4 to Decrypt a Image\nEnter 5 to Hide Image Inside Another Image\nEnter 6 to Reveal a Image Inside Another Image\nEnter To Hide Image Inside Another Image Without ")
choice=int(input())
if choice==1:
text=input("Enter the text to be encrypted:\n")
key=input("Enter 16 bytes long encryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=obj.encrypt_cbc(text,iv )
enctext=""
for i in cipher:
for j in i:
enctext+=chr(j)
print("Here is your encrypted message:",cipher)
elif choice==2:
print("A list needs to be passed as encrypted text ,so please modify the same in code")
key=input("Enter 16 bytes long decryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=[[82, 214, 73, 255, 189, 148, 31, 109, 36, 213, 241, 19, 240, 128, 113, 142], [248, 241, 148, 140, 143, 63, 222, 195, 202, 210, 244, 74, 102, 0, 190, 200], [29, 45, 179, 186, 183, 88, 115, 91, 115, 240, 60, 133, 170, 156, 139, 215]]
msg=obj.decrypt_cbc(cipher, iv)
msgstr=""
for i in msg:
for j in i:
msgstr+=chr(j)
print("Here is your decrypted message:",unpad(msgstr))
elif choice==3:
text=input("Enter the text to be encrypted:\n")
key=input("Enter 16 bytes long encryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=obj.encrypt_cbc(text,iv)
enctext=""
for i in cipher:
for j in i:
enctext+=chr(j)
encode(enctext)
elif choice==4:
name=input("Enter the name of the image to be decrypted along with proper extension (.png):\n")
rvale=decode(name)
print("The information hidden in image is: ",rvale)
ciphervec = [];
for k in rvale:
ciphervec.append(ord(k))
nlist=[]
tlist=[]
count=0
for i in ciphervec:
tlist.append(i)
if (count+1)%16==0:
nlist.append(list(tlist))
tlist.clear()
count+=1
key=input("Enter 16 bytes long decryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
msg=obj.decrypt_cbc(nlist, iv)
msgstr=""
for i in msg:
for j in i:
msgstr+=chr(j)
print("Here is your decrypted message:",unpad(msgstr))
elif choice==5:
name1=input("Enter the name of the First image (Cover Image) along with proper extension (.jpg):\n")
name2=input("Enter the name of the Second image (Cover Image) along with proper extension (.jpg):\n")
output = 'output.png'
merged_image = Steganography.merge(Image.open(name1), Image.open(name2))
merged_image.save(output)
elif choice==6:
name=input("Enter the name of Cover Image along with proper extension (.png):\n")
output = 'HiddenImage.png'
unmerged_image = Steganography.unmerge(Image.open(name))
unmerged_image.save(output)
| 39.537815 | 323 | 0.596174 | from AES import AES
from AES import unpad
from EncodeDecode import encode
from EncodeDecode import decode
from ImageInsideImage import *
from PIL import Image
if __name__ == '__main__':
print("Enter 1 to Ecrypt a Message Using AES Encryption\nEnter 2 to Decrypt a Message\nEnter 3 to Encrypt a Message and Hide It In Image Using LSB\nEnter 4 to Decrypt a Image\nEnter 5 to Hide Image Inside Another Image\nEnter 6 to Reveal a Image Inside Another Image\nEnter To Hide Image Inside Another Image Without ")
choice=int(input())
if choice==1:
text=input("Enter the text to be encrypted:\n")
key=input("Enter 16 bytes long encryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=obj.encrypt_cbc(text,iv )
enctext=""
for i in cipher:
for j in i:
enctext+=chr(j)
print("Here is your encrypted message:",cipher)
elif choice==2:
print("A list needs to be passed as encrypted text ,so please modify the same in code")
key=input("Enter 16 bytes long decryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=[[82, 214, 73, 255, 189, 148, 31, 109, 36, 213, 241, 19, 240, 128, 113, 142], [248, 241, 148, 140, 143, 63, 222, 195, 202, 210, 244, 74, 102, 0, 190, 200], [29, 45, 179, 186, 183, 88, 115, 91, 115, 240, 60, 133, 170, 156, 139, 215]]
msg=obj.decrypt_cbc(cipher, iv)
msgstr=""
for i in msg:
for j in i:
msgstr+=chr(j)
print("Here is your decrypted message:",unpad(msgstr))
elif choice==3:
text=input("Enter the text to be encrypted:\n")
key=input("Enter 16 bytes long encryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
cipher=obj.encrypt_cbc(text,iv)
enctext=""
for i in cipher:
for j in i:
enctext+=chr(j)
encode(enctext)
elif choice==4:
name=input("Enter the name of the image to be decrypted along with proper extension (.png):\n")
rvale=decode(name)
print("The information hidden in image is: ",rvale)
ciphervec = [];
for k in rvale:
ciphervec.append(ord(k))
nlist=[]
tlist=[]
count=0
for i in ciphervec:
tlist.append(i)
if (count+1)%16==0:
nlist.append(list(tlist))
tlist.clear()
count+=1
key=input("Enter 16 bytes long decryption key:\n")
while(len(key)!=16):
key=input("The length of the key needs to be 16, please enter 16 bytes long key\n")
iv=input("Enter 16 bytes long initialization vector:\n")
while(len(iv)!=16):
iv=input("The length of the initialization vector needs to be 16, please enter 16 bytes long iv\n")
obj=AES(key)
msg=obj.decrypt_cbc(nlist, iv)
msgstr=""
for i in msg:
for j in i:
msgstr+=chr(j)
print("Here is your decrypted message:",unpad(msgstr))
elif choice==5:
name1=input("Enter the name of the First image (Cover Image) along with proper extension (.jpg):\n")
name2=input("Enter the name of the Second image (Cover Image) along with proper extension (.jpg):\n")
output = 'output.png'
merged_image = Steganography.merge(Image.open(name1), Image.open(name2))
merged_image.save(output)
elif choice==6:
name=input("Enter the name of Cover Image along with proper extension (.png):\n")
output = 'HiddenImage.png'
unmerged_image = Steganography.unmerge(Image.open(name))
unmerged_image.save(output)
| true | true |
f729c7e980aec839545c12cbfe4598a07623ad46 | 721 | py | Python | tests/locust.py | geru-br/keyloop | b3147984ef2517d5d53518f969ad9637e1b54a00 | [
"MIT"
] | 1 | 2022-01-18T08:04:18.000Z | 2022-01-18T08:04:18.000Z | tests/locust.py | geru-br/keyloop | b3147984ef2517d5d53518f969ad9637e1b54a00 | [
"MIT"
] | 1 | 2020-03-16T20:35:07.000Z | 2020-03-16T20:35:07.000Z | tests/locust.py | geru-br/keyloop | b3147984ef2517d5d53518f969ad9637e1b54a00 | [
"MIT"
] | null | null | null | from locust import HttpLocust, TaskSet, between
import json
def login(l):
headers = {'content-type': 'application/vnd.api+json'}
l.client.post(
"/api/v1/realms/PLAYGROUND/auth-session",
data=json.dumps({
"data": {
"type":"auth-session",
"attributes":{
"username":"test@test.com.br",
"password":"1234567a"
}
}
}),
headers=headers
)
class UserBehavior(TaskSet):
tasks = {login: 1}
def on_start(self):
login(self)
def on_stop(self):
pass
class WebsiteUser(HttpLocust):
task_set = UserBehavior
wait_time = between(5.0, 9.0)
| 20.6 | 58 | 0.522885 | from locust import HttpLocust, TaskSet, between
import json
def login(l):
headers = {'content-type': 'application/vnd.api+json'}
l.client.post(
"/api/v1/realms/PLAYGROUND/auth-session",
data=json.dumps({
"data": {
"type":"auth-session",
"attributes":{
"username":"test@test.com.br",
"password":"1234567a"
}
}
}),
headers=headers
)
class UserBehavior(TaskSet):
tasks = {login: 1}
def on_start(self):
login(self)
def on_stop(self):
pass
class WebsiteUser(HttpLocust):
task_set = UserBehavior
wait_time = between(5.0, 9.0)
| true | true |
f729c9a3f69ec5fcd9aca062440ddcccfde15089 | 14,997 | py | Python | replaying/test.py | jdey4/progressive-learning | 410b3525ab63e1f7c32e9838460b2c9af7b9d256 | [
"Apache-2.0"
] | 1 | 2022-01-03T12:36:28.000Z | 2022-01-03T12:36:28.000Z | replaying/test.py | jdey4/progressive-learning | 410b3525ab63e1f7c32e9838460b2c9af7b9d256 | [
"Apache-2.0"
] | null | null | null | replaying/test.py | jdey4/progressive-learning | 410b3525ab63e1f7c32e9838460b2c9af7b9d256 | [
"Apache-2.0"
] | null | null | null | #%%
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
import seaborn as sns
import numpy as np
import pickle
from sklearn.model_selection import StratifiedKFold
from math import log2, ceil
import sys
#sys.path.append("../src/")
sys.path.append("../src_sampling/")
from lifelong_dnn import LifeLongDNN
from joblib import Parallel, delayed
#%%
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def get_colors(colors, inds):
c = [colors[i] for i in inds]
return c
def generate_2d_rotation(theta=0, acorn=None):
if acorn is not None:
np.random.seed(acorn)
R = np.array([
[np.cos(theta), np.sin(theta)],
[-np.sin(theta), np.cos(theta)]
])
return R
def generate_gaussian_parity(n, mean=np.array([-1, -1]), cov_scale=1, angle_params=None, k=1, acorn=None):
if acorn is not None:
np.random.seed(acorn)
d = len(mean)
if mean[0] == -1 and mean[1] == -1:
mean = mean + 1 / 2**k
mnt = np.random.multinomial(n, 1/(4**k) * np.ones(4**k))
cumsum = np.cumsum(mnt)
cumsum = np.concatenate(([0], cumsum))
Y = np.zeros(n)
X = np.zeros((n, d))
for i in range(2**k):
for j in range(2**k):
temp = np.random.multivariate_normal(mean, cov_scale * np.eye(d),
size=mnt[i*(2**k) + j])
temp[:, 0] += i*(1/2**(k-1))
temp[:, 1] += j*(1/2**(k-1))
X[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = temp
if i % 2 == j % 2:
Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 0
else:
Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 1
if d == 2:
if angle_params is None:
angle_params = np.random.uniform(0, 2*np.pi)
R = generate_2d_rotation(angle_params)
X = X @ R
else:
raise ValueError('d=%i not implemented!'%(d))
return X, Y.astype(int)
#%%
def experiment(n_xor, n_nxor, n_test, reps, n_trees, max_depth, acorn=None):
#print(1)
if n_xor==0 and n_nxor==0:
raise ValueError('Wake up and provide samples to train!!!')
if acorn != None:
np.random.seed(acorn)
errors = np.zeros((reps,4),dtype=float)
for i in range(reps):
l2f = LifeLongDNN(parallel=False)
uf1 = LifeLongDNN(parallel=False)
uf2 = LifeLongDNN(parallel=False)
#source data
xor, label_xor = generate_gaussian_parity(n_xor,cov_scale=0.1,angle_params=0)
test_xor, test_label_xor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=0)
'''min_xor = np.min(xor)
xor = (xor - min_xor)
max_xor = np.max(xor)
xor = xor/max_xor
test_xor = (test_xor-min_xor)/max_xor'''
#target data
if n_nxor!=0:
nxor, label_nxor = generate_gaussian_parity(n_nxor,cov_scale=0.1,angle_params=np.pi/2)
test_nxor, test_label_nxor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=np.pi/2)
'''min_nxor = np.min(nxor)
nxor = (nxor - min_nxor)
max_nxor = np.max(nxor)
nxor = nxor/max_nxor
test_nxor = (test_nxor-min_nxor)/max_nxor'''
if n_xor == 0:
l2f.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)
errors[i,0] = 0.5
errors[i,1] = 0.5
uf_task2=l2f.predict(test_nxor, representation=0, decider=0)
l2f_task2=l2f.predict(test_nxor, representation='all', decider=0)
errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test
errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test
elif n_nxor == 0:
l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)
uf_task1=l2f.predict(test_xor, representation=0, decider=0)
l2f_task1=l2f.predict(test_xor, representation='all', decider=0)
errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test
errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test
errors[i,2] = 0.5
errors[i,3] = 0.5
else:
l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)
delta = .001
#sample the grid
x = np.arange(-1,1,step=delta)
y = np.arange(-1,1,step=delta)
x,y = np.meshgrid(x,y)
sample = np.concatenate(
(
x.reshape(-1,1),
y.reshape(-1,1)
),
axis=1
)
#sample_label = l2f.predict(sample, representation=0,decider=0)
sample_label = l2f._estimate_posteriors(sample, representation='all', decider=0)
l2f.X_across_tasks[0] = sample
l2f.y_across_tasks[0] = sample_label
############################
l2f.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)
uf1.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)
uf2.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)
uf_task1=uf1.predict(test_xor, representation=0, decider=0)
l2f_task1=l2f.predict(test_xor, representation='all', decider=0)
uf_task2=uf2.predict(test_nxor, representation=0, decider=0)
l2f_task2=l2f.predict(test_nxor, representation='all', decider=1)
errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test
errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test
errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test
errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test
return np.mean(errors,axis=0)
#%%
mc_rep = 1000
n_test = 1000
n_trees = 10
n_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)
n_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)
mean_error = np.zeros((4, len(n_xor)+len(n_nxor)))
std_error = np.zeros((4, len(n_xor)+len(n_nxor)))
mean_te = np.zeros((2, len(n_xor)+len(n_nxor)))
std_te = np.zeros((2, len(n_xor)+len(n_nxor)))
for i,n1 in enumerate(n_xor):
print('starting to compute %s xor\n'%n1)
error = np.array(
Parallel(n_jobs=-1,verbose=1)(
delayed(experiment)(n1,0,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)
)
)
mean_error[:,i] = np.mean(error,axis=0)
std_error[:,i] = np.std(error,ddof=1,axis=0)
mean_te[0,i] = np.mean(error[:,0]/error[:,1])
mean_te[1,i] = np.mean(error[:,2]/error[:,3])
std_te[0,i] = np.std(error[:,0]/error[:,1],ddof=1)
std_te[1,i] = np.std(error[:,2]/error[:,3],ddof=1)
if n1==n_xor[-1]:
for j,n2 in enumerate(n_nxor):
print('starting to compute %s nxor\n'%n2)
error = np.array(
Parallel(n_jobs=-1,verbose=1)(
delayed(experiment)(n1,n2,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)
)
)
mean_error[:,i+j+1] = np.mean(error,axis=0)
std_error[:,i+j+1] = np.std(error,ddof=1,axis=0)
mean_te[0,i+j+1] = np.mean(error[:,0]/error[:,1])
mean_te[1,i+j+1] = np.mean(error[:,2]/error[:,3])
std_te[0,i+j+1] = np.std(error[:,0]/error[:,1],ddof=1)
std_te[1,i+j+1] = np.std(error[:,2]/error[:,3],ddof=1)
with open('./result/mean_xor_nxor.pickle','wb') as f:
pickle.dump(mean_error,f)
with open('./result/std_xor_nxor.pickle','wb') as f:
pickle.dump(std_error,f)
with open('./result/mean_te_xor_nxor.pickle','wb') as f:
pickle.dump(mean_te,f)
with open('./result/std_te_xor_nxor.pickle','wb') as f:
pickle.dump(std_te,f)
#%% Plotting the result
#mc_rep = 50
mean_error = unpickle('result/mean_xor_nxor.pickle')
std_error = unpickle('result/std_xor_nxor.pickle')
n_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)
n_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)
n1s = n_xor
n2s = n_nxor
ns = np.concatenate((n1s, n2s + n1s[-1]))
ls=['-', '--']
algorithms = ['Uncertainty Forest', 'Lifelong Forest']
TASK1='XOR'
TASK2='N-XOR'
fontsize=30
labelsize=28
colors = sns.color_palette("Set1", n_colors = 2)
fig = plt.figure(constrained_layout=True,figsize=(21,14))
gs = fig.add_gridspec(14, 21)
ax1 = fig.add_subplot(gs[7:,:6])
# for i, algo in enumerate(algorithms):
ax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[1], ls=ls[np.sum(0 > 1).astype(int)], lw=3)
#ax1.fill_between(ns,
# mean_error[0] + 1.96*std_error[0],
# mean_error[0] - 1.96*std_error[0],
# where=mean_error[0] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0],
# facecolor=colors[1],
# alpha=0.15,
# interpolate=True)
ax1.plot(ns, mean_error[1], label=algorithms[1], c=colors[0], ls=ls[np.sum(1 > 1).astype(int)], lw=3)
#ax1.fill_between(ns,
# mean_error[1] + 1.96*std_error[1, ],
# mean_error[1] - 1.96*std_error[1, ],
# where=mean_error[1] + 1.96*std_error[1] >= mean_error[1] - 1.96*std_error[1],
# facecolor=colors[0],
# alpha=0.15,
# interpolate=True)
ax1.set_ylabel('Generalization Error (%s)'%(TASK1), fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
ax1.set_ylim(0.1, 0.21)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
ax1.set_yticks([0.15, 0.2])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
ax1.set_title('XOR', fontsize=30)
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
#plt.tight_layout()
#plt.savefig('./result/figs/generalization_error_xor.pdf',dpi=500)
#####
mean_error = unpickle('result/mean_xor_nxor.pickle')
std_error = unpickle('result/std_xor_nxor.pickle')
algorithms = ['Uncertainty Forest', 'Lifelong Forest']
TASK1='XOR'
TASK2='N-XOR'
ax1 = fig.add_subplot(gs[7:,7:13])
# for i, algo in enumerate(algorithms):
ax1.plot(ns[len(n1s):], mean_error[2, len(n1s):], label=algorithms[0], c=colors[1], ls=ls[1], lw=3)
#ax1.fill_between(ns[len(n1s):],
# mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):],
# mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):],
# where=mean_error[2, len(n1s):] + 1.96*std_error[2, len(n1s):] >= mean_error[2, len(n1s):] - 1.96*std_error[2, len(n1s):],
# facecolor=colors[1],
# alpha=0.15,
# interpolate=True)
ax1.plot(ns[len(n1s):], mean_error[3, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)
#ax1.fill_between(ns[len(n1s):],
# mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):],
# mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):],
# where=mean_error[3, len(n1s):] + 1.96*std_error[3, len(n1s):] >= mean_error[3, len(n1s):] - 1.96*std_error[3, len(n1s):],
# facecolor=colors[0],
# alpha=0.15,
# interpolate=True)
ax1.set_ylabel('Generalization Error (%s)'%(TASK2), fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
# ax1.set_ylim(-0.01, 0.22)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
# ax1.set_yticks([0.15, 0.25, 0.35])
ax1.set_yticks([0.15, 0.2])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
ax1.set_ylim(0.11, 0.21)
ax1.set_xlim(-10)
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
# ax1.set_ylim(0.14, 0.36)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
ax1.set_title('N-XOR', fontsize=30)
#plt.tight_layout()
#plt.savefig('./result/figs/generalization_error_nxor.pdf',dpi=500)
#####
mean_error = unpickle('result/mean_te_xor_nxor.pickle')
std_error = unpickle('result/std_te_xor_nxor.pickle')
algorithms = ['Backward Transfer', 'Forward Transfer']
TASK1='XOR'
TASK2='N-XOR'
ax1 = fig.add_subplot(gs[7:,14:])
ax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)
#ax1.fill_between(ns,
# mean_error[0] + 1.96*std_error[0],
# mean_error[0] - 1.96*std_error[0],
# where=mean_error[1] + 1.96*std_error[0] >= mean_error[0] - 1.96*std_error[0],
# facecolor=colors[0],
# alpha=0.15,
# interpolate=True)
ax1.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)
#ax1.fill_between(ns[len(n1s):],
# mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):],
# mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):],
# where=mean_error[1, len(n1s):] + 1.96*std_error[1, len(n1s):] >= mean_error[1, len(n1s):] - 1.96*std_error[1, len(n1s):],
# facecolor=colors[0],
# alpha=0.15,
# interpolate=True)
ax1.set_ylabel('Transfer Efficiency', fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
ax1.set_ylim(.99, 1.4)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
ax1.set_yticks([1,1.2,1.4])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
ax1.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
#plt.tight_layout()
#plt.savefig('./result/figs/TE.pdf',dpi=500)
#####
colors = sns.color_palette('Dark2', n_colors=2)
X, Y = generate_gaussian_parity(750, cov_scale=0.1, angle_params=0)
Z, W = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/2)
ax = fig.add_subplot(gs[:6,4:10])
ax.scatter(X[:, 0], X[:, 1], c=get_colors(colors, Y), s=50)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Gaussian XOR', fontsize=30)
plt.tight_layout()
ax.axis('off')
#plt.savefig('./result/figs/gaussian-xor.pdf')
###
colors = sns.color_palette('Dark2', n_colors=2)
ax = fig.add_subplot(gs[:6,11:16])
ax.scatter(Z[:, 0], Z[:, 1], c=get_colors(colors, W), s=50)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Gaussian N-XOR', fontsize=30)
ax.axis('off')
#plt.tight_layout()
plt.savefig('./result/figs/xor_nxor_exp_sampling.pdf')
# %%
| 34.161731 | 131 | 0.609122 |
import random
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
import seaborn as sns
import numpy as np
import pickle
from sklearn.model_selection import StratifiedKFold
from math import log2, ceil
import sys
sys.path.append("../src_sampling/")
from lifelong_dnn import LifeLongDNN
from joblib import Parallel, delayed
def unpickle(file):
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def get_colors(colors, inds):
c = [colors[i] for i in inds]
return c
def generate_2d_rotation(theta=0, acorn=None):
if acorn is not None:
np.random.seed(acorn)
R = np.array([
[np.cos(theta), np.sin(theta)],
[-np.sin(theta), np.cos(theta)]
])
return R
def generate_gaussian_parity(n, mean=np.array([-1, -1]), cov_scale=1, angle_params=None, k=1, acorn=None):
if acorn is not None:
np.random.seed(acorn)
d = len(mean)
if mean[0] == -1 and mean[1] == -1:
mean = mean + 1 / 2**k
mnt = np.random.multinomial(n, 1/(4**k) * np.ones(4**k))
cumsum = np.cumsum(mnt)
cumsum = np.concatenate(([0], cumsum))
Y = np.zeros(n)
X = np.zeros((n, d))
for i in range(2**k):
for j in range(2**k):
temp = np.random.multivariate_normal(mean, cov_scale * np.eye(d),
size=mnt[i*(2**k) + j])
temp[:, 0] += i*(1/2**(k-1))
temp[:, 1] += j*(1/2**(k-1))
X[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = temp
if i % 2 == j % 2:
Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 0
else:
Y[cumsum[i*(2**k) + j]:cumsum[i*(2**k) + j + 1]] = 1
if d == 2:
if angle_params is None:
angle_params = np.random.uniform(0, 2*np.pi)
R = generate_2d_rotation(angle_params)
X = X @ R
else:
raise ValueError('d=%i not implemented!'%(d))
return X, Y.astype(int)
def experiment(n_xor, n_nxor, n_test, reps, n_trees, max_depth, acorn=None):
if n_xor==0 and n_nxor==0:
raise ValueError('Wake up and provide samples to train!!!')
if acorn != None:
np.random.seed(acorn)
errors = np.zeros((reps,4),dtype=float)
for i in range(reps):
l2f = LifeLongDNN(parallel=False)
uf1 = LifeLongDNN(parallel=False)
uf2 = LifeLongDNN(parallel=False)
xor, label_xor = generate_gaussian_parity(n_xor,cov_scale=0.1,angle_params=0)
test_xor, test_label_xor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=0)
if n_nxor!=0:
nxor, label_nxor = generate_gaussian_parity(n_nxor,cov_scale=0.1,angle_params=np.pi/2)
test_nxor, test_label_nxor = generate_gaussian_parity(n_test,cov_scale=0.1,angle_params=np.pi/2)
if n_xor == 0:
l2f.new_forest(nxor, label_nxor, n_estimators=n_trees,max_depth=max_depth)
errors[i,0] = 0.5
errors[i,1] = 0.5
uf_task2=l2f.predict(test_nxor, representation=0, decider=0)
l2f_task2=l2f.predict(test_nxor, representation='all', decider=0)
errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test
errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test
elif n_nxor == 0:
l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)
uf_task1=l2f.predict(test_xor, representation=0, decider=0)
l2f_task1=l2f.predict(test_xor, representation='all', decider=0)
errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test
errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test
errors[i,2] = 0.5
errors[i,3] = 0.5
else:
l2f.new_forest(xor, label_xor, n_estimators=n_trees,max_depth=max_depth)
delta = .001
x = np.arange(-1,1,step=delta)
y = np.arange(-1,1,step=delta)
x,y = np.meshgrid(x,y)
sample = np.concatenate(
(
x.reshape(-1,1),
y.reshape(-1,1)
),
axis=1
)
sample_label = l2f._estimate_posteriors(sample, representation='all', decider=0)
l2f.X_across_tasks[0] = sample
l2f.y_across_tasks[0] = sample_label
ct(test_xor, representation='all', decider=0)
uf_task2=uf2.predict(test_nxor, representation=0, decider=0)
l2f_task2=l2f.predict(test_nxor, representation='all', decider=1)
errors[i,0] = 1 - np.sum(uf_task1 == test_label_xor)/n_test
errors[i,1] = 1 - np.sum(l2f_task1 == test_label_xor)/n_test
errors[i,2] = 1 - np.sum(uf_task2 == test_label_nxor)/n_test
errors[i,3] = 1 - np.sum(l2f_task2 == test_label_nxor)/n_test
return np.mean(errors,axis=0)
mc_rep = 1000
n_test = 1000
n_trees = 10
n_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)
n_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)
mean_error = np.zeros((4, len(n_xor)+len(n_nxor)))
std_error = np.zeros((4, len(n_xor)+len(n_nxor)))
mean_te = np.zeros((2, len(n_xor)+len(n_nxor)))
std_te = np.zeros((2, len(n_xor)+len(n_nxor)))
for i,n1 in enumerate(n_xor):
print('starting to compute %s xor\n'%n1)
error = np.array(
Parallel(n_jobs=-1,verbose=1)(
delayed(experiment)(n1,0,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)
)
)
mean_error[:,i] = np.mean(error,axis=0)
std_error[:,i] = np.std(error,ddof=1,axis=0)
mean_te[0,i] = np.mean(error[:,0]/error[:,1])
mean_te[1,i] = np.mean(error[:,2]/error[:,3])
std_te[0,i] = np.std(error[:,0]/error[:,1],ddof=1)
std_te[1,i] = np.std(error[:,2]/error[:,3],ddof=1)
if n1==n_xor[-1]:
for j,n2 in enumerate(n_nxor):
print('starting to compute %s nxor\n'%n2)
error = np.array(
Parallel(n_jobs=-1,verbose=1)(
delayed(experiment)(n1,n2,n_test,1,n_trees=n_trees,max_depth=200) for _ in range(mc_rep)
)
)
mean_error[:,i+j+1] = np.mean(error,axis=0)
std_error[:,i+j+1] = np.std(error,ddof=1,axis=0)
mean_te[0,i+j+1] = np.mean(error[:,0]/error[:,1])
mean_te[1,i+j+1] = np.mean(error[:,2]/error[:,3])
std_te[0,i+j+1] = np.std(error[:,0]/error[:,1],ddof=1)
std_te[1,i+j+1] = np.std(error[:,2]/error[:,3],ddof=1)
with open('./result/mean_xor_nxor.pickle','wb') as f:
pickle.dump(mean_error,f)
with open('./result/std_xor_nxor.pickle','wb') as f:
pickle.dump(std_error,f)
with open('./result/mean_te_xor_nxor.pickle','wb') as f:
pickle.dump(mean_te,f)
with open('./result/std_te_xor_nxor.pickle','wb') as f:
pickle.dump(std_te,f)
mean_error = unpickle('result/mean_xor_nxor.pickle')
std_error = unpickle('result/std_xor_nxor.pickle')
n_xor = (100*np.arange(0.5, 7.25, step=0.25)).astype(int)
n_nxor = (100*np.arange(0.5, 7.5, step=0.25)).astype(int)
n1s = n_xor
n2s = n_nxor
ns = np.concatenate((n1s, n2s + n1s[-1]))
ls=['-', '--']
algorithms = ['Uncertainty Forest', 'Lifelong Forest']
TASK1='XOR'
TASK2='N-XOR'
fontsize=30
labelsize=28
colors = sns.color_palette("Set1", n_colors = 2)
fig = plt.figure(constrained_layout=True,figsize=(21,14))
gs = fig.add_gridspec(14, 21)
ax1 = fig.add_subplot(gs[7:,:6])
ax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[1], ls=ls[np.sum(0 > 1).astype(int)], lw=3)
ax1.plot(ns, mean_error[1], label=algorithms[1], c=colors[0], ls=ls[np.sum(1 > 1).astype(int)], lw=3)
ax1.set_ylabel('Generalization Error (%s)'%(TASK1), fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
ax1.set_ylim(0.1, 0.21)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
ax1.set_yticks([0.15, 0.2])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
ax1.set_title('XOR', fontsize=30)
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
r = unpickle('result/mean_xor_nxor.pickle')
std_error = unpickle('result/std_xor_nxor.pickle')
algorithms = ['Uncertainty Forest', 'Lifelong Forest']
TASK1='XOR'
TASK2='N-XOR'
ax1 = fig.add_subplot(gs[7:,7:13])
ax1.plot(ns[len(n1s):], mean_error[2, len(n1s):], label=algorithms[0], c=colors[1], ls=ls[1], lw=3)
ax1.plot(ns[len(n1s):], mean_error[3, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)
ax1.set_ylabel('Generalization Error (%s)'%(TASK2), fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
ax1.set_yticks([0.15, 0.2])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
ax1.set_ylim(0.11, 0.21)
ax1.set_xlim(-10)
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
ax1.set_title('N-XOR', fontsize=30)
r = unpickle('result/mean_te_xor_nxor.pickle')
std_error = unpickle('result/std_te_xor_nxor.pickle')
algorithms = ['Backward Transfer', 'Forward Transfer']
TASK1='XOR'
TASK2='N-XOR'
ax1 = fig.add_subplot(gs[7:,14:])
ax1.plot(ns, mean_error[0], label=algorithms[0], c=colors[0], ls=ls[0], lw=3)
ax1.plot(ns[len(n1s):], mean_error[1, len(n1s):], label=algorithms[1], c=colors[0], ls=ls[1], lw=3)
ax1.set_ylabel('Transfer Efficiency', fontsize=fontsize)
ax1.legend(loc='upper right', fontsize=20, frameon=False)
ax1.set_ylim(.99, 1.4)
ax1.set_xlabel('Total Sample Size', fontsize=fontsize)
ax1.tick_params(labelsize=labelsize)
ax1.set_yticks([1,1.2,1.4])
ax1.set_xticks([250,750, 1500])
ax1.axvline(x=750, c='gray', linewidth=1.5, linestyle="dashed")
right_side = ax1.spines["right"]
right_side.set_visible(False)
top_side = ax1.spines["top"]
top_side.set_visible(False)
ax1.hlines(1, 50,1500, colors='gray', linestyles='dashed',linewidth=1.5)
ax1.text(250, np.mean(ax1.get_ylim()), "%s"%(TASK1), fontsize=26)
ax1.text(900, np.mean(ax1.get_ylim()), "%s"%(TASK2), fontsize=26)
sns.color_palette('Dark2', n_colors=2)
X, Y = generate_gaussian_parity(750, cov_scale=0.1, angle_params=0)
Z, W = generate_gaussian_parity(750, cov_scale=0.1, angle_params=np.pi/2)
ax = fig.add_subplot(gs[:6,4:10])
ax.scatter(X[:, 0], X[:, 1], c=get_colors(colors, Y), s=50)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Gaussian XOR', fontsize=30)
plt.tight_layout()
ax.axis('off')
lors = sns.color_palette('Dark2', n_colors=2)
ax = fig.add_subplot(gs[:6,11:16])
ax.scatter(Z[:, 0], Z[:, 1], c=get_colors(colors, W), s=50)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Gaussian N-XOR', fontsize=30)
ax.axis('off')
plt.savefig('./result/figs/xor_nxor_exp_sampling.pdf')
| true | true |
f729c9de35d9d43e20ad9af19e86a468191ed2af | 374 | py | Python | os_hek/handler.py | holy-crust/reclaimer | 0aa693da3866ce7999c68d5f71f31a9c932cdb2c | [
"MIT"
] | null | null | null | os_hek/handler.py | holy-crust/reclaimer | 0aa693da3866ce7999c68d5f71f31a9c932cdb2c | [
"MIT"
] | null | null | null | os_hek/handler.py | holy-crust/reclaimer | 0aa693da3866ce7999c68d5f71f31a9c932cdb2c | [
"MIT"
] | null | null | null | import os
from reclaimer.hek.handler import HaloHandler
from reclaimer.os_hek.defs import __all__ as all_def_names
from supyr_struct.defs.constants import PATHDIV
class OsHaloHandler(HaloHandler):
frozen_imp_paths = all_def_names
default_defs_path = "reclaimer.os_hek.defs"
tagsdir = "%s%stags%s" % (os.path.abspath(os.curdir), PATHDIV, PATHDIV)
| 28.769231 | 76 | 0.759358 | import os
from reclaimer.hek.handler import HaloHandler
from reclaimer.os_hek.defs import __all__ as all_def_names
from supyr_struct.defs.constants import PATHDIV
class OsHaloHandler(HaloHandler):
frozen_imp_paths = all_def_names
default_defs_path = "reclaimer.os_hek.defs"
tagsdir = "%s%stags%s" % (os.path.abspath(os.curdir), PATHDIV, PATHDIV)
| true | true |
f729ca133af8f808a4bd13c6fcf77aa56d146c25 | 4,687 | py | Python | google/appengine/tools/devappserver2/admin/blobstore_viewer.py | vladushakov987/appengine_python3 | 0dd481c73e2537a50ee10f1b79cd65938087e555 | [
"Apache-2.0"
] | null | null | null | google/appengine/tools/devappserver2/admin/blobstore_viewer.py | vladushakov987/appengine_python3 | 0dd481c73e2537a50ee10f1b79cd65938087e555 | [
"Apache-2.0"
] | null | null | null | google/appengine/tools/devappserver2/admin/blobstore_viewer.py | vladushakov987/appengine_python3 | 0dd481c73e2537a50ee10f1b79cd65938087e555 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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.
#
"""A handler that displays information about blobstore blobs."""
from builtins import str
from google.appengine.ext import blobstore
from google.appengine.tools.devappserver2.admin import admin_request_handler
def _get_blobs(start, limit):
"""Return a list of BlobInfo objects ordered by most recently created.
Args:
start: The offset of the first blobstore.BlobInfo instances to return,
ordered by descending creation time.
limit: The maximum number of blobstore.BlobInfo blobstore to return.
Returns:
A list of blobstore.BlobInfo blobstore ordered by most recently created.
"""
q = blobstore.BlobInfo.all().order('-creation')
return q.fetch(limit, offset=start)
class BlobstoreRequestHandler(admin_request_handler.AdminRequestHandler):
"""A handler that displays information about blobstore blobs."""
BLOBS_PER_PAGE = 20
def get(self):
offset = int(self.request.get('offset', 0))
# Fetch an extra item to check if the next button should be enabled.
blob_infos = _get_blobs(offset, self.BLOBS_PER_PAGE+1)
if len(blob_infos) == self.BLOBS_PER_PAGE + 1:
next_offset = offset + self.BLOBS_PER_PAGE
else:
next_offset = None
previous = max(0, offset - self.BLOBS_PER_PAGE) if offset > 0 else None
self.response.write(self.render('blobstore_viewer.html', {
'blob_infos': blob_infos[:self.BLOBS_PER_PAGE],
'offset': offset,
'next': next_offset,
'previous': previous,
'return_to': self.request.uri}))
def post(self):
"""Deletes blobs identified in 'blob_key' form variables.
Multiple keys can be specified e.g. '...&blob_key=key1&blob_key=key2'.
Redirects the client back to the value specified in the 'return_to' form
variable.
"""
redirect_url = str(self.request.get('return_to', '/blobstore'))
keys = self.request.get_all('blob_key')
blobstore.delete(keys)
self.redirect(redirect_url)
class BlobRequestHandler(admin_request_handler.AdminRequestHandler):
"""A handler that displays information about a single blobstore blobs."""
# Content types that can be displayed with 'content-disposition: inline'.
# Some browsers can inline other contents, e.g. application/pdf,
# but not all so, those types are not in the list.
INLINEABLE_TYPES = ('image/', 'text/plain')
def get(self, key):
blob_info = blobstore.BlobInfo.get(key)
if blob_info is None:
# TODO: Display a message saying that this blob no longer
# exists.
self.redirect('/blobstore')
return
display = self.request.get('display')
if display:
self._display_blob(blob_info, display)
else:
self._display_blob_info(blob_info,
self.request.get('return_to', '/blobstore'))
def _display_blob_info(self, blob_info, return_url):
inlineable = False
for t in self.INLINEABLE_TYPES:
if blob_info.content_type.startswith(t):
inlineable = True
break
self.response.write(self.render('blob_viewer.html', {
'blob_info': blob_info,
'delete_uri': '/blobstore',
'download_uri': '%s?display=attachment' % self.request.path,
'inline_uri': '%s?display=inline' % self.request.path,
'inlineable': inlineable,
'return_to': return_url}))
def _display_blob(self, blob_info, content_disposition):
content_type = str(blob_info.content_type)
if (content_type == 'application/octet-stream' and
content_disposition == 'inline'):
# Try to display blob bytes as characters since some files (e.g. diffs)
# may be uploaded as application/octet stream but still have plain text
# content.
content_type = 'text/plain'
if content_disposition == 'attachment' and blob_info.filename:
content_disposition += '; filename=%s' % blob_info.filename
self.response.headers['Content-Type'] = content_type
self.response.headers['Content-Disposition'] = str(content_disposition)
reader = blob_info.open()
self.response.write(reader.read())
reader.close()
| 36.333333 | 77 | 0.704288 |
from builtins import str
from google.appengine.ext import blobstore
from google.appengine.tools.devappserver2.admin import admin_request_handler
def _get_blobs(start, limit):
q = blobstore.BlobInfo.all().order('-creation')
return q.fetch(limit, offset=start)
class BlobstoreRequestHandler(admin_request_handler.AdminRequestHandler):
BLOBS_PER_PAGE = 20
def get(self):
offset = int(self.request.get('offset', 0))
blob_infos = _get_blobs(offset, self.BLOBS_PER_PAGE+1)
if len(blob_infos) == self.BLOBS_PER_PAGE + 1:
next_offset = offset + self.BLOBS_PER_PAGE
else:
next_offset = None
previous = max(0, offset - self.BLOBS_PER_PAGE) if offset > 0 else None
self.response.write(self.render('blobstore_viewer.html', {
'blob_infos': blob_infos[:self.BLOBS_PER_PAGE],
'offset': offset,
'next': next_offset,
'previous': previous,
'return_to': self.request.uri}))
def post(self):
redirect_url = str(self.request.get('return_to', '/blobstore'))
keys = self.request.get_all('blob_key')
blobstore.delete(keys)
self.redirect(redirect_url)
class BlobRequestHandler(admin_request_handler.AdminRequestHandler):
INLINEABLE_TYPES = ('image/', 'text/plain')
def get(self, key):
blob_info = blobstore.BlobInfo.get(key)
if blob_info is None:
self.redirect('/blobstore')
return
display = self.request.get('display')
if display:
self._display_blob(blob_info, display)
else:
self._display_blob_info(blob_info,
self.request.get('return_to', '/blobstore'))
def _display_blob_info(self, blob_info, return_url):
inlineable = False
for t in self.INLINEABLE_TYPES:
if blob_info.content_type.startswith(t):
inlineable = True
break
self.response.write(self.render('blob_viewer.html', {
'blob_info': blob_info,
'delete_uri': '/blobstore',
'download_uri': '%s?display=attachment' % self.request.path,
'inline_uri': '%s?display=inline' % self.request.path,
'inlineable': inlineable,
'return_to': return_url}))
def _display_blob(self, blob_info, content_disposition):
content_type = str(blob_info.content_type)
if (content_type == 'application/octet-stream' and
content_disposition == 'inline'):
content_type = 'text/plain'
if content_disposition == 'attachment' and blob_info.filename:
content_disposition += '; filename=%s' % blob_info.filename
self.response.headers['Content-Type'] = content_type
self.response.headers['Content-Disposition'] = str(content_disposition)
reader = blob_info.open()
self.response.write(reader.read())
reader.close()
| true | true |
f729cab4dd26ab9cc864f67022e320fa974f4e5b | 2,323 | py | Python | src/programy/parser/template/nodes/oob.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | null | null | null | src/programy/parser/template/nodes/oob.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | null | null | null | src/programy/parser/template/nodes/oob.py | ItsPhant/program-y | c2b211fcaf8cedc7d6d95a8ea9470a913efa1622 | [
"MIT"
] | 1 | 2020-02-21T17:58:05.000Z | 2020-02-21T17:58:05.000Z | """
Copyright (c) 2016-17 Keith Sterling http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import logging
from programy.parser.template.nodes.base import TemplateNode
class TemplateOOBNode(TemplateNode):
def __init__(self):
TemplateNode.__init__(self)
def resolve_to_string(self, bot, clientid):
resolved = self.resolve_children_to_string(bot, clientid)
if logging.getLogger().isEnabledFor(logging.DEBUG):
logging.debug("[%s] resolved to [%s]", self.to_string(), resolved)
return "<oob>" + resolved + "</oob>"
def resolve(self, bot, clientid):
try:
return self.resolve_to_string(bot, clientid)
except Exception as excep:
logging.exception(excep)
return ""
def to_string(self):
return "OOB"
def to_xml(self, bot, clientid):
xml = "<oob>"
xml += self.children_to_xml(bot, clientid)
xml += "</oob>"
return xml
def parse_expression(self, graph, expression):
head_text = self.get_text_from_element(expression)
self.parse_text(graph, head_text)
for child in expression:
graph.parse_tag_expression(child, self)
tail_text = self.get_tail_from_element(child)
self.parse_text(graph, tail_text)
| 39.372881 | 120 | 0.712441 |
import logging
from programy.parser.template.nodes.base import TemplateNode
class TemplateOOBNode(TemplateNode):
def __init__(self):
TemplateNode.__init__(self)
def resolve_to_string(self, bot, clientid):
resolved = self.resolve_children_to_string(bot, clientid)
if logging.getLogger().isEnabledFor(logging.DEBUG):
logging.debug("[%s] resolved to [%s]", self.to_string(), resolved)
return "<oob>" + resolved + "</oob>"
def resolve(self, bot, clientid):
try:
return self.resolve_to_string(bot, clientid)
except Exception as excep:
logging.exception(excep)
return ""
def to_string(self):
return "OOB"
def to_xml(self, bot, clientid):
xml = "<oob>"
xml += self.children_to_xml(bot, clientid)
xml += "</oob>"
return xml
def parse_expression(self, graph, expression):
head_text = self.get_text_from_element(expression)
self.parse_text(graph, head_text)
for child in expression:
graph.parse_tag_expression(child, self)
tail_text = self.get_tail_from_element(child)
self.parse_text(graph, tail_text)
| true | true |
f729ccd1764351f7fd3a6bde73c400cfff35b597 | 282 | py | Python | create-target-array-in-the-given-order/create-target-array-in-the-given-order.py | ARBII-xD/Solving-Leetcode-Problems | 4631d66e46fce204afbe6d72e89aeedaf2192229 | [
"MIT"
] | null | null | null | create-target-array-in-the-given-order/create-target-array-in-the-given-order.py | ARBII-xD/Solving-Leetcode-Problems | 4631d66e46fce204afbe6d72e89aeedaf2192229 | [
"MIT"
] | null | null | null | create-target-array-in-the-given-order/create-target-array-in-the-given-order.py | ARBII-xD/Solving-Leetcode-Problems | 4631d66e46fce204afbe6d72e89aeedaf2192229 | [
"MIT"
] | null | null | null | class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
targetList = []
targetList.append(nums[0])
for i in range(1,len(nums)):
targetList.insert(index[i] , nums[i])
return targetList
| 31.333333 | 80 | 0.567376 | class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
targetList = []
targetList.append(nums[0])
for i in range(1,len(nums)):
targetList.insert(index[i] , nums[i])
return targetList
| true | true |
f729cddf796bde2b9780b2c4dc762d657897d4d6 | 7,157 | py | Python | tests/websockets/test_disk.py | tobiasbp/py-freenas | 09909b1e792f671c474587347ed659bde478d74a | [
"MIT"
] | null | null | null | tests/websockets/test_disk.py | tobiasbp/py-freenas | 09909b1e792f671c474587347ed659bde478d74a | [
"MIT"
] | null | null | null | tests/websockets/test_disk.py | tobiasbp/py-freenas | 09909b1e792f671c474587347ed659bde478d74a | [
"MIT"
] | null | null | null | import unittest
from unittest import IsolatedAsyncioTestCase
from unittest.mock import Mock
from pyfreenas.disk import DiskType
from pyfreenas.websockets.disk import CachingDisk
from pyfreenas.websockets.machine import CachingMachine
from tests.fakes.fakeserver import (
FreeNASServer,
TDiskQueryResult,
TDiskTemperaturesResult,
TVmQueryResult,
)
from typing import (
Any,
Dict,
List,
Union,
)
class TestDisk(IsolatedAsyncioTestCase):
_server: FreeNASServer
_machine: CachingMachine
def setUp(self):
self._server = FreeNASServer()
async def asyncSetUp(self):
self._machine = await CachingMachine.create(
self._server.host,
username=self._server.username,
password=self._server.password,
secure=False,
)
async def asyncTearDown(self):
await self._machine.close()
await self._server.stop()
async def test_ssd_data_interpretation(self) -> None:
DESCRIPTION = "Some Desc"
MODEL = "Samsung SSD 860 EVO 250GB"
NAME = "ada0"
SERIAL = "NOTREALSERIAL"
SIZE = 250059350016
TEMPERATURE = 22
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: TEMPERATURE},
)
await self._machine.get_disks()
self.assertEqual(len(self._machine.disks), 1)
disk = self._machine.disks[0]
self.assertEqual(
disk.description, DESCRIPTION,
)
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
self.assertEqual(disk.temperature, TEMPERATURE)
self.assertEqual(disk.type, DiskType.SSD)
async def test_hddd_data_interpretation(self) -> None:
DESCRIPTION = "Some Desc"
MODEL = "ATA WDC WD60EFAX-68S"
NAME = "da0"
SERIAL = "NOTREALSERIAL"
SIZE = 6001175126016
TEMPERATURE = 24
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "HDD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: TEMPERATURE},
)
await self._machine.get_disks()
self.assertEqual(len(self._machine.disks), 1)
disk = self._machine.disks[0]
self.assertEqual(
disk.description, DESCRIPTION,
)
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
self.assertEqual(disk.temperature, TEMPERATURE)
self.assertEqual(disk.type, DiskType.HDD)
async def test_availability(self) -> None:
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": "Some Desc",
"model": "Samsung SSD 860 EVO 250GB",
"name": "ada0",
"serial": "NOTREALSERIAL",
"size": 250059350016,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {"ada0": 42},
)
await self._machine.get_disks()
disk = self._machine.disks[0]
self.assertTrue(disk.available)
self._server.register_method_handler(
"disk.query", lambda *args: [], override=True,
)
await self._machine.get_disks()
self.assertFalse(disk.available)
self.assertEqual(len(self._machine._disk_fetcher._cached_disks), 0)
async def test_unavailable_caching(self) -> None:
"""Certain properites have caching even if no longer available"""
DESCRIPTION = "Some Desc"
MODEL = "ATA WDC WD60EFAX-68S"
NAME = "da0"
SERIAL = "NOTREALSERIAL"
SIZE = 6001175126016
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "HDD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: 42},
)
await self._machine.get_disks()
disk = self._machine.disks[0]
assert disk is not None
self._server.register_method_handler(
"disk.query", lambda *args: [], override=True,
)
await self._machine.get_disks()
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
with self.assertRaises(AssertionError):
disk.temperature
self.assertEqual(disk.type, DiskType.HDD)
async def test_same_instance_after_get_disks(self) -> None:
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": "Some Desc",
"model": "Samsung SSD 860 EVO 250GB",
"name": "ada0",
"serial": "NOTREALSERIAL",
"size": 250059350016,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {"ada0": 42},
)
await self._machine.get_disks()
original_disk = self._machine.disks[0]
await self._machine.get_disks()
new_disk = self._machine.disks[0]
self.assertIs(original_disk, new_disk)
def test_eq_impl(self) -> None:
self._machine._disk_fetcher._state = {
"ada0": {
"description": "",
"model": "",
"name": "ada0",
"serial": "someserial",
"size": 256,
"temperature": 42,
"type": "SSD",
}
}
a = CachingDisk(self._machine._disk_fetcher, "ada0")
b = CachingDisk(self._machine._disk_fetcher, "ada0")
self.assertEqual(a, b)
if __name__ == "__main__":
unittest.main()
| 31.390351 | 75 | 0.53556 | import unittest
from unittest import IsolatedAsyncioTestCase
from unittest.mock import Mock
from pyfreenas.disk import DiskType
from pyfreenas.websockets.disk import CachingDisk
from pyfreenas.websockets.machine import CachingMachine
from tests.fakes.fakeserver import (
FreeNASServer,
TDiskQueryResult,
TDiskTemperaturesResult,
TVmQueryResult,
)
from typing import (
Any,
Dict,
List,
Union,
)
class TestDisk(IsolatedAsyncioTestCase):
_server: FreeNASServer
_machine: CachingMachine
def setUp(self):
self._server = FreeNASServer()
async def asyncSetUp(self):
self._machine = await CachingMachine.create(
self._server.host,
username=self._server.username,
password=self._server.password,
secure=False,
)
async def asyncTearDown(self):
await self._machine.close()
await self._server.stop()
async def test_ssd_data_interpretation(self) -> None:
DESCRIPTION = "Some Desc"
MODEL = "Samsung SSD 860 EVO 250GB"
NAME = "ada0"
SERIAL = "NOTREALSERIAL"
SIZE = 250059350016
TEMPERATURE = 22
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: TEMPERATURE},
)
await self._machine.get_disks()
self.assertEqual(len(self._machine.disks), 1)
disk = self._machine.disks[0]
self.assertEqual(
disk.description, DESCRIPTION,
)
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
self.assertEqual(disk.temperature, TEMPERATURE)
self.assertEqual(disk.type, DiskType.SSD)
async def test_hddd_data_interpretation(self) -> None:
DESCRIPTION = "Some Desc"
MODEL = "ATA WDC WD60EFAX-68S"
NAME = "da0"
SERIAL = "NOTREALSERIAL"
SIZE = 6001175126016
TEMPERATURE = 24
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "HDD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: TEMPERATURE},
)
await self._machine.get_disks()
self.assertEqual(len(self._machine.disks), 1)
disk = self._machine.disks[0]
self.assertEqual(
disk.description, DESCRIPTION,
)
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
self.assertEqual(disk.temperature, TEMPERATURE)
self.assertEqual(disk.type, DiskType.HDD)
async def test_availability(self) -> None:
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": "Some Desc",
"model": "Samsung SSD 860 EVO 250GB",
"name": "ada0",
"serial": "NOTREALSERIAL",
"size": 250059350016,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {"ada0": 42},
)
await self._machine.get_disks()
disk = self._machine.disks[0]
self.assertTrue(disk.available)
self._server.register_method_handler(
"disk.query", lambda *args: [], override=True,
)
await self._machine.get_disks()
self.assertFalse(disk.available)
self.assertEqual(len(self._machine._disk_fetcher._cached_disks), 0)
async def test_unavailable_caching(self) -> None:
DESCRIPTION = "Some Desc"
MODEL = "ATA WDC WD60EFAX-68S"
NAME = "da0"
SERIAL = "NOTREALSERIAL"
SIZE = 6001175126016
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": DESCRIPTION,
"model": MODEL,
"name": NAME,
"serial": SERIAL,
"size": SIZE,
"type": "HDD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {NAME: 42},
)
await self._machine.get_disks()
disk = self._machine.disks[0]
assert disk is not None
self._server.register_method_handler(
"disk.query", lambda *args: [], override=True,
)
await self._machine.get_disks()
self.assertEqual(disk.model, MODEL)
self.assertEqual(disk.name, NAME)
self.assertEqual(disk.serial, SERIAL)
self.assertEqual(disk.size, SIZE)
with self.assertRaises(AssertionError):
disk.temperature
self.assertEqual(disk.type, DiskType.HDD)
async def test_same_instance_after_get_disks(self) -> None:
self._server.register_method_handler(
"disk.query",
lambda *args: [
{
"description": "Some Desc",
"model": "Samsung SSD 860 EVO 250GB",
"name": "ada0",
"serial": "NOTREALSERIAL",
"size": 250059350016,
"type": "SSD",
},
],
)
self._server.register_method_handler(
"disk.temperatures", lambda *args: {"ada0": 42},
)
await self._machine.get_disks()
original_disk = self._machine.disks[0]
await self._machine.get_disks()
new_disk = self._machine.disks[0]
self.assertIs(original_disk, new_disk)
def test_eq_impl(self) -> None:
self._machine._disk_fetcher._state = {
"ada0": {
"description": "",
"model": "",
"name": "ada0",
"serial": "someserial",
"size": 256,
"temperature": 42,
"type": "SSD",
}
}
a = CachingDisk(self._machine._disk_fetcher, "ada0")
b = CachingDisk(self._machine._disk_fetcher, "ada0")
self.assertEqual(a, b)
if __name__ == "__main__":
unittest.main()
| true | true |
f729d0a78065b4d1b211459c315a5f665132ceef | 790 | py | Python | tests/test_kernFeatureWriter.py | adobe-type-tools/python-modules | ce67101f5c3ab8476729dcc231dcc574b8a338df | [
"MIT"
] | 19 | 2015-03-24T10:48:04.000Z | 2021-05-30T10:11:39.000Z | tests/test_kernFeatureWriter.py | adobe-type-tools/python-modules | ce67101f5c3ab8476729dcc231dcc574b8a338df | [
"MIT"
] | 11 | 2015-03-24T22:31:35.000Z | 2020-08-26T12:46:21.000Z | tests/test_kernFeatureWriter.py | adobe-type-tools/python-modules | ce67101f5c3ab8476729dcc231dcc574b8a338df | [
"MIT"
] | 15 | 2015-03-23T20:03:23.000Z | 2019-12-06T16:22:54.000Z | import defcon
import sys
sys.path.append("..")
from kernFeatureWriter import *
def read_file(path):
'''
Read a file, split lines into a list, close the file.
'''
with open(path, 'r', encoding='utf-8') as f:
data = f.read().splitlines()
return data
def test_WhichApp():
assert WhichApp().appName == 'Defcon'
# import __mocks__ as flsys ???
# assert WhichApp().appName == 'FontLab'
def test_full_run():
args = Defaults()
test_dir = os.path.dirname(__file__)
ufo_path = os.path.join(test_dir, 'example.ufo')
example_feature = read_file(os.path.join(test_dir, 'example.fea'))
args.input_file = ufo_path
f = defcon.Font(ufo_path)
run(f, args)
assert read_file(os.path.join(test_dir, 'kern.fea')) == example_feature
| 23.939394 | 75 | 0.653165 | import defcon
import sys
sys.path.append("..")
from kernFeatureWriter import *
def read_file(path):
with open(path, 'r', encoding='utf-8') as f:
data = f.read().splitlines()
return data
def test_WhichApp():
assert WhichApp().appName == 'Defcon'
def test_full_run():
args = Defaults()
test_dir = os.path.dirname(__file__)
ufo_path = os.path.join(test_dir, 'example.ufo')
example_feature = read_file(os.path.join(test_dir, 'example.fea'))
args.input_file = ufo_path
f = defcon.Font(ufo_path)
run(f, args)
assert read_file(os.path.join(test_dir, 'kern.fea')) == example_feature
| true | true |
f729d0e86e178752226f22bdfde144a5fbfac047 | 1,019 | py | Python | main.py | cdlavila/Confidencial-Intervals-with-Python | 0b347fb577928c6cf74179e148be2de423d5e4f2 | [
"MIT"
] | 1 | 2021-10-09T15:16:43.000Z | 2021-10-09T15:16:43.000Z | main.py | cdlavila/Confidencial-Intervals-with-Python | 0b347fb577928c6cf74179e148be2de423d5e4f2 | [
"MIT"
] | null | null | null | main.py | cdlavila/Confidencial-Intervals-with-Python | 0b347fb577928c6cf74179e148be2de423d5e4f2 | [
"MIT"
] | null | null | null | from UI import interface
from Model import confidenceInterval as ci
interface.heading()
answer = interface.menu()
if answer == '1':
mean, deviation, confidence = interface.readDataNormalDistribution()
x1, x2, significancePoint = ci.confidenceIntervalForNormalDistribution(mean, deviation, confidence)
print("\033[;36m" + f'THE RANDOM VARIABLE IS IN THE INTERVAL ({x1}, {x2})'
f' WITH A CONFIDENCE OF {confidence}%')
ci.graphConfidenceInterval(mean, deviation, confidence, x1, x2, significancePoint * 100)
elif answer == '2':
deviation, sample, sampleMean, confidence = interface.readDataPopulationMean()
x1, x2, significancePoint = ci.confidenceIntervalForPopulationMean(deviation, sample, sampleMean, confidence)
print("\033[;36m" + f'THE POPULATION AVERAGE μ IS IN THE INTERVAL ({x1}, {x2}) '
f'WITH A CONFIDENCE OF {confidence}%')
ci.graphConfidenceInterval((x1+x2)/2, deviation, confidence, x1, x2, significancePoint * 100, False)
| 48.52381 | 113 | 0.707556 | from UI import interface
from Model import confidenceInterval as ci
interface.heading()
answer = interface.menu()
if answer == '1':
mean, deviation, confidence = interface.readDataNormalDistribution()
x1, x2, significancePoint = ci.confidenceIntervalForNormalDistribution(mean, deviation, confidence)
print("\033[;36m" + f'THE RANDOM VARIABLE IS IN THE INTERVAL ({x1}, {x2})'
f' WITH A CONFIDENCE OF {confidence}%')
ci.graphConfidenceInterval(mean, deviation, confidence, x1, x2, significancePoint * 100)
elif answer == '2':
deviation, sample, sampleMean, confidence = interface.readDataPopulationMean()
x1, x2, significancePoint = ci.confidenceIntervalForPopulationMean(deviation, sample, sampleMean, confidence)
print("\033[;36m" + f'THE POPULATION AVERAGE μ IS IN THE INTERVAL ({x1}, {x2}) '
f'WITH A CONFIDENCE OF {confidence}%')
ci.graphConfidenceInterval((x1+x2)/2, deviation, confidence, x1, x2, significancePoint * 100, False)
| true | true |
f729d170de44410c1c2eb53540fcb6e23b0e8756 | 6,960 | py | Python | automobile/register/register_model.py | manojmanivannan/MLOps | b082b628f0f85d3f36557ac9d90a091f612268b3 | [
"MIT"
] | null | null | null | automobile/register/register_model.py | manojmanivannan/MLOps | b082b628f0f85d3f36557ac9d90a091f612268b3 | [
"MIT"
] | null | null | null | automobile/register/register_model.py | manojmanivannan/MLOps | b082b628f0f85d3f36557ac9d90a091f612268b3 | [
"MIT"
] | null | null | null | """
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates and to vendors to perform work on your behalf)
through distribution, network access, service agreement, lease, rental, or
otherwise. This license does not purport to express any claim of ownership over
data you may have shared with Microsoft in the creation of the Software Code.
Unless applicable law gives you more rights, Microsoft reserves all other
rights not expressly granted herein, whether by implication, estoppel or
otherwise.
THE SOFTWARE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
MICROSOFT OR ITS LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE CODE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import json
import os
import sys
import argparse
import traceback
import joblib
from azureml.core import Run, Experiment, Workspace, Dataset
from azureml.core.model import Model as AMLModel
def main():
run = Run.get_context()
if (run.id.startswith('OfflineRun')):
from dotenv import load_dotenv
# For local development, set values in this section
load_dotenv()
workspace_name = os.environ.get("WORKSPACE_NAME")
experiment_name = os.environ.get("EXPERIMENT_NAME")
resource_group = os.environ.get("RESOURCE_GROUP")
subscription_id = os.environ.get("SUBSCRIPTION_ID")
# run_id useful to query previous runs
run_id = "bd184a18-2ac8-4951-8e78-e290bef3b012"
aml_workspace = Workspace.get(
name=workspace_name,
subscription_id=subscription_id,
resource_group=resource_group
)
ws = aml_workspace
exp = Experiment(ws, experiment_name)
else:
ws = run.experiment.workspace
exp = run.experiment
run_id = 'amlcompute'
parser = argparse.ArgumentParser("register")
parser.add_argument(
"--run_id",
type=str,
help="Training run ID",
)
parser.add_argument(
"--model_name",
type=str,
help="Name of the Model",
default="automobile_model.pkl",
)
parser.add_argument(
"--step_input",
type=str,
help=("input from previous steps")
)
args = parser.parse_args()
if (args.run_id is not None):
run_id = args.run_id
if (run_id == 'amlcompute'):
run_id = run.parent.id
model_name = args.model_name
model_path = args.step_input
print("Getting registration parameters")
# Load the registration parameters from the parameters file
with open("parameters.json") as f:
pars = json.load(f)
try:
register_args = pars["registration"]
except KeyError:
print("Could not load registration values from file")
register_args = {"tags": []}
model_tags = {}
for tag in register_args["tags"]:
try:
mtag = run.parent.get_metrics()[tag]
model_tags[tag] = mtag
except KeyError:
print(f"Could not find {tag} metric on parent run.")
# load the model
print("Loading model from " + model_path)
model_file = os.path.join(model_path, model_name)
model = joblib.load(model_file)
parent_tags = run.parent.get_tags()
try:
build_id = parent_tags["BuildId"]
except KeyError:
build_id = None
print("BuildId tag not found on parent run.")
print(f"Tags present: {parent_tags}")
try:
build_uri = parent_tags["BuildUri"]
except KeyError:
build_uri = None
print("BuildUri tag not found on parent run.")
print(f"Tags present: {parent_tags}")
if (model is not None):
dataset_id = parent_tags["dataset_id"]
if (build_id is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id)
elif (build_uri is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id)
else:
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id,
build_uri)
else:
print("Model not found. Skipping model registration.")
sys.exit(0)
def model_already_registered(model_name, exp, run_id):
model_list = AMLModel.list(exp.workspace, name=model_name, run_id=run_id)
if len(model_list) >= 1:
e = ("Model name:", model_name, "in workspace",
exp.workspace, "with run_id ", run_id, "is already registered.")
print(e)
raise Exception(e)
else:
print("Model is not registered for this run.")
def register_aml_model(
model_path,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id: str = 'none',
build_uri=None
):
try:
tagsValue = {"area": "automobile",
"run_id": run_id,
"experiment_name": exp.name}
tagsValue.update(model_tags)
if (build_id != 'none'):
model_already_registered(model_name, exp, run_id)
tagsValue["BuildId"] = build_id
if (build_uri is not None):
tagsValue["BuildUri"] = build_uri
model = AMLModel.register(
workspace=exp.workspace,
model_name=model_name,
model_path=model_path,
tags=tagsValue,
datasets=[('training data',
Dataset.get_by_id(exp.workspace, dataset_id))])
os.chdir("..")
print(
"Model registered: {} \nModel Description: {} "
"\nModel Version: {}".format(
model.name, model.description, model.version
)
)
except Exception:
traceback.print_exc(limit=None, file=None, chain=True)
print("Model registration failed")
raise
if __name__ == '__main__':
main()
| 32.372093 | 79 | 0.620259 | import json
import os
import sys
import argparse
import traceback
import joblib
from azureml.core import Run, Experiment, Workspace, Dataset
from azureml.core.model import Model as AMLModel
def main():
run = Run.get_context()
if (run.id.startswith('OfflineRun')):
from dotenv import load_dotenv
load_dotenv()
workspace_name = os.environ.get("WORKSPACE_NAME")
experiment_name = os.environ.get("EXPERIMENT_NAME")
resource_group = os.environ.get("RESOURCE_GROUP")
subscription_id = os.environ.get("SUBSCRIPTION_ID")
run_id = "bd184a18-2ac8-4951-8e78-e290bef3b012"
aml_workspace = Workspace.get(
name=workspace_name,
subscription_id=subscription_id,
resource_group=resource_group
)
ws = aml_workspace
exp = Experiment(ws, experiment_name)
else:
ws = run.experiment.workspace
exp = run.experiment
run_id = 'amlcompute'
parser = argparse.ArgumentParser("register")
parser.add_argument(
"--run_id",
type=str,
help="Training run ID",
)
parser.add_argument(
"--model_name",
type=str,
help="Name of the Model",
default="automobile_model.pkl",
)
parser.add_argument(
"--step_input",
type=str,
help=("input from previous steps")
)
args = parser.parse_args()
if (args.run_id is not None):
run_id = args.run_id
if (run_id == 'amlcompute'):
run_id = run.parent.id
model_name = args.model_name
model_path = args.step_input
print("Getting registration parameters")
with open("parameters.json") as f:
pars = json.load(f)
try:
register_args = pars["registration"]
except KeyError:
print("Could not load registration values from file")
register_args = {"tags": []}
model_tags = {}
for tag in register_args["tags"]:
try:
mtag = run.parent.get_metrics()[tag]
model_tags[tag] = mtag
except KeyError:
print(f"Could not find {tag} metric on parent run.")
print("Loading model from " + model_path)
model_file = os.path.join(model_path, model_name)
model = joblib.load(model_file)
parent_tags = run.parent.get_tags()
try:
build_id = parent_tags["BuildId"]
except KeyError:
build_id = None
print("BuildId tag not found on parent run.")
print(f"Tags present: {parent_tags}")
try:
build_uri = parent_tags["BuildUri"]
except KeyError:
build_uri = None
print("BuildUri tag not found on parent run.")
print(f"Tags present: {parent_tags}")
if (model is not None):
dataset_id = parent_tags["dataset_id"]
if (build_id is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id)
elif (build_uri is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id)
else:
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id,
build_uri)
else:
print("Model not found. Skipping model registration.")
sys.exit(0)
def model_already_registered(model_name, exp, run_id):
model_list = AMLModel.list(exp.workspace, name=model_name, run_id=run_id)
if len(model_list) >= 1:
e = ("Model name:", model_name, "in workspace",
exp.workspace, "with run_id ", run_id, "is already registered.")
print(e)
raise Exception(e)
else:
print("Model is not registered for this run.")
def register_aml_model(
model_path,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id: str = 'none',
build_uri=None
):
try:
tagsValue = {"area": "automobile",
"run_id": run_id,
"experiment_name": exp.name}
tagsValue.update(model_tags)
if (build_id != 'none'):
model_already_registered(model_name, exp, run_id)
tagsValue["BuildId"] = build_id
if (build_uri is not None):
tagsValue["BuildUri"] = build_uri
model = AMLModel.register(
workspace=exp.workspace,
model_name=model_name,
model_path=model_path,
tags=tagsValue,
datasets=[('training data',
Dataset.get_by_id(exp.workspace, dataset_id))])
os.chdir("..")
print(
"Model registered: {} \nModel Description: {} "
"\nModel Version: {}".format(
model.name, model.description, model.version
)
)
except Exception:
traceback.print_exc(limit=None, file=None, chain=True)
print("Model registration failed")
raise
if __name__ == '__main__':
main()
| true | true |
f729d2808f18b0becf83816b2015872b5ef39b72 | 7,865 | py | Python | qiskit/optimization/applications/ising/knapsack.py | stefan-woerner/aqua | 12e1b867e254977d9c5992612a7919d8fe016cb4 | [
"Apache-2.0"
] | 504 | 2018-12-15T16:34:03.000Z | 2022-03-26T11:24:53.000Z | qiskit/optimization/applications/ising/knapsack.py | stefan-woerner/aqua | 12e1b867e254977d9c5992612a7919d8fe016cb4 | [
"Apache-2.0"
] | 746 | 2018-12-16T16:44:42.000Z | 2021-07-10T16:59:43.000Z | qiskit/optimization/applications/ising/knapsack.py | stefan-woerner/aqua | 12e1b867e254977d9c5992612a7919d8fe016cb4 | [
"Apache-2.0"
] | 421 | 2018-12-22T14:49:00.000Z | 2022-03-04T09:47:07.000Z | # This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Convert knapsack parameters instances into Pauli list
The parameters are a list of values a list of weights and a maximum weight of the knapsack.
In the Knapsack Problem we are given a list of objects that each has a weight and a value.
We are also given a maximum weight we can carry. We need to pick a subset of the objects
so as to maximize the total value without going over the maximum weight.
If we have the weights w[i], the values v[i] and the maximum weight W_max.
We express the solution as a binary array x[i]
where we have a 1 for the items we take in the solution set.
We need to maximize sum(x[i]*v[i]) while respecting W_max >= sum(x[i]*w[i])
"""
import logging
import math
import numpy as np
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import WeightedPauliOperator
logger = logging.getLogger(__name__)
def get_operator(values, weights, max_weight):
"""
Generate Hamiltonian for the knapsack problem.
Notes:
To build the cost function for the Hamiltonian we add a term S
that will vary with our solution. In order to make it change wit the solution
we enhance X with a number of additional bits X' = [x_0,..x_{n-1},y_{n}..y_{n+m-1}].
The bytes y[i] will be the binary representation of S.
In this way the optimizer will be able to optimize S as well as X.
The cost function is
$$C(X') = M(W_{max} - \\sum_{i=0}^{n-1} x_{i}w_{i} - S)^2 - \\sum_{i}^{n-1} x_{i}v_{i}$$
where S = sum(2**j * y[j]), j goes from n to n+log(W_max).
M is a number large enough to dominate the sum of values.
Because S can only be positive, when W_max >= sum(x[i]*w[i])
the optimizer can find an S (or better the y[j] that compose S)
so that it will take the first term to 0.
This way the function is dominated by the sum of values.
If W_max < sum(x[i]*w[i]) then the first term can never be 0
and, multiplied by a large M, will always dominate the function.
The minimum value of the function will be that where the constraint is respected
and the sum of values is maximized.
Args:
values (list of non-negative integers) : a list of values
weights (list of non-negative integers) : a list of weights
max_weight (non negative integer) : the maximum weight the knapsack can carry
Returns:
WeightedPauliOperator: operator for the Hamiltonian
float: a constant shift for the obj function.
Raises:
ValueError: values and weights have different lengths
ValueError: A value or a weight is negative
ValueError: All values are zero
ValueError: max_weight is negative
"""
if len(values) != len(weights):
raise ValueError("The values and weights must have the same length")
if any(v < 0 for v in values) or any(w < 0 for w in weights):
raise ValueError("The values and weights cannot be negative")
if all(v == 0 for v in values):
raise ValueError("The values cannot all be 0")
if max_weight < 0:
raise ValueError("max_weight cannot be negative")
y_size = int(math.log(max_weight, 2)) + 1 if max_weight > 0 else 1
n = len(values)
num_values = n + y_size
pauli_list = []
shift = 0
# pylint: disable=invalid-name
M = 10 * np.sum(values)
# term for sum(x_i*w_i)**2
for i in range(n):
for j in range(n):
coefficient = -1 * 0.25 * weights[i] * weights[j] * M
pauli_op = _get_pauli_op(num_values, [j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [i, j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
# term for sum(2**j*y_j)**2
for i in range(y_size):
for j in range(y_size):
coefficient = -1 * 0.25 * (2 ** i) * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [n + i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [n + i, n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
# term for -2*W_max*sum(x_i*w_i)
for i in range(n):
coefficient = max_weight * weights[i] * M
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
# term for -2*W_max*sum(2**j*y_j)
for j in range(y_size):
coefficient = max_weight * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for i in range(n):
for j in range(y_size):
coefficient = -1 * 0.5 * weights[i] * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [i, n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
# term for sum(x_i*v_i)
for i in range(n):
coefficient = 0.5 * values[i]
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
return WeightedPauliOperator(paulis=pauli_list), shift
def get_solution(x, values):
"""
Get the solution to the knapsack problem
from the bitstring that represents
to the ground state of the Hamiltonian
Args:
x (numpy.ndarray): the ground state of the Hamiltonian.
values (numpy.ndarray): the list of values
Returns:
numpy.ndarray: a bit string that has a '1' at the indexes
corresponding to values that have been taken in the knapsack.
i.e. if the solution has a '1' at index i then
the value values[i] has been taken in the knapsack
"""
return x[:len(values)]
def knapsack_value_weight(solution, values, weights):
"""
Get the total wight and value of the items taken in the knapsack.
Args:
solution (numpy.ndarray) : binary string that represents the solution to the problem.
values (numpy.ndarray) : the list of values
weights (numpy.ndarray) : the list of weights
Returns:
tuple: the total value and weight of the items in the knapsack
"""
value = np.sum(solution * values)
weight = np.sum(solution * weights)
return value, weight
def _get_pauli_op(num_values, indexes):
pauli_x = np.zeros(num_values, dtype=bool)
pauli_z = np.zeros(num_values, dtype=bool)
for i in indexes:
pauli_z[i] = not pauli_z[i]
return Pauli((pauli_z, pauli_x))
| 35.111607 | 96 | 0.640432 |
import logging
import math
import numpy as np
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import WeightedPauliOperator
logger = logging.getLogger(__name__)
def get_operator(values, weights, max_weight):
if len(values) != len(weights):
raise ValueError("The values and weights must have the same length")
if any(v < 0 for v in values) or any(w < 0 for w in weights):
raise ValueError("The values and weights cannot be negative")
if all(v == 0 for v in values):
raise ValueError("The values cannot all be 0")
if max_weight < 0:
raise ValueError("max_weight cannot be negative")
y_size = int(math.log(max_weight, 2)) + 1 if max_weight > 0 else 1
n = len(values)
num_values = n + y_size
pauli_list = []
shift = 0
M = 10 * np.sum(values)
for i in range(n):
for j in range(n):
coefficient = -1 * 0.25 * weights[i] * weights[j] * M
pauli_op = _get_pauli_op(num_values, [j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [i, j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for i in range(y_size):
for j in range(y_size):
coefficient = -1 * 0.25 * (2 ** i) * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [n + i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [n + i, n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for i in range(n):
coefficient = max_weight * weights[i] * M
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for j in range(y_size):
coefficient = max_weight * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for i in range(n):
for j in range(y_size):
coefficient = -1 * 0.5 * weights[i] * (2 ** j) * M
pauli_op = _get_pauli_op(num_values, [n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
coefficient = -1 * coefficient
pauli_op = _get_pauli_op(num_values, [i, n + j])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
for i in range(n):
coefficient = 0.5 * values[i]
pauli_op = _get_pauli_op(num_values, [i])
pauli_list.append([coefficient, pauli_op])
shift -= coefficient
return WeightedPauliOperator(paulis=pauli_list), shift
def get_solution(x, values):
return x[:len(values)]
def knapsack_value_weight(solution, values, weights):
value = np.sum(solution * values)
weight = np.sum(solution * weights)
return value, weight
def _get_pauli_op(num_values, indexes):
pauli_x = np.zeros(num_values, dtype=bool)
pauli_z = np.zeros(num_values, dtype=bool)
for i in indexes:
pauli_z[i] = not pauli_z[i]
return Pauli((pauli_z, pauli_x))
| true | true |
f729d296f00b2dff7ad5da52ce4e82f23526c441 | 93 | py | Python | Hybrid/PlanB/2DFLIPFLUDS/flipsolver.py | clatterrr/NumericalComputationProjectsCollection | 95caf3121dc71a91b8e73c1ccc5909f4ab2551ea | [
"MIT"
] | 1 | 2022-01-19T08:55:55.000Z | 2022-01-19T08:55:55.000Z | Hybrid/PlanB/2DFLIPFLUDS/flipsolver.py | clatterrr/NumericalComputationProjectsCollection | 95caf3121dc71a91b8e73c1ccc5909f4ab2551ea | [
"MIT"
] | null | null | null | Hybrid/PlanB/2DFLIPFLUDS/flipsolver.py | clatterrr/NumericalComputationProjectsCollection | 95caf3121dc71a91b8e73c1ccc5909f4ab2551ea | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 4 10:20:35 2021
@author: Administrator
"""
| 11.625 | 35 | 0.591398 | true | true | |
f729d4c3e9afa190abe599e6bd025572088ac04b | 3,173 | py | Python | asab/api/log.py | TeskaLabs/asab | f28894b62bad192d8d30df01a8ad1b842ee2a2fb | [
"BSD-3-Clause"
] | 23 | 2018-03-07T18:58:13.000Z | 2022-03-29T17:11:47.000Z | asab/api/log.py | TeskaLabs/asab | f28894b62bad192d8d30df01a8ad1b842ee2a2fb | [
"BSD-3-Clause"
] | 87 | 2018-04-04T19:44:13.000Z | 2022-03-31T11:18:00.000Z | asab/api/log.py | TeskaLabs/asab | f28894b62bad192d8d30df01a8ad1b842ee2a2fb | [
"BSD-3-Clause"
] | 10 | 2018-04-30T16:40:25.000Z | 2022-03-09T10:55:24.000Z | import asyncio
import logging
import datetime
import aiohttp
from ..web.rest.json import json_response
from ..log import LOG_NOTICE
##
L = logging.getLogger(__name__)
##
class WebApiLoggingHandler(logging.Handler):
def __init__(self, app, level=logging.NOTSET, buffer_size: int = 10):
super().__init__(level=level)
self.Buffer = []
self._buffer_size = buffer_size
self.WebSockets = set()
app.PubSub.subscribe("Application.stop!", self._on_stop)
async def _on_stop(self, _on_stop, x):
for ws in list(self.WebSockets):
await ws.send_json({
"t": datetime.datetime.utcnow().isoformat() + 'Z',
"C": "asab.web",
"M": "Closed.",
"l": logging.INFO,
})
await ws.close()
def emit(self, record):
if logging.DEBUG < record.levelno <= logging.INFO:
severity = 6 # Informational
elif record.levelno <= LOG_NOTICE:
severity = 5 # Notice
elif record.levelno <= logging.WARNING:
severity = 4 # Warning
elif record.levelno <= logging.ERROR:
severity = 3 # Error
elif record.levelno <= logging.CRITICAL:
severity = 2 # Critical
else:
severity = 1 # Alert
log_entry = {
"t": datetime.datetime.utcfromtimestamp(record.created).isoformat() + 'Z',
"C": record.name,
"s": "{}:{}".format(record.funcName, record.lineno),
"p": record.process,
"Th": record.thread,
"l": severity,
}
message = record.getMessage()
if record.exc_text is not None:
message += '\n' + record.exc_text
if record.stack_info is not None:
message += '\n' + record.stack_info
if len(message) > 0:
log_entry['M'] = message
sd = record.__dict__.get("_struct_data")
if sd is not None:
log_entry['sd'] = sd
if len(self.Buffer) > self._buffer_size:
del self.Buffer[0]
self.Buffer.append(log_entry)
else:
self.Buffer.append(log_entry)
if len(self.WebSockets) > 0:
asyncio.ensure_future(self._send_ws(log_entry))
async def get_logs(self, request):
return json_response(request, self.Buffer)
async def ws(self, request):
'''
Websocket connection
Usable with e.g. with React Lazylog
https://github.com/mozilla-frontend-infra/react-lazylog#readme
<LazyLog
url={this.AsabLogWsURL}
follow
websocket
websocketOptions={{
formatMessage: e => log_message_format(e),
}}
/>
function log_message_format(e) {
e = JSON.parse(e)
var msg = e.t;
if (e.l != undefined) msg += " " + e.l;
if (e.sd != undefined) msg += ` ${JSON.stringify(e.sd)}`;
if (e.M != undefined) msg += " " + e.M;
if (e.C != undefined) msg += ` [${e.C}]`
return msg;
}
'''
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
await ws.send_json({
"t": datetime.datetime.utcnow().isoformat() + 'Z',
"C": "asab.web",
"M": "Connected.",
"l": logging.INFO,
})
# Send historical logs
for log_entry in self.Buffer:
await ws.send_json(log_entry)
self.WebSockets.add(ws)
try:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.ERROR:
break
finally:
self.WebSockets.remove(ws)
return ws
async def _send_ws(self, log_entry):
for ws in self.WebSockets:
await ws.send_json(log_entry)
| 21.153333 | 77 | 0.653955 | import asyncio
import logging
import datetime
import aiohttp
from ..web.rest.json import json_response
from ..log import LOG_NOTICE
L = logging.getLogger(__name__)
class WebApiLoggingHandler(logging.Handler):
def __init__(self, app, level=logging.NOTSET, buffer_size: int = 10):
super().__init__(level=level)
self.Buffer = []
self._buffer_size = buffer_size
self.WebSockets = set()
app.PubSub.subscribe("Application.stop!", self._on_stop)
async def _on_stop(self, _on_stop, x):
for ws in list(self.WebSockets):
await ws.send_json({
"t": datetime.datetime.utcnow().isoformat() + 'Z',
"C": "asab.web",
"M": "Closed.",
"l": logging.INFO,
})
await ws.close()
def emit(self, record):
if logging.DEBUG < record.levelno <= logging.INFO:
severity = 6
elif record.levelno <= LOG_NOTICE:
severity = 5
elif record.levelno <= logging.WARNING:
severity = 4
elif record.levelno <= logging.ERROR:
severity = 3
elif record.levelno <= logging.CRITICAL:
severity = 2
else:
severity = 1
log_entry = {
"t": datetime.datetime.utcfromtimestamp(record.created).isoformat() + 'Z',
"C": record.name,
"s": "{}:{}".format(record.funcName, record.lineno),
"p": record.process,
"Th": record.thread,
"l": severity,
}
message = record.getMessage()
if record.exc_text is not None:
message += '\n' + record.exc_text
if record.stack_info is not None:
message += '\n' + record.stack_info
if len(message) > 0:
log_entry['M'] = message
sd = record.__dict__.get("_struct_data")
if sd is not None:
log_entry['sd'] = sd
if len(self.Buffer) > self._buffer_size:
del self.Buffer[0]
self.Buffer.append(log_entry)
else:
self.Buffer.append(log_entry)
if len(self.WebSockets) > 0:
asyncio.ensure_future(self._send_ws(log_entry))
async def get_logs(self, request):
return json_response(request, self.Buffer)
async def ws(self, request):
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
await ws.send_json({
"t": datetime.datetime.utcnow().isoformat() + 'Z',
"C": "asab.web",
"M": "Connected.",
"l": logging.INFO,
})
for log_entry in self.Buffer:
await ws.send_json(log_entry)
self.WebSockets.add(ws)
try:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.ERROR:
break
finally:
self.WebSockets.remove(ws)
return ws
async def _send_ws(self, log_entry):
for ws in self.WebSockets:
await ws.send_json(log_entry)
| true | true |
f729d4d549ac895aa0f6359d18f77b199943c295 | 31 | py | Python | server/models/resnet/__init__.py | Mobile-and-Ubiquitous-Computing-2020-1/team1 | a3a5b4916a012ee0cd98cb186046a1957872b550 | [
"MIT"
] | 3 | 2020-03-23T10:32:43.000Z | 2020-06-25T03:36:06.000Z | server/models/resnet/__init__.py | Mobile-and-Ubiquitous-Computing-2020-1/team1 | a3a5b4916a012ee0cd98cb186046a1957872b550 | [
"MIT"
] | 4 | 2020-05-11T13:50:00.000Z | 2022-02-10T01:58:08.000Z | server/models/resnet/__init__.py | Mobile-and-Ubiquitous-Computing-2020-1/team1 | a3a5b4916a012ee0cd98cb186046a1957872b550 | [
"MIT"
] | 1 | 2020-08-13T00:01:01.000Z | 2020-08-13T00:01:01.000Z | from .resnet50 import resnet50
| 15.5 | 30 | 0.83871 | from .resnet50 import resnet50
| true | true |
f729d54c1d234bcf6e6e6ed381790c259c322a42 | 12,597 | py | Python | docs/make_docs.py | devshank3/Open3D | 91611eb562680a41be8a52497bb45d278f2c9377 | [
"MIT"
] | 15 | 2020-05-09T07:31:48.000Z | 2021-08-15T07:32:14.000Z | docs/make_docs.py | devshank3/Open3D | 91611eb562680a41be8a52497bb45d278f2c9377 | [
"MIT"
] | null | null | null | docs/make_docs.py | devshank3/Open3D | 91611eb562680a41be8a52497bb45d278f2c9377 | [
"MIT"
] | 5 | 2020-06-27T06:10:50.000Z | 2021-12-27T03:21:24.000Z | # ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018 www.open3d.org
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
# Sphinx makefile with api docs generation
# (1) The user call `make *` (e.g. `make html`) gets forwarded to make.py
# (2) make.py generate Python api docs, one ".rst" file per class / function
# (3) make.py calls the actual `sphinx-build`
from __future__ import print_function
import argparse
import subprocess
import sys
import multiprocessing
import importlib
import os
from inspect import getmembers, isbuiltin, isclass, ismodule
import shutil
import warnings
import weakref
from tempfile import mkdtemp
def _create_or_clear_dir(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
print("Removed directory %s" % dir_path)
os.makedirs(dir_path)
print("Created directory %s" % dir_path)
class PyAPIDocsBuilder:
"""
Generate Python API *.rst files, per (sub) module, per class, per function.
The file name is the full module name.
E.g. If output_dir == "python_api", the following files are generated:
python_api/open3d.camera.rst
python_api/open3d.camera.PinholeCameraIntrinsic.rst
...
"""
def __init__(self, output_dir, c_module, c_module_relative):
self.output_dir = output_dir
self.c_module = c_module
self.c_module_relative = c_module_relative
print("Generating *.rst Python API docs in directory: %s" %
self.output_dir)
def generate_rst(self):
_create_or_clear_dir(self.output_dir)
main_c_module = importlib.import_module(self.c_module)
sub_module_names = sorted(
[obj[0] for obj in getmembers(main_c_module) if ismodule(obj[1])])
for sub_module_name in sub_module_names:
PyAPIDocsBuilder._generate_sub_module_class_function_docs(
sub_module_name, self.output_dir)
@staticmethod
def _generate_function_doc(sub_module_full_name, function_name,
output_path):
# print("Generating docs: %s" % (output_path,))
out_string = ""
out_string += "%s.%s" % (sub_module_full_name, function_name)
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
out_string += "\n\n" + ".. autofunction:: %s" % function_name
out_string += "\n"
with open(output_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_class_doc(sub_module_full_name, class_name, output_path):
# print("Generating docs: %s" % (output_path,))
out_string = ""
out_string += "%s.%s" % (sub_module_full_name, class_name)
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
out_string += "\n\n" + ".. autoclass:: %s" % class_name
out_string += "\n :members:"
out_string += "\n :undoc-members:"
out_string += "\n :inherited-members:"
out_string += "\n"
with open(output_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_sub_module_doc(sub_module_name, class_names, function_names,
sub_module_doc_path):
# print("Generating docs: %s" % (sub_module_doc_path,))
class_names = sorted(class_names)
function_names = sorted(function_names)
sub_module_full_name = "open3d.%s" % (sub_module_name,)
out_string = ""
out_string += sub_module_full_name
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
if len(class_names) > 0:
out_string += "\n\n**Classes**"
out_string += "\n\n.. autosummary::"
out_string += "\n"
for class_name in class_names:
out_string += "\n " + "%s" % (class_name,)
out_string += "\n"
if len(function_names) > 0:
out_string += "\n\n**Functions**"
out_string += "\n\n.. autosummary::"
out_string += "\n"
for function_name in function_names:
out_string += "\n " + "%s" % (function_name,)
out_string += "\n"
obj_names = class_names + function_names
if len(obj_names) > 0:
out_string += "\n\n.. toctree::"
out_string += "\n :hidden:"
out_string += "\n"
for obj_name in obj_names:
out_string += "\n %s <%s.%s>" % (
obj_name,
sub_module_full_name,
obj_name,
)
out_string += "\n"
with open(sub_module_doc_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_sub_module_class_function_docs(sub_module_name, output_dir):
sub_module = importlib.import_module("open3d.open3d.%s" %
(sub_module_name,))
sub_module_full_name = "open3d.%s" % (sub_module_name,)
print("Generating docs for submodule: %s" % sub_module_full_name)
# Class docs
class_names = [
obj[0] for obj in getmembers(sub_module) if isclass(obj[1])
]
for class_name in class_names:
file_name = "%s.%s.rst" % (sub_module_full_name, class_name)
output_path = os.path.join(output_dir, file_name)
PyAPIDocsBuilder._generate_class_doc(sub_module_full_name,
class_name, output_path)
# Function docs
function_names = [
obj[0] for obj in getmembers(sub_module) if isbuiltin(obj[1])
]
for function_name in function_names:
file_name = "%s.%s.rst" % (sub_module_full_name, function_name)
output_path = os.path.join(output_dir, file_name)
PyAPIDocsBuilder._generate_function_doc(sub_module_full_name,
function_name, output_path)
# Submodule docs
sub_module_doc_path = os.path.join(output_dir,
sub_module_full_name + ".rst")
PyAPIDocsBuilder._generate_sub_module_doc(sub_module_name, class_names,
function_names,
sub_module_doc_path)
class SphinxDocsBuilder:
"""
SphinxDocsBuilder calls Python api docs generation and then calls
sphinx-build:
(1) The user call `make *` (e.g. `make html`) gets forwarded to make.py
(2) Calls PyAPIDocsBuilder to generate Python api docs rst files
(3) Calls `sphinx-build` with the user argument
"""
def __init__(self, html_output_dir, is_release):
# Directory structure for the Open3D Python package:
# open3d
# - __init__.py
# - open3d.so # Actual name depends on OS and Python version
self.c_module = "open3d.open3d" # Points to the open3d.so
self.c_module_relative = "open3d" # The relative module reference to open3d.so
self.python_api_output_dir = "python_api"
self.html_output_dir = html_output_dir
self.is_release = is_release
def run(self):
self._gen_python_api_docs()
self._run_sphinx()
def _gen_python_api_docs(self):
"""
Generate Python docs.
Each module, class and function gets one .rst file.
"""
# self.python_api_output_dir cannot be a temp dir, since other
# "*.rst" files reference it
pd = PyAPIDocsBuilder(self.python_api_output_dir, self.c_module,
self.c_module_relative)
pd.generate_rst()
def _run_sphinx(self):
"""
Call Sphinx command with hard-coded "html" target
"""
build_dir = os.path.join(self.html_output_dir, "html")
if self.is_release:
version_list = [
line.rstrip('\n').split(' ')[1]
for line in open('../src/Open3D/version.txt')
]
release_version = '.'.join(version_list[:3])
print("Building docs for release:", release_version)
cmd = [
"sphinx-build",
"-b",
"html",
"-D",
"version=" + release_version,
"-D",
"release=" + release_version,
"-j",
str(multiprocessing.cpu_count()),
".",
build_dir,
]
else:
cmd = [
"sphinx-build",
"-b",
"html",
"-j",
str(multiprocessing.cpu_count()),
".",
build_dir,
]
print('Calling: "%s"' % " ".join(cmd))
subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
class DoxygenDocsBuilder:
def __init__(self, html_output_dir):
self.html_output_dir = html_output_dir
def run(self):
doxygen_temp_dir = "doxygen"
_create_or_clear_dir(doxygen_temp_dir)
cmd = ["doxygen", "Doxyfile"]
print('Calling: "%s"' % " ".join(cmd))
subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
shutil.copytree(os.path.join("doxygen", "html"),
os.path.join(self.html_output_dir, "html", "cpp_api"))
if os.path.exists(doxygen_temp_dir):
shutil.rmtree(doxygen_temp_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--sphinx",
dest="build_sphinx",
action="store_true",
default=False,
help="Build Sphinx for main docs and Python API docs.")
parser.add_argument("--doxygen",
dest="build_doxygen",
action="store_true",
default=False,
help="Build Doxygen for C++ API docs.")
parser.add_argument("--is_release",
dest="is_release",
action="store_true",
default=False,
help="Show Open3D version number rather than git hash.")
args = parser.parse_args()
# Clear output dir if new docs are to be built
html_output_dir = "_out"
_create_or_clear_dir(html_output_dir)
# Sphinx is hard-coded to build with the "html" option
# To customize build, run sphinx-build manually
if args.build_sphinx:
print("Sphinx build enabled")
sdb = SphinxDocsBuilder(html_output_dir, args.is_release)
sdb.run()
else:
print("Sphinx build disabled, use --sphinx to enable")
# Doxygen is hard-coded to build with default option
# To customize build, customize Doxyfile or run doxygen manually
if args.build_doxygen:
print("Doxygen build enabled")
ddb = DoxygenDocsBuilder(html_output_dir)
ddb.run()
else:
print("Doxygen build disabled, use --doxygen to enable")
| 38.522936 | 87 | 0.578471 |
from __future__ import print_function
import argparse
import subprocess
import sys
import multiprocessing
import importlib
import os
from inspect import getmembers, isbuiltin, isclass, ismodule
import shutil
import warnings
import weakref
from tempfile import mkdtemp
def _create_or_clear_dir(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
print("Removed directory %s" % dir_path)
os.makedirs(dir_path)
print("Created directory %s" % dir_path)
class PyAPIDocsBuilder:
def __init__(self, output_dir, c_module, c_module_relative):
self.output_dir = output_dir
self.c_module = c_module
self.c_module_relative = c_module_relative
print("Generating *.rst Python API docs in directory: %s" %
self.output_dir)
def generate_rst(self):
_create_or_clear_dir(self.output_dir)
main_c_module = importlib.import_module(self.c_module)
sub_module_names = sorted(
[obj[0] for obj in getmembers(main_c_module) if ismodule(obj[1])])
for sub_module_name in sub_module_names:
PyAPIDocsBuilder._generate_sub_module_class_function_docs(
sub_module_name, self.output_dir)
@staticmethod
def _generate_function_doc(sub_module_full_name, function_name,
output_path):
out_string = ""
out_string += "%s.%s" % (sub_module_full_name, function_name)
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
out_string += "\n\n" + ".. autofunction:: %s" % function_name
out_string += "\n"
with open(output_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_class_doc(sub_module_full_name, class_name, output_path):
out_string = ""
out_string += "%s.%s" % (sub_module_full_name, class_name)
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
out_string += "\n\n" + ".. autoclass:: %s" % class_name
out_string += "\n :members:"
out_string += "\n :undoc-members:"
out_string += "\n :inherited-members:"
out_string += "\n"
with open(output_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_sub_module_doc(sub_module_name, class_names, function_names,
sub_module_doc_path):
class_names = sorted(class_names)
function_names = sorted(function_names)
sub_module_full_name = "open3d.%s" % (sub_module_name,)
out_string = ""
out_string += sub_module_full_name
out_string += "\n" + "-" * len(out_string)
out_string += "\n\n" + ".. currentmodule:: %s" % sub_module_full_name
if len(class_names) > 0:
out_string += "\n\n**Classes**"
out_string += "\n\n.. autosummary::"
out_string += "\n"
for class_name in class_names:
out_string += "\n " + "%s" % (class_name,)
out_string += "\n"
if len(function_names) > 0:
out_string += "\n\n**Functions**"
out_string += "\n\n.. autosummary::"
out_string += "\n"
for function_name in function_names:
out_string += "\n " + "%s" % (function_name,)
out_string += "\n"
obj_names = class_names + function_names
if len(obj_names) > 0:
out_string += "\n\n.. toctree::"
out_string += "\n :hidden:"
out_string += "\n"
for obj_name in obj_names:
out_string += "\n %s <%s.%s>" % (
obj_name,
sub_module_full_name,
obj_name,
)
out_string += "\n"
with open(sub_module_doc_path, "w") as f:
f.write(out_string)
@staticmethod
def _generate_sub_module_class_function_docs(sub_module_name, output_dir):
sub_module = importlib.import_module("open3d.open3d.%s" %
(sub_module_name,))
sub_module_full_name = "open3d.%s" % (sub_module_name,)
print("Generating docs for submodule: %s" % sub_module_full_name)
class_names = [
obj[0] for obj in getmembers(sub_module) if isclass(obj[1])
]
for class_name in class_names:
file_name = "%s.%s.rst" % (sub_module_full_name, class_name)
output_path = os.path.join(output_dir, file_name)
PyAPIDocsBuilder._generate_class_doc(sub_module_full_name,
class_name, output_path)
function_names = [
obj[0] for obj in getmembers(sub_module) if isbuiltin(obj[1])
]
for function_name in function_names:
file_name = "%s.%s.rst" % (sub_module_full_name, function_name)
output_path = os.path.join(output_dir, file_name)
PyAPIDocsBuilder._generate_function_doc(sub_module_full_name,
function_name, output_path)
sub_module_doc_path = os.path.join(output_dir,
sub_module_full_name + ".rst")
PyAPIDocsBuilder._generate_sub_module_doc(sub_module_name, class_names,
function_names,
sub_module_doc_path)
class SphinxDocsBuilder:
def __init__(self, html_output_dir, is_release):
self.c_module_relative = "open3d"
self.python_api_output_dir = "python_api"
self.html_output_dir = html_output_dir
self.is_release = is_release
def run(self):
self._gen_python_api_docs()
self._run_sphinx()
def _gen_python_api_docs(self):
pd = PyAPIDocsBuilder(self.python_api_output_dir, self.c_module,
self.c_module_relative)
pd.generate_rst()
def _run_sphinx(self):
build_dir = os.path.join(self.html_output_dir, "html")
if self.is_release:
version_list = [
line.rstrip('\n').split(' ')[1]
for line in open('../src/Open3D/version.txt')
]
release_version = '.'.join(version_list[:3])
print("Building docs for release:", release_version)
cmd = [
"sphinx-build",
"-b",
"html",
"-D",
"version=" + release_version,
"-D",
"release=" + release_version,
"-j",
str(multiprocessing.cpu_count()),
".",
build_dir,
]
else:
cmd = [
"sphinx-build",
"-b",
"html",
"-j",
str(multiprocessing.cpu_count()),
".",
build_dir,
]
print('Calling: "%s"' % " ".join(cmd))
subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
class DoxygenDocsBuilder:
def __init__(self, html_output_dir):
self.html_output_dir = html_output_dir
def run(self):
doxygen_temp_dir = "doxygen"
_create_or_clear_dir(doxygen_temp_dir)
cmd = ["doxygen", "Doxyfile"]
print('Calling: "%s"' % " ".join(cmd))
subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr)
shutil.copytree(os.path.join("doxygen", "html"),
os.path.join(self.html_output_dir, "html", "cpp_api"))
if os.path.exists(doxygen_temp_dir):
shutil.rmtree(doxygen_temp_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--sphinx",
dest="build_sphinx",
action="store_true",
default=False,
help="Build Sphinx for main docs and Python API docs.")
parser.add_argument("--doxygen",
dest="build_doxygen",
action="store_true",
default=False,
help="Build Doxygen for C++ API docs.")
parser.add_argument("--is_release",
dest="is_release",
action="store_true",
default=False,
help="Show Open3D version number rather than git hash.")
args = parser.parse_args()
html_output_dir = "_out"
_create_or_clear_dir(html_output_dir)
if args.build_sphinx:
print("Sphinx build enabled")
sdb = SphinxDocsBuilder(html_output_dir, args.is_release)
sdb.run()
else:
print("Sphinx build disabled, use --sphinx to enable")
if args.build_doxygen:
print("Doxygen build enabled")
ddb = DoxygenDocsBuilder(html_output_dir)
ddb.run()
else:
print("Doxygen build disabled, use --doxygen to enable")
| true | true |
f729d64044238fb6790234583b78269b0caced37 | 1,169 | py | Python | cuda_operator.py | theHamsta/PYRO-NN-Layers | c776c3d7315f483937a7cebf667c6d491ecd57e6 | [
"Apache-2.0"
] | 1 | 2021-05-25T07:19:54.000Z | 2021-05-25T07:19:54.000Z | cuda_operator.py | theHamsta/PYRO-NN-Layers | c776c3d7315f483937a7cebf667c6d491ecd57e6 | [
"Apache-2.0"
] | null | null | null | cuda_operator.py | theHamsta/PYRO-NN-Layers | c776c3d7315f483937a7cebf667c6d491ecd57e6 | [
"Apache-2.0"
] | null | null | null | # Copyright [2019] [Christopher Syben]
#
# 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.
#
# Makes every implemented operator in python available under the namespace pyronn_layers
# PYRO-NN is developed as an Open Source project under the Apache License, Version 2.0.
#
import os.path
import tensorflow as tf
import pyronn_layers
if tf.test.is_built_with_cuda():
_pyronn_layers_module = tf.load_op_library(os.path.dirname(__file__)+'/pyronn_layers.so')
''' TODO: Improve the getattr method to add only real kernel methods and not everything '''
for obj in dir(_pyronn_layers_module):
setattr(pyronn_layers, obj, getattr(_pyronn_layers_module, obj))
| 38.966667 | 95 | 0.765612 |
import os.path
import tensorflow as tf
import pyronn_layers
if tf.test.is_built_with_cuda():
_pyronn_layers_module = tf.load_op_library(os.path.dirname(__file__)+'/pyronn_layers.so')
for obj in dir(_pyronn_layers_module):
setattr(pyronn_layers, obj, getattr(_pyronn_layers_module, obj))
| true | true |
f729d7b5ba2bd12ce28285702d61c739f04b20d5 | 3,714 | py | Python | torch/utils/model_zoo.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 5668b5785296b314ea1321057420bcd077dba9ea | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | torch/utils/model_zoo.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 5668b5785296b314ea1321057420bcd077dba9ea | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | torch/utils/model_zoo.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 5668b5785296b314ea1321057420bcd077dba9ea | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
if sys.version_info[0] == 2:
from urlparse import urlparse
from urllib2 import urlopen
else:
from urllib.request import urlopen
from urllib.parse import urlparse
try:
from tqdm import tqdm
except ImportError:
tqdm = None # defined below
# matches bfd8deac from resnet18-bfd8deac.pth
HASH_REGEX = re.compile(r'-([a-f0-9]*)\.')
def load_url(url, model_dir=None, map_location=None):
r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
digits of the SHA256 hash of the contents of the file. The hash is used to
ensure unique names and to verify the contents of the file.
The default value of `model_dir` is ``$TORCH_HOME/models`` where
``$TORCH_HOME`` defaults to ``~/.torch``. The default directory can be
overriden with the ``$TORCH_MODEL_ZOO`` environment variable.
Args:
url (string): URL of the object to download
model_dir (string, optional): directory in which to save the object
map_location (optional): a function or a dict specifying how to remap storage locations (see torch.load)
Example:
>>> state_dict = torch.utils.model_zoo.load_url('https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth')
"""
if model_dir is None:
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
if not os.path.exists(model_dir):
os.makedirs(model_dir)
parts = urlparse(url)
filename = os.path.basename(parts.path)
cached_file = os.path.join(model_dir, filename)
if not os.path.exists(cached_file):
sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
hash_prefix = HASH_REGEX.search(filename).group(1)
_download_url_to_file(url, cached_file, hash_prefix)
return torch.load(cached_file, map_location=map_location)
def _download_url_to_file(url, dst, hash_prefix):
u = urlopen(url)
meta = u.info()
if hasattr(meta, 'getheaders'):
file_size = int(meta.getheaders("Content-Length")[0])
else:
file_size = int(meta.get_all("Content-Length")[0])
f = tempfile.NamedTemporaryFile(delete=False)
try:
sha256 = hashlib.sha256()
with tqdm(total=file_size) as pbar:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
sha256.update(buffer)
pbar.update(len(buffer))
f.close()
digest = sha256.hexdigest()
if digest[:len(hash_prefix)] != hash_prefix:
raise RuntimeError('invalid hash value (expected "{}", got "{}")'
.format(hash_prefix, digest))
shutil.move(f.name, dst)
finally:
f.close()
if os.path.exists(f.name):
os.remove(f.name)
if tqdm is None:
# fake tqdm if it's not installed
class tqdm(object):
def __init__(self, total):
self.total = total
self.n = 0
def update(self, n):
self.n += n
sys.stderr.write("\r{0:.1f}%".format(100 * self.n / float(self.total)))
sys.stderr.flush()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stderr.write('\n')
| 33.459459 | 120 | 0.633549 | import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
if sys.version_info[0] == 2:
from urlparse import urlparse
from urllib2 import urlopen
else:
from urllib.request import urlopen
from urllib.parse import urlparse
try:
from tqdm import tqdm
except ImportError:
tqdm = None
HASH_REGEX = re.compile(r'-([a-f0-9]*)\.')
def load_url(url, model_dir=None, map_location=None):
if model_dir is None:
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
if not os.path.exists(model_dir):
os.makedirs(model_dir)
parts = urlparse(url)
filename = os.path.basename(parts.path)
cached_file = os.path.join(model_dir, filename)
if not os.path.exists(cached_file):
sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
hash_prefix = HASH_REGEX.search(filename).group(1)
_download_url_to_file(url, cached_file, hash_prefix)
return torch.load(cached_file, map_location=map_location)
def _download_url_to_file(url, dst, hash_prefix):
u = urlopen(url)
meta = u.info()
if hasattr(meta, 'getheaders'):
file_size = int(meta.getheaders("Content-Length")[0])
else:
file_size = int(meta.get_all("Content-Length")[0])
f = tempfile.NamedTemporaryFile(delete=False)
try:
sha256 = hashlib.sha256()
with tqdm(total=file_size) as pbar:
while True:
buffer = u.read(8192)
if len(buffer) == 0:
break
f.write(buffer)
sha256.update(buffer)
pbar.update(len(buffer))
f.close()
digest = sha256.hexdigest()
if digest[:len(hash_prefix)] != hash_prefix:
raise RuntimeError('invalid hash value (expected "{}", got "{}")'
.format(hash_prefix, digest))
shutil.move(f.name, dst)
finally:
f.close()
if os.path.exists(f.name):
os.remove(f.name)
if tqdm is None:
class tqdm(object):
def __init__(self, total):
self.total = total
self.n = 0
def update(self, n):
self.n += n
sys.stderr.write("\r{0:.1f}%".format(100 * self.n / float(self.total)))
sys.stderr.flush()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stderr.write('\n')
| true | true |
f729d8de4b4616f12bb0b43879ea1877d4df9d37 | 3,934 | py | Python | m2data/reader.py | Mindful/m2data | c1f6f978ed44d622bdcce30d6098131919d60a99 | [
"MIT"
] | null | null | null | m2data/reader.py | Mindful/m2data | c1f6f978ed44d622bdcce30d6098131919d60a99 | [
"MIT"
] | null | null | null | m2data/reader.py | Mindful/m2data | c1f6f978ed44d622bdcce30d6098131919d60a99 | [
"MIT"
] | null | null | null | from itertools import takewhile, repeat
from typing import Iterable, Union
from collections.abc import Sized
from m2data.example import Example
# this is sometimes off by an example or two for very large files, but that probably doesn't matter much
def fast_example_count(filename) -> int:
f = open(filename, 'rb')
bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
return sum(buf.count(b'\nS ') for buf in bufgen) + 1 # no linebreak for first example
class M2ReaderException(Exception):
def __init__(self, text: str):
super().__init__(text)
class Reader:
"""Returns an Example object for each sentence with corrections in an .m2 file. """
def __init__(self, input_data: Union[Iterable[str], str], progress_bar: bool = False):
"""
:param input_data: the filename of an .m2 file to read in, or an iterable of lines as read from an .m2 file
:param progress_bar: whether or not to display a progress bar for reading the file. Requires tqdm if True
"""
self.progress_bar = progress_bar
if self.progress_bar:
try:
from tqdm import tqdm
self.tqdm = tqdm
except ModuleNotFoundError:
print("Warning: progress bar requires tqdm, which was not found. Proceeding without progress bar")
self.progress_bar = False
if isinstance(input_data, str):
self.input_file = open(input_data, 'r')
if self.progress_bar:
self.total_examples = fast_example_count(input_data)
self.desc = 'reading examples from {}'.format(input_data)
self.input_gen = (line for line in (line.strip() for line in self.input_file) if line)
elif isinstance(input_data, Iterable):
if self.progress_bar:
if isinstance(input_data, Sized):
self.total_examples = len(input_data)
self.desc = 'reading examples from input'
else:
self.progress_bar = False
print('Warning: Progress bar requires that input is a filename or iterable with length. Proceeding'
'without progress bar.')
self.input_gen = (line for line in (line.strip() for line in input_data) if line)
else:
raise TypeError('Input to reader must be either a string filename or an iterable of lines as strings')
def __iter__(self) -> Iterable[Example]:
if self.progress_bar:
progress_bar = self.tqdm(total=self.total_examples, desc=self.desc)
original_content_line = None
correction_lines = None
for line in self.input_gen:
if line[0] == 'S':
if original_content_line: # we've hit the start of a new example, yield the last one
progress_bar.update(1) if self.progress_bar else None
yield Example(original_content_line, correction_lines)
original_content_line = line
correction_lines = []
else:
if line[0] != 'A':
raise M2ReaderException('Nonempty lines in .m2 files must start with "A" or "S".'
'Found violating line: "{}"'.format(line))
if correction_lines is None:
raise M2ReaderException('Encountered an edit line ("A") before an original sentence line ("S")')
correction_lines.append(line)
yield Example(original_content_line, correction_lines)
progress_bar.update(1) if self.progress_bar else None
if self.progress_bar:
progress_bar.close()
if hasattr(self, 'input_file'):
self.input_file.close()
def __del__(self):
if hasattr(self, 'input_file'):
self.input_file.close() | 43.230769 | 119 | 0.612608 | from itertools import takewhile, repeat
from typing import Iterable, Union
from collections.abc import Sized
from m2data.example import Example
def fast_example_count(filename) -> int:
f = open(filename, 'rb')
bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
return sum(buf.count(b'\nS ') for buf in bufgen) + 1 # no linebreak for first example
class M2ReaderException(Exception):
def __init__(self, text: str):
super().__init__(text)
class Reader:
def __init__(self, input_data: Union[Iterable[str], str], progress_bar: bool = False):
self.progress_bar = progress_bar
if self.progress_bar:
try:
from tqdm import tqdm
self.tqdm = tqdm
except ModuleNotFoundError:
print("Warning: progress bar requires tqdm, which was not found. Proceeding without progress bar")
self.progress_bar = False
if isinstance(input_data, str):
self.input_file = open(input_data, 'r')
if self.progress_bar:
self.total_examples = fast_example_count(input_data)
self.desc = 'reading examples from {}'.format(input_data)
self.input_gen = (line for line in (line.strip() for line in self.input_file) if line)
elif isinstance(input_data, Iterable):
if self.progress_bar:
if isinstance(input_data, Sized):
self.total_examples = len(input_data)
self.desc = 'reading examples from input'
else:
self.progress_bar = False
print('Warning: Progress bar requires that input is a filename or iterable with length. Proceeding'
'without progress bar.')
self.input_gen = (line for line in (line.strip() for line in input_data) if line)
else:
raise TypeError('Input to reader must be either a string filename or an iterable of lines as strings')
def __iter__(self) -> Iterable[Example]:
if self.progress_bar:
progress_bar = self.tqdm(total=self.total_examples, desc=self.desc)
original_content_line = None
correction_lines = None
for line in self.input_gen:
if line[0] == 'S':
if original_content_line: # we've hit the start of a new example, yield the last one
progress_bar.update(1) if self.progress_bar else None
yield Example(original_content_line, correction_lines)
original_content_line = line
correction_lines = []
else:
if line[0] != 'A':
raise M2ReaderException('Nonempty lines in .m2 files must start with "A" or "S".'
'Found violating line: "{}"'.format(line))
if correction_lines is None:
raise M2ReaderException('Encountered an edit line ("A") before an original sentence line ("S")')
correction_lines.append(line)
yield Example(original_content_line, correction_lines)
progress_bar.update(1) if self.progress_bar else None
if self.progress_bar:
progress_bar.close()
if hasattr(self, 'input_file'):
self.input_file.close()
def __del__(self):
if hasattr(self, 'input_file'):
self.input_file.close() | true | true |
f729d97500dfd4fb73eeb1671698feb9746b119b | 1,255 | py | Python | xclib/classifier/_svm.py | iksteen/pyxclib | 2948162dd780f8230a785abfd2ee57e8ab5cc156 | [
"MIT"
] | 1 | 2021-04-20T13:52:55.000Z | 2021-04-20T13:52:55.000Z | xclib/classifier/_svm.py | iksteen/pyxclib | 2948162dd780f8230a785abfd2ee57e8ab5cc156 | [
"MIT"
] | null | null | null | xclib/classifier/_svm.py | iksteen/pyxclib | 2948162dd780f8230a785abfd2ee57e8ab5cc156 | [
"MIT"
] | null | null | null | from sklearn.svm import LinearSVC
import numpy as np
def apply_threshold(data, threshold):
data[np.where(np.abs(data) < threshold)] = 0
def train_one(data, loss, C, verbose, max_iter, threshold, dual, tol):
def _get_features(obj):
# Index samples iff they are required
# Helful in reducing memory footprint
if obj['ind'] is None:
return obj['data']
else:
return obj['data'].take(obj['ind'], axis=0)
X, y = _get_features(data), data['Y']
clf = LinearSVC(tol=tol,
loss=loss,
dual=dual,
C=C,
multi_class='ovr',
fit_intercept=True,
intercept_scaling=1,
class_weight=None,
verbose=verbose,
random_state=0,
max_iter=max_iter)
try:
clf.fit(X, y)
weight, bias = clf.coef_, clf.intercept_
except ValueError:
# TODO Find a solution for this; choose randomly may be?
weight, bias = np.zeros((1, X.shape[1]), dtype=np.float32), np.zeros(
(1), dtype=np.float32)
del clf
apply_threshold(weight, threshold)
return weight, bias
| 33.026316 | 77 | 0.540239 | from sklearn.svm import LinearSVC
import numpy as np
def apply_threshold(data, threshold):
data[np.where(np.abs(data) < threshold)] = 0
def train_one(data, loss, C, verbose, max_iter, threshold, dual, tol):
def _get_features(obj):
if obj['ind'] is None:
return obj['data']
else:
return obj['data'].take(obj['ind'], axis=0)
X, y = _get_features(data), data['Y']
clf = LinearSVC(tol=tol,
loss=loss,
dual=dual,
C=C,
multi_class='ovr',
fit_intercept=True,
intercept_scaling=1,
class_weight=None,
verbose=verbose,
random_state=0,
max_iter=max_iter)
try:
clf.fit(X, y)
weight, bias = clf.coef_, clf.intercept_
except ValueError:
weight, bias = np.zeros((1, X.shape[1]), dtype=np.float32), np.zeros(
(1), dtype=np.float32)
del clf
apply_threshold(weight, threshold)
return weight, bias
| true | true |
f729d9783b20ae9d667475c45fc4085bc6c626f7 | 3,846 | py | Python | adam/learner/semantics_utils.py | isi-vista/adam | 43542c4486af7533938e77e7191eae630541a891 | [
"MIT"
] | 8 | 2019-07-02T20:29:31.000Z | 2022-01-03T18:20:41.000Z | adam/learner/semantics_utils.py | Tubbz-alt/adam | 91f392f2529a98cd50c095a18769ae4b55ce4292 | [
"MIT"
] | 1,011 | 2019-07-02T18:00:48.000Z | 2022-03-25T14:56:32.000Z | adam/learner/semantics_utils.py | Tubbz-alt/adam | 91f392f2529a98cd50c095a18769ae4b55ce4292 | [
"MIT"
] | 4 | 2020-08-05T15:36:55.000Z | 2022-01-12T17:16:28.000Z | from typing import Optional, Any, Dict
import numpy as np
import pandas as pd
from more_itertools import first
from networkx import Graph, to_numpy_matrix
import matplotlib.pyplot as plt
import seaborn as sb
from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept
class SemanticsManager:
def __init__(self, semantics_graph: Graph) -> None:
self.semantics_graph: Graph = Graph()
# Create a new type of edge for each edge in the original semantics graph
# If any of the nodes is an action concept, we want to make a distinct new node to track syntax
for u, v, data in semantics_graph.edges(data=True):
syntactic_position = data["slot"]
new_u = (
self.concept_as_str_node(u, syntactic_position)
if isinstance(u, ActionConcept)
else self.concept_as_str_node(u)
)
new_v = (
self.concept_as_str_node(v, syntactic_position)
if isinstance(v, ActionConcept)
else self.concept_as_str_node(v)
)
self.semantics_graph.add_edge(new_u, new_v, weight=data["weight"])
self.nodes = list(self.semantics_graph.nodes)
self.semantics_matrix = to_numpy_matrix(self.semantics_graph)
def object_concept_embedding(self, concept: str) -> Any:
# Get a numpy array weighted adjacency embedding of the concept from the graph
return self.semantics_matrix[self.nodes.index(concept)]
def kind_concept_embedding(self, concept: str) -> Any:
# Get a numpy array weighted adjacency embedding averaging the members of a kind concept in the graph
member_embeddings = np.vstack(
[
self.object_concept_embedding(member)
for member in self.semantics_graph.neighbors(concept)
]
)
return np.mean(member_embeddings, axis=0)
def evaluate_kind_membership(self, word: str, kind: str) -> float:
word_node = self.concept_as_str_node(ObjectConcept(word))
kind_node = self.concept_as_str_node(KindConcept(kind))
if kind_node not in self.nodes or word_node not in self.nodes:
return 0
return cos_sim(
self.object_concept_embedding(word_node),
self.kind_concept_embedding(kind_node),
)
@staticmethod
def concept_as_str_node(concept: Concept, syntactic_position="") -> str:
if syntactic_position:
return f"{concept.debug_string}_{str(type(concept))}_{syntactic_position}"
else:
return f"{concept.debug_string}_{str(type(concept))}"
def get_concept_node_from_graph(
identifier: str, semantics_graph: Graph
) -> Optional[Concept]:
return first([n for n in semantics_graph.nodes if n.debug_string == identifier], None)
def cos_sim(a, b) -> float:
dot = np.dot(a.reshape(1, -1), b.reshape(-1, 1))
norma = np.linalg.norm(a.reshape(1, -1))
normb = np.linalg.norm(b.reshape(1, -1))
return dot / (norma * normb)
def generate_heatmap(nodes_to_embeddings: Dict[Concept, Any], filename: str):
if not nodes_to_embeddings:
return
similarity_matrix = np.zeros((len(nodes_to_embeddings), len(nodes_to_embeddings)))
for i, (_, embedding_1) in enumerate(nodes_to_embeddings.items()):
for j, (_, embedding_2) in enumerate(nodes_to_embeddings.items()):
similarity_matrix[i][j] = cos_sim(embedding_1, embedding_2)
names = [n.debug_string for n in nodes_to_embeddings.keys()]
df = pd.DataFrame(data=similarity_matrix, index=names, columns=names)
plt.rcParams["figure.figsize"] = (20.0, 20.0)
plt.rcParams["font.family"] = "serif"
sb.clustermap(df, row_cluster=True, col_cluster=True)
plt.savefig(f"plots/{filename}.png")
plt.close()
| 40.914894 | 109 | 0.671867 | from typing import Optional, Any, Dict
import numpy as np
import pandas as pd
from more_itertools import first
from networkx import Graph, to_numpy_matrix
import matplotlib.pyplot as plt
import seaborn as sb
from adam.semantics import Concept, KindConcept, ObjectConcept, ActionConcept
class SemanticsManager:
def __init__(self, semantics_graph: Graph) -> None:
self.semantics_graph: Graph = Graph()
for u, v, data in semantics_graph.edges(data=True):
syntactic_position = data["slot"]
new_u = (
self.concept_as_str_node(u, syntactic_position)
if isinstance(u, ActionConcept)
else self.concept_as_str_node(u)
)
new_v = (
self.concept_as_str_node(v, syntactic_position)
if isinstance(v, ActionConcept)
else self.concept_as_str_node(v)
)
self.semantics_graph.add_edge(new_u, new_v, weight=data["weight"])
self.nodes = list(self.semantics_graph.nodes)
self.semantics_matrix = to_numpy_matrix(self.semantics_graph)
def object_concept_embedding(self, concept: str) -> Any:
return self.semantics_matrix[self.nodes.index(concept)]
def kind_concept_embedding(self, concept: str) -> Any:
member_embeddings = np.vstack(
[
self.object_concept_embedding(member)
for member in self.semantics_graph.neighbors(concept)
]
)
return np.mean(member_embeddings, axis=0)
def evaluate_kind_membership(self, word: str, kind: str) -> float:
word_node = self.concept_as_str_node(ObjectConcept(word))
kind_node = self.concept_as_str_node(KindConcept(kind))
if kind_node not in self.nodes or word_node not in self.nodes:
return 0
return cos_sim(
self.object_concept_embedding(word_node),
self.kind_concept_embedding(kind_node),
)
@staticmethod
def concept_as_str_node(concept: Concept, syntactic_position="") -> str:
if syntactic_position:
return f"{concept.debug_string}_{str(type(concept))}_{syntactic_position}"
else:
return f"{concept.debug_string}_{str(type(concept))}"
def get_concept_node_from_graph(
identifier: str, semantics_graph: Graph
) -> Optional[Concept]:
return first([n for n in semantics_graph.nodes if n.debug_string == identifier], None)
def cos_sim(a, b) -> float:
dot = np.dot(a.reshape(1, -1), b.reshape(-1, 1))
norma = np.linalg.norm(a.reshape(1, -1))
normb = np.linalg.norm(b.reshape(1, -1))
return dot / (norma * normb)
def generate_heatmap(nodes_to_embeddings: Dict[Concept, Any], filename: str):
if not nodes_to_embeddings:
return
similarity_matrix = np.zeros((len(nodes_to_embeddings), len(nodes_to_embeddings)))
for i, (_, embedding_1) in enumerate(nodes_to_embeddings.items()):
for j, (_, embedding_2) in enumerate(nodes_to_embeddings.items()):
similarity_matrix[i][j] = cos_sim(embedding_1, embedding_2)
names = [n.debug_string for n in nodes_to_embeddings.keys()]
df = pd.DataFrame(data=similarity_matrix, index=names, columns=names)
plt.rcParams["figure.figsize"] = (20.0, 20.0)
plt.rcParams["font.family"] = "serif"
sb.clustermap(df, row_cluster=True, col_cluster=True)
plt.savefig(f"plots/{filename}.png")
plt.close()
| true | true |
f729dbddfe2f0e5d66654ec570374536e6b98d9d | 3,353 | py | Python | pano_libs/P0.py | ManuLado/Enviar-comandos-a-marlin | f7f474ad0459602176114c62e7c97874cb69191b | [
"MIT"
] | 2 | 2021-10-02T20:20:45.000Z | 2021-10-02T20:20:53.000Z | pano_libs/P0.py | ManuLado/2D-XRay_Scan_control | 5ba596c9b0db47125e2e29ed8084e61d326e8777 | [
"MIT"
] | null | null | null | pano_libs/P0.py | ManuLado/2D-XRay_Scan_control | 5ba596c9b0db47125e2e29ed8084e61d326e8777 | [
"MIT"
] | null | null | null | from random import randrange
import matplotlib.pyplot as plt
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
parser.add_argument("nombre1", help="echo the string you use here")
parser.add_argument("nombre2", help="echo the string you use here")
parser.add_argument("nombre3", help="echo the string you use here")
args = parser.parse_args()
dire=args.echo
name1=dire+'/'+args.nombre1
name2=dire+'/'+args.nombre2
k=args.nombre3
figsize = (10, 10)
rgb_l = cv2.cvtColor(cv2.imread(name1), cv2.COLOR_BGR2RGB)
gray_l = cv2.cvtColor(rgb_l, cv2.COLOR_RGB2GRAY)
rgb_r = cv2.cvtColor(cv2.imread(name2), cv2.COLOR_BGR2RGB)
gray_r = cv2.cvtColor(rgb_r, cv2.COLOR_RGB2GRAY)
# use orb if sift is not installed
feature_extractor = cv2.ORB_create()
# find the keypoints and descriptors with chosen feature_extractor
kp_l, desc_l = feature_extractor.detectAndCompute(gray_l, None)
kp_r, desc_r = feature_extractor.detectAndCompute(gray_r, None)
test = cv2.drawKeypoints(rgb_l, kp_l, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.figure(figsize=figsize)
plt.imshow(test)
plt.title("keypoints")
#plt.show()
bf = cv2.BFMatcher()
matches = bf.knnMatch(desc_l, desc_r, k=2)
# Apply ratio test
good_match = []
for m in matches:
if m[0].distance/m[1].distance < 0.5:
good_match.append(m)
good_match_arr = np.asarray(good_match)
# show only 30 matches
im_matches = cv2.drawMatchesKnn(rgb_l, kp_l, rgb_r, kp_r,
good_match[0:30], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
plt.figure(figsize=(20, 20))
plt.imshow(im_matches)
plt.title("keypoints matches")
#plt.show()
good_kp_l = np.array([kp_l[m.queryIdx].pt for m in good_match_arr[:, 0]]).reshape(-1, 1, 2)
good_kp_r = np.array([kp_r[m.trainIdx].pt for m in good_match_arr[:, 0]]).reshape(-1, 1, 2)
H, masked = cv2.findHomography(good_kp_r, good_kp_l, cv2.RANSAC, 5.0)
print(H)
rgb_r_warped = cv2.warpPerspective(rgb_r, H, (rgb_l.shape[1] + rgb_r.shape[1], rgb_l.shape[0]))
rgb_r_warped[0:rgb_l.shape[0], 0:rgb_l.shape[1]] = rgb_l
plt.figure(figsize=figsize)
plt.imshow(rgb_r_warped)
plt.title("naive warping")
#plt.show()
def warpTwoImages(img1, img2, H):
'''warp img2 to img1 with homograph H
from: https://stackoverflow.com/questions/13063201/how-to-show-the-whole-image-when-using-opencv-warpperspective
'''
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
pts1 = np.float32([[0, 0], [0, h1], [w1, h1], [w1, 0]]).reshape(-1, 1, 2)
pts2 = np.float32([[0, 0], [0, h2], [w2, h2], [w2, 0]]).reshape(-1, 1, 2)
pts2_ = cv2.perspectiveTransform(pts2, H)
pts = np.concatenate((pts1, pts2_), axis=0)
[xmin, ymin] = np.int32(pts.min(axis=0).ravel() - 0.5)
[xmax, ymax] = np.int32(pts.max(axis=0).ravel() + 0.5)
t = [-xmin, -ymin]
Ht = np.array([[1, 0, t[0]], [0, 1, t[1]], [0, 0, 1]]) # translate
result = cv2.warpPerspective(img2, Ht@H, (xmax-xmin, ymax-ymin))
result[t[1]:h1+t[1], t[0]:w1+t[0]] = img1
return result
result = warpTwoImages(rgb_l, rgb_r, H)
plt.figure(figsize=figsize)
plt.imshow(result)
plt.title("better warping")
#plt.show()
cv2.imwrite(dire+"_P0/"+str(k)+".jpg",result) | 35.670213 | 117 | 0.680286 | from random import randrange
import matplotlib.pyplot as plt
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
parser.add_argument("nombre1", help="echo the string you use here")
parser.add_argument("nombre2", help="echo the string you use here")
parser.add_argument("nombre3", help="echo the string you use here")
args = parser.parse_args()
dire=args.echo
name1=dire+'/'+args.nombre1
name2=dire+'/'+args.nombre2
k=args.nombre3
figsize = (10, 10)
rgb_l = cv2.cvtColor(cv2.imread(name1), cv2.COLOR_BGR2RGB)
gray_l = cv2.cvtColor(rgb_l, cv2.COLOR_RGB2GRAY)
rgb_r = cv2.cvtColor(cv2.imread(name2), cv2.COLOR_BGR2RGB)
gray_r = cv2.cvtColor(rgb_r, cv2.COLOR_RGB2GRAY)
feature_extractor = cv2.ORB_create()
kp_l, desc_l = feature_extractor.detectAndCompute(gray_l, None)
kp_r, desc_r = feature_extractor.detectAndCompute(gray_r, None)
test = cv2.drawKeypoints(rgb_l, kp_l, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
plt.figure(figsize=figsize)
plt.imshow(test)
plt.title("keypoints")
bf = cv2.BFMatcher()
matches = bf.knnMatch(desc_l, desc_r, k=2)
good_match = []
for m in matches:
if m[0].distance/m[1].distance < 0.5:
good_match.append(m)
good_match_arr = np.asarray(good_match)
im_matches = cv2.drawMatchesKnn(rgb_l, kp_l, rgb_r, kp_r,
good_match[0:30], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
plt.figure(figsize=(20, 20))
plt.imshow(im_matches)
plt.title("keypoints matches")
good_kp_l = np.array([kp_l[m.queryIdx].pt for m in good_match_arr[:, 0]]).reshape(-1, 1, 2)
good_kp_r = np.array([kp_r[m.trainIdx].pt for m in good_match_arr[:, 0]]).reshape(-1, 1, 2)
H, masked = cv2.findHomography(good_kp_r, good_kp_l, cv2.RANSAC, 5.0)
print(H)
rgb_r_warped = cv2.warpPerspective(rgb_r, H, (rgb_l.shape[1] + rgb_r.shape[1], rgb_l.shape[0]))
rgb_r_warped[0:rgb_l.shape[0], 0:rgb_l.shape[1]] = rgb_l
plt.figure(figsize=figsize)
plt.imshow(rgb_r_warped)
plt.title("naive warping")
def warpTwoImages(img1, img2, H):
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
pts1 = np.float32([[0, 0], [0, h1], [w1, h1], [w1, 0]]).reshape(-1, 1, 2)
pts2 = np.float32([[0, 0], [0, h2], [w2, h2], [w2, 0]]).reshape(-1, 1, 2)
pts2_ = cv2.perspectiveTransform(pts2, H)
pts = np.concatenate((pts1, pts2_), axis=0)
[xmin, ymin] = np.int32(pts.min(axis=0).ravel() - 0.5)
[xmax, ymax] = np.int32(pts.max(axis=0).ravel() + 0.5)
t = [-xmin, -ymin]
Ht = np.array([[1, 0, t[0]], [0, 1, t[1]], [0, 0, 1]])
result = cv2.warpPerspective(img2, Ht@H, (xmax-xmin, ymax-ymin))
result[t[1]:h1+t[1], t[0]:w1+t[0]] = img1
return result
result = warpTwoImages(rgb_l, rgb_r, H)
plt.figure(figsize=figsize)
plt.imshow(result)
plt.title("better warping")
cv2.imwrite(dire+"_P0/"+str(k)+".jpg",result) | true | true |
f729ddddacb585feb09b885d15890a8fa0bd1b87 | 816 | py | Python | photos/migrations/0007_monumenttype.py | kingsdigitallab/mmee-django | 43a8fcf02138f4b114507fa8894717e1363df4f1 | [
"MIT"
] | null | null | null | photos/migrations/0007_monumenttype.py | kingsdigitallab/mmee-django | 43a8fcf02138f4b114507fa8894717e1363df4f1 | [
"MIT"
] | 9 | 2020-02-11T23:19:52.000Z | 2021-06-09T17:39:45.000Z | photos/migrations/0007_monumenttype.py | kingsdigitallab/mmee-django | 43a8fcf02138f4b114507fa8894717e1363df4f1 | [
"MIT"
] | null | null | null | # Generated by Django 2.0.6 on 2018-07-03 14:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0006_alter_photo_and_photographer'),
]
operations = [
migrations.CreateModel(
name='MonumentType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=128, unique=True)),
],
options={
'ordering': ['title'],
},
),
migrations.AddField(
model_name='photo',
name='monument_type',
field=models.ManyToManyField(blank=True, null=True, to='photos.MonumentType'),
),
]
| 28.137931 | 114 | 0.560049 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0006_alter_photo_and_photographer'),
]
operations = [
migrations.CreateModel(
name='MonumentType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=128, unique=True)),
],
options={
'ordering': ['title'],
},
),
migrations.AddField(
model_name='photo',
name='monument_type',
field=models.ManyToManyField(blank=True, null=True, to='photos.MonumentType'),
),
]
| true | true |
f729dff0aa4f50ce943e0d25677e59524116d660 | 1,175 | py | Python | tamcolors/tam/tam_loop_receiver.py | cmcmarrow/tamcolors | 65a5f2455bbe35a739b98d14af158c3df7feb786 | [
"Apache-2.0"
] | 29 | 2020-07-17T23:46:17.000Z | 2022-02-06T05:36:44.000Z | tamcolors/tam/tam_loop_receiver.py | sudo-nikhil/tamcolors | 65a5f2455bbe35a739b98d14af158c3df7feb786 | [
"Apache-2.0"
] | 42 | 2020-07-25T19:39:52.000Z | 2021-02-24T01:19:58.000Z | tamcolors/tam/tam_loop_receiver.py | sudo-nikhil/tamcolors | 65a5f2455bbe35a739b98d14af158c3df7feb786 | [
"Apache-2.0"
] | 8 | 2020-07-18T23:02:48.000Z | 2020-12-30T04:07:35.000Z | # built in library
from abc import ABC
class TAMLoopReceiver(ABC):
def __init__(self, name):
self._name = name
self._running = True
self._receiver_settings = {}
def get_name(self):
"""
info: Will get the receiver name
:return: str
"""
return self._name
def get_handler(self):
"""
info: Will get an io if available
:return: TAMLoopIOHandler or None
"""
raise NotImplementedError()
def done(self):
"""
info: Will stop the receiver
:return: None
"""
self._running = False
def get_running(self):
"""
info: Checks if receiver is running
:return: bool
"""
return self._running
def set_receiver_settings(self, settings):
"""
info: will set the receiver io settings
:param settings: dict
:return: None
"""
self._receiver_settings = settings
def get_receiver_settings(self):
"""
info: will get the receiver io settings
:return: dict or None
"""
return self._receiver_settings
| 22.169811 | 47 | 0.55234 |
from abc import ABC
class TAMLoopReceiver(ABC):
def __init__(self, name):
self._name = name
self._running = True
self._receiver_settings = {}
def get_name(self):
return self._name
def get_handler(self):
raise NotImplementedError()
def done(self):
self._running = False
def get_running(self):
return self._running
def set_receiver_settings(self, settings):
self._receiver_settings = settings
def get_receiver_settings(self):
return self._receiver_settings
| true | true |
f729e20d205ec7356a21b63479b3865efad3c249 | 1,306 | py | Python | models/warnings_models.py | ichbineinNerd/Referee | 07683b2883cb1302b414157681e2d2ae8346d69e | [
"MIT"
] | 5 | 2019-04-11T17:55:59.000Z | 2021-02-04T01:38:35.000Z | models/warnings_models.py | ichbineinNerd/Referee | 07683b2883cb1302b414157681e2d2ae8346d69e | [
"MIT"
] | 6 | 2020-05-23T20:49:33.000Z | 2021-09-10T13:30:35.000Z | models/warnings_models.py | ichbineinNerd/Referee | 07683b2883cb1302b414157681e2d2ae8346d69e | [
"MIT"
] | 2 | 2020-05-24T08:32:43.000Z | 2020-05-27T14:21:45.000Z | from __future__ import annotations
from datetime import datetime
class RefWarning:
NEVER = datetime(9999, 1, 1)
def __init__(self, user_id: int, timestamp: datetime, mod_name: str, reason: str = "",
expiration_time: datetime = NEVER):
self.user_id = user_id
self.timestamp = timestamp
self.mod_name = mod_name
self.reason = reason
self.expiration_time = expiration_time
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((self.user_id, self.timestamp, self.reason, self.expiration_time))
def __repr__(self):
return str(self.__dict__)
@property
def timestamp_str(self):
return self.timestamp.strftime("%b-%d-%Y %H:%M")
@property
def date_str(self):
return self.timestamp.strftime("%b-%d-%Y")
@property
def expiration_str(self):
return self.expiration_time.strftime("%b-%d-%Y %H:%M")
@property
def expiration_date_str(self):
return self.expiration_time.strftime("%b-%d-%Y")
def is_expired(self):
return self.expiration_time < datetime.now()
| 27.208333 | 90 | 0.63706 | from __future__ import annotations
from datetime import datetime
class RefWarning:
NEVER = datetime(9999, 1, 1)
def __init__(self, user_id: int, timestamp: datetime, mod_name: str, reason: str = "",
expiration_time: datetime = NEVER):
self.user_id = user_id
self.timestamp = timestamp
self.mod_name = mod_name
self.reason = reason
self.expiration_time = expiration_time
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((self.user_id, self.timestamp, self.reason, self.expiration_time))
def __repr__(self):
return str(self.__dict__)
@property
def timestamp_str(self):
return self.timestamp.strftime("%b-%d-%Y %H:%M")
@property
def date_str(self):
return self.timestamp.strftime("%b-%d-%Y")
@property
def expiration_str(self):
return self.expiration_time.strftime("%b-%d-%Y %H:%M")
@property
def expiration_date_str(self):
return self.expiration_time.strftime("%b-%d-%Y")
def is_expired(self):
return self.expiration_time < datetime.now()
| true | true |
f729e2cc39bb8e37c1cd7b90d8c111a53df54359 | 41,062 | py | Python | theano/gpuarray/tests/test_dnn.py | alexlee-gk/Theano | e4e08782d3a10d010d3a99bc87fd0fc3b0465405 | [
"BSD-3-Clause"
] | null | null | null | theano/gpuarray/tests/test_dnn.py | alexlee-gk/Theano | e4e08782d3a10d010d3a99bc87fd0fc3b0465405 | [
"BSD-3-Clause"
] | null | null | null | theano/gpuarray/tests/test_dnn.py | alexlee-gk/Theano | e4e08782d3a10d010d3a99bc87fd0fc3b0465405 | [
"BSD-3-Clause"
] | 1 | 2020-07-30T16:55:30.000Z | 2020-07-30T16:55:30.000Z | from __future__ import absolute_import, print_function, division
import logging
from nose.plugins.skip import SkipTest
from nose_parameterized import parameterized
import numpy
from itertools import product, chain
import theano
from six import StringIO
import theano.tensor as T
import theano.tests.unittest_tools as utt
from theano.sandbox.neighbours import images2neibs
from theano.tensor.signal.pool import pool_2d
from theano.tensor.signal.pool import MaxPoolGrad, AveragePoolGrad
from .. import dnn
from ..basic_ops import GpuAllocEmpty
from .config import mode_with_gpu, mode_without_gpu, test_ctx_name
from . import test_nnet
from theano.configdefaults import SUPPORTED_DNN_CONV_ALGO_FWD
def test_dnn_conv_desc_merge():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
kern_shp = T.as_tensor_variable(
numpy.asarray([3, 1, 2, 2]).astype('int64'))
desc1 = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(2, 2),
conv_mode='conv')(kern_shp)
desc2 = dnn.GpuDnnConvDesc(border_mode='full', subsample=(1, 1),
conv_mode='cross')(kern_shp)
# CDataType is not DeepCopyable so this will crash if we don't use
# borrow=True
f = theano.function([], [theano.Out(desc1, borrow=True),
theano.Out(desc2, borrow=True)])
d1, d2 = f()
# This will be the case if they are merged, which would be bad.
assert d1 != d2
def test_dnn_conv_merge():
# This test that we merge correctly multiple dnn_conv.
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_shp = [2, 5, 6, 8]
kern_shp = [3, 5, 5, 6]
img = T.ftensor4('img')
kern = T.ftensor4('kern')
out = T.ftensor4('out')
desc = dnn.GpuDnnConvDesc(
border_mode='valid')(kern.shape)
# Test forward op
o1 = dnn.dnn_conv(img, kern)
o2 = dnn.dnn_conv(img, kern)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),
numpy.random.rand(*kern_shp).astype('float32'))
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]) == 1
# Test grad w op
o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc)
o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc)
f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]) == 1
# Test grad i op
o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc)
o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc)
f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]) == 1
def test_dnn_conv_inplace():
"""This test that we have inplace work correctly even when
GpuAllocEmpty get merged together.
"""
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_shp = [2, 5, 6, 8]
kern_shp = [3, 5, 5, 6]
img = T.ftensor4('img')
kern = T.ftensor4('kern')
out = T.ftensor4('out')
desc1 = dnn.GpuDnnConvDesc(border_mode='valid', conv_mode='conv')(
kern.shape)
desc2 = dnn.GpuDnnConvDesc(
border_mode='valid', conv_mode='cross')(kern.shape)
# Test forward op
o1 = dnn.dnn_conv(img, kern, conv_mode='conv')
o2 = dnn.dnn_conv(img, kern, conv_mode='cross')
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),
numpy.random.rand(*kern_shp).astype('float32'))
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
# Test grad w op
out = GpuAllocEmpty(kern.dtype, test_ctx_name)(*kern.shape)
o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc1)
o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc2)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
# Test grad i op
out = GpuAllocEmpty(img.dtype, test_ctx_name)(*img.shape)
o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc1)
o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc2)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
def pool_2d_i2n(input, ds=(2, 2), strides=None,
pad=(0, 0),
pool_function=T.max, mode='ignore_borders'):
if strides is None:
strides = ds
if strides[0] > ds[0] or strides[1] > ds[1]:
raise RuntimeError(
"strides should be smaller than or equal to ds,"
" strides=(%d, %d) and ds=(%d, %d)" %
(strides + ds))
shape = input.shape
if pad != (0, 0):
assert pool_function is T.max
pad_x = pad[0]
pad_y = pad[1]
a = T.alloc(-numpy.inf, shape[0], shape[1], shape[2] + pad_x * 2,
shape[3] + pad_y * 2)
input = T.set_subtensor(a[:, :,
pad_x:pad_x + shape[2],
pad_y:pad_y + shape[3]],
input)
shape = input.shape
neibs = images2neibs(input, ds, strides, mode=mode)
pooled_neibs = pool_function(neibs, axis=1)
output_width = (shape[2] - ds[0]) // strides[0] + 1
output_height = (shape[3] - ds[1]) // strides[1] + 1
pooled_output = pooled_neibs.reshape((shape[0], shape[1],
output_width, output_height))
return pooled_output
def test_pooling():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
# 'average_exc_pad' is disabled for versions < 4004
if dnn.version(raises=False) < 4004:
modes = ('max', 'average_inc_pad')
else:
modes = ('max', 'average_inc_pad', 'average_exc_pad')
x = T.ftensor4()
for mode, pad in product(modes,
((0, 0), (1, 0), (1, 0), (2, 3), (3, 2))):
if mode == 'max':
func = T.max
else:
func = T.mean
if pad != (0, 0) and func is T.mean:
continue
for ws in (4, 2, 5):
for stride in (2, 3):
if stride > ws:
continue
if pad[0] > stride or pad[1] > stride:
# Not implemented
continue
# We will check that the opt introduced it.
out1 = pool_2d(x, (ws, ws),
st=(stride, stride),
ignore_border=True,
padding=pad, mode=mode)
out2 = pool_2d_i2n(x, ds=(ws, ws), strides=(stride, stride),
pad=pad,
pool_function=func)
mode_without_gpu2 = mode_without_gpu.including()
mode_without_gpu2.check_isfinite = False
f1 = theano.function([x], out1, mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPool)
for node in f1.maker.fgraph.apply_nodes])
f2 = theano.function([x], out2, mode=mode_without_gpu2)
assert not any([isinstance(node.op, dnn.GpuDnnPool)
for node in f2.maker.fgraph.apply_nodes])
for shp in [(1, 10, 100, 100),
(1, 3, 99, 99),
(32, 1, 147, 197),
]:
data = numpy.random.normal(0, 1, shp).astype("float32")
a = f1(data)
b = f2(data)
utt.assert_allclose(a, b)
# Test the grad
for shp in [(1, 1, 2, 2),
(1, 1, 3, 3)]:
data = numpy.random.normal(0, 1, shp).astype("float32") * 10
ws = 2
stride = 2
if pad[0] > stride or pad[1] > stride:
# Not implemented
continue
# This test the CPU grad + opt + GPU implemtentation
def fn(x):
return pool_2d(x, (ws, ws), ignore_border=True,
padding=pad, mode=mode)
utt.verify_grad(fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
# Confirm that the opt would have inserted it.
fg = theano.function([x], theano.grad(fn(x).sum(), x),
mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)
for node in fg.maker.fgraph.toposort()])
# Test the GPU grad + GPU implementation
def fn(x):
dnn_op = dnn.dnn_pool(
x, ws=(ws, ws),
stride=(stride, stride),
pad=pad,
mode=mode)
return dnn_op
utt.verify_grad(fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
# Confirm that we get the good op.
fg = theano.function([x], theano.grad(fn(x).sum(), x),
mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)
for node in fg.maker.fgraph.toposort()])
g_out = fg(data)
# Compare against the CPU result
out = pool_2d(x, (ws, ws),
padding=pad,
ignore_border=True, mode=mode)
fc = theano.function([x], theano.grad(out.sum(), x),
mode=mode_without_gpu)
if mode == 'max':
assert any([isinstance(node.op, MaxPoolGrad)
for node in fc.maker.fgraph.toposort()])
else:
assert any([isinstance(node.op, AveragePoolGrad)
for node in fc.maker.fgraph.toposort()])
c_out = fc(data)
utt.assert_allclose(c_out, g_out)
def test_pooling_with_tensor_vars():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
x = T.ftensor4()
ws = theano.shared(numpy.array([2, 2], dtype='int32'))
st = theano.shared(numpy.array([1, 1], dtype='int32'))
pad = theano.shared(numpy.array([0, 0], dtype='int32'))
mode = 'max'
def fn(x):
dnn_op = dnn.dnn_pool(x,
ws=ws,
stride=st,
pad=pad,
mode=mode)
return dnn_op
for shp in [(1, 1, 2, 2),
(1, 1, 3, 3)]:
data = numpy.random.normal(0, 1, shp).astype("float32") * 10
theano.tests.unittest_tools.verify_grad(
fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
out2 = pool_2d_i2n(x, ds=(2, 2), strides=(1, 1),
pad=(0, 0),
pool_function=T.max)
mode_without_gpu2 = mode_without_gpu.including()
mode_without_gpu2.check_isfinite = False
f1 = theano.function([x], fn(x), mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPool)
for node in f1.maker.fgraph.apply_nodes])
f2 = theano.function([x], out2, mode=mode_without_gpu2)
assert not any([isinstance(node.op, dnn.GpuDnnPool)
for node in f2.maker.fgraph.apply_nodes])
for shp in [(1, 10, 100, 100),
(1, 3, 99, 99),
(32, 1, 147, 197),
]:
data = numpy.random.normal(0, 1, shp).astype("float32")
a = f1(data).__array__()
b = f2(data).__array__()
utt.assert_allclose(a, b)
def test_pooling_opt():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
x = T.fmatrix()
f = theano.function(
[x],
pool_2d(x, ds=(2, 2), mode='average_inc_pad',
ignore_border=True),
mode=mode_with_gpu)
assert any([isinstance(n.op, dnn.GpuDnnPool)
for n in f.maker.fgraph.toposort()])
f(numpy.zeros((10, 10), dtype='float32'))
f = theano.function(
[x],
T.grad(pool_2d(x, ds=(2, 2), mode='average_inc_pad',
ignore_border=True).sum(),
x),
mode=mode_with_gpu.including("cudnn"))
assert any([isinstance(n.op, dnn.GpuDnnPoolGrad)
for n in f.maker.fgraph.toposort()])
f(numpy.zeros((10, 10), dtype='float32'))
def test_dnn_tag():
"""
Test that if cudnn isn't avail we crash and that if it is avail, we use it.
"""
x = T.ftensor4()
old = theano.config.on_opt_error
theano.config.on_opt_error = "raise"
sio = StringIO()
handler = logging.StreamHandler(sio)
logging.getLogger('theano.compile.tests.test_dnn').addHandler(handler)
# Silence original handler when intentionnally generating warning messages
logging.getLogger('theano').removeHandler(theano.logging_default_handler)
raised = False
try:
f = theano.function(
[x],
pool_2d(x, ds=(2, 2), ignore_border=True),
mode=mode_with_gpu.including("cudnn"))
except (AssertionError, RuntimeError):
assert not dnn.dnn_available(test_ctx_name)
raised = True
finally:
theano.config.on_opt_error = old
logging.getLogger(
'theano.compile.tests.test_dnn').removeHandler(handler)
logging.getLogger('theano').addHandler(theano.logging_default_handler)
if not raised:
assert dnn.dnn_available(test_ctx_name)
assert any([isinstance(n.op, dnn.GpuDnnPool)
for n in f.maker.fgraph.toposort()])
class TestDnnInferShapes(utt.InferShapeTester):
border_modes = ['valid', 'full', 'half']
conv_modes = ['conv', 'cross']
def setUp(self):
super(TestDnnInferShapes, self).setUp()
self.mode = mode_with_gpu
def test_softmax(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
t = T.ftensor4('t')
rand_tensor = numpy.asarray(
numpy.random.rand(5, 4, 3, 2),
dtype='float32'
)
self._compile_and_check(
[t],
[dnn.GpuDnnSoftmax('accurate', 'channel')(t)],
[rand_tensor],
dnn.GpuDnnSoftmax
)
self._compile_and_check(
[t],
[
T.grad(
dnn.GpuDnnSoftmax(
'accurate',
'channel'
)(t).mean(),
t
)
],
[rand_tensor],
dnn.GpuDnnSoftmaxGrad
)
def _test_conv(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsamples, algo):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_val = numpy.asarray(img_val, dtype='float32')
kern_vals = numpy.asarray(kern_vals, dtype='float32')
for subsample in subsamples:
out_vals = numpy.zeros(
dnn.GpuDnnConv.get_out_shape(img_val.shape, kern_vals.shape,
border_mode=border_mode,
subsample=subsample),
dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=border_mode,
subsample=subsample,
conv_mode=conv_mode
)(kerns.shape)
conv = dnn.GpuDnnConv(algo=algo)(img, kerns, out, desc)
self._compile_and_check(
[img, kerns, out],
[conv],
[img_val, kern_vals, out_vals],
dnn.GpuDnnConv
)
@parameterized.expand(chain(product([SUPPORTED_DNN_CONV_ALGO_FWD[0]],
border_modes,
conv_modes),
product(SUPPORTED_DNN_CONV_ALGO_FWD[1:],
[border_modes[0]],
[conv_modes[0]])),
testcase_func_name=utt.custom_name_func)
def test_conv(self, algo, border_mode, conv_mode):
if algo == 'winograd' and dnn.version(raises=False) < 5000:
raise SkipTest(dnn.dnn_available.msg)
self._test_conv(T.ftensor4('img'),
T.ftensor4('kerns'),
T.ftensor4('out'),
numpy.random.rand(7, 2, 8, 4),
numpy.random.rand(8, 2, 4, 3),
border_mode,
conv_mode,
[(1, 1), (2, 2)],
algo)
@parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)
def test_conv3d_none(self, border_mode, conv_mode):
ftensor5 = T.TensorType(dtype="float32", broadcastable=(False,) * 5)
self._test_conv(ftensor5('img'),
ftensor5('kerns'),
ftensor5('out'),
numpy.random.rand(10, 2, 6, 4, 11),
numpy.random.rand(8, 2, 4, 3, 1),
border_mode,
conv_mode,
[(1, 1, 1), (2, 2, 2)],
'none')
def _test_conv_gradw(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsample):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_val = numpy.asarray(
img_val,
dtype='float32'
)
kern_vals = numpy.asarray(
kern_vals,
dtype='float32'
)
temp_img = img.dimshuffle(1, 0, 2, 3)
temp_kerns = kerns
if conv_mode == 'conv':
temp_kerns = temp_kerns[:, :, ::-1, ::-1]
temp_kerns = temp_kerns.dimshuffle(1, 0, 2, 3)
shape = (
kern_vals.shape[1], img_val.shape[1],
img_val.shape[2] - kern_vals.shape[2] + 1,
img_val.shape[3] - kern_vals.shape[3] + 1
)
out_vals = numpy.zeros(shape, dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=border_mode,
subsample=subsample,
conv_mode=conv_mode
)(out.shape)
conv_grad_w = dnn.GpuDnnConvGradW()(
temp_img,
temp_kerns,
out,
desc,
)
self._compile_and_check(
[temp_img, temp_kerns, out],
[conv_grad_w],
[img_val, kern_vals, out_vals],
dnn.GpuDnnConvGradW
)
@parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)
def test_conv_gradw(self, border_mode, conv_mode):
self._test_conv_gradw(T.ftensor4('img'),
T.ftensor4('kerns'),
T.ftensor4('out'),
numpy.random.rand(2, 5, 6, 8),
numpy.random.rand(2, 1, 5, 6),
border_mode,
conv_mode,
(1, 1))
def test_conv_gradi(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
kerns = T.ftensor4('kerns')
out = T.ftensor4('out')
kern_vals = numpy.asarray(
numpy.random.rand(13, 14, 15, 16),
dtype='float32'
)
out_vals = numpy.asarray(
numpy.random.rand(3, 13, 5, 6),
dtype='float32'
)
for params in product(
['valid'], # Should this work for 'full'?
[(1, 1)],
['conv', 'cross']
):
shape = (
out_vals.shape[0], kern_vals.shape[1],
out_vals.shape[2] + kern_vals.shape[2] - 1,
out_vals.shape[3] + kern_vals.shape[3] - 1
)
img_vals = numpy.zeros(shape, dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=params[0],
subsample=params[1],
conv_mode=params[2]
)(kerns.shape)
conv_grad_i = dnn.GpuDnnConvGradI()(
kerns,
out,
img,
desc,
)
self._compile_and_check(
[kerns, img, out],
[conv_grad_i],
[kern_vals, img_vals, out_vals],
dnn.GpuDnnConvGradI
)
def test_pool(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
img_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
# 'average_exc_pad' is disabled for versions < 4004
if dnn.version(raises=False) < 4004:
modes = ['max', 'average_inc_pad']
else:
modes = ['max', 'average_inc_pad', 'average_exc_pad']
for params in product(
[(1, 1), (2, 2), (3, 3)],
[(1, 1), (2, 2), (3, 3)],
modes
):
self._compile_and_check(
[img],
[dnn.GpuDnnPool(mode=params[2])(img, params[0], params[1], (0, 0))],
[img_val],
dnn.GpuDnnPool
)
def test_pool_grad(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
img_grad = T.ftensor4('img_grad')
out = T.ftensor4('out')
img_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
img_grad_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
out_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
for params in product(
[(1, 1), (2, 2), (3, 3)],
[(1, 1), (2, 2), (3, 3)],
['max', 'average_inc_pad']
):
pool_grad = dnn.GpuDnnPoolGrad(mode=params[2])(
img,
out,
img_grad,
params[0],
params[1],
(0, 0)
)
self._compile_and_check(
[img, img_grad, out],
[pool_grad],
[img_val, img_grad_val, out_val],
dnn.GpuDnnPoolGrad
)
# this has been a problem in the past
def test_dnn_conv_border_mode():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4()
kern = T.ftensor4()
dnn.dnn_conv(img, kern, border_mode=1)
dnn.dnn_conv(img, kern, border_mode=(2, 3))
dnn.dnn_conv(img, kern, border_mode='full')
dnn.dnn_conv(img, kern, border_mode='valid')
dnn.dnn_conv(img, kern, border_mode='half')
def test_dnn_conv_alpha_output_merge():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4()
kern = T.ftensor4()
out = T.ftensor4()
b = 1
c = 4
f = 3
ih = 5
iw = 8
kh = 2
kw = 6
img_val = numpy.random.random((b, c, ih, iw)).astype('float32')
kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')
out_val = numpy.random.random((b, f, ih - kh + 1,
iw - kw + 1)).astype('float32')
conv = dnn.dnn_conv(img, kern)
gw = theano.grad(conv.sum(), kern)
gi = theano.grad(conv.sum(), img)
lr = numpy.asarray(0.05, dtype='float32')
fr = lr * (conv + out)
wr = kern + lr * gw
ir = img + lr * gi
f1 = theano.function([img, kern, out], [fr, wr, ir], mode=mode_with_gpu)
assert isinstance(f1.maker.fgraph.outputs[0].owner.inputs[0].owner.op,
dnn.GpuDnnConv)
assert isinstance(f1.maker.fgraph.outputs[1].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradW)
assert isinstance(f1.maker.fgraph.outputs[2].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradI)
mode = mode_with_gpu
mode = mode.excluding('local_dnn_conv_alpha_merge')
mode = mode.excluding('local_dnn_convw_alpha_merge')
mode = mode.excluding('local_dnn_convi_alpha_merge')
mode = mode.excluding('local_dnn_conv_output_merge')
mode = mode.excluding('local_dnn_convw_output_merge')
mode = mode.excluding('local_dnn_convi_output_merge')
f2 = theano.function([img, kern, out], [fr, wr, ir], mode=mode)
assert not isinstance(f2.maker.fgraph.outputs[0].owner.inputs[0].owner.op,
dnn.GpuDnnConv)
assert not isinstance(f2.maker.fgraph.outputs[1].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradW)
assert not isinstance(f2.maker.fgraph.outputs[2].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradI)
out_f1 = f1(img_val, kern_val, out_val)
out_f2 = f2(img_val, kern_val, out_val)
assert len(out_f1) == len(out_f2)
for v1, v2 in zip(out_f1, out_f2):
utt.assert_allclose(v1, v2)
def test_dnn_conv_grad():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
b = 1
c = 4
f = 3
ih = 2
iw = 8
kh = 2
kw = 2
img_val = numpy.random.random((b, c, ih, iw)).astype('float32')
kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')
out_val = numpy.random.random((b, f, ih - kw + 1,
iw - kw + 1)).astype('float32')
def dconv(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConv()(img, kern, out, desc, alpha=0.5, beta=0.75)
def dconvi(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConvGradI()(kern, out, img, desc, alpha=-1.0,
beta=0.0)
def dconvw(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConvGradW()(img, out, kern, desc, alpha=0.75,
beta=-1.0)
utt.verify_grad(dconv, [img_val, kern_val, out_val])
utt.verify_grad(dconvi, [img_val, kern_val, out_val])
utt.verify_grad(dconvw, [img_val, kern_val, out_val])
def test_version():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
assert isinstance(dnn.version(), int)
class test_SoftMax(test_nnet.test_SoftMax):
gpu_op = dnn.GpuDnnSoftmax
gpu_grad_op = dnn.GpuDnnSoftmaxGrad
mode = mode_with_gpu
def setUp(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
def test_softmax_shape_0(self):
raise SkipTest("Cudnn doesn't support 0 shapes")
def test_softmax_grad(self):
def cmp(n, m, f, f_gpu):
data = numpy.arange(n * m, dtype='float32').reshape(n, m)
gdata = numpy.asarray(data)[:, :, None, None]
out = f(data)
gout = numpy.asarray(f_gpu(gdata))[:, :, 0, 0]
utt.assert_allclose(out, gout)
x = T.matrix('x', 'float32')
x_gpu = T.tensor4('x_gpu', 'float32')
f_z = T.nnet.softmax_op
f_gpu = dnn.GpuDnnSoftmax(
'accurate',
'channel'
)
# Verify the grad operation
dims = (2, 3, 4, 5)
gdata = numpy.arange(
numpy.product(dims),
dtype='float32'
).reshape(dims)
T.verify_grad(f_gpu, [gdata], rng=numpy.random,
mode=mode_with_gpu)
# Verify that the CPU and GPU implementations return the same results
# up to a tolerance.
self._test_softmax(
x,
x_gpu,
f_z,
f_gpu,
cmp
)
self._test_softmax(
x, x, f_z, f_z, self._cmp
)
# Verify that the SoftmaxGrad -> Gpu[Dnn]SoftmaxGrad
# optimization is applied when cudnn is required
y = T.fvector('y')
f = theano.function(
[y],
T.grad(T.nnet.softmax(y).mean(), y),
mode=mode_with_gpu
)
sorted_f = f.maker.fgraph.toposort()
val = numpy.random.rand(5).astype('float32')
out_dnn = f(val)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 1)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 0)
# Verify that the SoftmaxGrad -> Gpu[Dnn]SoftmaxGrad
# optimization is not applied when cudnn is excluded or not
# available
mode_wo_cudnn = mode_with_gpu.excluding("cudnn")
y = T.fvector('y')
f = theano.function(
[y],
T.grad(T.nnet.softmax(y).mean(), y),
mode=mode_wo_cudnn
)
sorted_f = f.maker.fgraph.toposort()
out_cpu = f(val)
utt.assert_allclose(out_dnn, out_cpu)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 0)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 1)
# Verify that the SoftmaxGrad -> GpuDnnSoftmaxGrad do not
# crash with manual graph
y = T.fvector('y')
o = theano.tensor.nnet.SoftmaxGrad()(y, y * 2)
f = theano.function([y], o, mode=mode_with_gpu)
sorted_f = f.maker.fgraph.toposort()
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 1)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 0)
def test_log_softmax(self):
# This is a test for an optimization that depends on cuDNN v3 or
# more recent. Don't test if the cuDNN version is too old.
if dnn.version(raises=False) < 3000:
raise SkipTest("Log-softmax is only in cudnn v3+")
x = T.ftensor4()
softmax_out = dnn.GpuDnnSoftmax('accurate', 'channel')(x)
log_out = T.log(T.as_tensor_variable(softmax_out))
f = theano.function([x], log_out, mode=mode_with_gpu)
# Ensure that the optimization has been applied
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
# Ensure that the output of the function is valid
input_shapes = [(3, 4, 5, 6),
(1025, 2, 3, 4),
(2, 1025, 3, 4),
(2, 3, 1025, 4),
(2, 3, 4, 1025),
(66000, 2, 3, 4),
(2, 66000, 3, 4),
(2, 3, 66000, 4),
(2, 3, 4, 66000)]
for inp_shape in input_shapes:
input_val = numpy.random.normal(0, 1, inp_shape).astype("float32")
out = f(input_val)
expected_out = numpy.log(numpy.exp(input_val) /
numpy.exp(input_val).sum(1)[:, None, :, :])
utt.assert_allclose(out, expected_out)
def test_log_softmax2(self):
# Test that the op LogSoftmax is correctly replaced by the op
# DnnSoftmax with the 'log' mode.
# This is a test for an optimization that depends on cuDNN v3 or
# more recent. Don't test if the cuDNN version is too old.
if dnn.version(raises=False) < 3000:
raise SkipTest("Log-softmax is only in cudnn v3+")
# Compile a reference function, on the CPU, to be used to validate the
# results of the other function.
x = T.fmatrix()
f_ref = theano.function([x], T.nnet.LogSoftmax()(x))
# Build the first graph and ensure that the optimization is applied
log_softmax_out = T.nnet.LogSoftmax()(x)
f = theano.function([x], log_softmax_out, mode=mode_with_gpu)
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
# Compare the output of the function with the reference function
inp = numpy.random.normal(0, 1, (5, 6)).astype("float32")
utt.assert_allclose(f(inp), f_ref(inp))
# Build the first graph and ensure that the optimization is applied
log_softmax_out = T.log(T.nnet.Softmax()(x))
f = theano.function([x], log_softmax_out, mode=mode_with_gpu)
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
# Compare the output of the function with the reference function
inp = numpy.random.normal(0, 1, (5, 6)).astype("float32")
utt.assert_allclose(f(inp), f_ref(inp))
def test_dnn_batchnorm_train():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
if dnn.version(raises=False) < 5000:
raise SkipTest("batch normalization requires cudnn v5+")
utt.seed_rng()
for mode in ('per-activation', 'spatial'):
for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):
x, scale, bias = (vartype(n) for n in ('x', 'scale', 'bias'))
ndim = x.ndim
eps = 5e-3 # some non-standard value to test if it's used
# forward pass
out, x_mean, x_invstd = dnn.dnn_batch_normalization_train(
x, scale, bias, mode, eps)
# reference forward pass
if mode == 'per-activation':
axes = (0,)
elif mode == 'spatial':
axes = (0,) + tuple(range(2, ndim))
x_mean2 = x.mean(axis=axes, keepdims=True)
x_invstd2 = T.inv(T.sqrt(x.var(axis=axes, keepdims=True) + eps))
scale2 = T.addbroadcast(scale, *axes)
bias2 = T.addbroadcast(bias, *axes)
out2 = (x - x_mean2) * (scale2 * x_invstd2) + bias2
# backward pass
dy = vartype('dy')
grads = T.grad(None, wrt=[x, scale, bias], known_grads={out: dy})
# reference backward pass
grads2 = T.grad(None, wrt=[x, scale, bias], known_grads={out2: dy})
# compile
f = theano.function([x, scale, bias, dy],
[out, x_mean, x_invstd, out2, x_mean2, x_invstd2] +
grads + grads2, mode=mode_with_gpu)
# run
for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):
data_shape = data_shape[:ndim]
param_shape = tuple(1 if d in axes else s
for d, s in enumerate(data_shape))
X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')
Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')
Scale = numpy.random.randn(*param_shape).astype('float32')
Bias = numpy.random.randn(*param_shape).astype('float32')
outputs = f(X, Scale, Bias, Dy)
# compare outputs
utt.assert_allclose(outputs[0], outputs[0 + 3]) # out
utt.assert_allclose(outputs[1], outputs[1 + 3]) # mean
utt.assert_allclose(outputs[2], outputs[2 + 3]) # invstd
# compare gradients
utt.assert_allclose(outputs[6], outputs[6 + 3]) # dx
utt.assert_allclose(outputs[7], outputs[7 + 3], rtol=3e-3) # dscale
utt.assert_allclose(outputs[8], outputs[8 + 3]) # dbias
def test_batchnorm_inference():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
if dnn.version(raises=False) < 5000:
raise SkipTest("batch normalization requires cudnn v5+")
utt.seed_rng()
for mode in ('per-activation', 'spatial'):
for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):
x, scale, bias, mean, var = (vartype(n) for n in ('x', 'scale',
'bias', 'mean',
'var'))
ndim = x.ndim
eps = 5e-3 # some non-standard value to test if it's used
# forward pass
out = dnn.dnn_batch_normalization_test(x, scale, bias, mean,
var, mode, eps)
# reference forward pass
if mode == 'per-activation':
axes = (0,)
elif mode == 'spatial':
axes = (0,) + tuple(range(2, ndim))
scale2, bias2, mean2, var2 = (T.addbroadcast(t, *axes)
for t in (scale, bias, mean, var))
out2 = (x - mean2) * (scale2 / T.sqrt(var2 + eps)) + bias2
# backward pass
dy = vartype('dy')
grads = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out: dy})
# reference backward pass
grads2 = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out2: dy})
# compile
f = theano.function([x, scale, bias, mean, var, dy],
[out, out2] + grads + grads2, mode=mode_with_gpu)
# run
for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):
data_shape = data_shape[:ndim]
param_shape = tuple(1 if d in axes else s
for d, s in enumerate(data_shape))
X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')
Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')
Scale = numpy.random.randn(*param_shape).astype('float32')
Bias = numpy.random.randn(*param_shape).astype('float32')
Mean = numpy.random.randn(*param_shape).astype('float32')
Var = numpy.random.rand(*param_shape).astype('float32')
outputs = f(X, Scale, Bias, Mean, Var, Dy)
# compare outputs
utt.assert_allclose(outputs[0], outputs[1]) # out
# compare gradients
utt.assert_allclose(outputs[2], outputs[2 + 5]) # dx
utt.assert_allclose(outputs[3], outputs[3 + 5]) # dscale
utt.assert_allclose(outputs[4], outputs[4 + 5]) # dbias
utt.assert_allclose(outputs[5], outputs[5 + 5]) # dmean
utt.assert_allclose(outputs[6], outputs[6 + 5], atol=2e-5) # dvar
| 37.775529 | 104 | 0.528518 | from __future__ import absolute_import, print_function, division
import logging
from nose.plugins.skip import SkipTest
from nose_parameterized import parameterized
import numpy
from itertools import product, chain
import theano
from six import StringIO
import theano.tensor as T
import theano.tests.unittest_tools as utt
from theano.sandbox.neighbours import images2neibs
from theano.tensor.signal.pool import pool_2d
from theano.tensor.signal.pool import MaxPoolGrad, AveragePoolGrad
from .. import dnn
from ..basic_ops import GpuAllocEmpty
from .config import mode_with_gpu, mode_without_gpu, test_ctx_name
from . import test_nnet
from theano.configdefaults import SUPPORTED_DNN_CONV_ALGO_FWD
def test_dnn_conv_desc_merge():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
kern_shp = T.as_tensor_variable(
numpy.asarray([3, 1, 2, 2]).astype('int64'))
desc1 = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(2, 2),
conv_mode='conv')(kern_shp)
desc2 = dnn.GpuDnnConvDesc(border_mode='full', subsample=(1, 1),
conv_mode='cross')(kern_shp)
# borrow=True
f = theano.function([], [theano.Out(desc1, borrow=True),
theano.Out(desc2, borrow=True)])
d1, d2 = f()
# This will be the case if they are merged, which would be bad.
assert d1 != d2
def test_dnn_conv_merge():
# This test that we merge correctly multiple dnn_conv.
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_shp = [2, 5, 6, 8]
kern_shp = [3, 5, 5, 6]
img = T.ftensor4('img')
kern = T.ftensor4('kern')
out = T.ftensor4('out')
desc = dnn.GpuDnnConvDesc(
border_mode='valid')(kern.shape)
# Test forward op
o1 = dnn.dnn_conv(img, kern)
o2 = dnn.dnn_conv(img, kern)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),
numpy.random.rand(*kern_shp).astype('float32'))
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]) == 1
# Test grad w op
o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc)
o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc)
f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]) == 1
# Test grad i op
o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc)
o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc)
f = theano.function([img, kern, out], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
assert len([n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]) == 1
def test_dnn_conv_inplace():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_shp = [2, 5, 6, 8]
kern_shp = [3, 5, 5, 6]
img = T.ftensor4('img')
kern = T.ftensor4('kern')
out = T.ftensor4('out')
desc1 = dnn.GpuDnnConvDesc(border_mode='valid', conv_mode='conv')(
kern.shape)
desc2 = dnn.GpuDnnConvDesc(
border_mode='valid', conv_mode='cross')(kern.shape)
# Test forward op
o1 = dnn.dnn_conv(img, kern, conv_mode='conv')
o2 = dnn.dnn_conv(img, kern, conv_mode='cross')
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
d1, d2 = f(numpy.random.rand(*img_shp).astype('float32'),
numpy.random.rand(*kern_shp).astype('float32'))
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConv)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
# Test grad w op
out = GpuAllocEmpty(kern.dtype, test_ctx_name)(*kern.shape)
o1 = dnn.GpuDnnConvGradW()(img, kern, out, desc1)
o2 = dnn.GpuDnnConvGradW()(img, kern, out, desc2)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradW)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
# Test grad i op
out = GpuAllocEmpty(img.dtype, test_ctx_name)(*img.shape)
o1 = dnn.GpuDnnConvGradI()(img, kern, out, desc1)
o2 = dnn.GpuDnnConvGradI()(img, kern, out, desc2)
f = theano.function([img, kern], [o1, o2], mode=mode_with_gpu)
topo = f.maker.fgraph.toposort()
convs = [n for n in topo if isinstance(n.op, dnn.GpuDnnConvGradI)]
assert len(convs) == 2
assert all([node.op.inplace for node in convs])
assert len([n for n in topo if isinstance(n.op, GpuAllocEmpty)]) == 2
def pool_2d_i2n(input, ds=(2, 2), strides=None,
pad=(0, 0),
pool_function=T.max, mode='ignore_borders'):
if strides is None:
strides = ds
if strides[0] > ds[0] or strides[1] > ds[1]:
raise RuntimeError(
"strides should be smaller than or equal to ds,"
" strides=(%d, %d) and ds=(%d, %d)" %
(strides + ds))
shape = input.shape
if pad != (0, 0):
assert pool_function is T.max
pad_x = pad[0]
pad_y = pad[1]
a = T.alloc(-numpy.inf, shape[0], shape[1], shape[2] + pad_x * 2,
shape[3] + pad_y * 2)
input = T.set_subtensor(a[:, :,
pad_x:pad_x + shape[2],
pad_y:pad_y + shape[3]],
input)
shape = input.shape
neibs = images2neibs(input, ds, strides, mode=mode)
pooled_neibs = pool_function(neibs, axis=1)
output_width = (shape[2] - ds[0]) // strides[0] + 1
output_height = (shape[3] - ds[1]) // strides[1] + 1
pooled_output = pooled_neibs.reshape((shape[0], shape[1],
output_width, output_height))
return pooled_output
def test_pooling():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
# 'average_exc_pad' is disabled for versions < 4004
if dnn.version(raises=False) < 4004:
modes = ('max', 'average_inc_pad')
else:
modes = ('max', 'average_inc_pad', 'average_exc_pad')
x = T.ftensor4()
for mode, pad in product(modes,
((0, 0), (1, 0), (1, 0), (2, 3), (3, 2))):
if mode == 'max':
func = T.max
else:
func = T.mean
if pad != (0, 0) and func is T.mean:
continue
for ws in (4, 2, 5):
for stride in (2, 3):
if stride > ws:
continue
if pad[0] > stride or pad[1] > stride:
# Not implemented
continue
# We will check that the opt introduced it.
out1 = pool_2d(x, (ws, ws),
st=(stride, stride),
ignore_border=True,
padding=pad, mode=mode)
out2 = pool_2d_i2n(x, ds=(ws, ws), strides=(stride, stride),
pad=pad,
pool_function=func)
mode_without_gpu2 = mode_without_gpu.including()
mode_without_gpu2.check_isfinite = False
f1 = theano.function([x], out1, mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPool)
for node in f1.maker.fgraph.apply_nodes])
f2 = theano.function([x], out2, mode=mode_without_gpu2)
assert not any([isinstance(node.op, dnn.GpuDnnPool)
for node in f2.maker.fgraph.apply_nodes])
for shp in [(1, 10, 100, 100),
(1, 3, 99, 99),
(32, 1, 147, 197),
]:
data = numpy.random.normal(0, 1, shp).astype("float32")
a = f1(data)
b = f2(data)
utt.assert_allclose(a, b)
# Test the grad
for shp in [(1, 1, 2, 2),
(1, 1, 3, 3)]:
data = numpy.random.normal(0, 1, shp).astype("float32") * 10
ws = 2
stride = 2
if pad[0] > stride or pad[1] > stride:
# Not implemented
continue
# This test the CPU grad + opt + GPU implemtentation
def fn(x):
return pool_2d(x, (ws, ws), ignore_border=True,
padding=pad, mode=mode)
utt.verify_grad(fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
# Confirm that the opt would have inserted it.
fg = theano.function([x], theano.grad(fn(x).sum(), x),
mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)
for node in fg.maker.fgraph.toposort()])
# Test the GPU grad + GPU implementation
def fn(x):
dnn_op = dnn.dnn_pool(
x, ws=(ws, ws),
stride=(stride, stride),
pad=pad,
mode=mode)
return dnn_op
utt.verify_grad(fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
# Confirm that we get the good op.
fg = theano.function([x], theano.grad(fn(x).sum(), x),
mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPoolGrad)
for node in fg.maker.fgraph.toposort()])
g_out = fg(data)
# Compare against the CPU result
out = pool_2d(x, (ws, ws),
padding=pad,
ignore_border=True, mode=mode)
fc = theano.function([x], theano.grad(out.sum(), x),
mode=mode_without_gpu)
if mode == 'max':
assert any([isinstance(node.op, MaxPoolGrad)
for node in fc.maker.fgraph.toposort()])
else:
assert any([isinstance(node.op, AveragePoolGrad)
for node in fc.maker.fgraph.toposort()])
c_out = fc(data)
utt.assert_allclose(c_out, g_out)
def test_pooling_with_tensor_vars():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
x = T.ftensor4()
ws = theano.shared(numpy.array([2, 2], dtype='int32'))
st = theano.shared(numpy.array([1, 1], dtype='int32'))
pad = theano.shared(numpy.array([0, 0], dtype='int32'))
mode = 'max'
def fn(x):
dnn_op = dnn.dnn_pool(x,
ws=ws,
stride=st,
pad=pad,
mode=mode)
return dnn_op
for shp in [(1, 1, 2, 2),
(1, 1, 3, 3)]:
data = numpy.random.normal(0, 1, shp).astype("float32") * 10
theano.tests.unittest_tools.verify_grad(
fn, [data],
cast_to_output_type=False,
mode=mode_with_gpu)
out2 = pool_2d_i2n(x, ds=(2, 2), strides=(1, 1),
pad=(0, 0),
pool_function=T.max)
mode_without_gpu2 = mode_without_gpu.including()
mode_without_gpu2.check_isfinite = False
f1 = theano.function([x], fn(x), mode=mode_with_gpu)
assert any([isinstance(node.op, dnn.GpuDnnPool)
for node in f1.maker.fgraph.apply_nodes])
f2 = theano.function([x], out2, mode=mode_without_gpu2)
assert not any([isinstance(node.op, dnn.GpuDnnPool)
for node in f2.maker.fgraph.apply_nodes])
for shp in [(1, 10, 100, 100),
(1, 3, 99, 99),
(32, 1, 147, 197),
]:
data = numpy.random.normal(0, 1, shp).astype("float32")
a = f1(data).__array__()
b = f2(data).__array__()
utt.assert_allclose(a, b)
def test_pooling_opt():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
x = T.fmatrix()
f = theano.function(
[x],
pool_2d(x, ds=(2, 2), mode='average_inc_pad',
ignore_border=True),
mode=mode_with_gpu)
assert any([isinstance(n.op, dnn.GpuDnnPool)
for n in f.maker.fgraph.toposort()])
f(numpy.zeros((10, 10), dtype='float32'))
f = theano.function(
[x],
T.grad(pool_2d(x, ds=(2, 2), mode='average_inc_pad',
ignore_border=True).sum(),
x),
mode=mode_with_gpu.including("cudnn"))
assert any([isinstance(n.op, dnn.GpuDnnPoolGrad)
for n in f.maker.fgraph.toposort()])
f(numpy.zeros((10, 10), dtype='float32'))
def test_dnn_tag():
x = T.ftensor4()
old = theano.config.on_opt_error
theano.config.on_opt_error = "raise"
sio = StringIO()
handler = logging.StreamHandler(sio)
logging.getLogger('theano.compile.tests.test_dnn').addHandler(handler)
# Silence original handler when intentionnally generating warning messages
logging.getLogger('theano').removeHandler(theano.logging_default_handler)
raised = False
try:
f = theano.function(
[x],
pool_2d(x, ds=(2, 2), ignore_border=True),
mode=mode_with_gpu.including("cudnn"))
except (AssertionError, RuntimeError):
assert not dnn.dnn_available(test_ctx_name)
raised = True
finally:
theano.config.on_opt_error = old
logging.getLogger(
'theano.compile.tests.test_dnn').removeHandler(handler)
logging.getLogger('theano').addHandler(theano.logging_default_handler)
if not raised:
assert dnn.dnn_available(test_ctx_name)
assert any([isinstance(n.op, dnn.GpuDnnPool)
for n in f.maker.fgraph.toposort()])
class TestDnnInferShapes(utt.InferShapeTester):
border_modes = ['valid', 'full', 'half']
conv_modes = ['conv', 'cross']
def setUp(self):
super(TestDnnInferShapes, self).setUp()
self.mode = mode_with_gpu
def test_softmax(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
t = T.ftensor4('t')
rand_tensor = numpy.asarray(
numpy.random.rand(5, 4, 3, 2),
dtype='float32'
)
self._compile_and_check(
[t],
[dnn.GpuDnnSoftmax('accurate', 'channel')(t)],
[rand_tensor],
dnn.GpuDnnSoftmax
)
self._compile_and_check(
[t],
[
T.grad(
dnn.GpuDnnSoftmax(
'accurate',
'channel'
)(t).mean(),
t
)
],
[rand_tensor],
dnn.GpuDnnSoftmaxGrad
)
def _test_conv(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsamples, algo):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_val = numpy.asarray(img_val, dtype='float32')
kern_vals = numpy.asarray(kern_vals, dtype='float32')
for subsample in subsamples:
out_vals = numpy.zeros(
dnn.GpuDnnConv.get_out_shape(img_val.shape, kern_vals.shape,
border_mode=border_mode,
subsample=subsample),
dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=border_mode,
subsample=subsample,
conv_mode=conv_mode
)(kerns.shape)
conv = dnn.GpuDnnConv(algo=algo)(img, kerns, out, desc)
self._compile_and_check(
[img, kerns, out],
[conv],
[img_val, kern_vals, out_vals],
dnn.GpuDnnConv
)
@parameterized.expand(chain(product([SUPPORTED_DNN_CONV_ALGO_FWD[0]],
border_modes,
conv_modes),
product(SUPPORTED_DNN_CONV_ALGO_FWD[1:],
[border_modes[0]],
[conv_modes[0]])),
testcase_func_name=utt.custom_name_func)
def test_conv(self, algo, border_mode, conv_mode):
if algo == 'winograd' and dnn.version(raises=False) < 5000:
raise SkipTest(dnn.dnn_available.msg)
self._test_conv(T.ftensor4('img'),
T.ftensor4('kerns'),
T.ftensor4('out'),
numpy.random.rand(7, 2, 8, 4),
numpy.random.rand(8, 2, 4, 3),
border_mode,
conv_mode,
[(1, 1), (2, 2)],
algo)
@parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)
def test_conv3d_none(self, border_mode, conv_mode):
ftensor5 = T.TensorType(dtype="float32", broadcastable=(False,) * 5)
self._test_conv(ftensor5('img'),
ftensor5('kerns'),
ftensor5('out'),
numpy.random.rand(10, 2, 6, 4, 11),
numpy.random.rand(8, 2, 4, 3, 1),
border_mode,
conv_mode,
[(1, 1, 1), (2, 2, 2)],
'none')
def _test_conv_gradw(self, img, kerns, out, img_val, kern_vals, border_mode, conv_mode, subsample):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img_val = numpy.asarray(
img_val,
dtype='float32'
)
kern_vals = numpy.asarray(
kern_vals,
dtype='float32'
)
temp_img = img.dimshuffle(1, 0, 2, 3)
temp_kerns = kerns
if conv_mode == 'conv':
temp_kerns = temp_kerns[:, :, ::-1, ::-1]
temp_kerns = temp_kerns.dimshuffle(1, 0, 2, 3)
shape = (
kern_vals.shape[1], img_val.shape[1],
img_val.shape[2] - kern_vals.shape[2] + 1,
img_val.shape[3] - kern_vals.shape[3] + 1
)
out_vals = numpy.zeros(shape, dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=border_mode,
subsample=subsample,
conv_mode=conv_mode
)(out.shape)
conv_grad_w = dnn.GpuDnnConvGradW()(
temp_img,
temp_kerns,
out,
desc,
)
self._compile_and_check(
[temp_img, temp_kerns, out],
[conv_grad_w],
[img_val, kern_vals, out_vals],
dnn.GpuDnnConvGradW
)
@parameterized.expand(product(border_modes, conv_modes), utt.custom_name_func)
def test_conv_gradw(self, border_mode, conv_mode):
self._test_conv_gradw(T.ftensor4('img'),
T.ftensor4('kerns'),
T.ftensor4('out'),
numpy.random.rand(2, 5, 6, 8),
numpy.random.rand(2, 1, 5, 6),
border_mode,
conv_mode,
(1, 1))
def test_conv_gradi(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
kerns = T.ftensor4('kerns')
out = T.ftensor4('out')
kern_vals = numpy.asarray(
numpy.random.rand(13, 14, 15, 16),
dtype='float32'
)
out_vals = numpy.asarray(
numpy.random.rand(3, 13, 5, 6),
dtype='float32'
)
for params in product(
['valid'], # Should this work for 'full'?
[(1, 1)],
['conv', 'cross']
):
shape = (
out_vals.shape[0], kern_vals.shape[1],
out_vals.shape[2] + kern_vals.shape[2] - 1,
out_vals.shape[3] + kern_vals.shape[3] - 1
)
img_vals = numpy.zeros(shape, dtype='float32')
desc = dnn.GpuDnnConvDesc(
border_mode=params[0],
subsample=params[1],
conv_mode=params[2]
)(kerns.shape)
conv_grad_i = dnn.GpuDnnConvGradI()(
kerns,
out,
img,
desc,
)
self._compile_and_check(
[kerns, img, out],
[conv_grad_i],
[kern_vals, img_vals, out_vals],
dnn.GpuDnnConvGradI
)
def test_pool(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
img_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
# 'average_exc_pad' is disabled for versions < 4004
if dnn.version(raises=False) < 4004:
modes = ['max', 'average_inc_pad']
else:
modes = ['max', 'average_inc_pad', 'average_exc_pad']
for params in product(
[(1, 1), (2, 2), (3, 3)],
[(1, 1), (2, 2), (3, 3)],
modes
):
self._compile_and_check(
[img],
[dnn.GpuDnnPool(mode=params[2])(img, params[0], params[1], (0, 0))],
[img_val],
dnn.GpuDnnPool
)
def test_pool_grad(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4('img')
img_grad = T.ftensor4('img_grad')
out = T.ftensor4('out')
img_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
img_grad_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
out_val = numpy.asarray(
numpy.random.rand(2, 3, 4, 5),
dtype='float32'
)
for params in product(
[(1, 1), (2, 2), (3, 3)],
[(1, 1), (2, 2), (3, 3)],
['max', 'average_inc_pad']
):
pool_grad = dnn.GpuDnnPoolGrad(mode=params[2])(
img,
out,
img_grad,
params[0],
params[1],
(0, 0)
)
self._compile_and_check(
[img, img_grad, out],
[pool_grad],
[img_val, img_grad_val, out_val],
dnn.GpuDnnPoolGrad
)
# this has been a problem in the past
def test_dnn_conv_border_mode():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4()
kern = T.ftensor4()
dnn.dnn_conv(img, kern, border_mode=1)
dnn.dnn_conv(img, kern, border_mode=(2, 3))
dnn.dnn_conv(img, kern, border_mode='full')
dnn.dnn_conv(img, kern, border_mode='valid')
dnn.dnn_conv(img, kern, border_mode='half')
def test_dnn_conv_alpha_output_merge():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
img = T.ftensor4()
kern = T.ftensor4()
out = T.ftensor4()
b = 1
c = 4
f = 3
ih = 5
iw = 8
kh = 2
kw = 6
img_val = numpy.random.random((b, c, ih, iw)).astype('float32')
kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')
out_val = numpy.random.random((b, f, ih - kh + 1,
iw - kw + 1)).astype('float32')
conv = dnn.dnn_conv(img, kern)
gw = theano.grad(conv.sum(), kern)
gi = theano.grad(conv.sum(), img)
lr = numpy.asarray(0.05, dtype='float32')
fr = lr * (conv + out)
wr = kern + lr * gw
ir = img + lr * gi
f1 = theano.function([img, kern, out], [fr, wr, ir], mode=mode_with_gpu)
assert isinstance(f1.maker.fgraph.outputs[0].owner.inputs[0].owner.op,
dnn.GpuDnnConv)
assert isinstance(f1.maker.fgraph.outputs[1].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradW)
assert isinstance(f1.maker.fgraph.outputs[2].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradI)
mode = mode_with_gpu
mode = mode.excluding('local_dnn_conv_alpha_merge')
mode = mode.excluding('local_dnn_convw_alpha_merge')
mode = mode.excluding('local_dnn_convi_alpha_merge')
mode = mode.excluding('local_dnn_conv_output_merge')
mode = mode.excluding('local_dnn_convw_output_merge')
mode = mode.excluding('local_dnn_convi_output_merge')
f2 = theano.function([img, kern, out], [fr, wr, ir], mode=mode)
assert not isinstance(f2.maker.fgraph.outputs[0].owner.inputs[0].owner.op,
dnn.GpuDnnConv)
assert not isinstance(f2.maker.fgraph.outputs[1].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradW)
assert not isinstance(f2.maker.fgraph.outputs[2].owner.inputs[0].owner.op,
dnn.GpuDnnConvGradI)
out_f1 = f1(img_val, kern_val, out_val)
out_f2 = f2(img_val, kern_val, out_val)
assert len(out_f1) == len(out_f2)
for v1, v2 in zip(out_f1, out_f2):
utt.assert_allclose(v1, v2)
def test_dnn_conv_grad():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
b = 1
c = 4
f = 3
ih = 2
iw = 8
kh = 2
kw = 2
img_val = numpy.random.random((b, c, ih, iw)).astype('float32')
kern_val = numpy.random.random((f, c, kh, kw)).astype('float32')
out_val = numpy.random.random((b, f, ih - kw + 1,
iw - kw + 1)).astype('float32')
def dconv(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConv()(img, kern, out, desc, alpha=0.5, beta=0.75)
def dconvi(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConvGradI()(kern, out, img, desc, alpha=-1.0,
beta=0.0)
def dconvw(img, kern, out):
desc = dnn.GpuDnnConvDesc(border_mode='valid', subsample=(1, 1),
conv_mode='conv')(kern.shape)
return dnn.GpuDnnConvGradW()(img, out, kern, desc, alpha=0.75,
beta=-1.0)
utt.verify_grad(dconv, [img_val, kern_val, out_val])
utt.verify_grad(dconvi, [img_val, kern_val, out_val])
utt.verify_grad(dconvw, [img_val, kern_val, out_val])
def test_version():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
assert isinstance(dnn.version(), int)
class test_SoftMax(test_nnet.test_SoftMax):
gpu_op = dnn.GpuDnnSoftmax
gpu_grad_op = dnn.GpuDnnSoftmaxGrad
mode = mode_with_gpu
def setUp(self):
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
def test_softmax_shape_0(self):
raise SkipTest("Cudnn doesn't support 0 shapes")
def test_softmax_grad(self):
def cmp(n, m, f, f_gpu):
data = numpy.arange(n * m, dtype='float32').reshape(n, m)
gdata = numpy.asarray(data)[:, :, None, None]
out = f(data)
gout = numpy.asarray(f_gpu(gdata))[:, :, 0, 0]
utt.assert_allclose(out, gout)
x = T.matrix('x', 'float32')
x_gpu = T.tensor4('x_gpu', 'float32')
f_z = T.nnet.softmax_op
f_gpu = dnn.GpuDnnSoftmax(
'accurate',
'channel'
)
dims = (2, 3, 4, 5)
gdata = numpy.arange(
numpy.product(dims),
dtype='float32'
).reshape(dims)
T.verify_grad(f_gpu, [gdata], rng=numpy.random,
mode=mode_with_gpu)
self._test_softmax(
x,
x_gpu,
f_z,
f_gpu,
cmp
)
self._test_softmax(
x, x, f_z, f_z, self._cmp
)
y = T.fvector('y')
f = theano.function(
[y],
T.grad(T.nnet.softmax(y).mean(), y),
mode=mode_with_gpu
)
sorted_f = f.maker.fgraph.toposort()
val = numpy.random.rand(5).astype('float32')
out_dnn = f(val)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 1)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 0)
mode_wo_cudnn = mode_with_gpu.excluding("cudnn")
y = T.fvector('y')
f = theano.function(
[y],
T.grad(T.nnet.softmax(y).mean(), y),
mode=mode_wo_cudnn
)
sorted_f = f.maker.fgraph.toposort()
out_cpu = f(val)
utt.assert_allclose(out_dnn, out_cpu)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 0)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 1)
y = T.fvector('y')
o = theano.tensor.nnet.SoftmaxGrad()(y, y * 2)
f = theano.function([y], o, mode=mode_with_gpu)
sorted_f = f.maker.fgraph.toposort()
assert(len([i
for i in sorted_f
if isinstance(
i.op,
self.gpu_grad_op)
]) == 1)
assert(len([i
for i in sorted_f
if isinstance(
i.op,
theano.tensor.nnet.SoftmaxGrad)
]) == 0)
def test_log_softmax(self):
if dnn.version(raises=False) < 3000:
raise SkipTest("Log-softmax is only in cudnn v3+")
x = T.ftensor4()
softmax_out = dnn.GpuDnnSoftmax('accurate', 'channel')(x)
log_out = T.log(T.as_tensor_variable(softmax_out))
f = theano.function([x], log_out, mode=mode_with_gpu)
# Ensure that the optimization has been applied
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
# Ensure that the output of the function is valid
input_shapes = [(3, 4, 5, 6),
(1025, 2, 3, 4),
(2, 1025, 3, 4),
(2, 3, 1025, 4),
(2, 3, 4, 1025),
(66000, 2, 3, 4),
(2, 66000, 3, 4),
(2, 3, 66000, 4),
(2, 3, 4, 66000)]
for inp_shape in input_shapes:
input_val = numpy.random.normal(0, 1, inp_shape).astype("float32")
out = f(input_val)
expected_out = numpy.log(numpy.exp(input_val) /
numpy.exp(input_val).sum(1)[:, None, :, :])
utt.assert_allclose(out, expected_out)
def test_log_softmax2(self):
# Test that the op LogSoftmax is correctly replaced by the op
# DnnSoftmax with the 'log' mode.
# This is a test for an optimization that depends on cuDNN v3 or
# more recent. Don't test if the cuDNN version is too old.
if dnn.version(raises=False) < 3000:
raise SkipTest("Log-softmax is only in cudnn v3+")
x = T.fmatrix()
f_ref = theano.function([x], T.nnet.LogSoftmax()(x))
log_softmax_out = T.nnet.LogSoftmax()(x)
f = theano.function([x], log_softmax_out, mode=mode_with_gpu)
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
inp = numpy.random.normal(0, 1, (5, 6)).astype("float32")
utt.assert_allclose(f(inp), f_ref(inp))
log_softmax_out = T.log(T.nnet.Softmax()(x))
f = theano.function([x], log_softmax_out, mode=mode_with_gpu)
dnn_softmax_nodes = [n for n in f.maker.fgraph.toposort() if
isinstance(n.op, dnn.GpuDnnSoftmax)]
assert len(dnn_softmax_nodes) == 1
assert dnn_softmax_nodes[0].op.algo == "log"
inp = numpy.random.normal(0, 1, (5, 6)).astype("float32")
utt.assert_allclose(f(inp), f_ref(inp))
def test_dnn_batchnorm_train():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
if dnn.version(raises=False) < 5000:
raise SkipTest("batch normalization requires cudnn v5+")
utt.seed_rng()
for mode in ('per-activation', 'spatial'):
for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):
x, scale, bias = (vartype(n) for n in ('x', 'scale', 'bias'))
ndim = x.ndim
eps = 5e-3
# forward pass
out, x_mean, x_invstd = dnn.dnn_batch_normalization_train(
x, scale, bias, mode, eps)
# reference forward pass
if mode == 'per-activation':
axes = (0,)
elif mode == 'spatial':
axes = (0,) + tuple(range(2, ndim))
x_mean2 = x.mean(axis=axes, keepdims=True)
x_invstd2 = T.inv(T.sqrt(x.var(axis=axes, keepdims=True) + eps))
scale2 = T.addbroadcast(scale, *axes)
bias2 = T.addbroadcast(bias, *axes)
out2 = (x - x_mean2) * (scale2 * x_invstd2) + bias2
# backward pass
dy = vartype('dy')
grads = T.grad(None, wrt=[x, scale, bias], known_grads={out: dy})
# reference backward pass
grads2 = T.grad(None, wrt=[x, scale, bias], known_grads={out2: dy})
# compile
f = theano.function([x, scale, bias, dy],
[out, x_mean, x_invstd, out2, x_mean2, x_invstd2] +
grads + grads2, mode=mode_with_gpu)
# run
for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):
data_shape = data_shape[:ndim]
param_shape = tuple(1 if d in axes else s
for d, s in enumerate(data_shape))
X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')
Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')
Scale = numpy.random.randn(*param_shape).astype('float32')
Bias = numpy.random.randn(*param_shape).astype('float32')
outputs = f(X, Scale, Bias, Dy)
# compare outputs
utt.assert_allclose(outputs[0], outputs[0 + 3]) # out
utt.assert_allclose(outputs[1], outputs[1 + 3]) # mean
utt.assert_allclose(outputs[2], outputs[2 + 3]) # invstd
# compare gradients
utt.assert_allclose(outputs[6], outputs[6 + 3]) # dx
utt.assert_allclose(outputs[7], outputs[7 + 3], rtol=3e-3) # dscale
utt.assert_allclose(outputs[8], outputs[8 + 3]) # dbias
def test_batchnorm_inference():
if not dnn.dnn_available(test_ctx_name):
raise SkipTest(dnn.dnn_available.msg)
if dnn.version(raises=False) < 5000:
raise SkipTest("batch normalization requires cudnn v5+")
utt.seed_rng()
for mode in ('per-activation', 'spatial'):
for vartype in (T.ftensor4, T.ftensor3, T.fmatrix, T.fvector):
x, scale, bias, mean, var = (vartype(n) for n in ('x', 'scale',
'bias', 'mean',
'var'))
ndim = x.ndim
eps = 5e-3 # some non-standard value to test if it's used
out = dnn.dnn_batch_normalization_test(x, scale, bias, mean,
var, mode, eps)
if mode == 'per-activation':
axes = (0,)
elif mode == 'spatial':
axes = (0,) + tuple(range(2, ndim))
scale2, bias2, mean2, var2 = (T.addbroadcast(t, *axes)
for t in (scale, bias, mean, var))
out2 = (x - mean2) * (scale2 / T.sqrt(var2 + eps)) + bias2
dy = vartype('dy')
grads = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out: dy})
grads2 = T.grad(None, wrt=[x, scale, bias, mean, var], known_grads={out2: dy})
f = theano.function([x, scale, bias, mean, var, dy],
[out, out2] + grads + grads2, mode=mode_with_gpu)
for data_shape in ((10, 20, 30, 40), (4, 3, 1, 1), (1, 1, 5, 5)):
data_shape = data_shape[:ndim]
param_shape = tuple(1 if d in axes else s
for d, s in enumerate(data_shape))
X = 4 + 3 * numpy.random.randn(*data_shape).astype('float32')
Dy = -1 + 2 * numpy.random.randn(*data_shape).astype('float32')
Scale = numpy.random.randn(*param_shape).astype('float32')
Bias = numpy.random.randn(*param_shape).astype('float32')
Mean = numpy.random.randn(*param_shape).astype('float32')
Var = numpy.random.rand(*param_shape).astype('float32')
outputs = f(X, Scale, Bias, Mean, Var, Dy)
utt.assert_allclose(outputs[0], outputs[1])
utt.assert_allclose(outputs[2], outputs[2 + 5])
utt.assert_allclose(outputs[3], outputs[3 + 5])
utt.assert_allclose(outputs[4], outputs[4 + 5])
utt.assert_allclose(outputs[5], outputs[5 + 5])
utt.assert_allclose(outputs[6], outputs[6 + 5], atol=2e-5)
| true | true |
f729e2ffc0cb2138fcb6b489613b38cef01a97b2 | 1,606 | py | Python | aliyun-python-sdk-vs/aliyunsdkvs/request/v20181212/DeleteRenderingDevicesRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 1,001 | 2015-07-24T01:32:41.000Z | 2022-03-25T01:28:18.000Z | aliyun-python-sdk-vs/aliyunsdkvs/request/v20181212/DeleteRenderingDevicesRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 363 | 2015-10-20T03:15:00.000Z | 2022-03-08T12:26:19.000Z | aliyun-python-sdk-vs/aliyunsdkvs/request/v20181212/DeleteRenderingDevicesRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | 682 | 2015-09-22T07:19:02.000Z | 2022-03-22T09:51:46.000Z | # 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 aliyunsdkvs.endpoint import endpoint_data
class DeleteRenderingDevicesRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'vs', '2018-12-12', 'DeleteRenderingDevices')
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_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('InstanceIds')
def set_InstanceIds(self,InstanceIds):
self.add_query_param('InstanceIds',InstanceIds) | 36.5 | 74 | 0.767746 |
from aliyunsdkcore.request import RpcRequest
from aliyunsdkvs.endpoint import endpoint_data
class DeleteRenderingDevicesRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'vs', '2018-12-12', 'DeleteRenderingDevices')
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_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('InstanceIds')
def set_InstanceIds(self,InstanceIds):
self.add_query_param('InstanceIds',InstanceIds) | true | true |
f729e46d8267cb5b0c01e06ebe931a33e4c63d20 | 6,479 | py | Python | add_filter_relations.py | Babelscape/crocodile | 424ae33c68fdf22eb305e75b2f498831526d87f8 | [
"MIT"
] | 14 | 2021-09-06T14:19:48.000Z | 2022-03-30T15:30:10.000Z | add_filter_relations.py | Babelscape/crocodile | 424ae33c68fdf22eb305e75b2f498831526d87f8 | [
"MIT"
] | 5 | 2022-01-24T16:10:27.000Z | 2022-03-29T09:33:29.000Z | add_filter_relations.py | Babelscape/crocodile | 424ae33c68fdf22eb305e75b2f498831526d87f8 | [
"MIT"
] | 4 | 2021-12-10T08:56:46.000Z | 2022-03-28T12:24:10.000Z | import jsonlines
import re
import transformers
import torch
from tqdm import trange, tqdm
import argparse
import os, sys
def get_case_insensitive_key_value(input_dict, key):
return next((value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None)
def filter_triples(model, tokenizer, texts):
if max([len(text) for text in texts])>256:
range_length = 12
else:
range_length = 64
result = []
for batch in range(0,len(texts),range_length):
encoded_input = tokenizer(
[ex[0] for ex in texts[batch: batch + range_length]], [ex[1] for ex in texts[batch: batch + range_length]],
return_tensors="pt",
add_special_tokens=True,
max_length=256,
padding='longest',
return_token_type_ids=False,
truncation_strategy='only_first')
for tensor in encoded_input:
encoded_input[tensor] = encoded_input[tensor].cuda()
with torch.no_grad(): # remove this if you need gradients.
outputs = model(**encoded_input, return_dict=True, output_attentions=False, output_hidden_states = False)
result.append(outputs['logits'].softmax(dim=1))
del outputs
logits = torch.cat(result)
# if language == 'ko':
# return logits.argmax(1) == get_case_insensitive_key_value(model.config.label2id, 'entailment')# [:,get_case_insensitive_key_value(model.config.label2id, 'entailment')]>0.75
return logits[:,get_case_insensitive_key_value(model.config.label2id, 'entailment')]#>0.75
def prepare_triplet(subject_entity, object_entity, article_text, predicate):
text_triplet = ''
text_triplet += re.compile("(?<!\d)\.(?!\d)").split(article_text[:min(subject_entity['boundaries'][0], object_entity['boundaries'][0])])[-1]
text_triplet += article_text[min(subject_entity['boundaries'][0], object_entity['boundaries'][0]):max(subject_entity['boundaries'][1], object_entity['boundaries'][1])]
text_triplet += re.compile("(?<!\d)\.(?!\d)").split(article_text[max(subject_entity['boundaries'][1], object_entity['boundaries'][1]):])[0]
if language == 'ko' or language == 'kosource':
return (text_triplet.strip('\n'), ' '.join([str(subject_entity['surfaceform']), str(object_entity['surfaceform']), str(predicate['surfaceform'])]))
# return (text_triplet.strip('\n'), ' '.join([str(object_entity['surfaceform']), str(predicate['surfaceform']), str(subject_entity['surfaceform'])]))
return (text_triplet.strip('\n'), ' '.join([str(subject_entity['surfaceform']), str(predicate['surfaceform']), str(object_entity['surfaceform'])]))
def main(folder_input = 'out/ko'):
global language
language = folder_input.split('/')[1]
if language == 'ko' or language == 'kosource':
model_name_or_path = '/home/huguetcabot/sentence_transformers/test-glue/XNLI'
# model_name_or_path = '/home/huguetcabot/sentence_transformers/test-glue/run-1/checkpoint-3910'
else:
model_name_or_path = 'joeddav/xlm-roberta-large-xnli'
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_name_or_path)
model_config = transformers.AutoConfig.from_pretrained(
model_name_or_path,
# num_labels=2,
output_hidden_states=True,
output_attentions=True,
)
model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config = model_config)
model.cuda()
model.eval()
model.half()
with jsonlines.open(f'out_clean/{"/".join(folder_input.split("/")[1:])}.jsonl', mode='w') as writer:
for k,j,y in os.walk(folder_input):
for file_name in y:
with jsonlines.open(k + '/' + file_name) as reader:
for i, article in tqdm(enumerate(reader)):
previous = []
triples_list = []
texts = []
for triple in article['triples']:
if triple['subject']['boundaries'] != None and triple['object']['boundaries'] != None and (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:
previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))
triples_list.append(triple)
texts.append(prepare_triplet(triple['subject'], triple['object'], article['text'], triple["predicate"]))
elif (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:
distance = 1000000
for entity in article['entities']:
if entity['uri'] == triple['subject']['uri']:
if abs(min(triple['object']['boundaries'])-min(entity['boundaries'])) < distance:
subject_entity = entity
distance = abs(min(triple['object']['boundaries'])-min(entity['boundaries']))
triple['subject'] = subject_entity
previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))
triples_list.append(triple)
texts.append(prepare_triplet(subject_entity, triple['object'], article['text'], triple["predicate"]))
indexes = filter_triples(model, tokenizer, texts)
if len(indexes) == 0:
continue
for pred, trip in zip(indexes, triples_list):
trip['confidence'] = pred.item()
# article['triples'] = [x for i,x in zip(indexes, triples_list) if (i == True) or x["predicate"]["uri"] in ["P569", "P570"]]
article['triples'] = triples_list
writer.write(article)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
parser.add_argument("--folder_input",
help="input file")
args = parser.parse_args()
main(args.folder_input)
| 58.9 | 200 | 0.590832 | import jsonlines
import re
import transformers
import torch
from tqdm import trange, tqdm
import argparse
import os, sys
def get_case_insensitive_key_value(input_dict, key):
return next((value for dict_key, value in input_dict.items() if dict_key.lower() == key.lower()), None)
def filter_triples(model, tokenizer, texts):
if max([len(text) for text in texts])>256:
range_length = 12
else:
range_length = 64
result = []
for batch in range(0,len(texts),range_length):
encoded_input = tokenizer(
[ex[0] for ex in texts[batch: batch + range_length]], [ex[1] for ex in texts[batch: batch + range_length]],
return_tensors="pt",
add_special_tokens=True,
max_length=256,
padding='longest',
return_token_type_ids=False,
truncation_strategy='only_first')
for tensor in encoded_input:
encoded_input[tensor] = encoded_input[tensor].cuda()
with torch.no_grad():
outputs = model(**encoded_input, return_dict=True, output_attentions=False, output_hidden_states = False)
result.append(outputs['logits'].softmax(dim=1))
del outputs
logits = torch.cat(result)
tailment')]
def prepare_triplet(subject_entity, object_entity, article_text, predicate):
text_triplet = ''
text_triplet += re.compile("(?<!\d)\.(?!\d)").split(article_text[:min(subject_entity['boundaries'][0], object_entity['boundaries'][0])])[-1]
text_triplet += article_text[min(subject_entity['boundaries'][0], object_entity['boundaries'][0]):max(subject_entity['boundaries'][1], object_entity['boundaries'][1])]
text_triplet += re.compile("(?<!\d)\.(?!\d)").split(article_text[max(subject_entity['boundaries'][1], object_entity['boundaries'][1]):])[0]
if language == 'ko' or language == 'kosource':
return (text_triplet.strip('\n'), ' '.join([str(subject_entity['surfaceform']), str(object_entity['surfaceform']), str(predicate['surfaceform'])]))
return (text_triplet.strip('\n'), ' '.join([str(subject_entity['surfaceform']), str(predicate['surfaceform']), str(object_entity['surfaceform'])]))
def main(folder_input = 'out/ko'):
global language
language = folder_input.split('/')[1]
if language == 'ko' or language == 'kosource':
model_name_or_path = '/home/huguetcabot/sentence_transformers/test-glue/XNLI'
else:
model_name_or_path = 'joeddav/xlm-roberta-large-xnli'
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_name_or_path)
model_config = transformers.AutoConfig.from_pretrained(
model_name_or_path,
output_hidden_states=True,
output_attentions=True,
)
model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config = model_config)
model.cuda()
model.eval()
model.half()
with jsonlines.open(f'out_clean/{"/".join(folder_input.split("/")[1:])}.jsonl', mode='w') as writer:
for k,j,y in os.walk(folder_input):
for file_name in y:
with jsonlines.open(k + '/' + file_name) as reader:
for i, article in tqdm(enumerate(reader)):
previous = []
triples_list = []
texts = []
for triple in article['triples']:
if triple['subject']['boundaries'] != None and triple['object']['boundaries'] != None and (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:
previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))
triples_list.append(triple)
texts.append(prepare_triplet(triple['subject'], triple['object'], article['text'], triple["predicate"]))
elif (triple['subject']['boundaries'], triple['object']['boundaries']) not in previous:
distance = 1000000
for entity in article['entities']:
if entity['uri'] == triple['subject']['uri']:
if abs(min(triple['object']['boundaries'])-min(entity['boundaries'])) < distance:
subject_entity = entity
distance = abs(min(triple['object']['boundaries'])-min(entity['boundaries']))
triple['subject'] = subject_entity
previous.append((triple['subject']['boundaries'], triple['object']['boundaries']))
triples_list.append(triple)
texts.append(prepare_triplet(subject_entity, triple['object'], article['text'], triple["predicate"]))
indexes = filter_triples(model, tokenizer, texts)
if len(indexes) == 0:
continue
for pred, trip in zip(indexes, triples_list):
trip['confidence'] = pred.item()
article['triples'] = triples_list
writer.write(article)
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
parser.add_argument("--folder_input",
help="input file")
args = parser.parse_args()
main(args.folder_input)
| true | true |
f729e4a18c914ce149affd3f8a81920b280d3c55 | 2,271 | py | Python | venv/Lib/site-packages/sqlalchemy/dialects/mysql/cymysql.py | ajayiagbebaku/NFL-Model | afcc67a85ca7138c58c3334d45988ada2da158ed | [
"MIT"
] | 5,383 | 2018-11-27T07:34:03.000Z | 2022-03-31T19:40:59.000Z | venv/Lib/site-packages/sqlalchemy/dialects/mysql/cymysql.py | ajayiagbebaku/NFL-Model | afcc67a85ca7138c58c3334d45988ada2da158ed | [
"MIT"
] | 2,719 | 2018-11-27T07:55:01.000Z | 2022-03-31T22:09:44.000Z | venv/Lib/site-packages/sqlalchemy/dialects/mysql/cymysql.py | ajayiagbebaku/NFL-Model | afcc67a85ca7138c58c3334d45988ada2da158ed | [
"MIT"
] | 1,056 | 2015-01-03T00:30:17.000Z | 2022-03-15T12:56:24.000Z | # mysql/cymysql.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
r"""
.. dialect:: mysql+cymysql
:name: CyMySQL
:dbapi: cymysql
:connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]
:url: https://github.com/nakagami/CyMySQL
.. note::
The CyMySQL dialect is **not tested as part of SQLAlchemy's continuous
integration** and may have unresolved issues. The recommended MySQL
dialects are mysqlclient and PyMySQL.
""" # noqa
from .base import BIT
from .base import MySQLDialect
from .mysqldb import MySQLDialect_mysqldb
from ... import util
class _cymysqlBIT(BIT):
def result_processor(self, dialect, coltype):
"""Convert MySQL's 64 bit, variable length binary string to a long."""
def process(value):
if value is not None:
v = 0
for i in util.iterbytes(value):
v = v << 8 | i
return v
return value
return process
class MySQLDialect_cymysql(MySQLDialect_mysqldb):
driver = "cymysql"
supports_statement_cache = True
description_encoding = None
supports_sane_rowcount = True
supports_sane_multi_rowcount = False
supports_unicode_statements = True
colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _cymysqlBIT})
@classmethod
def dbapi(cls):
return __import__("cymysql")
def _detect_charset(self, connection):
return connection.connection.charset
def _extract_error_code(self, exception):
return exception.errno
def is_disconnect(self, e, connection, cursor):
if isinstance(e, self.dbapi.OperationalError):
return self._extract_error_code(e) in (
2006,
2013,
2014,
2045,
2055,
)
elif isinstance(e, self.dbapi.InterfaceError):
# if underlying connection is closed,
# this is the error you get
return True
else:
return False
dialect = MySQLDialect_cymysql
| 27.361446 | 85 | 0.638485 |
from .base import BIT
from .base import MySQLDialect
from .mysqldb import MySQLDialect_mysqldb
from ... import util
class _cymysqlBIT(BIT):
def result_processor(self, dialect, coltype):
def process(value):
if value is not None:
v = 0
for i in util.iterbytes(value):
v = v << 8 | i
return v
return value
return process
class MySQLDialect_cymysql(MySQLDialect_mysqldb):
driver = "cymysql"
supports_statement_cache = True
description_encoding = None
supports_sane_rowcount = True
supports_sane_multi_rowcount = False
supports_unicode_statements = True
colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _cymysqlBIT})
@classmethod
def dbapi(cls):
return __import__("cymysql")
def _detect_charset(self, connection):
return connection.connection.charset
def _extract_error_code(self, exception):
return exception.errno
def is_disconnect(self, e, connection, cursor):
if isinstance(e, self.dbapi.OperationalError):
return self._extract_error_code(e) in (
2006,
2013,
2014,
2045,
2055,
)
elif isinstance(e, self.dbapi.InterfaceError):
return True
else:
return False
dialect = MySQLDialect_cymysql
| true | true |
f729e4e182ac3a20e7743ca6dc182dca213a44ad | 1,340 | py | Python | src/sentry/testutils/skips.py | kinghuang/sentry | 5c22673994a62f54a782d1c595852986ccc51ae9 | [
"BSD-3-Clause"
] | 1 | 2019-10-17T17:46:16.000Z | 2019-10-17T17:46:16.000Z | src/sentry/testutils/skips.py | kinghuang/sentry | 5c22673994a62f54a782d1c595852986ccc51ae9 | [
"BSD-3-Clause"
] | null | null | null | src/sentry/testutils/skips.py | kinghuang/sentry | 5c22673994a62f54a782d1c595852986ccc51ae9 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import
from django.conf import settings
from six.moves.urllib.parse import urlparse
import os
import socket
import pytest
_service_status = {}
def cassandra_is_available():
if "cassandra" in _service_status:
return _service_status["cassandra"]
try:
socket.create_connection(("127.0.0.1", 9042), 1.0)
except socket.error:
_service_status["cassandra"] = False
else:
_service_status["cassandra"] = True
return _service_status["cassandra"]
requires_cassandra = pytest.mark.skipif(
not cassandra_is_available(), reason="requires cassandra server running"
)
def snuba_is_available():
if "snuba" in _service_status:
return _service_status["snuba"]
try:
parsed = urlparse(settings.SENTRY_SNUBA)
socket.create_connection((parsed.host, parsed.port), 1.0)
except socket.error:
_service_status["snuba"] = False
else:
_service_status["snuba"] = True
return _service_status["snuba"]
requires_snuba = pytest.mark.skipif(not snuba_is_available, reason="requires snuba server running")
def xfail_if_not_postgres(reason):
def decorator(function):
return pytest.mark.xfail(os.environ.get("TEST_SUITE") != "postgres", reason=reason)(
function
)
return decorator
| 25.283019 | 99 | 0.700746 | from __future__ import absolute_import
from django.conf import settings
from six.moves.urllib.parse import urlparse
import os
import socket
import pytest
_service_status = {}
def cassandra_is_available():
if "cassandra" in _service_status:
return _service_status["cassandra"]
try:
socket.create_connection(("127.0.0.1", 9042), 1.0)
except socket.error:
_service_status["cassandra"] = False
else:
_service_status["cassandra"] = True
return _service_status["cassandra"]
requires_cassandra = pytest.mark.skipif(
not cassandra_is_available(), reason="requires cassandra server running"
)
def snuba_is_available():
if "snuba" in _service_status:
return _service_status["snuba"]
try:
parsed = urlparse(settings.SENTRY_SNUBA)
socket.create_connection((parsed.host, parsed.port), 1.0)
except socket.error:
_service_status["snuba"] = False
else:
_service_status["snuba"] = True
return _service_status["snuba"]
requires_snuba = pytest.mark.skipif(not snuba_is_available, reason="requires snuba server running")
def xfail_if_not_postgres(reason):
def decorator(function):
return pytest.mark.xfail(os.environ.get("TEST_SUITE") != "postgres", reason=reason)(
function
)
return decorator
| true | true |
f729e502185aa58d4b4f06cb88e475a162fc589b | 333 | py | Python | examples/community/custom_user/forms.py | junhoyeo/fastdj | 73284946270d1f7ae13f077931b360f70e5a0143 | [
"MIT"
] | 7 | 2020-02-04T05:08:19.000Z | 2022-01-01T15:49:38.000Z | backend/custom_user/forms.py | code-yeongyu/sunrin-club-applying-system-backend | 217bba7165b75234147ab9230ff084cadfd4cf15 | [
"MIT"
] | null | null | null | backend/custom_user/forms.py | code-yeongyu/sunrin-club-applying-system-backend | 217bba7165b75234147ab9230ff084cadfd4cf15 | [
"MIT"
] | 5 | 2020-02-04T05:09:21.000Z | 2021-11-26T00:46:41.000Z | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2') | 30.272727 | 66 | 0.732733 | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2') | true | true |
f729e5919eadd4d9d935506d38e1e21deec0e140 | 31,381 | py | Python | paasta_tools/cli/cmds/status.py | yuanxu-li/paasta | 5b04f45659293f873c65111a9d1d0909aeed4019 | [
"Apache-2.0"
] | null | null | null | paasta_tools/cli/cmds/status.py | yuanxu-li/paasta | 5b04f45659293f873c65111a9d1d0909aeed4019 | [
"Apache-2.0"
] | null | null | null | paasta_tools/cli/cmds/status.py | yuanxu-li/paasta | 5b04f45659293f873c65111a9d1d0909aeed4019 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# 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 difflib
import os
import sys
from collections import defaultdict
from datetime import datetime
from distutils.util import strtobool
from itertools import groupby
from typing import Callable
from typing import DefaultDict
from typing import Dict
from typing import Iterable
from typing import List
from typing import Mapping
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
import humanize
from bravado.exception import HTTPError
from service_configuration_lib import read_deploy
from paasta_tools import kubernetes_tools
from paasta_tools.adhoc_tools import AdhocJobConfig
from paasta_tools.api.client import get_paasta_api_client
from paasta_tools.chronos_tools import ChronosJobConfig
from paasta_tools.cli.utils import execute_paasta_serviceinit_on_remote_master
from paasta_tools.cli.utils import figure_out_service_name
from paasta_tools.cli.utils import get_instance_configs_for_service
from paasta_tools.cli.utils import lazy_choices_completer
from paasta_tools.cli.utils import list_deploy_groups
from paasta_tools.flinkcluster_tools import FlinkClusterConfig
from paasta_tools.flinkcluster_tools import get_dashboard_url
from paasta_tools.kubernetes_tools import KubernetesDeploymentConfig
from paasta_tools.kubernetes_tools import KubernetesDeployStatus
from paasta_tools.marathon_serviceinit import bouncing_status_human
from paasta_tools.marathon_serviceinit import desired_state_human
from paasta_tools.marathon_serviceinit import marathon_app_deploy_status_human
from paasta_tools.marathon_serviceinit import status_marathon_job_human
from paasta_tools.marathon_tools import MarathonDeployStatus
from paasta_tools.monitoring_tools import get_team
from paasta_tools.monitoring_tools import list_teams
from paasta_tools.tron_tools import TronActionConfig
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import datetime_from_utc_to_local
from paasta_tools.utils import DEFAULT_SOA_DIR
from paasta_tools.utils import get_soa_cluster_deploy_files
from paasta_tools.utils import InstanceConfig
from paasta_tools.utils import list_all_instances_for_service
from paasta_tools.utils import list_clusters
from paasta_tools.utils import list_services
from paasta_tools.utils import load_deployments_json
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import paasta_print
from paasta_tools.utils import PaastaColors
from paasta_tools.utils import SystemPaastaConfig
HTTP_ONLY_INSTANCE_CONFIG: Sequence[Type[InstanceConfig]] = [
FlinkClusterConfig,
KubernetesDeploymentConfig,
]
SSH_ONLY_INSTANCE_CONFIG = [
ChronosJobConfig,
AdhocJobConfig,
]
def add_subparser(
subparsers,
) -> None:
status_parser = subparsers.add_parser(
'status',
help="Display the status of a PaaSTA service.",
description=(
"'paasta status' works by SSH'ing to remote PaaSTA masters and "
"inspecting the local APIs, and reports on the overal health "
"of a service."
),
epilog=(
"Note: This command requires SSH and sudo privileges on the remote PaaSTA "
"masters."
),
)
status_parser.add_argument(
'-v', '--verbose',
action='count',
dest="verbose",
default=0,
help="Print out more output regarding the state of the service. "
"A second -v will also print the stdout/stderr tail.",
)
status_parser.add_argument(
'-d', '--soa-dir',
dest="soa_dir",
metavar="SOA_DIR",
default=DEFAULT_SOA_DIR,
help="define a different soa config directory",
)
add_instance_filter_arguments(status_parser)
status_parser.set_defaults(command=paasta_status)
def add_instance_filter_arguments(
status_parser,
verb: str = 'inspect',
) -> None:
status_parser.add_argument(
'-s', '--service',
help=f'The name of the service you wish to {verb}',
).completer = lazy_choices_completer(list_services)
status_parser.add_argument(
'-c', '--clusters',
help=f"A comma-separated list of clusters to {verb}. By default, will {verb} all clusters.\n"
f"For example: --clusters norcal-prod,nova-prod",
).completer = lazy_choices_completer(list_clusters)
status_parser.add_argument(
'-i', '--instances',
help=f"A comma-separated list of instances to {verb}. By default, will {verb} all instances.\n"
f"For example: --instances canary,main",
) # No completer because we need to know service first and we can't until some other stuff has happened
status_parser.add_argument(
'-l', '--deploy-group',
help=(
f'Name of the deploy group which you want to {verb}. '
f'If specified together with --instances and/or --clusters, will {verb} common instances only.'
),
).completer = lazy_choices_completer(list_deploy_groups)
status_parser.add_argument(
'-o', '--owner',
help=f'Only {verb} instances with this owner specified in soa-configs.',
).completer = lazy_choices_completer(list_teams)
status_parser.add_argument(
'-r', '--registration',
help=f'Only {verb} instances with this registration.',
)
def missing_deployments_message(
service: str,
) -> str:
message = (
f"{service} has no deployments in deployments.json yet.\n "
"Has Jenkins run?"
)
return message
def get_deploy_info(
deploy_file_path: str,
) -> Mapping:
deploy_info = read_deploy(deploy_file_path)
if not deploy_info:
paasta_print('Error encountered with %s' % deploy_file_path)
exit(1)
return deploy_info
def get_planned_deployments(
service: str,
soa_dir: str,
) -> Iterable[str]:
for cluster, cluster_deploy_file in get_soa_cluster_deploy_files(
service=service,
soa_dir=soa_dir,
):
for instance in get_deploy_info(cluster_deploy_file):
yield f'{cluster}.{instance}'
def list_deployed_clusters(
pipeline: Sequence[str],
actual_deployments: Sequence[str],
) -> Sequence[str]:
"""Returns a list of clusters that a service is deployed to given
an input deploy pipeline and the actual deployments"""
deployed_clusters: List[str] = []
for namespace in pipeline:
cluster, instance = namespace.split('.')
if namespace in actual_deployments:
if cluster not in deployed_clusters:
deployed_clusters.append(cluster)
return deployed_clusters
def get_actual_deployments(
service: str,
soa_dir: str,
) -> Mapping[str, str]:
deployments_json = load_deployments_json(service, soa_dir)
if not deployments_json:
paasta_print("Warning: it looks like %s has not been deployed anywhere yet!" % service, file=sys.stderr)
# Create a dictionary of actual $service Jenkins deployments
actual_deployments = {}
for key, branch_dict in deployments_json.config_dict.items():
service, namespace = key.split(':')
if service == service:
value = branch_dict['docker_image']
sha = value[value.rfind('-') + 1:]
actual_deployments[namespace.replace('paasta-', '', 1)] = sha
return actual_deployments
def paasta_status_on_api_endpoint(
cluster: str,
service: str,
instance: str,
output: List[str],
system_paasta_config: SystemPaastaConfig,
verbose: int,
) -> int:
client = get_paasta_api_client(cluster, system_paasta_config)
if not client:
paasta_print('Cannot get a paasta-api client')
exit(1)
try:
status = client.service.status_instance(service=service, instance=instance).result()
except HTTPError as exc:
paasta_print(exc.response.text)
return exc.status_code
output.append(' instance: %s' % PaastaColors.blue(instance))
if status.git_sha != '':
output.append(' Git sha: %s (desired)' % status.git_sha)
if status.marathon is not None:
return print_marathon_status(service, instance, output, status.marathon)
elif status.kubernetes is not None:
return print_kubernetes_status(service, instance, output, status.kubernetes)
elif status.tron is not None:
return print_tron_status(service, instance, output, status.tron, verbose)
elif status.flinkcluster is not None:
return print_flinkcluster_status(cluster, service, instance, output, status.flinkcluster.get('status'), verbose)
else:
paasta_print("Not implemented: Looks like %s is not a Marathon or Kubernetes instance" % instance)
return 0
def print_marathon_status(
service: str,
instance: str,
output: List[str],
marathon_status,
) -> int:
if marathon_status.error_message:
output.append(marathon_status.error_message)
return 1
bouncing_status = bouncing_status_human(
marathon_status.app_count,
marathon_status.bounce_method,
)
desired_state = desired_state_human(
marathon_status.desired_state,
marathon_status.expected_instance_count,
)
output.append(f" State: {bouncing_status} - Desired state: {desired_state}")
status = MarathonDeployStatus.fromstring(marathon_status.deploy_status)
if status != MarathonDeployStatus.NotRunning:
if status == MarathonDeployStatus.Delayed:
deploy_status = marathon_app_deploy_status_human(status, marathon_status.backoff_seconds)
else:
deploy_status = marathon_app_deploy_status_human(status)
else:
deploy_status = 'NotRunning'
output.append(
" {}".format(
status_marathon_job_human(
service=service,
instance=instance,
deploy_status=deploy_status,
desired_app_id=marathon_status.app_id,
app_count=marathon_status.app_count,
running_instances=marathon_status.running_instance_count,
normal_instance_count=marathon_status.expected_instance_count,
),
),
)
return 0
def kubernetes_app_deploy_status_human(status, backoff_seconds=None):
status_string = kubernetes_tools.KubernetesDeployStatus.tostring(status)
if status == kubernetes_tools.KubernetesDeployStatus.Waiting:
deploy_status = "%s (new tasks waiting for capacity to become available)" % PaastaColors.red(status_string)
elif status == kubernetes_tools.KubernetesDeployStatus.Deploying:
deploy_status = PaastaColors.yellow(status_string)
elif status == kubernetes_tools.KubernetesDeployStatus.Running:
deploy_status = PaastaColors.bold(status_string)
else:
deploy_status = status_string
return deploy_status
def status_kubernetes_job_human(
service: str,
instance: str,
deploy_status: str,
desired_app_id: str,
app_count: int,
running_instances: int,
normal_instance_count: int,
) -> str:
name = PaastaColors.cyan(compose_job_id(service, instance))
if app_count >= 0:
if running_instances >= normal_instance_count:
status = PaastaColors.green("Healthy")
instance_count = PaastaColors.green("(%d/%d)" % (running_instances, normal_instance_count))
elif running_instances == 0:
status = PaastaColors.yellow("Critical")
instance_count = PaastaColors.red("(%d/%d)" % (running_instances, normal_instance_count))
else:
status = PaastaColors.yellow("Warning")
instance_count = PaastaColors.yellow("(%d/%d)" % (running_instances, normal_instance_count))
return "Kubernetes: {} - up with {} instances. Status: {}".format(
status, instance_count, deploy_status,
)
else:
status = PaastaColors.yellow("Warning")
return "Kubernetes: {} - {} (app {}) is not configured in Kubernetes yet (waiting for bounce)".format(
status, name, desired_app_id,
)
def print_flinkcluster_status(
cluster: str,
service: str,
instance: str,
output: List[str],
status,
verbose: int,
) -> int:
if status is None:
output.append(PaastaColors.red(" Flink cluster is not available yet"))
return 1
if status.state != "running":
output.append(" State: {state}".format(
state=PaastaColors.yellow(status.state),
))
output.append(f" No other information available in non-running state")
return 0
dashboard_url = get_dashboard_url(
cluster=cluster,
service=service,
instance=instance,
)
if verbose:
output.append(f" Flink version: {status.config['flink-version']} {status.config['flink-revision']}")
else:
output.append(f" Flink version: {status.config['flink-version']}")
output.append(f" URL: {dashboard_url}/")
output.append(f" State: {status.state}")
output.append(
" Jobs:"
f" {status.overview['jobs-running']} running,"
f" {status.overview['jobs-finished']} finished,"
f" {status.overview['jobs-failed']} failed,"
f" {status.overview['jobs-cancelled']} cancelled",
)
output.append(
" "
f" {status.overview['taskmanagers']} taskmanagers,"
f" {status.overview['slots-available']}/{status.overview['slots-total']} slots available",
)
output.append(f" Jobs:")
if verbose:
output.append(f" Job Name State Job ID Started")
else:
output.append(f" Job Name State Started")
# Use only the most recent jobs
unique_jobs = (
sorted(jobs, key=lambda j: -j['start-time'])[0]
for _, jobs in groupby(
sorted(status.jobs, key=lambda j: j['name']),
lambda j: j['name'],
)
)
for job in unique_jobs:
job_id = job['jid']
if verbose:
fmt = """ {job_name: <32.32} {state: <11} {job_id} {start_time}
{dashboard_url}"""
else:
fmt = " {job_name: <32.32} {state: <11} {start_time}"
start_time = datetime_from_utc_to_local(datetime.utcfromtimestamp(int(job['start-time']) // 1000))
output.append(fmt.format(
job_id=job_id,
job_name=job['name'].split('.', 2)[2],
state=job['state'],
start_time=f'{str(start_time)} ({humanize.naturaltime(start_time)})',
dashboard_url=PaastaColors.grey(
f'{dashboard_url}/#/jobs/{job_id}',
),
))
if job_id in status.exceptions:
exceptions = status.exceptions[job_id]
root_exception = exceptions['root-exception']
if root_exception is not None:
output.append(f" Exception: {root_exception}")
ts = exceptions['timestamp']
if ts is not None:
exc_ts = datetime_from_utc_to_local(datetime.utcfromtimestamp(int(ts) // 1000))
output.append(f" {str(exc_ts)} ({humanize.naturaltime(exc_ts)})")
return 0
def print_kubernetes_status(
service: str,
instance: str,
output: List[str],
kubernetes_status,
) -> int:
if kubernetes_status.error_message:
output.append(kubernetes_status.error_message)
return 1
bouncing_status = bouncing_status_human(
kubernetes_status.app_count,
kubernetes_status.bounce_method,
)
desired_state = desired_state_human(
kubernetes_status.desired_state,
kubernetes_status.expected_instance_count,
)
output.append(f" State: {bouncing_status} - Desired state: {desired_state}")
status = KubernetesDeployStatus.fromstring(kubernetes_status.deploy_status)
deploy_status = kubernetes_app_deploy_status_human(status)
output.append(
" {}".format(
status_kubernetes_job_human(
service=service,
instance=instance,
deploy_status=deploy_status,
desired_app_id=kubernetes_status.app_id,
app_count=kubernetes_status.app_count,
running_instances=kubernetes_status.running_instance_count,
normal_instance_count=kubernetes_status.expected_instance_count,
),
),
)
return 0
def print_tron_status(
service: str,
instance: str,
output: List[str],
tron_status,
verbose: int = 0,
) -> int:
output.append(f" Tron job: {tron_status.job_name}")
if verbose:
output.append(f" Status: {tron_status.job_status}")
output.append(f" Schedule: {tron_status.job_schedule}")
output.append(" Dashboard: {}".format(PaastaColors.blue(tron_status.job_url)))
output.append(f" Action: {tron_status.action_name}")
output.append(f" Status: {tron_status.action_state}")
if verbose:
output.append(f" Start time: {tron_status.action_start_time}")
output.append(f" Command: {tron_status.action_command}")
if verbose > 1:
output.append(f" Raw Command: {tron_status.action_raw_command}")
output.append(f" Stdout: \n{tron_status.action_stdout}")
output.append(f" Stderr: \n{tron_status.action_stderr}")
return 0
def report_status_for_cluster(
service: str,
cluster: str,
deploy_pipeline: Sequence[str],
actual_deployments: Mapping[str, str],
instance_whitelist: Mapping[str, Type[InstanceConfig]],
system_paasta_config: SystemPaastaConfig,
verbose: int = 0,
use_api_endpoint: bool = False,
) -> Tuple[int, Sequence[str]]:
"""With a given service and cluster, prints the status of the instances
in that cluster"""
output = ['', 'service: %s' % service, 'cluster: %s' % cluster]
seen_instances = []
deployed_instances = []
instances = instance_whitelist.keys()
http_only_instances = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
in HTTP_ONLY_INSTANCE_CONFIG
]
ssh_only_instances = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
in SSH_ONLY_INSTANCE_CONFIG
]
tron_jobs = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
== TronActionConfig
]
for namespace in deploy_pipeline:
cluster_in_pipeline, instance = namespace.split('.')
seen_instances.append(instance)
if cluster_in_pipeline != cluster:
continue
if instances and instance not in instances:
continue
# Case: service deployed to cluster.instance
if namespace in actual_deployments:
deployed_instances.append(instance)
# Case: flinkcluster instances don't use `deployments.json`
elif instance_whitelist.get(instance) == FlinkClusterConfig:
deployed_instances.append(instance)
# Case: service NOT deployed to cluster.instance
else:
output.append(' instance: %s' % PaastaColors.red(instance))
output.append(' Git sha: None (not deployed yet)')
api_return_code = 0
ssh_return_code = 0
if len(deployed_instances) > 0:
http_only_deployed_instances = [
deployed_instance
for deployed_instance in deployed_instances
if (
deployed_instance in http_only_instances
or deployed_instance not in ssh_only_instances and use_api_endpoint
)
]
if len(http_only_deployed_instances):
return_codes = [
paasta_status_on_api_endpoint(
cluster=cluster,
service=service,
instance=deployed_instance,
output=output,
system_paasta_config=system_paasta_config,
verbose=verbose,
)
for deployed_instance in http_only_deployed_instances
]
if any(return_codes):
api_return_code = 1
ssh_only_deployed_instances = [
deployed_instance
for deployed_instance in deployed_instances
if (
deployed_instance in ssh_only_instances
or deployed_instance not in http_only_instances and not use_api_endpoint
)
]
if len(ssh_only_deployed_instances):
ssh_return_code, status = execute_paasta_serviceinit_on_remote_master(
'status', cluster, service, ','.join(
deployed_instance
for deployed_instance in ssh_only_deployed_instances
),
system_paasta_config, stream=False, verbose=verbose,
ignore_ssh_output=True,
)
# Status results are streamed. This print is for possible error messages.
if status is not None:
for line in status.rstrip().split('\n'):
output.append(' %s' % line)
if len(tron_jobs) > 0:
return_codes = [
paasta_status_on_api_endpoint(
cluster=cluster,
service=service,
instance=tron_job,
output=output,
system_paasta_config=system_paasta_config,
verbose=verbose,
)
for tron_job in tron_jobs
]
seen_instances.extend(tron_jobs)
output.append(report_invalid_whitelist_values(instances, seen_instances, 'instance'))
if ssh_return_code:
return_code = ssh_return_code
elif api_return_code:
return_code = api_return_code
else:
return_code = 0
return return_code, output
def report_invalid_whitelist_values(
whitelist: Iterable[str],
items: Sequence[str],
item_type: str,
) -> str:
"""Warns the user if there are entries in ``whitelist`` which don't
correspond to any item in ``items``. Helps highlight typos.
"""
return_string = ""
bogus_entries = []
if whitelist is None:
return ''
for entry in whitelist:
if entry not in items:
bogus_entries.append(entry)
if len(bogus_entries) > 0:
return_string = (
"\n"
"Warning: This service does not have any %s matching these names:\n%s"
) % (item_type, ",".join(bogus_entries))
return return_string
def verify_instances(
args_instances: str,
service: str,
clusters: Sequence[str],
) -> Sequence[str]:
"""Verify that a list of instances specified by user is correct for this service.
:param args_instances: a list of instances.
:param service: the service name
:param cluster: a list of clusters
:returns: a list of instances specified in args_instances without any exclusions.
"""
unverified_instances = args_instances.split(",")
service_instances: Set[str] = list_all_instances_for_service(service, clusters=clusters)
misspelled_instances: Sequence[str] = [i for i in unverified_instances if i not in service_instances]
if misspelled_instances:
suggestions: List[str] = []
for instance in misspelled_instances:
suggestions.extend(difflib.get_close_matches(instance, service_instances, n=5, cutoff=0.5)) # type: ignore
suggestions = list(set(suggestions))
if clusters:
message = (
"%s doesn't have any instances matching %s on %s."
% (
service,
', '.join(sorted(misspelled_instances)),
', '.join(sorted(clusters)),
)
)
else:
message = ("%s doesn't have any instances matching %s."
% (service, ', '.join(sorted(misspelled_instances))))
paasta_print(PaastaColors.red(message))
if suggestions:
paasta_print("Did you mean any of these?")
for instance in sorted(suggestions):
paasta_print(" %s" % instance)
return unverified_instances
def normalize_registrations(
service: str,
registrations: Sequence[str],
) -> Sequence[str]:
ret = []
for reg in registrations:
if '.' not in reg:
ret.append(f"{service}.{reg}")
else:
ret.append(reg)
return ret
def get_filters(
args,
) -> Sequence[Callable[[InstanceConfig], bool]]:
"""Figures out which filters to apply from an args object, and returns them
:param args: args object
:returns: list of functions that take an instance config and returns if the instance conf matches the filter
"""
filters = []
if args.service:
filters.append(lambda conf: conf.get_service() in args.service.split(','))
if args.clusters:
filters.append(lambda conf: conf.get_cluster() in args.clusters.split(','))
if args.instances:
filters.append(lambda conf: conf.get_instance() in args.instances.split(','))
if args.deploy_group:
filters.append(lambda conf: conf.get_deploy_group() in args.deploy_group.split(','))
if args.registration:
normalized_regs = normalize_registrations(
service=args.service,
registrations=args.registration.split(','),
)
filters.append(
lambda conf: any(
reg in normalized_regs
for reg in (conf.get_registrations() if hasattr(conf, 'get_registrations') else [])
),
)
if args.owner:
owners = args.owner.split(',')
filters.append(
# If the instance owner is None, check the service owner, else check the instance owner
lambda conf: get_team(
overrides={},
service=conf.get_service(),
soa_dir=args.soa_dir,
) in owners if conf.get_team() is None else conf.get_team() in owners,
)
return filters
def apply_args_filters(
args,
) -> Mapping[str, Mapping[str, Mapping[str, Type[InstanceConfig]]]]:
"""
Take an args object and returns the dict of cluster:service:instances
Currently, will filter by clusters, instances, services, and deploy_groups
If no instances are found, will print a message and try to find matching instances
for each service
:param args: args object containing attributes to filter by
:returns: Dict of dicts, in format {cluster_name: {service_name: {instance1, instance2}}}
"""
clusters_services_instances: DefaultDict[
str,
DefaultDict[
str, Dict[str, Type[InstanceConfig]]
]
] = defaultdict(lambda: defaultdict(dict))
if args.service is None and args.owner is None:
args.service = figure_out_service_name(args, soa_dir=args.soa_dir)
filters = get_filters(args)
all_services = list_services(soa_dir=args.soa_dir)
if args.service and args.service not in all_services:
paasta_print(PaastaColors.red(f'The service "{args.service}" does not exist.'))
suggestions = difflib.get_close_matches(args.service, all_services, n=5, cutoff=0.5)
if suggestions:
paasta_print(PaastaColors.red(f'Did you mean any of these?'))
for suggestion in suggestions:
paasta_print(PaastaColors.red(f' {suggestion}'))
return clusters_services_instances
i_count = 0
for service in all_services:
if args.service and service != args.service:
continue
for instance_conf in get_instance_configs_for_service(service, soa_dir=args.soa_dir):
if all([f(instance_conf) for f in filters]):
cluster_service = clusters_services_instances[instance_conf.get_cluster()][service]
cluster_service[instance_conf.get_instance()] = instance_conf.__class__
i_count += 1
if i_count == 0 and args.service and args.instances:
if args.clusters:
clusters = args.clusters.split(',')
else:
clusters = list_clusters()
for service in args.service.split(','):
verify_instances(args.instances, service, clusters)
return clusters_services_instances
def paasta_status(
args,
) -> int:
"""Print the status of a Yelp service running on PaaSTA.
:param args: argparse.Namespace obj created from sys.args by cli"""
soa_dir = args.soa_dir
system_paasta_config = load_system_paasta_config()
if 'USE_API_ENDPOINT' in os.environ:
use_api_endpoint = strtobool(os.environ['USE_API_ENDPOINT'])
else:
use_api_endpoint = False
return_codes = [0]
tasks = []
clusters_services_instances = apply_args_filters(args)
for cluster, service_instances in clusters_services_instances.items():
for service, instances in service_instances.items():
all_flink = all(i == FlinkClusterConfig for i in instances.values())
actual_deployments: Mapping[str, str]
if all_flink:
actual_deployments = {}
else:
actual_deployments = get_actual_deployments(service, soa_dir)
if all_flink or actual_deployments:
deploy_pipeline = list(get_planned_deployments(service, soa_dir))
tasks.append((
report_status_for_cluster, dict(
service=service,
cluster=cluster,
deploy_pipeline=deploy_pipeline,
actual_deployments=actual_deployments,
instance_whitelist=instances,
system_paasta_config=system_paasta_config,
verbose=args.verbose,
use_api_endpoint=use_api_endpoint,
),
))
else:
paasta_print(missing_deployments_message(service))
return_codes.append(1)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
tasks = [executor.submit(t[0], **t[1]) for t in tasks] # type: ignore
for future in concurrent.futures.as_completed(tasks): # type: ignore
return_code, output = future.result()
paasta_print('\n'.join(output))
return_codes.append(return_code)
return max(return_codes)
| 36.532014 | 120 | 0.653835 |
import concurrent.futures
import difflib
import os
import sys
from collections import defaultdict
from datetime import datetime
from distutils.util import strtobool
from itertools import groupby
from typing import Callable
from typing import DefaultDict
from typing import Dict
from typing import Iterable
from typing import List
from typing import Mapping
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
import humanize
from bravado.exception import HTTPError
from service_configuration_lib import read_deploy
from paasta_tools import kubernetes_tools
from paasta_tools.adhoc_tools import AdhocJobConfig
from paasta_tools.api.client import get_paasta_api_client
from paasta_tools.chronos_tools import ChronosJobConfig
from paasta_tools.cli.utils import execute_paasta_serviceinit_on_remote_master
from paasta_tools.cli.utils import figure_out_service_name
from paasta_tools.cli.utils import get_instance_configs_for_service
from paasta_tools.cli.utils import lazy_choices_completer
from paasta_tools.cli.utils import list_deploy_groups
from paasta_tools.flinkcluster_tools import FlinkClusterConfig
from paasta_tools.flinkcluster_tools import get_dashboard_url
from paasta_tools.kubernetes_tools import KubernetesDeploymentConfig
from paasta_tools.kubernetes_tools import KubernetesDeployStatus
from paasta_tools.marathon_serviceinit import bouncing_status_human
from paasta_tools.marathon_serviceinit import desired_state_human
from paasta_tools.marathon_serviceinit import marathon_app_deploy_status_human
from paasta_tools.marathon_serviceinit import status_marathon_job_human
from paasta_tools.marathon_tools import MarathonDeployStatus
from paasta_tools.monitoring_tools import get_team
from paasta_tools.monitoring_tools import list_teams
from paasta_tools.tron_tools import TronActionConfig
from paasta_tools.utils import compose_job_id
from paasta_tools.utils import datetime_from_utc_to_local
from paasta_tools.utils import DEFAULT_SOA_DIR
from paasta_tools.utils import get_soa_cluster_deploy_files
from paasta_tools.utils import InstanceConfig
from paasta_tools.utils import list_all_instances_for_service
from paasta_tools.utils import list_clusters
from paasta_tools.utils import list_services
from paasta_tools.utils import load_deployments_json
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import paasta_print
from paasta_tools.utils import PaastaColors
from paasta_tools.utils import SystemPaastaConfig
HTTP_ONLY_INSTANCE_CONFIG: Sequence[Type[InstanceConfig]] = [
FlinkClusterConfig,
KubernetesDeploymentConfig,
]
SSH_ONLY_INSTANCE_CONFIG = [
ChronosJobConfig,
AdhocJobConfig,
]
def add_subparser(
subparsers,
) -> None:
status_parser = subparsers.add_parser(
'status',
help="Display the status of a PaaSTA service.",
description=(
"'paasta status' works by SSH'ing to remote PaaSTA masters and "
"inspecting the local APIs, and reports on the overal health "
"of a service."
),
epilog=(
"Note: This command requires SSH and sudo privileges on the remote PaaSTA "
"masters."
),
)
status_parser.add_argument(
'-v', '--verbose',
action='count',
dest="verbose",
default=0,
help="Print out more output regarding the state of the service. "
"A second -v will also print the stdout/stderr tail.",
)
status_parser.add_argument(
'-d', '--soa-dir',
dest="soa_dir",
metavar="SOA_DIR",
default=DEFAULT_SOA_DIR,
help="define a different soa config directory",
)
add_instance_filter_arguments(status_parser)
status_parser.set_defaults(command=paasta_status)
def add_instance_filter_arguments(
status_parser,
verb: str = 'inspect',
) -> None:
status_parser.add_argument(
'-s', '--service',
help=f'The name of the service you wish to {verb}',
).completer = lazy_choices_completer(list_services)
status_parser.add_argument(
'-c', '--clusters',
help=f"A comma-separated list of clusters to {verb}. By default, will {verb} all clusters.\n"
f"For example: --clusters norcal-prod,nova-prod",
).completer = lazy_choices_completer(list_clusters)
status_parser.add_argument(
'-i', '--instances',
help=f"A comma-separated list of instances to {verb}. By default, will {verb} all instances.\n"
f"For example: --instances canary,main",
) # No completer because we need to know service first and we can't until some other stuff has happened
status_parser.add_argument(
'-l', '--deploy-group',
help=(
f'Name of the deploy group which you want to {verb}. '
f'If specified together with --instances and/or --clusters, will {verb} common instances only.'
),
).completer = lazy_choices_completer(list_deploy_groups)
status_parser.add_argument(
'-o', '--owner',
help=f'Only {verb} instances with this owner specified in soa-configs.',
).completer = lazy_choices_completer(list_teams)
status_parser.add_argument(
'-r', '--registration',
help=f'Only {verb} instances with this registration.',
)
def missing_deployments_message(
service: str,
) -> str:
message = (
f"{service} has no deployments in deployments.json yet.\n "
"Has Jenkins run?"
)
return message
def get_deploy_info(
deploy_file_path: str,
) -> Mapping:
deploy_info = read_deploy(deploy_file_path)
if not deploy_info:
paasta_print('Error encountered with %s' % deploy_file_path)
exit(1)
return deploy_info
def get_planned_deployments(
service: str,
soa_dir: str,
) -> Iterable[str]:
for cluster, cluster_deploy_file in get_soa_cluster_deploy_files(
service=service,
soa_dir=soa_dir,
):
for instance in get_deploy_info(cluster_deploy_file):
yield f'{cluster}.{instance}'
def list_deployed_clusters(
pipeline: Sequence[str],
actual_deployments: Sequence[str],
) -> Sequence[str]:
deployed_clusters: List[str] = []
for namespace in pipeline:
cluster, instance = namespace.split('.')
if namespace in actual_deployments:
if cluster not in deployed_clusters:
deployed_clusters.append(cluster)
return deployed_clusters
def get_actual_deployments(
service: str,
soa_dir: str,
) -> Mapping[str, str]:
deployments_json = load_deployments_json(service, soa_dir)
if not deployments_json:
paasta_print("Warning: it looks like %s has not been deployed anywhere yet!" % service, file=sys.stderr)
actual_deployments = {}
for key, branch_dict in deployments_json.config_dict.items():
service, namespace = key.split(':')
if service == service:
value = branch_dict['docker_image']
sha = value[value.rfind('-') + 1:]
actual_deployments[namespace.replace('paasta-', '', 1)] = sha
return actual_deployments
def paasta_status_on_api_endpoint(
cluster: str,
service: str,
instance: str,
output: List[str],
system_paasta_config: SystemPaastaConfig,
verbose: int,
) -> int:
client = get_paasta_api_client(cluster, system_paasta_config)
if not client:
paasta_print('Cannot get a paasta-api client')
exit(1)
try:
status = client.service.status_instance(service=service, instance=instance).result()
except HTTPError as exc:
paasta_print(exc.response.text)
return exc.status_code
output.append(' instance: %s' % PaastaColors.blue(instance))
if status.git_sha != '':
output.append(' Git sha: %s (desired)' % status.git_sha)
if status.marathon is not None:
return print_marathon_status(service, instance, output, status.marathon)
elif status.kubernetes is not None:
return print_kubernetes_status(service, instance, output, status.kubernetes)
elif status.tron is not None:
return print_tron_status(service, instance, output, status.tron, verbose)
elif status.flinkcluster is not None:
return print_flinkcluster_status(cluster, service, instance, output, status.flinkcluster.get('status'), verbose)
else:
paasta_print("Not implemented: Looks like %s is not a Marathon or Kubernetes instance" % instance)
return 0
def print_marathon_status(
service: str,
instance: str,
output: List[str],
marathon_status,
) -> int:
if marathon_status.error_message:
output.append(marathon_status.error_message)
return 1
bouncing_status = bouncing_status_human(
marathon_status.app_count,
marathon_status.bounce_method,
)
desired_state = desired_state_human(
marathon_status.desired_state,
marathon_status.expected_instance_count,
)
output.append(f" State: {bouncing_status} - Desired state: {desired_state}")
status = MarathonDeployStatus.fromstring(marathon_status.deploy_status)
if status != MarathonDeployStatus.NotRunning:
if status == MarathonDeployStatus.Delayed:
deploy_status = marathon_app_deploy_status_human(status, marathon_status.backoff_seconds)
else:
deploy_status = marathon_app_deploy_status_human(status)
else:
deploy_status = 'NotRunning'
output.append(
" {}".format(
status_marathon_job_human(
service=service,
instance=instance,
deploy_status=deploy_status,
desired_app_id=marathon_status.app_id,
app_count=marathon_status.app_count,
running_instances=marathon_status.running_instance_count,
normal_instance_count=marathon_status.expected_instance_count,
),
),
)
return 0
def kubernetes_app_deploy_status_human(status, backoff_seconds=None):
status_string = kubernetes_tools.KubernetesDeployStatus.tostring(status)
if status == kubernetes_tools.KubernetesDeployStatus.Waiting:
deploy_status = "%s (new tasks waiting for capacity to become available)" % PaastaColors.red(status_string)
elif status == kubernetes_tools.KubernetesDeployStatus.Deploying:
deploy_status = PaastaColors.yellow(status_string)
elif status == kubernetes_tools.KubernetesDeployStatus.Running:
deploy_status = PaastaColors.bold(status_string)
else:
deploy_status = status_string
return deploy_status
def status_kubernetes_job_human(
service: str,
instance: str,
deploy_status: str,
desired_app_id: str,
app_count: int,
running_instances: int,
normal_instance_count: int,
) -> str:
name = PaastaColors.cyan(compose_job_id(service, instance))
if app_count >= 0:
if running_instances >= normal_instance_count:
status = PaastaColors.green("Healthy")
instance_count = PaastaColors.green("(%d/%d)" % (running_instances, normal_instance_count))
elif running_instances == 0:
status = PaastaColors.yellow("Critical")
instance_count = PaastaColors.red("(%d/%d)" % (running_instances, normal_instance_count))
else:
status = PaastaColors.yellow("Warning")
instance_count = PaastaColors.yellow("(%d/%d)" % (running_instances, normal_instance_count))
return "Kubernetes: {} - up with {} instances. Status: {}".format(
status, instance_count, deploy_status,
)
else:
status = PaastaColors.yellow("Warning")
return "Kubernetes: {} - {} (app {}) is not configured in Kubernetes yet (waiting for bounce)".format(
status, name, desired_app_id,
)
def print_flinkcluster_status(
cluster: str,
service: str,
instance: str,
output: List[str],
status,
verbose: int,
) -> int:
if status is None:
output.append(PaastaColors.red(" Flink cluster is not available yet"))
return 1
if status.state != "running":
output.append(" State: {state}".format(
state=PaastaColors.yellow(status.state),
))
output.append(f" No other information available in non-running state")
return 0
dashboard_url = get_dashboard_url(
cluster=cluster,
service=service,
instance=instance,
)
if verbose:
output.append(f" Flink version: {status.config['flink-version']} {status.config['flink-revision']}")
else:
output.append(f" Flink version: {status.config['flink-version']}")
output.append(f" URL: {dashboard_url}/")
output.append(f" State: {status.state}")
output.append(
" Jobs:"
f" {status.overview['jobs-running']} running,"
f" {status.overview['jobs-finished']} finished,"
f" {status.overview['jobs-failed']} failed,"
f" {status.overview['jobs-cancelled']} cancelled",
)
output.append(
" "
f" {status.overview['taskmanagers']} taskmanagers,"
f" {status.overview['slots-available']}/{status.overview['slots-total']} slots available",
)
output.append(f" Jobs:")
if verbose:
output.append(f" Job Name State Job ID Started")
else:
output.append(f" Job Name State Started")
unique_jobs = (
sorted(jobs, key=lambda j: -j['start-time'])[0]
for _, jobs in groupby(
sorted(status.jobs, key=lambda j: j['name']),
lambda j: j['name'],
)
)
for job in unique_jobs:
job_id = job['jid']
if verbose:
fmt = """ {job_name: <32.32} {state: <11} {job_id} {start_time}
{dashboard_url}"""
else:
fmt = " {job_name: <32.32} {state: <11} {start_time}"
start_time = datetime_from_utc_to_local(datetime.utcfromtimestamp(int(job['start-time']) // 1000))
output.append(fmt.format(
job_id=job_id,
job_name=job['name'].split('.', 2)[2],
state=job['state'],
start_time=f'{str(start_time)} ({humanize.naturaltime(start_time)})',
dashboard_url=PaastaColors.grey(
f'{dashboard_url}/#/jobs/{job_id}',
),
))
if job_id in status.exceptions:
exceptions = status.exceptions[job_id]
root_exception = exceptions['root-exception']
if root_exception is not None:
output.append(f" Exception: {root_exception}")
ts = exceptions['timestamp']
if ts is not None:
exc_ts = datetime_from_utc_to_local(datetime.utcfromtimestamp(int(ts) // 1000))
output.append(f" {str(exc_ts)} ({humanize.naturaltime(exc_ts)})")
return 0
def print_kubernetes_status(
service: str,
instance: str,
output: List[str],
kubernetes_status,
) -> int:
if kubernetes_status.error_message:
output.append(kubernetes_status.error_message)
return 1
bouncing_status = bouncing_status_human(
kubernetes_status.app_count,
kubernetes_status.bounce_method,
)
desired_state = desired_state_human(
kubernetes_status.desired_state,
kubernetes_status.expected_instance_count,
)
output.append(f" State: {bouncing_status} - Desired state: {desired_state}")
status = KubernetesDeployStatus.fromstring(kubernetes_status.deploy_status)
deploy_status = kubernetes_app_deploy_status_human(status)
output.append(
" {}".format(
status_kubernetes_job_human(
service=service,
instance=instance,
deploy_status=deploy_status,
desired_app_id=kubernetes_status.app_id,
app_count=kubernetes_status.app_count,
running_instances=kubernetes_status.running_instance_count,
normal_instance_count=kubernetes_status.expected_instance_count,
),
),
)
return 0
def print_tron_status(
service: str,
instance: str,
output: List[str],
tron_status,
verbose: int = 0,
) -> int:
output.append(f" Tron job: {tron_status.job_name}")
if verbose:
output.append(f" Status: {tron_status.job_status}")
output.append(f" Schedule: {tron_status.job_schedule}")
output.append(" Dashboard: {}".format(PaastaColors.blue(tron_status.job_url)))
output.append(f" Action: {tron_status.action_name}")
output.append(f" Status: {tron_status.action_state}")
if verbose:
output.append(f" Start time: {tron_status.action_start_time}")
output.append(f" Command: {tron_status.action_command}")
if verbose > 1:
output.append(f" Raw Command: {tron_status.action_raw_command}")
output.append(f" Stdout: \n{tron_status.action_stdout}")
output.append(f" Stderr: \n{tron_status.action_stderr}")
return 0
def report_status_for_cluster(
service: str,
cluster: str,
deploy_pipeline: Sequence[str],
actual_deployments: Mapping[str, str],
instance_whitelist: Mapping[str, Type[InstanceConfig]],
system_paasta_config: SystemPaastaConfig,
verbose: int = 0,
use_api_endpoint: bool = False,
) -> Tuple[int, Sequence[str]]:
output = ['', 'service: %s' % service, 'cluster: %s' % cluster]
seen_instances = []
deployed_instances = []
instances = instance_whitelist.keys()
http_only_instances = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
in HTTP_ONLY_INSTANCE_CONFIG
]
ssh_only_instances = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
in SSH_ONLY_INSTANCE_CONFIG
]
tron_jobs = [
instance for instance, instance_config_class in instance_whitelist.items() if instance_config_class
== TronActionConfig
]
for namespace in deploy_pipeline:
cluster_in_pipeline, instance = namespace.split('.')
seen_instances.append(instance)
if cluster_in_pipeline != cluster:
continue
if instances and instance not in instances:
continue
if namespace in actual_deployments:
deployed_instances.append(instance)
elif instance_whitelist.get(instance) == FlinkClusterConfig:
deployed_instances.append(instance)
# Case: service NOT deployed to cluster.instance
else:
output.append(' instance: %s' % PaastaColors.red(instance))
output.append(' Git sha: None (not deployed yet)')
api_return_code = 0
ssh_return_code = 0
if len(deployed_instances) > 0:
http_only_deployed_instances = [
deployed_instance
for deployed_instance in deployed_instances
if (
deployed_instance in http_only_instances
or deployed_instance not in ssh_only_instances and use_api_endpoint
)
]
if len(http_only_deployed_instances):
return_codes = [
paasta_status_on_api_endpoint(
cluster=cluster,
service=service,
instance=deployed_instance,
output=output,
system_paasta_config=system_paasta_config,
verbose=verbose,
)
for deployed_instance in http_only_deployed_instances
]
if any(return_codes):
api_return_code = 1
ssh_only_deployed_instances = [
deployed_instance
for deployed_instance in deployed_instances
if (
deployed_instance in ssh_only_instances
or deployed_instance not in http_only_instances and not use_api_endpoint
)
]
if len(ssh_only_deployed_instances):
ssh_return_code, status = execute_paasta_serviceinit_on_remote_master(
'status', cluster, service, ','.join(
deployed_instance
for deployed_instance in ssh_only_deployed_instances
),
system_paasta_config, stream=False, verbose=verbose,
ignore_ssh_output=True,
)
# Status results are streamed. This print is for possible error messages.
if status is not None:
for line in status.rstrip().split('\n'):
output.append(' %s' % line)
if len(tron_jobs) > 0:
return_codes = [
paasta_status_on_api_endpoint(
cluster=cluster,
service=service,
instance=tron_job,
output=output,
system_paasta_config=system_paasta_config,
verbose=verbose,
)
for tron_job in tron_jobs
]
seen_instances.extend(tron_jobs)
output.append(report_invalid_whitelist_values(instances, seen_instances, 'instance'))
if ssh_return_code:
return_code = ssh_return_code
elif api_return_code:
return_code = api_return_code
else:
return_code = 0
return return_code, output
def report_invalid_whitelist_values(
whitelist: Iterable[str],
items: Sequence[str],
item_type: str,
) -> str:
return_string = ""
bogus_entries = []
if whitelist is None:
return ''
for entry in whitelist:
if entry not in items:
bogus_entries.append(entry)
if len(bogus_entries) > 0:
return_string = (
"\n"
"Warning: This service does not have any %s matching these names:\n%s"
) % (item_type, ",".join(bogus_entries))
return return_string
def verify_instances(
args_instances: str,
service: str,
clusters: Sequence[str],
) -> Sequence[str]:
unverified_instances = args_instances.split(",")
service_instances: Set[str] = list_all_instances_for_service(service, clusters=clusters)
misspelled_instances: Sequence[str] = [i for i in unverified_instances if i not in service_instances]
if misspelled_instances:
suggestions: List[str] = []
for instance in misspelled_instances:
suggestions.extend(difflib.get_close_matches(instance, service_instances, n=5, cutoff=0.5)) # type: ignore
suggestions = list(set(suggestions))
if clusters:
message = (
"%s doesn't have any instances matching %s on %s."
% (
service,
', '.join(sorted(misspelled_instances)),
', '.join(sorted(clusters)),
)
)
else:
message = ("%s doesn't have any instances matching %s."
% (service, ', '.join(sorted(misspelled_instances))))
paasta_print(PaastaColors.red(message))
if suggestions:
paasta_print("Did you mean any of these?")
for instance in sorted(suggestions):
paasta_print(" %s" % instance)
return unverified_instances
def normalize_registrations(
service: str,
registrations: Sequence[str],
) -> Sequence[str]:
ret = []
for reg in registrations:
if '.' not in reg:
ret.append(f"{service}.{reg}")
else:
ret.append(reg)
return ret
def get_filters(
args,
) -> Sequence[Callable[[InstanceConfig], bool]]:
filters = []
if args.service:
filters.append(lambda conf: conf.get_service() in args.service.split(','))
if args.clusters:
filters.append(lambda conf: conf.get_cluster() in args.clusters.split(','))
if args.instances:
filters.append(lambda conf: conf.get_instance() in args.instances.split(','))
if args.deploy_group:
filters.append(lambda conf: conf.get_deploy_group() in args.deploy_group.split(','))
if args.registration:
normalized_regs = normalize_registrations(
service=args.service,
registrations=args.registration.split(','),
)
filters.append(
lambda conf: any(
reg in normalized_regs
for reg in (conf.get_registrations() if hasattr(conf, 'get_registrations') else [])
),
)
if args.owner:
owners = args.owner.split(',')
filters.append(
# If the instance owner is None, check the service owner, else check the instance owner
lambda conf: get_team(
overrides={},
service=conf.get_service(),
soa_dir=args.soa_dir,
) in owners if conf.get_team() is None else conf.get_team() in owners,
)
return filters
def apply_args_filters(
args,
) -> Mapping[str, Mapping[str, Mapping[str, Type[InstanceConfig]]]]:
clusters_services_instances: DefaultDict[
str,
DefaultDict[
str, Dict[str, Type[InstanceConfig]]
]
] = defaultdict(lambda: defaultdict(dict))
if args.service is None and args.owner is None:
args.service = figure_out_service_name(args, soa_dir=args.soa_dir)
filters = get_filters(args)
all_services = list_services(soa_dir=args.soa_dir)
if args.service and args.service not in all_services:
paasta_print(PaastaColors.red(f'The service "{args.service}" does not exist.'))
suggestions = difflib.get_close_matches(args.service, all_services, n=5, cutoff=0.5)
if suggestions:
paasta_print(PaastaColors.red(f'Did you mean any of these?'))
for suggestion in suggestions:
paasta_print(PaastaColors.red(f' {suggestion}'))
return clusters_services_instances
i_count = 0
for service in all_services:
if args.service and service != args.service:
continue
for instance_conf in get_instance_configs_for_service(service, soa_dir=args.soa_dir):
if all([f(instance_conf) for f in filters]):
cluster_service = clusters_services_instances[instance_conf.get_cluster()][service]
cluster_service[instance_conf.get_instance()] = instance_conf.__class__
i_count += 1
if i_count == 0 and args.service and args.instances:
if args.clusters:
clusters = args.clusters.split(',')
else:
clusters = list_clusters()
for service in args.service.split(','):
verify_instances(args.instances, service, clusters)
return clusters_services_instances
def paasta_status(
args,
) -> int:
soa_dir = args.soa_dir
system_paasta_config = load_system_paasta_config()
if 'USE_API_ENDPOINT' in os.environ:
use_api_endpoint = strtobool(os.environ['USE_API_ENDPOINT'])
else:
use_api_endpoint = False
return_codes = [0]
tasks = []
clusters_services_instances = apply_args_filters(args)
for cluster, service_instances in clusters_services_instances.items():
for service, instances in service_instances.items():
all_flink = all(i == FlinkClusterConfig for i in instances.values())
actual_deployments: Mapping[str, str]
if all_flink:
actual_deployments = {}
else:
actual_deployments = get_actual_deployments(service, soa_dir)
if all_flink or actual_deployments:
deploy_pipeline = list(get_planned_deployments(service, soa_dir))
tasks.append((
report_status_for_cluster, dict(
service=service,
cluster=cluster,
deploy_pipeline=deploy_pipeline,
actual_deployments=actual_deployments,
instance_whitelist=instances,
system_paasta_config=system_paasta_config,
verbose=args.verbose,
use_api_endpoint=use_api_endpoint,
),
))
else:
paasta_print(missing_deployments_message(service))
return_codes.append(1)
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
tasks = [executor.submit(t[0], **t[1]) for t in tasks] # type: ignore
for future in concurrent.futures.as_completed(tasks): # type: ignore
return_code, output = future.result()
paasta_print('\n'.join(output))
return_codes.append(return_code)
return max(return_codes)
| true | true |
f729e706d2484f595cf802f9d8bf9fbac86d4c32 | 5,134 | py | Python | scripts/extract_toolbox_sections.py | beatrizserrano/galaxy | e149d9d32e1bca6c07c38b1a9cdabfee60323610 | [
"CC-BY-3.0"
] | null | null | null | scripts/extract_toolbox_sections.py | beatrizserrano/galaxy | e149d9d32e1bca6c07c38b1a9cdabfee60323610 | [
"CC-BY-3.0"
] | 6 | 2021-11-11T20:57:49.000Z | 2021-12-10T15:30:33.000Z | scripts/extract_toolbox_sections.py | beatrizserrano/galaxy | e149d9d32e1bca6c07c38b1a9cdabfee60323610 | [
"CC-BY-3.0"
] | null | null | null | import os
from collections import defaultdict
from xml.etree import ElementTree as ET
# Todo: ""
# execute from galaxy root dir
tooldict = defaultdict(list)
def main():
doc = ET.parse("tool_conf.xml")
root = doc.getroot()
# index range 1-1000, current sections/tools divided between 250-750
sectionindex = 250
sectionfactor = int(500 / len(root))
for rootchild in root:
currentsectionlabel = ""
if rootchild.tag == "section":
sectionname = rootchild.attrib["name"]
# per section tool index range 1-1000, current labels/tools
# divided between 20 and 750
toolindex = 250
toolfactor = int(500 / len(rootchild))
currentlabel = ""
for sectionchild in rootchild:
if sectionchild.tag == "tool":
addToToolDict(sectionchild, sectionname, sectionindex, toolindex, currentlabel)
toolindex += toolfactor
elif sectionchild.tag == "label":
currentlabel = sectionchild.attrib["text"]
sectionindex += sectionfactor
elif rootchild.tag == "tool":
addToToolDict(rootchild, "", sectionindex, None, currentsectionlabel)
sectionindex += sectionfactor
elif rootchild.tag == "label":
currentsectionlabel = rootchild.attrib["text"]
sectionindex += sectionfactor
# scan galaxy root tools dir for tool-specific xmls
toolconffilelist = getfnl(os.path.join(os.getcwd(), "tools"))
# foreach tool xml:
# check if the tags element exists in the tool xml (as child of <tool>)
# if not, add empty tags element for later use
# if this tool is in the above tooldict, add the toolboxposition element to the tool xml
# if not, then nothing.
for toolconffile in toolconffilelist:
hastags = False
hastoolboxpos = False
# parse tool config file into a document structure as defined by the ElementTree
tooldoc = ET.parse(toolconffile)
# get the root element of the toolconfig file
tooldocroot = tooldoc.getroot()
# check tags element, set flag
tagselement = tooldocroot.find("tags")
if tagselement:
hastags = True
# check if toolboxposition element already exists in this tooconfig file
toolboxposelement = tooldocroot.find("toolboxposition")
if toolboxposelement:
hastoolboxpos = True
if not (hastags and hastoolboxpos):
original = open(toolconffile)
contents = original.readlines()
original.close()
# the new elements will be added directly below the root tool element
addelementsatposition = 1
# but what's on the first line? Root or not?
if contents[0].startswith("<?"):
addelementsatposition = 2
newelements = []
if not hastoolboxpos:
if toolconffile in tooldict:
for attributes in tooldict[toolconffile]:
# create toolboxposition element
sectionelement = ET.Element("toolboxposition")
sectionelement.attrib = attributes
sectionelement.tail = "\n "
newelements.append(ET.tostring(sectionelement, "utf-8"))
if not hastags:
# create empty tags element
newelements.append("<tags/>\n ")
contents = contents[0:addelementsatposition] + newelements + contents[addelementsatposition:]
# add .new for testing/safety purposes :P
newtoolconffile = open(toolconffile, "w")
newtoolconffile.writelines(contents)
newtoolconffile.close()
def addToToolDict(tool, sectionname, sectionindex, toolindex, currentlabel):
toolfile = tool.attrib["file"]
realtoolfile = os.path.join(os.getcwd(), "tools", toolfile)
# define attributes for the toolboxposition xml-tag
attribdict = {}
if sectionname:
attribdict["section"] = sectionname
if currentlabel:
attribdict["label"] = currentlabel
if sectionindex:
attribdict["sectionorder"] = str(sectionindex)
if toolindex:
attribdict["order"] = str(toolindex)
tooldict[realtoolfile].append(attribdict)
# Build a list of all toolconf xml files in the tools directory
def getfnl(startdir):
filenamelist = []
for root, _dirs, files in os.walk(startdir):
for fn in files:
fullfn = os.path.join(root, fn)
if fn.endswith(".xml"):
try:
doc = ET.parse(fullfn)
except Exception as e:
raise Exception(f"Oops, bad XML in '{fullfn}': {e}")
rootelement = doc.getroot()
# here we check if this xml file actually is a tool conf xml!
if rootelement.tag == "tool":
filenamelist.append(fullfn)
return filenamelist
if __name__ == "__main__":
main()
| 37.75 | 105 | 0.603428 | import os
from collections import defaultdict
from xml.etree import ElementTree as ET
tooldict = defaultdict(list)
def main():
doc = ET.parse("tool_conf.xml")
root = doc.getroot()
sectionindex = 250
sectionfactor = int(500 / len(root))
for rootchild in root:
currentsectionlabel = ""
if rootchild.tag == "section":
sectionname = rootchild.attrib["name"]
toolindex = 250
toolfactor = int(500 / len(rootchild))
currentlabel = ""
for sectionchild in rootchild:
if sectionchild.tag == "tool":
addToToolDict(sectionchild, sectionname, sectionindex, toolindex, currentlabel)
toolindex += toolfactor
elif sectionchild.tag == "label":
currentlabel = sectionchild.attrib["text"]
sectionindex += sectionfactor
elif rootchild.tag == "tool":
addToToolDict(rootchild, "", sectionindex, None, currentsectionlabel)
sectionindex += sectionfactor
elif rootchild.tag == "label":
currentsectionlabel = rootchild.attrib["text"]
sectionindex += sectionfactor
toolconffilelist = getfnl(os.path.join(os.getcwd(), "tools"))
for toolconffile in toolconffilelist:
hastags = False
hastoolboxpos = False
tooldoc = ET.parse(toolconffile)
tooldocroot = tooldoc.getroot()
tagselement = tooldocroot.find("tags")
if tagselement:
hastags = True
toolboxposelement = tooldocroot.find("toolboxposition")
if toolboxposelement:
hastoolboxpos = True
if not (hastags and hastoolboxpos):
original = open(toolconffile)
contents = original.readlines()
original.close()
addelementsatposition = 1
if contents[0].startswith("<?"):
addelementsatposition = 2
newelements = []
if not hastoolboxpos:
if toolconffile in tooldict:
for attributes in tooldict[toolconffile]:
# create toolboxposition element
sectionelement = ET.Element("toolboxposition")
sectionelement.attrib = attributes
sectionelement.tail = "\n "
newelements.append(ET.tostring(sectionelement, "utf-8"))
if not hastags:
# create empty tags element
newelements.append("<tags/>\n ")
contents = contents[0:addelementsatposition] + newelements + contents[addelementsatposition:]
# add .new for testing/safety purposes :P
newtoolconffile = open(toolconffile, "w")
newtoolconffile.writelines(contents)
newtoolconffile.close()
def addToToolDict(tool, sectionname, sectionindex, toolindex, currentlabel):
toolfile = tool.attrib["file"]
realtoolfile = os.path.join(os.getcwd(), "tools", toolfile)
# define attributes for the toolboxposition xml-tag
attribdict = {}
if sectionname:
attribdict["section"] = sectionname
if currentlabel:
attribdict["label"] = currentlabel
if sectionindex:
attribdict["sectionorder"] = str(sectionindex)
if toolindex:
attribdict["order"] = str(toolindex)
tooldict[realtoolfile].append(attribdict)
# Build a list of all toolconf xml files in the tools directory
def getfnl(startdir):
filenamelist = []
for root, _dirs, files in os.walk(startdir):
for fn in files:
fullfn = os.path.join(root, fn)
if fn.endswith(".xml"):
try:
doc = ET.parse(fullfn)
except Exception as e:
raise Exception(f"Oops, bad XML in '{fullfn}': {e}")
rootelement = doc.getroot()
# here we check if this xml file actually is a tool conf xml!
if rootelement.tag == "tool":
filenamelist.append(fullfn)
return filenamelist
if __name__ == "__main__":
main()
| true | true |
f729e714918038b9f396ec89a8394119a0377539 | 460 | py | Python | tests/dsfs/test_neural_networks.py | dbradf/dsfs | efcd08ca56b4e14b926cc824f15474b04a9d94cb | [
"Apache-2.0"
] | null | null | null | tests/dsfs/test_neural_networks.py | dbradf/dsfs | efcd08ca56b4e14b926cc824f15474b04a9d94cb | [
"Apache-2.0"
] | null | null | null | tests/dsfs/test_neural_networks.py | dbradf/dsfs | efcd08ca56b4e14b926cc824f15474b04a9d94cb | [
"Apache-2.0"
] | null | null | null | import dsfs.neural_networks as under_test
def test_xor_network():
xor_network = [[[20.0, 20, -30], [20.0, 20, -10]], [[-60.0, 60, -30]]]
assert 0.000 < under_test.feed_forward(xor_network, [0, 0])[-1][0] < 0.001
assert 0.999 < under_test.feed_forward(xor_network, [1, 0])[-1][0] < 1.000
assert 0.999 < under_test.feed_forward(xor_network, [0, 1])[-1][0] < 1.000
assert 0.000 < under_test.feed_forward(xor_network, [1, 1])[-1][0] < 0.001
| 41.818182 | 78 | 0.634783 | import dsfs.neural_networks as under_test
def test_xor_network():
xor_network = [[[20.0, 20, -30], [20.0, 20, -10]], [[-60.0, 60, -30]]]
assert 0.000 < under_test.feed_forward(xor_network, [0, 0])[-1][0] < 0.001
assert 0.999 < under_test.feed_forward(xor_network, [1, 0])[-1][0] < 1.000
assert 0.999 < under_test.feed_forward(xor_network, [0, 1])[-1][0] < 1.000
assert 0.000 < under_test.feed_forward(xor_network, [1, 1])[-1][0] < 0.001
| true | true |
f729e94618f3fc85023f8d1fd03c604f683d234c | 409 | py | Python | sort/insert_sort.py | GetDarren/leetcode-vanilla | d00b307a85a9f1cf329739c1f660b7357667cd58 | [
"MIT"
] | null | null | null | sort/insert_sort.py | GetDarren/leetcode-vanilla | d00b307a85a9f1cf329739c1f660b7357667cd58 | [
"MIT"
] | null | null | null | sort/insert_sort.py | GetDarren/leetcode-vanilla | d00b307a85a9f1cf329739c1f660b7357667cd58 | [
"MIT"
] | null | null | null | """
循环不变式 就是 : A[0, j-1]
"""
from random_array import random
def insert_sort(arr):
if len(arr) < 2:
raise Exception("array is too short to sort")
for j in range(1, len(arr)):
pivot = arr[j]
i = j - 1
while i >= 0 and arr[i] > pivot:
arr[i+1] = arr[i]
i -= 1
arr[i+1] = pivot
return arr
if __name__ == '__main__':
arr=random(10)
print(insert_sort(arr))
| 18.590909 | 49 | 0.555012 | from random_array import random
def insert_sort(arr):
if len(arr) < 2:
raise Exception("array is too short to sort")
for j in range(1, len(arr)):
pivot = arr[j]
i = j - 1
while i >= 0 and arr[i] > pivot:
arr[i+1] = arr[i]
i -= 1
arr[i+1] = pivot
return arr
if __name__ == '__main__':
arr=random(10)
print(insert_sort(arr))
| true | true |
f729e94fef7fdd7139406d699760c860a32fcf34 | 20,680 | py | Python | third_party/blink/tools/blinkpy/common/pretty_diff.py | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | third_party/blink/tools/blinkpy/common/pretty_diff.py | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | third_party/blink/tools/blinkpy/common/pretty_diff.py | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Prettifies 'git diff' output.
prettify_diff() takes a diff string, and returns an HTML string decorating the
diff.
This code doesn't support other diff commands such as "diff" and "svn diff".
"""
import base64
import difflib
import mimetypes
import re
import six
import zlib
if six.PY2:
import cgi
else:
import html as cgi
from blinkpy.common.base85 import decode_base85
# The style below is meant to be similar to PolyGerrit.
_LEADING_HTML = """<!DOCTYPE html>
<meta charset="UTF-8">
<style>
body {
background: white;
font-family: "Roboto Mono", Menlo, "Lucida Console", Monaco, monospace;
}
table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
margin-top: 1em;
}
td { white-space: pre-wrap; font-size: 14px; }
.fileheader { position: sticky; top: 0px; }
.fileheader-container {
background: #eee;
border-bottom: 1px solid #ddd;
border-top: 1px solid #ddd;
box-sizing: border-box;
display: flex;
line-height: 2.25em;
padding: 0.2em 1rem 0.2em 1rem;
}
.filename { flex-grow: 1; }
.fileheader button { flex-grow: 0; width: 2.25em; }
.rename { color: #999999; display: block; }
.fileinfo { background: #fafafa; color: #3a66d9; }
.filehooter div { border-top: 1px solid #ddd; }
.hunkheader { background: rgb(255, 247, 212); color: #757575; }
.lineno {
background: #fafafa;
box-sizing: border-box;
color: #666;
padding: 0 0.5em;
text-align: right;
user-select: none;
vertical-align: top;
width: 94px;
}
.emptylineno { box-sizing: border-box; user-select: none; width: 94px; }
.code { border-left: 1px solid #ddd; word-break: break-all; }
.del { background: #ffeeee; }
.del.strong { background: #ffcaca; }
.add { background: #eeffee; }
.add.strong { background: #caffca; }
.binary { padding: 8px; border-left: 1px solid #ddd; }
pre { white-space: pre-wrap; font-size: 14px; }
.hidden { display: none; }
</style>
<body>
<script>
function toggleFollowingRows(button) {
button.textContent = button.textContent == '\\u25B2' ? '\\u25BC' : '\\u25B2';
let parent = button;
while (parent && parent.tagName != 'TR') {
parent = parent.parentNode;
}
if (!parent)
return;
for (let next = parent.nextSibling; next; next = next.nextSibling) {
if (next.tagName == 'TR')
next.classList.toggle('hidden')
}
}
</script>
"""
def prettify_diff(diff_str):
diff_lines = diff_str.split('\n')
# List of DiffFile instances
diff_files = []
diff_file, diff_lines = DiffFile.parse(diff_lines)
while diff_file:
diff_files.append(diff_file)
diff_file, diff_lines = DiffFile.parse(diff_lines)
result_html = _LEADING_HTML
for diff_file in diff_files:
result_html += diff_file.prettify()
# If diff_lines still has unconsumed lines, this code has a bug or the input
# diff is broken. We show the raw diff in such case.
if diff_lines:
result_html += '<pre>'
for line in diff_lines:
result_html += cgi.escape(line) + '\n'
result_html += '</pre>'
return result_html + '</body>\n'
class DiffFile(object):
"""Represents diff for a single file.
An instance of this class contains one of the following:
- Text hunks
- Two binary hunks
- Meta information
"""
LINK_BASE_URL = 'https://chromium.googlesource.com/chromium/src/+/master/'
def __init__(self,
old_name,
new_name,
hunks=None,
binaries=None,
info=None):
assert old_name or new_name
assert bool(hunks) + bool(binaries) + bool(info) == 1
self._old_name = old_name
self._new_name = new_name
self._hunks = hunks
self._binaries = binaries
self._info = info
def prettify(self):
status = 'M'
pretty_name = self._linkify(self._new_name)
additional_info = ''
if self._old_name == '':
status = 'A'
pretty_name = cgi.escape(self._new_name)
elif self._new_name == '':
status = 'D'
pretty_name = self._linkify(self._old_name)
elif self._old_name != self._new_name:
status = 'R'
pretty_name = cgi.escape(self._new_name)
additional_info = (
'\n<span class=rename>Renamed from {}</span>'.format(
self._linkify(self._old_name)))
result_html = (
'\n<table>\n<tr><td colspan=3 class=fileheader>'
'<div class=fileheader-container>'
'<div class=filename>' + status + ' ' + pretty_name +
additional_info + '</div>'
'<button type=button onclick="toggleFollowingRows(this);">▲</button>'
'</div></tr>')
if self._hunks:
for hunk in self._hunks:
result_html += hunk.prettify()
elif self._info:
result_html += '<tr><td colspan=3 class=fileinfo>{}</tr>'.format(
cgi.escape('\n'.join(self._info)))
else:
old_binary, new_binary = self._binaries # pylint: disable=unpacking-non-sequence
if self._old_name and old_binary:
result_html += old_binary.prettify(
self._mime_from_name(self._old_name), 'del')
if self._new_name and new_binary:
result_html += new_binary.prettify(
self._mime_from_name(self._new_name), 'add')
return result_html + '<tr><td colspan=3 class=filehooter><div></div></table>\n'
def _linkify(self, name):
return '<a href="{url}" target="_new">{anchor}</a>'.format(
url=DiffFile.LINK_BASE_URL + cgi.escape(name),
anchor=cgi.escape(name))
def _mime_from_name(self, name):
mime_type, _ = mimetypes.guess_type(name)
return mime_type if mime_type else 'application/octet-stream'
@staticmethod
def parse(lines):
"""Parses diff lines, and creates a DiffFile instance.
Finds a file diff header, creates a single DiffFile instance, and
returns a tuple of the DiffFile instance and unconsumed lines. If a file
diff isn't found, (None, lines) is returned.
"""
diff_command_re = r'diff (?:-[^ ]+ )*a/([^ ]+) b/([^ ]+)'
old_name = None
new_name = None
info_lines = None
found_diff_command_line = False
for i, line in enumerate(lines):
if not found_diff_command_line:
match = re.match(diff_command_re, line)
if not match:
continue
old_name = match.group(1)
new_name = match.group(2)
info_lines = []
found_diff_command_line = True
continue
match = re.match(r'(GIT binary patch|--- ([^ ]+).*)', line)
if match:
if match.group(0) == 'GIT binary patch':
return DiffFile._parse_binaries(lines[i + 1:], old_name,
new_name)
return DiffFile._parse_text_hunks(lines[i:], old_name,
new_name)
index_match = re.match(r'^index ([0-9a-f]+)\.\.([0-9a-f]+).*',
line)
if index_match:
# Adjusts old_name and new_name for file addition/removal.
old_name, new_name = DiffFile._adjust_names(
index_match, old_name, new_name)
continue
diff_match = re.match(diff_command_re, line)
if diff_match:
# There are no hunks. Renaming without any modification,
# or adding/removing an empty file.
return (DiffFile(old_name, new_name, info=info_lines),
lines[i:])
# File mode, rename summary, etc.
info_lines.append(line)
if found_diff_command_line and info_lines:
return (DiffFile(old_name, new_name, info=info_lines), [])
return (None, lines)
@staticmethod
def _parse_binaries(lines, old_name, new_name):
new_binary, remaining_lines = BinaryHunk.parse(lines)
old_binary, remaining_lines = BinaryHunk.parse(remaining_lines)
return (DiffFile(
old_name, new_name, binaries=(old_binary, new_binary)),
remaining_lines)
@staticmethod
def _parse_text_hunks(lines, old_name, new_name):
line = lines[0]
if len(lines) < 2:
raise ValueError('"+++ " line is missing after "{}"'.format(line))
next_line = lines[1]
if not next_line.startswith('+++ '):
raise ValueError('"+++ " line is missing after "{}"'.format(line))
hunks, remaining_lines = DiffHunk.parse(lines[2:])
return (DiffFile(old_name, new_name, hunks=hunks), remaining_lines)
@staticmethod
def _adjust_names(match, old_name, new_name):
old_index = match.group(1)
new_index = match.group(2)
if old_index and re.match(r'^0+$', old_index):
old_name = ''
if new_index and re.match(r'^0+$', new_index):
new_name = ''
return (old_name, new_name)
class DiffHunk(object):
"""Represents a single text hunk, starting with '@@ -d,d +d,d @@'.
This class also has code to detect character-level diff.
"""
def __init__(self, old_start, new_start, context, lines):
self._old_start = old_start
self._new_start = new_start
self._context = ''
if context:
self._context = context
if self._context.startswith(' '):
self._context = self._context[1:]
self._lines = lines
# _annotations is a list of None or a list of tuples.
# A tuple consists of start index and end index, and it represents a
# modified part of a line, which should be highlighted in the pretty
# diff.
self._annotations = [None for _ in self._lines]
for deleted_index, inserted_index in self._find_operations(
self._lines):
DiffHunk._annotate_character_diff(
self._lines, deleted_index, inserted_index, self._annotations)
@staticmethod
def _find_operations(lines):
"""Finds 'operations' in the hunk.
A hunk contains one or more operations, and an operation is one of the
followings:
- Replace operation: '-' lines, followed by '+' lines
- Delete operation: '-' lines, not followed by '+' lines
- Insertion operation: '+' lines
"""
# List of tuples which consist of (list of '-' line index, list of '+' line index)
operations = []
inserted_index = []
deleted_index = []
for i, line in enumerate(lines):
if line[0] == ' ':
if deleted_index or inserted_index:
operations.append((deleted_index, inserted_index))
deleted_index = []
inserted_index = []
elif line[0] == '-':
if inserted_index:
operations.append((deleted_index, inserted_index))
deleted_index = []
inserted_index = []
deleted_index.append(i)
else:
assert line[0] == '+'
inserted_index.append(i)
if deleted_index or inserted_index:
operations.append((deleted_index, inserted_index))
return operations
@staticmethod
def _annotate_character_diff(lines, deleted_index, inserted_index,
annotations):
assert len(lines) == len(annotations)
if not deleted_index:
for i in inserted_index:
annotations[i] = [(0, len(lines[i]) - 1)]
return
if not inserted_index:
for i in deleted_index:
annotations[i] = [(0, len(lines[i]) - 1)]
return
deleted_str = ''.join([lines[i][1:] for i in deleted_index])
inserted_str = ''.join([lines[i][1:] for i in inserted_index])
matcher = difflib.SequenceMatcher(None, deleted_str, inserted_str)
for tag, d_start, d_end, i_start, i_end in matcher.get_opcodes():
if tag == 'delete':
DiffHunk._annotate(lines, deleted_index[0], d_start, d_end,
annotations)
elif tag == 'insert':
DiffHunk._annotate(lines, inserted_index[0], i_start, i_end,
annotations)
elif tag == 'replace':
DiffHunk._annotate(lines, deleted_index[0], d_start, d_end,
annotations)
DiffHunk._annotate(lines, inserted_index[0], i_start, i_end,
annotations)
@staticmethod
def _annotate(lines, index, start, end, annotations):
assert index < len(lines)
line_len = len(lines[index]) - 1
if line_len == 0 and start == 0:
annotations[index] = [(0, 0)]
DiffHunk._annotate(lines, index + 1, start, end, annotations)
return
if start >= line_len:
DiffHunk._annotate(lines, index + 1, start - line_len,
end - line_len, annotations)
return
if not annotations[index]:
annotations[index] = []
annotations[index].append((start, min(line_len, end)))
if end > line_len:
DiffHunk._annotate(lines, index + 1, 0, end - line_len,
annotations)
def prettify_code(self, index, klass):
line = self._lines[index][1:]
annotation = self._annotations[index]
if not annotation:
return '<td class="code {klass}">{code}'.format(
klass=klass, code=cgi.escape(line))
start, end = annotation[0]
if start == 0 and end == len(line):
return '<td class="code {klass} strong">{code}'.format(
klass=klass, code=cgi.escape(line))
i = 0
result_html = '<td class="code {}">'.format(klass)
for start, end in annotation:
result_html += cgi.escape(line[i:start])
result_html += '<span class="{} strong">'.format(klass)
result_html += cgi.escape(line[start:end])
result_html += '</span>'
i = end
return result_html + cgi.escape(line[i:])
def prettify(self):
result_html = ('<tr><td class=hunkheader>@@<td class=hunkheader>@@'
'<td class=hunkheader>{}</tr>\n').format(
cgi.escape(self._context))
old_lineno = self._old_start
new_lineno = self._new_start
for i, line in enumerate(self._lines):
if line[0] == ' ':
result_html += (
'<tr><td class=lineno>{old_lineno}<td '
'class=lineno>{new_lineno}<td class=code>{code}'
'</tr>\n').format(
old_lineno=old_lineno,
new_lineno=new_lineno,
code=cgi.escape(line[1:]))
old_lineno += 1
new_lineno += 1
elif line[0] == '-':
result_html += '<tr><td class=lineno>{lineno}<td class=emptylineno>{code}</tr>\n'.format(
lineno=old_lineno, code=self.prettify_code(i, 'del'))
old_lineno += 1
else:
assert line[0] == '+'
result_html += '<tr><td class=emptylineno><td class=lineno>{lineno}{code}</tr>\n'.format(
lineno=new_lineno, code=self.prettify_code(i, 'add'))
new_lineno += 1
return result_html
@staticmethod
def parse(lines):
"""Parses diff lines, and creates a sequence of DiffHunk instances.
Finds a hunk header, creates a sequence of DiffHunk instances, and
returns a tuple of the DiffHunk list and unconsumed lines. If a hunk
header isn't found, ValueError is raised.
"""
old_start = None
new_start = None
context = None
hunk_lines = None
hunks = []
hunk_header_re = r'^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)?'
found_hunk_header = False
for i, line in enumerate(lines):
if not found_hunk_header:
match = re.match(hunk_header_re, line)
if match:
found_hunk_header = True
old_start = int(match.group(1))
new_start = int(match.group(2))
context = match.group(3)
hunk_lines = []
continue
if line.startswith((' ', '-', '+')):
hunk_lines.append(line)
continue
hunks.append(DiffHunk(old_start, new_start, context, hunk_lines))
match = re.match(hunk_header_re, line)
if not match:
return (hunks, lines[i:])
old_start = int(match.group(1))
new_start = int(match.group(2))
context = match.group(3)
hunk_lines = []
if found_hunk_header:
hunks.append(DiffHunk(old_start, new_start, context, hunk_lines))
else:
raise ValueError('Found no hunks')
return (hunks, [])
class BinaryHunk(object):
"""Represents a binary hunk.
A binary diff for a single file contains two binary hunks. An
instance of this class represents a single binary hunk.
"""
def __init__(self, bin_type, size, bin_data):
assert bin_type in ('literal', 'delta')
self._type = bin_type
self._size = size
self._compressed_data = bin_data
def prettify(self, mime_type, klass):
result_html = (
'<tr><td class=emptylineno><td class=emptylineno>'
'<td class="{klass} strong binary">Binary {type}; {size}'
' Bytes<br>\n').format(
klass=klass, type=self._type, size=self._size)
if self._type == 'delta':
# Because we can assume the input diff is always produced by git, we
# can obtain the original blob, apply the delta, and render both of
# the original blob and the patched blob. However, we're not sure
# how much it is worth to do.
#
# For 'delta' format, see patch_delta() in patch-delta.c.
# https://github.com/git/git/blob/master/patch-delta.c
return result_html + 'We don\'t support rendering a delta binary hunk.'
if mime_type.startswith('image/'):
return result_html + '<img src="data:{type};base64,{data}">'.format(
type=mime_type,
data=base64.b64encode(zlib.decompress(self._compressed_data)))
return result_html + 'We don\'t support rendering {} binary.'.format(
mime_type)
@staticmethod
def parse(lines):
"""Creates a BinaryHunk instance starting with lines[0].
Returns a tuple of the BinaryHunk instance and unconsumed lines.
"""
match = re.match(r'(literal|delta) (\d+)', lines[0])
if not match:
raise ValueError('No "literal <size>" or "delta <size>".')
bin_type = match.group(1)
size = int(match.group(2))
bin_data = ''
lines = lines[1:]
for i, line in enumerate(lines):
if len(line) == 0:
return (BinaryHunk(bin_type, size, bin_data), lines[i + 1:])
line_length_letter = line[0]
# Map a letter to a number.
# A-Z -> 1-26
# a-z -> 27-52
line_length = 1 + ord(line_length_letter) - ord('A')
if line_length_letter >= 'a':
line_length = 27 + ord(line_length_letter) - ord('a')
if line_length * 5 > (len(line) - 1) * 4:
raise ValueError('Base85 length mismatch: length by the first '
'letter:{}, actual:{}, line:"{}"'.format(
line_length * 5, (len(line) - 1) * 4,
line))
bin_data += decode_base85(line[1:])[0:line_length]
raise ValueError('No blank line terminating a binary hunk.')
| 37.944954 | 105 | 0.562234 |
import base64
import difflib
import mimetypes
import re
import six
import zlib
if six.PY2:
import cgi
else:
import html as cgi
from blinkpy.common.base85 import decode_base85
_LEADING_HTML = """<!DOCTYPE html>
<meta charset="UTF-8">
<style>
body {
background: white;
font-family: "Roboto Mono", Menlo, "Lucida Console", Monaco, monospace;
}
table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
margin-top: 1em;
}
td { white-space: pre-wrap; font-size: 14px; }
.fileheader { position: sticky; top: 0px; }
.fileheader-container {
background: #eee;
border-bottom: 1px solid #ddd;
border-top: 1px solid #ddd;
box-sizing: border-box;
display: flex;
line-height: 2.25em;
padding: 0.2em 1rem 0.2em 1rem;
}
.filename { flex-grow: 1; }
.fileheader button { flex-grow: 0; width: 2.25em; }
.rename { color: #999999; display: block; }
.fileinfo { background: #fafafa; color: #3a66d9; }
.filehooter div { border-top: 1px solid #ddd; }
.hunkheader { background: rgb(255, 247, 212); color: #757575; }
.lineno {
background: #fafafa;
box-sizing: border-box;
color: #666;
padding: 0 0.5em;
text-align: right;
user-select: none;
vertical-align: top;
width: 94px;
}
.emptylineno { box-sizing: border-box; user-select: none; width: 94px; }
.code { border-left: 1px solid #ddd; word-break: break-all; }
.del { background: #ffeeee; }
.del.strong { background: #ffcaca; }
.add { background: #eeffee; }
.add.strong { background: #caffca; }
.binary { padding: 8px; border-left: 1px solid #ddd; }
pre { white-space: pre-wrap; font-size: 14px; }
.hidden { display: none; }
</style>
<body>
<script>
function toggleFollowingRows(button) {
button.textContent = button.textContent == '\\u25B2' ? '\\u25BC' : '\\u25B2';
let parent = button;
while (parent && parent.tagName != 'TR') {
parent = parent.parentNode;
}
if (!parent)
return;
for (let next = parent.nextSibling; next; next = next.nextSibling) {
if (next.tagName == 'TR')
next.classList.toggle('hidden')
}
}
</script>
"""
def prettify_diff(diff_str):
diff_lines = diff_str.split('\n')
diff_files = []
diff_file, diff_lines = DiffFile.parse(diff_lines)
while diff_file:
diff_files.append(diff_file)
diff_file, diff_lines = DiffFile.parse(diff_lines)
result_html = _LEADING_HTML
for diff_file in diff_files:
result_html += diff_file.prettify()
if diff_lines:
result_html += '<pre>'
for line in diff_lines:
result_html += cgi.escape(line) + '\n'
result_html += '</pre>'
return result_html + '</body>\n'
class DiffFile(object):
LINK_BASE_URL = 'https://chromium.googlesource.com/chromium/src/+/master/'
def __init__(self,
old_name,
new_name,
hunks=None,
binaries=None,
info=None):
assert old_name or new_name
assert bool(hunks) + bool(binaries) + bool(info) == 1
self._old_name = old_name
self._new_name = new_name
self._hunks = hunks
self._binaries = binaries
self._info = info
def prettify(self):
status = 'M'
pretty_name = self._linkify(self._new_name)
additional_info = ''
if self._old_name == '':
status = 'A'
pretty_name = cgi.escape(self._new_name)
elif self._new_name == '':
status = 'D'
pretty_name = self._linkify(self._old_name)
elif self._old_name != self._new_name:
status = 'R'
pretty_name = cgi.escape(self._new_name)
additional_info = (
'\n<span class=rename>Renamed from {}</span>'.format(
self._linkify(self._old_name)))
result_html = (
'\n<table>\n<tr><td colspan=3 class=fileheader>'
'<div class=fileheader-container>'
'<div class=filename>' + status + ' ' + pretty_name +
additional_info + '</div>'
'<button type=button onclick="toggleFollowingRows(this);">▲</button>'
'</div></tr>')
if self._hunks:
for hunk in self._hunks:
result_html += hunk.prettify()
elif self._info:
result_html += '<tr><td colspan=3 class=fileinfo>{}</tr>'.format(
cgi.escape('\n'.join(self._info)))
else:
old_binary, new_binary = self._binaries
if self._old_name and old_binary:
result_html += old_binary.prettify(
self._mime_from_name(self._old_name), 'del')
if self._new_name and new_binary:
result_html += new_binary.prettify(
self._mime_from_name(self._new_name), 'add')
return result_html + '<tr><td colspan=3 class=filehooter><div></div></table>\n'
def _linkify(self, name):
return '<a href="{url}" target="_new">{anchor}</a>'.format(
url=DiffFile.LINK_BASE_URL + cgi.escape(name),
anchor=cgi.escape(name))
def _mime_from_name(self, name):
mime_type, _ = mimetypes.guess_type(name)
return mime_type if mime_type else 'application/octet-stream'
@staticmethod
def parse(lines):
diff_command_re = r'diff (?:-[^ ]+ )*a/([^ ]+) b/([^ ]+)'
old_name = None
new_name = None
info_lines = None
found_diff_command_line = False
for i, line in enumerate(lines):
if not found_diff_command_line:
match = re.match(diff_command_re, line)
if not match:
continue
old_name = match.group(1)
new_name = match.group(2)
info_lines = []
found_diff_command_line = True
continue
match = re.match(r'(GIT binary patch|--- ([^ ]+).*)', line)
if match:
if match.group(0) == 'GIT binary patch':
return DiffFile._parse_binaries(lines[i + 1:], old_name,
new_name)
return DiffFile._parse_text_hunks(lines[i:], old_name,
new_name)
index_match = re.match(r'^index ([0-9a-f]+)\.\.([0-9a-f]+).*',
line)
if index_match:
old_name, new_name = DiffFile._adjust_names(
index_match, old_name, new_name)
continue
diff_match = re.match(diff_command_re, line)
if diff_match:
return (DiffFile(old_name, new_name, info=info_lines),
lines[i:])
info_lines.append(line)
if found_diff_command_line and info_lines:
return (DiffFile(old_name, new_name, info=info_lines), [])
return (None, lines)
@staticmethod
def _parse_binaries(lines, old_name, new_name):
new_binary, remaining_lines = BinaryHunk.parse(lines)
old_binary, remaining_lines = BinaryHunk.parse(remaining_lines)
return (DiffFile(
old_name, new_name, binaries=(old_binary, new_binary)),
remaining_lines)
@staticmethod
def _parse_text_hunks(lines, old_name, new_name):
line = lines[0]
if len(lines) < 2:
raise ValueError('"+++ " line is missing after "{}"'.format(line))
next_line = lines[1]
if not next_line.startswith('+++ '):
raise ValueError('"+++ " line is missing after "{}"'.format(line))
hunks, remaining_lines = DiffHunk.parse(lines[2:])
return (DiffFile(old_name, new_name, hunks=hunks), remaining_lines)
@staticmethod
def _adjust_names(match, old_name, new_name):
old_index = match.group(1)
new_index = match.group(2)
if old_index and re.match(r'^0+$', old_index):
old_name = ''
if new_index and re.match(r'^0+$', new_index):
new_name = ''
return (old_name, new_name)
class DiffHunk(object):
def __init__(self, old_start, new_start, context, lines):
self._old_start = old_start
self._new_start = new_start
self._context = ''
if context:
self._context = context
if self._context.startswith(' '):
self._context = self._context[1:]
self._lines = lines
self._annotations = [None for _ in self._lines]
for deleted_index, inserted_index in self._find_operations(
self._lines):
DiffHunk._annotate_character_diff(
self._lines, deleted_index, inserted_index, self._annotations)
@staticmethod
def _find_operations(lines):
operations = []
inserted_index = []
deleted_index = []
for i, line in enumerate(lines):
if line[0] == ' ':
if deleted_index or inserted_index:
operations.append((deleted_index, inserted_index))
deleted_index = []
inserted_index = []
elif line[0] == '-':
if inserted_index:
operations.append((deleted_index, inserted_index))
deleted_index = []
inserted_index = []
deleted_index.append(i)
else:
assert line[0] == '+'
inserted_index.append(i)
if deleted_index or inserted_index:
operations.append((deleted_index, inserted_index))
return operations
@staticmethod
def _annotate_character_diff(lines, deleted_index, inserted_index,
annotations):
assert len(lines) == len(annotations)
if not deleted_index:
for i in inserted_index:
annotations[i] = [(0, len(lines[i]) - 1)]
return
if not inserted_index:
for i in deleted_index:
annotations[i] = [(0, len(lines[i]) - 1)]
return
deleted_str = ''.join([lines[i][1:] for i in deleted_index])
inserted_str = ''.join([lines[i][1:] for i in inserted_index])
matcher = difflib.SequenceMatcher(None, deleted_str, inserted_str)
for tag, d_start, d_end, i_start, i_end in matcher.get_opcodes():
if tag == 'delete':
DiffHunk._annotate(lines, deleted_index[0], d_start, d_end,
annotations)
elif tag == 'insert':
DiffHunk._annotate(lines, inserted_index[0], i_start, i_end,
annotations)
elif tag == 'replace':
DiffHunk._annotate(lines, deleted_index[0], d_start, d_end,
annotations)
DiffHunk._annotate(lines, inserted_index[0], i_start, i_end,
annotations)
@staticmethod
def _annotate(lines, index, start, end, annotations):
assert index < len(lines)
line_len = len(lines[index]) - 1
if line_len == 0 and start == 0:
annotations[index] = [(0, 0)]
DiffHunk._annotate(lines, index + 1, start, end, annotations)
return
if start >= line_len:
DiffHunk._annotate(lines, index + 1, start - line_len,
end - line_len, annotations)
return
if not annotations[index]:
annotations[index] = []
annotations[index].append((start, min(line_len, end)))
if end > line_len:
DiffHunk._annotate(lines, index + 1, 0, end - line_len,
annotations)
def prettify_code(self, index, klass):
line = self._lines[index][1:]
annotation = self._annotations[index]
if not annotation:
return '<td class="code {klass}">{code}'.format(
klass=klass, code=cgi.escape(line))
start, end = annotation[0]
if start == 0 and end == len(line):
return '<td class="code {klass} strong">{code}'.format(
klass=klass, code=cgi.escape(line))
i = 0
result_html = '<td class="code {}">'.format(klass)
for start, end in annotation:
result_html += cgi.escape(line[i:start])
result_html += '<span class="{} strong">'.format(klass)
result_html += cgi.escape(line[start:end])
result_html += '</span>'
i = end
return result_html + cgi.escape(line[i:])
def prettify(self):
result_html = ('<tr><td class=hunkheader>@@<td class=hunkheader>@@'
'<td class=hunkheader>{}</tr>\n').format(
cgi.escape(self._context))
old_lineno = self._old_start
new_lineno = self._new_start
for i, line in enumerate(self._lines):
if line[0] == ' ':
result_html += (
'<tr><td class=lineno>{old_lineno}<td '
'class=lineno>{new_lineno}<td class=code>{code}'
'</tr>\n').format(
old_lineno=old_lineno,
new_lineno=new_lineno,
code=cgi.escape(line[1:]))
old_lineno += 1
new_lineno += 1
elif line[0] == '-':
result_html += '<tr><td class=lineno>{lineno}<td class=emptylineno>{code}</tr>\n'.format(
lineno=old_lineno, code=self.prettify_code(i, 'del'))
old_lineno += 1
else:
assert line[0] == '+'
result_html += '<tr><td class=emptylineno><td class=lineno>{lineno}{code}</tr>\n'.format(
lineno=new_lineno, code=self.prettify_code(i, 'add'))
new_lineno += 1
return result_html
@staticmethod
def parse(lines):
old_start = None
new_start = None
context = None
hunk_lines = None
hunks = []
hunk_header_re = r'^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)?'
found_hunk_header = False
for i, line in enumerate(lines):
if not found_hunk_header:
match = re.match(hunk_header_re, line)
if match:
found_hunk_header = True
old_start = int(match.group(1))
new_start = int(match.group(2))
context = match.group(3)
hunk_lines = []
continue
if line.startswith((' ', '-', '+')):
hunk_lines.append(line)
continue
hunks.append(DiffHunk(old_start, new_start, context, hunk_lines))
match = re.match(hunk_header_re, line)
if not match:
return (hunks, lines[i:])
old_start = int(match.group(1))
new_start = int(match.group(2))
context = match.group(3)
hunk_lines = []
if found_hunk_header:
hunks.append(DiffHunk(old_start, new_start, context, hunk_lines))
else:
raise ValueError('Found no hunks')
return (hunks, [])
class BinaryHunk(object):
def __init__(self, bin_type, size, bin_data):
assert bin_type in ('literal', 'delta')
self._type = bin_type
self._size = size
self._compressed_data = bin_data
def prettify(self, mime_type, klass):
result_html = (
'<tr><td class=emptylineno><td class=emptylineno>'
'<td class="{klass} strong binary">Binary {type}; {size}'
' Bytes<br>\n').format(
klass=klass, type=self._type, size=self._size)
if self._type == 'delta':
# how much it is worth to do.
#
# For 'delta' format, see patch_delta() in patch-delta.c.
# https://github.com/git/git/blob/master/patch-delta.c
return result_html + 'We don\'t support rendering a delta binary hunk.'
if mime_type.startswith('image/'):
return result_html + '<img src="data:{type};base64,{data}">'.format(
type=mime_type,
data=base64.b64encode(zlib.decompress(self._compressed_data)))
return result_html + 'We don\'t support rendering {} binary.'.format(
mime_type)
@staticmethod
def parse(lines):
match = re.match(r'(literal|delta) (\d+)', lines[0])
if not match:
raise ValueError('No "literal <size>" or "delta <size>".')
bin_type = match.group(1)
size = int(match.group(2))
bin_data = ''
lines = lines[1:]
for i, line in enumerate(lines):
if len(line) == 0:
return (BinaryHunk(bin_type, size, bin_data), lines[i + 1:])
line_length_letter = line[0]
# Map a letter to a number.
# A-Z -> 1-26
# a-z -> 27-52
line_length = 1 + ord(line_length_letter) - ord('A')
if line_length_letter >= 'a':
line_length = 27 + ord(line_length_letter) - ord('a')
if line_length * 5 > (len(line) - 1) * 4:
raise ValueError('Base85 length mismatch: length by the first '
'letter:{}, actual:{}, line:"{}"'.format(
line_length * 5, (len(line) - 1) * 4,
line))
bin_data += decode_base85(line[1:])[0:line_length]
raise ValueError('No blank line terminating a binary hunk.')
| true | true |
f729eae915a3f96d01c2d8dbee3cd29b73654f13 | 7,571 | py | Python | fhirclient/models/composition_tests.py | carolinarsm/client-py | db1b6e3e28036dee11da75412003c7d90e591c6d | [
"Apache-2.0"
] | 418 | 2015-07-01T08:23:16.000Z | 2022-03-31T14:02:30.000Z | fhirclient/models/composition_tests.py | carolinarsm/client-py | db1b6e3e28036dee11da75412003c7d90e591c6d | [
"Apache-2.0"
] | 312 | 2017-09-08T15:42:13.000Z | 2022-03-23T18:21:40.000Z | fhirclient/models/composition_tests.py | carolinarsm/client-py | db1b6e3e28036dee11da75412003c7d90e591c6d | [
"Apache-2.0"
] | 185 | 2015-03-30T20:23:16.000Z | 2022-03-30T14:39:26.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import composition
from .fhirdate import FHIRDate
class CompositionTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("Composition", js["resourceType"])
return composition.Composition(js)
def testComposition1(self):
inst = self.instantiate_from("composition-example-mixed.json")
self.assertIsNotNone(inst, "Must have instantiated a Composition instance")
self.implComposition1(inst)
js = inst.as_json()
self.assertEqual("Composition", js["resourceType"])
inst2 = composition.Composition(js)
self.implComposition1(inst2)
def implComposition1(self, inst):
self.assertEqual(inst.attester[0].mode, "legal")
self.assertEqual(inst.attester[0].time.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.attester[0].time.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.category[0].coding[0].code, "LP173421-1")
self.assertEqual(inst.category[0].coding[0].display, "Report")
self.assertEqual(inst.category[0].coding[0].system, "http://loinc.org")
self.assertEqual(inst.confidentiality, "N")
self.assertEqual(inst.date.date, FHIRDate("2018-10-30T16:56:04+11:00").date)
self.assertEqual(inst.date.as_json(), "2018-10-30T16:56:04+11:00")
self.assertEqual(inst.id, "example-mixed")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data")
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.section[0].code.coding[0].code, "newborn")
self.assertEqual(inst.section[0].code.coding[0].display, "New Born Details")
self.assertEqual(inst.section[0].code.coding[0].system, "http://acme.org/codes/SectionType")
self.assertEqual(inst.section[0].text.status, "generated")
self.assertEqual(inst.section[0].title, "Child's Details")
self.assertEqual(inst.section[1].code.coding[0].code, "mother")
self.assertEqual(inst.section[1].code.coding[0].display, "Mother's Details")
self.assertEqual(inst.section[1].code.coding[0].system, "http://acme.org/codes/SectionType")
self.assertEqual(inst.section[1].text.status, "generated")
self.assertEqual(inst.section[1].title, "Mpther's Details")
self.assertEqual(inst.status, "final")
self.assertEqual(inst.text.status, "generated")
self.assertEqual(inst.title, "Discharge Summary (Neonatal Service)")
self.assertEqual(inst.type.coding[0].code, "78418-1")
self.assertEqual(inst.type.coding[0].display, "Neonatal perinatal medicine Discharge summary")
self.assertEqual(inst.type.coding[0].system, "http://loinc.org")
def testComposition2(self):
inst = self.instantiate_from("composition-example.json")
self.assertIsNotNone(inst, "Must have instantiated a Composition instance")
self.implComposition2(inst)
js = inst.as_json()
self.assertEqual("Composition", js["resourceType"])
inst2 = composition.Composition(js)
self.implComposition2(inst2)
def implComposition2(self, inst):
self.assertEqual(inst.attester[0].mode, "legal")
self.assertEqual(inst.attester[0].time.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.attester[0].time.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.category[0].coding[0].code, "LP173421-1")
self.assertEqual(inst.category[0].coding[0].display, "Report")
self.assertEqual(inst.category[0].coding[0].system, "http://loinc.org")
self.assertEqual(inst.confidentiality, "N")
self.assertEqual(inst.date.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.date.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.event[0].code[0].coding[0].code, "HEALTHREC")
self.assertEqual(inst.event[0].code[0].coding[0].display, "health record")
self.assertEqual(inst.event[0].code[0].coding[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActCode")
self.assertEqual(inst.event[0].period.end.date, FHIRDate("2012-11-12").date)
self.assertEqual(inst.event[0].period.end.as_json(), "2012-11-12")
self.assertEqual(inst.event[0].period.start.date, FHIRDate("2010-07-18").date)
self.assertEqual(inst.event[0].period.start.as_json(), "2010-07-18")
self.assertEqual(inst.id, "example")
self.assertEqual(inst.identifier.system, "http://healthintersections.com.au/test")
self.assertEqual(inst.identifier.value, "1")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data")
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.relatesTo[0].code, "replaces")
self.assertEqual(inst.relatesTo[1].code, "appends")
self.assertEqual(inst.relatesTo[1].targetIdentifier.system, "http://example.org/fhir/NamingSystem/document-ids")
self.assertEqual(inst.relatesTo[1].targetIdentifier.value, "ABC123")
self.assertEqual(inst.section[0].code.coding[0].code, "11348-0")
self.assertEqual(inst.section[0].code.coding[0].display, "History of past illness Narrative")
self.assertEqual(inst.section[0].code.coding[0].system, "http://loinc.org")
self.assertEqual(inst.section[0].mode, "snapshot")
self.assertEqual(inst.section[0].orderedBy.coding[0].code, "event-date")
self.assertEqual(inst.section[0].orderedBy.coding[0].display, "Sorted by Event Date")
self.assertEqual(inst.section[0].orderedBy.coding[0].system, "http://terminology.hl7.org/CodeSystem/list-order")
self.assertEqual(inst.section[0].text.status, "generated")
self.assertEqual(inst.section[0].title, "History of present illness")
self.assertEqual(inst.section[1].code.coding[0].code, "10157-6")
self.assertEqual(inst.section[1].code.coding[0].display, "History of family member diseases Narrative")
self.assertEqual(inst.section[1].code.coding[0].system, "http://loinc.org")
self.assertEqual(inst.section[1].emptyReason.coding[0].code, "withheld")
self.assertEqual(inst.section[1].emptyReason.coding[0].display, "Information Withheld")
self.assertEqual(inst.section[1].emptyReason.coding[0].system, "http://terminology.hl7.org/CodeSystem/list-empty-reason")
self.assertEqual(inst.section[1].mode, "snapshot")
self.assertEqual(inst.section[1].text.status, "generated")
self.assertEqual(inst.section[1].title, "History of family member diseases")
self.assertEqual(inst.status, "final")
self.assertEqual(inst.text.status, "generated")
self.assertEqual(inst.title, "Consultation Note")
self.assertEqual(inst.type.coding[0].code, "11488-4")
self.assertEqual(inst.type.coding[0].display, "Consult note")
self.assertEqual(inst.type.coding[0].system, "http://loinc.org")
| 59.614173 | 129 | 0.683133 |
import os
import io
import unittest
import json
from . import composition
from .fhirdate import FHIRDate
class CompositionTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("Composition", js["resourceType"])
return composition.Composition(js)
def testComposition1(self):
inst = self.instantiate_from("composition-example-mixed.json")
self.assertIsNotNone(inst, "Must have instantiated a Composition instance")
self.implComposition1(inst)
js = inst.as_json()
self.assertEqual("Composition", js["resourceType"])
inst2 = composition.Composition(js)
self.implComposition1(inst2)
def implComposition1(self, inst):
self.assertEqual(inst.attester[0].mode, "legal")
self.assertEqual(inst.attester[0].time.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.attester[0].time.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.category[0].coding[0].code, "LP173421-1")
self.assertEqual(inst.category[0].coding[0].display, "Report")
self.assertEqual(inst.category[0].coding[0].system, "http://loinc.org")
self.assertEqual(inst.confidentiality, "N")
self.assertEqual(inst.date.date, FHIRDate("2018-10-30T16:56:04+11:00").date)
self.assertEqual(inst.date.as_json(), "2018-10-30T16:56:04+11:00")
self.assertEqual(inst.id, "example-mixed")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data")
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.section[0].code.coding[0].code, "newborn")
self.assertEqual(inst.section[0].code.coding[0].display, "New Born Details")
self.assertEqual(inst.section[0].code.coding[0].system, "http://acme.org/codes/SectionType")
self.assertEqual(inst.section[0].text.status, "generated")
self.assertEqual(inst.section[0].title, "Child's Details")
self.assertEqual(inst.section[1].code.coding[0].code, "mother")
self.assertEqual(inst.section[1].code.coding[0].display, "Mother's Details")
self.assertEqual(inst.section[1].code.coding[0].system, "http://acme.org/codes/SectionType")
self.assertEqual(inst.section[1].text.status, "generated")
self.assertEqual(inst.section[1].title, "Mpther's Details")
self.assertEqual(inst.status, "final")
self.assertEqual(inst.text.status, "generated")
self.assertEqual(inst.title, "Discharge Summary (Neonatal Service)")
self.assertEqual(inst.type.coding[0].code, "78418-1")
self.assertEqual(inst.type.coding[0].display, "Neonatal perinatal medicine Discharge summary")
self.assertEqual(inst.type.coding[0].system, "http://loinc.org")
def testComposition2(self):
inst = self.instantiate_from("composition-example.json")
self.assertIsNotNone(inst, "Must have instantiated a Composition instance")
self.implComposition2(inst)
js = inst.as_json()
self.assertEqual("Composition", js["resourceType"])
inst2 = composition.Composition(js)
self.implComposition2(inst2)
def implComposition2(self, inst):
self.assertEqual(inst.attester[0].mode, "legal")
self.assertEqual(inst.attester[0].time.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.attester[0].time.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.category[0].coding[0].code, "LP173421-1")
self.assertEqual(inst.category[0].coding[0].display, "Report")
self.assertEqual(inst.category[0].coding[0].system, "http://loinc.org")
self.assertEqual(inst.confidentiality, "N")
self.assertEqual(inst.date.date, FHIRDate("2012-01-04T09:10:14Z").date)
self.assertEqual(inst.date.as_json(), "2012-01-04T09:10:14Z")
self.assertEqual(inst.event[0].code[0].coding[0].code, "HEALTHREC")
self.assertEqual(inst.event[0].code[0].coding[0].display, "health record")
self.assertEqual(inst.event[0].code[0].coding[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActCode")
self.assertEqual(inst.event[0].period.end.date, FHIRDate("2012-11-12").date)
self.assertEqual(inst.event[0].period.end.as_json(), "2012-11-12")
self.assertEqual(inst.event[0].period.start.date, FHIRDate("2010-07-18").date)
self.assertEqual(inst.event[0].period.start.as_json(), "2010-07-18")
self.assertEqual(inst.id, "example")
self.assertEqual(inst.identifier.system, "http://healthintersections.com.au/test")
self.assertEqual(inst.identifier.value, "1")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data")
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.relatesTo[0].code, "replaces")
self.assertEqual(inst.relatesTo[1].code, "appends")
self.assertEqual(inst.relatesTo[1].targetIdentifier.system, "http://example.org/fhir/NamingSystem/document-ids")
self.assertEqual(inst.relatesTo[1].targetIdentifier.value, "ABC123")
self.assertEqual(inst.section[0].code.coding[0].code, "11348-0")
self.assertEqual(inst.section[0].code.coding[0].display, "History of past illness Narrative")
self.assertEqual(inst.section[0].code.coding[0].system, "http://loinc.org")
self.assertEqual(inst.section[0].mode, "snapshot")
self.assertEqual(inst.section[0].orderedBy.coding[0].code, "event-date")
self.assertEqual(inst.section[0].orderedBy.coding[0].display, "Sorted by Event Date")
self.assertEqual(inst.section[0].orderedBy.coding[0].system, "http://terminology.hl7.org/CodeSystem/list-order")
self.assertEqual(inst.section[0].text.status, "generated")
self.assertEqual(inst.section[0].title, "History of present illness")
self.assertEqual(inst.section[1].code.coding[0].code, "10157-6")
self.assertEqual(inst.section[1].code.coding[0].display, "History of family member diseases Narrative")
self.assertEqual(inst.section[1].code.coding[0].system, "http://loinc.org")
self.assertEqual(inst.section[1].emptyReason.coding[0].code, "withheld")
self.assertEqual(inst.section[1].emptyReason.coding[0].display, "Information Withheld")
self.assertEqual(inst.section[1].emptyReason.coding[0].system, "http://terminology.hl7.org/CodeSystem/list-empty-reason")
self.assertEqual(inst.section[1].mode, "snapshot")
self.assertEqual(inst.section[1].text.status, "generated")
self.assertEqual(inst.section[1].title, "History of family member diseases")
self.assertEqual(inst.status, "final")
self.assertEqual(inst.text.status, "generated")
self.assertEqual(inst.title, "Consultation Note")
self.assertEqual(inst.type.coding[0].code, "11488-4")
self.assertEqual(inst.type.coding[0].display, "Consult note")
self.assertEqual(inst.type.coding[0].system, "http://loinc.org")
| true | true |
f729eaee359cb5f980f37f19c2c502894bfeb4e4 | 16,157 | py | Python | tests/quick_test.py | panchiittp/pyross | d5a455ae36a61e2fba29b30f1da774f1b284f1e2 | [
"MIT"
] | null | null | null | tests/quick_test.py | panchiittp/pyross | d5a455ae36a61e2fba29b30f1da774f1b284f1e2 | [
"MIT"
] | null | null | null | tests/quick_test.py | panchiittp/pyross | d5a455ae36a61e2fba29b30f1da774f1b284f1e2 | [
"MIT"
] | null | null | null | #!python
"""Unittesting for the pyross module. Run as python -m unittest pyross.test."""
import sys
#remove pwd from path that tries to import .pyx files
for i in sys.path:
if 'pyross' in i or i == '':
sys.path.remove(i)
# print(sys.path)
import pyross
import unittest
import inspect
import numpy as np
import scipy as sp
class DeterministicTest(unittest.TestCase):
"""testing deterministic.pyx."""
N = np.asarray([10000], dtype=np.float64)
M = 1
alpha = 0
beta = 0.0071
gIa = 0.008
gIs = 0.008
gI = 0.008
gE = 0.007
gIc = 0.1
gIhp= 0.1
gIsp= 0.1
gIcp= 0.1
gIh = 0.1
gA = 0
tE = 0
tIa = 0
tIs = 0
Tf = 100
Nf = 1000
fsa = 0
fh = 1
sa = 0
iaa = 0
hh = 0
cc = 0
mm = 0
tE = 0
tA = 0
tIa = 0
tIs = 0
kI = 1
kE = 1
k = 1
ep = 0
parameters = {'N': N, 'M': M, 'alpha': alpha,
'beta': beta, 'gIa': gIa, 'gIs': gIs,
'gIsp':gIsp,'gIhp':gIhp,'gIcp':gIcp,
'gI': gI, 'iaa': iaa,
'gE': gE, 'gA': gA, 'tE': tE,
'gIc': gIc, 'gIh': gIh, 'fh': fh,
'tIa': tIa, 'tIs': tIs, 'fsa': fsa,
'sa': sa, 'hh': hh, 'cc': cc,
'mm': mm, 'tA': tA, 'tE': tE,
'tIa': tIa, 'tIs': tIs, 'kI': kI,
'kE': kE, 'ep': ep, 'k': k}
def __init__(self, *args, **kwargs):
super(DeterministicTest, self).__init__(*args, **kwargs)
# self.parameters = self.parameters
def contactMatrix(self, t): return np.identity(self.M)
def test_decay(self):
"""
Exponential decay from infected to recovered. Paths agree within .1%.
"""
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
sim = SIR.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator='solve_ivp')
time_points = np.linspace(0, self.Tf, self.Nf)
exp_decay = sp.integrate.solve_ivp(lambda t, y: -self.gIs * y,
(0, self.Tf), self.N,
t_eval=time_points)
diff = (sim['X'][:, 2] - exp_decay.y)/self.N
self.assertTrue((diff < 0.001).all(), msg="paths differ > .1%")
def test_integrators(self):
"""
All integration methods produce paths which agree within .1%
"""
integrators = ['solve_ivp', 'odeint', 'odespy',
'odespy-rkf45', 'odespy-rk4']
paths = []
model = pyross.deterministic.SIR(self.parameters, self.M, self.N)
for integrator in integrators:
try:
data = model.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator=integrator)
except ImportError:
print(f"{integrator} is not installed, skipping...")
pass
paths.append(data['X'])
for i in range(len(paths)):
for j in range(len(paths)):
if i != j:
diff = (paths[i]-paths[j])/self.N
self.assertTrue((np.asarray(diff) < 0.001).all(),
msg=f"path {i} not equal to path {j}")
def test_SIRS(self):
"""Test to make sure SIRS collapses down to SIR"""
self.parameters['ep'] = 0
self.parameters['sa'] = 0
self.parameters['iaa'] = 0
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
SIRS = pyross.deterministic.SIRS(self.parameters, self.M, self.N)
SIRdata = SIR.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
SIRSdata = SIRS.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
self.assertTrue((SIRdata-SIRSdata[:, 0:3] < 0.001).all(),
msg="paths differ > .1%")
def test_init_models(self):
"""Test initialisation of deterministic models"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
def test_run_models(self):
"""Runs all deterministic models"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
traj_dict={}
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
x0 = np.array([*self.N, *np.ones(self.M),
*np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
class StochasticTest(unittest.TestCase):
"""testing stochastic.pyx"""
nloops=10
iinfec = 3000
Tf = 10
def __init__(self, *args, **kwargs):
super(StochasticTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.stochastic_models = dict(inspect.getmembers(pyross.stochastic,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all stochastic models"""
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
# x0 = np.array([*self.N, *np.ones(self.M),
# *np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))
# traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
def test_run_models(self):
"""Runs all stochastic models"""
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N + M*10)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*10,
*np.zeros(m.nClass -2)],
dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
def test_stochastic_mean_gillespie(self):
"""Runs stochastic models a few times and compares mean to
deterministic"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
# print(mS.kk)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
# print(name, np.sum(absdiff[:,:-1]))
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_mean_tau(self):
"""Runs stochastic models a few times and compares mean to
deterministic using tau leaping"""
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
# print(mS.kk)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping')['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
# print(name, np.sum(absdiff[:,:-1]))
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_integrators(self):
"""Compare tau leaping to Gillespie.
This will fail because there is a problem with SIkR
Also, difference is an order of magnitude greater than
Gillespie from the mean.
"""
self.nloops=10
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
gtraj = []
tautraj = []
for i in range(self.nloops):
gtraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='gillespie')['X'])
tautraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping', epsilon=1E-3)['X'])
gmean = np.sum(gtraj, axis=0)
taumean= np.sum(tautraj, axis=0)
absdiff = np.abs(gmean - taumean)/(N*self.Tf)
# print(name, np.sum(absdiff), np.shape(gmean), np.shape(taumean))
self.assertTrue(np.sum(absdiff)<.1, msg=f"{name} model disagreement")
class ControlTest(unittest.TestCase):
"""testing control.pyx"""
def __init__(self, *args, **kwargs):
super(ControlTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.control,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all control models"""
for name, model in self.control_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
class InferenceTest(unittest.TestCase):
"""testing inference.pyx"""
def __init__(self, *args, **kwargs):
super(InferenceTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.inference,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all inference models"""
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, fi, N, steps)
class ForecastTest(unittest.TestCase):
"""testing forcast.pyx"""
def __init__(self, *args, **kwargs):
super(ForecastTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.forecast,
inspect.isclass))
self.parameters['cov'] = np.identity(2)
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
"""Initializes all forcast models"""
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, Ni)
class UtilsPythonTest(unittest.TestCase):
"""Testing the minimization function in utils_python.py"""
def __init__(self, *args, **kwargs):
super(UtilsPythonTest, self).__init__(*args, **kwargs)
def test_minimization(self):
"""Test the minimization(...) function in utils_python.py with a few simple examples"""
# A simple example
f1 = lambda x, grad=0: 1 + np.linalg.norm(x)**2
# A multi-modal example
f2 = lambda x, grad=0: 1 + np.linalg.norm(x)**2 + 0.1*np.abs(np.sin(4*np.pi*np.linalg.norm(x)))
# Test global optimisation
guess = np.array([1.0, 1.0])
bounds = np.array([[-2.0, 2.0], [-2.0, 2.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, cma_random_seed=1, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, verbose=False, cma_random_seed=2)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
# Test local optimisation
guess = np.array([2.0, 2.0])
bounds = np.array([[-5.0, 5.0], [-5.0, 5.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=False, enable_local=True,
ftol=1e-5, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
# And now combined
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=True,
ftol=1e-5, global_ftol_factor=100, verbose=False, cma_random_seed=4)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
if __name__ == '__main__':
unittest.main()
| 43.432796 | 108 | 0.518351 |
import sys
for i in sys.path:
if 'pyross' in i or i == '':
sys.path.remove(i)
import pyross
import unittest
import inspect
import numpy as np
import scipy as sp
class DeterministicTest(unittest.TestCase):
N = np.asarray([10000], dtype=np.float64)
M = 1
alpha = 0
beta = 0.0071
gIa = 0.008
gIs = 0.008
gI = 0.008
gE = 0.007
gIc = 0.1
gIhp= 0.1
gIsp= 0.1
gIcp= 0.1
gIh = 0.1
gA = 0
tE = 0
tIa = 0
tIs = 0
Tf = 100
Nf = 1000
fsa = 0
fh = 1
sa = 0
iaa = 0
hh = 0
cc = 0
mm = 0
tE = 0
tA = 0
tIa = 0
tIs = 0
kI = 1
kE = 1
k = 1
ep = 0
parameters = {'N': N, 'M': M, 'alpha': alpha,
'beta': beta, 'gIa': gIa, 'gIs': gIs,
'gIsp':gIsp,'gIhp':gIhp,'gIcp':gIcp,
'gI': gI, 'iaa': iaa,
'gE': gE, 'gA': gA, 'tE': tE,
'gIc': gIc, 'gIh': gIh, 'fh': fh,
'tIa': tIa, 'tIs': tIs, 'fsa': fsa,
'sa': sa, 'hh': hh, 'cc': cc,
'mm': mm, 'tA': tA, 'tE': tE,
'tIa': tIa, 'tIs': tIs, 'kI': kI,
'kE': kE, 'ep': ep, 'k': k}
def __init__(self, *args, **kwargs):
super(DeterministicTest, self).__init__(*args, **kwargs)
def contactMatrix(self, t): return np.identity(self.M)
def test_decay(self):
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
sim = SIR.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator='solve_ivp')
time_points = np.linspace(0, self.Tf, self.Nf)
exp_decay = sp.integrate.solve_ivp(lambda t, y: -self.gIs * y,
(0, self.Tf), self.N,
t_eval=time_points)
diff = (sim['X'][:, 2] - exp_decay.y)/self.N
self.assertTrue((diff < 0.001).all(), msg="paths differ > .1%")
def test_integrators(self):
integrators = ['solve_ivp', 'odeint', 'odespy',
'odespy-rkf45', 'odespy-rk4']
paths = []
model = pyross.deterministic.SIR(self.parameters, self.M, self.N)
for integrator in integrators:
try:
data = model.simulate(np.zeros(1), np.zeros(1), self.N,
self.contactMatrix, self.Tf,
self.Nf, integrator=integrator)
except ImportError:
print(f"{integrator} is not installed, skipping...")
pass
paths.append(data['X'])
for i in range(len(paths)):
for j in range(len(paths)):
if i != j:
diff = (paths[i]-paths[j])/self.N
self.assertTrue((np.asarray(diff) < 0.001).all(),
msg=f"path {i} not equal to path {j}")
def test_SIRS(self):
self.parameters['ep'] = 0
self.parameters['sa'] = 0
self.parameters['iaa'] = 0
SIR = pyross.deterministic.SIR(self.parameters, self.M, self.N)
SIRS = pyross.deterministic.SIRS(self.parameters, self.M, self.N)
SIRdata = SIR.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
SIRSdata = SIRS.simulate(self.N, np.ones(1), np.zeros(1),
self.contactMatrix, self.Tf,
self.Nf)['X']
self.assertTrue((SIRdata-SIRSdata[:, 0:3] < 0.001).all(),
msg="paths differ > .1%")
def test_init_models(self):
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
def test_run_models(self):
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
traj_dict={}
for name, model in deterministic_models.items():
if name.startswith('S') and not 'Spp':
m = model(self.parameters, self.M, self.N)
x0 = np.array([*self.N, *np.ones(self.M),
*np.zeros(m.nClass -2)], dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
class StochasticTest(unittest.TestCase):
nloops=10
iinfec = 3000
Tf = 10
def __init__(self, *args, **kwargs):
super(StochasticTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.stochastic_models = dict(inspect.getmembers(pyross.stochastic,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
def test_run_models(self):
traj_dict={}
for name, model in self.stochastic_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N + M*10)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*10,
*np.zeros(m.nClass -2)],
dtype=np.float64).reshape((m.nClass,1))
traj_dict[name] = m.simulate(*x0, self.contactMatrix, 100, 100)
def test_stochastic_mean_gillespie(self):
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_mean_tau(self):
deterministic_models = dict(inspect.getmembers(pyross.deterministic,
inspect.isclass))
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
mD = deterministic_models[name](params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
trajectories = []
for i in range(self.nloops):
traj = mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping')['X']
trajectories.append(traj)
traj_mean = np.mean(trajectories, axis=0)[:-1]
mean = mD.simulate(*x0, self.contactMatrix, self.Tf, self.Tf)['X']
absdiff = np.abs(traj_mean -mean)/(N*self.Tf)
self.assertTrue(np.sum(absdiff[:,:-1])<0.01,
msg=f"{name} model disagreement")
def test_stochastic_integrators(self):
self.nloops=10
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
for name, model in self.stochastic_models.items():
if name.startswith('S'):
mS = model(params, M, N + M*self.iinfec)
x0 = np.array([*self.parameters['N'],
*np.ones(self.parameters['M'])*self.iinfec,
*np.zeros(mS.nClass -2)],
dtype=np.float64).reshape((mS.nClass,1))
gtraj = []
tautraj = []
for i in range(self.nloops):
gtraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='gillespie')['X'])
tautraj.append(mS.simulate(*x0, self.contactMatrix, self.Tf, self.Tf,
method='tau_leaping', epsilon=1E-3)['X'])
gmean = np.sum(gtraj, axis=0)
taumean= np.sum(tautraj, axis=0)
absdiff = np.abs(gmean - taumean)/(N*self.Tf)
self.assertTrue(np.sum(absdiff)<.1, msg=f"{name} model disagreement")
class ControlTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(ControlTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.control,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
for name, model in self.control_models.items():
if name.startswith('S'):
params, M, N = self.parameters, self.parameters['M'], self.parameters['N']
m = model(params, M, N)
class InferenceTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(InferenceTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.inference,
inspect.isclass))
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, fi, N, steps)
class ForecastTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(ForecastTest, self).__init__(*args, **kwargs)
self.parameters = DeterministicTest.parameters
self.control_models = dict(inspect.getmembers(pyross.forecast,
inspect.isclass))
self.parameters['cov'] = np.identity(2)
def contactMatrix(self, t): return np.identity(self.parameters['M'])
def test_init_models(self):
for name, model in self.control_models.items():
if name.startswith('S') and name != "SIR_type":
params, M, Ni = self.parameters, self.parameters['M'], self.parameters['N']
N = int(np.sum(Ni))
fi = Ni/N
steps = 1
m = model(params, M, Ni)
class UtilsPythonTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(UtilsPythonTest, self).__init__(*args, **kwargs)
def test_minimization(self):
f1 = lambda x, grad=0: 1 + np.linalg.norm(x)**2
f2 = lambda x, grad=0: 1 + np.linalg.norm(x)**2 + 0.1*np.abs(np.sin(4*np.pi*np.linalg.norm(x)))
guess = np.array([1.0, 1.0])
bounds = np.array([[-2.0, 2.0], [-2.0, 2.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, cma_random_seed=1, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=False,
ftol=1e-4, verbose=False, cma_random_seed=2)
self.assertTrue(np.abs(y - 1.0) < 1e-3)
guess = np.array([2.0, 2.0])
bounds = np.array([[-5.0, 5.0], [-5.0, 5.0]])
x, y = pyross.utils_python.minimization(f1, guess, bounds, enable_global=False, enable_local=True,
ftol=1e-5, verbose=False)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
x, y = pyross.utils_python.minimization(f2, guess, bounds, enable_global=True, enable_local=True,
ftol=1e-5, global_ftol_factor=100, verbose=False, cma_random_seed=4)
self.assertTrue(np.abs(y - 1.0) < 1e-4)
if __name__ == '__main__':
unittest.main()
| true | true |
f729ebdbc441f606cce6d4823d02a249f2b77337 | 1,260 | py | Python | test/metrics/android_startup_powrails.py | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | 3 | 2021-03-07T19:52:29.000Z | 2021-11-25T01:57:25.000Z | test/metrics/android_startup_powrails.py | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | 9 | 2019-12-30T02:56:16.000Z | 2020-12-22T07:05:04.000Z | test/metrics/android_startup_powrails.py | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | 15 | 2018-09-17T18:30:47.000Z | 2021-11-25T01:57:19.000Z | #!/usr/bin/python
# Copyright (C) 2018 The Android Open Source Project
#
# 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.
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import synth_common
trace = synth_common.create_trace()
trace.add_packet()
# Add Power Rails description for 3 rails.
trace.add_power_rails_desc(1, 'PR_1')
trace.add_power_rails_desc(2, 'PR_2')
trace.add_power_rails_desc(3, 'PR_3')
# Add data at ts = 5 ms.
trace.add_power_rails_data(5, 1, 12)
trace.add_power_rails_data(5, 2, 10)
trace.add_power_rails_data(5, 3, 8)
# Add data at ts = 6 ms.
trace.add_power_rails_data(6, 1, 50)
trace.add_power_rails_data(6, 2, 70)
trace.add_power_rails_data(6, 3, 15)
print(trace.trace.SerializeToString())
| 31.5 | 74 | 0.761905 |
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import synth_common
trace = synth_common.create_trace()
trace.add_packet()
trace.add_power_rails_desc(1, 'PR_1')
trace.add_power_rails_desc(2, 'PR_2')
trace.add_power_rails_desc(3, 'PR_3')
trace.add_power_rails_data(5, 1, 12)
trace.add_power_rails_data(5, 2, 10)
trace.add_power_rails_data(5, 3, 8)
trace.add_power_rails_data(6, 1, 50)
trace.add_power_rails_data(6, 2, 70)
trace.add_power_rails_data(6, 3, 15)
print(trace.trace.SerializeToString())
| true | true |
f729ed17f785ba9a429071f6f20dbd6ca0f95643 | 3,316 | py | Python | test6.py | rscinto/WeatherStation | df11d550f54e0a2a3964915f13482f76379f0c24 | [
"MIT"
] | null | null | null | test6.py | rscinto/WeatherStation | df11d550f54e0a2a3964915f13482f76379f0c24 | [
"MIT"
] | null | null | null | test6.py | rscinto/WeatherStation | df11d550f54e0a2a3964915f13482f76379f0c24 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
#
import RPi.GPIO as GPIO
from signal import pause
#import dht11
import math
#
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
#import subprocess
#
#import sys
import board
import pigpio
import DHT
import time
import datetime
# Raspberry Pi pin configuration:
RST = None # on the PiOLED this pin isnt used
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
# Initialize library.
disp.begin()
# Clear display.
disp.clear()
disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0
# Load default font.
font = ImageFont.load_default()
LED_red = 20
num_readings = 0
time_even = 0.0
time_odd = 0.0
time_difference = 0.0
temperature = 0.0
humidity = 0.0
sensor = DHT.DHT11
pi = pigpio.pi()
pin = 4 # Data - Pin 7 (BCM 4)
s = DHT.sensor(pi, pin, model = sensor)
#Magnet sensor
GPIO_PIN = 16
def setup():
GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location
GPIO.setwarnings(False)
GPIO.setup(LED_red,GPIO.OUT)
GPIO.setup(GPIO_PIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.add_event_detect(GPIO_PIN, GPIO.RISING, callback=outputFunction, bouncetime=100)
# function called when sensor is tripped
def outputFunction(null):
global num_readings
print("Sensor is blocked")
GPIO.output(LED_red,GPIO.HIGH)
num_readings += num_readings
def loop():
while True:
global temperature
global humidity
global GPIO_PIN
GPIO.output(LED_red,GPIO.LOW)
time.sleep(2)
timestamp, gpio, status, temperature, humidity = s.read() #read DHT device
# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)
# Write two lines of text.
draw.text((x, top), "Weather Station ", font=font, fill=255)
draw.text((x, top+8), "Temperature: C " + str(temperature), font=font, fill=255)
draw.text((x, top+16), "Wind Speed: kts ", font=font, fill=255)
draw.text((x, top+25), "Humidity: % " + str(humidity), font=font, fill=255)
# Display image.
disp.image(image)
disp.display()
def destroy():
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy() | 25.312977 | 103 | 0.646261 |
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import RPi.GPIO as GPIO
from signal import pause
import math
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import board
import pigpio
import DHT
import time
import datetime
RST = None
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
disp.begin()
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0,0,width,height), outline=0, fill=0)
padding = -2
top = padding
bottom = height-padding
x = 0
font = ImageFont.load_default()
LED_red = 20
num_readings = 0
time_even = 0.0
time_odd = 0.0
time_difference = 0.0
temperature = 0.0
humidity = 0.0
sensor = DHT.DHT11
pi = pigpio.pi()
pin = 4
s = DHT.sensor(pi, pin, model = sensor)
GPIO_PIN = 16
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LED_red,GPIO.OUT)
GPIO.setup(GPIO_PIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.add_event_detect(GPIO_PIN, GPIO.RISING, callback=outputFunction, bouncetime=100)
def outputFunction(null):
global num_readings
print("Sensor is blocked")
GPIO.output(LED_red,GPIO.HIGH)
num_readings += num_readings
def loop():
while True:
global temperature
global humidity
global GPIO_PIN
GPIO.output(LED_red,GPIO.LOW)
time.sleep(2)
timestamp, gpio, status, temperature, humidity = s.read()
draw.rectangle((0,0,width,height), outline=0, fill=0)
draw.text((x, top), "Weather Station ", font=font, fill=255)
draw.text((x, top+8), "Temperature: C " + str(temperature), font=font, fill=255)
draw.text((x, top+16), "Wind Speed: kts ", font=font, fill=255)
draw.text((x, top+25), "Humidity: % " + str(humidity), font=font, fill=255)
disp.image(image)
disp.display()
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
setup()
try:
loop()
except KeyboardInterrupt:
destroy() | true | true |
f729ed6fd28f976514f79ff059bea5c9cde24f99 | 956 | py | Python | tests/test.py | kagemeka/competitive-programming | c70fe481bcd518f507b885fc9234691d8ce63171 | [
"MIT"
] | 1 | 2021-07-11T03:20:10.000Z | 2021-07-11T03:20:10.000Z | tests/test.py | kagemeka/competitive-programming | c70fe481bcd518f507b885fc9234691d8ce63171 | [
"MIT"
] | 39 | 2021-07-10T05:21:09.000Z | 2021-12-15T06:10:12.000Z | tests/test.py | kagemeka/competitive-programming | c70fe481bcd518f507b885fc9234691d8ce63171 | [
"MIT"
] | null | null | null | import functools
import typing
class Accumulate:
@staticmethod
def __call__(
func: typing.Callable,
identity: int,
):
def fn(
a: typing.Iterable[int],
) -> int:
return functools.reduce(
func,
a,
identity,
)
return fn
T = typing.TypeVar('T')
def accumulate(
e: T,
) -> typing.Callable[
[typing.Callable[[T, T], T]],
typing.Callable[[typing.Iterable[T]], T],
]:
def decorate(
op: typing.Callable[[T, T], T],
) -> typing.Callable[[typing.Iterable[T]], T]:
import functools
def wrapped(a: typing.Iterable[T]) -> T:
return functools.reduce(op, a, e)
return wrapped
return decorate
@accumulate(0)
def xor(a: int, b: int) -> int:
return a ^ b
def main() -> typing.NoReturn:
print(xor((0, 1, 2, 4)))
if __name__ == '__main__':
main() | 18.384615 | 50 | 0.520921 | import functools
import typing
class Accumulate:
@staticmethod
def __call__(
func: typing.Callable,
identity: int,
):
def fn(
a: typing.Iterable[int],
) -> int:
return functools.reduce(
func,
a,
identity,
)
return fn
T = typing.TypeVar('T')
def accumulate(
e: T,
) -> typing.Callable[
[typing.Callable[[T, T], T]],
typing.Callable[[typing.Iterable[T]], T],
]:
def decorate(
op: typing.Callable[[T, T], T],
) -> typing.Callable[[typing.Iterable[T]], T]:
import functools
def wrapped(a: typing.Iterable[T]) -> T:
return functools.reduce(op, a, e)
return wrapped
return decorate
@accumulate(0)
def xor(a: int, b: int) -> int:
return a ^ b
def main() -> typing.NoReturn:
print(xor((0, 1, 2, 4)))
if __name__ == '__main__':
main() | true | true |
f729ee85fe98cf94b4dbc20ab1851bdb837e4c73 | 1,083 | py | Python | Configuration/Generator/python/PhotonJet_Pt_10_14TeV_TuneCUETP8M1_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | Configuration/Generator/python/PhotonJet_Pt_10_14TeV_TuneCUETP8M1_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | Configuration/Generator/python/PhotonJet_Pt_10_14TeV_TuneCUETP8M1_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
pythiaHepMCVerbosity = cms.untracked.bool(False),
maxEventsToPrint = cms.untracked.int32(0),
pythiaPylistVerbosity = cms.untracked.int32(0),
filterEfficiency = cms.untracked.double(1.0),
comEnergy = cms.double(14000.0),
PythiaParameters = cms.PSet(
pythia8CommonSettingsBlock,
pythia8CUEP8M1SettingsBlock,
processParameters = cms.vstring(
'PromptPhoton:all = on',
'PhaseSpace:pTHatMin = 10.',
),
parameterSets = cms.vstring('pythia8CommonSettings',
'pythia8CUEP8M1Settings',
'processParameters',
)
)
)
| 45.125 | 74 | 0.54386 | import FWCore.ParameterSet.Config as cms
from Configuration.Generator.Pythia8CommonSettings_cfi import *
from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *
generator = cms.EDFilter("Pythia8GeneratorFilter",
pythiaHepMCVerbosity = cms.untracked.bool(False),
maxEventsToPrint = cms.untracked.int32(0),
pythiaPylistVerbosity = cms.untracked.int32(0),
filterEfficiency = cms.untracked.double(1.0),
comEnergy = cms.double(14000.0),
PythiaParameters = cms.PSet(
pythia8CommonSettingsBlock,
pythia8CUEP8M1SettingsBlock,
processParameters = cms.vstring(
'PromptPhoton:all = on',
'PhaseSpace:pTHatMin = 10.',
),
parameterSets = cms.vstring('pythia8CommonSettings',
'pythia8CUEP8M1Settings',
'processParameters',
)
)
)
| true | true |
f729ef58649691ca9cf4d55e3e30024b565a869a | 1,897 | py | Python | dummy_2d_features.py | jhong93/vpd | 1ed3e8631c46e078ecb9a7756dba1f1c14aead5b | [
"BSD-3-Clause"
] | 7 | 2021-11-26T01:15:23.000Z | 2022-03-15T10:51:47.000Z | dummy_2d_features.py | jhong93/vpd | 1ed3e8631c46e078ecb9a7756dba1f1c14aead5b | [
"BSD-3-Clause"
] | 4 | 2022-01-15T09:46:00.000Z | 2022-02-05T07:10:18.000Z | dummy_2d_features.py | jhong93/vpd | 1ed3e8631c46e078ecb9a7756dba1f1c14aead5b | [
"BSD-3-Clause"
] | 1 | 2021-09-18T16:50:14.000Z | 2021-09-18T16:50:14.000Z | #!/usr/bin/env python3
"""
Convert COCO17 2D poses to dummy embeddings for 2D-VPD.
"""
import os
import argparse
import numpy as np
from tqdm import tqdm
from util.io import store_pickle, load_gz_json
from vipe_dataset.dataset_base import normalize_2d_skeleton
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('pose_dir', type=str)
parser.add_argument('-o', '--out_dir', type=str)
parser.add_argument('--no_flip', action='store_true')
return parser.parse_args()
def main(pose_dir, out_dir, no_flip):
for video_name in tqdm(sorted(os.listdir(pose_dir))):
if video_name.endswith('.json.gz'):
# Flat case
video_pose_path = os.path.join(pose_dir, video_name)
video_name = video_name.split('.json.gz')[0]
else:
# Nested case
video_pose_path = os.path.join(
pose_dir, video_name, 'coco_keypoints.json.gz')
if not os.path.exists(video_pose_path):
print('Not found:', video_pose_path)
continue
embs = []
for frame_num, pose_data in load_gz_json(video_pose_path):
raw_2d = np.array(pose_data[0][-1])
pose_2d = normalize_2d_skeleton(raw_2d, False, to_tensor=False)
emb = pose_2d[:, :2].flatten() # drop confidence column
meta = {'is_2d': True, 'kp_score': np.mean(pose_2d[:, 2] + 0.5).item()}
if not no_flip:
emb2 = normalize_2d_skeleton(
raw_2d, True, to_tensor=False)[:, :2].flatten()
emb = np.stack([emb, emb2])
embs.append((frame_num, emb, meta))
if out_dir is not None:
os.makedirs(out_dir, exist_ok=True)
store_pickle(os.path.join(out_dir, video_name + '.emb.pkl'), embs)
print('Done!')
if __name__ == '__main__':
main(**vars(get_args())) | 32.706897 | 83 | 0.614128 |
import os
import argparse
import numpy as np
from tqdm import tqdm
from util.io import store_pickle, load_gz_json
from vipe_dataset.dataset_base import normalize_2d_skeleton
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('pose_dir', type=str)
parser.add_argument('-o', '--out_dir', type=str)
parser.add_argument('--no_flip', action='store_true')
return parser.parse_args()
def main(pose_dir, out_dir, no_flip):
for video_name in tqdm(sorted(os.listdir(pose_dir))):
if video_name.endswith('.json.gz'):
video_pose_path = os.path.join(pose_dir, video_name)
video_name = video_name.split('.json.gz')[0]
else:
video_pose_path = os.path.join(
pose_dir, video_name, 'coco_keypoints.json.gz')
if not os.path.exists(video_pose_path):
print('Not found:', video_pose_path)
continue
embs = []
for frame_num, pose_data in load_gz_json(video_pose_path):
raw_2d = np.array(pose_data[0][-1])
pose_2d = normalize_2d_skeleton(raw_2d, False, to_tensor=False)
emb = pose_2d[:, :2].flatten()
meta = {'is_2d': True, 'kp_score': np.mean(pose_2d[:, 2] + 0.5).item()}
if not no_flip:
emb2 = normalize_2d_skeleton(
raw_2d, True, to_tensor=False)[:, :2].flatten()
emb = np.stack([emb, emb2])
embs.append((frame_num, emb, meta))
if out_dir is not None:
os.makedirs(out_dir, exist_ok=True)
store_pickle(os.path.join(out_dir, video_name + '.emb.pkl'), embs)
print('Done!')
if __name__ == '__main__':
main(**vars(get_args())) | true | true |
f729ef5be0ca6d131bb95c8b19e87d2238010156 | 3,299 | py | Python | dump-roasts.py | jglogan/roastime-data | cfd7bc7b85435225e9316d0aa00bf490b2f4b66f | [
"MIT"
] | 1 | 2021-12-14T21:24:47.000Z | 2021-12-14T21:24:47.000Z | dump-roasts.py | jglogan/roastime-data | cfd7bc7b85435225e9316d0aa00bf490b2f4b66f | [
"MIT"
] | null | null | null | dump-roasts.py | jglogan/roastime-data | cfd7bc7b85435225e9316d0aa00bf490b2f4b66f | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
import argparse
import csv
import datetime
import json
import os
import sys
roast_fields = [
'dateTime',
'uid',
'roastNumber',
'roastName',
'beanId',
'rating',
'serialNumber',
'firmware',
'hardware',
{'fields': ['ambient', 'ambientTemp'], 'mapped_field': 'ambient', 'type': float},
{'fields': ['humidity', 'roomHumidity'], 'mapped_field': 'humidity', 'type': float},
{'fields': ['weightGreen'], 'mapped_field': 'weightGreen', 'type': float},
{'fields': ['weightRoasted'], 'mapped_field': 'weightRoasted', 'type': float},
'preheatTemperature',
'beanChargeTemperature',
'beanDropTemperature',
'drumChargeTemperature',
'drumDropTemperature',
'totalRoastTime',
'sampleRate',
'roastStartIndex',
'indexYellowingStart',
'indexFirstCrackStart',
'indexFirstCrackEnd',
'indexSecondCrackStart',
'indexSecondCrackEnd',
'roastEndIndex',
]
def set_roast_column(roast_json, roast_columns, roast_field):
if 'fields' in roast_field:
for field in roast_field['fields']:
if field in roast_json:
roast_columns[roast_field['mapped_field']] = roast_field['type'](roast_json[field])
return
roast_columns[roast_field['mapped_field']] = ''
return
roast_columns[roast_field] = roast_json.get(roast_field, None)
def load_roast(roast_pathname):
sys.stderr.write(f'loading {roast_pathname}\n')
with open(roast_pathname, 'r', encoding='utf-8') as roast_file:
roast_json = json.load(roast_file)
roast = {}
for roast_field in roast_fields:
set_roast_column(roast_json, roast, roast_field)
roast['date'] = datetime.datetime.fromtimestamp(roast['dateTime'] / 1000).strftime('%Y-%m-%d')
roast['time'] = datetime.datetime.fromtimestamp(roast['dateTime'] / 1000).strftime('%H:%M:%S')
return roast
def load_roasts(roast_dirname):
roasts = []
for roast_filename in os.listdir(roast_dirname):
roast = load_roast(os.path.join(roast_dirname, roast_filename))
roasts.append(roast)
return roasts
def get_fields():
return [f if 'mapped_field' not in f else f['mapped_field'] for f in roast_fields]
def main():
default_fields = ['date', 'time', 'beanId', 'weightGreen']
valid_fields = ', '.join(get_fields())
epilog = f'Valid field names are: {valid_fields}'
parser = argparse.ArgumentParser(description='Convert RoasTime roast data to CSV.', epilog=epilog)
parser.add_argument('-f', '--fields', help=f'comma-separated list of fields (default is {",".join(default_fields)})')
parser.add_argument('output_file', metavar='PATH', help='CSV file name')
roast_path = os.path.join(os.path.expanduser("~"), "Library/Application Support/roast-time/roasts")
args = parser.parse_args()
roasts = load_roasts(roast_path)
fields = default_fields if args.fields is None else args.fields.split(",")
with open(args.output_file, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(fields)
for roast in roasts:
writer.writerow([roast[field] for field in fields])
if __name__ == "__main__":
rv = main()
sys.exit(rv)
| 33.323232 | 121 | 0.658381 |
import argparse
import csv
import datetime
import json
import os
import sys
roast_fields = [
'dateTime',
'uid',
'roastNumber',
'roastName',
'beanId',
'rating',
'serialNumber',
'firmware',
'hardware',
{'fields': ['ambient', 'ambientTemp'], 'mapped_field': 'ambient', 'type': float},
{'fields': ['humidity', 'roomHumidity'], 'mapped_field': 'humidity', 'type': float},
{'fields': ['weightGreen'], 'mapped_field': 'weightGreen', 'type': float},
{'fields': ['weightRoasted'], 'mapped_field': 'weightRoasted', 'type': float},
'preheatTemperature',
'beanChargeTemperature',
'beanDropTemperature',
'drumChargeTemperature',
'drumDropTemperature',
'totalRoastTime',
'sampleRate',
'roastStartIndex',
'indexYellowingStart',
'indexFirstCrackStart',
'indexFirstCrackEnd',
'indexSecondCrackStart',
'indexSecondCrackEnd',
'roastEndIndex',
]
def set_roast_column(roast_json, roast_columns, roast_field):
if 'fields' in roast_field:
for field in roast_field['fields']:
if field in roast_json:
roast_columns[roast_field['mapped_field']] = roast_field['type'](roast_json[field])
return
roast_columns[roast_field['mapped_field']] = ''
return
roast_columns[roast_field] = roast_json.get(roast_field, None)
def load_roast(roast_pathname):
sys.stderr.write(f'loading {roast_pathname}\n')
with open(roast_pathname, 'r', encoding='utf-8') as roast_file:
roast_json = json.load(roast_file)
roast = {}
for roast_field in roast_fields:
set_roast_column(roast_json, roast, roast_field)
roast['date'] = datetime.datetime.fromtimestamp(roast['dateTime'] / 1000).strftime('%Y-%m-%d')
roast['time'] = datetime.datetime.fromtimestamp(roast['dateTime'] / 1000).strftime('%H:%M:%S')
return roast
def load_roasts(roast_dirname):
roasts = []
for roast_filename in os.listdir(roast_dirname):
roast = load_roast(os.path.join(roast_dirname, roast_filename))
roasts.append(roast)
return roasts
def get_fields():
return [f if 'mapped_field' not in f else f['mapped_field'] for f in roast_fields]
def main():
default_fields = ['date', 'time', 'beanId', 'weightGreen']
valid_fields = ', '.join(get_fields())
epilog = f'Valid field names are: {valid_fields}'
parser = argparse.ArgumentParser(description='Convert RoasTime roast data to CSV.', epilog=epilog)
parser.add_argument('-f', '--fields', help=f'comma-separated list of fields (default is {",".join(default_fields)})')
parser.add_argument('output_file', metavar='PATH', help='CSV file name')
roast_path = os.path.join(os.path.expanduser("~"), "Library/Application Support/roast-time/roasts")
args = parser.parse_args()
roasts = load_roasts(roast_path)
fields = default_fields if args.fields is None else args.fields.split(",")
with open(args.output_file, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(fields)
for roast in roasts:
writer.writerow([roast[field] for field in fields])
if __name__ == "__main__":
rv = main()
sys.exit(rv)
| true | true |
f729ef60b68c40e555be435faed97dbc1fd4116d | 12,824 | py | Python | owtf/plugin/plugin_params.py | alienus/owtf | b6d81fac83c324c2b8c6fe2a974c036881c1fcd0 | [
"BSD-3-Clause"
] | null | null | null | owtf/plugin/plugin_params.py | alienus/owtf | b6d81fac83c324c2b8c6fe2a974c036881c1fcd0 | [
"BSD-3-Clause"
] | null | null | null | owtf/plugin/plugin_params.py | alienus/owtf | b6d81fac83c324c2b8c6fe2a974c036881c1fcd0 | [
"BSD-3-Clause"
] | null | null | null | """
owtf.plugin.plugin_params.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Manage parameters to the plugins
"""
import logging
from collections import defaultdict
from owtf.config import config_handler
from owtf.db.database import get_scoped_session
from owtf.managers.error import add_error
from owtf.utils.error import abort_framework
from owtf.utils.logger import logger
from owtf.utils.strings import merge_dicts
class PluginParams(object):
def __init__(self, options):
self.init = False
self.no_args = []
self.logger = logger
self.session = get_scoped_session()
self.logger.setup_logging()
def process_args(self):
"""Process args
:return: True if run is successful
:rtype: `bool`
"""
self.args = defaultdict(list)
for arg in self.raw_args:
if 'O' == arg:
continue
chunks = arg.split('=')
if len(chunks) < 2:
add_error(self.session, "USER ERROR: %s arguments should be in NAME=VALUE format" % str(chunks), 'user')
return False
arg_name = chunks[0]
try:
arg_val = arg.replace(arg_name, '')[1:]
except ValueError:
add_error(self.session, "USER ERROR: %s arguments should be in NAME=VALUE format" % str(arg_name), 'user')
return False
self.args[arg_name] = arg_val
return True
def list_args(self, args, mandatory=True):
"""List of available arguments
:param args: Args
:type args: `dict`
:param mandatory: True/false if mandatory to set
:type mandatory: `bool`
:return: None
:rtype: None
"""
logging.info("") # Newline
if mandatory:
logging.info("mandatory parameters:")
else:
logging.info("Optional parameters:")
for arg_name, arg_description in list(args.items()):
if arg_description is None:
arg_description = ""
logging.info("- %s%s%s" % (arg_name, (30 - len(arg_name)) * '_', arg_description.replace('\n', "\n")))
def get_args_example(self, full_args_list):
"""Arguments for an example plugin
:param full_args_list: Full list of args
:type full_args_list: `dict`
:return: Padded example
:rtype: `str`
"""
args_str = []
for key, value in list(merge_dicts(full_args_list['mandatory'], full_args_list['Optional']).items()):
args_str.append(key)
pad = '=? '
return pad.join(args_str) + pad
def show_param_info(self, full_args_list, plugin):
"""Show parameter info for a plugin
:param full_args_list: Full args list
:type full_args_list: `dict`
:param plugin: Plugin
:type plugin: `dict`
:return: None
:rtype: None
"""
logging.info("\nInformation for %s" % self.show_plugin(plugin))
logging.info("\nDescription: %s" % str(full_args_list['Description']))
self.list_args(full_args_list['mandatory'], True)
if len(full_args_list['Optional']) > 0:
self.list_args(full_args_list['Optional'], False)
logging.info("\nUsage: %s\n" % self.get_args_example(full_args_list))
abort_framework("User is only viewing options, exiting")
def show_plugin(self, plugin):
"""Show plugin info
:param plugin: Plugin dict
:type plugin: `dict`
:return: Formatted plugin string
:rtype: `str`
"""
return "plugin: {0}/{1}".format(plugin['type'], plugin['file'])
def default_arg_from_config(self, args, arg_name, settings_list):
"""Get default args from config
:param args: args list
:type args: `dict`
:param arg_name: Name of arg to fetch
:type arg_name: `str`
:param settings_list: List of settings
:type settings_list: `list`
:return: True if run is successful
:rtype: `bool`
"""
default_order_str = " (Default order is: %s)" % str(settings_list)
for setting in settings_list:
if config_handler.is_set(setting): # argument is set in config
args[arg_name] = config_handler.get_val(setting)
logging.info("default not passed '%s' to '%s'%s" % (arg_name, str(args[arg_name]), default_order_str))
return True
logging.info("Could not default not passed: '%s'%s" % (arg_name, default_order_str))
return False
def get_arg_list(self, session, arg_list, plugin, mandatory=True):
"""Get args list
:param arg_list: available args
:type arg_list: `dict`
:param plugin: Plugin info
:type plugin: `dict`
:param mandatory: Mandatory to list?
:type mandatory: `bool`
:return: available args for plugins
:rtype: `dict`
"""
if not self.init:
self.init = True
if not self.process_args(): # Process Passed arguments the first time only
return self.ret_arg_error({}, plugin) # Abort processing (invalid data)
args = {}
for arg_name in arg_list:
if arg_name not in self.args:
config_default_order = ["%s_%s_%s" % (plugin['code'], plugin['type'], arg_name),
'%s_%s' % (plugin['code'], arg_name), arg_name]
default = self.default_arg_from_config(args, arg_name, config_default_order)
if default or mandatory is False:
# The Parameter has been defaulted, must skip loop to avoid assignment at the bottom or
# argument is optional = ok to skip
continue
add_error(session, "USER ERROR: %s requires argument: '%s'" % (self.show_plugin(plugin), arg_name),
'user')
return self.ret_arg_error({}, plugin) # Abort processing (invalid data)
args[arg_name] = self.args[arg_name]
return args
def get_arg_error(self, plugin):
"""Set arg error
:param plugin: Plugin dict
:type plugin: `dict`
:return: Argument error for a plugin
:rtype: `bool`
"""
return plugin['argError']
def set_arg_error(self, plugin, error=True):
"""Set arg error for a plugin
:param plugin: Plugin dict
:type plugin: `dict`
:param error: Error or not
:type error: `bool`
:return: None
:rtype: None
"""
plugin['argError'] = error
def ret_arg_error(self, return_val, plugin):
"""Returns the arg error for a plugin
:param return_val: The return value
:type return_val: `bools`
:param plugin: Plugin dict
:type plugin: `dict`
:return: return val
:rtype: `str`
"""
self.set_arg_error(plugin, True)
return return_val
def check_arg_list(self, full_args_list, plugin):
"""Check args list for a plugin
:param full_args_list: Full args list
:type full_args_list: `dict`
:param plugin: Plugin dict
:type plugin: `dict`
:return: True if run successful
:rtype: `bool`
"""
if ('Mandatory' not in full_args_list) or ('Optional' not in full_args_list):
add_error("OWTF PLUGIN BUG: %s requires declared Mandatory and Optional arguments" %
self.show_plugin(plugin))
return self.ret_arg_error(True, plugin)
if 'Description' not in full_args_list:
add_error("OWTF PLUGIN BUG: %s requires a Description" % self.show_plugin(plugin))
return self.ret_arg_error(False, plugin)
return True
def set_args_basic(self, all_args, plugin):
"""Set basic required args
:param all_args: All available args
:type all_args: `dict`
:param plugin: Plugin dict
:type plugin: `dict`
:return: Replaced args list
:rtype: `list`
"""
if not all_args:
return self.no_args
args_str = []
for arg_name, arg_val in list(all_args.items()):
args_str.append(arg_name + "=" + str(self.args[arg_name]))
all_args[arg_name] = arg_val
plugin['args'] = ' '.join(args_str) # Record arguments in plugin dictionary
return [all_args]
def set_config(self, args):
"""Set config for args
:param args: Args to override
:type args: `dict`
:return: None
:rtype: None
"""
for arg_name, arg_val in list(args.items()):
logging.info("Overriding configuration setting '_%s' with value %s.." % (arg_name, str(arg_val)))
config_handler.set_general_val('string', '_%s' % arg_name, arg_val) # Pre-pend "_" to avoid naming collisions
def get_permutations(self, args):
"""Get permutations from args
:param args: Available args
:type args: `dict`
:return: List of permutations
:rtype: `defaultdict`
"""
permutations = defaultdict(list)
if 'REPEAT_DELIM' not in args:
return permutations # No permutations
separator = args['REPEAT_DELIM']
for arg_name, arg_val in list(args.items()):
if arg_name == 'REPEAT_DELIM':
continue # The repeat delimiter is not considered a permutation: It's the permutation delimiter :)
chunks = arg_val.split(separator)
if len(chunks) > 1:
permutations[arg_name] = chunks
return permutations
def set_permutation(self, arg_name, permutations, permutation_list):
"""Add a particular permutation for an arg
:param arg_name: Arg to replace
:type arg_name: `str`
:param permutations: List of permutations
:type permutations: `list`
:param permutation_list: Permutation list
:type permutation_list: `list`
:return: None
:rtype: None
"""
for i in range(0, len(permutation_list)):
count = 0
for perm in permutations:
perm_args = permutation_list[i].copy() # 1st copy by value original arguments
perm_args[arg_name] = perm # 2nd override argument with permutation
if count == 0: # Modify 1st existing record with permutation
permutation_list[i] = perm_args
else:
permutation_list.append(perm_args) # 3rd store each subsequent permutation as a different set of args
count += 1
def set_args(self, all_args, plugin):
"""Set args from all args for a plugin
:param all_args: All available args
:type all_args: `dict`
:param plugin: Plugin
:type plugin: `dict`
:return: List of permutations
:rtype: `list`
"""
arg_list = self.set_args_basic(all_args, plugin)
if not arg_list:
return arg_list # Nothing to do
args = arg_list[0]
permutation_list = [args]
for arg_name, permutations in list(self.get_permutations(args).items()):
self.set_permutation(arg_name, permutations, permutation_list)
if not permutation_list:
return arg_list # No permutations, return original arguments
return permutation_list
def get_args(self, session, full_args_list, plugin):
"""Get args from a full list for a plugin
:param full_args_list: available args
:type full_args_list: `dict`
:param plugin: Plugin
:type plugin: `dict`
:return: None
:rtype: None
"""
self.set_arg_error(plugin, False)
if not self.check_arg_list(full_args_list, plugin):
return self.no_args
if 'O' in self.raw_args: # To view available options
self.show_param_info(full_args_list, plugin)
return self.no_args # Abort processing, just showing options
mandatory = self.get_arg_list(session, full_args_list['Mandatory'], plugin, True)
optional = self.get_arg_list(session, full_args_list['Optional'], plugin, False)
if self.get_arg_error(plugin):
logging.info("")
logging.warn("ERROR: Aborting argument processing, please correct the errors above and try again")
logging.info("")
return self.no_args # Error processing arguments, must abort processing
all_args = merge_dicts(mandatory, optional)
return self.set_args(all_args, plugin)
plugin_params = PluginParams(options={})
| 37.497076 | 122 | 0.592171 | import logging
from collections import defaultdict
from owtf.config import config_handler
from owtf.db.database import get_scoped_session
from owtf.managers.error import add_error
from owtf.utils.error import abort_framework
from owtf.utils.logger import logger
from owtf.utils.strings import merge_dicts
class PluginParams(object):
def __init__(self, options):
self.init = False
self.no_args = []
self.logger = logger
self.session = get_scoped_session()
self.logger.setup_logging()
def process_args(self):
self.args = defaultdict(list)
for arg in self.raw_args:
if 'O' == arg:
continue
chunks = arg.split('=')
if len(chunks) < 2:
add_error(self.session, "USER ERROR: %s arguments should be in NAME=VALUE format" % str(chunks), 'user')
return False
arg_name = chunks[0]
try:
arg_val = arg.replace(arg_name, '')[1:]
except ValueError:
add_error(self.session, "USER ERROR: %s arguments should be in NAME=VALUE format" % str(arg_name), 'user')
return False
self.args[arg_name] = arg_val
return True
def list_args(self, args, mandatory=True):
logging.info("")
if mandatory:
logging.info("mandatory parameters:")
else:
logging.info("Optional parameters:")
for arg_name, arg_description in list(args.items()):
if arg_description is None:
arg_description = ""
logging.info("- %s%s%s" % (arg_name, (30 - len(arg_name)) * '_', arg_description.replace('\n', "\n")))
def get_args_example(self, full_args_list):
args_str = []
for key, value in list(merge_dicts(full_args_list['mandatory'], full_args_list['Optional']).items()):
args_str.append(key)
pad = '=? '
return pad.join(args_str) + pad
def show_param_info(self, full_args_list, plugin):
logging.info("\nInformation for %s" % self.show_plugin(plugin))
logging.info("\nDescription: %s" % str(full_args_list['Description']))
self.list_args(full_args_list['mandatory'], True)
if len(full_args_list['Optional']) > 0:
self.list_args(full_args_list['Optional'], False)
logging.info("\nUsage: %s\n" % self.get_args_example(full_args_list))
abort_framework("User is only viewing options, exiting")
def show_plugin(self, plugin):
return "plugin: {0}/{1}".format(plugin['type'], plugin['file'])
def default_arg_from_config(self, args, arg_name, settings_list):
default_order_str = " (Default order is: %s)" % str(settings_list)
for setting in settings_list:
if config_handler.is_set(setting):
args[arg_name] = config_handler.get_val(setting)
logging.info("default not passed '%s' to '%s'%s" % (arg_name, str(args[arg_name]), default_order_str))
return True
logging.info("Could not default not passed: '%s'%s" % (arg_name, default_order_str))
return False
def get_arg_list(self, session, arg_list, plugin, mandatory=True):
if not self.init:
self.init = True
if not self.process_args():
return self.ret_arg_error({}, plugin)
args = {}
for arg_name in arg_list:
if arg_name not in self.args:
config_default_order = ["%s_%s_%s" % (plugin['code'], plugin['type'], arg_name),
'%s_%s' % (plugin['code'], arg_name), arg_name]
default = self.default_arg_from_config(args, arg_name, config_default_order)
if default or mandatory is False:
continue
add_error(session, "USER ERROR: %s requires argument: '%s'" % (self.show_plugin(plugin), arg_name),
'user')
return self.ret_arg_error({}, plugin)
args[arg_name] = self.args[arg_name]
return args
def get_arg_error(self, plugin):
return plugin['argError']
def set_arg_error(self, plugin, error=True):
plugin['argError'] = error
def ret_arg_error(self, return_val, plugin):
self.set_arg_error(plugin, True)
return return_val
def check_arg_list(self, full_args_list, plugin):
if ('Mandatory' not in full_args_list) or ('Optional' not in full_args_list):
add_error("OWTF PLUGIN BUG: %s requires declared Mandatory and Optional arguments" %
self.show_plugin(plugin))
return self.ret_arg_error(True, plugin)
if 'Description' not in full_args_list:
add_error("OWTF PLUGIN BUG: %s requires a Description" % self.show_plugin(plugin))
return self.ret_arg_error(False, plugin)
return True
def set_args_basic(self, all_args, plugin):
if not all_args:
return self.no_args
args_str = []
for arg_name, arg_val in list(all_args.items()):
args_str.append(arg_name + "=" + str(self.args[arg_name]))
all_args[arg_name] = arg_val
plugin['args'] = ' '.join(args_str)
return [all_args]
def set_config(self, args):
for arg_name, arg_val in list(args.items()):
logging.info("Overriding configuration setting '_%s' with value %s.." % (arg_name, str(arg_val)))
config_handler.set_general_val('string', '_%s' % arg_name, arg_val)
def get_permutations(self, args):
permutations = defaultdict(list)
if 'REPEAT_DELIM' not in args:
return permutations
separator = args['REPEAT_DELIM']
for arg_name, arg_val in list(args.items()):
if arg_name == 'REPEAT_DELIM':
continue
chunks = arg_val.split(separator)
if len(chunks) > 1:
permutations[arg_name] = chunks
return permutations
def set_permutation(self, arg_name, permutations, permutation_list):
for i in range(0, len(permutation_list)):
count = 0
for perm in permutations:
perm_args = permutation_list[i].copy() # 1st copy by value original arguments
perm_args[arg_name] = perm # 2nd override argument with permutation
if count == 0: # Modify 1st existing record with permutation
permutation_list[i] = perm_args
else:
permutation_list.append(perm_args) # 3rd store each subsequent permutation as a different set of args
count += 1
def set_args(self, all_args, plugin):
arg_list = self.set_args_basic(all_args, plugin)
if not arg_list:
return arg_list # Nothing to do
args = arg_list[0]
permutation_list = [args]
for arg_name, permutations in list(self.get_permutations(args).items()):
self.set_permutation(arg_name, permutations, permutation_list)
if not permutation_list:
return arg_list # No permutations, return original arguments
return permutation_list
def get_args(self, session, full_args_list, plugin):
self.set_arg_error(plugin, False)
if not self.check_arg_list(full_args_list, plugin):
return self.no_args
if 'O' in self.raw_args: # To view available options
self.show_param_info(full_args_list, plugin)
return self.no_args # Abort processing, just showing options
mandatory = self.get_arg_list(session, full_args_list['Mandatory'], plugin, True)
optional = self.get_arg_list(session, full_args_list['Optional'], plugin, False)
if self.get_arg_error(plugin):
logging.info("")
logging.warn("ERROR: Aborting argument processing, please correct the errors above and try again")
logging.info("")
return self.no_args # Error processing arguments, must abort processing
all_args = merge_dicts(mandatory, optional)
return self.set_args(all_args, plugin)
plugin_params = PluginParams(options={})
| true | true |
f729ef684ba87ce3a349558d7e959d1f2d28e025 | 9,264 | py | Python | stonesoup/simulator/simple.py | JPompeus/Stone-Soup | 030c60aaf5ff92d7bb53f06e350c0bf58c9af037 | [
"MIT"
] | null | null | null | stonesoup/simulator/simple.py | JPompeus/Stone-Soup | 030c60aaf5ff92d7bb53f06e350c0bf58c9af037 | [
"MIT"
] | 4 | 2020-03-10T13:51:00.000Z | 2020-03-23T12:38:24.000Z | stonesoup/simulator/simple.py | JPompeus/Stone-Soup | 030c60aaf5ff92d7bb53f06e350c0bf58c9af037 | [
"MIT"
] | 1 | 2019-12-09T14:33:09.000Z | 2019-12-09T14:33:09.000Z | # -*- coding: utf-8 -*-
import datetime
import numpy as np
from ..base import Property
from ..models.measurement import MeasurementModel
from ..models.transition import TransitionModel
from ..reader import GroundTruthReader
from ..types.detection import TrueDetection, Clutter
from ..types.groundtruth import GroundTruthPath, GroundTruthState
from ..types.numeric import Probability
from ..types.state import GaussianState, State
from .base import DetectionSimulator, GroundTruthSimulator
from stonesoup.buffered_generator import BufferedGenerator
class SingleTargetGroundTruthSimulator(GroundTruthSimulator):
"""Target simulator that produces a single target"""
transition_model = Property(
TransitionModel, doc="Transition Model used as propagator for track.")
initial_state = Property(
State,
doc="Initial state to use to generate ground truth")
timestep = Property(
datetime.timedelta,
default=datetime.timedelta(seconds=1),
doc="Time step between each state. Default one second.")
number_steps = Property(
int, default=100, doc="Number of time steps to run for")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@BufferedGenerator.generator_method
def groundtruth_paths_gen(self):
time = self.initial_state.timestamp or datetime.datetime.now()
gttrack = GroundTruthPath([
GroundTruthState(self.initial_state.state_vector, timestamp=time,
metadata={"index": self.index})])
yield time, {gttrack}
for _ in range(self.number_steps - 1):
time += self.timestep
# Move track forward
trans_state_vector = self.transition_model.function(
gttrack[-1].state_vector,
time_interval=self.timestep)
gttrack.append(GroundTruthState(
trans_state_vector, timestamp=time,
metadata={"index": self.index}))
yield time, {gttrack}
class SwitchOneTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):
"""Target simulator that produces a single target. This target switches
between multiple transition models based on a markov matrix
(:attr:`model_probs`)"""
transition_models = Property(
[TransitionModel], doc="List of transition models to be used, ensure\
that they all have the same dimensions.")
model_probs = Property([float], doc="A matrix of probabilities.\
The element in the ith row and the jth column is the probability of\
switching from the ith transition model in :attr:`transition_models`\
to the jth")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@property
def transition_model(self):
self.index = np.random.choice(range(0, len(self.transition_models)),
p=self.model_probs[self.index])
return self.transition_models[self.index]
class MultiTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):
"""Target simulator that produces multiple targets.
Targets are created and destroyed randomly, as defined by the birth rate
and death probability."""
transition_model = Property(
TransitionModel, doc="Transition Model used as propagator for track.")
initial_state = Property(
GaussianState,
doc="Initial state to use to generate states")
birth_rate = Property(
float, default=1.0, doc="Rate at which tracks are born. Expected "
"number of occurrences (λ) in Poisson distribution. Default 1.0.")
death_probability = Property(
Probability, default=0.1,
doc="Probability of track dying in each time step. Default 0.1.")
@BufferedGenerator.generator_method
def groundtruth_paths_gen(self):
groundtruth_paths = set()
time = self.initial_state.timestamp or datetime.datetime.now()
for _ in range(self.number_steps):
# Random drop tracks
groundtruth_paths.difference_update(
gttrack
for gttrack in groundtruth_paths.copy()
if np.random.rand() <= self.death_probability)
# Move tracks forward
for gttrack in groundtruth_paths:
self.index = gttrack[-1].metadata.get("index")
trans_state_vector = self.transition_model.function(
gttrack[-1].state_vector,
time_interval=self.timestep)
gttrack.append(GroundTruthState(
trans_state_vector, timestamp=time,
metadata={"index": self.index}))
# Random create
for _ in range(np.random.poisson(self.birth_rate)):
self.index = 0
gttrack = GroundTruthPath()
gttrack.append(GroundTruthState(
self.initial_state.state_vector +
np.sqrt(self.initial_state.covar) @
np.random.randn(self.initial_state.ndim, 1),
timestamp=time, metadata={"index": self.index}))
groundtruth_paths.add(gttrack)
yield time, groundtruth_paths
time += self.timestep
class SwitchMultiTargetGroundTruthSimulator(MultiTargetGroundTruthSimulator):
"""Functions identically to :class:`~.MultiTargetGroundTruthSimulator`,
but has the transition model switching ability from
:class:`.SwitchOneTargetGroundTruthSimulator`"""
transition_models = Property(
[TransitionModel], doc="List of transition models to be used, ensure\
that they all have the same dimensions.")
model_probs = Property([float], doc="A matrix of probabilities.\
The element in the ith row and the jth column is the probability of\
switching from the ith transition model in :attr:`transition_models`\
to the jth")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@property
def transition_model(self):
self.index = np.random.choice(range(0, len(self.transition_models)),
p=self.model_probs[self.index])
return self.transition_models[self.index]
class SimpleDetectionSimulator(DetectionSimulator):
"""A simple detection simulator.
Parameters
----------
groundtruth : GroundTruthReader
Source of ground truth tracks used to generate detections for.
measurement_model : MeasurementModel
Measurement model used in generating detections.
"""
groundtruth = Property(GroundTruthReader)
measurement_model = Property(MeasurementModel)
meas_range = Property(np.ndarray)
detection_probability = Property(Probability, default=0.9)
clutter_rate = Property(float, default=2.0)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.real_detections = set()
self.clutter_detections = set()
self.index = 0
@property
def clutter_spatial_density(self):
"""returns the clutter spatial density of the measurement space - num
clutter detections per unit volume per timestep"""
return self.clutter_rate/np.prod(np.diff(self.meas_range))
@BufferedGenerator.generator_method
def detections_gen(self):
for time, tracks in self.groundtruth:
self.real_detections.clear()
self.clutter_detections.clear()
for track in tracks:
self.index = track[-1].metadata.get("index")
if np.random.rand() < self.detection_probability:
detection = TrueDetection(
self.measurement_model.function(
track[-1].state_vector),
timestamp=track[-1].timestamp,
groundtruth_path=track)
detection.clutter = False
self.real_detections.add(detection)
# generate clutter
for _ in range(np.random.poisson(self.clutter_rate)):
detection = Clutter(
np.random.rand(self.measurement_model.ndim_meas, 1) *
np.diff(self.meas_range) + self.meas_range[:, :1],
timestamp=time)
self.clutter_detections.add(detection)
yield time, self.real_detections | self.clutter_detections
class SwitchDetectionSimulator(SimpleDetectionSimulator):
"""Functions identically as the :class:`SimpleDetectionSimulator`, but for
ground truth paths formed using multiple transition models it allows the
user to assign a detection probability to each transition models.
For example, if you wanted a higher detection probability when the
simulated object makes a turn"""
detection_probabilities = Property([Probability], doc="List of\
probabilities that correspond to the detection probability of the\
simulated object while undergoing each transition model")
@property
def detection_probability(self):
return self.detection_probabilities[self.index]
| 40.454148 | 78 | 0.655117 |
import datetime
import numpy as np
from ..base import Property
from ..models.measurement import MeasurementModel
from ..models.transition import TransitionModel
from ..reader import GroundTruthReader
from ..types.detection import TrueDetection, Clutter
from ..types.groundtruth import GroundTruthPath, GroundTruthState
from ..types.numeric import Probability
from ..types.state import GaussianState, State
from .base import DetectionSimulator, GroundTruthSimulator
from stonesoup.buffered_generator import BufferedGenerator
class SingleTargetGroundTruthSimulator(GroundTruthSimulator):
transition_model = Property(
TransitionModel, doc="Transition Model used as propagator for track.")
initial_state = Property(
State,
doc="Initial state to use to generate ground truth")
timestep = Property(
datetime.timedelta,
default=datetime.timedelta(seconds=1),
doc="Time step between each state. Default one second.")
number_steps = Property(
int, default=100, doc="Number of time steps to run for")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@BufferedGenerator.generator_method
def groundtruth_paths_gen(self):
time = self.initial_state.timestamp or datetime.datetime.now()
gttrack = GroundTruthPath([
GroundTruthState(self.initial_state.state_vector, timestamp=time,
metadata={"index": self.index})])
yield time, {gttrack}
for _ in range(self.number_steps - 1):
time += self.timestep
trans_state_vector = self.transition_model.function(
gttrack[-1].state_vector,
time_interval=self.timestep)
gttrack.append(GroundTruthState(
trans_state_vector, timestamp=time,
metadata={"index": self.index}))
yield time, {gttrack}
class SwitchOneTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):
transition_models = Property(
[TransitionModel], doc="List of transition models to be used, ensure\
that they all have the same dimensions.")
model_probs = Property([float], doc="A matrix of probabilities.\
The element in the ith row and the jth column is the probability of\
switching from the ith transition model in :attr:`transition_models`\
to the jth")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@property
def transition_model(self):
self.index = np.random.choice(range(0, len(self.transition_models)),
p=self.model_probs[self.index])
return self.transition_models[self.index]
class MultiTargetGroundTruthSimulator(SingleTargetGroundTruthSimulator):
transition_model = Property(
TransitionModel, doc="Transition Model used as propagator for track.")
initial_state = Property(
GaussianState,
doc="Initial state to use to generate states")
birth_rate = Property(
float, default=1.0, doc="Rate at which tracks are born. Expected "
"number of occurrences (λ) in Poisson distribution. Default 1.0.")
death_probability = Property(
Probability, default=0.1,
doc="Probability of track dying in each time step. Default 0.1.")
@BufferedGenerator.generator_method
def groundtruth_paths_gen(self):
groundtruth_paths = set()
time = self.initial_state.timestamp or datetime.datetime.now()
for _ in range(self.number_steps):
groundtruth_paths.difference_update(
gttrack
for gttrack in groundtruth_paths.copy()
if np.random.rand() <= self.death_probability)
for gttrack in groundtruth_paths:
self.index = gttrack[-1].metadata.get("index")
trans_state_vector = self.transition_model.function(
gttrack[-1].state_vector,
time_interval=self.timestep)
gttrack.append(GroundTruthState(
trans_state_vector, timestamp=time,
metadata={"index": self.index}))
for _ in range(np.random.poisson(self.birth_rate)):
self.index = 0
gttrack = GroundTruthPath()
gttrack.append(GroundTruthState(
self.initial_state.state_vector +
np.sqrt(self.initial_state.covar) @
np.random.randn(self.initial_state.ndim, 1),
timestamp=time, metadata={"index": self.index}))
groundtruth_paths.add(gttrack)
yield time, groundtruth_paths
time += self.timestep
class SwitchMultiTargetGroundTruthSimulator(MultiTargetGroundTruthSimulator):
transition_models = Property(
[TransitionModel], doc="List of transition models to be used, ensure\
that they all have the same dimensions.")
model_probs = Property([float], doc="A matrix of probabilities.\
The element in the ith row and the jth column is the probability of\
switching from the ith transition model in :attr:`transition_models`\
to the jth")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.index = 0
@property
def transition_model(self):
self.index = np.random.choice(range(0, len(self.transition_models)),
p=self.model_probs[self.index])
return self.transition_models[self.index]
class SimpleDetectionSimulator(DetectionSimulator):
groundtruth = Property(GroundTruthReader)
measurement_model = Property(MeasurementModel)
meas_range = Property(np.ndarray)
detection_probability = Property(Probability, default=0.9)
clutter_rate = Property(float, default=2.0)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.real_detections = set()
self.clutter_detections = set()
self.index = 0
@property
def clutter_spatial_density(self):
return self.clutter_rate/np.prod(np.diff(self.meas_range))
@BufferedGenerator.generator_method
def detections_gen(self):
for time, tracks in self.groundtruth:
self.real_detections.clear()
self.clutter_detections.clear()
for track in tracks:
self.index = track[-1].metadata.get("index")
if np.random.rand() < self.detection_probability:
detection = TrueDetection(
self.measurement_model.function(
track[-1].state_vector),
timestamp=track[-1].timestamp,
groundtruth_path=track)
detection.clutter = False
self.real_detections.add(detection)
for _ in range(np.random.poisson(self.clutter_rate)):
detection = Clutter(
np.random.rand(self.measurement_model.ndim_meas, 1) *
np.diff(self.meas_range) + self.meas_range[:, :1],
timestamp=time)
self.clutter_detections.add(detection)
yield time, self.real_detections | self.clutter_detections
class SwitchDetectionSimulator(SimpleDetectionSimulator):
detection_probabilities = Property([Probability], doc="List of\
probabilities that correspond to the detection probability of the\
simulated object while undergoing each transition model")
@property
def detection_probability(self):
return self.detection_probabilities[self.index]
| true | true |
f729f12176ee792d4c983261f3ac3717876984d3 | 1,212 | py | Python | eta/t/test_parser.py | lewismj/eta | a07a9c078f8e2c9e166febea0ee61351c25caaa8 | [
"BSD-2-Clause"
] | null | null | null | eta/t/test_parser.py | lewismj/eta | a07a9c078f8e2c9e166febea0ee61351c25caaa8 | [
"BSD-2-Clause"
] | null | null | null | eta/t/test_parser.py | lewismj/eta | a07a9c078f8e2c9e166febea0ee61351c25caaa8 | [
"BSD-2-Clause"
] | null | null | null | """
Basic unit tests for the parser class.
"""
import unittest
from eta.parser import parser
from eta.types import Symbol
from lark.visitors import VisitError
class ParserTest(unittest.TestCase):
def test_basic_expressions(self):
try:
parser.parse("(defun (foo x y) (+ x y))")
parser.parse("(+ 21 35 12 7)")
parser.parse("(/ 10 2)")
parser.parse("(defun (len xs) "
"(if (== xs nil) "
" (0) (+ 1 (len (tail xs)))))")
except VisitError:
self.fail("Failed to parse basic expressions.")
def test_expression_structure_basic(self):
ast = parser.parse("(+ 1 2)")
self.assertEqual(1, len(ast))
expression = ast[0]
self.assertEqual(Symbol("+"), expression[0])
self.assertEqual(1, expression[1])
self.assertEqual(2, expression[2])
def test_parsed_as_number(self):
ast = parser.parse("(-1)")
self.assertEqual(1, len(ast))
def make_suite():
return unittest.makeSuite(ParserTest, 'Parser test')
if __name__ == '__main__':
suite = make_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
| 27.545455 | 59 | 0.584158 | import unittest
from eta.parser import parser
from eta.types import Symbol
from lark.visitors import VisitError
class ParserTest(unittest.TestCase):
def test_basic_expressions(self):
try:
parser.parse("(defun (foo x y) (+ x y))")
parser.parse("(+ 21 35 12 7)")
parser.parse("(/ 10 2)")
parser.parse("(defun (len xs) "
"(if (== xs nil) "
" (0) (+ 1 (len (tail xs)))))")
except VisitError:
self.fail("Failed to parse basic expressions.")
def test_expression_structure_basic(self):
ast = parser.parse("(+ 1 2)")
self.assertEqual(1, len(ast))
expression = ast[0]
self.assertEqual(Symbol("+"), expression[0])
self.assertEqual(1, expression[1])
self.assertEqual(2, expression[2])
def test_parsed_as_number(self):
ast = parser.parse("(-1)")
self.assertEqual(1, len(ast))
def make_suite():
return unittest.makeSuite(ParserTest, 'Parser test')
if __name__ == '__main__':
suite = make_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
| true | true |
f729f1284ac97c73e57672805869326a3657d65a | 2,949 | py | Python | bc/search/tests/test_synonyms.py | Buckinghamshire-Digital-Service/buckinghamshire-council | bbbdb52b515bcdfc79a2bd9198dfa4828405370e | [
"BSD-3-Clause"
] | 1 | 2021-02-27T07:27:17.000Z | 2021-02-27T07:27:17.000Z | bc/search/tests/test_synonyms.py | Buckinghamshire-Digital-Service/buckinghamshire-council | bbbdb52b515bcdfc79a2bd9198dfa4828405370e | [
"BSD-3-Clause"
] | null | null | null | bc/search/tests/test_synonyms.py | Buckinghamshire-Digital-Service/buckinghamshire-council | bbbdb52b515bcdfc79a2bd9198dfa4828405370e | [
"BSD-3-Clause"
] | 1 | 2021-06-09T15:56:54.000Z | 2021-06-09T15:56:54.000Z | from unittest.mock import patch
from django.test import TestCase
from bc.search.tests.fixtures import TermFactory
from bc.search.utils import SYNONYMS_CACHE_KEY, cache, get_synonyms
class SynonymTest(TestCase):
def test_basic(self):
TermFactory(canonical_term="foo", synonyms=["soup", "potatoes"])
self.assertListEqual(get_synonyms(), ["foo, soup, potatoes"])
def test_multi_word_phrase_synonym(self):
TermFactory(
canonical_term="foo",
synonyms=["haircuts arguments", "small things", "rabbits"],
)
self.assertListEqual(
get_synonyms(), ["foo, haircuts arguments, small things, rabbits"],
)
def test_multi_word_canonical_term(self):
TermFactory(
canonical_term="people with noses", synonyms=["more jam", "soot", "flies"]
)
self.assertListEqual(
get_synonyms(), ["people with noses, more jam, soot, flies"],
)
def test_multiple_synonyms(self):
TermFactory(canonical_term="foo", synonyms=["fish", "jam"])
TermFactory(
canonical_term="bar", synonyms=["tobogganing", "showers", "toasters"]
)
self.assertListEqual(
get_synonyms(), ["foo, fish, jam", "bar, tobogganing, showers, toasters"],
)
def test_synonyms_are_lower_cased(self):
TermFactory(canonical_term="foo", synonyms=["Belgium", "fire", "water"])
self.assertListEqual(get_synonyms(), ["foo, belgium, fire, water"])
@patch("bc.search.signal_handlers.get_synonyms")
def test_signal_is_triggered(self, mock_get_synonyms):
TermFactory(canonical_term="foo", synonyms=["lights", "Burma"])
mock_get_synonyms.assert_called_once_with(force_update=True)
def test_synonyms_are_cached(self):
cache.delete(SYNONYMS_CACHE_KEY)
self.assertEqual(cache.get(SYNONYMS_CACHE_KEY), None)
TermFactory(canonical_term="foo", synonyms=["light", "air"])
self.assertListEqual(cache.get(SYNONYMS_CACHE_KEY), ["foo, light, air"])
def test_synonym_cache_can_be_updated(self):
TermFactory(
canonical_term="foo", synonyms=["things that go 'uhh'", "Arthur Negus"]
)
cache.set(SYNONYMS_CACHE_KEY, ["foo, colonel gaddafi"])
self.assertListEqual(cache.get(SYNONYMS_CACHE_KEY), ["foo, colonel gaddafi"])
self.assertListEqual(
get_synonyms(force_update=True), ["foo, things that go 'uhh', arthur negus"]
)
self.assertListEqual(
cache.get(SYNONYMS_CACHE_KEY), ["foo, things that go 'uhh', arthur negus"]
)
def test_cache_is_used(self):
cache.set(SYNONYMS_CACHE_KEY, ["foo, eggnog, radiators"])
self.assertListEqual(get_synonyms(), ["foo, eggnog, radiators"])
TermFactory(canonical_term="bar", synonyms=["grandmothers"])
self.assertListEqual(get_synonyms(), ["bar, grandmothers"])
| 39.32 | 88 | 0.656833 | from unittest.mock import patch
from django.test import TestCase
from bc.search.tests.fixtures import TermFactory
from bc.search.utils import SYNONYMS_CACHE_KEY, cache, get_synonyms
class SynonymTest(TestCase):
def test_basic(self):
TermFactory(canonical_term="foo", synonyms=["soup", "potatoes"])
self.assertListEqual(get_synonyms(), ["foo, soup, potatoes"])
def test_multi_word_phrase_synonym(self):
TermFactory(
canonical_term="foo",
synonyms=["haircuts arguments", "small things", "rabbits"],
)
self.assertListEqual(
get_synonyms(), ["foo, haircuts arguments, small things, rabbits"],
)
def test_multi_word_canonical_term(self):
TermFactory(
canonical_term="people with noses", synonyms=["more jam", "soot", "flies"]
)
self.assertListEqual(
get_synonyms(), ["people with noses, more jam, soot, flies"],
)
def test_multiple_synonyms(self):
TermFactory(canonical_term="foo", synonyms=["fish", "jam"])
TermFactory(
canonical_term="bar", synonyms=["tobogganing", "showers", "toasters"]
)
self.assertListEqual(
get_synonyms(), ["foo, fish, jam", "bar, tobogganing, showers, toasters"],
)
def test_synonyms_are_lower_cased(self):
TermFactory(canonical_term="foo", synonyms=["Belgium", "fire", "water"])
self.assertListEqual(get_synonyms(), ["foo, belgium, fire, water"])
@patch("bc.search.signal_handlers.get_synonyms")
def test_signal_is_triggered(self, mock_get_synonyms):
TermFactory(canonical_term="foo", synonyms=["lights", "Burma"])
mock_get_synonyms.assert_called_once_with(force_update=True)
def test_synonyms_are_cached(self):
cache.delete(SYNONYMS_CACHE_KEY)
self.assertEqual(cache.get(SYNONYMS_CACHE_KEY), None)
TermFactory(canonical_term="foo", synonyms=["light", "air"])
self.assertListEqual(cache.get(SYNONYMS_CACHE_KEY), ["foo, light, air"])
def test_synonym_cache_can_be_updated(self):
TermFactory(
canonical_term="foo", synonyms=["things that go 'uhh'", "Arthur Negus"]
)
cache.set(SYNONYMS_CACHE_KEY, ["foo, colonel gaddafi"])
self.assertListEqual(cache.get(SYNONYMS_CACHE_KEY), ["foo, colonel gaddafi"])
self.assertListEqual(
get_synonyms(force_update=True), ["foo, things that go 'uhh', arthur negus"]
)
self.assertListEqual(
cache.get(SYNONYMS_CACHE_KEY), ["foo, things that go 'uhh', arthur negus"]
)
def test_cache_is_used(self):
cache.set(SYNONYMS_CACHE_KEY, ["foo, eggnog, radiators"])
self.assertListEqual(get_synonyms(), ["foo, eggnog, radiators"])
TermFactory(canonical_term="bar", synonyms=["grandmothers"])
self.assertListEqual(get_synonyms(), ["bar, grandmothers"])
| true | true |
f729f150a9457bcfb66b694ad7626c679afc605a | 3,103 | py | Python | ucsmsdk/mometa/bios/BiosSettingRef.py | anoop1984/python_sdk | c4a226bad5e10ad233eda62bc8f6d66a5a82b651 | [
"Apache-2.0"
] | null | null | null | ucsmsdk/mometa/bios/BiosSettingRef.py | anoop1984/python_sdk | c4a226bad5e10ad233eda62bc8f6d66a5a82b651 | [
"Apache-2.0"
] | null | null | null | ucsmsdk/mometa/bios/BiosSettingRef.py | anoop1984/python_sdk | c4a226bad5e10ad233eda62bc8f6d66a5a82b651 | [
"Apache-2.0"
] | null | null | null | """This module contains the general information for BiosSettingRef ManagedObject."""
import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class BiosSettingRefConsts():
IS_DEFAULT_NO = "no"
IS_DEFAULT_YES = "yes"
IS_SUPPORTED_NO = "no"
IS_SUPPORTED_YES = "yes"
class BiosSettingRef(ManagedObject):
"""This is BiosSettingRef class."""
consts = BiosSettingRefConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("BiosSettingRef", "biosSettingRef", "setting-ref-[name]", VersionMeta.Version131c, "InputOutput", 0x3f, [], [""], [u'biosParameterRef'], [], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version131c, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"constant_name": MoPropertyMeta("constant_name", "constantName", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []),
"is_default": MoPropertyMeta("is_default", "isDefault", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []),
"is_supported": MoPropertyMeta("is_supported", "isSupported", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version131c, MoPropertyMeta.NAMING, 0x8, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{1,256}""", [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []),
"sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"constantName": "constant_name",
"dn": "dn",
"isDefault": "is_default",
"isSupported": "is_supported",
"name": "name",
"rn": "rn",
"sacl": "sacl",
"status": "status",
}
def __init__(self, parent_mo_or_dn, name, **kwargs):
self._dirty_mask = 0
self.name = name
self.child_action = None
self.constant_name = None
self.is_default = None
self.is_supported = None
self.sacl = None
self.status = None
ManagedObject.__init__(self, "BiosSettingRef", parent_mo_or_dn, **kwargs)
| 51.716667 | 248 | 0.636481 | import sys, os
from ...ucsmo import ManagedObject
from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class BiosSettingRefConsts():
IS_DEFAULT_NO = "no"
IS_DEFAULT_YES = "yes"
IS_SUPPORTED_NO = "no"
IS_SUPPORTED_YES = "yes"
class BiosSettingRef(ManagedObject):
consts = BiosSettingRefConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("BiosSettingRef", "biosSettingRef", "setting-ref-[name]", VersionMeta.Version131c, "InputOutput", 0x3f, [], [""], [u'biosParameterRef'], [], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version131c, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"constant_name": MoPropertyMeta("constant_name", "constantName", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []),
"is_default": MoPropertyMeta("is_default", "isDefault", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []),
"is_supported": MoPropertyMeta("is_supported", "isSupported", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version131c, MoPropertyMeta.NAMING, 0x8, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{1,256}""", [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []),
"sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
}
prop_map = {
"childAction": "child_action",
"constantName": "constant_name",
"dn": "dn",
"isDefault": "is_default",
"isSupported": "is_supported",
"name": "name",
"rn": "rn",
"sacl": "sacl",
"status": "status",
}
def __init__(self, parent_mo_or_dn, name, **kwargs):
self._dirty_mask = 0
self.name = name
self.child_action = None
self.constant_name = None
self.is_default = None
self.is_supported = None
self.sacl = None
self.status = None
ManagedObject.__init__(self, "BiosSettingRef", parent_mo_or_dn, **kwargs)
| true | true |
f729f26ea4e35c38ddbe2c84c2bc600c4af7bd30 | 1,110 | py | Python | body/test/test_dxl_comms.py | hello-ag/stretch_body | 4d9a1f10617b8f7155b8498c5333821818ce24ab | [
"RSA-MD"
] | null | null | null | body/test/test_dxl_comms.py | hello-ag/stretch_body | 4d9a1f10617b8f7155b8498c5333821818ce24ab | [
"RSA-MD"
] | 1 | 2021-08-29T21:42:17.000Z | 2021-08-30T05:58:15.000Z | body/test/test_dxl_comms.py | hello-ag/stretch_body | 4d9a1f10617b8f7155b8498c5333821818ce24ab | [
"RSA-MD"
] | 3 | 2021-08-20T22:51:57.000Z | 2021-09-02T17:05:25.000Z | # Logging level must be set before importing any stretch_body class
import stretch_body.robot_params
#stretch_body.robot_params.RobotParams.set_logging_level("DEBUG")
import unittest
import stretch_body.device
import stretch_body.robot as robot
import numpy as np
class TestTimingStats(unittest.TestCase):
def test_thread_starvation_group_sync_read(self):
robot = stretch_body.robot.Robot()
robot.end_of_arm.params['use_group_sync_read']=1
print(robot.end_of_arm.joints)
print('Starting test_thread_starvation')
print('Latency timer of %f'%robot.end_of_arm.params['dxl_latency_timer'])
print('Testing on tool %s'%robot.params['tool'])
robot.startup()
try:
for itr in range(100): #Make large CPU load
x = np.random.rand(3, 1000, 1000)
x.tolist()
except (IndexError, IOError) as e:
self.fail("IndexError or IOError failure in comms")
self.assertTrue(robot.end_of_arm.comm_errors.status['n_rx']<2)
robot.end_of_arm.comm_errors.pretty_print()
robot.stop()
| 39.642857 | 81 | 0.692793 |
import stretch_body.robot_params
import unittest
import stretch_body.device
import stretch_body.robot as robot
import numpy as np
class TestTimingStats(unittest.TestCase):
def test_thread_starvation_group_sync_read(self):
robot = stretch_body.robot.Robot()
robot.end_of_arm.params['use_group_sync_read']=1
print(robot.end_of_arm.joints)
print('Starting test_thread_starvation')
print('Latency timer of %f'%robot.end_of_arm.params['dxl_latency_timer'])
print('Testing on tool %s'%robot.params['tool'])
robot.startup()
try:
for itr in range(100):
x = np.random.rand(3, 1000, 1000)
x.tolist()
except (IndexError, IOError) as e:
self.fail("IndexError or IOError failure in comms")
self.assertTrue(robot.end_of_arm.comm_errors.status['n_rx']<2)
robot.end_of_arm.comm_errors.pretty_print()
robot.stop()
| true | true |
f729f2fd022c7e13fb4bc572acfc2350bc58e2f3 | 403 | py | Python | app/emails.py | JoyWambui/write-a-way | 2b535406f5c62722d478db8c186562009cf50e65 | [
"MIT"
] | null | null | null | app/emails.py | JoyWambui/write-a-way | 2b535406f5c62722d478db8c186562009cf50e65 | [
"MIT"
] | null | null | null | app/emails.py | JoyWambui/write-a-way | 2b535406f5c62722d478db8c186562009cf50e65 | [
"MIT"
] | null | null | null | import os
from flask_mail import Message
from flask import render_template
from . import mail
def mail_message(subject,template,to,**kwargs):
sender_email =os.environ.get("MAIL_USERNAME")
email = Message(subject, sender=sender_email, recipients=[to])
email.body= render_template(template + ".txt",**kwargs)
email.html = render_template(template + ".html",**kwargs)
mail.send(email) | 33.583333 | 66 | 0.741935 | import os
from flask_mail import Message
from flask import render_template
from . import mail
def mail_message(subject,template,to,**kwargs):
sender_email =os.environ.get("MAIL_USERNAME")
email = Message(subject, sender=sender_email, recipients=[to])
email.body= render_template(template + ".txt",**kwargs)
email.html = render_template(template + ".html",**kwargs)
mail.send(email) | true | true |
f729f311d8ca65272c4d0f7490c02839068e71a4 | 833 | py | Python | examples/trio_example.py | leanprover-community/lean-client-python | efeb257b7e672d02c1005a6624251ad6dd392451 | [
"Apache-2.0"
] | 13 | 2020-05-03T21:32:14.000Z | 2021-06-01T10:32:11.000Z | examples/trio_example.py | leanprover-community/lean-client-python | efeb257b7e672d02c1005a6624251ad6dd392451 | [
"Apache-2.0"
] | 22 | 2020-04-25T12:18:12.000Z | 2021-07-22T19:39:19.000Z | examples/trio_example.py | leanprover-community/lean-client-python | efeb257b7e672d02c1005a6624251ad6dd392451 | [
"Apache-2.0"
] | 2 | 2020-05-06T07:58:33.000Z | 2020-11-03T22:11:54.000Z | #!/usr/bin/env python
from pathlib import Path
import trio # type: ignore
from lean_client.trio_server import TrioLeanServer
async def main():
lines = Path('test.lean').read_text().split('\n')
async with trio.open_nursery() as nursery:
server = TrioLeanServer(nursery, debug=False)
await server.start()
await server.full_sync('test.lean')
for i, line in enumerate(lines):
before = await server.state('test.lean', i+1, 0)
after = await server.state('test.lean', i+1, len(line))
if before or after:
print(f'Line {i+1}: {line}')
print(f'State before:\n{before}\n')
print(f'State after:\n{after}\n')
server.kill()
nursery.cancel_scope.cancel()
if __name__ == '__main__':
trio.run(main)
| 28.724138 | 67 | 0.59904 |
from pathlib import Path
import trio
from lean_client.trio_server import TrioLeanServer
async def main():
lines = Path('test.lean').read_text().split('\n')
async with trio.open_nursery() as nursery:
server = TrioLeanServer(nursery, debug=False)
await server.start()
await server.full_sync('test.lean')
for i, line in enumerate(lines):
before = await server.state('test.lean', i+1, 0)
after = await server.state('test.lean', i+1, len(line))
if before or after:
print(f'Line {i+1}: {line}')
print(f'State before:\n{before}\n')
print(f'State after:\n{after}\n')
server.kill()
nursery.cancel_scope.cancel()
if __name__ == '__main__':
trio.run(main)
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.