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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7268d97ecd869e307e958def5462cfcc567d433 | 13,947 | py | Python | discum/guild/guild.py | DJJ05/Discord-S.C.U.M | 498c2aebb71cef331b1c47a8bb6ffe65e88d2a34 | [
"MIT"
] | 1 | 2022-01-02T13:39:38.000Z | 2022-01-02T13:39:38.000Z | discum/guild/guild.py | DJJ05/Discord-S.C.U.M | 498c2aebb71cef331b1c47a8bb6ffe65e88d2a34 | [
"MIT"
] | null | null | null | discum/guild/guild.py | DJJ05/Discord-S.C.U.M | 498c2aebb71cef331b1c47a8bb6ffe65e88d2a34 | [
"MIT"
] | 2 | 2022-02-17T13:04:55.000Z | 2022-02-28T00:48:00.000Z | from ..RESTapiwrap import Wrapper
from ..utils.permissions import PERMS, Permissions
from ..utils.contextproperties import ContextProperties
import time
import base64
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
class Guild(object):
__slots__ = ['discord', 's', 'log']
def __init__(self, discord, s, log): #s is the requests session object
self.discord = discord
self.s = s
self.log = log
'''
invite codes / server info
'''
#get guild info from invite code
def getInfoFromInviteCode(self, inviteCode, with_counts, with_expiration, fromJoinGuildNav):
url = self.discord+"invites/"+inviteCode
if (with_counts!=None or with_expiration!=None or fromJoinGuildNav):
url += "?"
data = {}
if fromJoinGuildNav:
data["inputValue"] = inviteCode
if with_counts != None:
data["with_counts"] = with_counts
if with_expiration != None:
data["with_expiration"] = with_expiration
url += "&".join( "%s=%s" % (k, quote(repr(data[k]).lower())) for k in data)
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
#just the join guild endpoint, default location mimics joining a guild from the ([+]Add a Server) button
def joinGuildRaw(self, inviteCode, guild_id=None, channel_id=None, channel_type=None, location="join guild"):
url = self.discord+"invites/"+inviteCode
if location in ("accept invite page", "join guild"):
return Wrapper.sendRequest(self.s, 'post', url, {}, headerModifications={"update":{"X-Context-Properties":ContextProperties.get(location, guild_id=guild_id, channel_id=channel_id, channel_type=channel_type)}}, log=self.log)
elif location == "markdown":
return Wrapper.sendRequest(self.s, 'post', url, {}, headerModifications={"update":{"X-Context-Properties":ContextProperties.get("markdown")}}, log=self.log)
def joinGuild(self, inviteCode, location, wait):
location = location.lower()
if location in ("accept invite page", "join guild"):
guildData = self.getInfoFromInviteCode(inviteCode, with_counts=True, with_expiration=True, fromJoinGuildNav=(location.lower()=="join guild")).json()
if wait: time.sleep(wait)
return self.joinGuildRaw(inviteCode, guildData["guild"]["id"], guildData["channel"]["id"], guildData["channel"]["type"], location)
elif location == "markdown":
return self.joinGuildRaw(inviteCode, location="markdown")
def previewGuild(self, guildID, sessionID):
url = self.discord+"guilds/"+guildID+"/members/@me?lurker=true"
if sessionID != None:
url += "&session_id="+sessionID
return Wrapper.sendRequest(self.s, 'put', url, headerModifications={"update":{"X-Context-Properties":"e30="}}, log=self.log)
def leaveGuild(self, guildID, lurking):
url = self.discord+"users/@me/guilds/"+guildID
body = {"lurking": lurking}
return Wrapper.sendRequest(self.s, 'delete', url, body, log=self.log)
def createInvite(self, channelID, max_age_seconds, max_uses, grantTempMembership, checkInvite, targetType): #has to be a channel thats in a guild. also checkInvite and targetType are basically useless.
url = self.discord+"channels/"+channelID+"/invites"
if max_age_seconds == False:
max_age_seconds = 0
if max_uses == False:
max_uses = 0
body = {"max_age": max_age_seconds, "max_uses": max_uses, "temporary": grantTempMembership}
if checkInvite != "":
body["validate"] = checkInvite
if targetType != "":
body["target_type"] = targetType
return Wrapper.sendRequest(self.s, 'post', url, body, headerModifications={"update":{"X-Context-Properties":ContextProperties.get("guild header")}}, log=self.log)
def deleteInvite(self, inviteCode):
url = self.discord+'invites/'+inviteCode
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
def getGuildInvites(self, guildID):
url = self.discord+'guilds/'+guildID+'/invites'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getChannelInvites(self, channelID):
url = self.discord+'channels/'+channelID+'/invites'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuilds(self, with_counts):
url = self.discord+"users/@me/guilds"
if with_counts != None:
url += "?with_counts="+repr(with_counts).lower()
headerMods = {"update":{"X-Track":self.s.headers.get("X-Super-Properties")}, "remove":["X-Super-Properties"]}
return Wrapper.sendRequest(self.s, 'get', url, headerModifications=headerMods, log=self.log)
def getGuildChannels(self, guildID):
url = self.discord+'guilds/'+guildID+'/channels'
headerMods = {"update":{"X-Track":self.s.headers.get("X-Super-Properties")}, "remove":["X-Super-Properties"]}
return Wrapper.sendRequest(self.s, 'get', url, headerModifications=headerMods, log=self.log)
def getDiscoverableGuilds(self, offset, limit):
url = self.discord+"discoverable-guilds?offset="+repr(offset)+"&limit="+repr(limit)
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildRegions(self, guildID):
url = self.discord+'guilds/'+guildID+'/regions'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
'''
server moderation and management
'''
#create a guild
def createGuild(self, name, icon, channels, systemChannelID, template):
url = self.discord+"guilds"
body = {"name": name, "icon":icon, "channels":channels, "system_channel_id":systemChannelID, "guild_template_code":template}
if icon != None:
with open(icon, "rb") as image:
encodedImage = base64.b64encode(image.read()).decode('utf-8')
body["icon"] = "data:image/png;base64,"+encodedImage
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
#delete a guild (assuming you are the owner)
def deleteGuild(self, guildID):
url = self.discord+"guilds/%s/delete" % (guildID)
body = {}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
#kick a user
def kick(self, guildID, userID, reason):
url = self.discord+"guilds/%s/members/%s?reason=%s" % (guildID, userID, quote(reason))
headerMods = {"update":{"X-Audit-Log-Reason":reason}} if reason=="" else {}
return Wrapper.sendRequest(self.s, 'delete', url, headerModifications=headerMods, log=self.log)
#ban a user
def ban(self, guildID, userID, deleteMessagesDays, reason):
url = self.discord+"guilds/%s/bans/%s" % (guildID, userID)
body = {"delete_message_days": str(deleteMessagesDays), "reason": reason}
headerMods = {"update":{"X-Audit-Log-Reason":reason}} if reason=="" else {}
return Wrapper.sendRequest(self.s, 'put', url, body, headerModifications=headerMods, log=self.log)
def revokeBan(self, guildID, userID):
url = self.discord+"guilds/"+guildID+"/bans/"+userID
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
#lookup a user in a guild. thx Echocage for finding this api endpoint
'''
removed as this is a bot-only request. Use bot.gateway.checkGuildMembers instead.
def getGuildMember(self, guildID, userID):
url = self.discord+"guilds/%s/members/%s" % (guildID, userID)
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
'''
def getRoleMemberCounts(self, guildID):
url = self.discord+"guilds/"+guildID+"/roles/member-counts"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildIntegrations(self, guildID, include_applications):
url = self.discord+"guilds/"+guildID+"/integrations"
if include_applications != None:
url += "?include_applications="+repr(include_applications).lower()
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildTemplates(self, guildID):
url = self.discord+"guilds/"+guildID+"/templates"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getRoleMemberIDs(self, guildID, roleID):
url = self.discord+"guilds/"+guildID+"/roles/"+roleID+"/member-ids"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def addMembersToRole(self, guildID, roleID, memberIDs):
if isinstance(memberIDs, str):
memberIDs = [memberIDs]
url = self.discord+"guilds/"+guildID+"/roles/"+roleID+"/members"
body = {"member_ids":memberIDs}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
def setMemberRoles(self, guildID, memberID, roleIDs):
if isinstance(roleIDs, str):
roleIDs = [roleIDs]
url = self.discord+"guilds/"+guildID+"/members/"+memberID
body = {"roles": roleIDs}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
'''
other stuff
'''
#get member verification data
def getMemberVerificationData(self, guildID, with_guild, invite_code):
url = self.discord+"guilds/"+guildID+"/member-verification?with_guild="+str(with_guild).lower()
if invite_code != None:
url += "&invite_code="+invite_code
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def agreeGuildRules(self, guildID, form_fields, version):
url = self.discord+"guilds/"+guildID+"/requests/@me"
form_fields[0]['response'] = True
body = {"version":version, "form_fields":form_fields}
return Wrapper.sendRequest(self.s, 'put', url, body, log=self.log)
### threads
#create thread
def createThread(self, channelID, name, messageID, public, archiveAfter):
url = self.discord+"channels/"+channelID
if messageID:
url += "/messages/"+messageID
url += "/threads"
choice = archiveAfter.lower()
if choice == '1 hour':
archiveAfterSeconds = 60
elif choice in ('24 hour', '24 hours', '1 day'):
archiveAfterSeconds = 1440
elif choice in ('3 day', '3 days'):
archiveAfterSeconds = 4320
elif choice in ('1 week', '7 day', '7 days'):
archiveAfterSeconds = 10080
threadType = 11 if public else 12
body = {"name": name, "type": threadType, "auto_archive_duration": archiveAfterSeconds}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
#leave thread
def leaveThread(self, threadID, location):
url = self.discord+"channels/"+threadID+"/thread-members/@me?location="+quote(location)
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
#join thread
def joinThread(self, threadID, location):
url = self.discord+"channels/"+threadID+"/thread-members/@me?location="+quote(location)
return Wrapper.sendRequest(self.s, 'post', url, log=self.log)
#archive thread
def archiveThread(self, threadID, lock):
url = self.discord+"channels/"+threadID
body = {"archived": True, "locked": lock}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
#unarchive thread
def unarchiveThread(self, threadID, lock):
url = self.discord+"channels/"+threadID
body = {"archived": False, "locked": lock}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
'''
other
'''
#lookup school
def lookupSchool(self, email, allowMultipleGuilds, useVerificationCode):
url = self.discord+"guilds/automations/email-domain-lookup"
body = {"email":email,"allow_multiple_guilds":allowMultipleGuilds}
if useVerificationCode != None:
body["use_verification_code"] = useVerificationCode
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
#https://discord.com/channels/hubID/mainChannelID
def schoolHubWaitlistSignup(self, email, school):
url = self.discord+"hub-waitlist/signup"
body = {"email":email,"school":school}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def schoolHubSignup(self, email, hubID):
url = self.discord+'guilds/automations/email-domain-lookup'
body = {"email":email,"guild_id":hubID,"allow_multiple_guilds":True,"use_verification_code":True}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def verifySchoolHubSignup(self, hubID, email, code):
url = self.discord+'guilds/automations/email-domain-lookup/verify-code'
body = {"code":code,"guild_id":hubID,"email":email}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def getSchoolHubGuilds(self, hubID): #note, the "entity_id" returned in each entry is the guildID
url = self.discord+'channels/'+hubID+'/directory-entries' #ik it says channels, but it's the hubID/"guildID".
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getSchoolHubDirectoryCounts(self, hubID): #this only returns the # of guilds/groups in each directory/category. This doesn't even return the category names
url = self.discord+'channels/'+hubID+'/directory-entries/counts'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def joinGuildFromSchoolHub(self, hubID, guildID):
url = self.discord+'guilds/'+guildID+'/members/@me?lurker=false&directory_channel_id='+hubID
headerMods = {"update":{"X-Context-Properties":ContextProperties.get("school hub guild")}}
return Wrapper.sendRequest(self.s, 'put', url, headerModifications=headerMods, log=self.log)
def searchSchoolHub(self, hubID, query):
url = self.discord+'channels/'+hubID+'/directory-entries/search?query='+query
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getMySchoolHubGuilds(self, hubID): #or guilds you own that can potentially be added to the hub
url = self.discord+'channels/'+hubID+'/directory-entries/list'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def setSchoolHubGuildDetails(self, hubID, guildID, description, directoryID): #directoryID (int) is not a snowflake
url = self.discord+'channels/'+hubID+'/directory-entry/'+guildID
body = {"description":description,"primary_category_id":directoryID}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def getLiveStages(self, extra):
url = self.discord+'stage-instances'
if extra:
url += '/extra'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
#the only time this is observed in the client is in a guild
def getChannel(self, channelID):
url = self.discord+'channels/'+channelID
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildActivitiesConfig(self, guildID):
url = self.discord+'activities/guilds/'+guildID+'/config'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
| 44.990323 | 226 | 0.723095 | from ..RESTapiwrap import Wrapper
from ..utils.permissions import PERMS, Permissions
from ..utils.contextproperties import ContextProperties
import time
import base64
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
class Guild(object):
__slots__ = ['discord', 's', 'log']
def __init__(self, discord, s, log):
self.discord = discord
self.s = s
self.log = log
def getInfoFromInviteCode(self, inviteCode, with_counts, with_expiration, fromJoinGuildNav):
url = self.discord+"invites/"+inviteCode
if (with_counts!=None or with_expiration!=None or fromJoinGuildNav):
url += "?"
data = {}
if fromJoinGuildNav:
data["inputValue"] = inviteCode
if with_counts != None:
data["with_counts"] = with_counts
if with_expiration != None:
data["with_expiration"] = with_expiration
url += "&".join( "%s=%s" % (k, quote(repr(data[k]).lower())) for k in data)
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def joinGuildRaw(self, inviteCode, guild_id=None, channel_id=None, channel_type=None, location="join guild"):
url = self.discord+"invites/"+inviteCode
if location in ("accept invite page", "join guild"):
return Wrapper.sendRequest(self.s, 'post', url, {}, headerModifications={"update":{"X-Context-Properties":ContextProperties.get(location, guild_id=guild_id, channel_id=channel_id, channel_type=channel_type)}}, log=self.log)
elif location == "markdown":
return Wrapper.sendRequest(self.s, 'post', url, {}, headerModifications={"update":{"X-Context-Properties":ContextProperties.get("markdown")}}, log=self.log)
def joinGuild(self, inviteCode, location, wait):
location = location.lower()
if location in ("accept invite page", "join guild"):
guildData = self.getInfoFromInviteCode(inviteCode, with_counts=True, with_expiration=True, fromJoinGuildNav=(location.lower()=="join guild")).json()
if wait: time.sleep(wait)
return self.joinGuildRaw(inviteCode, guildData["guild"]["id"], guildData["channel"]["id"], guildData["channel"]["type"], location)
elif location == "markdown":
return self.joinGuildRaw(inviteCode, location="markdown")
def previewGuild(self, guildID, sessionID):
url = self.discord+"guilds/"+guildID+"/members/@me?lurker=true"
if sessionID != None:
url += "&session_id="+sessionID
return Wrapper.sendRequest(self.s, 'put', url, headerModifications={"update":{"X-Context-Properties":"e30="}}, log=self.log)
def leaveGuild(self, guildID, lurking):
url = self.discord+"users/@me/guilds/"+guildID
body = {"lurking": lurking}
return Wrapper.sendRequest(self.s, 'delete', url, body, log=self.log)
def createInvite(self, channelID, max_age_seconds, max_uses, grantTempMembership, checkInvite, targetType):
url = self.discord+"channels/"+channelID+"/invites"
if max_age_seconds == False:
max_age_seconds = 0
if max_uses == False:
max_uses = 0
body = {"max_age": max_age_seconds, "max_uses": max_uses, "temporary": grantTempMembership}
if checkInvite != "":
body["validate"] = checkInvite
if targetType != "":
body["target_type"] = targetType
return Wrapper.sendRequest(self.s, 'post', url, body, headerModifications={"update":{"X-Context-Properties":ContextProperties.get("guild header")}}, log=self.log)
def deleteInvite(self, inviteCode):
url = self.discord+'invites/'+inviteCode
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
def getGuildInvites(self, guildID):
url = self.discord+'guilds/'+guildID+'/invites'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getChannelInvites(self, channelID):
url = self.discord+'channels/'+channelID+'/invites'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuilds(self, with_counts):
url = self.discord+"users/@me/guilds"
if with_counts != None:
url += "?with_counts="+repr(with_counts).lower()
headerMods = {"update":{"X-Track":self.s.headers.get("X-Super-Properties")}, "remove":["X-Super-Properties"]}
return Wrapper.sendRequest(self.s, 'get', url, headerModifications=headerMods, log=self.log)
def getGuildChannels(self, guildID):
url = self.discord+'guilds/'+guildID+'/channels'
headerMods = {"update":{"X-Track":self.s.headers.get("X-Super-Properties")}, "remove":["X-Super-Properties"]}
return Wrapper.sendRequest(self.s, 'get', url, headerModifications=headerMods, log=self.log)
def getDiscoverableGuilds(self, offset, limit):
url = self.discord+"discoverable-guilds?offset="+repr(offset)+"&limit="+repr(limit)
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildRegions(self, guildID):
url = self.discord+'guilds/'+guildID+'/regions'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def createGuild(self, name, icon, channels, systemChannelID, template):
url = self.discord+"guilds"
body = {"name": name, "icon":icon, "channels":channels, "system_channel_id":systemChannelID, "guild_template_code":template}
if icon != None:
with open(icon, "rb") as image:
encodedImage = base64.b64encode(image.read()).decode('utf-8')
body["icon"] = "data:image/png;base64,"+encodedImage
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def deleteGuild(self, guildID):
url = self.discord+"guilds/%s/delete" % (guildID)
body = {}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def kick(self, guildID, userID, reason):
url = self.discord+"guilds/%s/members/%s?reason=%s" % (guildID, userID, quote(reason))
headerMods = {"update":{"X-Audit-Log-Reason":reason}} if reason=="" else {}
return Wrapper.sendRequest(self.s, 'delete', url, headerModifications=headerMods, log=self.log)
def ban(self, guildID, userID, deleteMessagesDays, reason):
url = self.discord+"guilds/%s/bans/%s" % (guildID, userID)
body = {"delete_message_days": str(deleteMessagesDays), "reason": reason}
headerMods = {"update":{"X-Audit-Log-Reason":reason}} if reason=="" else {}
return Wrapper.sendRequest(self.s, 'put', url, body, headerModifications=headerMods, log=self.log)
def revokeBan(self, guildID, userID):
url = self.discord+"guilds/"+guildID+"/bans/"+userID
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
def getRoleMemberCounts(self, guildID):
url = self.discord+"guilds/"+guildID+"/roles/member-counts"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildIntegrations(self, guildID, include_applications):
url = self.discord+"guilds/"+guildID+"/integrations"
if include_applications != None:
url += "?include_applications="+repr(include_applications).lower()
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildTemplates(self, guildID):
url = self.discord+"guilds/"+guildID+"/templates"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getRoleMemberIDs(self, guildID, roleID):
url = self.discord+"guilds/"+guildID+"/roles/"+roleID+"/member-ids"
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def addMembersToRole(self, guildID, roleID, memberIDs):
if isinstance(memberIDs, str):
memberIDs = [memberIDs]
url = self.discord+"guilds/"+guildID+"/roles/"+roleID+"/members"
body = {"member_ids":memberIDs}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
def setMemberRoles(self, guildID, memberID, roleIDs):
if isinstance(roleIDs, str):
roleIDs = [roleIDs]
url = self.discord+"guilds/"+guildID+"/members/"+memberID
body = {"roles": roleIDs}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
def getMemberVerificationData(self, guildID, with_guild, invite_code):
url = self.discord+"guilds/"+guildID+"/member-verification?with_guild="+str(with_guild).lower()
if invite_code != None:
url += "&invite_code="+invite_code
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def agreeGuildRules(self, guildID, form_fields, version):
url = self.discord+"guilds/"+guildID+"/requests/@me"
form_fields[0]['response'] = True
body = {"version":version, "form_fields":form_fields}
return Wrapper.sendRequest(self.s, 'put', url, body, log=self.log)
d(self, channelID, name, messageID, public, archiveAfter):
url = self.discord+"channels/"+channelID
if messageID:
url += "/messages/"+messageID
url += "/threads"
choice = archiveAfter.lower()
if choice == '1 hour':
archiveAfterSeconds = 60
elif choice in ('24 hour', '24 hours', '1 day'):
archiveAfterSeconds = 1440
elif choice in ('3 day', '3 days'):
archiveAfterSeconds = 4320
elif choice in ('1 week', '7 day', '7 days'):
archiveAfterSeconds = 10080
threadType = 11 if public else 12
body = {"name": name, "type": threadType, "auto_archive_duration": archiveAfterSeconds}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def leaveThread(self, threadID, location):
url = self.discord+"channels/"+threadID+"/thread-members/@me?location="+quote(location)
return Wrapper.sendRequest(self.s, 'delete', url, log=self.log)
def joinThread(self, threadID, location):
url = self.discord+"channels/"+threadID+"/thread-members/@me?location="+quote(location)
return Wrapper.sendRequest(self.s, 'post', url, log=self.log)
def archiveThread(self, threadID, lock):
url = self.discord+"channels/"+threadID
body = {"archived": True, "locked": lock}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
def unarchiveThread(self, threadID, lock):
url = self.discord+"channels/"+threadID
body = {"archived": False, "locked": lock}
return Wrapper.sendRequest(self.s, 'patch', url, body, log=self.log)
def lookupSchool(self, email, allowMultipleGuilds, useVerificationCode):
url = self.discord+"guilds/automations/email-domain-lookup"
body = {"email":email,"allow_multiple_guilds":allowMultipleGuilds}
if useVerificationCode != None:
body["use_verification_code"] = useVerificationCode
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def schoolHubWaitlistSignup(self, email, school):
url = self.discord+"hub-waitlist/signup"
body = {"email":email,"school":school}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def schoolHubSignup(self, email, hubID):
url = self.discord+'guilds/automations/email-domain-lookup'
body = {"email":email,"guild_id":hubID,"allow_multiple_guilds":True,"use_verification_code":True}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def verifySchoolHubSignup(self, hubID, email, code):
url = self.discord+'guilds/automations/email-domain-lookup/verify-code'
body = {"code":code,"guild_id":hubID,"email":email}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def getSchoolHubGuilds(self, hubID):
url = self.discord+'channels/'+hubID+'/directory-entries'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getSchoolHubDirectoryCounts(self, hubID): #this only returns the # of guilds/groups in each directory/category. This doesn't even return the category names
url = self.discord+'channels/'+hubID+'/directory-entries/counts'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def joinGuildFromSchoolHub(self, hubID, guildID):
url = self.discord+'guilds/'+guildID+'/members/@me?lurker=false&directory_channel_id='+hubID
headerMods = {"update":{"X-Context-Properties":ContextProperties.get("school hub guild")}}
return Wrapper.sendRequest(self.s, 'put', url, headerModifications=headerMods, log=self.log)
def searchSchoolHub(self, hubID, query):
url = self.discord+'channels/'+hubID+'/directory-entries/search?query='+query
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getMySchoolHubGuilds(self, hubID):
url = self.discord+'channels/'+hubID+'/directory-entries/list'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def setSchoolHubGuildDetails(self, hubID, guildID, description, directoryID):
url = self.discord+'channels/'+hubID+'/directory-entry/'+guildID
body = {"description":description,"primary_category_id":directoryID}
return Wrapper.sendRequest(self.s, 'post', url, body, log=self.log)
def getLiveStages(self, extra):
url = self.discord+'stage-instances'
if extra:
url += '/extra'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getChannel(self, channelID):
url = self.discord+'channels/'+channelID
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
def getGuildActivitiesConfig(self, guildID):
url = self.discord+'activities/guilds/'+guildID+'/config'
return Wrapper.sendRequest(self.s, 'get', url, log=self.log)
| true | true |
f7268dac2e06e129091c886ee83609a1a78deda9 | 2,558 | py | Python | sharpy/combat/terran/micro_liberators.py | DuncanDHall/sharpy-sc2 | 7a47a7538ad99214e3f0288b6213cac882551180 | [
"MIT"
] | null | null | null | sharpy/combat/terran/micro_liberators.py | DuncanDHall/sharpy-sc2 | 7a47a7538ad99214e3f0288b6213cac882551180 | [
"MIT"
] | null | null | null | sharpy/combat/terran/micro_liberators.py | DuncanDHall/sharpy-sc2 | 7a47a7538ad99214e3f0288b6213cac882551180 | [
"MIT"
] | null | null | null | from typing import Dict, Optional
from sc2.ids.ability_id import AbilityId
from sharpy.combat import Action, MoveType, MicroStep
from sc2.ids.unit_typeid import UnitTypeId
from sc2.unit import Unit
from sc2.position import Point2
class MicroLiberators(MicroStep):
def __init__(self, group_distance: float = -5):
super().__init__()
self.last_siege = 0
self.group_distance = group_distance
self.focus_fired: Dict[int, float] = dict()
self.closest_units: Dict[int, Optional[Unit]] = dict()
def unit_solve_combat(self, unit: Unit, current_command: Action) -> Action:
return self.final_solve(unit, super().unit_solve_combat(unit, current_command))
def final_solve(self, unit: Unit, command: Action) -> Action:
time = self.knowledge.ai.time
# TODO: When in AG mode, look for relevant enemies inside the sieged zone.
relevant_ground_enemies = self.cache.enemy_in_range(unit.position, 10).not_structure.not_flying.visible
if self.move_type == MoveType.PanicRetreat:
# TODO: Unsiege
return command
if (
(
self.move_type == MoveType.Assault
or self.move_type == MoveType.SearchAndDestroy
or self.move_type == MoveType.DefensiveRetreat
)
and self.engage_ratio < 0.5
and self.can_engage_ratio < 0.5
and len(self.closest_units) < 1
):
if self.group.ground_units and isinstance(command.target, Point2):
# TODO: Unsiege
# Regroup with the ground army
return Action(self.group.center.towards(command.target, self.group_distance), False)
if not relevant_ground_enemies.exists:
if unit.type_id == UnitTypeId.LIBERATOR:
return command
if unit.type_id == UnitTypeId.LIBERATORAG:
return Action(None, False, AbilityId.MORPH_LIBERATORAAMODE)
if unit.type_id == UnitTypeId.LIBERATOR and relevant_ground_enemies.exists:
target: Optional[Unit] = None
enemy: Unit
for enemy in relevant_ground_enemies:
if enemy.distance_to(unit) < 12:
target = enemy
if target is not None:
self.last_siege = time
# TODO: Save position and zone link with current liberator to CooldownManager
return Action(target.position, False, AbilityId.MORPH_LIBERATORAGMODE)
return command
| 38.757576 | 111 | 0.635262 | from typing import Dict, Optional
from sc2.ids.ability_id import AbilityId
from sharpy.combat import Action, MoveType, MicroStep
from sc2.ids.unit_typeid import UnitTypeId
from sc2.unit import Unit
from sc2.position import Point2
class MicroLiberators(MicroStep):
def __init__(self, group_distance: float = -5):
super().__init__()
self.last_siege = 0
self.group_distance = group_distance
self.focus_fired: Dict[int, float] = dict()
self.closest_units: Dict[int, Optional[Unit]] = dict()
def unit_solve_combat(self, unit: Unit, current_command: Action) -> Action:
return self.final_solve(unit, super().unit_solve_combat(unit, current_command))
def final_solve(self, unit: Unit, command: Action) -> Action:
time = self.knowledge.ai.time
relevant_ground_enemies = self.cache.enemy_in_range(unit.position, 10).not_structure.not_flying.visible
if self.move_type == MoveType.PanicRetreat:
return command
if (
(
self.move_type == MoveType.Assault
or self.move_type == MoveType.SearchAndDestroy
or self.move_type == MoveType.DefensiveRetreat
)
and self.engage_ratio < 0.5
and self.can_engage_ratio < 0.5
and len(self.closest_units) < 1
):
if self.group.ground_units and isinstance(command.target, Point2):
return Action(self.group.center.towards(command.target, self.group_distance), False)
if not relevant_ground_enemies.exists:
if unit.type_id == UnitTypeId.LIBERATOR:
return command
if unit.type_id == UnitTypeId.LIBERATORAG:
return Action(None, False, AbilityId.MORPH_LIBERATORAAMODE)
if unit.type_id == UnitTypeId.LIBERATOR and relevant_ground_enemies.exists:
target: Optional[Unit] = None
enemy: Unit
for enemy in relevant_ground_enemies:
if enemy.distance_to(unit) < 12:
target = enemy
if target is not None:
self.last_siege = time
return Action(target.position, False, AbilityId.MORPH_LIBERATORAGMODE)
return command
| true | true |
f7268dd4e5fbd94440e9ab3dc5fe73f4c538070d | 6,616 | py | Python | bindings/python/ensmallen_graph/datasets/string/proteusmirabilis.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | bindings/python/ensmallen_graph/datasets/string/proteusmirabilis.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | bindings/python/ensmallen_graph/datasets/string/proteusmirabilis.py | caufieldjh/ensmallen_graph | 14e98b1cdbc73193a84a913d7d4f2b2b3eb2c43a | [
"MIT"
] | null | null | null | """
This file offers the methods to automatically retrieve the graph Proteus mirabilis.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-02 21:06:19.073950
The undirected graph Proteus mirabilis has 3626 nodes and 280355 weighted
edges, of which none are self-loops. The graph is dense as it has a density
of 0.04266 and has 14 connected components, where the component with most
nodes has 3592 nodes and the component with the least nodes has 2 nodes.
The graph median node degree is 128, the mean node degree is 154.64, and
the node degree mode is 1. The top 5 most central nodes are 529507.PMI2600
(degree 1405), 529507.PMI2826 (degree 1179), 529507.PMI1545 (degree 1018),
529507.PMI3678 (degree 983) and 529507.PMI2101 (degree 965).
References
---------------------
Please cite the following if you use the data:
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.string import ProteusMirabilis
# Then load the graph
graph = ProteusMirabilis()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen_graph import EnsmallenGraph # pylint: disable=import-error
def ProteusMirabilis(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the Proteus mirabilis graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False,
Wether to load the graph as directed or undirected.
By default false.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache_path: str = "graphs",
Where to store the downloaded graphs.
additional_graph_kwargs: Dict,
Additional graph kwargs.
Returns
-----------------------
Instace of Proteus mirabilis graph.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-02 21:06:19.073950
The undirected graph Proteus mirabilis has 3626 nodes and 280355 weighted
edges, of which none are self-loops. The graph is dense as it has a density
of 0.04266 and has 14 connected components, where the component with most
nodes has 3592 nodes and the component with the least nodes has 2 nodes.
The graph median node degree is 128, the mean node degree is 154.64, and
the node degree mode is 1. The top 5 most central nodes are 529507.PMI2600
(degree 1405), 529507.PMI2826 (degree 1179), 529507.PMI1545 (degree 1018),
529507.PMI3678 (degree 983) and 529507.PMI2101 (degree 965).
References
---------------------
Please cite the following if you use the data:
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
Usage example
----------------------
The usage of this graph is relatively straightforward:
.. code:: python
# First import the function to retrieve the graph from the datasets
from ensmallen_graph.datasets.string import ProteusMirabilis
# Then load the graph
graph = ProteusMirabilis()
# Finally, you can do anything with it, for instance, compute its report:
print(graph)
# If you need to run a link prediction task with validation,
# you can split the graph using a connected holdout as follows:
train_graph, validation_graph = graph.connected_holdout(
# You can use an 80/20 split the holdout, for example.
train_size=0.8,
# The random state is used to reproduce the holdout.
random_state=42,
# Wether to show a loading bar.
verbose=True
)
# Remember that, if you need, you can enable the memory-time trade-offs:
train_graph.enable(
vector_sources=True,
vector_destinations=True,
vector_outbounds=True
)
# Consider using the methods made available in the Embiggen package
# to run graph embedding or link prediction tasks.
"""
return AutomaticallyRetrievedGraph(
graph_name="ProteusMirabilis",
dataset="string",
directed=directed,
verbose=verbose,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| 35.005291 | 223 | 0.700574 | from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen_graph import EnsmallenGraph
def ProteusMirabilis(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/string",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
return AutomaticallyRetrievedGraph(
graph_name="ProteusMirabilis",
dataset="string",
directed=directed,
verbose=verbose,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| true | true |
f7268f4b4bb9d783f2b2aaad61a415d7093b910f | 65 | py | Python | tools/__init__.py | mchonan1996/safetyculture-sdk-python | 9737b8716698844dc09316baed0d50fc55c6ea8b | [
"Apache-2.0"
] | 22 | 2017-03-03T05:16:46.000Z | 2021-12-28T20:39:02.000Z | tools/__init__.py | mchonan1996/safetyculture-sdk-python | 9737b8716698844dc09316baed0d50fc55c6ea8b | [
"Apache-2.0"
] | 12 | 2017-02-28T06:29:07.000Z | 2021-03-25T21:42:14.000Z | tools/__init__.py | mchonan1996/safetyculture-sdk-python | 9737b8716698844dc09316baed0d50fc55c6ea8b | [
"Apache-2.0"
] | 15 | 2017-02-23T00:49:18.000Z | 2021-12-28T20:39:20.000Z | from .exporter import csvExporter
from .exporter import exporter
| 21.666667 | 33 | 0.846154 | from .exporter import csvExporter
from .exporter import exporter
| true | true |
f7268fd09962820734816832c033e7525fcd9ab8 | 432 | py | Python | website/util/time.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | website/util/time.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | website/util/time.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import time
from datetime import datetime
def get_timestamp():
return int(time.time())
def throttle_period_expired(timestamp, throttle):
if not timestamp:
return True
elif isinstance(timestamp, datetime):
return (datetime.utcnow() - timestamp).total_seconds() > throttle
else:
return (get_timestamp() - timestamp) > throttle
| 24 | 73 | 0.699074 |
from __future__ import absolute_import
import time
from datetime import datetime
def get_timestamp():
return int(time.time())
def throttle_period_expired(timestamp, throttle):
if not timestamp:
return True
elif isinstance(timestamp, datetime):
return (datetime.utcnow() - timestamp).total_seconds() > throttle
else:
return (get_timestamp() - timestamp) > throttle
| true | true |
f726902376e280ba863a7c19c43b900218daf48a | 4,130 | py | Python | alipay/aop/api/request/AlipayMarketingCampaignPromotionactivityCustomerReceiveRequest.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 213 | 2018-08-27T16:49:32.000Z | 2021-12-29T04:34:12.000Z | alipay/aop/api/request/AlipayMarketingCampaignPromotionactivityCustomerReceiveRequest.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 29 | 2018-09-29T06:43:00.000Z | 2021-09-02T03:27:32.000Z | alipay/aop/api/request/AlipayMarketingCampaignPromotionactivityCustomerReceiveRequest.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 59 | 2018-08-27T16:59:26.000Z | 2022-03-25T10:08:15.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayMarketingCampaignPromotionactivityCustomerReceiveModel import AlipayMarketingCampaignPromotionactivityCustomerReceiveModel
class AlipayMarketingCampaignPromotionactivityCustomerReceiveRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
if isinstance(value, AlipayMarketingCampaignPromotionactivityCustomerReceiveModel):
self._biz_content = value
else:
self._biz_content = AlipayMarketingCampaignPromotionactivityCustomerReceiveModel.from_alipay_dict(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'alipay.marketing.campaign.promotionactivity.customer.receive'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
| 28.482759 | 155 | 0.658111 |
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayMarketingCampaignPromotionactivityCustomerReceiveModel import AlipayMarketingCampaignPromotionactivityCustomerReceiveModel
class AlipayMarketingCampaignPromotionactivityCustomerReceiveRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
if isinstance(value, AlipayMarketingCampaignPromotionactivityCustomerReceiveModel):
self._biz_content = value
else:
self._biz_content = AlipayMarketingCampaignPromotionactivityCustomerReceiveModel.from_alipay_dict(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'alipay.marketing.campaign.promotionactivity.customer.receive'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
| true | true |
f7269048fed394fc95bcb70e5e4e1c5ecb768bd1 | 2,752 | py | Python | py_pdf_term/analysis/_analysis/occurrences/term.py | kumachan-mis/pdf-slides-term | cf3319e4de723bd9424d23141803342d3c649103 | [
"MIT"
] | 1 | 2021-01-08T16:05:30.000Z | 2021-01-08T16:05:30.000Z | py_pdf_term/analysis/_analysis/occurrences/term.py | kumachan-mis/py-slides-term | 1e9337b97ae8968950489e728fc7aeeeb7eb1f4b | [
"MIT"
] | 21 | 2021-01-03T13:50:59.000Z | 2021-06-17T00:27:49.000Z | py_pdf_term/analysis/_analysis/occurrences/term.py | kumachan-mis/pdf-slides-term | cf3319e4de723bd9424d23141803342d3c649103 | [
"MIT"
] | null | null | null | from dataclasses import dataclass
from typing import Set, Dict
from ..runner import AnalysisRunner
from py_pdf_term.candidates import DomainCandidateTermList
from py_pdf_term._common.data import Term
@dataclass(frozen=True)
class DomainTermOccurrence:
domain: str
# unique domain name
term_freq: Dict[str, int]
# brute force counting of lemmatized term occurrences in the domain
# count even if the lemmatized term occurs as a part of a lemmatized phrase
doc_term_freq: Dict[str, int]
# number of documents in the domain that contain the lemmatized term
# count even if the lemmatized term occurs as a part of a lemmatized phrase
@dataclass(frozen=True)
class _DomainTermOccurrence:
domain: str
# unique domain name
term_freq: Dict[str, int]
# brute force counting of lemmatized term occurrences in the domain
# count even if the term occurs as a part of a lemmatized phrase
doc_term_set: Dict[str, Set[int]]
# set of document IDs in the domain that contain the lemmatized term
# add even if the lemmatized term occurs as a part of a lemmatized phrase
class TermOccurrenceAnalyzer:
def __init__(self, ignore_augmented: bool = True) -> None:
self._runner = AnalysisRunner(ignore_augmented=ignore_augmented)
def analyze(
self, domain_candidates: DomainCandidateTermList
) -> DomainTermOccurrence:
domain_candidates_set = domain_candidates.to_candidates_str_set(
lambda candidate: candidate.lemma()
)
def update(
term_occ: _DomainTermOccurrence,
pdf_id: int,
page_num: int,
subcandidate: Term,
) -> None:
subcandidate_lemma = subcandidate.lemma()
if subcandidate_lemma not in domain_candidates_set:
return
term_occ.term_freq[subcandidate_lemma] = (
term_occ.term_freq.get(subcandidate_lemma, 0) + 1
)
doc_term_set = term_occ.doc_term_set.get(subcandidate_lemma, set())
doc_term_set.add(pdf_id)
term_occ.doc_term_set[subcandidate_lemma] = doc_term_set
term_occ = self._runner.run_through_subcandidates(
domain_candidates,
_DomainTermOccurrence(domain_candidates.domain, dict(), dict()),
update,
)
term_occ = self._finalize(term_occ)
return term_occ
def _finalize(self, term_occ: _DomainTermOccurrence) -> DomainTermOccurrence:
doc_term_freq = {
candidate_str: len(doc_term_set)
for candidate_str, doc_term_set in term_occ.doc_term_set.items()
}
return DomainTermOccurrence(term_occ.domain, term_occ.term_freq, doc_term_freq)
| 37.189189 | 87 | 0.68968 | from dataclasses import dataclass
from typing import Set, Dict
from ..runner import AnalysisRunner
from py_pdf_term.candidates import DomainCandidateTermList
from py_pdf_term._common.data import Term
@dataclass(frozen=True)
class DomainTermOccurrence:
domain: str
term_freq: Dict[str, int]
doc_term_freq: Dict[str, int]
@dataclass(frozen=True)
class _DomainTermOccurrence:
domain: str
term_freq: Dict[str, int]
doc_term_set: Dict[str, Set[int]]
class TermOccurrenceAnalyzer:
def __init__(self, ignore_augmented: bool = True) -> None:
self._runner = AnalysisRunner(ignore_augmented=ignore_augmented)
def analyze(
self, domain_candidates: DomainCandidateTermList
) -> DomainTermOccurrence:
domain_candidates_set = domain_candidates.to_candidates_str_set(
lambda candidate: candidate.lemma()
)
def update(
term_occ: _DomainTermOccurrence,
pdf_id: int,
page_num: int,
subcandidate: Term,
) -> None:
subcandidate_lemma = subcandidate.lemma()
if subcandidate_lemma not in domain_candidates_set:
return
term_occ.term_freq[subcandidate_lemma] = (
term_occ.term_freq.get(subcandidate_lemma, 0) + 1
)
doc_term_set = term_occ.doc_term_set.get(subcandidate_lemma, set())
doc_term_set.add(pdf_id)
term_occ.doc_term_set[subcandidate_lemma] = doc_term_set
term_occ = self._runner.run_through_subcandidates(
domain_candidates,
_DomainTermOccurrence(domain_candidates.domain, dict(), dict()),
update,
)
term_occ = self._finalize(term_occ)
return term_occ
def _finalize(self, term_occ: _DomainTermOccurrence) -> DomainTermOccurrence:
doc_term_freq = {
candidate_str: len(doc_term_set)
for candidate_str, doc_term_set in term_occ.doc_term_set.items()
}
return DomainTermOccurrence(term_occ.domain, term_occ.term_freq, doc_term_freq)
| true | true |
f72690a7b3248a10457383f38300fee9412153dd | 124,514 | py | Python | Compiler/types.py | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | null | null | null | Compiler/types.py | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | null | null | null | Compiler/types.py | lemonviv/Pivot-SPDZ | f3db87d8849e5f9fa39f321d85feec83107ee405 | [
"BSD-2-Clause"
] | null | null | null | from Compiler.program import Tape
from Compiler.exceptions import *
from Compiler.instructions import *
from Compiler.instructions_base import *
from .floatingpoint import two_power
from . import comparison, floatingpoint
import math
from . import util
import operator
from functools import reduce
class ClientMessageType:
""" Enum to define type of message sent to external client. Each may be array of length n."""
# No client message type to be sent, for backwards compatibility - virtual machine relies on this value
NoType = 0
# 3 x sint x n
TripleShares = 1
# 1 x cint x n
ClearModpInt = 2
# 1 x regint x n
Int32 = 3
# 1 x cint (fixed point left shifted by precision) x n
ClearModpFix = 4
class MPCThread(object):
def __init__(self, target, name, args = [], runtime_arg = None):
""" Create a thread from a callable object. """
if not callable(target):
raise CompilerError('Target %s for thread %s is not callable' % (target,name))
self.name = name
self.tape = Tape(program.name + '-' + name, program)
self.target = target
self.args = args
self.runtime_arg = runtime_arg
self.running = 0
def start(self, runtime_arg = None):
self.running += 1
program.start_thread(self, runtime_arg or self.runtime_arg)
def join(self):
if not self.running:
raise CompilerError('Thread %s is not running' % self.name)
self.running -= 1
program.stop_thread(self)
def vectorize(operation):
def vectorized_operation(self, *args, **kwargs):
if len(args):
if (isinstance(args[0], Tape.Register) or isinstance(args[0], sfloat)) \
and args[0].size != self.size:
raise CompilerError('Different vector sizes of operands')
set_global_vector_size(self.size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
return vectorized_operation
def vectorize_max(operation):
def vectorized_operation(self, *args, **kwargs):
size = self.size
for arg in args:
try:
size = max(size, arg.size)
except AttributeError:
pass
set_global_vector_size(size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
return vectorized_operation
def vectorized_classmethod(function):
def vectorized_function(cls, *args, **kwargs):
size = None
if 'size' in kwargs:
size = kwargs.pop('size')
if size:
set_global_vector_size(size)
res = function(cls, *args, **kwargs)
reset_global_vector_size()
else:
res = function(cls, *args, **kwargs)
return res
return classmethod(vectorized_function)
def vectorize_init(function):
def vectorized_init(*args, **kwargs):
size = None
if len(args) > 1 and (isinstance(args[1], Tape.Register) or \
isinstance(args[1], sfloat)):
size = args[1].size
if 'size' in kwargs and kwargs['size'] is not None \
and kwargs['size'] != size:
raise CompilerError('Mismatch in vector size')
if 'size' in kwargs and kwargs['size']:
size = kwargs['size']
if size is not None:
set_global_vector_size(size)
res = function(*args, **kwargs)
reset_global_vector_size()
else:
res = function(*args, **kwargs)
return res
return vectorized_init
def set_instruction_type(operation):
def instruction_typed_operation(self, *args, **kwargs):
set_global_instruction_type(self.instruction_type)
res = operation(self, *args, **kwargs)
reset_global_instruction_type()
return res
return instruction_typed_operation
def read_mem_value(operation):
def read_mem_operation(self, *args, **kwargs):
if len(args) > 0 and isinstance(args[0], MemValue):
args = (args[0].read(),) + args[1:]
return operation(self, *args, **kwargs)
return read_mem_operation
class _number(object):
def square(self):
return self * self
def __add__(self, other):
if other is 0:
return self
else:
return self.add(other)
def __mul__(self, other):
if other is 0:
return 0
elif other is 1:
return self
else:
return self.mul(other)
__radd__ = __add__
__rmul__ = __mul__
@vectorize
def __pow__(self, exp):
if isinstance(exp, int) and exp >= 0:
if exp == 0:
return self.__class__(1)
exp = bin(exp)[3:]
res = self
for i in exp:
res = res.square()
if i == '1':
res *= self
return res
else:
return NotImplemented
def mul_no_reduce(self, other, res_params=None):
return self * other
def reduce_after_mul(self):
return self
def pow2(self, bit_length=None, security=None):
return 2**self
def min(self, other):
return (self < other).if_else(self, other)
def max(self, other):
return (self < other).if_else(other, self)
class _int(object):
def if_else(self, a, b):
if hasattr(a, 'for_mux'):
f, a, b = a.for_mux(b)
else:
f = lambda x: x
return f(self * (a - b) + b)
def cond_swap(self, a, b):
prod = self * (a - b)
return a - prod, b + prod
def bit_xor(self, other):
return self + other - 2 * self * other
class _gf2n(object):
def if_else(self, a, b):
return b ^ self * self.hard_conv(a ^ b)
def cond_swap(self, a, b, t=None):
prod = self * self.hard_conv(a ^ b)
res = a ^ prod, b ^ prod
if t is None:
return res
else:
return tuple(t.conv(r) for r in res)
def bit_xor(self, other):
return self ^ other
class _structure(object):
MemValue = classmethod(lambda cls, value: MemValue(cls.conv(value)))
@classmethod
def Array(cls, size, *args, **kwargs):
return Array(size, cls, *args, **kwargs)
@classmethod
def Matrix(cls, rows, columns, *args, **kwargs):
return Matrix(rows, columns, cls, *args, **kwargs)
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
return sum(row[k].mul_no_reduce(matrix[k].get_vector(),
res_params) \
for k in range(len(row))).reduce_after_mul()
class _register(Tape.Register, _number, _structure):
@staticmethod
def n_elements():
return 1
@vectorized_classmethod
def conv(cls, val):
if isinstance(val, MemValue):
val = val.read()
if isinstance(val, cls):
return val
elif not isinstance(val, _register):
try:
return type(val)(cls.conv(v) for v in val)
except TypeError:
pass
except CompilerError:
pass
return cls(val)
@vectorized_classmethod
@read_mem_value
def hard_conv(cls, val):
if type(val) == cls:
return val
elif not isinstance(val, _register):
try:
return val.hard_conv_me(cls)
except AttributeError:
try:
return type(val)(cls.hard_conv(v) for v in val)
except TypeError:
pass
return cls(val)
@vectorized_classmethod
@set_instruction_type
def _load_mem(cls, address, direct_inst, indirect_inst):
res = cls()
if isinstance(address, _register):
indirect_inst(res, cls._expand_address(address,
get_global_vector_size()))
else:
direct_inst(res, address)
return res
@staticmethod
def _expand_address(address, size):
address = regint.conv(address)
if size > 1 and address.size == 1:
res = regint(size=size)
for i in range(size):
movint(res[i], address + regint(i, size=1))
return res
else:
return address
@set_instruction_type
def _store_in_mem(self, address, direct_inst, indirect_inst):
if isinstance(address, _register):
indirect_inst(self, self._expand_address(address, self.size))
else:
direct_inst(self, address)
@classmethod
def prep_res(cls, other):
return cls()
@staticmethod
def bit_compose(bits):
return sum(b << i for i,b in enumerate(bits))
@classmethod
def malloc(cls, size):
return program.malloc(size, cls)
@set_instruction_type
def __init__(self, reg_type, val, size):
if isinstance(val, (tuple, list)):
size = len(val)
super(_register, self).__init__(reg_type, program.curr_tape, size=size)
if isinstance(val, int):
self.load_int(val)
elif isinstance(val, (tuple, list)):
for i, x in enumerate(val):
self.mov(self[i], type(self)(x, size=1))
elif val is not None:
self.load_other(val)
def sizeof(self):
return self.size
def extend(self, n):
return self
def expand_to_vector(self, size=None):
if size is None:
size = get_global_vector_size()
if self.size == size:
return self
assert self.size == 1
res = type(self)(size=size)
for i in range(size):
movs(res[i], self)
return res
class _clear(_register):
__slots__ = []
mov = staticmethod(movc)
@vectorized_classmethod
@set_instruction_type
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmemc(regint(start), regint(end))
@set_instruction_type
@vectorize
def load_other(self, val):
if isinstance(val, type(self)):
movc(self, val)
else:
self.convert_from(val)
@vectorize
@read_mem_value
def convert_from(self, val):
if not isinstance(val, regint):
val = regint(val)
convint(self, val)
@set_instruction_type
@vectorize
def print_reg(self, comment=''):
print_reg(self, comment)
@set_instruction_type
@vectorize
def print_reg_plain(self):
print_reg_plain(self)
@set_instruction_type
@vectorize
def raw_output(self):
raw_output(self)
@set_instruction_type
@read_mem_value
@vectorize
def clear_op(self, other, c_inst, ci_inst, reverse=False):
cls = self.__class__
res = self.prep_res(other)
if isinstance(other, cls):
c_inst(res, self, other)
elif isinstance(other, int):
if self.in_immediate_range(other):
ci_inst(res, self, other)
else:
if reverse:
c_inst(res, cls(other), self)
else:
c_inst(res, self, cls(other))
else:
return NotImplemented
return res
@set_instruction_type
@read_mem_value
@vectorize
def coerce_op(self, other, inst, reverse=False):
cls = self.__class__
res = cls()
if isinstance(other, int):
other = cls(other)
elif not isinstance(other, cls):
return NotImplemented
if reverse:
inst(res, other, self)
else:
inst(res, self, other)
return res
def add(self, other):
return self.clear_op(other, addc, addci)
def mul(self, other):
return self.clear_op(other, mulc, mulci)
def __sub__(self, other):
return self.clear_op(other, subc, subci)
def __rsub__(self, other):
return self.clear_op(other, subc, subcfi, True)
def __truediv__(self, other):
return self.clear_op(other, divc, divci)
def __rtruediv__(self, other):
return self.coerce_op(other, divc, True)
def __eq__(self, other):
if isinstance(other, (_clear,int)):
return regint(self) == other
else:
return NotImplemented
def __ne__(self, other):
return 1 - (self == other)
def __and__(self, other):
return self.clear_op(other, andc, andci)
def __xor__(self, other):
return self.clear_op(other, xorc, xorci)
def __or__(self, other):
return self.clear_op(other, orc, orci)
__rand__ = __and__
__rxor__ = __xor__
__ror__ = __or__
def reveal(self):
return self
class cint(_clear, _int):
" Clear mod p integer type. """
__slots__ = []
instruction_type = 'modp'
reg_type = 'c'
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
res = [cls() for i in range(n)]
readsocketc(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketc(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
""" Send a list of modp integers to socket """
writesocketc(client_id, message_type, *values)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldmc, ldmci)
def store_in_mem(self, address):
self._store_in_mem(address, stmc, stmci)
@staticmethod
def in_immediate_range(value):
return value < 2**31 and value >= -2**31
def __init__(self, val=None, size=None):
super(cint, self).__init__('c', val=val, size=size)
@vectorize
def load_int(self, val):
if val:
# +1 for sign
program.curr_tape.require_bit_length(1 + int(math.ceil(math.log(abs(val)))))
if self.in_immediate_range(val):
ldi(self, val)
else:
max = 2**31 - 1
sign = abs(val) // val
val = abs(val)
chunks = []
while val:
mod = val % max
val = (val - mod) // max
chunks.append(mod)
sum = cint(sign * chunks.pop())
for i,chunk in enumerate(reversed(chunks)):
sum *= max
if i == len(chunks) - 1:
addci(self, sum, sign * chunk)
elif chunk:
sum += sign * chunk
def to_regint(self, n_bits=None, dest=None):
dest = regint() if dest is None else dest
convmodp(dest, self, bitlength=n_bits)
return dest
def __mod__(self, other):
return self.clear_op(other, modc, modci)
def __rmod__(self, other):
return self.coerce_op(other, modc, True)
def __lt__(self, other):
if isinstance(other, (type(self),int)):
return regint(self) < other
else:
return NotImplemented
def __gt__(self, other):
if isinstance(other, (type(self),int)):
return regint(self) > other
else:
return NotImplemented
def __le__(self, other):
return 1 - (self > other)
def __ge__(self, other):
return 1 - (self < other)
@vectorize
def __eq__(self, other):
if not isinstance(other, (_clear, int)):
return NotImplemented
res = 1
remaining = program.bit_length
while remaining > 0:
if isinstance(other, cint):
o = other.to_regint(min(remaining, 64))
else:
o = other % 2 ** 64
res *= (self.to_regint(min(remaining, 64)) == o)
self >>= 64
other >>= 64
remaining -= 64
return res
def __lshift__(self, other):
return self.clear_op(other, shlc, shlci)
def __rshift__(self, other):
return self.clear_op(other, shrc, shrci)
def __neg__(self):
return 0 - self
def __abs__(self):
return (self >= 0).if_else(self, -self)
@vectorize
def __invert__(self):
res = cint()
notc(res, self, program.bit_length)
return res
def __rpow__(self, base):
if base == 2:
return 1 << self
else:
return NotImplemented
@vectorize
def __rlshift__(self, other):
return cint(other) << self
@vectorize
def __rrshift__(self, other):
return cint(other) >> self
@read_mem_value
def mod2m(self, other, bit_length=None, signed=None):
return self % 2**other
@read_mem_value
def right_shift(self, other, bit_length=None):
return self >> other
@read_mem_value
def greater_than(self, other, bit_length=None):
return self > other
def bit_decompose(self, bit_length=None):
if bit_length == 0:
return []
bit_length = bit_length or program.bit_length
return floatingpoint.bits(self, bit_length)
def legendre(self):
res = cint()
legendrec(res, self)
return res
def digest(self, num_bytes):
res = cint()
digestc(res, self, num_bytes)
return res
def print_if(self, string):
cond_print_str(self, string)
class cgf2n(_clear, _gf2n):
__slots__ = []
instruction_type = 'gf2n'
reg_type = 'cg'
@classmethod
def bit_compose(cls, bits, step=None):
size = bits[0].size
res = cls(size=size)
vgbitcom(size, res, step or 1, *bits)
return res
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, gldmc, gldmci)
def store_in_mem(self, address):
self._store_in_mem(address, gstmc, gstmci)
@staticmethod
def in_immediate_range(value):
return value < 2**32 and value >= 0
def __init__(self, val=None, size=None):
super(cgf2n, self).__init__('cg', val=val, size=size)
@vectorize
def load_int(self, val):
if val < 0:
raise CompilerError('Negative GF2n immediate')
if self.in_immediate_range(val):
gldi(self, val)
else:
chunks = []
while val:
mod = val % 2**32
val >>= 32
chunks.append(mod)
sum = cgf2n(chunks.pop())
for i,chunk in enumerate(reversed(chunks)):
sum <<= 32
if i == len(chunks) - 1:
gaddci(self, sum, chunk)
elif chunk:
sum += chunk
def __mul__(self, other):
return super(cgf2n, self).__mul__(other)
def __neg__(self):
return self
@vectorize
def __invert__(self):
res = cgf2n()
gnotc(res, self)
return res
@vectorize
def __lshift__(self, other):
if isinstance(other, int):
res = cgf2n()
gshlci(res, self, other)
return res
else:
return NotImplemented
@vectorize
def __rshift__(self, other):
if isinstance(other, int):
res = cgf2n()
gshrci(res, self, other)
return res
else:
return NotImplemented
@vectorize
def bit_decompose(self, bit_length=None, step=None):
bit_length = bit_length or program.galois_length
step = step or 1
res = [type(self)() for _ in range(bit_length // step)]
gbitdec(self, step, *res)
return res
class regint(_register, _int):
__slots__ = []
reg_type = 'ci'
instruction_type = 'modp'
mov = staticmethod(movint)
@classmethod
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmemint(regint(start), regint(end))
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldmint, ldminti)
def store_in_mem(self, address):
self._store_in_mem(address, stmint, stminti)
@vectorized_classmethod
def pop(cls):
res = cls()
popint(res)
return res
@vectorized_classmethod
def push(cls, value):
pushint(cls.conv(value))
@vectorized_classmethod
def get_random(cls, bit_length):
""" Public insecure randomness """
if isinstance(bit_length, int):
bit_length = regint(bit_length)
res = cls()
rand(res, bit_length)
return res
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
""" Receive n register values from socket """
res = [cls() for i in range(n)]
readsocketint(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorized_classmethod
def read_client_public_key(cls, client_id):
""" Receive 8 register values from socket containing client public key."""
res = [cls() for i in range(8)]
readclientpublickey(client_id, *res)
return res
@vectorized_classmethod
def init_secure_socket(cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8):
""" Use 8 register values containing client public key."""
initsecuresocket(client_id, w1, w2, w3, w4, w5, w6, w7, w8)
@vectorized_classmethod
def resp_secure_socket(cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8):
""" Receive 8 register values from socket containing client public key."""
respsecuresocket(client_id, w1, w2, w3, w4, w5, w6, w7, w8)
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketint(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
""" Send a list of integers to socket """
writesocketint(client_id, message_type, *values)
@vectorize_init
def __init__(self, val=None, size=None):
super(regint, self).__init__(self.reg_type, val=val, size=size)
def load_int(self, val):
if cint.in_immediate_range(val):
ldint(self, val)
else:
lower = val % 2**32
upper = val >> 32
if lower >= 2**31:
lower -= 2**32
upper += 1
addint(self, regint(upper) * regint(2**16)**2, regint(lower))
@read_mem_value
def load_other(self, val):
if isinstance(val, cgf2n):
gconvgf2n(self, val)
elif isinstance(val, regint):
addint(self, val, regint(0))
else:
try:
val.to_regint(dest=self)
except AttributeError:
raise CompilerError("Cannot convert '%s' to integer" % \
type(val))
@vectorize
@read_mem_value
def int_op(self, other, inst, reverse=False):
try:
other = self.conv(other)
except:
return NotImplemented
res = regint()
if reverse:
inst(res, other, self)
else:
inst(res, self, other)
return res
def add(self, other):
return self.int_op(other, addint)
def __sub__(self, other):
return self.int_op(other, subint)
def __rsub__(self, other):
return self.int_op(other, subint, True)
def mul(self, other):
return self.int_op(other, mulint)
def __neg__(self):
return 0 - self
def __floordiv__(self, other):
return self.int_op(other, divint)
def __rfloordiv__(self, other):
return self.int_op(other, divint, True)
__truediv__ = __floordiv__
__rtruediv__ = __rfloordiv__
def __mod__(self, other):
return self - (self / other) * other
def __rmod__(self, other):
return regint(other) % self
def __rpow__(self, other):
return other**cint(self)
def __eq__(self, other):
return self.int_op(other, eqc)
def __ne__(self, other):
return 1 - (self == other)
def __lt__(self, other):
return self.int_op(other, ltc)
def __gt__(self, other):
return self.int_op(other, gtc)
def __le__(self, other):
return 1 - (self > other)
def __ge__(self, other):
return 1 - (self < other)
def __lshift__(self, other):
if isinstance(other, int):
return self * 2**other
else:
return regint(cint(self) << other)
def __rshift__(self, other):
if isinstance(other, int):
return self / 2**other
else:
return regint(cint(self) >> other)
def __rlshift__(self, other):
return regint(other << cint(self))
def __rrshift__(self, other):
return regint(other >> cint(self))
def __and__(self, other):
return regint(other & cint(self))
def __or__(self, other):
return regint(other | cint(self))
def __xor__(self, other):
return regint(other ^ cint(self))
__rand__ = __and__
__ror__ = __or__
__rxor__ = __xor__
def mod2m(self, *args, **kwargs):
return cint(self).mod2m(*args, **kwargs)
@vectorize
def bit_decompose(self, bit_length=None):
bit_length = bit_length or min(64, program.bit_length)
if bit_length > 64:
raise CompilerError('too many bits demanded')
res = [regint() for i in range(bit_length)]
bitdecint(self, *res)
return res
@staticmethod
def bit_compose(bits):
two = regint(2)
res = 0
for bit in reversed(bits):
res *= two
res += bit
return res
def reveal(self):
return self
def print_reg_plain(self):
print_int(self)
def print_if(self, string):
cint(self).print_if(string)
class localint(object):
""" Local integer that must prevented from leaking into the secure
computation. Uses regint internally. """
def __init__(self, value=None):
self._v = regint(value)
self.size = 1
def output(self):
self._v.print_reg_plain()
__lt__ = lambda self, other: localint(self._v < other)
__le__ = lambda self, other: localint(self._v <= other)
__gt__ = lambda self, other: localint(self._v > other)
__ge__ = lambda self, other: localint(self._v >= other)
__eq__ = lambda self, other: localint(self._v == other)
__ne__ = lambda self, other: localint(self._v != other)
class _secret(_register):
__slots__ = []
mov = staticmethod(movs)
PreOR = staticmethod(lambda l: floatingpoint.PreORC(l))
PreOp = staticmethod(lambda op, l: floatingpoint.PreOpL(op, l))
@vectorized_classmethod
@set_instruction_type
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmems(regint(start), regint(end))
@vectorized_classmethod
@set_instruction_type
def get_input_from(cls, player):
""" Secret input """
res = cls()
asm_input(res, player)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_triple(cls):
""" Secret random triple according to security model """
res = (cls(), cls(), cls())
triple(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_bit(cls):
""" Secret random bit according to security model """
res = cls()
bit(res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_square(cls):
""" Secret random square according to security model """
res = (cls(), cls())
square(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_inverse(cls):
""" Secret random inverse according to security model """
res = (cls(), cls())
inverse(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_input_mask_for(cls, player):
res = cls()
inputmask(res, player)
return res
@classmethod
@set_instruction_type
def dot_product(cls, x, y):
x = list(x)
set_global_vector_size(x[0].size)
res = cls()
dotprods(res, x, y)
reset_global_vector_size()
return res
@classmethod
@set_instruction_type
def row_matrix_mul(cls, row, matrix, res_params=None):
assert len(row) == len(matrix)
size = len(matrix[0])
res = cls(size=size)
dotprods(*sum(([res[j], row, [matrix[k][j] for k in range(len(row))]]
for j in range(size)), []))
return res
@classmethod
@set_instruction_type
def matrix_mul(cls, A, B, n, res_params=None):
assert len(A) % n == 0
assert len(B) % n == 0
size = len(A) * len(B) // n**2
res = cls(size=size)
n_rows = len(A) // n
n_cols = len(B) // n
dotprods(*sum(([res[j], [A[j // n_cols * n + k] for k in range(n)],
[B[k * n_cols + j % n_cols] for k in range(n)]]
for j in range(size)), []))
return res
def __init__(self, reg_type, val=None, size=None):
if isinstance(val, self.clear_type):
size = val.size
super(_secret, self).__init__(reg_type, val=val, size=size)
@set_instruction_type
@vectorize
def load_int(self, val):
if self.clear_type.in_immediate_range(val):
ldsi(self, val)
else:
self.load_clear(self.clear_type(val))
@vectorize
def load_clear(self, val):
addm(self, self.__class__(0), val)
@set_instruction_type
@read_mem_value
@vectorize
def load_other(self, val):
if isinstance(val, self.clear_type):
self.load_clear(val)
elif isinstance(val, type(self)):
movs(self, val)
else:
self.load_clear(self.clear_type(val))
def _new_by_number(self, i):
res = type(self)(size=1)
res.i = i
res.program = self.program
return res
@set_instruction_type
@read_mem_value
@vectorize
def secret_op(self, other, s_inst, m_inst, si_inst, reverse=False):
cls = self.__class__
res = self.prep_res(other)
if isinstance(other, regint):
other = res.clear_type(other)
if isinstance(other, cls):
s_inst(res, self, other)
elif isinstance(other, res.clear_type):
if reverse:
m_inst(res, other, self)
else:
m_inst(res, self, other)
elif isinstance(other, int):
if self.clear_type.in_immediate_range(other):
si_inst(res, self, other)
else:
if reverse:
m_inst(res, res.clear_type(other), self)
else:
m_inst(res, self, res.clear_type(other))
else:
return NotImplemented
return res
def add(self, other):
return self.secret_op(other, adds, addm, addsi)
@set_instruction_type
def mul(self, other):
if isinstance(other, _secret) and max(self.size, other.size) > 1 \
and min(self.size, other.size) == 1:
x, y = (other, self) if self.size < other.size else (self, other)
res = type(self)(size=x.size)
mulrs(res, x, y)
return res
return self.secret_op(other, muls, mulm, mulsi)
def __sub__(self, other):
return self.secret_op(other, subs, subml, subsi)
def __rsub__(self, other):
return self.secret_op(other, subs, submr, subsfi, True)
@vectorize
def __truediv__(self, other):
return self * (self.clear_type(1) / other)
@vectorize
def __rtruediv__(self, other):
a,b = self.get_random_inverse()
return other * a / (a * self).reveal()
@set_instruction_type
@vectorize
def square(self):
res = self.__class__()
sqrs(res, self)
return res
@set_instruction_type
@vectorize
def reveal(self):
res = self.clear_type()
asm_open(res, self)
return res
@set_instruction_type
def reveal_to(self, player):
masked = self.__class__()
startprivateoutput(masked, self, player)
stopprivateoutput(masked.reveal(), player)
class sint(_secret, _int):
" Shared mod p integer type. """
__slots__ = []
instruction_type = 'modp'
clear_type = cint
reg_type = 's'
PreOp = staticmethod(floatingpoint.PreOpL)
PreOR = staticmethod(floatingpoint.PreOR)
get_type = staticmethod(lambda n: sint)
@vectorized_classmethod
def get_random_int(cls, bits):
""" Secret random n-bit number according to security model """
res = sint()
comparison.PRandInt(res, bits)
return res
@vectorized_classmethod
def get_input_from(cls, player):
""" Secret input """
res = cls()
inputmixed('int', res, player)
return res
@classmethod
def get_raw_input_from(cls, player):
res = cls()
startinput(player, 1)
stopinput(player, res)
return res
@classmethod
def receive_from_client(cls, n, client_id, message_type=ClientMessageType.NoType):
""" Securely obtain shares of n values input by a client """
# send shares of a triple to client
triples = list(itertools.chain(*(sint.get_random_triple() for i in range(n))))
sint.write_shares_to_socket(client_id, triples, message_type)
received = cint.read_from_socket(client_id, n)
y = [0] * n
for i in range(n):
y[i] = received[i] - triples[i * 3]
return y
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
""" Receive n shares and MAC shares from socket """
res = [cls() for i in range(n)]
readsockets(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
""" Send share and MAC share to socket """
writesockets(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
""" Send a list of shares and MAC shares to socket """
writesockets(client_id, message_type, *values)
@vectorize
def write_share_to_socket(self, client_id, message_type=ClientMessageType.NoType):
""" Send only share to socket """
writesocketshare(client_id, message_type, self)
@vectorized_classmethod
def write_shares_to_socket(cls, client_id, values, message_type=ClientMessageType.NoType, include_macs=False):
""" Send shares of a list of values to a specified client socket """
if include_macs:
writesockets(client_id, message_type, *values)
else:
writesocketshare(client_id, message_type, *values)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldms, ldmsi)
def store_in_mem(self, address):
self._store_in_mem(address, stms, stmsi)
def __init__(self, val=None, size=None):
super(sint, self).__init__('s', val=val, size=size)
@vectorize
def __neg__(self):
return 0 - self
@vectorize
def __abs__(self):
return (self >= 0).if_else(self, -self)
@read_mem_value
@vectorize
def __lt__(self, other, bit_length=None, security=None):
res = sint()
comparison.LTZ(res, self - other,
(bit_length or program.bit_length) + 1,
security or program.security)
return res
@read_mem_value
@vectorize
def __gt__(self, other, bit_length=None, security=None):
res = sint()
comparison.LTZ(res, other - self,
(bit_length or program.bit_length) + 1,
security or program.security)
return res
def __le__(self, other, bit_length=None, security=None):
return 1 - self.greater_than(other, bit_length, security)
def __ge__(self, other, bit_length=None, security=None):
return 1 - self.less_than(other, bit_length, security)
@read_mem_value
@vectorize
def __eq__(self, other, bit_length=None, security=None):
return floatingpoint.EQZ(self - other, bit_length or program.bit_length,
security or program.security)
def __ne__(self, other, bit_length=None, security=None):
return 1 - self.equal(other, bit_length, security)
less_than = __lt__
greater_than = __gt__
less_equal = __le__
greater_equal = __ge__
equal = __eq__
not_equal = __ne__
@vectorize
def __mod__(self, modulus):
if isinstance(modulus, int):
l = math.log(modulus, 2)
if 2**int(round(l)) == modulus:
return self.mod2m(int(l))
raise NotImplementedError('Modulo only implemented for powers of two.')
@read_mem_value
def mod2m(self, m, bit_length=None, security=None, signed=True):
bit_length = bit_length or program.bit_length
security = security or program.security
if isinstance(m, int):
if m == 0:
return 0
if m >= bit_length:
return self
res = sint()
comparison.Mod2m(res, self, bit_length, m, security, signed)
else:
res, pow2 = floatingpoint.Trunc(self, bit_length, m, security, True)
return res
@vectorize
def __rpow__(self, base):
if base == 2:
return self.pow2()
else:
return NotImplemented
@vectorize
def pow2(self, bit_length=None, security=None):
return floatingpoint.Pow2(self, bit_length or program.bit_length, \
security or program.security)
def __lshift__(self, other, bit_length=None, security=None):
return self * util.pow2_value(other, bit_length, security)
@vectorize
@read_mem_value
def __rshift__(self, other, bit_length=None, security=None):
bit_length = bit_length or program.bit_length
security = security or program.security
if isinstance(other, int):
if other == 0:
return self
res = sint()
comparison.Trunc(res, self, bit_length, other, security, True)
return res
elif isinstance(other, sint):
return floatingpoint.Trunc(self, bit_length, other, security)
else:
return floatingpoint.Trunc(self, bit_length, sint(other), security)
left_shift = __lshift__
right_shift = __rshift__
def __rlshift__(self, other):
return other * 2**self
@vectorize
def __rrshift__(self, other):
return floatingpoint.Trunc(other, program.bit_length, self, program.security)
def bit_decompose(self, bit_length=None, security=None):
if bit_length == 0:
return []
bit_length = bit_length or program.bit_length
security = security or program.security
return floatingpoint.BitDec(self, bit_length, bit_length, security)
def TruncMul(self, other, k, m, kappa=None, nearest=False):
return (self * other).round(k, m, kappa, nearest, signed=True)
def TruncPr(self, k, m, kappa=None, signed=True):
return floatingpoint.TruncPr(self, k, m, kappa, signed=signed)
@vectorize
def round(self, k, m, kappa=None, nearest=False, signed=False):
kappa = kappa or program.security
secret = isinstance(m, sint)
if nearest:
if secret:
raise NotImplementedError()
return comparison.TruncRoundNearest(self, k, m, kappa,
signed=signed)
else:
if secret:
return floatingpoint.Trunc(self, k, m, kappa)
return self.TruncPr(k, m, kappa, signed=signed)
def Norm(self, k, f, kappa=None, simplex_flag=False):
return library.Norm(self, k, f, kappa, simplex_flag)
@vectorize
def int_div(self, other, bit_length=None, security=None):
k = bit_length or program.bit_length
kappa = security or program.security
tmp = library.IntDiv(self, other, k, kappa)
res = type(self)()
comparison.Trunc(res, tmp, 2 * k, k, kappa, True)
return res
@staticmethod
def two_power(n):
return floatingpoint.two_power(n)
class sgf2n(_secret, _gf2n):
__slots__ = []
instruction_type = 'gf2n'
clear_type = cgf2n
reg_type = 'sg'
@classmethod
def get_type(cls, length):
return cls
@classmethod
def get_raw_input_from(cls, player):
res = cls()
gstartinput(player, 1)
gstopinput(player, res)
return res
def add(self, other):
if isinstance(other, sgf2nint):
return NotImplemented
else:
return super(sgf2n, self).add(other)
def mul(self, other):
if isinstance(other, (sgf2nint)):
return NotImplemented
else:
return super(sgf2n, self).mul(other)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, gldms, gldmsi)
def store_in_mem(self, address):
self._store_in_mem(address, gstms, gstmsi)
def __init__(self, val=None, size=None):
super(sgf2n, self).__init__('sg', val=val, size=size)
def __neg__(self):
return self
@vectorize
def __invert__(self):
return self ^ cgf2n(2**program.galois_length - 1)
def __xor__(self, other):
if other is 0:
return self
else:
return super(sgf2n, self).add(other)
__rxor__ = __xor__
@vectorize
def __and__(self, other):
if isinstance(other, int):
other_bits = [(other >> i) & 1 \
for i in range(program.galois_length)]
else:
other_bits = other.bit_decompose()
self_bits = self.bit_decompose()
return sum((x * y) << i \
for i,(x,y) in enumerate(zip(self_bits, other_bits)))
__rand__ = __and__
@vectorize
def __lshift__(self, other):
return self * cgf2n(1 << other)
@vectorize
def right_shift(self, other, bit_length=None):
bits = self.bit_decompose(bit_length)
return sum(b << i for i,b in enumerate(bits[other:]))
def equal(self, other, bit_length=None, expand=1):
bits = [1 - bit for bit in (self - other).bit_decompose(bit_length)][::expand]
while len(bits) > 1:
bits.insert(0, bits.pop() * bits.pop())
return bits[0]
def not_equal(self, other, bit_length=None):
return 1 - self.equal(other, bit_length)
__eq__ = equal
__ne__ = not_equal
@vectorize
def bit_decompose(self, bit_length=None, step=1):
if bit_length == 0:
return []
bit_length = bit_length or program.galois_length
random_bits = [self.get_random_bit() \
for i in range(0, bit_length, step)]
one = cgf2n(1)
masked = sum([b * (one << (i * step)) for i,b in enumerate(random_bits)], self).reveal()
masked_bits = masked.bit_decompose(bit_length,step=step)
return [m + r for m,r in zip(masked_bits, random_bits)]
@vectorize
def bit_decompose_embedding(self):
random_bits = [self.get_random_bit() \
for i in range(8)]
one = cgf2n(1)
wanted_positions = [0, 5, 10, 15, 20, 25, 30, 35]
masked = sum([b * (one << wanted_positions[i]) for i,b in enumerate(random_bits)], self).reveal()
return [self.clear_type((masked >> wanted_positions[i]) & one) + r for i,r in enumerate(random_bits)]
for t in (sint, sgf2n):
t.bit_type = t
t.basic_type = t
t.default_type = t
class _bitint(object):
bits = None
log_rounds = False
linear_rounds = False
@classmethod
def bit_adder(cls, a, b, carry_in=0, get_carry=False):
a, b = list(a), list(b)
a += [0] * (len(b) - len(a))
b += [0] * (len(a) - len(b))
return cls.bit_adder_selection(a, b, carry_in=carry_in,
get_carry=get_carry)
@classmethod
def bit_adder_selection(cls, a, b, carry_in=0, get_carry=False):
if cls.log_rounds:
return cls.carry_lookahead_adder(a, b, carry_in=carry_in)
elif cls.linear_rounds:
return cls.ripple_carry_adder(a, b, carry_in=carry_in)
else:
return cls.carry_select_adder(a, b, carry_in=carry_in)
@classmethod
def carry_lookahead_adder(cls, a, b, fewer_inv=False, carry_in=0,
get_carry=False):
lower = []
for (ai,bi) in zip(a,b):
if ai is 0 or bi is 0:
lower.append(ai + bi)
a.pop(0)
b.pop(0)
else:
break
d = [cls.half_adder(ai, bi) for (ai,bi) in zip(a,b)]
carry = floatingpoint.carry
if fewer_inv:
pre_op = floatingpoint.PreOpL2
else:
pre_op = floatingpoint.PreOpL
if d:
carries = list(zip(*pre_op(carry, [(0, carry_in)] + d)))[1]
else:
carries = []
res = lower + cls.sum_from_carries(a, b, carries)
if get_carry:
res += [carries[-1]]
return res
@staticmethod
def sum_from_carries(a, b, carries):
return [ai.bit_xor(bi).bit_xor(carry) \
for (ai, bi, carry) in zip(a, b, carries)]
@classmethod
def carry_select_adder(cls, a, b, get_carry=False, carry_in=0):
a += [0] * (len(b) - len(a))
b += [0] * (len(a) - len(b))
n = len(a)
for m in range(100):
if sum(range(m + 1)) + 1 >= n:
break
for k in range(m, -1, -1):
if sum(range(m, k - 1, -1)) + 1 >= n:
break
blocks = list(range(m, k, -1))
blocks.append(n - sum(blocks))
blocks.reverse()
#print 'blocks:', blocks
if len(blocks) > 1 and blocks[0] > blocks[1]:
raise Exception('block size not increasing:', blocks)
if sum(blocks) != n:
raise Exception('blocks not summing up: %s != %s' % \
(sum(blocks), n))
res = []
carry = carry_in
cin_one = util.long_one(a + b)
for m in blocks:
aa = a[:m]
bb = b[:m]
a = a[m:]
b = b[m:]
cc = [cls.ripple_carry_adder(aa, bb, i) for i in (0, cin_one)]
for i in range(m):
res.append(util.if_else(carry, cc[1][i], cc[0][i]))
carry = util.if_else(carry, cc[1][m], cc[0][m])
if get_carry:
res += [carry]
return res
@classmethod
def ripple_carry_adder(cls, a, b, carry_in=0):
carry = carry_in
res = []
for aa, bb in zip(a, b):
cc, carry = cls.full_adder(aa, bb, carry)
res.append(cc)
res.append(carry)
return res
@staticmethod
def full_adder(a, b, carry):
s = a + b
return s + carry, util.if_else(s, carry, a)
@staticmethod
def half_adder(a, b):
return a + b, a & b
@staticmethod
def bit_comparator(a, b):
long_one = util.long_one(a + b)
op = lambda y,x,*args: (util.if_else(x[1], x[0], y[0]), \
util.if_else(x[1], long_one, y[1]))
return floatingpoint.KOpL(op, [(bi, ai + bi) for (ai,bi) in zip(a,b)])
@classmethod
def bit_less_than(cls, a, b):
x, not_equal = cls.bit_comparator(a, b)
return util.if_else(not_equal, x, 0)
@staticmethod
def get_highest_different_bits(a, b, index):
diff = [ai + bi for (ai,bi) in reversed(list(zip(a,b)))]
preor = floatingpoint.PreOR(diff, raw=True)
highest_diff = [x - y for (x,y) in reversed(list(zip(preor, [0] + preor)))]
raw = sum(map(operator.mul, highest_diff, (a,b)[index]))
return raw.bit_decompose()[0]
def load_int(self, other):
if -2**(self.n_bits-1) <= other < 2**(self.n_bits-1):
self.bin_type.load_int(self, other + 2**self.n_bits \
if other < 0 else other)
else:
raise CompilerError('Invalid signed %d-bit integer: %d' % \
(self.n_bits, other))
def add(self, other):
if type(other) == self.bin_type:
raise CompilerError('Unclear addition')
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
return self.compose(self.bit_adder(a, b))
def mul(self, other):
if type(other) == self.bin_type:
raise CompilerError('Unclear multiplication')
self_bits = self.bit_decompose()
if isinstance(other, int):
other_bits = util.bit_decompose(other, self.n_bits)
bit_matrix = [[x * y for y in self_bits] for x in other_bits]
else:
try:
other_bits = other.bit_decompose()
if len(other_bits) == 1:
return type(self)(other_bits[0] * self)
if len(self_bits) != len(other_bits):
raise NotImplementedError('Multiplication of different lengths')
except AttributeError:
pass
try:
other = self.bin_type(other)
except CompilerError:
return NotImplemented
products = [x * other for x in self_bits]
bit_matrix = [util.bit_decompose(x, self.n_bits) for x in products]
return self.compose(self.wallace_tree_from_matrix(bit_matrix, False))
@classmethod
def wallace_tree_from_matrix(cls, bit_matrix, get_carry=True):
columns = [[_f for _f in (bit_matrix[j][i-j] \
for j in range(min(len(bit_matrix), i + 1))) if _f] \
for i in range(len(bit_matrix[0]))]
return cls.wallace_tree_from_columns(columns, get_carry)
@classmethod
def wallace_tree_from_columns(cls, columns, get_carry=True):
self = cls
while max(len(c) for c in columns) > 2:
new_columns = [[] for i in range(len(columns) + 1)]
for i,col in enumerate(columns):
while len(col) > 2:
s, carry = self.full_adder(*(col.pop() for i in range(3)))
new_columns[i].append(s)
new_columns[i+1].append(carry)
if len(col) == 2:
s, carry = self.half_adder(*(col.pop() for i in range(2)))
new_columns[i].append(s)
new_columns[i+1].append(carry)
else:
new_columns[i].extend(col)
if get_carry:
columns = new_columns
else:
columns = new_columns[:-1]
for col in columns:
col.extend([0] * (2 - len(col)))
return self.bit_adder(*list(zip(*columns)))
@classmethod
def wallace_tree(cls, rows):
return cls.wallace_tree_from_columns([list(x) for x in zip(*rows)])
def __sub__(self, other):
if type(other) == sgf2n:
raise CompilerError('Unclear subtraction')
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
d = [(1 + ai + bi, (1 - ai) * bi) for (ai,bi) in zip(a,b)]
borrow = lambda y,x,*args: \
(x[0] * y[0], 1 - (1 - x[1]) * (1 - x[0] * y[1]))
borrows = (0,) + list(zip(*floatingpoint.PreOpL(borrow, d)))[1]
return self.compose(ai + bi + borrow \
for (ai,bi,borrow) in zip(a,b,borrows))
def __rsub__(self, other):
raise NotImplementedError()
def __truediv__(self, other):
raise NotImplementedError()
def __truerdiv__(self, other):
raise NotImplementedError()
def __lshift__(self, other):
return self.compose(([0] * other + self.bit_decompose())[:self.n_bits])
def __rshift__(self, other):
return self.compose(self.bit_decompose()[other:])
def bit_decompose(self, n_bits=None, *args):
if self.bits is None:
self.bits = self.force_bit_decompose(self.n_bits)
if n_bits is None:
return self.bits[:]
else:
return self.bits[:n_bits] + [self.fill_bit()] * (n_bits - self.n_bits)
def fill_bit(self):
return self.bits[-1]
@staticmethod
def prep_comparison(a, b):
a[-1], b[-1] = b[-1], a[-1]
def comparison(self, other, const_rounds=False, index=None):
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
self.prep_comparison(a, b)
if const_rounds:
return self.get_highest_different_bits(a, b, index)
else:
return self.bit_comparator(a, b)
def __lt__(self, other):
if program.options.comparison == 'log':
x, not_equal = self.comparison(other)
return util.if_else(not_equal, x, 0)
else:
return self.comparison(other, True, 1)
def __le__(self, other):
if program.options.comparison == 'log':
x, not_equal = self.comparison(other)
return util.if_else(not_equal, x, 1)
else:
return 1 - self.comparison(other, True, 0)
def __ge__(self, other):
return 1 - (self < other)
def __gt__(self, other):
return 1 - (self <= other)
def __eq__(self, other):
diff = self ^ other
diff_bits = [1 - x for x in diff.bit_decompose()]
return floatingpoint.KMul(diff_bits)
def __ne__(self, other):
return 1 - (self == other)
def __neg__(self):
return 1 + self.compose(1 ^ b for b in self.bit_decompose())
def __abs__(self):
return util.if_else(self.bit_decompose()[-1], -self, self)
less_than = lambda self, other, *args, **kwargs: self < other
greater_than = lambda self, other, *args, **kwargs: self > other
less_equal = lambda self, other, *args, **kwargs: self <= other
greater_equal = lambda self, other, *args, **kwargs: self >= other
equal = lambda self, other, *args, **kwargs: self == other
not_equal = lambda self, other, *args, **kwargs: self != other
class intbitint(_bitint, sint):
@staticmethod
def full_adder(a, b, carry):
s = a.bit_xor(b)
return s.bit_xor(carry), util.if_else(s, carry, a)
@staticmethod
def half_adder(a, b):
carry = a * b
return a + b - 2 * carry, carry
@staticmethod
def sum_from_carries(a, b, carries):
return [a[i] + b[i] + carries[i] - 2 * carries[i + 1] \
for i in range(len(a))]
@classmethod
def bit_adder_selection(cls, a, b, carry_in=0, get_carry=False):
if cls.linear_rounds:
return cls.ripple_carry_adder(a, b, carry_in=carry_in)
# experimental cut-off with dead code elimination
elif len(a) < 122 or cls.log_rounds:
return cls.carry_lookahead_adder(a, b, carry_in=carry_in,
get_carry=get_carry)
else:
return cls.carry_select_adder(a, b, carry_in=carry_in)
class sgf2nint(_bitint, sgf2n):
bin_type = sgf2n
@classmethod
def compose(cls, bits):
bits = list(bits)
if len(bits) > cls.n_bits:
raise CompilerError('Too many bits')
res = cls()
res.bits = bits + [0] * (cls.n_bits - len(bits))
gmovs(res, sum(b << i for i,b in enumerate(bits)))
return res
def load_other(self, other):
if isinstance(other, sgf2nint):
gmovs(self, self.compose(other.bit_decompose(self.n_bits)))
elif isinstance(other, sgf2n):
gmovs(self, other)
else:
gaddm(self, sgf2n(0), cgf2n(other))
def force_bit_decompose(self, n_bits=None):
return sgf2n(self).bit_decompose(n_bits)
class sgf2nuint(sgf2nint):
def load_int(self, other):
if 0 <= other < 2**self.n_bits:
sgf2n.load_int(self, other)
else:
raise CompilerError('Invalid unsigned %d-bit integer: %d' % \
(self.n_bits, other))
def fill_bit(self):
return 0
@staticmethod
def prep_comparison(a, b):
pass
class sgf2nuint32(sgf2nuint):
n_bits = 32
class sgf2nint32(sgf2nint):
n_bits = 32
def get_sgf2nint(n):
class sgf2nint_spec(sgf2nint):
n_bits = n
#sgf2nint_spec.__name__ = 'sgf2unint' + str(n)
return sgf2nint_spec
def get_sgf2nuint(n):
class sgf2nuint_spec(sgf2nint):
n_bits = n
#sgf2nuint_spec.__name__ = 'sgf2nuint' + str(n)
return sgf2nuint_spec
class sgf2nfloat(sgf2n):
@classmethod
def set_precision(cls, vlen, plen):
cls.vlen = vlen
cls.plen = plen
class v_type(sgf2nuint):
n_bits = 2 * vlen + 1
class p_type(sgf2nint):
n_bits = plen
class pdiff_type(sgf2nuint):
n_bits = plen
cls.v_type = v_type
cls.p_type = p_type
cls.pdiff_type = pdiff_type
def __init__(self, val, p=None, z=None, s=None):
super(sgf2nfloat, self).__init__()
if p is None and type(val) == sgf2n:
bits = val.bit_decompose(self.vlen + self.plen + 1)
self.v = self.v_type.compose(bits[:self.vlen])
self.p = self.p_type.compose(bits[self.vlen:-1])
self.s = bits[-1]
self.z = util.tree_reduce(operator.mul, (1 - b for b in self.v.bits))
else:
if p is None:
v, p, z, s = sfloat.convert_float(val, self.vlen, self.plen)
# correct sfloat
p += self.vlen - 1
v_bits = util.bit_decompose(v, self.vlen)
p_bits = util.bit_decompose(p, self.plen)
self.v = self.v_type.compose(v_bits)
self.p = self.p_type.compose(p_bits)
self.z = z
self.s = s
else:
self.v, self.p, self.z, self.s = val, p, z, s
v_bits = val.bit_decompose()[:self.vlen]
p_bits = p.bit_decompose()[:self.plen]
gmovs(self, util.bit_compose(v_bits + p_bits + [self.s]))
def add(self, other):
a = self.p < other.p
b = self.p == other.p
c = self.v < other.v
other_dominates = (b.if_else(c, a))
pmax, pmin = a.cond_swap(self.p, other.p, self.p_type)
vmax, vmin = other_dominates.cond_swap(self.v, other.v, self.v_type)
s3 = self.s ^ other.s
pdiff = self.pdiff_type(pmax - pmin)
d = self.vlen < pdiff
pow_delta = util.pow2(d.if_else(0, pdiff).bit_decompose(util.log2(self.vlen)))
v3 = vmax
v4 = self.v_type(sgf2n(vmax) * pow_delta) + self.v_type(s3.if_else(-vmin, vmin))
v = self.v_type(sgf2n(d.if_else(v3, v4) << self.vlen) / pow_delta)
v >>= self.vlen - 1
h = floatingpoint.PreOR(v.bits[self.vlen+1::-1])
tmp = sum(util.if_else(b, 0, 1 << i) for i,b in enumerate(h))
pow_p0 = 1 + self.v_type(tmp)
v = (v * pow_p0) >> 2
p = pmax - sum(self.p_type.compose([1 - b]) for b in h) + 1
v = self.z.if_else(other.v, other.z.if_else(self.v, v))
z = v == 0
p = z.if_else(0, self.z.if_else(other.p, other.z.if_else(self.p, p)))
s = other_dominates.if_else(other.s, self.s)
s = self.z.if_else(other.s, other.z.if_else(self.s, s))
return sgf2nfloat(v, p, z, s)
def mul(self, other):
v = (self.v * other.v) >> (self.vlen - 1)
b = v.bits[self.vlen]
v = b.if_else(v >> 1, v)
p = self.p + other.p + self.p_type.compose([b])
s = self.s + other.s
z = util.or_op(self.z, other.z)
return sgf2nfloat(v, p, z, s)
sgf2nfloat.set_precision(24, 8)
def parse_type(other, k=None, f=None):
# converts type to cfix/sfix depending on the case
if isinstance(other, cfix.scalars):
return cfix(other, k=k, f=f)
elif isinstance(other, cint):
tmp = cfix()
tmp.load_int(other)
return tmp
elif isinstance(other, sint):
tmp = sfix()
tmp.load_int(other)
return tmp
elif isinstance(other, sfloat):
tmp = sfix(other)
return tmp
else:
return other
class cfix(_number, _structure):
""" Clear fixed point type. """
__slots__ = ['value', 'f', 'k', 'size']
reg_type = 'c'
scalars = (int, float, regint)
@classmethod
def set_precision(cls, f, k = None):
# k is the whole bitlength of fixed point
# f is the bitlength of decimal part
cls.f = f
if k is None:
cls.k = 2 * f
else:
cls.k = k
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
res = []
res.append(cint.load_mem(address))
return cfix(*res)
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
""" Read one or more cfix values from a socket.
Sender will have already bit shifted and sent as cints."""
cint_input = cint.read_from_socket(client_id, n)
if n == 1:
return cfix(cint_inputs)
else:
return list(map(cfix, cint_inputs))
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
""" Send cfix to socket. Value is sent as bit shifted cint. """
writesocketc(client_id, message_type, cint(self.v))
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
""" Send a list of cfix values to socket. Values are sent as bit shifted cints. """
def cfix_to_cint(fix_val):
return cint(fix_val.v)
cint_values = list(map(cfix_to_cint, values))
writesocketc(client_id, message_type, *cint_values)
@staticmethod
def malloc(size):
return program.malloc(size, cint)
@staticmethod
def n_elements():
return 1
@vectorize_init
def __init__(self, v=None, k=None, f=None, size=None):
f = f or self.f
k = k or self.k
self.f = f
self.k = k
self.size = get_global_vector_size()
if isinstance(v, cint):
self.v = cint(v,size=self.size)
elif isinstance(v, cfix.scalars):
v = v * (2 ** f)
try:
v = int(round(v))
except TypeError:
pass
self.v = cint(v, size=self.size)
elif isinstance(v, cfix):
self.v = v.v
elif isinstance(v, MemValue):
self.v = v
elif v is None:
self.v = cint(0)
else:
raise CompilerError('cannot initialize cfix with %s' % v)
@vectorize
def load_int(self, v):
self.v = cint(v) * (2 ** self.f)
@classmethod
def conv(cls, other):
if isinstance(other, cls):
return other
else:
try:
res = cfix()
res.load_int(other)
return res
except (TypeError, CompilerError):
pass
return cls(other)
def store_in_mem(self, address):
self.v.store_in_mem(address)
def sizeof(self):
return self.size * 4
@vectorize
def add(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(self.v + other.v)
else:
return NotImplemented
@vectorize
def mul(self, other):
other = parse_type(other)
if isinstance(other, cfix):
assert self.f == other.f
sgn = cint(1 - 2 * (self.v * other.v < 0))
absolute = self.v * other.v * sgn
val = sgn * (absolute >> self.f)
return cfix(val)
elif isinstance(other, sfix):
return NotImplemented
else:
raise CompilerError('Invalid type %s for cfix.__mul__' % type(other))
@vectorize
def __sub__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(self.v - other.v)
elif isinstance(other, sfix):
return sfix(self.v - other.v)
else:
raise NotImplementedError
@vectorize
def __neg__(self):
# cfix type always has .v
return cfix(-self.v)
def __rsub__(self, other):
return -self + other
@vectorize
def __eq__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v == other.v
elif isinstance(other, sfix):
return other.v.equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __lt__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v < other.v
elif isinstance(other, sfix):
if(self.k != other.k or self.f != other.f):
raise TypeError('Incompatible fixed point types in comparison')
return other.v.greater_than(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __le__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v <= other.v
elif isinstance(other, sfix):
return other.v.greater_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __gt__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v > other.v
elif isinstance(other, sfix):
return other.v.less_than(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __ge__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v >= other.v
elif isinstance(other, sfix):
return other.v.less_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __ne__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v != other.v
elif isinstance(other, sfix):
return other.v.not_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __truediv__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(library.cint_cint_division(self.v, other.v, self.k, self.f))
elif isinstance(other, sfix):
return sfix(library.FPDiv(self.v, other.v, self.k, self.f,
other.kappa, nearest=sfix.round_nearest))
else:
raise TypeError('Incompatible fixed point types in division')
def print_plain(self):
if self.k > 64:
raise CompilerError('Printing of fixed-point numbers not ' +
'implemented for more than 64-bit precision')
tmp = regint()
convmodp(tmp, self.v, bitlength=self.k)
sign = cint(tmp < 0)
abs_v = sign.if_else(-self.v, self.v)
print_float_plain(cint(abs_v), cint(-self.f), \
cint(0), cint(sign))
class _single(_number, _structure):
""" Representation as single integer preserving the order """
""" E.g. fixed-point numbers """
__slots__ = ['v']
kappa = 40
round_nearest = False
@property
@classmethod
def reg_type(cls):
return cls.int_type.reg_type
@classmethod
def receive_from_client(cls, n, client_id, message_type=ClientMessageType.NoType):
""" Securely obtain shares of n values input by a client.
Assumes client has already run bit shift to convert fixed point to integer."""
sint_inputs = cls.int_type.receive_from_client(n, client_id, ClientMessageType.TripleShares)
return list(map(cls, sint_inputs))
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._new(cls.int_type.load_mem(address))
@classmethod
@read_mem_value
def conv(cls, other):
if isinstance(other, cls):
return other
else:
try:
return cls.from_sint(other)
except (TypeError, CompilerError):
pass
return cls(other)
@classmethod
def coerce(cls, other):
return cls.conv(other)
@classmethod
def malloc(cls, size):
return program.malloc(size, cls.int_type)
@staticmethod
def n_elements():
return 1
@classmethod
def dot_product(cls, x, y, res_params=None):
return cls.unreduced_dot_product(x, y, res_params).reduce_after_mul()
@classmethod
def unreduced_dot_product(cls, x, y, res_params=None):
dp = cls.int_type.dot_product([xx.pre_mul() for xx in x],
[yy.pre_mul() for yy in y])
return x[0].unreduced(dp, y[0], res_params, len(x))
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
int_matrix = [y.get_vector().pre_mul() for y in matrix]
col = cls.int_type.row_matrix_mul([x.pre_mul() for x in row],
int_matrix)
res = row[0].unreduced(col, matrix[0][0], res_params,
len(row)).reduce_after_mul()
return res
@classmethod
def matrix_mul(cls, A, B, n, res_params=None):
AA = A.pre_mul()
BB = B.pre_mul()
CC = cls.int_type.matrix_mul(AA, BB, n)
res = A.unreduced(CC, B, res_params, n).reduce_after_mul()
return res
def store_in_mem(self, address):
self.v.store_in_mem(address)
@property
def size(self):
return self.v.size
def sizeof(self):
return self.size
def __len__(self):
return len(self.v)
@vectorize
def __sub__(self, other):
other = self.coerce(other)
return self + (-other)
def __rsub__(self, other):
return -self + other
@vectorize
def __eq__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __le__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.less_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __lt__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.less_than(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __ge__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.greater_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __gt__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.greater_than(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __ne__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.not_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
class _fix(_single):
""" Shared fixed point type. """
__slots__ = ['v', 'f', 'k', 'size']
@classmethod
def set_precision(cls, f, k = None):
cls.f = f
# default bitlength = 2*precision
if k is None:
cls.k = 2 * f
else:
if k < f:
raise CompilerError('bit length cannot be less than precision')
cls.k = k
@classmethod
def coerce(cls, other):
if isinstance(other, (_fix, cls.clear_type)):
return other
else:
return cls.conv(other)
@classmethod
def from_sint(cls, other, k=None, f=None):
res = cls()
res.f = f or cls.f
res.k = k or cls.k
res.load_int(cls.int_type.conv(other))
return res
@classmethod
def _new(cls, other, k=None, f=None):
res = cls(other)
res.k = k or cls.k
res.f = f or cls.f
return res
@vectorize_init
def __init__(self, _v=None, size=None):
self.size = get_global_vector_size()
f = self.f
k = self.k
# warning: don't initialize a sfix from a sint, this is only used in internal methods;
# for external initialization use load_int.
if _v is None:
self.v = self.int_type(0)
elif isinstance(_v, self.int_type):
self.v = _v
self.size = _v.size
elif isinstance(_v, cfix.scalars):
self.v = self.int_type(int(round(_v * (2 ** f))), size=self.size)
elif isinstance(_v, self.float_type):
p = (f + _v.p)
b = (p.greater_equal(0, _v.vlen))
a = b*(_v.v << (p)) + (1-b)*(_v.v >> (-p))
self.v = (1-2*_v.s)*a
elif isinstance(_v, type(self)):
self.v = _v.v
elif isinstance(_v, (MemValue, MemFix)):
#this is a memvalue object
self.v = type(self)(_v.read()).v
else:
raise CompilerError('cannot convert %s to sfix' % _v)
if not isinstance(self.v, self.int_type):
raise CompilerError('sfix conversion failure: %s/%s' % (_v, self.v))
@vectorize
def load_int(self, v):
self.v = self.int_type(v) << self.f
def __getitem__(self, index):
return self._new(self.v[index])
@vectorize
def add(self, other):
other = self.coerce(other)
if isinstance(other, (_fix, cfix)):
return self._new(self.v + other.v, k=self.k, f=self.f)
elif isinstance(other, cfix.scalars):
tmp = cfix(other, k=self.k, f=self.f)
return self + tmp
else:
return NotImplemented
@vectorize
def mul(self, other):
if isinstance(other, (sint, cint, regint, int)):
return self._new(self.v * other, k=self.k, f=self.f)
elif isinstance(other, float):
if int(other) == other:
return self.mul(int(other))
v = int(round(other * 2 ** self.f))
if v == 0:
return 0
f = self.f
while v % 2 == 0:
f -= 1
v //= 2
k = len(bin(abs(v))) - 1
other = self.multipliable(v, k, f)
other = self.coerce(other)
if isinstance(other, (_fix, self.clear_type)):
val = self.v.TruncMul(other.v, self.k + other.k, other.f,
self.kappa,
self.round_nearest)
if self.size >= other.size:
return self._new(val, k=self.k, f=self.f)
else:
return self.vec._new(val, k=self.k, f=self.f)
elif isinstance(other, cfix.scalars):
scalar_fix = cfix(other)
return self * scalar_fix
else:
return NotImplemented
@vectorize
def __neg__(self):
return type(self)(-self.v)
@vectorize
def __truediv__(self, other):
other = self.coerce(other)
if isinstance(other, _fix):
return type(self)(library.FPDiv(self.v, other.v, self.k, self.f,
self.kappa,
nearest=self.round_nearest))
elif isinstance(other, cfix):
return type(self)(library.sint_cint_division(self.v, other.v, self.k, self.f, self.kappa))
else:
raise TypeError('Incompatible fixed point types in division')
@vectorize
def __rtruediv__(self, other):
return self.coerce(other) / self
@vectorize
def compute_reciprocal(self):
return type(self)(library.FPDiv(cint(2) ** self.f, self.v, self.k, self.f, self.kappa, True))
def reveal(self):
val = self.v.reveal()
res = self.clear_type(val)
res.f = self.f
res.k = self.k
return res
class sfix(_fix):
int_type = sint
clear_type = cfix
@vectorized_classmethod
def get_input_from(cls, player):
v = cls.int_type()
inputmixed('fix', v, cls.f, player)
return cls._new(v)
@vectorized_classmethod
def get_random(cls, lower, upper):
""" Uniform random number around centre of bounds """
""" Range can be smaller """
log_range = int(math.log(upper - lower, 2))
n_bits = log_range + cls.f
average = lower + 0.5 * (upper - lower)
lower = average - 0.5 * 2 ** log_range
return cls._new(cls.int_type.get_random_int(n_bits)) + lower
def coerce(self, other):
return parse_type(other, k=self.k, f=self.f)
def mul_no_reduce(self, other, res_params=None):
assert self.f == other.f
return self.unreduced(self.v * other.v)
def pre_mul(self):
return self.v
def unreduced(self, v, other=None, res_params=None, n_summands=1):
return unreduced_sfix(v, self.k * 2, self.f, self.kappa)
@staticmethod
def multipliable(v, k, f):
return cfix(cint.conv(v), k, f)
class unreduced_sfix(_single):
int_type = sint
@classmethod
def _new(cls, v):
return cls(v, 2 * sfix.k, sfix.f, sfix.kappa)
def __init__(self, v, k, m, kappa):
self.v = v
self.k = k
self.m = m
self.kappa = kappa
def __add__(self, other):
if other is 0:
return self
assert self.k == other.k
assert self.m == other.m
assert self.kappa == other.kappa
return unreduced_sfix(self.v + other.v, self.k, self.m, self.kappa)
__radd__ = __add__
@vectorize
def reduce_after_mul(self):
return sfix(sfix.int_type.round(self.v, self.k, self.m, self.kappa,
nearest=sfix.round_nearest,
signed=True))
sfix.unreduced_type = unreduced_sfix
# this is for 20 bit decimal precision
# with 40 bitlength of entire number
# these constants have been chosen for multiplications to fit in 128 bit prime field
# (precision n1) 41 + (precision n2) 41 + (stat_sec) 40 = 82 + 40 = 122 <= 128
# with statistical security of 40
fixed_lower = 20
fixed_upper = 40
sfix.set_precision(fixed_lower, fixed_upper)
cfix.set_precision(fixed_lower, fixed_upper)
class squant(_single):
""" Quantization as in ArXiv:1712.05877v1 """
__slots__ = ['params']
int_type = sint
clamp = True
@classmethod
def set_params(cls, S, Z=0, k=8):
cls.params = squant_params(S, Z, k)
@classmethod
def from_sint(cls, other):
raise CompilerError('sint to squant conversion not implemented')
@classmethod
def _new(cls, value, params=None):
res = cls(params=params)
res.v = value
return res
@read_mem_value
def __init__(self, value=None, params=None):
if params is not None:
self.params = params
if value is None:
# need to set v manually
pass
elif isinstance(value, cfix.scalars):
set_global_vector_size(1)
q = util.round_to_int(value / self.S + self.Z)
if util.is_constant(q) and (q < 0 or q >= 2**self.k):
raise CompilerError('%f not quantizable' % value)
self.v = self.int_type(q)
reset_global_vector_size()
elif isinstance(value, squant) and value.params == self.params:
self.v = value.v
else:
raise CompilerError('cannot convert %s to squant' % value)
def __getitem__(self, index):
return type(self)._new(self.v[index], self.params)
def get_params(self):
return self.params
@property
def S(self):
return self.params.S
@property
def Z(self):
return self.params.Z
@property
def k(self):
return self.params.k
def coerce(self, other):
other = self.conv(other)
return self._new(util.expand(other.v, self.size), other.params)
@vectorize
def add(self, other):
other = self.coerce(other)
assert self.get_params() == other.get_params()
return self._new(self.v + other.v - util.expand(self.Z, self.v.size))
def mul(self, other, res_params=None):
return self.mul_no_reduce(other, res_params).reduce_after_mul()
def mul_no_reduce(self, other, res_params=None):
if isinstance(other, (sint, cint, regint)):
return self._new(other * (self.v - self.Z) + self.Z,
params=self.get_params())
other = self.coerce(other)
tmp = (self.v - self.Z) * (other.v - other.Z)
return _unreduced_squant(tmp, (self.get_params(), other.get_params()),
res_params=res_params)
def pre_mul(self):
return self.v - util.expand(self.Z, self.v.size)
def unreduced(self, v, other, res_params=None, n_summands=1):
return _unreduced_squant(v, (self.get_params(), other.get_params()),
res_params, n_summands)
@vectorize
def for_mux(self, other):
other = self.coerce(other)
assert self.params == other.params
f = lambda x: self._new(x, self.params)
return f, self.v, other.v
@vectorize
def __neg__(self):
return self._new(-self.v + 2 * util.expand(self.Z, self.v.size))
class _unreduced_squant(object):
def __init__(self, v, params, res_params=None, n_summands=1):
self.v = v
self.params = params
self.n_summands = n_summands
self.res_params = res_params or params[0]
def __add__(self, other):
if other is 0:
return self
assert self.params == other.params
assert self.res_params == other.res_params
return _unreduced_squant(self.v + other.v, self.params, self.res_params,
self.n_summands + other.n_summands)
__radd__ = __add__
def reduce_after_mul(self):
return squant_params.conv(self.res_params).reduce(self)
class squant_params(object):
max_n_summands = 2048
@staticmethod
def conv(other):
if isinstance(other, squant_params):
return other
else:
return squant_params(*other)
def __init__(self, S, Z=0, k=8):
try:
self.S = float(S)
except:
self.S = S
self.Z = MemValue.if_necessary(Z)
self.k = k
self._store = {}
if program.options.ring:
# cheaper probabilistic truncation
self.max_length = int(program.options.ring) - 1
else:
# safe choice for secret shift
self.max_length = 71
def __iter__(self):
yield self.S
yield self.Z
yield self.k
def is_constant(self):
return util.is_constant_float(self.S) and util.is_constant(self.Z)
def get(self, input_params, n_summands):
p = input_params
M = p[0].S * p[1].S / self.S
logM = util.log2(M)
n_shift = self.max_length - p[0].k - p[1].k - util.log2(n_summands)
if util.is_constant_float(M):
n_shift -= logM
int_mult = int(round(M * 2 ** (n_shift)))
else:
int_mult = MemValue(M.v << (n_shift + M.p))
shifted_Z = MemValue.if_necessary(self.Z << n_shift)
return n_shift, int_mult, shifted_Z
def precompute(self, *input_params):
self._store[input_params] = self.get(input_params, self.max_n_summands)
def get_stored(self, unreduced):
assert unreduced.n_summands <= self.max_n_summands
return self._store[unreduced.params]
def reduce(self, unreduced):
ps = (self,) + unreduced.params
if reduce(operator.and_, (p.is_constant() for p in ps)):
n_shift, int_mult, shifted_Z = self.get(unreduced.params,
unreduced.n_summands)
else:
n_shift, int_mult, shifted_Z = self.get_stored(unreduced)
size = unreduced.v.size
n_shift = util.expand(n_shift, size)
shifted_Z = util.expand(shifted_Z, size)
int_mult = util.expand(int_mult, size)
tmp = unreduced.v * int_mult + shifted_Z
shifted = tmp.round(self.max_length, n_shift,
kappa=squant.kappa, nearest=squant.round_nearest,
signed=True)
if squant.clamp:
length = max(self.k, self.max_length - n_shift) + 1
top = (1 << self.k) - 1
over = shifted.greater_than(top, length, squant.kappa)
under = shifted.less_than(0, length, squant.kappa)
shifted = over.if_else(top, shifted)
shifted = under.if_else(0, shifted)
return squant._new(shifted, params=self)
class sfloat(_number, _structure):
""" Shared floating point data type, representing (1 - 2s)*(1 - z)*v*2^p.
v: significand
p: exponent
z: zero flag
s: sign bit
"""
__slots__ = ['v', 'p', 'z', 's', 'size']
# single precision
vlen = 24
plen = 8
kappa = 40
round_nearest = False
@staticmethod
def n_elements():
return 4
@classmethod
def malloc(cls, size):
return program.malloc(size * cls.n_elements(), sint)
@classmethod
def is_address_tuple(cls, address):
if isinstance(address, (list, tuple)):
assert(len(address) == cls.n_elements())
return True
return False
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
size = get_global_vector_size()
if cls.is_address_tuple(address):
return sfloat(*(sint.load_mem(a, size=size) for a in address))
res = []
for i in range(4):
res.append(sint.load_mem(address + i * size, size=size))
return sfloat(*res)
@classmethod
def set_error(cls, error):
# incompatible with loops
#cls.error += error - cls.error * error
cls.error = error
pass
@classmethod
def conv(cls, other):
if isinstance(other, cls):
return other
else:
return cls(other)
@classmethod
def coerce(cls, other):
return cls.conv(other)
@staticmethod
def convert_float(v, vlen, plen):
if v < 0:
s = 1
else:
s = 0
if v == 0:
v = 0
p = 0
z = 1
else:
p = int(math.floor(math.log(abs(v), 2))) - vlen + 1
vv = v
v = int(round(abs(v) * 2 ** (-p)))
if v == 2 ** vlen:
p += 1
v //= 2
z = 0
if p < -2 ** (plen - 1):
print('Warning: %e truncated to zero' % vv)
v, p, z = 0, 0, 1
if p >= 2 ** (plen - 1):
raise CompilerError('Cannot convert %s to float ' \
'with %d exponent bits' % (vv, plen))
return v, p, z, s
@vectorized_classmethod
def get_input_from(cls, player):
v = sint()
p = sint()
z = sint()
s = sint()
inputmixed('float', v, p, z, s, cls.vlen, player)
return cls(v, p, z, s)
@vectorize_init
@read_mem_value
def __init__(self, v, p=None, z=None, s=None, size=None):
self.size = get_global_vector_size()
if p is None:
if isinstance(v, sfloat):
p = v.p
z = v.z
s = v.s
v = v.v
elif isinstance(v, sfix):
f = v.f
v, p, z, s = floatingpoint.Int2FL(v.v, v.k,
self.vlen, self.kappa)
p = p - f
elif util.is_constant_float(v):
v, p, z, s = self.convert_float(v, self.vlen, self.plen)
else:
v, p, z, s = floatingpoint.Int2FL(sint.conv(v),
program.bit_length,
self.vlen, self.kappa)
if isinstance(v, int):
if not ((v >= 2**(self.vlen-1) and v < 2**(self.vlen)) or v == 0):
raise CompilerError('Floating point number malformed: significand')
self.v = library.load_int_to_secret(v)
else:
self.v = v
if isinstance(p, int):
if not (p >= -2**(self.plen - 1) and p < 2**(self.plen - 1)):
raise CompilerError('Floating point number malformed: exponent %d not unsigned %d-bit integer' % (p, self.plen))
self.p = library.load_int_to_secret(p)
else:
self.p = p
if isinstance(z, int):
if not (z == 0 or z == 1):
raise CompilerError('Floating point number malformed: zero bit')
self.z = sint()
ldsi(self.z, z)
else:
self.z = z
if isinstance(s, int):
if not (s == 0 or s == 1):
raise CompilerError('Floating point number malformed: sign')
self.s = sint()
ldsi(self.s, s)
else:
self.s = s
def __getitem__(self, index):
return sfloat(*(x[index] for x in self))
def __iter__(self):
yield self.v
yield self.p
yield self.z
yield self.s
def store_in_mem(self, address):
if self.is_address_tuple(address):
for a, x in zip(address, self):
x.store_in_mem(a)
return
for i,x in enumerate((self.v, self.p, self.z, self.s)):
x.store_in_mem(address + i * self.size)
def sizeof(self):
return self.size * self.n_elements()
@vectorize
def add(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
a,c,d,e = [sint() for i in range(4)]
t = sint()
t2 = sint()
v1 = self.v
v2 = other.v
p1 = self.p
p2 = other.p
s1 = self.s
s2 = other.s
z1 = self.z
z2 = other.z
a = p1.less_than(p2, self.plen, self.kappa)
b = floatingpoint.EQZ(p1 - p2, self.plen, self.kappa)
c = v1.less_than(v2, self.vlen, self.kappa)
ap1 = a*p1
ap2 = a*p2
aneg = 1 - a
bneg = 1 - b
cneg = 1 - c
av1 = a*v1
av2 = a*v2
cv1 = c*v1
cv2 = c*v2
pmax = ap2 + p1 - ap1
pmin = p2 - ap2 + ap1
vmax = bneg*(av2 + v1 - av1) + b*(cv2 + v1 - cv1)
vmin = bneg*(av1 + v2 - av2) + b*(cv1 + v2 - cv2)
s3 = s1 + s2 - 2 * s1 * s2
comparison.LTZ(d, self.vlen + pmin - pmax + sfloat.round_nearest,
self.plen, self.kappa)
pow_delta = floatingpoint.Pow2((1 - d) * (pmax - pmin),
self.vlen + 1 + sfloat.round_nearest,
self.kappa)
# deviate from paper for more precision
#v3 = 2 * (vmax - s3) + 1
v3 = vmax
v4 = vmax * pow_delta + (1 - 2 * s3) * vmin
to_trunc = (d * v3 + (1 - d) * v4)
if program.options.ring:
to_trunc <<= 1 + sfloat.round_nearest
v = floatingpoint.TruncInRing(to_trunc,
2 * (self.vlen + 1 +
sfloat.round_nearest),
pow_delta)
else:
to_trunc *= two_power(self.vlen + sfloat.round_nearest)
v = to_trunc * floatingpoint.Inv(pow_delta)
comparison.Trunc(t, v, 2 * self.vlen + 1 + sfloat.round_nearest,
self.vlen - 1, self.kappa, False)
v = t
u = floatingpoint.BitDec(v, self.vlen + 2 + sfloat.round_nearest,
self.vlen + 2 + sfloat.round_nearest, self.kappa,
list(range(1 + sfloat.round_nearest,
self.vlen + 2 + sfloat.round_nearest)))
# using u[0] doesn't seem necessary
h = floatingpoint.PreOR(u[:sfloat.round_nearest:-1], self.kappa)
p0 = self.vlen + 1 - sum(h)
pow_p0 = 1 + sum([two_power(i) * (1 - h[i]) for i in range(len(h))])
if self.round_nearest:
t2, overflow = \
floatingpoint.TruncRoundNearestAdjustOverflow(pow_p0 * v,
self.vlen + 3,
self.vlen,
self.kappa)
p0 = p0 - overflow
else:
comparison.Trunc(t2, pow_p0 * v, self.vlen + 2, 2, self.kappa, False)
v = t2
# deviate for more precision
#p = pmax - p0 + 1 - d
p = pmax - p0 + 1
zz = self.z*other.z
zprod = 1 - self.z - other.z + zz
v = zprod*t2 + self.z*v2 + other.z*v1
z = floatingpoint.EQZ(v, self.vlen, self.kappa)
p = (zprod*p + self.z*p2 + other.z*p1)*(1 - z)
s = (1 - b)*(a*other.s + aneg*self.s) + b*(c*other.s + cneg*self.s)
s = zprod*s + (other.z - zz)*self.s + (self.z - zz)*other.s
return sfloat(v, p, z, s)
else:
return NotImplemented
@vectorize_max
def mul(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
v1 = sint()
v2 = sint()
b = sint()
c2expl = cint()
comparison.ld2i(c2expl, self.vlen)
if sfloat.round_nearest:
v1 = comparison.TruncRoundNearest(self.v*other.v, 2*self.vlen,
self.vlen-1, self.kappa)
else:
comparison.Trunc(v1, self.v*other.v, 2*self.vlen, self.vlen-1, self.kappa, False)
t = v1 - c2expl
comparison.LTZ(b, t, self.vlen+1, self.kappa)
comparison.Trunc(v2, b*v1 + v1, self.vlen+1, 1, self.kappa, False)
z1, z2, s1, s2, p1, p2 = (x.expand_to_vector() for x in \
(self.z, other.z, self.s, other.s,
self.p, other.p))
z = z1 + z2 - self.z*other.z # = OR(z1, z2)
s = s1 + s2 - self.s*other.s*2 # = XOR(s1,s2)
p = (p1 + p2 - b + self.vlen)*(1 - z)
return sfloat(v2, p, z, s)
else:
return NotImplemented
def __sub__(self, other):
return self + -other
def __rsub__(self, other):
return -self + other
def __truediv__(self, other):
other = self.conv(other)
v = floatingpoint.SDiv(self.v, other.v + other.z * (2**self.vlen - 1),
self.vlen, self.kappa, self.round_nearest)
b = v.less_than(two_power(self.vlen-1), self.vlen + 1, self.kappa)
overflow = v.greater_equal(two_power(self.vlen), self.vlen + 1, self.kappa)
underflow = v.less_than(two_power(self.vlen-2), self.vlen + 1, self.kappa)
v = (v + b * v) * (1 - overflow) * (1 - underflow) + \
overflow * (2**self.vlen - 1) + \
underflow * (2**(self.vlen-1)) * (1 - self.z)
p = (1 - self.z) * (self.p - other.p - self.vlen - b + 1)
z = self.z
s = self.s + other.s - 2 * self.s * other.s
sfloat.set_error(other.z)
return sfloat(v, p, z, s)
def __rtruediv__(self, other):
return self.conv(other) / self
@vectorize
def __neg__(self):
return sfloat(self.v, self.p, self.z, (1 - self.s) * (1 - self.z))
@vectorize
def __lt__(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
z1 = self.z
z2 = other.z
s1 = self.s
s2 = other.s
a = self.p.less_than(other.p, self.plen, self.kappa)
c = floatingpoint.EQZ(self.p - other.p, self.plen, self.kappa)
d = ((1 - 2*self.s)*self.v).less_than((1 - 2*other.s)*other.v, self.vlen + 1, self.kappa)
cd = c*d
ca = c*a
b1 = cd + a - ca
b2 = cd + 1 + ca - c - a
s12 = self.s*other.s
z12 = self.z*other.z
b = (z1 - z12)*(1 - s2) + (z2 - z12)*s1 + (1 + z12 - z1 - z2)*(s1 - s12 + (1 + s12 - s1 - s2)*b1 + s12*b2)
return b
else:
return NotImplemented
def __ge__(self, other):
return 1 - (self < other)
def __gt__(self, other):
return self.conv(other) < self
def __le__(self, other):
return self.conv(other) >= self
@vectorize
def __eq__(self, other):
other = self.conv(other)
# the sign can be both ways for zeroes
both_zero = self.z * other.z
return floatingpoint.EQZ(self.v - other.v, self.vlen, self.kappa) * \
floatingpoint.EQZ(self.p - other.p, self.plen, self.kappa) * \
(1 - self.s - other.s + 2 * self.s * other.s) * \
(1 - both_zero) + both_zero
def __ne__(self, other):
return 1 - (self == other)
def log2(self):
up = self.v.greater_than(1 << (self.vlen - 1), self.vlen, self.kappa)
return self.p + self.vlen - 1 + up
def round_to_int(self):
direction = self.p.greater_equal(-self.vlen, self.plen, self.kappa)
right = self.v.right_shift(-self.p - 1, self.vlen + 1, self.kappa)
up = right.mod2m(1, self.vlen + 1, self.kappa)
right = right.right_shift(1, self.vlen + 1, self.kappa) + up
abs_value = direction * right
return self.s.if_else(-abs_value, abs_value)
def value(self):
""" Gets actual floating point value, if emulation is enabled. """
return (1 - 2*self.s.value)*(1 - self.z.value)*self.v.value/float(2**self.p.value)
def reveal(self):
return cfloat(self.v.reveal(), self.p.reveal(), self.z.reveal(), self.s.reveal())
class cfloat(object):
# Helper class used for printing sfloats
__slots__ = ['v', 'p', 'z', 's']
def __init__(self, v, p, z, s):
self.v, self.p, self.z, self.s = [cint.conv(x) for x in (v, p, z, s)]
def print_float_plain(self):
print_float_plain(self.v, self.p, self.z, self.s)
sfix.float_type = sfloat
_types = {
'c': cint,
's': sint,
'sg': sgf2n,
'cg': cgf2n,
'ci': regint,
}
def _get_type(t):
if t in _types:
return _types[t]
else:
return t
class Array(object):
@classmethod
def create_from(cls, l):
if isinstance(l, cls):
return l
tmp = list(l)
res = cls(len(tmp), type(tmp[0]))
res.assign(tmp)
return res
def __init__(self, length, value_type, address=None, debug=None):
value_type = _get_type(value_type)
self.address = address
self.length = length
self.value_type = value_type
if address is None:
self.address = self._malloc()
self.address_cache = {}
self.debug = debug
def _malloc(self):
return self.value_type.malloc(self.length)
def delete(self):
if program:
program.free(self.address, self.value_type.reg_type)
def get_address(self, index):
key = str(index)
if isinstance(index, int) and self.length is not None:
index += self.length * (index < 0)
if index >= self.length or index < 0:
raise IndexError('index %s, length %s' % \
(str(index), str(self.length)))
if (program.curr_block, key) not in self.address_cache:
n = self.value_type.n_elements()
length = self.length
if n == 1:
# length can be None for single-element arrays
length = 0
self.address_cache[program.curr_block, key] = \
util.untuplify([self.address + index + i * length \
for i in range(n)])
if self.debug:
library.print_ln_if(index >= self.length, 'OF:' + self.debug)
library.print_ln_if(self.address_cache[program.curr_block, key] >= program.allocated_mem[self.value_type.reg_type], 'AOF:' + self.debug)
return self.address_cache[program.curr_block, key]
def get_slice(self, index):
if index.stop is None and self.length is None:
raise CompilerError('Cannot slice array of unknown length')
return index.start or 0, index.stop or self.length, index.step or 1
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = self.get_slice(index)
res_length = (stop - start - 1) // step + 1
res = Array(res_length, self.value_type)
@library.for_range(res_length)
def f(i):
res[i] = self[start+i*step]
return res
return self._load(self.get_address(index))
def __setitem__(self, index, value):
if isinstance(index, slice):
start, stop, step = self.get_slice(index)
value = Array.create_from(value)
source_index = MemValue(0)
@library.for_range(start, stop, step)
def f(i):
self[i] = value[source_index]
source_index.iadd(1)
return
self._store(value, self.get_address(index))
# the following two are useful for compile-time lengths
# and thus differ from the usual Python syntax
def get_range(self, start, size):
return [self[start + i] for i in range(size)]
def set_range(self, start, values):
for i, value in enumerate(values):
self[start + i] = value
def _load(self, address):
return self.value_type.load_mem(address)
def _store(self, value, address):
self.value_type.conv(value).store_in_mem(address)
def __len__(self):
return self.length
def __iter__(self):
for i in range(self.length):
yield self[i]
def same_shape(self):
return Array(self.length, self.value_type)
def assign(self, other, base=0):
try:
other = other.get_vector()
except:
pass
try:
other.store_in_mem(self.get_address(base))
assert len(self) >= other.size + base
except AttributeError:
for i,j in enumerate(other):
self[i] = j
return self
def assign_all(self, value, use_threads=True, conv=True):
if conv:
value = self.value_type.conv(value)
mem_value = MemValue(value)
n_threads = 8 if use_threads and len(self) > 2**20 else 1
@library.for_range_multithread(n_threads, 1024, len(self))
def f(i):
self[i] = mem_value
return self
def get_vector(self, base=0, size=None):
size = size or self.length
return self.value_type.load_mem(self.get_address(base), size=size)
def get_mem_value(self, index):
return MemValue(self[index], self.get_address(index))
def input_from(self, player, budget=None):
self.assign(self.value_type.get_input_from(player, size=len(self)))
def __add__(self, other):
if other is 0:
return self
assert len(self) == len(other)
return self.get_vector() + other
def __sub__(self, other):
assert len(self) == len(other)
return self.get_vector() - other
def __mul__(self, value):
return self.get_vector() * value
def __pow__(self, value):
return self.get_vector() ** value
__radd__ = __add__
__rmul__ = __mul__
def shuffle(self):
@library.for_range(len(self))
def _(i):
j = regint.get_random(64) % (len(self) - i)
tmp = self[i]
self[i] = self[i + j]
self[i + j] = tmp
def reveal(self):
return Array.create_from(x.reveal() for x in self)
sint.dynamic_array = Array
sgf2n.dynamic_array = Array
class SubMultiArray(object):
def __init__(self, sizes, value_type, address, index, debug=None):
self.sizes = sizes
self.value_type = _get_type(value_type)
self.address = address + index * self.total_size()
self.sub_cache = {}
self.debug = debug
if debug:
library.print_ln_if(self.address + reduce(operator.mul, self.sizes) * self.value_type.n_elements() > program.allocated_mem[self.value_type.reg_type], 'AOF%d:' % len(self.sizes) + self.debug)
def __getitem__(self, index):
if util.is_constant(index) and index >= self.sizes[0]:
raise StopIteration
key = program.curr_block, str(index)
if key not in self.sub_cache:
if self.debug:
library.print_ln_if(index >= self.sizes[0], \
'OF%d:' % len(self.sizes) + self.debug)
if len(self.sizes) == 2:
self.sub_cache[key] = \
Array(self.sizes[1], self.value_type, \
self.address + index * self.sizes[1] *
self.value_type.n_elements(), \
debug=self.debug)
else:
self.sub_cache[key] = \
SubMultiArray(self.sizes[1:], self.value_type, \
self.address, index, debug=self.debug)
return self.sub_cache[key]
def __setitem__(self, index, other):
self[index].assign(other)
def __len__(self):
return self.sizes[0]
def assign_all(self, value):
@library.for_range(self.sizes[0])
def f(i):
self[i].assign_all(value)
return self
def total_size(self):
return reduce(operator.mul, self.sizes) * self.value_type.n_elements()
def get_vector(self, base=0, size=None):
assert self.value_type.n_elements() == 1
size = size or self.total_size()
return self.value_type.load_mem(self.address + base, size=size)
def assign_vector(self, vector, base=0):
assert self.value_type.n_elements() == 1
assert vector.size <= self.total_size()
vector.store_in_mem(self.address + base)
def assign(self, other):
if self.value_type.n_elements() > 1:
assert self.sizes == other.sizes
self.assign_vector(other.get_vector())
def same_shape(self):
return MultiArray(self.sizes, self.value_type)
def input_from(self, player, budget=None):
@library.for_range_opt(self.sizes[0], budget=budget)
def _(i):
self[i].input_from(player, budget=budget)
def schur(self, other):
assert self.sizes == other.sizes
if len(self.sizes) == 2:
res = Matrix(self.sizes[0], self.sizes[1], self.value_type)
else:
res = MultiArray(self.sizes, self.value_type)
res.assign_vector(self.get_vector() * other.get_vector())
return res
def __add__(self, other):
if other is 0:
return self
assert self.sizes == other.sizes
if len(self.sizes) == 2:
res = Matrix(self.sizes[0], self.sizes[1], self.value_type)
else:
res = MultiArray(self.sizes, self.value_type)
res.assign_vector(self.get_vector() + other.get_vector())
return res
__radd__ = __add__
def iadd(self, other):
assert self.sizes == other.sizes
self.assign_vector(self.get_vector() + other.get_vector())
def __mul__(self, other):
return self.mul(other)
def mul(self, other, res_params=None):
assert len(self.sizes) == 2
if isinstance(other, Array):
assert len(other) == self.sizes[1]
if self.value_type.n_elements() == 1:
matrix = Matrix(len(other), 1, other.value_type, \
address=other.address)
res = self * matrix
return Array(res.sizes[0], res.value_type, address=res.address)
else:
matrix = Matrix(len(other), 1, other.value_type)
for i, x in enumerate(other):
matrix[i][0] = x
res = self * matrix
return Array.create_from(x[0] for x in res)
elif isinstance(other, SubMultiArray):
assert len(other.sizes) == 2
assert other.sizes[0] == self.sizes[1]
if res_params is not None:
class t(self.value_type):
pass
t.params = res_params
else:
t = self.value_type
res_matrix = Matrix(self.sizes[0], other.sizes[1], t)
try:
if max(res_matrix.sizes) > 1000:
raise AttributeError()
A = self.get_vector()
B = other.get_vector()
res_matrix.assign_vector(
self.value_type.matrix_mul(A, B, self.sizes[1],
res_params))
except (AttributeError, AssertionError):
# fallback for sfloat etc.
@library.for_range_opt(self.sizes[0])
def _(i):
try:
res_matrix[i] = self.value_type.row_matrix_mul(
self[i], other, res_params)
except AttributeError:
# fallback for binary circuits
@library.for_range(other.sizes[1])
def _(j):
res_matrix[i][j] = 0
@library.for_range(self.sizes[1])
def _(k):
res_matrix[i][j] += self[i][k] * other[k][j]
return res_matrix
else:
raise NotImplementedError
def budget_mul(self, other, n_rows, row, n_columns, column, reduce=True,
res=None):
assert len(self.sizes) == 2
assert len(other.sizes) == 2
if res is None:
if reduce:
res_matrix = Matrix(n_rows, n_columns, self.value_type)
else:
res_matrix = Matrix(n_rows, n_columns, \
self.value_type.unreduced_type)
else:
res_matrix = res
@library.for_range_opt(n_rows)
def _(i):
@library.for_range_opt(n_columns)
def _(j):
col = column(other, j)
r = row(self, i)
if reduce:
res_matrix[i][j] = self.value_type.dot_product(r, col)
else:
entry = self.value_type.unreduced_dot_product(r, col)
res_matrix[i][j] = entry
return res_matrix
def plain_mul(self, other, res=None):
assert other.sizes[0] == self.sizes[1]
return self.budget_mul(other, self.sizes[0], lambda x, i: x[i], \
other.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))],
res=res)
def mul_trans(self, other):
assert other.sizes[1] == self.sizes[1]
return self.budget_mul(other, self.sizes[0], lambda x, i: x[i], \
other.sizes[0], lambda x, j: x[j])
def trans_mul(self, other, reduce=True, res=None):
assert other.sizes[0] == self.sizes[0]
return self.budget_mul(other, self.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))], \
other.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))],
reduce=reduce, res=res)
def transpose(self):
assert len(self.sizes) == 2
res = Matrix(self.sizes[1], self.sizes[0], self.value_type)
@library.for_range_opt(self.sizes[1])
def _(i):
@library.for_range_opt(self.sizes[0])
def _(j):
res[i][j] = self[j][i]
return res
class MultiArray(SubMultiArray):
def __init__(self, sizes, value_type, debug=None, address=None):
if isinstance(address, Array):
self.array = address
else:
self.array = Array(reduce(operator.mul, sizes), \
value_type, address=address)
SubMultiArray.__init__(self, sizes, value_type, self.array.address, 0, \
debug=debug)
if len(sizes) < 2:
raise CompilerError('Use Array')
class Matrix(MultiArray):
def __init__(self, rows, columns, value_type, debug=None, address=None):
MultiArray.__init__(self, [rows, columns], value_type, debug=debug, \
address=address)
class VectorArray(object):
def __init__(self, length, value_type, vector_size, address=None):
self.array = Array(length * vector_size, value_type, address)
self.vector_size = vector_size
self.value_type = value_type
def __getitem__(self, index):
return self.value_type.load_mem(self.array.address + \
index * self.vector_size,
size=self.vector_size)
def __setitem__(self, index, value):
if value.size != self.vector_size:
raise CompilerError('vector size mismatch')
value.store_in_mem(self.array.address + index * self.vector_size)
class _mem(_number):
__add__ = lambda self,other: self.read() + other
__sub__ = lambda self,other: self.read() - other
__mul__ = lambda self,other: self.read() * other
__truediv__ = lambda self,other: self.read() / other
__mod__ = lambda self,other: self.read() % other
__pow__ = lambda self,other: self.read() ** other
__neg__ = lambda self,other: -self.read()
__lt__ = lambda self,other: self.read() < other
__gt__ = lambda self,other: self.read() > other
__le__ = lambda self,other: self.read() <= other
__ge__ = lambda self,other: self.read() >= other
__eq__ = lambda self,other: self.read() == other
__ne__ = lambda self,other: self.read() != other
__and__ = lambda self,other: self.read() & other
__xor__ = lambda self,other: self.read() ^ other
__or__ = lambda self,other: self.read() | other
__lshift__ = lambda self,other: self.read() << other
__rshift__ = lambda self,other: self.read() >> other
__radd__ = lambda self,other: other + self.read()
__rsub__ = lambda self,other: other - self.read()
__rmul__ = lambda self,other: other * self.read()
__rtruediv__ = lambda self,other: other / self.read()
__rmod__ = lambda self,other: other % self.read()
__rand__ = lambda self,other: other & self.read()
__rxor__ = lambda self,other: other ^ self.read()
__ror__ = lambda self,other: other | self.read()
__iadd__ = lambda self,other: self.write(self.read() + other)
__isub__ = lambda self,other: self.write(self.read() - other)
__imul__ = lambda self,other: self.write(self.read() * other)
__idiv__ = lambda self,other: self.write(self.read() / other)
__imod__ = lambda self,other: self.write(self.read() % other)
__ipow__ = lambda self,other: self.write(self.read() ** other)
__iand__ = lambda self,other: self.write(self.read() & other)
__ixor__ = lambda self,other: self.write(self.read() ^ other)
__ior__ = lambda self,other: self.write(self.read() | other)
__ilshift__ = lambda self,other: self.write(self.read() << other)
__irshift__ = lambda self,other: self.write(self.read() >> other)
iadd = __iadd__
isub = __isub__
imul = __imul__
idiv = __idiv__
imod = __imod__
ipow = __ipow__
iand = __iand__
ixor = __ixor__
ior = __ior__
ilshift = __ilshift__
irshift = __irshift__
store_in_mem = lambda self,address: self.read().store_in_mem(address)
class MemValue(_mem):
__slots__ = ['last_write_block', 'reg_type', 'register', 'address', 'deleted']
@classmethod
def if_necessary(cls, value):
if util.is_constant_float(value):
return value
else:
return cls(value)
def __init__(self, value, address=None):
self.last_write_block = None
if isinstance(value, int):
self.value_type = regint
value = regint(value)
elif isinstance(value, MemValue):
self.value_type = value.value_type
else:
self.value_type = type(value)
self.deleted = False
if address is None:
self.address = self.value_type.malloc(1)
self.write(value)
else:
self.address = address
def delete(self):
self.value_type.free(self.address)
self.deleted = True
def check(self):
if self.deleted:
raise CompilerError('MemValue deleted')
def read(self):
self.check()
if program.curr_block != self.last_write_block:
self.register = library.load_mem(self.address, self.value_type)
self.last_write_block = program.curr_block
return self.register
def write(self, value):
self.check()
if isinstance(value, MemValue):
self.register = value.read()
elif isinstance(value, int):
self.register = self.value_type(value)
else:
self.register = value
if not isinstance(self.register, self.value_type):
raise CompilerError('Mismatch in register type, cannot write \
%s to %s' % (type(self.register), self.value_type))
self.register.store_in_mem(self.address)
self.last_write_block = program.curr_block
return self
def reveal(self):
return self.read().reveal()
less_than = lambda self,other,bit_length=None,security=None: \
self.read().less_than(other,bit_length,security)
greater_than = lambda self,other,bit_length=None,security=None: \
self.read().greater_than(other,bit_length,security)
less_equal = lambda self,other,bit_length=None,security=None: \
self.read().less_equal(other,bit_length,security)
greater_equal = lambda self,other,bit_length=None,security=None: \
self.read().greater_equal(other,bit_length,security)
equal = lambda self,other,bit_length=None,security=None: \
self.read().equal(other,bit_length,security)
not_equal = lambda self,other,bit_length=None,security=None: \
self.read().not_equal(other,bit_length,security)
pow2 = lambda self,*args,**kwargs: self.read().pow2(*args, **kwargs)
mod2m = lambda self,*args,**kwargs: self.read().mod2m(*args, **kwargs)
right_shift = lambda self,*args,**kwargs: self.read().right_shift(*args, **kwargs)
bit_decompose = lambda self,*args,**kwargs: self.read().bit_decompose(*args, **kwargs)
if_else = lambda self,*args,**kwargs: self.read().if_else(*args, **kwargs)
expand_to_vector = lambda self,*args,**kwargs: \
self.read().expand_to_vector(*args, **kwargs)
def __repr__(self):
return 'MemValue(%s,%d)' % (self.value_type, self.address)
class MemFloat(_mem):
def __init__(self, *args):
value = sfloat(*args)
self.v = MemValue(value.v)
self.p = MemValue(value.p)
self.z = MemValue(value.z)
self.s = MemValue(value.s)
def write(self, *args):
value = sfloat(*args)
self.v.write(value.v)
self.p.write(value.p)
self.z.write(value.z)
self.s.write(value.s)
def read(self):
return sfloat(self.v, self.p, self.z, self.s)
class MemFix(_mem):
def __init__(self, *args):
arg_type = type(*args)
if arg_type == sfix:
value = sfix(*args)
elif arg_type == cfix:
value = cfix(*args)
else:
raise CompilerError('MemFix init argument error')
self.reg_type = value.v.reg_type
self.v = MemValue(value.v)
def write(self, *args):
value = sfix(*args)
self.v.write(value.v)
def reveal(self):
return cfix(self.v.reveal())
def read(self):
val = self.v.read()
if isinstance(val, sint):
return sfix(val)
else:
return cfix(val)
def getNamedTupleType(*names):
class NamedTuple(object):
class NamedTupleArray(object):
def __init__(self, size, t):
from . import types
self.arrays = [types.Array(size, t) for i in range(len(names))]
def __getitem__(self, index):
return NamedTuple(array[index] for array in self.arrays)
def __setitem__(self, index, item):
for array,value in zip(self.arrays, item):
array[index] = value
@classmethod
def get_array(cls, size, t):
return cls.NamedTupleArray(size, t)
def __init__(self, *args):
if len(args) == 1:
args = args[0]
for name, value in zip(names, args):
self.__dict__[name] = value
def __iter__(self):
for name in names:
yield self.__dict__[name]
def __add__(self, other):
return NamedTuple(i + j for i,j in zip(self, other))
def __sub__(self, other):
return NamedTuple(i - j for i,j in zip(self, other))
def __xor__(self, other):
return NamedTuple(i ^ j for i,j in zip(self, other))
def __mul__(self, other):
return NamedTuple(other * i for i in self)
__rmul__ = __mul__
__rxor__ = __xor__
def reveal(self):
return self.__type__(x.reveal() for x in self)
return NamedTuple
from . import library
| 32.792731 | 202 | 0.561166 | from Compiler.program import Tape
from Compiler.exceptions import *
from Compiler.instructions import *
from Compiler.instructions_base import *
from .floatingpoint import two_power
from . import comparison, floatingpoint
import math
from . import util
import operator
from functools import reduce
class ClientMessageType:
NoType = 0
TripleShares = 1
ClearModpInt = 2
Int32 = 3
ClearModpFix = 4
class MPCThread(object):
def __init__(self, target, name, args = [], runtime_arg = None):
if not callable(target):
raise CompilerError('Target %s for thread %s is not callable' % (target,name))
self.name = name
self.tape = Tape(program.name + '-' + name, program)
self.target = target
self.args = args
self.runtime_arg = runtime_arg
self.running = 0
def start(self, runtime_arg = None):
self.running += 1
program.start_thread(self, runtime_arg or self.runtime_arg)
def join(self):
if not self.running:
raise CompilerError('Thread %s is not running' % self.name)
self.running -= 1
program.stop_thread(self)
def vectorize(operation):
def vectorized_operation(self, *args, **kwargs):
if len(args):
if (isinstance(args[0], Tape.Register) or isinstance(args[0], sfloat)) \
and args[0].size != self.size:
raise CompilerError('Different vector sizes of operands')
set_global_vector_size(self.size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
return vectorized_operation
def vectorize_max(operation):
def vectorized_operation(self, *args, **kwargs):
size = self.size
for arg in args:
try:
size = max(size, arg.size)
except AttributeError:
pass
set_global_vector_size(size)
res = operation(self, *args, **kwargs)
reset_global_vector_size()
return res
return vectorized_operation
def vectorized_classmethod(function):
def vectorized_function(cls, *args, **kwargs):
size = None
if 'size' in kwargs:
size = kwargs.pop('size')
if size:
set_global_vector_size(size)
res = function(cls, *args, **kwargs)
reset_global_vector_size()
else:
res = function(cls, *args, **kwargs)
return res
return classmethod(vectorized_function)
def vectorize_init(function):
def vectorized_init(*args, **kwargs):
size = None
if len(args) > 1 and (isinstance(args[1], Tape.Register) or \
isinstance(args[1], sfloat)):
size = args[1].size
if 'size' in kwargs and kwargs['size'] is not None \
and kwargs['size'] != size:
raise CompilerError('Mismatch in vector size')
if 'size' in kwargs and kwargs['size']:
size = kwargs['size']
if size is not None:
set_global_vector_size(size)
res = function(*args, **kwargs)
reset_global_vector_size()
else:
res = function(*args, **kwargs)
return res
return vectorized_init
def set_instruction_type(operation):
def instruction_typed_operation(self, *args, **kwargs):
set_global_instruction_type(self.instruction_type)
res = operation(self, *args, **kwargs)
reset_global_instruction_type()
return res
return instruction_typed_operation
def read_mem_value(operation):
def read_mem_operation(self, *args, **kwargs):
if len(args) > 0 and isinstance(args[0], MemValue):
args = (args[0].read(),) + args[1:]
return operation(self, *args, **kwargs)
return read_mem_operation
class _number(object):
def square(self):
return self * self
def __add__(self, other):
if other is 0:
return self
else:
return self.add(other)
def __mul__(self, other):
if other is 0:
return 0
elif other is 1:
return self
else:
return self.mul(other)
__radd__ = __add__
__rmul__ = __mul__
@vectorize
def __pow__(self, exp):
if isinstance(exp, int) and exp >= 0:
if exp == 0:
return self.__class__(1)
exp = bin(exp)[3:]
res = self
for i in exp:
res = res.square()
if i == '1':
res *= self
return res
else:
return NotImplemented
def mul_no_reduce(self, other, res_params=None):
return self * other
def reduce_after_mul(self):
return self
def pow2(self, bit_length=None, security=None):
return 2**self
def min(self, other):
return (self < other).if_else(self, other)
def max(self, other):
return (self < other).if_else(other, self)
class _int(object):
def if_else(self, a, b):
if hasattr(a, 'for_mux'):
f, a, b = a.for_mux(b)
else:
f = lambda x: x
return f(self * (a - b) + b)
def cond_swap(self, a, b):
prod = self * (a - b)
return a - prod, b + prod
def bit_xor(self, other):
return self + other - 2 * self * other
class _gf2n(object):
def if_else(self, a, b):
return b ^ self * self.hard_conv(a ^ b)
def cond_swap(self, a, b, t=None):
prod = self * self.hard_conv(a ^ b)
res = a ^ prod, b ^ prod
if t is None:
return res
else:
return tuple(t.conv(r) for r in res)
def bit_xor(self, other):
return self ^ other
class _structure(object):
MemValue = classmethod(lambda cls, value: MemValue(cls.conv(value)))
@classmethod
def Array(cls, size, *args, **kwargs):
return Array(size, cls, *args, **kwargs)
@classmethod
def Matrix(cls, rows, columns, *args, **kwargs):
return Matrix(rows, columns, cls, *args, **kwargs)
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
return sum(row[k].mul_no_reduce(matrix[k].get_vector(),
res_params) \
for k in range(len(row))).reduce_after_mul()
class _register(Tape.Register, _number, _structure):
@staticmethod
def n_elements():
return 1
@vectorized_classmethod
def conv(cls, val):
if isinstance(val, MemValue):
val = val.read()
if isinstance(val, cls):
return val
elif not isinstance(val, _register):
try:
return type(val)(cls.conv(v) for v in val)
except TypeError:
pass
except CompilerError:
pass
return cls(val)
@vectorized_classmethod
@read_mem_value
def hard_conv(cls, val):
if type(val) == cls:
return val
elif not isinstance(val, _register):
try:
return val.hard_conv_me(cls)
except AttributeError:
try:
return type(val)(cls.hard_conv(v) for v in val)
except TypeError:
pass
return cls(val)
@vectorized_classmethod
@set_instruction_type
def _load_mem(cls, address, direct_inst, indirect_inst):
res = cls()
if isinstance(address, _register):
indirect_inst(res, cls._expand_address(address,
get_global_vector_size()))
else:
direct_inst(res, address)
return res
@staticmethod
def _expand_address(address, size):
address = regint.conv(address)
if size > 1 and address.size == 1:
res = regint(size=size)
for i in range(size):
movint(res[i], address + regint(i, size=1))
return res
else:
return address
@set_instruction_type
def _store_in_mem(self, address, direct_inst, indirect_inst):
if isinstance(address, _register):
indirect_inst(self, self._expand_address(address, self.size))
else:
direct_inst(self, address)
@classmethod
def prep_res(cls, other):
return cls()
@staticmethod
def bit_compose(bits):
return sum(b << i for i,b in enumerate(bits))
@classmethod
def malloc(cls, size):
return program.malloc(size, cls)
@set_instruction_type
def __init__(self, reg_type, val, size):
if isinstance(val, (tuple, list)):
size = len(val)
super(_register, self).__init__(reg_type, program.curr_tape, size=size)
if isinstance(val, int):
self.load_int(val)
elif isinstance(val, (tuple, list)):
for i, x in enumerate(val):
self.mov(self[i], type(self)(x, size=1))
elif val is not None:
self.load_other(val)
def sizeof(self):
return self.size
def extend(self, n):
return self
def expand_to_vector(self, size=None):
if size is None:
size = get_global_vector_size()
if self.size == size:
return self
assert self.size == 1
res = type(self)(size=size)
for i in range(size):
movs(res[i], self)
return res
class _clear(_register):
__slots__ = []
mov = staticmethod(movc)
@vectorized_classmethod
@set_instruction_type
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmemc(regint(start), regint(end))
@set_instruction_type
@vectorize
def load_other(self, val):
if isinstance(val, type(self)):
movc(self, val)
else:
self.convert_from(val)
@vectorize
@read_mem_value
def convert_from(self, val):
if not isinstance(val, regint):
val = regint(val)
convint(self, val)
@set_instruction_type
@vectorize
def print_reg(self, comment=''):
print_reg(self, comment)
@set_instruction_type
@vectorize
def print_reg_plain(self):
print_reg_plain(self)
@set_instruction_type
@vectorize
def raw_output(self):
raw_output(self)
@set_instruction_type
@read_mem_value
@vectorize
def clear_op(self, other, c_inst, ci_inst, reverse=False):
cls = self.__class__
res = self.prep_res(other)
if isinstance(other, cls):
c_inst(res, self, other)
elif isinstance(other, int):
if self.in_immediate_range(other):
ci_inst(res, self, other)
else:
if reverse:
c_inst(res, cls(other), self)
else:
c_inst(res, self, cls(other))
else:
return NotImplemented
return res
@set_instruction_type
@read_mem_value
@vectorize
def coerce_op(self, other, inst, reverse=False):
cls = self.__class__
res = cls()
if isinstance(other, int):
other = cls(other)
elif not isinstance(other, cls):
return NotImplemented
if reverse:
inst(res, other, self)
else:
inst(res, self, other)
return res
def add(self, other):
return self.clear_op(other, addc, addci)
def mul(self, other):
return self.clear_op(other, mulc, mulci)
def __sub__(self, other):
return self.clear_op(other, subc, subci)
def __rsub__(self, other):
return self.clear_op(other, subc, subcfi, True)
def __truediv__(self, other):
return self.clear_op(other, divc, divci)
def __rtruediv__(self, other):
return self.coerce_op(other, divc, True)
def __eq__(self, other):
if isinstance(other, (_clear,int)):
return regint(self) == other
else:
return NotImplemented
def __ne__(self, other):
return 1 - (self == other)
def __and__(self, other):
return self.clear_op(other, andc, andci)
def __xor__(self, other):
return self.clear_op(other, xorc, xorci)
def __or__(self, other):
return self.clear_op(other, orc, orci)
__rand__ = __and__
__rxor__ = __xor__
__ror__ = __or__
def reveal(self):
return self
class cint(_clear, _int):
__slots__ = []
instruction_type = 'modp'
reg_type = 'c'
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
res = [cls() for i in range(n)]
readsocketc(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketc(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
writesocketc(client_id, message_type, *values)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldmc, ldmci)
def store_in_mem(self, address):
self._store_in_mem(address, stmc, stmci)
@staticmethod
def in_immediate_range(value):
return value < 2**31 and value >= -2**31
def __init__(self, val=None, size=None):
super(cint, self).__init__('c', val=val, size=size)
@vectorize
def load_int(self, val):
if val:
program.curr_tape.require_bit_length(1 + int(math.ceil(math.log(abs(val)))))
if self.in_immediate_range(val):
ldi(self, val)
else:
max = 2**31 - 1
sign = abs(val) // val
val = abs(val)
chunks = []
while val:
mod = val % max
val = (val - mod) // max
chunks.append(mod)
sum = cint(sign * chunks.pop())
for i,chunk in enumerate(reversed(chunks)):
sum *= max
if i == len(chunks) - 1:
addci(self, sum, sign * chunk)
elif chunk:
sum += sign * chunk
def to_regint(self, n_bits=None, dest=None):
dest = regint() if dest is None else dest
convmodp(dest, self, bitlength=n_bits)
return dest
def __mod__(self, other):
return self.clear_op(other, modc, modci)
def __rmod__(self, other):
return self.coerce_op(other, modc, True)
def __lt__(self, other):
if isinstance(other, (type(self),int)):
return regint(self) < other
else:
return NotImplemented
def __gt__(self, other):
if isinstance(other, (type(self),int)):
return regint(self) > other
else:
return NotImplemented
def __le__(self, other):
return 1 - (self > other)
def __ge__(self, other):
return 1 - (self < other)
@vectorize
def __eq__(self, other):
if not isinstance(other, (_clear, int)):
return NotImplemented
res = 1
remaining = program.bit_length
while remaining > 0:
if isinstance(other, cint):
o = other.to_regint(min(remaining, 64))
else:
o = other % 2 ** 64
res *= (self.to_regint(min(remaining, 64)) == o)
self >>= 64
other >>= 64
remaining -= 64
return res
def __lshift__(self, other):
return self.clear_op(other, shlc, shlci)
def __rshift__(self, other):
return self.clear_op(other, shrc, shrci)
def __neg__(self):
return 0 - self
def __abs__(self):
return (self >= 0).if_else(self, -self)
@vectorize
def __invert__(self):
res = cint()
notc(res, self, program.bit_length)
return res
def __rpow__(self, base):
if base == 2:
return 1 << self
else:
return NotImplemented
@vectorize
def __rlshift__(self, other):
return cint(other) << self
@vectorize
def __rrshift__(self, other):
return cint(other) >> self
@read_mem_value
def mod2m(self, other, bit_length=None, signed=None):
return self % 2**other
@read_mem_value
def right_shift(self, other, bit_length=None):
return self >> other
@read_mem_value
def greater_than(self, other, bit_length=None):
return self > other
def bit_decompose(self, bit_length=None):
if bit_length == 0:
return []
bit_length = bit_length or program.bit_length
return floatingpoint.bits(self, bit_length)
def legendre(self):
res = cint()
legendrec(res, self)
return res
def digest(self, num_bytes):
res = cint()
digestc(res, self, num_bytes)
return res
def print_if(self, string):
cond_print_str(self, string)
class cgf2n(_clear, _gf2n):
__slots__ = []
instruction_type = 'gf2n'
reg_type = 'cg'
@classmethod
def bit_compose(cls, bits, step=None):
size = bits[0].size
res = cls(size=size)
vgbitcom(size, res, step or 1, *bits)
return res
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, gldmc, gldmci)
def store_in_mem(self, address):
self._store_in_mem(address, gstmc, gstmci)
@staticmethod
def in_immediate_range(value):
return value < 2**32 and value >= 0
def __init__(self, val=None, size=None):
super(cgf2n, self).__init__('cg', val=val, size=size)
@vectorize
def load_int(self, val):
if val < 0:
raise CompilerError('Negative GF2n immediate')
if self.in_immediate_range(val):
gldi(self, val)
else:
chunks = []
while val:
mod = val % 2**32
val >>= 32
chunks.append(mod)
sum = cgf2n(chunks.pop())
for i,chunk in enumerate(reversed(chunks)):
sum <<= 32
if i == len(chunks) - 1:
gaddci(self, sum, chunk)
elif chunk:
sum += chunk
def __mul__(self, other):
return super(cgf2n, self).__mul__(other)
def __neg__(self):
return self
@vectorize
def __invert__(self):
res = cgf2n()
gnotc(res, self)
return res
@vectorize
def __lshift__(self, other):
if isinstance(other, int):
res = cgf2n()
gshlci(res, self, other)
return res
else:
return NotImplemented
@vectorize
def __rshift__(self, other):
if isinstance(other, int):
res = cgf2n()
gshrci(res, self, other)
return res
else:
return NotImplemented
@vectorize
def bit_decompose(self, bit_length=None, step=None):
bit_length = bit_length or program.galois_length
step = step or 1
res = [type(self)() for _ in range(bit_length // step)]
gbitdec(self, step, *res)
return res
class regint(_register, _int):
__slots__ = []
reg_type = 'ci'
instruction_type = 'modp'
mov = staticmethod(movint)
@classmethod
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmemint(regint(start), regint(end))
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldmint, ldminti)
def store_in_mem(self, address):
self._store_in_mem(address, stmint, stminti)
@vectorized_classmethod
def pop(cls):
res = cls()
popint(res)
return res
@vectorized_classmethod
def push(cls, value):
pushint(cls.conv(value))
@vectorized_classmethod
def get_random(cls, bit_length):
if isinstance(bit_length, int):
bit_length = regint(bit_length)
res = cls()
rand(res, bit_length)
return res
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
res = [cls() for i in range(n)]
readsocketint(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorized_classmethod
def read_client_public_key(cls, client_id):
res = [cls() for i in range(8)]
readclientpublickey(client_id, *res)
return res
@vectorized_classmethod
def init_secure_socket(cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8):
initsecuresocket(client_id, w1, w2, w3, w4, w5, w6, w7, w8)
@vectorized_classmethod
def resp_secure_socket(cls, client_id, w1, w2, w3, w4, w5, w6, w7, w8):
respsecuresocket(client_id, w1, w2, w3, w4, w5, w6, w7, w8)
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketint(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
writesocketint(client_id, message_type, *values)
@vectorize_init
def __init__(self, val=None, size=None):
super(regint, self).__init__(self.reg_type, val=val, size=size)
def load_int(self, val):
if cint.in_immediate_range(val):
ldint(self, val)
else:
lower = val % 2**32
upper = val >> 32
if lower >= 2**31:
lower -= 2**32
upper += 1
addint(self, regint(upper) * regint(2**16)**2, regint(lower))
@read_mem_value
def load_other(self, val):
if isinstance(val, cgf2n):
gconvgf2n(self, val)
elif isinstance(val, regint):
addint(self, val, regint(0))
else:
try:
val.to_regint(dest=self)
except AttributeError:
raise CompilerError("Cannot convert '%s' to integer" % \
type(val))
@vectorize
@read_mem_value
def int_op(self, other, inst, reverse=False):
try:
other = self.conv(other)
except:
return NotImplemented
res = regint()
if reverse:
inst(res, other, self)
else:
inst(res, self, other)
return res
def add(self, other):
return self.int_op(other, addint)
def __sub__(self, other):
return self.int_op(other, subint)
def __rsub__(self, other):
return self.int_op(other, subint, True)
def mul(self, other):
return self.int_op(other, mulint)
def __neg__(self):
return 0 - self
def __floordiv__(self, other):
return self.int_op(other, divint)
def __rfloordiv__(self, other):
return self.int_op(other, divint, True)
__truediv__ = __floordiv__
__rtruediv__ = __rfloordiv__
def __mod__(self, other):
return self - (self / other) * other
def __rmod__(self, other):
return regint(other) % self
def __rpow__(self, other):
return other**cint(self)
def __eq__(self, other):
return self.int_op(other, eqc)
def __ne__(self, other):
return 1 - (self == other)
def __lt__(self, other):
return self.int_op(other, ltc)
def __gt__(self, other):
return self.int_op(other, gtc)
def __le__(self, other):
return 1 - (self > other)
def __ge__(self, other):
return 1 - (self < other)
def __lshift__(self, other):
if isinstance(other, int):
return self * 2**other
else:
return regint(cint(self) << other)
def __rshift__(self, other):
if isinstance(other, int):
return self / 2**other
else:
return regint(cint(self) >> other)
def __rlshift__(self, other):
return regint(other << cint(self))
def __rrshift__(self, other):
return regint(other >> cint(self))
def __and__(self, other):
return regint(other & cint(self))
def __or__(self, other):
return regint(other | cint(self))
def __xor__(self, other):
return regint(other ^ cint(self))
__rand__ = __and__
__ror__ = __or__
__rxor__ = __xor__
def mod2m(self, *args, **kwargs):
return cint(self).mod2m(*args, **kwargs)
@vectorize
def bit_decompose(self, bit_length=None):
bit_length = bit_length or min(64, program.bit_length)
if bit_length > 64:
raise CompilerError('too many bits demanded')
res = [regint() for i in range(bit_length)]
bitdecint(self, *res)
return res
@staticmethod
def bit_compose(bits):
two = regint(2)
res = 0
for bit in reversed(bits):
res *= two
res += bit
return res
def reveal(self):
return self
def print_reg_plain(self):
print_int(self)
def print_if(self, string):
cint(self).print_if(string)
class localint(object):
def __init__(self, value=None):
self._v = regint(value)
self.size = 1
def output(self):
self._v.print_reg_plain()
__lt__ = lambda self, other: localint(self._v < other)
__le__ = lambda self, other: localint(self._v <= other)
__gt__ = lambda self, other: localint(self._v > other)
__ge__ = lambda self, other: localint(self._v >= other)
__eq__ = lambda self, other: localint(self._v == other)
__ne__ = lambda self, other: localint(self._v != other)
class _secret(_register):
__slots__ = []
mov = staticmethod(movs)
PreOR = staticmethod(lambda l: floatingpoint.PreORC(l))
PreOp = staticmethod(lambda op, l: floatingpoint.PreOpL(op, l))
@vectorized_classmethod
@set_instruction_type
def protect_memory(cls, start, end):
program.curr_tape.start_new_basicblock(name='protect-memory')
protectmems(regint(start), regint(end))
@vectorized_classmethod
@set_instruction_type
def get_input_from(cls, player):
res = cls()
asm_input(res, player)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_triple(cls):
res = (cls(), cls(), cls())
triple(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_bit(cls):
res = cls()
bit(res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_square(cls):
res = (cls(), cls())
square(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_inverse(cls):
res = (cls(), cls())
inverse(*res)
return res
@vectorized_classmethod
@set_instruction_type
def get_random_input_mask_for(cls, player):
res = cls()
inputmask(res, player)
return res
@classmethod
@set_instruction_type
def dot_product(cls, x, y):
x = list(x)
set_global_vector_size(x[0].size)
res = cls()
dotprods(res, x, y)
reset_global_vector_size()
return res
@classmethod
@set_instruction_type
def row_matrix_mul(cls, row, matrix, res_params=None):
assert len(row) == len(matrix)
size = len(matrix[0])
res = cls(size=size)
dotprods(*sum(([res[j], row, [matrix[k][j] for k in range(len(row))]]
for j in range(size)), []))
return res
@classmethod
@set_instruction_type
def matrix_mul(cls, A, B, n, res_params=None):
assert len(A) % n == 0
assert len(B) % n == 0
size = len(A) * len(B) // n**2
res = cls(size=size)
n_rows = len(A) // n
n_cols = len(B) // n
dotprods(*sum(([res[j], [A[j // n_cols * n + k] for k in range(n)],
[B[k * n_cols + j % n_cols] for k in range(n)]]
for j in range(size)), []))
return res
def __init__(self, reg_type, val=None, size=None):
if isinstance(val, self.clear_type):
size = val.size
super(_secret, self).__init__(reg_type, val=val, size=size)
@set_instruction_type
@vectorize
def load_int(self, val):
if self.clear_type.in_immediate_range(val):
ldsi(self, val)
else:
self.load_clear(self.clear_type(val))
@vectorize
def load_clear(self, val):
addm(self, self.__class__(0), val)
@set_instruction_type
@read_mem_value
@vectorize
def load_other(self, val):
if isinstance(val, self.clear_type):
self.load_clear(val)
elif isinstance(val, type(self)):
movs(self, val)
else:
self.load_clear(self.clear_type(val))
def _new_by_number(self, i):
res = type(self)(size=1)
res.i = i
res.program = self.program
return res
@set_instruction_type
@read_mem_value
@vectorize
def secret_op(self, other, s_inst, m_inst, si_inst, reverse=False):
cls = self.__class__
res = self.prep_res(other)
if isinstance(other, regint):
other = res.clear_type(other)
if isinstance(other, cls):
s_inst(res, self, other)
elif isinstance(other, res.clear_type):
if reverse:
m_inst(res, other, self)
else:
m_inst(res, self, other)
elif isinstance(other, int):
if self.clear_type.in_immediate_range(other):
si_inst(res, self, other)
else:
if reverse:
m_inst(res, res.clear_type(other), self)
else:
m_inst(res, self, res.clear_type(other))
else:
return NotImplemented
return res
def add(self, other):
return self.secret_op(other, adds, addm, addsi)
@set_instruction_type
def mul(self, other):
if isinstance(other, _secret) and max(self.size, other.size) > 1 \
and min(self.size, other.size) == 1:
x, y = (other, self) if self.size < other.size else (self, other)
res = type(self)(size=x.size)
mulrs(res, x, y)
return res
return self.secret_op(other, muls, mulm, mulsi)
def __sub__(self, other):
return self.secret_op(other, subs, subml, subsi)
def __rsub__(self, other):
return self.secret_op(other, subs, submr, subsfi, True)
@vectorize
def __truediv__(self, other):
return self * (self.clear_type(1) / other)
@vectorize
def __rtruediv__(self, other):
a,b = self.get_random_inverse()
return other * a / (a * self).reveal()
@set_instruction_type
@vectorize
def square(self):
res = self.__class__()
sqrs(res, self)
return res
@set_instruction_type
@vectorize
def reveal(self):
res = self.clear_type()
asm_open(res, self)
return res
@set_instruction_type
def reveal_to(self, player):
masked = self.__class__()
startprivateoutput(masked, self, player)
stopprivateoutput(masked.reveal(), player)
class sint(_secret, _int):
__slots__ = []
instruction_type = 'modp'
clear_type = cint
reg_type = 's'
PreOp = staticmethod(floatingpoint.PreOpL)
PreOR = staticmethod(floatingpoint.PreOR)
get_type = staticmethod(lambda n: sint)
@vectorized_classmethod
def get_random_int(cls, bits):
res = sint()
comparison.PRandInt(res, bits)
return res
@vectorized_classmethod
def get_input_from(cls, player):
res = cls()
inputmixed('int', res, player)
return res
@classmethod
def get_raw_input_from(cls, player):
res = cls()
startinput(player, 1)
stopinput(player, res)
return res
@classmethod
def receive_from_client(cls, n, client_id, message_type=ClientMessageType.NoType):
triples = list(itertools.chain(*(sint.get_random_triple() for i in range(n))))
sint.write_shares_to_socket(client_id, triples, message_type)
received = cint.read_from_socket(client_id, n)
y = [0] * n
for i in range(n):
y[i] = received[i] - triples[i * 3]
return y
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
res = [cls() for i in range(n)]
readsockets(client_id, *res)
if n == 1:
return res[0]
else:
return res
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesockets(client_id, message_type, self)
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
writesockets(client_id, message_type, *values)
@vectorize
def write_share_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketshare(client_id, message_type, self)
@vectorized_classmethod
def write_shares_to_socket(cls, client_id, values, message_type=ClientMessageType.NoType, include_macs=False):
if include_macs:
writesockets(client_id, message_type, *values)
else:
writesocketshare(client_id, message_type, *values)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, ldms, ldmsi)
def store_in_mem(self, address):
self._store_in_mem(address, stms, stmsi)
def __init__(self, val=None, size=None):
super(sint, self).__init__('s', val=val, size=size)
@vectorize
def __neg__(self):
return 0 - self
@vectorize
def __abs__(self):
return (self >= 0).if_else(self, -self)
@read_mem_value
@vectorize
def __lt__(self, other, bit_length=None, security=None):
res = sint()
comparison.LTZ(res, self - other,
(bit_length or program.bit_length) + 1,
security or program.security)
return res
@read_mem_value
@vectorize
def __gt__(self, other, bit_length=None, security=None):
res = sint()
comparison.LTZ(res, other - self,
(bit_length or program.bit_length) + 1,
security or program.security)
return res
def __le__(self, other, bit_length=None, security=None):
return 1 - self.greater_than(other, bit_length, security)
def __ge__(self, other, bit_length=None, security=None):
return 1 - self.less_than(other, bit_length, security)
@read_mem_value
@vectorize
def __eq__(self, other, bit_length=None, security=None):
return floatingpoint.EQZ(self - other, bit_length or program.bit_length,
security or program.security)
def __ne__(self, other, bit_length=None, security=None):
return 1 - self.equal(other, bit_length, security)
less_than = __lt__
greater_than = __gt__
less_equal = __le__
greater_equal = __ge__
equal = __eq__
not_equal = __ne__
@vectorize
def __mod__(self, modulus):
if isinstance(modulus, int):
l = math.log(modulus, 2)
if 2**int(round(l)) == modulus:
return self.mod2m(int(l))
raise NotImplementedError('Modulo only implemented for powers of two.')
@read_mem_value
def mod2m(self, m, bit_length=None, security=None, signed=True):
bit_length = bit_length or program.bit_length
security = security or program.security
if isinstance(m, int):
if m == 0:
return 0
if m >= bit_length:
return self
res = sint()
comparison.Mod2m(res, self, bit_length, m, security, signed)
else:
res, pow2 = floatingpoint.Trunc(self, bit_length, m, security, True)
return res
@vectorize
def __rpow__(self, base):
if base == 2:
return self.pow2()
else:
return NotImplemented
@vectorize
def pow2(self, bit_length=None, security=None):
return floatingpoint.Pow2(self, bit_length or program.bit_length, \
security or program.security)
def __lshift__(self, other, bit_length=None, security=None):
return self * util.pow2_value(other, bit_length, security)
@vectorize
@read_mem_value
def __rshift__(self, other, bit_length=None, security=None):
bit_length = bit_length or program.bit_length
security = security or program.security
if isinstance(other, int):
if other == 0:
return self
res = sint()
comparison.Trunc(res, self, bit_length, other, security, True)
return res
elif isinstance(other, sint):
return floatingpoint.Trunc(self, bit_length, other, security)
else:
return floatingpoint.Trunc(self, bit_length, sint(other), security)
left_shift = __lshift__
right_shift = __rshift__
def __rlshift__(self, other):
return other * 2**self
@vectorize
def __rrshift__(self, other):
return floatingpoint.Trunc(other, program.bit_length, self, program.security)
def bit_decompose(self, bit_length=None, security=None):
if bit_length == 0:
return []
bit_length = bit_length or program.bit_length
security = security or program.security
return floatingpoint.BitDec(self, bit_length, bit_length, security)
def TruncMul(self, other, k, m, kappa=None, nearest=False):
return (self * other).round(k, m, kappa, nearest, signed=True)
def TruncPr(self, k, m, kappa=None, signed=True):
return floatingpoint.TruncPr(self, k, m, kappa, signed=signed)
@vectorize
def round(self, k, m, kappa=None, nearest=False, signed=False):
kappa = kappa or program.security
secret = isinstance(m, sint)
if nearest:
if secret:
raise NotImplementedError()
return comparison.TruncRoundNearest(self, k, m, kappa,
signed=signed)
else:
if secret:
return floatingpoint.Trunc(self, k, m, kappa)
return self.TruncPr(k, m, kappa, signed=signed)
def Norm(self, k, f, kappa=None, simplex_flag=False):
return library.Norm(self, k, f, kappa, simplex_flag)
@vectorize
def int_div(self, other, bit_length=None, security=None):
k = bit_length or program.bit_length
kappa = security or program.security
tmp = library.IntDiv(self, other, k, kappa)
res = type(self)()
comparison.Trunc(res, tmp, 2 * k, k, kappa, True)
return res
@staticmethod
def two_power(n):
return floatingpoint.two_power(n)
class sgf2n(_secret, _gf2n):
__slots__ = []
instruction_type = 'gf2n'
clear_type = cgf2n
reg_type = 'sg'
@classmethod
def get_type(cls, length):
return cls
@classmethod
def get_raw_input_from(cls, player):
res = cls()
gstartinput(player, 1)
gstopinput(player, res)
return res
def add(self, other):
if isinstance(other, sgf2nint):
return NotImplemented
else:
return super(sgf2n, self).add(other)
def mul(self, other):
if isinstance(other, (sgf2nint)):
return NotImplemented
else:
return super(sgf2n, self).mul(other)
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._load_mem(address, gldms, gldmsi)
def store_in_mem(self, address):
self._store_in_mem(address, gstms, gstmsi)
def __init__(self, val=None, size=None):
super(sgf2n, self).__init__('sg', val=val, size=size)
def __neg__(self):
return self
@vectorize
def __invert__(self):
return self ^ cgf2n(2**program.galois_length - 1)
def __xor__(self, other):
if other is 0:
return self
else:
return super(sgf2n, self).add(other)
__rxor__ = __xor__
@vectorize
def __and__(self, other):
if isinstance(other, int):
other_bits = [(other >> i) & 1 \
for i in range(program.galois_length)]
else:
other_bits = other.bit_decompose()
self_bits = self.bit_decompose()
return sum((x * y) << i \
for i,(x,y) in enumerate(zip(self_bits, other_bits)))
__rand__ = __and__
@vectorize
def __lshift__(self, other):
return self * cgf2n(1 << other)
@vectorize
def right_shift(self, other, bit_length=None):
bits = self.bit_decompose(bit_length)
return sum(b << i for i,b in enumerate(bits[other:]))
def equal(self, other, bit_length=None, expand=1):
bits = [1 - bit for bit in (self - other).bit_decompose(bit_length)][::expand]
while len(bits) > 1:
bits.insert(0, bits.pop() * bits.pop())
return bits[0]
def not_equal(self, other, bit_length=None):
return 1 - self.equal(other, bit_length)
__eq__ = equal
__ne__ = not_equal
@vectorize
def bit_decompose(self, bit_length=None, step=1):
if bit_length == 0:
return []
bit_length = bit_length or program.galois_length
random_bits = [self.get_random_bit() \
for i in range(0, bit_length, step)]
one = cgf2n(1)
masked = sum([b * (one << (i * step)) for i,b in enumerate(random_bits)], self).reveal()
masked_bits = masked.bit_decompose(bit_length,step=step)
return [m + r for m,r in zip(masked_bits, random_bits)]
@vectorize
def bit_decompose_embedding(self):
random_bits = [self.get_random_bit() \
for i in range(8)]
one = cgf2n(1)
wanted_positions = [0, 5, 10, 15, 20, 25, 30, 35]
masked = sum([b * (one << wanted_positions[i]) for i,b in enumerate(random_bits)], self).reveal()
return [self.clear_type((masked >> wanted_positions[i]) & one) + r for i,r in enumerate(random_bits)]
for t in (sint, sgf2n):
t.bit_type = t
t.basic_type = t
t.default_type = t
class _bitint(object):
bits = None
log_rounds = False
linear_rounds = False
@classmethod
def bit_adder(cls, a, b, carry_in=0, get_carry=False):
a, b = list(a), list(b)
a += [0] * (len(b) - len(a))
b += [0] * (len(a) - len(b))
return cls.bit_adder_selection(a, b, carry_in=carry_in,
get_carry=get_carry)
@classmethod
def bit_adder_selection(cls, a, b, carry_in=0, get_carry=False):
if cls.log_rounds:
return cls.carry_lookahead_adder(a, b, carry_in=carry_in)
elif cls.linear_rounds:
return cls.ripple_carry_adder(a, b, carry_in=carry_in)
else:
return cls.carry_select_adder(a, b, carry_in=carry_in)
@classmethod
def carry_lookahead_adder(cls, a, b, fewer_inv=False, carry_in=0,
get_carry=False):
lower = []
for (ai,bi) in zip(a,b):
if ai is 0 or bi is 0:
lower.append(ai + bi)
a.pop(0)
b.pop(0)
else:
break
d = [cls.half_adder(ai, bi) for (ai,bi) in zip(a,b)]
carry = floatingpoint.carry
if fewer_inv:
pre_op = floatingpoint.PreOpL2
else:
pre_op = floatingpoint.PreOpL
if d:
carries = list(zip(*pre_op(carry, [(0, carry_in)] + d)))[1]
else:
carries = []
res = lower + cls.sum_from_carries(a, b, carries)
if get_carry:
res += [carries[-1]]
return res
@staticmethod
def sum_from_carries(a, b, carries):
return [ai.bit_xor(bi).bit_xor(carry) \
for (ai, bi, carry) in zip(a, b, carries)]
@classmethod
def carry_select_adder(cls, a, b, get_carry=False, carry_in=0):
a += [0] * (len(b) - len(a))
b += [0] * (len(a) - len(b))
n = len(a)
for m in range(100):
if sum(range(m + 1)) + 1 >= n:
break
for k in range(m, -1, -1):
if sum(range(m, k - 1, -1)) + 1 >= n:
break
blocks = list(range(m, k, -1))
blocks.append(n - sum(blocks))
blocks.reverse()
if len(blocks) > 1 and blocks[0] > blocks[1]:
raise Exception('block size not increasing:', blocks)
if sum(blocks) != n:
raise Exception('blocks not summing up: %s != %s' % \
(sum(blocks), n))
res = []
carry = carry_in
cin_one = util.long_one(a + b)
for m in blocks:
aa = a[:m]
bb = b[:m]
a = a[m:]
b = b[m:]
cc = [cls.ripple_carry_adder(aa, bb, i) for i in (0, cin_one)]
for i in range(m):
res.append(util.if_else(carry, cc[1][i], cc[0][i]))
carry = util.if_else(carry, cc[1][m], cc[0][m])
if get_carry:
res += [carry]
return res
@classmethod
def ripple_carry_adder(cls, a, b, carry_in=0):
carry = carry_in
res = []
for aa, bb in zip(a, b):
cc, carry = cls.full_adder(aa, bb, carry)
res.append(cc)
res.append(carry)
return res
@staticmethod
def full_adder(a, b, carry):
s = a + b
return s + carry, util.if_else(s, carry, a)
@staticmethod
def half_adder(a, b):
return a + b, a & b
@staticmethod
def bit_comparator(a, b):
long_one = util.long_one(a + b)
op = lambda y,x,*args: (util.if_else(x[1], x[0], y[0]), \
util.if_else(x[1], long_one, y[1]))
return floatingpoint.KOpL(op, [(bi, ai + bi) for (ai,bi) in zip(a,b)])
@classmethod
def bit_less_than(cls, a, b):
x, not_equal = cls.bit_comparator(a, b)
return util.if_else(not_equal, x, 0)
@staticmethod
def get_highest_different_bits(a, b, index):
diff = [ai + bi for (ai,bi) in reversed(list(zip(a,b)))]
preor = floatingpoint.PreOR(diff, raw=True)
highest_diff = [x - y for (x,y) in reversed(list(zip(preor, [0] + preor)))]
raw = sum(map(operator.mul, highest_diff, (a,b)[index]))
return raw.bit_decompose()[0]
def load_int(self, other):
if -2**(self.n_bits-1) <= other < 2**(self.n_bits-1):
self.bin_type.load_int(self, other + 2**self.n_bits \
if other < 0 else other)
else:
raise CompilerError('Invalid signed %d-bit integer: %d' % \
(self.n_bits, other))
def add(self, other):
if type(other) == self.bin_type:
raise CompilerError('Unclear addition')
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
return self.compose(self.bit_adder(a, b))
def mul(self, other):
if type(other) == self.bin_type:
raise CompilerError('Unclear multiplication')
self_bits = self.bit_decompose()
if isinstance(other, int):
other_bits = util.bit_decompose(other, self.n_bits)
bit_matrix = [[x * y for y in self_bits] for x in other_bits]
else:
try:
other_bits = other.bit_decompose()
if len(other_bits) == 1:
return type(self)(other_bits[0] * self)
if len(self_bits) != len(other_bits):
raise NotImplementedError('Multiplication of different lengths')
except AttributeError:
pass
try:
other = self.bin_type(other)
except CompilerError:
return NotImplemented
products = [x * other for x in self_bits]
bit_matrix = [util.bit_decompose(x, self.n_bits) for x in products]
return self.compose(self.wallace_tree_from_matrix(bit_matrix, False))
@classmethod
def wallace_tree_from_matrix(cls, bit_matrix, get_carry=True):
columns = [[_f for _f in (bit_matrix[j][i-j] \
for j in range(min(len(bit_matrix), i + 1))) if _f] \
for i in range(len(bit_matrix[0]))]
return cls.wallace_tree_from_columns(columns, get_carry)
@classmethod
def wallace_tree_from_columns(cls, columns, get_carry=True):
self = cls
while max(len(c) for c in columns) > 2:
new_columns = [[] for i in range(len(columns) + 1)]
for i,col in enumerate(columns):
while len(col) > 2:
s, carry = self.full_adder(*(col.pop() for i in range(3)))
new_columns[i].append(s)
new_columns[i+1].append(carry)
if len(col) == 2:
s, carry = self.half_adder(*(col.pop() for i in range(2)))
new_columns[i].append(s)
new_columns[i+1].append(carry)
else:
new_columns[i].extend(col)
if get_carry:
columns = new_columns
else:
columns = new_columns[:-1]
for col in columns:
col.extend([0] * (2 - len(col)))
return self.bit_adder(*list(zip(*columns)))
@classmethod
def wallace_tree(cls, rows):
return cls.wallace_tree_from_columns([list(x) for x in zip(*rows)])
def __sub__(self, other):
if type(other) == sgf2n:
raise CompilerError('Unclear subtraction')
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
d = [(1 + ai + bi, (1 - ai) * bi) for (ai,bi) in zip(a,b)]
borrow = lambda y,x,*args: \
(x[0] * y[0], 1 - (1 - x[1]) * (1 - x[0] * y[1]))
borrows = (0,) + list(zip(*floatingpoint.PreOpL(borrow, d)))[1]
return self.compose(ai + bi + borrow \
for (ai,bi,borrow) in zip(a,b,borrows))
def __rsub__(self, other):
raise NotImplementedError()
def __truediv__(self, other):
raise NotImplementedError()
def __truerdiv__(self, other):
raise NotImplementedError()
def __lshift__(self, other):
return self.compose(([0] * other + self.bit_decompose())[:self.n_bits])
def __rshift__(self, other):
return self.compose(self.bit_decompose()[other:])
def bit_decompose(self, n_bits=None, *args):
if self.bits is None:
self.bits = self.force_bit_decompose(self.n_bits)
if n_bits is None:
return self.bits[:]
else:
return self.bits[:n_bits] + [self.fill_bit()] * (n_bits - self.n_bits)
def fill_bit(self):
return self.bits[-1]
@staticmethod
def prep_comparison(a, b):
a[-1], b[-1] = b[-1], a[-1]
def comparison(self, other, const_rounds=False, index=None):
a = self.bit_decompose()
b = util.bit_decompose(other, self.n_bits)
self.prep_comparison(a, b)
if const_rounds:
return self.get_highest_different_bits(a, b, index)
else:
return self.bit_comparator(a, b)
def __lt__(self, other):
if program.options.comparison == 'log':
x, not_equal = self.comparison(other)
return util.if_else(not_equal, x, 0)
else:
return self.comparison(other, True, 1)
def __le__(self, other):
if program.options.comparison == 'log':
x, not_equal = self.comparison(other)
return util.if_else(not_equal, x, 1)
else:
return 1 - self.comparison(other, True, 0)
def __ge__(self, other):
return 1 - (self < other)
def __gt__(self, other):
return 1 - (self <= other)
def __eq__(self, other):
diff = self ^ other
diff_bits = [1 - x for x in diff.bit_decompose()]
return floatingpoint.KMul(diff_bits)
def __ne__(self, other):
return 1 - (self == other)
def __neg__(self):
return 1 + self.compose(1 ^ b for b in self.bit_decompose())
def __abs__(self):
return util.if_else(self.bit_decompose()[-1], -self, self)
less_than = lambda self, other, *args, **kwargs: self < other
greater_than = lambda self, other, *args, **kwargs: self > other
less_equal = lambda self, other, *args, **kwargs: self <= other
greater_equal = lambda self, other, *args, **kwargs: self >= other
equal = lambda self, other, *args, **kwargs: self == other
not_equal = lambda self, other, *args, **kwargs: self != other
class intbitint(_bitint, sint):
@staticmethod
def full_adder(a, b, carry):
s = a.bit_xor(b)
return s.bit_xor(carry), util.if_else(s, carry, a)
@staticmethod
def half_adder(a, b):
carry = a * b
return a + b - 2 * carry, carry
@staticmethod
def sum_from_carries(a, b, carries):
return [a[i] + b[i] + carries[i] - 2 * carries[i + 1] \
for i in range(len(a))]
@classmethod
def bit_adder_selection(cls, a, b, carry_in=0, get_carry=False):
if cls.linear_rounds:
return cls.ripple_carry_adder(a, b, carry_in=carry_in)
elif len(a) < 122 or cls.log_rounds:
return cls.carry_lookahead_adder(a, b, carry_in=carry_in,
get_carry=get_carry)
else:
return cls.carry_select_adder(a, b, carry_in=carry_in)
class sgf2nint(_bitint, sgf2n):
bin_type = sgf2n
@classmethod
def compose(cls, bits):
bits = list(bits)
if len(bits) > cls.n_bits:
raise CompilerError('Too many bits')
res = cls()
res.bits = bits + [0] * (cls.n_bits - len(bits))
gmovs(res, sum(b << i for i,b in enumerate(bits)))
return res
def load_other(self, other):
if isinstance(other, sgf2nint):
gmovs(self, self.compose(other.bit_decompose(self.n_bits)))
elif isinstance(other, sgf2n):
gmovs(self, other)
else:
gaddm(self, sgf2n(0), cgf2n(other))
def force_bit_decompose(self, n_bits=None):
return sgf2n(self).bit_decompose(n_bits)
class sgf2nuint(sgf2nint):
def load_int(self, other):
if 0 <= other < 2**self.n_bits:
sgf2n.load_int(self, other)
else:
raise CompilerError('Invalid unsigned %d-bit integer: %d' % \
(self.n_bits, other))
def fill_bit(self):
return 0
@staticmethod
def prep_comparison(a, b):
pass
class sgf2nuint32(sgf2nuint):
n_bits = 32
class sgf2nint32(sgf2nint):
n_bits = 32
def get_sgf2nint(n):
class sgf2nint_spec(sgf2nint):
n_bits = n
return sgf2nint_spec
def get_sgf2nuint(n):
class sgf2nuint_spec(sgf2nint):
n_bits = n
return sgf2nuint_spec
class sgf2nfloat(sgf2n):
@classmethod
def set_precision(cls, vlen, plen):
cls.vlen = vlen
cls.plen = plen
class v_type(sgf2nuint):
n_bits = 2 * vlen + 1
class p_type(sgf2nint):
n_bits = plen
class pdiff_type(sgf2nuint):
n_bits = plen
cls.v_type = v_type
cls.p_type = p_type
cls.pdiff_type = pdiff_type
def __init__(self, val, p=None, z=None, s=None):
super(sgf2nfloat, self).__init__()
if p is None and type(val) == sgf2n:
bits = val.bit_decompose(self.vlen + self.plen + 1)
self.v = self.v_type.compose(bits[:self.vlen])
self.p = self.p_type.compose(bits[self.vlen:-1])
self.s = bits[-1]
self.z = util.tree_reduce(operator.mul, (1 - b for b in self.v.bits))
else:
if p is None:
v, p, z, s = sfloat.convert_float(val, self.vlen, self.plen)
p += self.vlen - 1
v_bits = util.bit_decompose(v, self.vlen)
p_bits = util.bit_decompose(p, self.plen)
self.v = self.v_type.compose(v_bits)
self.p = self.p_type.compose(p_bits)
self.z = z
self.s = s
else:
self.v, self.p, self.z, self.s = val, p, z, s
v_bits = val.bit_decompose()[:self.vlen]
p_bits = p.bit_decompose()[:self.plen]
gmovs(self, util.bit_compose(v_bits + p_bits + [self.s]))
def add(self, other):
a = self.p < other.p
b = self.p == other.p
c = self.v < other.v
other_dominates = (b.if_else(c, a))
pmax, pmin = a.cond_swap(self.p, other.p, self.p_type)
vmax, vmin = other_dominates.cond_swap(self.v, other.v, self.v_type)
s3 = self.s ^ other.s
pdiff = self.pdiff_type(pmax - pmin)
d = self.vlen < pdiff
pow_delta = util.pow2(d.if_else(0, pdiff).bit_decompose(util.log2(self.vlen)))
v3 = vmax
v4 = self.v_type(sgf2n(vmax) * pow_delta) + self.v_type(s3.if_else(-vmin, vmin))
v = self.v_type(sgf2n(d.if_else(v3, v4) << self.vlen) / pow_delta)
v >>= self.vlen - 1
h = floatingpoint.PreOR(v.bits[self.vlen+1::-1])
tmp = sum(util.if_else(b, 0, 1 << i) for i,b in enumerate(h))
pow_p0 = 1 + self.v_type(tmp)
v = (v * pow_p0) >> 2
p = pmax - sum(self.p_type.compose([1 - b]) for b in h) + 1
v = self.z.if_else(other.v, other.z.if_else(self.v, v))
z = v == 0
p = z.if_else(0, self.z.if_else(other.p, other.z.if_else(self.p, p)))
s = other_dominates.if_else(other.s, self.s)
s = self.z.if_else(other.s, other.z.if_else(self.s, s))
return sgf2nfloat(v, p, z, s)
def mul(self, other):
v = (self.v * other.v) >> (self.vlen - 1)
b = v.bits[self.vlen]
v = b.if_else(v >> 1, v)
p = self.p + other.p + self.p_type.compose([b])
s = self.s + other.s
z = util.or_op(self.z, other.z)
return sgf2nfloat(v, p, z, s)
sgf2nfloat.set_precision(24, 8)
def parse_type(other, k=None, f=None):
if isinstance(other, cfix.scalars):
return cfix(other, k=k, f=f)
elif isinstance(other, cint):
tmp = cfix()
tmp.load_int(other)
return tmp
elif isinstance(other, sint):
tmp = sfix()
tmp.load_int(other)
return tmp
elif isinstance(other, sfloat):
tmp = sfix(other)
return tmp
else:
return other
class cfix(_number, _structure):
__slots__ = ['value', 'f', 'k', 'size']
reg_type = 'c'
scalars = (int, float, regint)
@classmethod
def set_precision(cls, f, k = None):
cls.f = f
if k is None:
cls.k = 2 * f
else:
cls.k = k
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
res = []
res.append(cint.load_mem(address))
return cfix(*res)
@vectorized_classmethod
def read_from_socket(cls, client_id, n=1):
cint_input = cint.read_from_socket(client_id, n)
if n == 1:
return cfix(cint_inputs)
else:
return list(map(cfix, cint_inputs))
@vectorize
def write_to_socket(self, client_id, message_type=ClientMessageType.NoType):
writesocketc(client_id, message_type, cint(self.v))
@vectorized_classmethod
def write_to_socket(self, client_id, values, message_type=ClientMessageType.NoType):
def cfix_to_cint(fix_val):
return cint(fix_val.v)
cint_values = list(map(cfix_to_cint, values))
writesocketc(client_id, message_type, *cint_values)
@staticmethod
def malloc(size):
return program.malloc(size, cint)
@staticmethod
def n_elements():
return 1
@vectorize_init
def __init__(self, v=None, k=None, f=None, size=None):
f = f or self.f
k = k or self.k
self.f = f
self.k = k
self.size = get_global_vector_size()
if isinstance(v, cint):
self.v = cint(v,size=self.size)
elif isinstance(v, cfix.scalars):
v = v * (2 ** f)
try:
v = int(round(v))
except TypeError:
pass
self.v = cint(v, size=self.size)
elif isinstance(v, cfix):
self.v = v.v
elif isinstance(v, MemValue):
self.v = v
elif v is None:
self.v = cint(0)
else:
raise CompilerError('cannot initialize cfix with %s' % v)
@vectorize
def load_int(self, v):
self.v = cint(v) * (2 ** self.f)
@classmethod
def conv(cls, other):
if isinstance(other, cls):
return other
else:
try:
res = cfix()
res.load_int(other)
return res
except (TypeError, CompilerError):
pass
return cls(other)
def store_in_mem(self, address):
self.v.store_in_mem(address)
def sizeof(self):
return self.size * 4
@vectorize
def add(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(self.v + other.v)
else:
return NotImplemented
@vectorize
def mul(self, other):
other = parse_type(other)
if isinstance(other, cfix):
assert self.f == other.f
sgn = cint(1 - 2 * (self.v * other.v < 0))
absolute = self.v * other.v * sgn
val = sgn * (absolute >> self.f)
return cfix(val)
elif isinstance(other, sfix):
return NotImplemented
else:
raise CompilerError('Invalid type %s for cfix.__mul__' % type(other))
@vectorize
def __sub__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(self.v - other.v)
elif isinstance(other, sfix):
return sfix(self.v - other.v)
else:
raise NotImplementedError
@vectorize
def __neg__(self):
return cfix(-self.v)
def __rsub__(self, other):
return -self + other
@vectorize
def __eq__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v == other.v
elif isinstance(other, sfix):
return other.v.equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __lt__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v < other.v
elif isinstance(other, sfix):
if(self.k != other.k or self.f != other.f):
raise TypeError('Incompatible fixed point types in comparison')
return other.v.greater_than(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __le__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v <= other.v
elif isinstance(other, sfix):
return other.v.greater_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __gt__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v > other.v
elif isinstance(other, sfix):
return other.v.less_than(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __ge__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v >= other.v
elif isinstance(other, sfix):
return other.v.less_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __ne__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return self.v != other.v
elif isinstance(other, sfix):
return other.v.not_equal(self.v, self.k, other.kappa)
else:
raise NotImplementedError
@vectorize
def __truediv__(self, other):
other = parse_type(other)
if isinstance(other, cfix):
return cfix(library.cint_cint_division(self.v, other.v, self.k, self.f))
elif isinstance(other, sfix):
return sfix(library.FPDiv(self.v, other.v, self.k, self.f,
other.kappa, nearest=sfix.round_nearest))
else:
raise TypeError('Incompatible fixed point types in division')
def print_plain(self):
if self.k > 64:
raise CompilerError('Printing of fixed-point numbers not ' +
'implemented for more than 64-bit precision')
tmp = regint()
convmodp(tmp, self.v, bitlength=self.k)
sign = cint(tmp < 0)
abs_v = sign.if_else(-self.v, self.v)
print_float_plain(cint(abs_v), cint(-self.f), \
cint(0), cint(sign))
class _single(_number, _structure):
__slots__ = ['v']
kappa = 40
round_nearest = False
@property
@classmethod
def reg_type(cls):
return cls.int_type.reg_type
@classmethod
def receive_from_client(cls, n, client_id, message_type=ClientMessageType.NoType):
sint_inputs = cls.int_type.receive_from_client(n, client_id, ClientMessageType.TripleShares)
return list(map(cls, sint_inputs))
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
return cls._new(cls.int_type.load_mem(address))
@classmethod
@read_mem_value
def conv(cls, other):
if isinstance(other, cls):
return other
else:
try:
return cls.from_sint(other)
except (TypeError, CompilerError):
pass
return cls(other)
@classmethod
def coerce(cls, other):
return cls.conv(other)
@classmethod
def malloc(cls, size):
return program.malloc(size, cls.int_type)
@staticmethod
def n_elements():
return 1
@classmethod
def dot_product(cls, x, y, res_params=None):
return cls.unreduced_dot_product(x, y, res_params).reduce_after_mul()
@classmethod
def unreduced_dot_product(cls, x, y, res_params=None):
dp = cls.int_type.dot_product([xx.pre_mul() for xx in x],
[yy.pre_mul() for yy in y])
return x[0].unreduced(dp, y[0], res_params, len(x))
@classmethod
def row_matrix_mul(cls, row, matrix, res_params=None):
int_matrix = [y.get_vector().pre_mul() for y in matrix]
col = cls.int_type.row_matrix_mul([x.pre_mul() for x in row],
int_matrix)
res = row[0].unreduced(col, matrix[0][0], res_params,
len(row)).reduce_after_mul()
return res
@classmethod
def matrix_mul(cls, A, B, n, res_params=None):
AA = A.pre_mul()
BB = B.pre_mul()
CC = cls.int_type.matrix_mul(AA, BB, n)
res = A.unreduced(CC, B, res_params, n).reduce_after_mul()
return res
def store_in_mem(self, address):
self.v.store_in_mem(address)
@property
def size(self):
return self.v.size
def sizeof(self):
return self.size
def __len__(self):
return len(self.v)
@vectorize
def __sub__(self, other):
other = self.coerce(other)
return self + (-other)
def __rsub__(self, other):
return -self + other
@vectorize
def __eq__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __le__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.less_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __lt__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.less_than(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __ge__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.greater_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __gt__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.greater_than(other.v, self.k, self.kappa)
else:
raise NotImplementedError
@vectorize
def __ne__(self, other):
other = self.coerce(other)
if isinstance(other, (cfix, _single)):
return self.v.not_equal(other.v, self.k, self.kappa)
else:
raise NotImplementedError
class _fix(_single):
__slots__ = ['v', 'f', 'k', 'size']
@classmethod
def set_precision(cls, f, k = None):
cls.f = f
if k is None:
cls.k = 2 * f
else:
if k < f:
raise CompilerError('bit length cannot be less than precision')
cls.k = k
@classmethod
def coerce(cls, other):
if isinstance(other, (_fix, cls.clear_type)):
return other
else:
return cls.conv(other)
@classmethod
def from_sint(cls, other, k=None, f=None):
res = cls()
res.f = f or cls.f
res.k = k or cls.k
res.load_int(cls.int_type.conv(other))
return res
@classmethod
def _new(cls, other, k=None, f=None):
res = cls(other)
res.k = k or cls.k
res.f = f or cls.f
return res
@vectorize_init
def __init__(self, _v=None, size=None):
self.size = get_global_vector_size()
f = self.f
k = self.k
# for external initialization use load_int.
if _v is None:
self.v = self.int_type(0)
elif isinstance(_v, self.int_type):
self.v = _v
self.size = _v.size
elif isinstance(_v, cfix.scalars):
self.v = self.int_type(int(round(_v * (2 ** f))), size=self.size)
elif isinstance(_v, self.float_type):
p = (f + _v.p)
b = (p.greater_equal(0, _v.vlen))
a = b*(_v.v << (p)) + (1-b)*(_v.v >> (-p))
self.v = (1-2*_v.s)*a
elif isinstance(_v, type(self)):
self.v = _v.v
elif isinstance(_v, (MemValue, MemFix)):
#this is a memvalue object
self.v = type(self)(_v.read()).v
else:
raise CompilerError('cannot convert %s to sfix' % _v)
if not isinstance(self.v, self.int_type):
raise CompilerError('sfix conversion failure: %s/%s' % (_v, self.v))
@vectorize
def load_int(self, v):
self.v = self.int_type(v) << self.f
def __getitem__(self, index):
return self._new(self.v[index])
@vectorize
def add(self, other):
other = self.coerce(other)
if isinstance(other, (_fix, cfix)):
return self._new(self.v + other.v, k=self.k, f=self.f)
elif isinstance(other, cfix.scalars):
tmp = cfix(other, k=self.k, f=self.f)
return self + tmp
else:
return NotImplemented
@vectorize
def mul(self, other):
if isinstance(other, (sint, cint, regint, int)):
return self._new(self.v * other, k=self.k, f=self.f)
elif isinstance(other, float):
if int(other) == other:
return self.mul(int(other))
v = int(round(other * 2 ** self.f))
if v == 0:
return 0
f = self.f
while v % 2 == 0:
f -= 1
v //= 2
k = len(bin(abs(v))) - 1
other = self.multipliable(v, k, f)
other = self.coerce(other)
if isinstance(other, (_fix, self.clear_type)):
val = self.v.TruncMul(other.v, self.k + other.k, other.f,
self.kappa,
self.round_nearest)
if self.size >= other.size:
return self._new(val, k=self.k, f=self.f)
else:
return self.vec._new(val, k=self.k, f=self.f)
elif isinstance(other, cfix.scalars):
scalar_fix = cfix(other)
return self * scalar_fix
else:
return NotImplemented
@vectorize
def __neg__(self):
return type(self)(-self.v)
@vectorize
def __truediv__(self, other):
other = self.coerce(other)
if isinstance(other, _fix):
return type(self)(library.FPDiv(self.v, other.v, self.k, self.f,
self.kappa,
nearest=self.round_nearest))
elif isinstance(other, cfix):
return type(self)(library.sint_cint_division(self.v, other.v, self.k, self.f, self.kappa))
else:
raise TypeError('Incompatible fixed point types in division')
@vectorize
def __rtruediv__(self, other):
return self.coerce(other) / self
@vectorize
def compute_reciprocal(self):
return type(self)(library.FPDiv(cint(2) ** self.f, self.v, self.k, self.f, self.kappa, True))
def reveal(self):
val = self.v.reveal()
res = self.clear_type(val)
res.f = self.f
res.k = self.k
return res
class sfix(_fix):
int_type = sint
clear_type = cfix
@vectorized_classmethod
def get_input_from(cls, player):
v = cls.int_type()
inputmixed('fix', v, cls.f, player)
return cls._new(v)
@vectorized_classmethod
def get_random(cls, lower, upper):
log_range = int(math.log(upper - lower, 2))
n_bits = log_range + cls.f
average = lower + 0.5 * (upper - lower)
lower = average - 0.5 * 2 ** log_range
return cls._new(cls.int_type.get_random_int(n_bits)) + lower
def coerce(self, other):
return parse_type(other, k=self.k, f=self.f)
def mul_no_reduce(self, other, res_params=None):
assert self.f == other.f
return self.unreduced(self.v * other.v)
def pre_mul(self):
return self.v
def unreduced(self, v, other=None, res_params=None, n_summands=1):
return unreduced_sfix(v, self.k * 2, self.f, self.kappa)
@staticmethod
def multipliable(v, k, f):
return cfix(cint.conv(v), k, f)
class unreduced_sfix(_single):
int_type = sint
@classmethod
def _new(cls, v):
return cls(v, 2 * sfix.k, sfix.f, sfix.kappa)
def __init__(self, v, k, m, kappa):
self.v = v
self.k = k
self.m = m
self.kappa = kappa
def __add__(self, other):
if other is 0:
return self
assert self.k == other.k
assert self.m == other.m
assert self.kappa == other.kappa
return unreduced_sfix(self.v + other.v, self.k, self.m, self.kappa)
__radd__ = __add__
@vectorize
def reduce_after_mul(self):
return sfix(sfix.int_type.round(self.v, self.k, self.m, self.kappa,
nearest=sfix.round_nearest,
signed=True))
sfix.unreduced_type = unreduced_sfix
# this is for 20 bit decimal precision
# with 40 bitlength of entire number
# these constants have been chosen for multiplications to fit in 128 bit prime field
# (precision n1) 41 + (precision n2) 41 + (stat_sec) 40 = 82 + 40 = 122 <= 128
# with statistical security of 40
fixed_lower = 20
fixed_upper = 40
sfix.set_precision(fixed_lower, fixed_upper)
cfix.set_precision(fixed_lower, fixed_upper)
class squant(_single):
__slots__ = ['params']
int_type = sint
clamp = True
@classmethod
def set_params(cls, S, Z=0, k=8):
cls.params = squant_params(S, Z, k)
@classmethod
def from_sint(cls, other):
raise CompilerError('sint to squant conversion not implemented')
@classmethod
def _new(cls, value, params=None):
res = cls(params=params)
res.v = value
return res
@read_mem_value
def __init__(self, value=None, params=None):
if params is not None:
self.params = params
if value is None:
# need to set v manually
pass
elif isinstance(value, cfix.scalars):
set_global_vector_size(1)
q = util.round_to_int(value / self.S + self.Z)
if util.is_constant(q) and (q < 0 or q >= 2**self.k):
raise CompilerError('%f not quantizable' % value)
self.v = self.int_type(q)
reset_global_vector_size()
elif isinstance(value, squant) and value.params == self.params:
self.v = value.v
else:
raise CompilerError('cannot convert %s to squant' % value)
def __getitem__(self, index):
return type(self)._new(self.v[index], self.params)
def get_params(self):
return self.params
@property
def S(self):
return self.params.S
@property
def Z(self):
return self.params.Z
@property
def k(self):
return self.params.k
def coerce(self, other):
other = self.conv(other)
return self._new(util.expand(other.v, self.size), other.params)
@vectorize
def add(self, other):
other = self.coerce(other)
assert self.get_params() == other.get_params()
return self._new(self.v + other.v - util.expand(self.Z, self.v.size))
def mul(self, other, res_params=None):
return self.mul_no_reduce(other, res_params).reduce_after_mul()
def mul_no_reduce(self, other, res_params=None):
if isinstance(other, (sint, cint, regint)):
return self._new(other * (self.v - self.Z) + self.Z,
params=self.get_params())
other = self.coerce(other)
tmp = (self.v - self.Z) * (other.v - other.Z)
return _unreduced_squant(tmp, (self.get_params(), other.get_params()),
res_params=res_params)
def pre_mul(self):
return self.v - util.expand(self.Z, self.v.size)
def unreduced(self, v, other, res_params=None, n_summands=1):
return _unreduced_squant(v, (self.get_params(), other.get_params()),
res_params, n_summands)
@vectorize
def for_mux(self, other):
other = self.coerce(other)
assert self.params == other.params
f = lambda x: self._new(x, self.params)
return f, self.v, other.v
@vectorize
def __neg__(self):
return self._new(-self.v + 2 * util.expand(self.Z, self.v.size))
class _unreduced_squant(object):
def __init__(self, v, params, res_params=None, n_summands=1):
self.v = v
self.params = params
self.n_summands = n_summands
self.res_params = res_params or params[0]
def __add__(self, other):
if other is 0:
return self
assert self.params == other.params
assert self.res_params == other.res_params
return _unreduced_squant(self.v + other.v, self.params, self.res_params,
self.n_summands + other.n_summands)
__radd__ = __add__
def reduce_after_mul(self):
return squant_params.conv(self.res_params).reduce(self)
class squant_params(object):
max_n_summands = 2048
@staticmethod
def conv(other):
if isinstance(other, squant_params):
return other
else:
return squant_params(*other)
def __init__(self, S, Z=0, k=8):
try:
self.S = float(S)
except:
self.S = S
self.Z = MemValue.if_necessary(Z)
self.k = k
self._store = {}
if program.options.ring:
# cheaper probabilistic truncation
self.max_length = int(program.options.ring) - 1
else:
# safe choice for secret shift
self.max_length = 71
def __iter__(self):
yield self.S
yield self.Z
yield self.k
def is_constant(self):
return util.is_constant_float(self.S) and util.is_constant(self.Z)
def get(self, input_params, n_summands):
p = input_params
M = p[0].S * p[1].S / self.S
logM = util.log2(M)
n_shift = self.max_length - p[0].k - p[1].k - util.log2(n_summands)
if util.is_constant_float(M):
n_shift -= logM
int_mult = int(round(M * 2 ** (n_shift)))
else:
int_mult = MemValue(M.v << (n_shift + M.p))
shifted_Z = MemValue.if_necessary(self.Z << n_shift)
return n_shift, int_mult, shifted_Z
def precompute(self, *input_params):
self._store[input_params] = self.get(input_params, self.max_n_summands)
def get_stored(self, unreduced):
assert unreduced.n_summands <= self.max_n_summands
return self._store[unreduced.params]
def reduce(self, unreduced):
ps = (self,) + unreduced.params
if reduce(operator.and_, (p.is_constant() for p in ps)):
n_shift, int_mult, shifted_Z = self.get(unreduced.params,
unreduced.n_summands)
else:
n_shift, int_mult, shifted_Z = self.get_stored(unreduced)
size = unreduced.v.size
n_shift = util.expand(n_shift, size)
shifted_Z = util.expand(shifted_Z, size)
int_mult = util.expand(int_mult, size)
tmp = unreduced.v * int_mult + shifted_Z
shifted = tmp.round(self.max_length, n_shift,
kappa=squant.kappa, nearest=squant.round_nearest,
signed=True)
if squant.clamp:
length = max(self.k, self.max_length - n_shift) + 1
top = (1 << self.k) - 1
over = shifted.greater_than(top, length, squant.kappa)
under = shifted.less_than(0, length, squant.kappa)
shifted = over.if_else(top, shifted)
shifted = under.if_else(0, shifted)
return squant._new(shifted, params=self)
class sfloat(_number, _structure):
__slots__ = ['v', 'p', 'z', 's', 'size']
# single precision
vlen = 24
plen = 8
kappa = 40
round_nearest = False
@staticmethod
def n_elements():
return 4
@classmethod
def malloc(cls, size):
return program.malloc(size * cls.n_elements(), sint)
@classmethod
def is_address_tuple(cls, address):
if isinstance(address, (list, tuple)):
assert(len(address) == cls.n_elements())
return True
return False
@vectorized_classmethod
def load_mem(cls, address, mem_type=None):
size = get_global_vector_size()
if cls.is_address_tuple(address):
return sfloat(*(sint.load_mem(a, size=size) for a in address))
res = []
for i in range(4):
res.append(sint.load_mem(address + i * size, size=size))
return sfloat(*res)
@classmethod
def set_error(cls, error):
# incompatible with loops
#cls.error += error - cls.error * error
cls.error = error
pass
@classmethod
def conv(cls, other):
if isinstance(other, cls):
return other
else:
return cls(other)
@classmethod
def coerce(cls, other):
return cls.conv(other)
@staticmethod
def convert_float(v, vlen, plen):
if v < 0:
s = 1
else:
s = 0
if v == 0:
v = 0
p = 0
z = 1
else:
p = int(math.floor(math.log(abs(v), 2))) - vlen + 1
vv = v
v = int(round(abs(v) * 2 ** (-p)))
if v == 2 ** vlen:
p += 1
v //= 2
z = 0
if p < -2 ** (plen - 1):
print('Warning: %e truncated to zero' % vv)
v, p, z = 0, 0, 1
if p >= 2 ** (plen - 1):
raise CompilerError('Cannot convert %s to float ' \
'with %d exponent bits' % (vv, plen))
return v, p, z, s
@vectorized_classmethod
def get_input_from(cls, player):
v = sint()
p = sint()
z = sint()
s = sint()
inputmixed('float', v, p, z, s, cls.vlen, player)
return cls(v, p, z, s)
@vectorize_init
@read_mem_value
def __init__(self, v, p=None, z=None, s=None, size=None):
self.size = get_global_vector_size()
if p is None:
if isinstance(v, sfloat):
p = v.p
z = v.z
s = v.s
v = v.v
elif isinstance(v, sfix):
f = v.f
v, p, z, s = floatingpoint.Int2FL(v.v, v.k,
self.vlen, self.kappa)
p = p - f
elif util.is_constant_float(v):
v, p, z, s = self.convert_float(v, self.vlen, self.plen)
else:
v, p, z, s = floatingpoint.Int2FL(sint.conv(v),
program.bit_length,
self.vlen, self.kappa)
if isinstance(v, int):
if not ((v >= 2**(self.vlen-1) and v < 2**(self.vlen)) or v == 0):
raise CompilerError('Floating point number malformed: significand')
self.v = library.load_int_to_secret(v)
else:
self.v = v
if isinstance(p, int):
if not (p >= -2**(self.plen - 1) and p < 2**(self.plen - 1)):
raise CompilerError('Floating point number malformed: exponent %d not unsigned %d-bit integer' % (p, self.plen))
self.p = library.load_int_to_secret(p)
else:
self.p = p
if isinstance(z, int):
if not (z == 0 or z == 1):
raise CompilerError('Floating point number malformed: zero bit')
self.z = sint()
ldsi(self.z, z)
else:
self.z = z
if isinstance(s, int):
if not (s == 0 or s == 1):
raise CompilerError('Floating point number malformed: sign')
self.s = sint()
ldsi(self.s, s)
else:
self.s = s
def __getitem__(self, index):
return sfloat(*(x[index] for x in self))
def __iter__(self):
yield self.v
yield self.p
yield self.z
yield self.s
def store_in_mem(self, address):
if self.is_address_tuple(address):
for a, x in zip(address, self):
x.store_in_mem(a)
return
for i,x in enumerate((self.v, self.p, self.z, self.s)):
x.store_in_mem(address + i * self.size)
def sizeof(self):
return self.size * self.n_elements()
@vectorize
def add(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
a,c,d,e = [sint() for i in range(4)]
t = sint()
t2 = sint()
v1 = self.v
v2 = other.v
p1 = self.p
p2 = other.p
s1 = self.s
s2 = other.s
z1 = self.z
z2 = other.z
a = p1.less_than(p2, self.plen, self.kappa)
b = floatingpoint.EQZ(p1 - p2, self.plen, self.kappa)
c = v1.less_than(v2, self.vlen, self.kappa)
ap1 = a*p1
ap2 = a*p2
aneg = 1 - a
bneg = 1 - b
cneg = 1 - c
av1 = a*v1
av2 = a*v2
cv1 = c*v1
cv2 = c*v2
pmax = ap2 + p1 - ap1
pmin = p2 - ap2 + ap1
vmax = bneg*(av2 + v1 - av1) + b*(cv2 + v1 - cv1)
vmin = bneg*(av1 + v2 - av2) + b*(cv1 + v2 - cv2)
s3 = s1 + s2 - 2 * s1 * s2
comparison.LTZ(d, self.vlen + pmin - pmax + sfloat.round_nearest,
self.plen, self.kappa)
pow_delta = floatingpoint.Pow2((1 - d) * (pmax - pmin),
self.vlen + 1 + sfloat.round_nearest,
self.kappa)
# deviate from paper for more precision
#v3 = 2 * (vmax - s3) + 1
v3 = vmax
v4 = vmax * pow_delta + (1 - 2 * s3) * vmin
to_trunc = (d * v3 + (1 - d) * v4)
if program.options.ring:
to_trunc <<= 1 + sfloat.round_nearest
v = floatingpoint.TruncInRing(to_trunc,
2 * (self.vlen + 1 +
sfloat.round_nearest),
pow_delta)
else:
to_trunc *= two_power(self.vlen + sfloat.round_nearest)
v = to_trunc * floatingpoint.Inv(pow_delta)
comparison.Trunc(t, v, 2 * self.vlen + 1 + sfloat.round_nearest,
self.vlen - 1, self.kappa, False)
v = t
u = floatingpoint.BitDec(v, self.vlen + 2 + sfloat.round_nearest,
self.vlen + 2 + sfloat.round_nearest, self.kappa,
list(range(1 + sfloat.round_nearest,
self.vlen + 2 + sfloat.round_nearest)))
# using u[0] doesn't seem necessary
h = floatingpoint.PreOR(u[:sfloat.round_nearest:-1], self.kappa)
p0 = self.vlen + 1 - sum(h)
pow_p0 = 1 + sum([two_power(i) * (1 - h[i]) for i in range(len(h))])
if self.round_nearest:
t2, overflow = \
floatingpoint.TruncRoundNearestAdjustOverflow(pow_p0 * v,
self.vlen + 3,
self.vlen,
self.kappa)
p0 = p0 - overflow
else:
comparison.Trunc(t2, pow_p0 * v, self.vlen + 2, 2, self.kappa, False)
v = t2
p = pmax - p0 + 1
zz = self.z*other.z
zprod = 1 - self.z - other.z + zz
v = zprod*t2 + self.z*v2 + other.z*v1
z = floatingpoint.EQZ(v, self.vlen, self.kappa)
p = (zprod*p + self.z*p2 + other.z*p1)*(1 - z)
s = (1 - b)*(a*other.s + aneg*self.s) + b*(c*other.s + cneg*self.s)
s = zprod*s + (other.z - zz)*self.s + (self.z - zz)*other.s
return sfloat(v, p, z, s)
else:
return NotImplemented
@vectorize_max
def mul(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
v1 = sint()
v2 = sint()
b = sint()
c2expl = cint()
comparison.ld2i(c2expl, self.vlen)
if sfloat.round_nearest:
v1 = comparison.TruncRoundNearest(self.v*other.v, 2*self.vlen,
self.vlen-1, self.kappa)
else:
comparison.Trunc(v1, self.v*other.v, 2*self.vlen, self.vlen-1, self.kappa, False)
t = v1 - c2expl
comparison.LTZ(b, t, self.vlen+1, self.kappa)
comparison.Trunc(v2, b*v1 + v1, self.vlen+1, 1, self.kappa, False)
z1, z2, s1, s2, p1, p2 = (x.expand_to_vector() for x in \
(self.z, other.z, self.s, other.s,
self.p, other.p))
z = z1 + z2 - self.z*other.z
s = s1 + s2 - self.s*other.s*2
p = (p1 + p2 - b + self.vlen)*(1 - z)
return sfloat(v2, p, z, s)
else:
return NotImplemented
def __sub__(self, other):
return self + -other
def __rsub__(self, other):
return -self + other
def __truediv__(self, other):
other = self.conv(other)
v = floatingpoint.SDiv(self.v, other.v + other.z * (2**self.vlen - 1),
self.vlen, self.kappa, self.round_nearest)
b = v.less_than(two_power(self.vlen-1), self.vlen + 1, self.kappa)
overflow = v.greater_equal(two_power(self.vlen), self.vlen + 1, self.kappa)
underflow = v.less_than(two_power(self.vlen-2), self.vlen + 1, self.kappa)
v = (v + b * v) * (1 - overflow) * (1 - underflow) + \
overflow * (2**self.vlen - 1) + \
underflow * (2**(self.vlen-1)) * (1 - self.z)
p = (1 - self.z) * (self.p - other.p - self.vlen - b + 1)
z = self.z
s = self.s + other.s - 2 * self.s * other.s
sfloat.set_error(other.z)
return sfloat(v, p, z, s)
def __rtruediv__(self, other):
return self.conv(other) / self
@vectorize
def __neg__(self):
return sfloat(self.v, self.p, self.z, (1 - self.s) * (1 - self.z))
@vectorize
def __lt__(self, other):
other = self.conv(other)
if isinstance(other, sfloat):
z1 = self.z
z2 = other.z
s1 = self.s
s2 = other.s
a = self.p.less_than(other.p, self.plen, self.kappa)
c = floatingpoint.EQZ(self.p - other.p, self.plen, self.kappa)
d = ((1 - 2*self.s)*self.v).less_than((1 - 2*other.s)*other.v, self.vlen + 1, self.kappa)
cd = c*d
ca = c*a
b1 = cd + a - ca
b2 = cd + 1 + ca - c - a
s12 = self.s*other.s
z12 = self.z*other.z
b = (z1 - z12)*(1 - s2) + (z2 - z12)*s1 + (1 + z12 - z1 - z2)*(s1 - s12 + (1 + s12 - s1 - s2)*b1 + s12*b2)
return b
else:
return NotImplemented
def __ge__(self, other):
return 1 - (self < other)
def __gt__(self, other):
return self.conv(other) < self
def __le__(self, other):
return self.conv(other) >= self
@vectorize
def __eq__(self, other):
other = self.conv(other)
both_zero = self.z * other.z
return floatingpoint.EQZ(self.v - other.v, self.vlen, self.kappa) * \
floatingpoint.EQZ(self.p - other.p, self.plen, self.kappa) * \
(1 - self.s - other.s + 2 * self.s * other.s) * \
(1 - both_zero) + both_zero
def __ne__(self, other):
return 1 - (self == other)
def log2(self):
up = self.v.greater_than(1 << (self.vlen - 1), self.vlen, self.kappa)
return self.p + self.vlen - 1 + up
def round_to_int(self):
direction = self.p.greater_equal(-self.vlen, self.plen, self.kappa)
right = self.v.right_shift(-self.p - 1, self.vlen + 1, self.kappa)
up = right.mod2m(1, self.vlen + 1, self.kappa)
right = right.right_shift(1, self.vlen + 1, self.kappa) + up
abs_value = direction * right
return self.s.if_else(-abs_value, abs_value)
def value(self):
return (1 - 2*self.s.value)*(1 - self.z.value)*self.v.value/float(2**self.p.value)
def reveal(self):
return cfloat(self.v.reveal(), self.p.reveal(), self.z.reveal(), self.s.reveal())
class cfloat(object):
__slots__ = ['v', 'p', 'z', 's']
def __init__(self, v, p, z, s):
self.v, self.p, self.z, self.s = [cint.conv(x) for x in (v, p, z, s)]
def print_float_plain(self):
print_float_plain(self.v, self.p, self.z, self.s)
sfix.float_type = sfloat
_types = {
'c': cint,
's': sint,
'sg': sgf2n,
'cg': cgf2n,
'ci': regint,
}
def _get_type(t):
if t in _types:
return _types[t]
else:
return t
class Array(object):
@classmethod
def create_from(cls, l):
if isinstance(l, cls):
return l
tmp = list(l)
res = cls(len(tmp), type(tmp[0]))
res.assign(tmp)
return res
def __init__(self, length, value_type, address=None, debug=None):
value_type = _get_type(value_type)
self.address = address
self.length = length
self.value_type = value_type
if address is None:
self.address = self._malloc()
self.address_cache = {}
self.debug = debug
def _malloc(self):
return self.value_type.malloc(self.length)
def delete(self):
if program:
program.free(self.address, self.value_type.reg_type)
def get_address(self, index):
key = str(index)
if isinstance(index, int) and self.length is not None:
index += self.length * (index < 0)
if index >= self.length or index < 0:
raise IndexError('index %s, length %s' % \
(str(index), str(self.length)))
if (program.curr_block, key) not in self.address_cache:
n = self.value_type.n_elements()
length = self.length
if n == 1:
length = 0
self.address_cache[program.curr_block, key] = \
util.untuplify([self.address + index + i * length \
for i in range(n)])
if self.debug:
library.print_ln_if(index >= self.length, 'OF:' + self.debug)
library.print_ln_if(self.address_cache[program.curr_block, key] >= program.allocated_mem[self.value_type.reg_type], 'AOF:' + self.debug)
return self.address_cache[program.curr_block, key]
def get_slice(self, index):
if index.stop is None and self.length is None:
raise CompilerError('Cannot slice array of unknown length')
return index.start or 0, index.stop or self.length, index.step or 1
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = self.get_slice(index)
res_length = (stop - start - 1) // step + 1
res = Array(res_length, self.value_type)
@library.for_range(res_length)
def f(i):
res[i] = self[start+i*step]
return res
return self._load(self.get_address(index))
def __setitem__(self, index, value):
if isinstance(index, slice):
start, stop, step = self.get_slice(index)
value = Array.create_from(value)
source_index = MemValue(0)
@library.for_range(start, stop, step)
def f(i):
self[i] = value[source_index]
source_index.iadd(1)
return
self._store(value, self.get_address(index))
def get_range(self, start, size):
return [self[start + i] for i in range(size)]
def set_range(self, start, values):
for i, value in enumerate(values):
self[start + i] = value
def _load(self, address):
return self.value_type.load_mem(address)
def _store(self, value, address):
self.value_type.conv(value).store_in_mem(address)
def __len__(self):
return self.length
def __iter__(self):
for i in range(self.length):
yield self[i]
def same_shape(self):
return Array(self.length, self.value_type)
def assign(self, other, base=0):
try:
other = other.get_vector()
except:
pass
try:
other.store_in_mem(self.get_address(base))
assert len(self) >= other.size + base
except AttributeError:
for i,j in enumerate(other):
self[i] = j
return self
def assign_all(self, value, use_threads=True, conv=True):
if conv:
value = self.value_type.conv(value)
mem_value = MemValue(value)
n_threads = 8 if use_threads and len(self) > 2**20 else 1
@library.for_range_multithread(n_threads, 1024, len(self))
def f(i):
self[i] = mem_value
return self
def get_vector(self, base=0, size=None):
size = size or self.length
return self.value_type.load_mem(self.get_address(base), size=size)
def get_mem_value(self, index):
return MemValue(self[index], self.get_address(index))
def input_from(self, player, budget=None):
self.assign(self.value_type.get_input_from(player, size=len(self)))
def __add__(self, other):
if other is 0:
return self
assert len(self) == len(other)
return self.get_vector() + other
def __sub__(self, other):
assert len(self) == len(other)
return self.get_vector() - other
def __mul__(self, value):
return self.get_vector() * value
def __pow__(self, value):
return self.get_vector() ** value
__radd__ = __add__
__rmul__ = __mul__
def shuffle(self):
@library.for_range(len(self))
def _(i):
j = regint.get_random(64) % (len(self) - i)
tmp = self[i]
self[i] = self[i + j]
self[i + j] = tmp
def reveal(self):
return Array.create_from(x.reveal() for x in self)
sint.dynamic_array = Array
sgf2n.dynamic_array = Array
class SubMultiArray(object):
def __init__(self, sizes, value_type, address, index, debug=None):
self.sizes = sizes
self.value_type = _get_type(value_type)
self.address = address + index * self.total_size()
self.sub_cache = {}
self.debug = debug
if debug:
library.print_ln_if(self.address + reduce(operator.mul, self.sizes) * self.value_type.n_elements() > program.allocated_mem[self.value_type.reg_type], 'AOF%d:' % len(self.sizes) + self.debug)
def __getitem__(self, index):
if util.is_constant(index) and index >= self.sizes[0]:
raise StopIteration
key = program.curr_block, str(index)
if key not in self.sub_cache:
if self.debug:
library.print_ln_if(index >= self.sizes[0], \
'OF%d:' % len(self.sizes) + self.debug)
if len(self.sizes) == 2:
self.sub_cache[key] = \
Array(self.sizes[1], self.value_type, \
self.address + index * self.sizes[1] *
self.value_type.n_elements(), \
debug=self.debug)
else:
self.sub_cache[key] = \
SubMultiArray(self.sizes[1:], self.value_type, \
self.address, index, debug=self.debug)
return self.sub_cache[key]
def __setitem__(self, index, other):
self[index].assign(other)
def __len__(self):
return self.sizes[0]
def assign_all(self, value):
@library.for_range(self.sizes[0])
def f(i):
self[i].assign_all(value)
return self
def total_size(self):
return reduce(operator.mul, self.sizes) * self.value_type.n_elements()
def get_vector(self, base=0, size=None):
assert self.value_type.n_elements() == 1
size = size or self.total_size()
return self.value_type.load_mem(self.address + base, size=size)
def assign_vector(self, vector, base=0):
assert self.value_type.n_elements() == 1
assert vector.size <= self.total_size()
vector.store_in_mem(self.address + base)
def assign(self, other):
if self.value_type.n_elements() > 1:
assert self.sizes == other.sizes
self.assign_vector(other.get_vector())
def same_shape(self):
return MultiArray(self.sizes, self.value_type)
def input_from(self, player, budget=None):
@library.for_range_opt(self.sizes[0], budget=budget)
def _(i):
self[i].input_from(player, budget=budget)
def schur(self, other):
assert self.sizes == other.sizes
if len(self.sizes) == 2:
res = Matrix(self.sizes[0], self.sizes[1], self.value_type)
else:
res = MultiArray(self.sizes, self.value_type)
res.assign_vector(self.get_vector() * other.get_vector())
return res
def __add__(self, other):
if other is 0:
return self
assert self.sizes == other.sizes
if len(self.sizes) == 2:
res = Matrix(self.sizes[0], self.sizes[1], self.value_type)
else:
res = MultiArray(self.sizes, self.value_type)
res.assign_vector(self.get_vector() + other.get_vector())
return res
__radd__ = __add__
def iadd(self, other):
assert self.sizes == other.sizes
self.assign_vector(self.get_vector() + other.get_vector())
def __mul__(self, other):
return self.mul(other)
def mul(self, other, res_params=None):
assert len(self.sizes) == 2
if isinstance(other, Array):
assert len(other) == self.sizes[1]
if self.value_type.n_elements() == 1:
matrix = Matrix(len(other), 1, other.value_type, \
address=other.address)
res = self * matrix
return Array(res.sizes[0], res.value_type, address=res.address)
else:
matrix = Matrix(len(other), 1, other.value_type)
for i, x in enumerate(other):
matrix[i][0] = x
res = self * matrix
return Array.create_from(x[0] for x in res)
elif isinstance(other, SubMultiArray):
assert len(other.sizes) == 2
assert other.sizes[0] == self.sizes[1]
if res_params is not None:
class t(self.value_type):
pass
t.params = res_params
else:
t = self.value_type
res_matrix = Matrix(self.sizes[0], other.sizes[1], t)
try:
if max(res_matrix.sizes) > 1000:
raise AttributeError()
A = self.get_vector()
B = other.get_vector()
res_matrix.assign_vector(
self.value_type.matrix_mul(A, B, self.sizes[1],
res_params))
except (AttributeError, AssertionError):
@library.for_range_opt(self.sizes[0])
def _(i):
try:
res_matrix[i] = self.value_type.row_matrix_mul(
self[i], other, res_params)
except AttributeError:
@library.for_range(other.sizes[1])
def _(j):
res_matrix[i][j] = 0
@library.for_range(self.sizes[1])
def _(k):
res_matrix[i][j] += self[i][k] * other[k][j]
return res_matrix
else:
raise NotImplementedError
def budget_mul(self, other, n_rows, row, n_columns, column, reduce=True,
res=None):
assert len(self.sizes) == 2
assert len(other.sizes) == 2
if res is None:
if reduce:
res_matrix = Matrix(n_rows, n_columns, self.value_type)
else:
res_matrix = Matrix(n_rows, n_columns, \
self.value_type.unreduced_type)
else:
res_matrix = res
@library.for_range_opt(n_rows)
def _(i):
@library.for_range_opt(n_columns)
def _(j):
col = column(other, j)
r = row(self, i)
if reduce:
res_matrix[i][j] = self.value_type.dot_product(r, col)
else:
entry = self.value_type.unreduced_dot_product(r, col)
res_matrix[i][j] = entry
return res_matrix
def plain_mul(self, other, res=None):
assert other.sizes[0] == self.sizes[1]
return self.budget_mul(other, self.sizes[0], lambda x, i: x[i], \
other.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))],
res=res)
def mul_trans(self, other):
assert other.sizes[1] == self.sizes[1]
return self.budget_mul(other, self.sizes[0], lambda x, i: x[i], \
other.sizes[0], lambda x, j: x[j])
def trans_mul(self, other, reduce=True, res=None):
assert other.sizes[0] == self.sizes[0]
return self.budget_mul(other, self.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))], \
other.sizes[1], \
lambda x, j: [x[k][j] for k in range(len(x))],
reduce=reduce, res=res)
def transpose(self):
assert len(self.sizes) == 2
res = Matrix(self.sizes[1], self.sizes[0], self.value_type)
@library.for_range_opt(self.sizes[1])
def _(i):
@library.for_range_opt(self.sizes[0])
def _(j):
res[i][j] = self[j][i]
return res
class MultiArray(SubMultiArray):
def __init__(self, sizes, value_type, debug=None, address=None):
if isinstance(address, Array):
self.array = address
else:
self.array = Array(reduce(operator.mul, sizes), \
value_type, address=address)
SubMultiArray.__init__(self, sizes, value_type, self.array.address, 0, \
debug=debug)
if len(sizes) < 2:
raise CompilerError('Use Array')
class Matrix(MultiArray):
def __init__(self, rows, columns, value_type, debug=None, address=None):
MultiArray.__init__(self, [rows, columns], value_type, debug=debug, \
address=address)
class VectorArray(object):
def __init__(self, length, value_type, vector_size, address=None):
self.array = Array(length * vector_size, value_type, address)
self.vector_size = vector_size
self.value_type = value_type
def __getitem__(self, index):
return self.value_type.load_mem(self.array.address + \
index * self.vector_size,
size=self.vector_size)
def __setitem__(self, index, value):
if value.size != self.vector_size:
raise CompilerError('vector size mismatch')
value.store_in_mem(self.array.address + index * self.vector_size)
class _mem(_number):
__add__ = lambda self,other: self.read() + other
__sub__ = lambda self,other: self.read() - other
__mul__ = lambda self,other: self.read() * other
__truediv__ = lambda self,other: self.read() / other
__mod__ = lambda self,other: self.read() % other
__pow__ = lambda self,other: self.read() ** other
__neg__ = lambda self,other: -self.read()
__lt__ = lambda self,other: self.read() < other
__gt__ = lambda self,other: self.read() > other
__le__ = lambda self,other: self.read() <= other
__ge__ = lambda self,other: self.read() >= other
__eq__ = lambda self,other: self.read() == other
__ne__ = lambda self,other: self.read() != other
__and__ = lambda self,other: self.read() & other
__xor__ = lambda self,other: self.read() ^ other
__or__ = lambda self,other: self.read() | other
__lshift__ = lambda self,other: self.read() << other
__rshift__ = lambda self,other: self.read() >> other
__radd__ = lambda self,other: other + self.read()
__rsub__ = lambda self,other: other - self.read()
__rmul__ = lambda self,other: other * self.read()
__rtruediv__ = lambda self,other: other / self.read()
__rmod__ = lambda self,other: other % self.read()
__rand__ = lambda self,other: other & self.read()
__rxor__ = lambda self,other: other ^ self.read()
__ror__ = lambda self,other: other | self.read()
__iadd__ = lambda self,other: self.write(self.read() + other)
__isub__ = lambda self,other: self.write(self.read() - other)
__imul__ = lambda self,other: self.write(self.read() * other)
__idiv__ = lambda self,other: self.write(self.read() / other)
__imod__ = lambda self,other: self.write(self.read() % other)
__ipow__ = lambda self,other: self.write(self.read() ** other)
__iand__ = lambda self,other: self.write(self.read() & other)
__ixor__ = lambda self,other: self.write(self.read() ^ other)
__ior__ = lambda self,other: self.write(self.read() | other)
__ilshift__ = lambda self,other: self.write(self.read() << other)
__irshift__ = lambda self,other: self.write(self.read() >> other)
iadd = __iadd__
isub = __isub__
imul = __imul__
idiv = __idiv__
imod = __imod__
ipow = __ipow__
iand = __iand__
ixor = __ixor__
ior = __ior__
ilshift = __ilshift__
irshift = __irshift__
store_in_mem = lambda self,address: self.read().store_in_mem(address)
class MemValue(_mem):
__slots__ = ['last_write_block', 'reg_type', 'register', 'address', 'deleted']
@classmethod
def if_necessary(cls, value):
if util.is_constant_float(value):
return value
else:
return cls(value)
def __init__(self, value, address=None):
self.last_write_block = None
if isinstance(value, int):
self.value_type = regint
value = regint(value)
elif isinstance(value, MemValue):
self.value_type = value.value_type
else:
self.value_type = type(value)
self.deleted = False
if address is None:
self.address = self.value_type.malloc(1)
self.write(value)
else:
self.address = address
def delete(self):
self.value_type.free(self.address)
self.deleted = True
def check(self):
if self.deleted:
raise CompilerError('MemValue deleted')
def read(self):
self.check()
if program.curr_block != self.last_write_block:
self.register = library.load_mem(self.address, self.value_type)
self.last_write_block = program.curr_block
return self.register
def write(self, value):
self.check()
if isinstance(value, MemValue):
self.register = value.read()
elif isinstance(value, int):
self.register = self.value_type(value)
else:
self.register = value
if not isinstance(self.register, self.value_type):
raise CompilerError('Mismatch in register type, cannot write \
%s to %s' % (type(self.register), self.value_type))
self.register.store_in_mem(self.address)
self.last_write_block = program.curr_block
return self
def reveal(self):
return self.read().reveal()
less_than = lambda self,other,bit_length=None,security=None: \
self.read().less_than(other,bit_length,security)
greater_than = lambda self,other,bit_length=None,security=None: \
self.read().greater_than(other,bit_length,security)
less_equal = lambda self,other,bit_length=None,security=None: \
self.read().less_equal(other,bit_length,security)
greater_equal = lambda self,other,bit_length=None,security=None: \
self.read().greater_equal(other,bit_length,security)
equal = lambda self,other,bit_length=None,security=None: \
self.read().equal(other,bit_length,security)
not_equal = lambda self,other,bit_length=None,security=None: \
self.read().not_equal(other,bit_length,security)
pow2 = lambda self,*args,**kwargs: self.read().pow2(*args, **kwargs)
mod2m = lambda self,*args,**kwargs: self.read().mod2m(*args, **kwargs)
right_shift = lambda self,*args,**kwargs: self.read().right_shift(*args, **kwargs)
bit_decompose = lambda self,*args,**kwargs: self.read().bit_decompose(*args, **kwargs)
if_else = lambda self,*args,**kwargs: self.read().if_else(*args, **kwargs)
expand_to_vector = lambda self,*args,**kwargs: \
self.read().expand_to_vector(*args, **kwargs)
def __repr__(self):
return 'MemValue(%s,%d)' % (self.value_type, self.address)
class MemFloat(_mem):
def __init__(self, *args):
value = sfloat(*args)
self.v = MemValue(value.v)
self.p = MemValue(value.p)
self.z = MemValue(value.z)
self.s = MemValue(value.s)
def write(self, *args):
value = sfloat(*args)
self.v.write(value.v)
self.p.write(value.p)
self.z.write(value.z)
self.s.write(value.s)
def read(self):
return sfloat(self.v, self.p, self.z, self.s)
class MemFix(_mem):
def __init__(self, *args):
arg_type = type(*args)
if arg_type == sfix:
value = sfix(*args)
elif arg_type == cfix:
value = cfix(*args)
else:
raise CompilerError('MemFix init argument error')
self.reg_type = value.v.reg_type
self.v = MemValue(value.v)
def write(self, *args):
value = sfix(*args)
self.v.write(value.v)
def reveal(self):
return cfix(self.v.reveal())
def read(self):
val = self.v.read()
if isinstance(val, sint):
return sfix(val)
else:
return cfix(val)
def getNamedTupleType(*names):
class NamedTuple(object):
class NamedTupleArray(object):
def __init__(self, size, t):
from . import types
self.arrays = [types.Array(size, t) for i in range(len(names))]
def __getitem__(self, index):
return NamedTuple(array[index] for array in self.arrays)
def __setitem__(self, index, item):
for array,value in zip(self.arrays, item):
array[index] = value
@classmethod
def get_array(cls, size, t):
return cls.NamedTupleArray(size, t)
def __init__(self, *args):
if len(args) == 1:
args = args[0]
for name, value in zip(names, args):
self.__dict__[name] = value
def __iter__(self):
for name in names:
yield self.__dict__[name]
def __add__(self, other):
return NamedTuple(i + j for i,j in zip(self, other))
def __sub__(self, other):
return NamedTuple(i - j for i,j in zip(self, other))
def __xor__(self, other):
return NamedTuple(i ^ j for i,j in zip(self, other))
def __mul__(self, other):
return NamedTuple(other * i for i in self)
__rmul__ = __mul__
__rxor__ = __xor__
def reveal(self):
return self.__type__(x.reveal() for x in self)
return NamedTuple
from . import library
| true | true |
f72692b82fed413b8a80f995369aec1ebc838715 | 668 | py | Python | onlineassessmentsystem/blog/migrations/0001_initial.py | nevilparmar11/SDP_Online_Assessment_System | 012a1ec7dfca2973a5e03b0f970394cfa674b61e | [
"MIT"
] | 2 | 2021-05-22T15:44:19.000Z | 2021-05-22T17:59:58.000Z | onlineassessmentsystem/blog/migrations/0001_initial.py | jwalit21/SDP_Online_Assessment_System | a778a0e0ae264fe74037a5f0b210d205ebc18d98 | [
"MIT"
] | 7 | 2021-01-18T06:06:38.000Z | 2021-03-03T15:09:17.000Z | onlineassessmentsystem/blog/migrations/0001_initial.py | jwalit21/SDP_Online_Assessment_System | a778a0e0ae264fe74037a5f0b210d205ebc18d98 | [
"MIT"
] | 2 | 2021-03-05T12:28:28.000Z | 2021-05-24T16:10:07.000Z | # Generated by Django 3.1.5 on 2021-01-09 16:06
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
('blogId', models.AutoField(primary_key=True, serialize=False)),
('title', models.CharField(default='DEFAULT-BLOG', max_length=50)),
('description', models.CharField(default='Default Blog description', max_length=1000)),
('attachmentPath', models.FileField(max_length=254, upload_to='blogs/')),
],
),
]
| 27.833333 | 103 | 0.58982 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
('blogId', models.AutoField(primary_key=True, serialize=False)),
('title', models.CharField(default='DEFAULT-BLOG', max_length=50)),
('description', models.CharField(default='Default Blog description', max_length=1000)),
('attachmentPath', models.FileField(max_length=254, upload_to='blogs/')),
],
),
]
| true | true |
f72693b15cffa1a04a5fc7222fdd4715cbead461 | 716 | py | Python | tests/test_mag_orms.py | nestauk/ai_research | 19fd193b098dc68706b945e959fad29c4bfed781 | [
"MIT"
] | 3 | 2020-02-24T19:25:39.000Z | 2021-06-29T10:38:29.000Z | tests/test_mag_orms.py | nestauk/ai_research | 19fd193b098dc68706b945e959fad29c4bfed781 | [
"MIT"
] | 19 | 2020-02-24T07:48:52.000Z | 2020-12-21T10:50:14.000Z | tests/test_mag_orms.py | nestauk/ai_research | 19fd193b098dc68706b945e959fad29c4bfed781 | [
"MIT"
] | null | null | null | import pytest
import unittest
import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from ai_research.mag.mag_orm import Base
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
class TestMag(unittest.TestCase):
"""Check that the MAG ORM works as expected"""
engine = create_engine(os.getenv("test_postgresdb"))
Session = sessionmaker(engine)
def setUp(self):
"""Create the temporary table"""
Base.metadata.create_all(self.engine)
def tearDown(self):
"""Drop the temporary table"""
Base.metadata.drop_all(self.engine)
def test_build(self):
pass
if __name__ == "__main__":
unittest.main()
| 22.375 | 56 | 0.710894 | import pytest
import unittest
import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from ai_research.mag.mag_orm import Base
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
class TestMag(unittest.TestCase):
engine = create_engine(os.getenv("test_postgresdb"))
Session = sessionmaker(engine)
def setUp(self):
Base.metadata.create_all(self.engine)
def tearDown(self):
Base.metadata.drop_all(self.engine)
def test_build(self):
pass
if __name__ == "__main__":
unittest.main()
| true | true |
f72693b16d34b944f5bb4a1349f76575267e7ffa | 1,136 | py | Python | examples/hacker_news/hacker_news/resources/s3_notebook_io_manager.py | kstennettlull/dagster | dd6f57e170ff03bf145f1dd1417e0b2c3156b1d6 | [
"Apache-2.0"
] | null | null | null | examples/hacker_news/hacker_news/resources/s3_notebook_io_manager.py | kstennettlull/dagster | dd6f57e170ff03bf145f1dd1417e0b2c3156b1d6 | [
"Apache-2.0"
] | null | null | null | examples/hacker_news/hacker_news/resources/s3_notebook_io_manager.py | kstennettlull/dagster | dd6f57e170ff03bf145f1dd1417e0b2c3156b1d6 | [
"Apache-2.0"
] | null | null | null | from dagstermill.io_managers import OutputNotebookIOManager
from dagster import io_manager
from .fixed_s3_pickle_io_manager import s3_client
class S3OutputNotebookIOManager(OutputNotebookIOManager):
"""Defines an IOManager that will store dagstermill output notebooks on s3"""
def _get_key(self, context) -> str:
return "notebooks/" + "_".join(context.get_run_scoped_output_identifier())
def load_input(self, context) -> bytes:
key = self._get_key(context.upstream_output)
bucket = context.resources.s3_bucket
context.log.info("loading from: s3_bucket[%s], s3_key[%s]", bucket, key)
return s3_client().get_object(Bucket=bucket, Key=key)["Body"].read()
def handle_output(self, context, obj: bytes):
key = self._get_key(context)
bucket = context.resources.s3_bucket
context.log.info("storing to: s3_bucket[%s], s3_key[%s]", bucket, key)
s3_client().put_object(Bucket=bucket, Key=key, Body=obj)
@io_manager(required_resource_keys={"s3_bucket"})
def s3_notebook_io_manager(_) -> OutputNotebookIOManager:
return S3OutputNotebookIOManager()
| 37.866667 | 82 | 0.727113 | from dagstermill.io_managers import OutputNotebookIOManager
from dagster import io_manager
from .fixed_s3_pickle_io_manager import s3_client
class S3OutputNotebookIOManager(OutputNotebookIOManager):
def _get_key(self, context) -> str:
return "notebooks/" + "_".join(context.get_run_scoped_output_identifier())
def load_input(self, context) -> bytes:
key = self._get_key(context.upstream_output)
bucket = context.resources.s3_bucket
context.log.info("loading from: s3_bucket[%s], s3_key[%s]", bucket, key)
return s3_client().get_object(Bucket=bucket, Key=key)["Body"].read()
def handle_output(self, context, obj: bytes):
key = self._get_key(context)
bucket = context.resources.s3_bucket
context.log.info("storing to: s3_bucket[%s], s3_key[%s]", bucket, key)
s3_client().put_object(Bucket=bucket, Key=key, Body=obj)
@io_manager(required_resource_keys={"s3_bucket"})
def s3_notebook_io_manager(_) -> OutputNotebookIOManager:
return S3OutputNotebookIOManager()
| true | true |
f72695448dd7c1288748bbad417bedf5678eb8a3 | 3,495 | py | Python | src/wpusher/vdesk.py | brenttaylor/WindowPusher | d6ecb9aa1ad69e954cba5632ee56fd6f6c1f8c06 | [
"BSD-3-Clause"
] | null | null | null | src/wpusher/vdesk.py | brenttaylor/WindowPusher | d6ecb9aa1ad69e954cba5632ee56fd6f6c1f8c06 | [
"BSD-3-Clause"
] | null | null | null | src/wpusher/vdesk.py | brenttaylor/WindowPusher | d6ecb9aa1ad69e954cba5632ee56fd6f6c1f8c06 | [
"BSD-3-Clause"
] | null | null | null | import user32
import win32con
import ctypes
import collections
class VirtualDesktopException(Exception):
pass
class NoForegroundWindow(VirtualDesktopException):
pass
class VirtualDesktop(object):
def __init__(self):
self.window = []
self.removed_windows = []
def remove_foreground_window(self):
foreground_window = user32.GetForegroundWindow()
if user32.IsWindowVisible(foreground_window):
self.removed_windows.append(foreground_window)
user32.ShowWindow(foreground_window, win32con.SW_HIDE)
return foreground_window
raise NoForegroundWindow("This Desktop is empty of windows.")
def add_window(self, window):
self.window.append(window)
def show(self):
self.removed_windows = []
for Window in self.window:
user32.ShowWindow(Window, win32con.SW_SHOW)
if len(self.window) > 0:
user32.SetForegroundWindow(self.window[-1])
def hide(self):
self.window = []
def enum_windows_proc(hWnd, lParam):
if not hWnd: return True
if not user32.IsWindowVisible(hWnd): return True
# Get Window Title
length = user32.SendMessage(hWnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buffer = ctypes.create_unicode_buffer(length + 1)
if not user32.SendMessage(hWnd, win32con.WM_GETTEXT, length + 1, ctypes.byref(buffer)):
return True
if buffer.value != "Program Manager":
if not (hWnd in self.removed_windows):
if hWnd == user32.GetForegroundWindow():
self.window.append(hWnd)
else:
self.window.insert(0, hWnd)
user32.ShowWindow(hWnd, win32con.SW_HIDE)
return True
user32.EnumWindows(enum_windows_proc, 0)
def __del__(self):
self.show()
class DesktopManager(object):
__Previous = 1
__Next = -1
def __init__(self, desktop_count=4):
self.Desktops = collections.deque([VirtualDesktop() for x in xrange(desktop_count)])
self.Index = collections.deque(range(desktop_count))
def _move(self, direction):
self.Desktops.rotate(direction)
self.Index.rotate(direction)
def _display_desktop(self, direction):
self.Desktops[0].hide()
self._move(direction)
self.Desktops[0].show()
def _move_window_to(self, direction, HideWindow=True):
foreground_window = self.Desktops[0].remove_foreground_window()
self._move(direction)
self.Desktops[0].add_window(foreground_window)
self._move(-direction)
def display_next(self):
self._display_desktop(self.__Next)
def display_previous(self):
self._display_desktop(self.__Previous)
def move_window_to_next_desktop(self):
self._move_window_to(self.__Next)
def move_window_to_previous_desktop(self):
self._move_window_to(self.__Previous)
def move_window_to_next_desktop_and_display(self):
self._move_window_to(self.__Next)
self._display_desktop(self.__Next)
def move_window_to_previous_desktop_and_display(self):
self._move_window_to(self.__Previous)
self._display_desktop(self.__Previous)
def get_current_desktop_number(self):
return self.Index[0]
def show_all_windows(self):
[Desktop.show() for Desktop in self.Desktops]
| 29.871795 | 99 | 0.654649 | import user32
import win32con
import ctypes
import collections
class VirtualDesktopException(Exception):
pass
class NoForegroundWindow(VirtualDesktopException):
pass
class VirtualDesktop(object):
def __init__(self):
self.window = []
self.removed_windows = []
def remove_foreground_window(self):
foreground_window = user32.GetForegroundWindow()
if user32.IsWindowVisible(foreground_window):
self.removed_windows.append(foreground_window)
user32.ShowWindow(foreground_window, win32con.SW_HIDE)
return foreground_window
raise NoForegroundWindow("This Desktop is empty of windows.")
def add_window(self, window):
self.window.append(window)
def show(self):
self.removed_windows = []
for Window in self.window:
user32.ShowWindow(Window, win32con.SW_SHOW)
if len(self.window) > 0:
user32.SetForegroundWindow(self.window[-1])
def hide(self):
self.window = []
def enum_windows_proc(hWnd, lParam):
if not hWnd: return True
if not user32.IsWindowVisible(hWnd): return True
length = user32.SendMessage(hWnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buffer = ctypes.create_unicode_buffer(length + 1)
if not user32.SendMessage(hWnd, win32con.WM_GETTEXT, length + 1, ctypes.byref(buffer)):
return True
if buffer.value != "Program Manager":
if not (hWnd in self.removed_windows):
if hWnd == user32.GetForegroundWindow():
self.window.append(hWnd)
else:
self.window.insert(0, hWnd)
user32.ShowWindow(hWnd, win32con.SW_HIDE)
return True
user32.EnumWindows(enum_windows_proc, 0)
def __del__(self):
self.show()
class DesktopManager(object):
__Previous = 1
__Next = -1
def __init__(self, desktop_count=4):
self.Desktops = collections.deque([VirtualDesktop() for x in xrange(desktop_count)])
self.Index = collections.deque(range(desktop_count))
def _move(self, direction):
self.Desktops.rotate(direction)
self.Index.rotate(direction)
def _display_desktop(self, direction):
self.Desktops[0].hide()
self._move(direction)
self.Desktops[0].show()
def _move_window_to(self, direction, HideWindow=True):
foreground_window = self.Desktops[0].remove_foreground_window()
self._move(direction)
self.Desktops[0].add_window(foreground_window)
self._move(-direction)
def display_next(self):
self._display_desktop(self.__Next)
def display_previous(self):
self._display_desktop(self.__Previous)
def move_window_to_next_desktop(self):
self._move_window_to(self.__Next)
def move_window_to_previous_desktop(self):
self._move_window_to(self.__Previous)
def move_window_to_next_desktop_and_display(self):
self._move_window_to(self.__Next)
self._display_desktop(self.__Next)
def move_window_to_previous_desktop_and_display(self):
self._move_window_to(self.__Previous)
self._display_desktop(self.__Previous)
def get_current_desktop_number(self):
return self.Index[0]
def show_all_windows(self):
[Desktop.show() for Desktop in self.Desktops]
| true | true |
f7269554e70b05b444508f2c600f6f0487716659 | 2,187 | py | Python | src/jobhunt_prod/scrape/multiprocess_simply.py | smiller20/CareerCentral | 455df0910dff1a1883fd56365a7a4feeb7726b22 | [
"MIT"
] | null | null | null | src/jobhunt_prod/scrape/multiprocess_simply.py | smiller20/CareerCentral | 455df0910dff1a1883fd56365a7a4feeb7726b22 | [
"MIT"
] | null | null | null | src/jobhunt_prod/scrape/multiprocess_simply.py | smiller20/CareerCentral | 455df0910dff1a1883fd56365a7a4feeb7726b22 | [
"MIT"
] | 1 | 2020-12-04T22:57:24.000Z | 2020-12-04T22:57:24.000Z | """
simply hired using multi process design
scrape through 11 pages of simply using a multi processing for each I/O (4x faster)
"""
from requests import get
from bs4 import BeautifulSoup
from threading import Thread
import multiprocessing
from os import getpid
import psutil
def get_simply(url, role ):
alldata={}
response = get(url, headers={'User-Agent': 'Mozilla/5.0'})
try:
soup = BeautifulSoup(response.text, 'html.parser')
content_container= soup.find_all('div', {'class': ['SerpJob-jobCard']})
link= 'https://www.simplyhired.com'
except AttributeError:
pass
for content in content_container:
title, href=None , None
try:
title=content.a.text
href=content.a['href']
company=content.span.text
summary=content.p.text
except TypeError:
pass
except AttributeError:
pass
if title is not None and role.upper() in title.upper():
if href is not None:
href=link+href
alldata[href]=[title, company, summary, href]
return alldata
def getrole_simply(role, location):
test_data ={}
if "," in location:
location=location.split(',')
location= location[0].strip()+ "," + location[1].strip()
url_first= 'https://www.simplyhired.com/search?q='+role+'&l='+location
url= 'https://www.simplyhired.com/search?q='+role+'&l='+location + '&pn='
processor_count= multiprocessing.cpu_count() #get cpu count
pool=multiprocessing.Pool(11)
iterable = zip( [ url +str(i) if i != 0 else url_first for i in range(1,30) ], [role for i in range(1,30) ] )
result_pool=pool.starmap( get_simply, iterable)
pool.close()
pool.join()
for i, p in enumerate(result_pool):
for key, value in p.items():
if value not in test_data.values():
test_data[key]= value
return test_data
'''
process = psutil.Process(getpid())
print('total memory usage: ' , process.memory_info().rss , psutil.cpu_percent()) # in bytes
'''
if __name__ == "__main__":
getrole_simply('python', 'new jersey') | 33.646154 | 120 | 0.621856 |
from requests import get
from bs4 import BeautifulSoup
from threading import Thread
import multiprocessing
from os import getpid
import psutil
def get_simply(url, role ):
alldata={}
response = get(url, headers={'User-Agent': 'Mozilla/5.0'})
try:
soup = BeautifulSoup(response.text, 'html.parser')
content_container= soup.find_all('div', {'class': ['SerpJob-jobCard']})
link= 'https://www.simplyhired.com'
except AttributeError:
pass
for content in content_container:
title, href=None , None
try:
title=content.a.text
href=content.a['href']
company=content.span.text
summary=content.p.text
except TypeError:
pass
except AttributeError:
pass
if title is not None and role.upper() in title.upper():
if href is not None:
href=link+href
alldata[href]=[title, company, summary, href]
return alldata
def getrole_simply(role, location):
test_data ={}
if "," in location:
location=location.split(',')
location= location[0].strip()+ "," + location[1].strip()
url_first= 'https://www.simplyhired.com/search?q='+role+'&l='+location
url= 'https://www.simplyhired.com/search?q='+role+'&l='+location + '&pn='
processor_count= multiprocessing.cpu_count()
pool=multiprocessing.Pool(11)
iterable = zip( [ url +str(i) if i != 0 else url_first for i in range(1,30) ], [role for i in range(1,30) ] )
result_pool=pool.starmap( get_simply, iterable)
pool.close()
pool.join()
for i, p in enumerate(result_pool):
for key, value in p.items():
if value not in test_data.values():
test_data[key]= value
return test_data
if __name__ == "__main__":
getrole_simply('python', 'new jersey') | true | true |
f7269559f7d7eaf9efb701f4e1ac759e3c36654f | 502 | py | Python | aardvark/__about__.py | mbaciu-gpsw/aardvark | c2a0797bf3769ba819dcbacd4a80f4e9764d035e | [
"Apache-2.0"
] | null | null | null | aardvark/__about__.py | mbaciu-gpsw/aardvark | c2a0797bf3769ba819dcbacd4a80f4e9764d035e | [
"Apache-2.0"
] | 10 | 2019-07-23T09:03:02.000Z | 2019-10-15T14:53:14.000Z | aardvark/__about__.py | mbaciu-gpsw/aardvark | c2a0797bf3769ba819dcbacd4a80f4e9764d035e | [
"Apache-2.0"
] | 1 | 2022-01-11T13:06:32.000Z | 2022-01-11T13:06:32.000Z | __all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "aardvark"
__summary__ = ("Multi-Account AWS IAM Access Advisor API")
__uri__ = "https://github.com/Netflix-Skunkworks/aardvark"
__version__ = "0.2.1"
__author__ = "Patrick Kelley, Travis McPeak"
__email__ = "pkelley@netflix.com, tmcpeak@netflix.com"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2017 {0}".format(__author__)
| 29.529412 | 71 | 0.7251 | __all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "aardvark"
__summary__ = ("Multi-Account AWS IAM Access Advisor API")
__uri__ = "https://github.com/Netflix-Skunkworks/aardvark"
__version__ = "0.2.1"
__author__ = "Patrick Kelley, Travis McPeak"
__email__ = "pkelley@netflix.com, tmcpeak@netflix.com"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2017 {0}".format(__author__)
| true | true |
f726956703146c7de18a5d8a95ca243d34616547 | 12,727 | py | Python | pydmd/hankeldmd.py | kathryn-garside/PyDMD-fork | 0158c4144019f0899ce34ec44286b0f700c56b38 | [
"MIT"
] | null | null | null | pydmd/hankeldmd.py | kathryn-garside/PyDMD-fork | 0158c4144019f0899ce34ec44286b0f700c56b38 | [
"MIT"
] | null | null | null | pydmd/hankeldmd.py | kathryn-garside/PyDMD-fork | 0158c4144019f0899ce34ec44286b0f700c56b38 | [
"MIT"
] | null | null | null | """
Derived module from dmdbase.py for hankel dmd.
Reference:
- H. Arbabi, I. Mezic, Ergodic theory, dynamic mode decomposition, and
computation of spectral properties of the Koopman operator. SIAM Journal on
Applied Dynamical Systems, 2017, 16.4: 2096-2126.
"""
from copy import copy
import numpy as np
from .dmdbase import DMDBase
from .dmd import DMD
class HankelDMD(DMDBase):
"""
Hankel Dynamic Mode Decomposition
:param svd_rank: the rank for the truncation; If 0, the method computes the
optimal rank and uses it for truncation; if positive interger, the
method uses the argument for the truncation; if float between 0 and 1,
the rank is the number of the biggest singular values that are needed
to reach the 'energy' specified by `svd_rank`; if -1, the method does
not compute truncation.
:type svd_rank: int or float
:param int tlsq_rank: rank truncation computing Total Least Square. Default
is 0, that means no truncation.
:param bool exact: flag to compute either exact DMD or projected DMD.
Default is False.
:param opt: argument to control the computation of DMD modes amplitudes.
See :class:`DMDBase`. Default is False.
:type opt: bool or int
:param rescale_mode: Scale Atilde as shown in
10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its
eigendecomposition. None means no rescaling, 'auto' means automatic
rescaling using singular values, otherwise the scaling factors.
:type rescale_mode: {'auto'} or None or numpy.ndarray
:param bool forward_backward: If True, the low-rank operator is computed
like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is
False.
:param int d: the new order for spatial dimension of the input snapshots.
Default is 1.
:param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by
magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary
part to break ties) if `sorted_eigs='real'`. Default: False.
:type sorted_eigs: {'real', 'abs'} or False
:param reconstruction_method: Method used to reconstruct the snapshots of
the dynamical system from the multiple versions available due to how
HankelDMD is conceived. If `'first'` (default) the first version
available is selected (i.e. the nearest to the 0-th row in the
augmented matrix). If `'mean'` we compute the element-wise mean. If
`reconstruction_method` is an array of float values we compute the
weighted average (for each snapshots) using the given values as weights
(the number of weights must be equal to `d`).
:type reconstruction_method: {'first', 'mean'} or array-like
"""
def __init__(
self,
svd_rank=0,
tlsq_rank=0,
exact=False,
opt=False,
rescale_mode=None,
forward_backward=False,
d=1,
sorted_eigs=False,
reconstruction_method="first",
):
super().__init__(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
sorted_eigs=sorted_eigs,
)
self._d = d
if isinstance(reconstruction_method, list):
if len(reconstruction_method) != d:
raise ValueError(
"The length of the array of weights must be equal to d"
)
elif isinstance(reconstruction_method, np.ndarray):
if (
reconstruction_method.ndim > 1
or reconstruction_method.shape[0] != d
):
raise ValueError(
"The length of the array of weights must be equal to d"
)
self._reconstruction_method = reconstruction_method
self._sub_dmd = DMD(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
forward_backward=forward_backward,
sorted_eigs=sorted_eigs,
)
@property
def d(self):
"""The new order for spatial dimension of the input snapshots."""
return self._d
def _hankel_first_occurrence(self, time):
r"""
For a given `t` such that there is :math:`k \in \mathbb{N}` such that
:math:`t = t_0 + k dt`, return the index of the first column in Hankel
pseudo matrix (see also :func:`_pseudo_hankel_matrix`) which contains
the snapshot corresponding to `t`.
:param time: The time corresponding to the requested snapshot.
:return: The index of the first appeareance of `time` in the columns of
Hankel pseudo matrix.
:rtype: int
"""
return max(
0,
(time - self.original_time["t0"]) // self.dmd_time["dt"]
- (self.original_time["t0"] + self.d - 1),
)
def _update_sub_dmd_time(self):
"""
Update the time dictionaries (`dmd_time` and `original_time`) of
the auxiliary DMD instance `HankelDMD._sub_dmd` after an update of the
time dictionaries of the time dictionaries of this instance of the
higher level instance of `HankelDMD`.
"""
self._sub_dmd.dmd_time["t0"] = self._hankel_first_occurrence(
self.dmd_time["t0"]
)
self._sub_dmd.dmd_time["tend"] = self._hankel_first_occurrence(
self.dmd_time["tend"]
)
def reconstructions_of_timeindex(self, timeindex=None):
"""
Build a collection of all the available versions of the given
`timeindex`. The indexing of time instants is the same used for
:func:`reconstructed_data`. For each time instant there are at least
one and at most `d` versions. If `timeindex` is `None` the function
returns the whole collection, for all the time instants.
:param int timeindex: The index of the time snapshot.
:return: a collection of all the available versions for the given
time snapshot, or for all the time snapshots if `timeindex` is
`None` (in the second case, time varies along the first dimension
of the array returned).
:rtype: numpy.ndarray or list
"""
self._update_sub_dmd_time()
rec = self._sub_dmd.reconstructed_data
space_dim = rec.shape[0] // self.d
time_instants = rec.shape[1] + self.d - 1
# for each time instance, we collect all its appearences. each
# snapshot appears at most d times (for instance, the first appears
# only once).
reconstructed_snapshots = np.full(
(time_instants, self.d, space_dim), np.nan, dtype=rec.dtype
)
c_idxes = (
np.array(range(self.d))[:, None]
.repeat(2, axis=1)[None, :]
.repeat(rec.shape[1], axis=0)
)
c_idxes[:, :, 0] += np.array(range(rec.shape[1]))[:, None]
reconstructed_snapshots[c_idxes[:, :, 0], c_idxes[:, :, 1]] = np.array(
np.swapaxes(np.split(rec.T, self.d, axis=1), 0, 1)
)
if timeindex is None:
return reconstructed_snapshots
return reconstructed_snapshots[timeindex]
def _first_reconstructions(self, reconstructions):
"""Return the first occurrence of each snapshot available in the given
matrix (which must be the result of `self._sub_dmd.reconstructed_data`,
or have the same shape).
:param reconstructions: A matrix of (higher-order) snapshots having
shape `(space*self.d, time_instants)`
:type reconstructions: np.ndarray
:return: The first snapshot that occurs in `reconstructions` for each
available time instant.
:rtype: np.ndarray
"""
first_nonmasked_idx = np.repeat(
np.array(range(reconstructions.shape[0]))[:, None], 2, axis=1
)
first_nonmasked_idx[self.d - 1 :, 1] = self.d - 1
return reconstructions[
first_nonmasked_idx[:, 0], first_nonmasked_idx[:, 1]
].T
@property
def reconstructed_data(self):
self._update_sub_dmd_time()
rec = self.reconstructions_of_timeindex()
rec = np.ma.array(rec, mask=np.isnan(rec))
if self._reconstruction_method == "first":
result = self._first_reconstructions(rec)
elif self._reconstruction_method == "mean":
result = np.mean(rec, axis=1).T
elif isinstance(self._reconstruction_method, (np.ndarray, list)):
result = np.average(
rec, axis=1, weights=self._reconstruction_method
).T
else:
raise ValueError(
"The reconstruction method wasn't recognized: {}".format(
self._reconstruction_method
)
)
# we want to return only the requested timesteps
time_index = min(
self.d - 1,
int(
(self.dmd_time["t0"] - self.original_time["t0"])
// self.dmd_time["dt"]
),
)
result = result[:, time_index : time_index + len(self.dmd_timesteps)]
return result.filled(fill_value=0)
def _pseudo_hankel_matrix(self, X):
"""
Method for arranging the input snapshots `X` into the (pseudo) Hankel
matrix. The attribute `d` controls the shape of the output matrix.
:Example:
>>> from pydmd import HankelDMD
>>> dmd = HankelDMD(d=2)
>>> a = np.array([[1, 2, 3, 4, 5]])
>>> dmd._pseudo_hankel_matrix(a)
array([[1, 2, 3, 4],
[2, 3, 4, 5]])
>>> dmd = pydmd.hankeldmd.HankelDMD(d=4)
>>> dmd._pseudo_hankel_matrix(a)
array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
"""
return np.concatenate(
[X[:, i : X.shape[1] - self.d + i + 1] for i in range(self.d)],
axis=0,
)
@property
def modes(self):
return self._sub_dmd.modes
@property
def eigs(self):
return self._sub_dmd.eigs
@property
def amplitudes(self):
return self._sub_dmd.amplitudes
@property
def operator(self):
return self._sub_dmd.operator
@property
def svd_rank(self):
return self._sub_dmd.svd_rank
@property
def modes_activation_bitmask(self):
return self._sub_dmd.modes_activation_bitmask
@modes_activation_bitmask.setter
def modes_activation_bitmask(self, value):
self._sub_dmd.modes_activation_bitmask = value
# due to how we implemented HankelDMD we need an alternative implementation
# of __getitem__
def __getitem__(self, key):
"""
Restrict the DMD modes used by this instance to a subset of indexes
specified by keys. The value returned is a shallow copy of this DMD
instance, with a different value in :func:`modes_activation_bitmask`.
Therefore assignments to attributes are not reflected into the original
instance.
However the DMD instance returned should not be used for low-level
manipulations on DMD modes, since the underlying DMD operator is shared
with the original instance. For this reasons modifications to NumPy
arrays may result in unwanted and unspecified situations which should
be avoided in principle.
:param key: An index (integer), slice or list of indexes.
:type key: int or slice or list or np.ndarray
:return: A shallow copy of this DMD instance having only a subset of
DMD modes which are those indexed by `key`.
:rtype: HankelDMD
"""
sub_dmd_copy = copy(self._sub_dmd)
sub_dmd_copy.allocate_proxy()
shallow_copy = copy(self)
shallow_copy._sub_dmd = sub_dmd_copy
return DMDBase.__getitem__(shallow_copy, key)
def fit(self, X):
"""
Compute the Dynamic Modes Decomposition to the input data.
:param X: the input snapshots.
:type X: numpy.ndarray or iterable
"""
snp, self._snapshots_shape = self._col_major_2darray(X)
self._snapshots = self._pseudo_hankel_matrix(snp)
self._sub_dmd.fit(self._snapshots)
# Default timesteps
n_samples = snp.shape[1]
self._set_initial_time_dictionary(
{"t0": 0, "tend": n_samples - 1, "dt": 1}
)
return self
| 36.997093 | 79 | 0.613735 | from copy import copy
import numpy as np
from .dmdbase import DMDBase
from .dmd import DMD
class HankelDMD(DMDBase):
def __init__(
self,
svd_rank=0,
tlsq_rank=0,
exact=False,
opt=False,
rescale_mode=None,
forward_backward=False,
d=1,
sorted_eigs=False,
reconstruction_method="first",
):
super().__init__(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
sorted_eigs=sorted_eigs,
)
self._d = d
if isinstance(reconstruction_method, list):
if len(reconstruction_method) != d:
raise ValueError(
"The length of the array of weights must be equal to d"
)
elif isinstance(reconstruction_method, np.ndarray):
if (
reconstruction_method.ndim > 1
or reconstruction_method.shape[0] != d
):
raise ValueError(
"The length of the array of weights must be equal to d"
)
self._reconstruction_method = reconstruction_method
self._sub_dmd = DMD(
svd_rank=svd_rank,
tlsq_rank=tlsq_rank,
exact=exact,
opt=opt,
rescale_mode=rescale_mode,
forward_backward=forward_backward,
sorted_eigs=sorted_eigs,
)
@property
def d(self):
return self._d
def _hankel_first_occurrence(self, time):
return max(
0,
(time - self.original_time["t0"]) // self.dmd_time["dt"]
- (self.original_time["t0"] + self.d - 1),
)
def _update_sub_dmd_time(self):
self._sub_dmd.dmd_time["t0"] = self._hankel_first_occurrence(
self.dmd_time["t0"]
)
self._sub_dmd.dmd_time["tend"] = self._hankel_first_occurrence(
self.dmd_time["tend"]
)
def reconstructions_of_timeindex(self, timeindex=None):
self._update_sub_dmd_time()
rec = self._sub_dmd.reconstructed_data
space_dim = rec.shape[0] // self.d
time_instants = rec.shape[1] + self.d - 1
reconstructed_snapshots = np.full(
(time_instants, self.d, space_dim), np.nan, dtype=rec.dtype
)
c_idxes = (
np.array(range(self.d))[:, None]
.repeat(2, axis=1)[None, :]
.repeat(rec.shape[1], axis=0)
)
c_idxes[:, :, 0] += np.array(range(rec.shape[1]))[:, None]
reconstructed_snapshots[c_idxes[:, :, 0], c_idxes[:, :, 1]] = np.array(
np.swapaxes(np.split(rec.T, self.d, axis=1), 0, 1)
)
if timeindex is None:
return reconstructed_snapshots
return reconstructed_snapshots[timeindex]
def _first_reconstructions(self, reconstructions):
first_nonmasked_idx = np.repeat(
np.array(range(reconstructions.shape[0]))[:, None], 2, axis=1
)
first_nonmasked_idx[self.d - 1 :, 1] = self.d - 1
return reconstructions[
first_nonmasked_idx[:, 0], first_nonmasked_idx[:, 1]
].T
@property
def reconstructed_data(self):
self._update_sub_dmd_time()
rec = self.reconstructions_of_timeindex()
rec = np.ma.array(rec, mask=np.isnan(rec))
if self._reconstruction_method == "first":
result = self._first_reconstructions(rec)
elif self._reconstruction_method == "mean":
result = np.mean(rec, axis=1).T
elif isinstance(self._reconstruction_method, (np.ndarray, list)):
result = np.average(
rec, axis=1, weights=self._reconstruction_method
).T
else:
raise ValueError(
"The reconstruction method wasn't recognized: {}".format(
self._reconstruction_method
)
)
# we want to return only the requested timesteps
time_index = min(
self.d - 1,
int(
(self.dmd_time["t0"] - self.original_time["t0"])
// self.dmd_time["dt"]
),
)
result = result[:, time_index : time_index + len(self.dmd_timesteps)]
return result.filled(fill_value=0)
def _pseudo_hankel_matrix(self, X):
return np.concatenate(
[X[:, i : X.shape[1] - self.d + i + 1] for i in range(self.d)],
axis=0,
)
@property
def modes(self):
return self._sub_dmd.modes
@property
def eigs(self):
return self._sub_dmd.eigs
@property
def amplitudes(self):
return self._sub_dmd.amplitudes
@property
def operator(self):
return self._sub_dmd.operator
@property
def svd_rank(self):
return self._sub_dmd.svd_rank
@property
def modes_activation_bitmask(self):
return self._sub_dmd.modes_activation_bitmask
@modes_activation_bitmask.setter
def modes_activation_bitmask(self, value):
self._sub_dmd.modes_activation_bitmask = value
# due to how we implemented HankelDMD we need an alternative implementation
# of __getitem__
def __getitem__(self, key):
sub_dmd_copy = copy(self._sub_dmd)
sub_dmd_copy.allocate_proxy()
shallow_copy = copy(self)
shallow_copy._sub_dmd = sub_dmd_copy
return DMDBase.__getitem__(shallow_copy, key)
def fit(self, X):
snp, self._snapshots_shape = self._col_major_2darray(X)
self._snapshots = self._pseudo_hankel_matrix(snp)
self._sub_dmd.fit(self._snapshots)
# Default timesteps
n_samples = snp.shape[1]
self._set_initial_time_dictionary(
{"t0": 0, "tend": n_samples - 1, "dt": 1}
)
return self
| true | true |
f72695c880ab96368ab83d470e012d516b14bf5a | 1,438 | py | Python | pfrl/policies/softmax_policy.py | tkelestemur/pfrl | 388855fb30313185d43ae0d0f4b694be647a5c43 | [
"MIT"
] | null | null | null | pfrl/policies/softmax_policy.py | tkelestemur/pfrl | 388855fb30313185d43ae0d0f4b694be647a5c43 | [
"MIT"
] | 1 | 2021-05-14T20:53:26.000Z | 2021-05-20T15:58:32.000Z | pfrl/policies/softmax_policy.py | tkelestemur/pfrl | 388855fb30313185d43ae0d0f4b694be647a5c43 | [
"MIT"
] | 1 | 2021-06-09T03:17:34.000Z | 2021-06-09T03:17:34.000Z | import torch
from torch import nn
from torch.distributions import Categorical
class SoftmaxCategoricalHead(nn.Module):
def forward(self, logits):
return torch.distributions.Categorical(logits=logits)
# class MultiSoftmaxCategoricalHead(nn.Module):
# def forward(self, logits):
# return Independent(Categorical(logits=logits), reinterpreted_batch_ndims=1)
class MultiCategorical():
def __init__(self, dims=None, logits=None):
self.dims = dims
logits = torch.split(logits, tuple(dims), dim=1)
self.dists = [Categorical(logits=logits_dim) for logits_dim in logits]
def log_prob(self, actions):
actions = torch.unbind(actions, dim=1)
logprobs = torch.stack([
dist.log_prob(action) for dist, action in zip(self.dists, actions)
], dim=1)
return logprobs.sum(dim=1)
def entropy(self):
return torch.stack([dist.entropy() for dist in self.dists], dim=1).sum(dim=1)
def sample(self):
return torch.stack([dist.sample() for dist in self.dists], dim=1)
def mode(self):
return torch.stack([
torch.argmax(dist.probs, dim=1) for dist in self.dists
], dim=1)
class MultiSoftmaxCategoricalHead(nn.Module):
def __init__(self, dims=None):
self.dims = dims
super().__init__()
def forward(self, logits):
return MultiCategorical(dims=self.dims, logits=logits)
| 29.958333 | 85 | 0.665508 | import torch
from torch import nn
from torch.distributions import Categorical
class SoftmaxCategoricalHead(nn.Module):
def forward(self, logits):
return torch.distributions.Categorical(logits=logits)
class MultiCategorical():
def __init__(self, dims=None, logits=None):
self.dims = dims
logits = torch.split(logits, tuple(dims), dim=1)
self.dists = [Categorical(logits=logits_dim) for logits_dim in logits]
def log_prob(self, actions):
actions = torch.unbind(actions, dim=1)
logprobs = torch.stack([
dist.log_prob(action) for dist, action in zip(self.dists, actions)
], dim=1)
return logprobs.sum(dim=1)
def entropy(self):
return torch.stack([dist.entropy() for dist in self.dists], dim=1).sum(dim=1)
def sample(self):
return torch.stack([dist.sample() for dist in self.dists], dim=1)
def mode(self):
return torch.stack([
torch.argmax(dist.probs, dim=1) for dist in self.dists
], dim=1)
class MultiSoftmaxCategoricalHead(nn.Module):
def __init__(self, dims=None):
self.dims = dims
super().__init__()
def forward(self, logits):
return MultiCategorical(dims=self.dims, logits=logits)
| true | true |
f72695ed24f4c5a0ae1409ac5bdd45ac4dd38389 | 27,191 | py | Python | .qt_for_python/rcc/application.py | RodrooMtz/app_escritorio | e918f086d2b3a0a9749c8afb20e11845773cd117 | [
"MIT"
] | null | null | null | .qt_for_python/rcc/application.py | RodrooMtz/app_escritorio | e918f086d2b3a0a9749c8afb20e11845773cd117 | [
"MIT"
] | null | null | null | .qt_for_python/rcc/application.py | RodrooMtz/app_escritorio | e918f086d2b3a0a9749c8afb20e11845773cd117 | [
"MIT"
] | null | null | null | # Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 6.0.4
# WARNING! All changes made in this file will be lost!
from PySide6 import QtCore
qt_resource_data = b"\
\x00\x00\x08\x19\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x07\xabIDATX\xc3\xad\
W[P\x93g\x1a\xf6\xca\xce\xec\xcc\xf6b/\xbc\xd9\
\xe9\xce\xecn\xbd\xda\xd9\x9b\xb5\xce\xba;{\xb0\xad\xcc\
z\xb1\xce\xce:\xb3vTpu\xdb\xe2\x81\xd6\xb6T\
\x04\xbb\xa5 m\xc1\x82\x06\x08\x07QB\x80\x80\x80\x02\
!\x81\x10\x92@H\x10s$!gr\x80\x04B \
\x9c\x09G\xb5Tx\xf6\xfb~\x13\x160X\x8b}g\
\x9e\xf9/\x92\xfc\xcf\xfb>\xcf\xfb\xbe\xdf\x97]\x00v\
\xfd\x98 \xf1\x0b\x82\x14\x02\x03\xc1u\x82\x03\xcf\xfd\xfe\
\x8fH\xbc\x9b \xe1W\xaf\xef\xb5*\x8c\xd6e\xdb\x02\
`\x19\x1e[\x09'\xf13\xfa\x19\x81\x22\xfc\xdc>v\
H~\x8a\xa0\xb9\xb6Y\x1c2\xcf\xadB9\xfe\x1dD\
\xf6Q\xd8\xc7\xe6\xe8\x87\x86={\xf6XSR\xae,\
\xca::\x10N\xe2\xe5I\xc3\xc41\x04\xb7>I\xf9\
,`\x9b]YSM\x03M\xb6\x114\xeb\xfb 1\
y`\x19\x9d\xc5\xbb\xef\xbe?\xc5\xab\xbe\x83\xf1\x89)\
LO\xcf\xae\x92\xef\xd7\xbct\x02\x11\x9f\x0f\xbe\x1d\xe3\
\xb2\x04CO\xb43@\x8b{\x06\xcd=.4\xeb\xec\
\xa8W\xf6 \x87S\x852^5C\xbc\xb0\xf4\x90\x81\
\xc1`\x5c&\xbfK|\xe1\x04H\x1c$8A\xfd\xdd\
\xeas'\xf1\xb9'\x04H\x87\x97\xc1\xd7\xbb \x22U\
7\xdc7\xa2\xb8N\x88,V>\xccV\xdb:q\x04\
,\x16k,\xfc\xce\xe7'\x10\x916\x93\x95?F}\
\xa5\xfe\x12\xc4o\xf4Y1\xb6\x02~\xef Z{\x9c\
\xe0?0\xa1L(CF\x0e\x1b\xb2\x0e\xf9&\xd2\xf9\
\xc5e\xcc-,!4\xbf\x88\xbd{\xf7Z\xc9;~\
\xbam\x02$~C\x90F=5\x13iu\xb3\x80\xd2\
?\x0f\xcb\xc4\xe2\x9aP\xa1Z\xb4l\xf1Y\xa0\xb6\xa0\
\xa6]\x8d/\xb2sq\xb7\x9e\xff\x0c1%\x9d\x09\xcd\
cbj\x06\x83C\x81'\xe4\xdd\xbc-\xd3\xb0;\x92\
\x033&\xd4S\xb5\xd3\xfbXO\x88\xc5\x03!\x88,\
CP\xbaF\xd0\xed\x09B\xe5\x9bB\x9bs\xfc\xa9\xcf\
Z\x1b\xee*t\xc8\xbc\xc9E\x09\xa7l\x93\xcf\x9b\x88\
'\xa7\x11\x18\x1d\xc3\x80o\x08\xa2\xd6\xd6%\xc2Q\xdb\
(\x12\x87\xc6\x1f\xaf\x82/b\x94M\x89$\x90\x22\xea\
R-\x9aB\xab\xe8\x18y\x04\xa1\xc5\xcf\x10St\xf6\
\x0d\xa3\xd3\xe1\x87\xd4<\x80\x16\xbd\x03\x0d]\x06\x14\xd5\
\x0a\x90\x91\x95\x0d/y\xf1\xc6\xaa\xa9\xd4\xb3s\x0bL\
\xc5\x94\xd8\xdd\xef\x85\xc9b\x05\xb7\xbc\x12\xa5\xe5\x95K\
\x13\xf3\xcb\xab#\x0f\x017\xd9\x11\xe6\xd9\x15\x84\x97\x15\
\x13\x06\xcb<\xd0h\xf2\xa3\xdd\xee_'\x96;\x86 \
\xb3x\xd7}\xe6\x08\xa4\xf8<3\x1b*\x8d6\xaa\xdc\
S3!\x8c\x8e\x8d3\x15\xd3&\xe47\x09\xf1\xc1\xc5\
\x8fQs\xaf\x01\xbee`\xfc\x11\xa0#\x13#\xf2\xce\
\xa1\xbe]\xb9\xb8Q\x01\x83\x81ttM\xa7\x1e\x0ag\
\x80\xa9\xb8\xdd\xea\x83\xd8\xe8B\x93\xca\xcc\xf8|\xe5\xcb\
,\x88\xda$Q\x89\xa7g\xe7\x18\x1b\x86\x86G`w\
8I\x82:$|\xf8!\xae\xb3\x0b\xe1\x99\x5c\x80o\
\x09\xd0\x90\xde\xe1\x0f,\x81\xab\x1f\xc4}\xef\x04\xdd\x07\
\x1da\xeb\xff\x9f\xc0\x1d\xb9\x16\x1d\xf6!H\xcc\xfdO\
}\xee\xd4\x22\x9dU\x84\xaa\x9a\xbaM>G\xe4\x8e\xf8\
<<\x12\x84\xd3\xdd\x0f\xbd\xc1\x88\xc2\xe2b\x9c~/\
\x1e=\x03\x01\xf4/\x02\x83\x84\xbc\xc5\xff-\xee:C\
(Q\x91\xf7\xf6\x05\xf1N\xdc\xbf}\x843i\xe3 \
\x18\xf43\xab\xe0\xc9Th58\xd1\xd8\xdd\x0b\x9eX\
\x89\xac\x5c\xf63>G\xaa\x9e\x9c\x9ee\xe4\xee\xf7\x0e\
\xa2\xd7lAC\x03\x1f'b\xe3 \xe9\xd6\xc0E\xcf\
\x01R\x90$\xb8\x86\xb2\x9e\x00n\xb4\xdbP\xd1\x1bD\
\x85\xce\x8bJ~\x0bm\xbe\x9b['\xd1\xa0\x99\xf8\x16\
e\x22\x05\xee)\xf4(\x13\xc8\x90x5\x0b\x1a\xad>\
\xaa\xdcc\x13\x93\xf0\x0d\x0d\xc3f\xef\x83\xb4]\x8e\xc4\
K\x97\x90\xc3\xca\xc3\xd4c\xc0NzI1N\xfa\x89\
\x94\x7f[;\x84|\x85\x13%j\x1fJ\xd5\x03\xe8\xf2\
0\xa3(\x22\xf8\xf93\x09t\x8f.\xa1\xa8\xbe\x15\xa5\
|\x09\xb2J*\xf0\xcf\xe3qQ\xe5\xf6\x07F\xd1\xe7\
\xf2@\xab7 \xfdj\x06\x92\xbfH\x83\xcd7\x02'\
\xa9\xda@\x1aL\xe0{\x88R\x9d\x1fE\xdd\xfd\x0cq\
A\x97\x1b\xc5\xdd\x1e\x88\x9cA\xfc\xf9\xcd\xb7]\x84\xeb\
l\xb4C\xd0(\xf7N#\xa7\xfc\x1e\xb2K\xab\xf1Q\
\xeaWH\xfeo\xea\xfaXQ\xb9G\x82\xe3\xf0\x0c\xf8\
`4\x99Q\xc9\xab\xc2\xfbg\xcfA\xfe@\x03?\xe9\
n\xb2\x8d\x19\xb9oi\x06\x19\xd2\x9b*/r\xe5\x0e\
\xe4u\xf6\xa1\xf0\xbe\x1b\x1c\x95\x1b\xf9\x9c\xca)\xc2S\
\xb8\xdd)\xdc+v\x04\x90Q\xc8\xc5\x95ky8\x11\
\x9f\x80\x9b\xb7n3c\x15\x91\xdbjs@\x22m\xc7\
\x85\x84\x0fPt\xbb\x0c\xf3+\x80\x9f4X\xf7$ \
\x1c|\x84J\xd3\x188\xfaa\x86\x9cV\xfdU\xb3\x1e\
\xac\x0e;\xb8:\x1f\xd9!\x1ez/\xe0\x13\xbc\xba]\
\x02&\xbe\xc1\x83\x94o\xd88\x9f\x9c\x8a\x03\x7f=\x04\
c\xaf\x99\xe9n*\xb7F\xd7\x83\xa4\xcb\xc9H\xff:\
\x8b\x8c\xd5<S\xb5q\xf6\xa9\xdc5\xf6i\x5c\x97Y\
\x19\xd9\xbfn!\xa7\xa0\xd4\x82t\xbe\x1aW\x9b4`\
\xc9\xcc\x10\xbb\x82\xf8\xe5\xaf_\xa7g\xc0;\xe1u\x1f\
5\xcc5\xddf|\x94\x96\x85\xb8s\x17\xf1\x97C1\
L\xd5t\x99\xf0\xaa\xaaq\xfa\xf4\x19h\xcc\x0e\x8c\x92\
-6\x14\x1e\xabZ\xc7\x0cx\xe6qp\x0d#L\xa3\
e\x8a\x0c\x8c\xec\xb4\xfa\x9c\xb6^\x94t9\xd0f\xf7\
\xaf\x1e=\x11KG.o\xc3y\x135,\x5c\x99\x1a\
\xf1\x97>\xc7\xd1\xd83\xf881\x09\x86^\x13\x1a\x9b\
\x04\xf8\xdd\x1b\xfbQO\xd4\xf1\x90\x99\xee\x9a\x00\xaa\xad\
\x93`+]\x0c9\xf5\xbc\xf0\xbeg\xbd\xea\xcc\x16=\
JU\x1e\x08m\x01\x94\xd4\xf1C\xe1eS@\xf0\xca\
\xf7%`+nj\xc7\xa9\x84D\xc4\x1c9\x8a\xdc|\
6ZZ\xc58\x14\x13\x83/95\xc8\x14j\x98\xe6\
\xa2\xd5\xd2'\xf5\x9azL\x13\xa1Id\xb7\x99\x90\xdb\
nF\xb9\xda\x8d\x06\xa5v9,9=\xf9N\x13\xec\
\xd9r\xd4G\x0d;\xabF\x88c\xff9\x8f\xdf\xee\xfb\
=\x1a\xf9\x02\x9c\xbf\x90\x80\x93\xf1\x17p\xa3\xad\x07\x19\
\xc4OJ\x14\xe9n\xbaX\xa8\xef,\xfa\x94\x98P(\
\xb7@\xe9\x0e<\xf9W\xec)*w-\xc1g\x04\xfb\
\xb6\xb9\xe4D\x8d\xbe\xcc\xb2Z\xfc\xe3\xe4\x19\x1c<\xf4\
7\xb0r\xf3\xb0\xef\xc0\x1fP \xd1!\x89'e*\
\xa6K\x85>\xbf!\xd5F\xe4.\x90[!\xb0\x0c\xae\
\xe5\xdc\xe2\xd2\x11\x13\x13\xe4\x87o<\xaf<\xe7\x96\x15\
5\x9ciE\xe5\xf8\xfb\xb1X\x1c?\x19\x877\xf6\xef\
\xc7\x8d:\x11\x92\xab\xa4\x0c!\xedp\xea5U!\x8b\
4[\xc9\x037*4n\xd4I:\x17\xc3rs\x08\
\x8em\x95\xfb\x87$\xe0Jesp\xe4\xf8)\x1c>\
|\x98\x8cc.2\x05*\x5c\x22\xd5\xd3]~M\xdc\
\x0b6\xe9tv\xa7\x1dw\x8c\xe4\x88\xb6\xf9\x9e\x84\xb7\
\x1a\x95\xfb\x22\xbdI\xfd\x80\x0bm\xf4\x042JxL\
\x0f\x9cKI\xc3\xb5\xa6.|\xc2me6Y\xf1\x83\
\x01\x5c\x97\x9a\xc1Q{ \xf3\x04\xd7\xce%&\x056\
\xc8\xfd\xc7\x9d\xc8\x1d\xd5\x82\xdc\x1a\x01\xce^NE\x81\
X\x85x\xf6]\x5c\xa9U\x90\xaa\xfb\xc0\x96\xdbP\xad\
u\xe3\xaeTA/\x10\xca\x0dr\xbf\xba\xd3j\xa3\x05\
\xb7\xa2Q\xf8\x1d\xafC\x8dO\xb9-\x88\xcb\xe6\xe1\x9a\
H\x8f\xaa\x1e/\x9a5\xe6\xc7\x7fz\xf3-Wx\xac\
\xa8\xdc\xaf\xbd\xac\xdc\xd1\xe2\x08\xdd\x05\x5cu\x1f\xde\xcb\
\xafE\xb9v\x002g`\xf5\xc2\xa7\x97\xa9\xdc\xf7\x08\
\xd2\xa9\xdc;\xf8\x03\xf3\xc2\xf1\x13\x82\xca\x1c\xee\x9dP\
\x0b9\x94\xb8\x0d\xc2\xc8\x16\xa3\x17\x87\xc3/\x22\xf7\x0e\
\xff\xdam\x8a\xdda\x99\xd5\x1b\xb6\xd8k\xbb^2\xbe\
/\x89\xff\x01f\xb9_\xfc\x11\x80=\xcf\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x03T\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x02\xe6IDATX\xc3\xd5\
\x97\xcdN\x13a\x14\x86\xeb5\x94\x95{q\xe1\xd2\xc4\
\xe0\x05\xb8\xe2\x0e\x5c\xb8\xf4\x02\x5c\xb10\xea\x05\x18\x96\
&bX\xb8\xb0\x91X \xd1\x9d\xbf\x89\xa4\x14\xb1R\
\xa4HE\x94\xfe\xd0\x02C\xff\xa6\x9d\x19\xa6e\x80\xe3\
y{\xfa\x85QJ\x82\xc9!\x86I\xde\x9c3\xa7\xf3\
\xcd\xfb\x9c\xf3M\x9bN\x84\x88\x22\xffS\x91s\x01\xc0\
\xc7\xd5\x90n\xff\xa5\xfb\xac\xc7==d\x0d\xa9\x02\xf0\
12<<\xbcj4::\xba\x19V<\x1e\xaf&\
\x93\xc9V:\x9dv\x13\x89Dk`` \xcdkn\
h\x02\xa48\xd2\xe1\xe1q\x99\xba\xef\xb7\xc9\xb2,\xda\
\xdf\xdf'\x86\xf1x\xcd\x18\xeb\x8a\x1a@?\xf3\xb0\x1c\
\xc7\xa5Lf\xb9\x0b\x14\x04\x01\xc5b\xb1:\xaf{p\
\x1a\x88S\x01\x1c\x1c\x10ww\xb2l\xdb\xa1\xf9\xf9\xcf\
d\x0e\xd7u\xe9\xf9\xc4D\x17B\x05\x00&{\xc1\xc9\
\xaa7\x1cJ\xce\xcdS\xf8p]\x0f\x8b\x17T\x00\x82\
\x10@gO\x14\xce\xed\xa6G\x1fgf\xe9\xf5\x9b\xb7\
\x14\x9f\x9c\xa4\xa9\xa9iz\xf7\xfe\x03E\xa3\xd1e^\
\x7fA\x05\xc0\xef\x10\xed\xb6%\x86\x85\x9a\xe3\x05\x94]\
\xcd\xd1\xe4\xf4+z2\xfe\x94\x9e\xc5^\xd0Lb\x0e\
\x8b\x17U\x00\xda\x81\x18\xf5\x13 <\xff\x90j\xcd6\
\x157\xab\x94/nS\x89c\x8d\xb7\x85\xd7~Q\x01\
\xf0y\xcc\xcd]\x1e\xb5\xc7{\xdb\xee\x9f;\xbe\xe4\x88\
]\xb8\xbd\xee\xe2\x94\xca3\xe0u\xe4\xc6uWb\xd8\
\x109\xea\xe63D\xd4\x01\xa7\x06\xe0\xf4:\xad9\x22\
\x98\x98hr\x80\x98kPS\x9d\x00\x00*-\xb91\
\xe2NS\x8c\x10\x0d\x04\xf2m\xfb(\xb6|E\x00\x9b\
;\xdbj\xfci\x8e<l\x88\x1a\xae9\x13\x80:\x8f\
\xb7T#*\xd7\xc5\x04\x06\x06\x005(\x9c\x17\xab\xbc\
%\xbb\xca\x13\xc0Ma\x0e\x15*rn\xcc~Z\x02\
hj\xdd\xad\xf1\x94'\x00S\xdc\x1cqm[@`\
\x9a\xab\x1cu\x9e\xeb\x81A\x15G\x11\xc0j\x891\x0c\
\xd6w\x04 \x0cd&b\xb6iu\x8b\xa8\xaa\x09P\
\xb6\xc5\xbc\xd0\x03\xf8\xbe)c\x87)`\x0c\x18\x84\x1c\
\x00[ME\x00t\x03S\x98\xad\x94\xc5\x1c\xe7F\xe6\
\x1c\x00\xc8q]\xa9\xa1\x08\x80\xfd\xfcV\x12s3\x01\
\x085\x18B\xe8\xda|\x8e)\xa8N\x00[\x00\x03\xc8\
\x98g6\x04\x002\xe6\x85\xde\xf8\x17\x0b\xfc,\xd8\x8a\
\x00\x18g:O\xb4T\x14#\x98\x02\x00\x02\x0c>\xfb\
\xc5S(\xf0C\xb8fI\xf7k\xf9R\x87\xd7\xbeT\
\x01\xc8U\x8f\xbaN\xadK\x0e\x90\xaf\x85\xde\xb7\xc2\x92\
=O\xa6\xb3\xde\xa3\xb1q\xeb\xda\xd0\xf5\x15\x98\xb3n\
\xa9\x00l4\xa4k\x18\xff\xe0\x11\x7fZ\x17S\xd4\x13\
\x0bYo\xe4\xee\xbd\xe2\xa5\xc1\xcbK|m\x8cu\x87\
5\xa8\xfa\xb7\x1c\xdde\xd9<\x8f\x1f\x19\xfe\x9e\xcf\x1e\
7\xbd\xc9\xbax&oF\x00h\xf2\xff\x81\x99\x94\x9e\
\xe9?\xbf\x19\x01B\xd3\xf4\xfc\xbd\x9c\x9e\xa5~\x03Q\
l%\xa1\x92\x95\x0aw\x00\x00\x00\x00IEND\xae\
B`\x82\
\x00\x00\x05:\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x04\xccIDATX\xc3\xb5\
\x97]L[e\x1c\xc6wo\xbc\xd9\xe5\x12I q\
\xd7&\xe3N\x13\xb8p\xd1\x85D\xbdP\xe3\x10\x18\xe5\
+.&J\x04'\x86\xaa\x8b\x99\xe0\xd0\xa2l\x19\x86\
9\x17\xdc\x1a\x16\x98\x80@l\xa6C\xca +\x83\x1e\
(\xcc\xda\xd1\x96\xd2\xd2J{\xfa\x01\xa5\xd0\xef\x16\x1e\
\xdf\xff\xdb\x1d\xc7\xcc\x04*\x87\x93<9o!\x9c\xe7\
\xf7<\xefG\x0f\x87\x00\x1c\xcaF\xcf\xbd\xfa\xe9\xbbL\
Z&a\x0fj`\xca\xd9\xe9y\xd9\x9a?]P\xf2\
\xa5\xc1\xe9\x8f\xa7W\xc3@0\x02\x84\xa2\x19\xad\xc72\
\x8a'\x81X\x22s\xbfyk\xdaK\x10r\x02\x1c{\
\xe7\xac\xda\x1c\xd8\xc8\x98\x12@\x84\x99\x85\xe3\x19\x911\
)\x1aKa%\x94D8\x9aBs\x87\xc6\xbe\x13\xc4\
\xff\x02\x90\x12\x93y$\xf1\xc8X\x92\xcf\x1f\x84]\x8c\
\xc2\xe5\x09\x22\x12K\xa3\xf4\xc3\xefM4uY\x01\xb0\
\xeb\xd86\xd5\x90\x9e:\xfc\xcc\xb9\xe7_.\x11?V\
\x9eEEU\x0d*\x99\xde\xaf\xad\xc3\x9d\xb1\x89\xc7\x00\
\xac\xb6%\xfc\xb9\xe8\x87k\x15X\xf6\x04\x10\x08\xc6\xd2\
\xaf\x9c\xbep\x9fA\x1c\xd9\x15\x80]\x87\x99\x1a\x8a\x8a\
\x8a\xcc\x92Z[[\xdd\xa4\xafU\xad\xfe\xafT\xdf\xa6\
\x06\x06\x06195\x85\xd9\xb99\xe8&&PPP\
\x80!\xcdo|\xdeI\xa6\xf9\x05\xcc\x98\x5c\x1c\xc0\xe1\
OA\xf4\x85\xf0C\xaf\xce\xcd\x00j\xf6\x02PCf\
\xd8\xe5\x8a\xc7\xe3\xf0z\xbdH\xa7\xd3\x98\x9c\x9cDe\
e5fg\x8d\xbc\x81\x07f\x1bt\xd3\x16\x0e@2\
-x\xf0\xdd\x8dQ\x8f\xac\x00\xe1p\x18F\xa3\x91\x8f\
S\xa9\x14~\xea\xedE\xe3'\x9fa\x86A8\x96\xdc\
Pwu\xe3LC#\xce5\x9d\xc7\xed\x91q\x5c\xbc\
>,/\xc0\xc6\xc6\x06\xf4z\xfdc@}}\xfdP\
2\x88\xd0F\x1cf\x9b\x0b\x82\xc1\x88\xa9\x19\x13\xac\x0e\
\x11\x97\xbadn\x80\x00\xa6\xd8:\xd8~E\x22\x11\x94\
+*0\xae\x13@\xe7\x04mW\xda\xaa4\xbe|S\
\xe65@f:\x9d\x0e\xc3\xc3\xc3\xe8e\xf5\xf7\xf7\xf7\
C\xab\xd5\xa2\xaa\xba\x06cw\xf5\x90\x0e*w\x90\xed\
\x04\xb6\x0e\xda\xbbe\x06\xa0y\xb7\xdb\xed\x18\x1a\x1aB\
gg'zzz8PIi\x19ni\xf5\x10\xd7\
\x00o\x08\xb0\xf9\x00g\x00\xb8\xd0%3\xc0\xd6\xd6\x16\
\xdf\x09\x81@\x00\xa2(\xc2\xef\xf7cmm\x0d\xa7\x14\
\x95\xd0\xfc\xae\xe7\xa9\xc9|\xc1\x0b\x98=@\x9b\xdc\x00\
\xdbA677\xf9v\xa4V\x14\x15\xd5\xe8\xfbU\xe0\
\xa9\x1d\x81G\x00\xe7;\x0f\x00\x80\xcc%\x80$3O\
$\x12(+\xaf\xe2\x00\x7f\xb8\x00\x8b\x98\x01\xa06Z\
\xd5\x070\x05\xff\x98'\x93<=MI\xc9\xa9J\x0e\
\xa0\xb7\xb3\x03\x89=\xc5\xf8\x170\xb1\x00|q\xf5\x00\
\x00\xa4\xea\xc9\x98\x14\x8b\xc5P\xa6\xa8\x82zH\xc0\x98\
\x19\xb8k\x05\xe6\x9c\x99\xfb\xe7Wd\x04\x90\xd2Sj\
\x02\x88F\xa3\xdc<\x14\x0a\xa1\xb8\xb4\x02\xd7\x06\x05\xdc\
f\x87\xe4\xa0\x01\x1cd\xc4\x04(;d\x06H=\x9c\
s\x12\x99\xd3\xb9@ \xc5eU\xb8\xd8-\xa0\x7f:\
c\xae}\x90i\xe0\xa3v\x99\x00\xfe]=\xa5&\xad\
\xae\xaer\x88\xb7J*p\xb9W\xc0=\x1b\xb8~\x9e\
\x01\xee\xcc\x03g.\xed\x13@\xaa\x9dD\x8b\x8e\x92\xd3\
qL\xdf\x01+++X__\xe7\x10'Y\x03\xdf\
t\x09PO\x00\xbf\xcce\x1a\xb82\x064\xec\xa7\x01\
\xc9X\xda\xebdNi)9\x1dD\x04@\xf5\xd3\xcf\
\xde|[\x81\x96\xeb\x02O~u\x1c\xb8q\x0f\xf8q\
,\x9e~\xbdNm\xa67\xaa\xac\x00\x9ed,m7\
2%\x00\xd1#\xf2\xe4\x12\xcc\x1b'\x15h\xef\x11\xa0\
\xbcf[\x7fO5\xe2<q\x9a\xbf\x8ei\xf7\xfcJ\
&\x01\x90\xa9$i\xb5SB2\x0f\x06\x83p\xb9\x5c\
\xdc\x90^J\xe8\xb3\xc7\xe3\x81\xdb\xed\xc6\xf1\x13\xaf%\
\x9f}\xa1\x9cL;\x98\x8a\x99\x8e>\xc9xG\x00\x95\
J\xc5\x01\xa4\x15.\xcd7\x19RR:\xf7)\xb5\xc3\
\xe1\xe0\x22\xe3\xc5\xc5E\x0e\xf5\xe2\xf1\x97\x5c\xf4\x1e\xb9\
\x93\xe9\xae\x00---n\xe9`\xa1\xd4\xd2\x97\x0d\x8d\
\x97\x97\x97\xe1\xf3\xf9`\xb3\xd9\xf8}ii\x89C\x10\
\x00\x8d\x0b\x0b\x0b\xcd\xb2\x00\xd0\xa2\x92R\x93\x11\x8d\xe9\
N\xdfxT;5`\xb5Zy\xf5\xd4\x0a\xfd\xce`\
0$\xf2\xf2\xf2\xee\xb3g\x1c\xd9\x17@SS\x93[\
\x9agJO\x22\x13\xaa\x9a\xc6\x16\x8b\x997@\x9fG\
GG#mmm\xde\xfc\xfc|\x13\xfb\xdbA\xa6\xb2\
\xbd\x9a\xff'@ss3\x9f\x02JG\x10T?U\
???\xcf\xeb\xd6h4\x91\xba\xba:\xe7\xc3\xb4]\
L\x1f0\x1d\xcd\xc6xG\x00\xa5R\xe9v:\x9d\xbc\
bJJo>\x94\xb4\xbe\xbe\xde\x99\x93\x93#\x99\x16\
gSuV\x00\x8d\x8d\x8dn\x8b\xc5\x82\x81\x81\x81H\
mm\xad377WV\xd3\xdd\x00\xf8\x7fFL\xc2\
A\x99n\xd7\xdfC9V\x18\x85p\xc8\x04\x00\x00\x00\
\x00IEND\xaeB`\x82\
\x00\x00\x05+\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x04\xbdIDATX\xc3\xed\
WkL\x93W\x18>#q\xc92\xe9\x16\x97\xa8T\
e8\x9d\x02\x15\xf6\x03\x872\x93\x01f,[p\xc4\
0\xff`\xa2.\x1a:\x1dN\x03\xba1\x89[\xb3\x80\
\xd9\x0c\x84\x02\x19X\x1c\x14\x8b\x85\xb2\x82\x95^\xe4f\
\x0b\x8e1\xf8\xc3F\xcb-\x81\x15\xdc\xa8\xc2\x1c\x1b\xb7\
ji\x91\xf2\xee\xbc\x87\xaf\x0c\xdc\xb8\x0da\xd9\xb2\x93\
<\xed\x97\xf3}\xfd\xde\xe7\xbc\xef\xf3^J\x00\x80\xfc\
\x93 \xff\x0a\x02t\x09(D\x14\xd9\x14q\x14\x01+\
F\x80\xae\xddd\xdd\xc6f\x22L\xf8\x95\xc4\x8bG\xc8\
\xa1\xd3\xf7\xc8\x8e\x97;82a+A \x85\x9c\xbe\
0H.\xdd\x80\x19@2\xabyM\xf4\xbe\xfbr\x13\
hd\x06\x91\x04^\xa3Q\xf4\x06\xee\x85G\xf5\xd0\xbd\
\x83\xcbM \x9b\x9d\xf6@t/\xbd\x162= \x89\
?H\xa5,\x1b\x01\x8c1y\xc1\xbb\x9d\x88K\xc6\xd7\
\xc6&\x0e\xa0\x10\xb9\xfdB\xfe\xc5+6F\x8c\x12\x5c\
N\x02\x93\xa7\xa7\xa7\x0d\xcc\xd39\xb9\x98c6\x14\x0a\
\xd2\xe4\xa3+A \x8c)\x9e*\xdf7G\xeb\xdc{\
\xb5\xcc\x89\x9e@D\x96T\x83+,\x0b6FH\x08\
\x13\xf5d*{.T\x03\x01\xf8\x037\xbf\xc0\x0e4\
*T\xdfb\x88R\xd5,X\x03t\x1d\x16\x08\x04z\
EU\xf5\xc8\xa0mt\xc2\xd4s\xf7!\xbesQ\x95\
\x90\xae\x8f\xd0\x13\xcf\xe5\x94\x83\x87\xb4\x02\x9e\xcc.\x03\
\xd4\x06\xdd\xaf\x99\xcb\xb0\xaf\xaf\xaf>\xbf\xd2`\xb5\xdb\
\xed\x80\xf8y\xe4>\xc4^\xab\xb4\xb9\x88/\x86\x80'\
\xd3\xc0g\xf9\x8e\x19\xf5`\xd7^3\xbav\xdas\xee\
h\xd8\xc7\xc7G\x9f\xab\xab\xb0\x0e\x0f\x0d\xc1\x10\x87\xb2\
\xf6.\xe7\x967\xf7wsa\xd8\xbd\xe8^\x80/f\
\x9a\xa0\x86\xdf\xa96B\xf7\xf0\x03\xd8\x19\x9f\xd4\xcf\xa5\
\xe7\x1a\x8a\x98-~\xfem\x97T\x1ak__\x1f\xb8\
\xd0\xd1s\x07br\x15VN\xc4\x87\x97\xd4\x8c0\x14\
\xe9\x15\xb7\x1e8\x1c\x0e@\xa4\xd6\x191\x9e\x85\x9b\x05\
~m\xa9%\x1a[\x97\xd9\x0c\xe6.\x0a\xf3$\x14\xdf\
6\x8e{\xbd\x1e\xd1\xcdB\xc8\x09o\xa9\x04<\xd1\xbd\
V\xab\x15\x10w\x7f\x1b\x84\xf3\x92\x5c\xbbR\xa9\x84\xfa\
\xfaz0\x99L\x0cu\xdf5\xc1Q\xb1d\x18\xc9Q\
D>\xb6v\xcc\xb4@O\x93_~\xd3\xd6\xdf\xdf\x0f\
2\x99\x0cD\x22\x11\xa8T*\x90J\xa5\xa0\xd1h \
K[9\xbe\xe9\x95\xe0\x1f\xb8S\xafy,\xf3\x00\x97\
\x8e\x22\x9e\xc7\x86\xe6S)\x19\xf6\x82\x82\x02\xe6\xe2\xa0\
\xa0 \xe0\xf1x`\xb1X@[^\x01\xfb\xcf&\x0c\
-\xa6S\xceg\x94\xcf\x09L\x83\xe2[{\xe6\xc2`\
\x9a\xb2\x14\x14\x0a\x05\x88\xc5b\xc8\xcc\xcc\x84\xa2\xa2\x22\
P\xab\xd5\xd0\xd9\xd9\xc9`\xec\xfe\xc9\xb9\xc9\xdb\xa7u\
.\xb7\xcfK\x80\xae\xb7\xd8)p\x0e\xc0j\x97\xacx\
\x88\xca\x7f\x82\xe2)\x89\x0e>\x97+![\x96\x0f\x07\
c\xe3G\x84\x1f&\xd8\x92rd\x8eo\x1a\xbf\x07\xa3\
\xd1\x08-\xad-\xf0\xcb\xc0 \x1c8\xf1\xbe\x05\xb3b\
\xc1\x04\x5ci\x84\x85\x85\x84F\xdc&\xe72\xac,\xcf\
3\xb5\x13\xec;\xe3\xba\xd33\xaf\x82\xe5\xfez\x89\x06\
\x9e\xde\xfcb\x1b\xf7<\x92\x8d{f\xabO[\xca5\
\xedXCC=444\x80\xa5\xb7\x172\x14\xc5\xc3\
\xf3\xe9\xc0e<\x92\xe5(\x9e6]\xe5\x9c*2x\
}\xf4\x83.Zl\x121\x0c\x1b%\xeaq\xf7/\xcb\
'\xef\x05\x87_\xfe\xd3\xe4D\x0bLh\xf4\xc9>u\
\x95\x1e\x0c\x06\x03\xb4\xb7\xb7\xc3\xd7\xc6\x961\xae\x81\x09\
f\xf16m8h<I::e\xf8b\x81\x83D\
\xbdWC\xb6\x0a^\x9b*\xc3\x94\x5c\xb0B\x0f\xab$\
\xb4\x04\x9fJ\xaa\x9bC71(\xd4O\xf2\x0a\xc7t\
:\x1d\xd4\xd6\xd6\x82\xc9|\xdb\xb9a\x9b\xf7_\xeab\
\xb2\xe5~\x9cu\x1f\x0d\xf3\xb2\xd4N\xf2\xf6\xb1\xeb.\
\xb6\xae\x94\xc3\x90l\x97U\xc1KW\xab\x80\x9cMn\
Z\xd0\x1cI\xbd\xb1\xe7\x88\xb0\xef\xcaW\xc5PZZ\
\x0a\x1d?\xf6L\x04\x06\x87t<\xaa\x0b\xc2\x84F\x8d\
\x07\xc8o\x02\xd9\xf9\xaa~\x9a\xf10F\x8e6 \xaf\
\xbcJxCi\x00\x92(\x1d\x98\xcd\x95\xb3y\xc3}\
=\xbf\xf9Dj\xa6].\x97CSK+D\x1c{\
\xf7\xce\xf4\x14%\xae\xf1\x8a\xf5w\x9c\xf5p\x02\xc2\xd9\
\x0f\x89\xd1\x81\x03O\x8e\xf7\xdc\xd2i\xe7\xf3\xdfu\xfc\
o\x14.6\xd2\xef\xd8\x17iI\xbe,\x9d\xc8\xd3\x96\
;\xa7\x0f1\x8c%\xc6\xdf\x9f\xbaw_q5\xa0A\
l\xb5\x08\x8c\xf9\x94\xf1\xe0\xf03K\x9a|h\x13Z\
\xbd\xce\xa3\xd9kOH\xf7\x0c\x0f\xb0\x0f\xfe\xf3\x87\xc8\
\xf9/\xee\xb9In\x00\xf6{>\xed\xf7\x08\x1e*>\
]\xe5X\xaa\xf1GZ\xf5\xb6Y\x0b\x11\x1d\xb3C\xc9\
\x918\x099\xf9\xa9\x96!\xfa\x5c\x1a\x0d\xcf\xb3\xff\xff\
7\xfcO\x13\xf8\x1d\xe7\x87\x19\xb9D\xc3\x01\xcf\x00\x00\
\x00\x00IEND\xaeB`\x82\
\x00\x00\x06m\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x064IDATx^\xad\x97[lT\xc7\
\x1d\xc6\x7fs\xce\xd9\x8b\xbd\xf6\xfa\x16\xa0\xbe\x00\x0e\xb2\
ic$BJ!\x22\xa1-\x95b\xa5/\xeeKh\
+\x95\xa6U\xa5\xc6`U\xaa\xda\xb4\xaa\xfaV\x09U\
\xca\x03\x94'\xda\x07\x84\x14)\xad\xc4\x8b\xa5R\x83y\
\x08\xc5\x189\x0ei\xd3\x84\x9a\x9bcj\xec\xb2\x04\x1b\
;\xbb\xf6z\x8f\xbd\xbb\xde\xb3g\xa6\xc3h\x85\xe5r\
l\x88\xc9'}\xfa\x9f\x9d\x87\xfd~\xf3\x9f\x99s\x11\
J)\x82$\x84x\x05x\x9e\xc7kH)\xf5w\xd6\
(' \xb8C\xbb\x01h\x97R\xbe\xc6cdY\xd6\
\x07\x1a\xf6\xbb@\xb7\x069\xff\x14\x00&\xfc\xb7\xed\xf5\
\xe2`]DDn\xce\x89\x8a+W\xaeP]S\x8d\
@\x00\xa0P\x08e(A)f\xd3i^\xa9\x17/\
\xbc\xb4Nl;\xf1\x1f\xb9G\x83|[CL<M\
\x07\xf6\xff`\x8b\xdd,%\xf8J2<<Lee\
%+\xc9u]\x1e\xc0n\xa9\xb0\x22\x1b\xa2*r?\
\xa7\xea\x81\xb5\x03\x08-\x05H\xa1\x0d\xf4]\xbcH.\
\x97\xc3/\x16QJ\x91\xcf\xe7Y\x5c\x5c\xa4P(P\
\xd4c\xb5\xb5\xb5\x94\x01X\x80\xf8\x82\xf6\x80\x01\x006\
D\x05\x1f\x0f\xbcK>;\x8f\x85D\x952\xe2\xb6\xc4\
\xb6\x04!!p>Sl\x8c;\x80D*\x04\xf0\x9c\
\x10\x02\xe0\xcb@\x05P\x0f4`\xc4Hi\x9f$\x02\
\x01N\x9c8!\x00\x81\x05\xd2\x87\x96\x96g\x09em\
\x14\xe5(\xa5\xb4A\x08XW\x19%\xe2\xd8DB\x16\
\xc3\x13s\x5c\xbc=A\xf7X\x8e\x5c$\xbe\xa9\xbd}\
\xf7\xef-\xcbZ\xdc\xb1cGYUU\x95\xd3\xd8\xd8\
\x18~\xe0\x86\x86\x86\xd0\xa5K\x97\xdc\xae\xae\xae\x08\xf0\
\xd6\xaa\x1d\x00\x13DU,\xc2s\xd51\xf2\x9eO\xa1\
(\x91Ja\x09A\xd8\xb1\x88\x86l\xe6r\x05\x12\xa2\
\x8e?\x9f\xff+\x0dM\x1b\x01\x22\xc0f\x96\x84\xef\xfb\
x\x9eGuu\xb5\x9ePK\xf4\xea\xd5\xab\x87\x84\x10\
(\xa5\xdeZ\x11\xc0\xb2A\x00\xb6-\x90\xda\xb6\x148\
\x08\xa4\x12X\xc2\x8c\x1b\x8fL\xb9\xec{\xf5;\xd47\
6\x11|/\xc1\x84g2\x19\xca\xcb\xcb\xcdf>v\
\xec\xd8&\xbd\x7f\x0e.A,\x01\xd0\xd9\xd9\xa9\x0e\x1d\
:\xa4l!\x08Y\x10\xb6-\x1c\xc7\xc6BP\xb4\xcd\
\x1a\x1b\x00\xc7\xb2\x888\x96\xae\x02`Yx\x10\xc0\xdc\
\xdc\x1c555\x06 \x1a\x8dr\xe4\xc8\x91\xcd\xc0\x03\
\x88\x1b\x1a\xa2\xc7b\xb9\xb0mt0f\x8d\xcb#6\
\xb1\xa8\xa3\xc7,2\x8b\x1e\x93\x99\x1cc\xa9y\xee\xcc\
.\xe8\xdfEr\xf9<\xab\xc8,A6\x9b5\xa7f\
\xe9\xffm\x0e\x1c8\xb0\x1e\xe8\x00X\x06\xa0\xb4t\x16\
\x8e\x0d\xe1\x90\xc0S\x8a\xb1\xa4\xcb\x8d\x8c\x83\xd3\xb2\x97\
\xa6}\xaf\xb3\xb5\xe3\x17\xac\xdb\xfb:\x0d/\xb4s\xfb\
\xce$\xfd\xfd\xfd$\x93I\x94R\xe6\xfa\xf8\xf1\xe3\xe8\
\xba\xac3\xe7\xce\x9d\xe3\xe8\xd1\xa3\x1c>|\x98\xde\xde\
^\x12\x89\x84\x04,\xa1\x15\xdc\x01\xed\xff\xce\xe6\xf8\xe7\
\x94Ok\xc7\xcf\xf8\xe6/\xdf&\xf6\xf57\x99|\xa6\
\x83k\xfe.\xae\xf1-dk\x17\xad{\x7fN^V\
s\xfaog\xd1wM\xee\xdc\x9d\xe2\x1b\xafvr\xfd\
\xfau\x03\xa0gk\xd6?\x16\x8b\x99\xebx<\x8e\xe3\
8%8\x04\xc0#\x00\x96%\x98\xcaA:\xde\xca\xfe\
\xdf\xbdM\xd5\xae\xd7(\x84b\x08\xdbBY\x82lA\
r\x7ff\x91O\xeef\x18\xb8\xear\xfa\x1fad\xd5\
^\xae\x8f\xdcg2\xd7\xc6\x85\x0f\xee\x9b\x00\xed\x87\xa1\
\xcd\xcd\xcd\xb4\xb5\xb5\x19755\xa1\xa1\x14 \x83\x1f\
F\x16\xdcq\x15\xdf\xff\xe9o\xa8l\xd8H\xe2\xec;\
L\x8f^\xc3\x89\x94\xb1\xb5y\x07\x9b[\xb6\xf3Iy\
%c\x09\x97\xcff\xf2\xdc\x9d\xce2\xa1\xed\x88\x0dL\
'\xe7\xd8\xb7+\xca\xfa%\x003{=k\xea\xea\xea\
\x00\xccu*\x952\x00J+\x10\xa0\xb9Zp\xe1\x9d\
c(,\xca\xe6\xc6\xd9\x10\x8fR\x94\x92{\xc3}$\
e\x05\xdb\xda\x7fLM\xdb\xcb|<\x9cf\xd2_\xc0\
\xcdx,\xcck/x \x00\xb5t:B\xa1\x90\x09\
-\xdd\xea\x1f\x8e\x01*\xf8>`\xc1\xc6\xb8\xa0P\x1c\
#\x1c\x8bS\xb7\xa5\x96\x92xv}\x05\xe9\xac\xc7h\
\xff\x9f\x98\xae\xbcL\xcb\xf6\x83\xb8\x0ba\xbc\x82\xa4X\
\x94x\xda!\xc7B-\xaa\x80\xe3i\xa0\x96\xd5\x15\x01\
\x00\xd6\xc7C\x84\xca#\xfc\xbfjc!\x9e\xa9\x0cs\
\xe1\xdf\x83\xec\xd9\xf9\x13\xca\xa3\x0e\xb92G\x03(\x03\
ak\x00\x16K!\xa5\x1c%0*\x15\xa4\x5c\x05@\
X\xa5*\xcc\xf5#\xfapl\x86\xf1Y\x8f\xef\xfd\xfa\
\x8f\xdc\xca\xd4\xe0D\x5c\xa2\x11\x1b\xcf\x93\x14=\x07\xd3\
\x01\xa5\x90R\xf2PjY\x01V\x05\x10\x08L\x0d\x04\
\x18\x9dv\xf9\xd5_\x86\x18\xbd\xb7\x80=\x93g\xd3\xba\
2\xf2y_\xbbh\xea\xce\xaf\xd4p\xf9\xdd\xe0%\x00\
\x9ex\x09L\xb8\x10<\xa2\xd6/U\xf2\x87\x1f>\xcf\
\xf5O3D\x1b\xb7\xb1\xf3\xc5\x97Y\x12\x5cN`\x8e\
\xdbS\x01(\xc0\x12%\x00m\xd4R}\xb1\xb5\x96\xdd\
[\xe2t\xbf\x97\xa5j\xf7W\xf9\xd1\x1bo\x10\xa0\xb5\
\x03\x98\xb57\xd5\xd8\x08\x01\xd2\xcbSpSx\xf33\
\x14\xb3i\x0a\x19\x1f%\xfd\xd5\x82\xd6\x08\xf0\xf0)\xe7\
\xe3\xe73\x14\xe6u\xa8\x0e\xd6\x00\xcb\xf7\x89\x10\xc13\
}\xfa\xd7r\x8c\xb2\x137\x03\xc7\x01\xb2\x1e\xfe\xad\x94\
\xcco\xf7DT\x03\xd8_p\x07\x08\x92\x09\xfd\xd7=\
?\xfd~B\xa6\xcf\xdf\xf6\xef\x02\xeev;\xfc\x92\x06\
\xa8\xe3s\xcau]\x1fpW\xed\x00@2\xab\x0a\x1f\
~*\xd3\xbd\xb7\xfc\xd4\xcdi9\x05\xf4\x03\x97th\
\xbf\x10\xa2\xd3\xb6\xed\xaf}\x9e%XXX\xf0\x07\x06\
\x06\xd2'O\x9e\x9c\x06\xba\x83\x00>\x1aI\xca\xad\xe3\
\xb3*\xd7;\xe2\xa7nL\xcb\xd1R\xe8Y\x1dt\x8b\
\x00=\x09\xc0\xd0\xd0\x90\xdb\xd3\xd3\x93\xd2N\xcf\xce\xce\
\x9e.\xbd\x1d\xdf\x08\x02\xe8\xee\xea)\x00\x8c\x04\x84\x06\
\x85\xaf\x08055U\xd0/\x22\xa9S\xa7N%\xc7\
\xc7\xc7/\x03g\x81~\x1d\xec\xae\xb8\x09K\xdfv\xda\
O&\x85\x01@\x08@aZ\xfc\xde\xe0`\xba\xbb\xbb\
;\xa5\xdf\x8a\xcc$\xd0^\xeds\xcda\xed\x9aw3\
n\x11`p\xf0\xfdt___\xfa\xcc\x993\xa6\xc5\
\xa5\xd0\x8fx\x02\x89\xb5\x9ec!D\x18x\x13\xd8O\
is\x06\xb4\xf8\xb1\xfa\x1f\xbd\xfa*_\xf2\xd8\x15\x9d\
\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x04\xa3\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x045IDATX\xc3\xe5\
\x97\xcd\x8fTE\x14\xc5\x7f\xb7\xea\xd6{\xaf\xdbn\xc7\
\xf9@\x9d\x89FM4\x99D\x8d\x1aH\x98\xc4\x8c\x1f\
\x1b\xfe\x02L\x5c\xf1\x07\x18\x16.M\x5ckX\xc3\x8e\
\xc4\x8d\x1b\x17\xce\x82htA\x5c\x18\x0d\xe2\xc4\xc6\x00\
=`PQ\x19`\x02\xa2\x0e\x0c\x83\xd3\xfd^\xf7\x94\
\x8b\xaa\xee\xf9`\xe6\x0d\x84Q\x16VR\xa9\xce{\xb7\
\xeb\x9e:\xf7\xd4\xa9z\xea\xbd\xe7~6\xe5>\xb7>\
\x80]\xbbv\xbd\x03\xec\xfd\x8f\xf2N5\x1a\x8d\x03\xeb\
\x19\xd8\xbb\xef\xbd\xa3;\x1f\x1fv\x00\x9c<:\xcf\xcc\
\x977X\x9c\xef\xdcS\xa6\xda\xa0\xf2\xdck\x03\xbc\xb8\
g\x10\x80\x8b\x7f\x16|\xf8\xee\x1e\x80\xdb\x00p\xfc\xec\
\x1c\xdf?0\x04x.\xfd\xb8\xc0\xfe\xb7\xceo\xcbr\
\x0f\x1dy\x9a\x0b#\x96\xd3\x9f\x1fd\xfc\xd5}\x9bk\
@E\xb0\x16@xp,#\xcb\xb2m\x0100\x96\
a\x8dP\x1b|\x14#%\x22\x14+\xd8\x18\x91\xd5\x95\
s\xe7\xce\x83*\xb8\x04\xd2\x14\xb2\x0c\xd2,\x8cI\x0a\
I\x12\xdew:\x90\xe7\x90\xb7\xa1\xd5\x82v+\x8em\
(r\xb2\xfa8\xd6\x0a\xe3\xaf\xbcIk\xf1\xfa\xe6\x00\
\xac\x15\xac\x15\x04\xb0F\xd8\xbd{\xe7\x16k\xeb\x86\xae\
\x80Z\xa8V\x81\xeamQ\x8d\xaf\x04\xb5\x82\xf7\xa0\xa6\
\x84\x01g\x055\x82\x08\xa8\x0a\x95,\xc3# \x1e\x08\
\xc0\xf0\x1e/\x02\xde#\x12&\x15|\x88#\xc4!\x1e\
<!^@MX\x18@\xd7J\x89\x06\xac\xa0\xdac\
\x00\x9a3\xbf\x05\x8aS\x07i\x02\x95\x04\xb24\xf6\x04\
\x12\x07N\xa1\xe8@^@+\x8f\xbd\x05K9\xb4s\
\xc8\x0bT\x87q=\x00*\xe5%p1@\xd509\
\xf9\xd2\xd6\x0a\xf3>\xd0\xaf\x16\xaa\x1b\x8b\xf6\xd8'a\
a\xbd\x1c%% \x00\xf0\x81\x8d4M\xa3:\xc3\xb3\
\x98\x11\x89l\x07\xdac\x09V\x98_)F\xfca\xcd\
r\x7fa\x1d-\xd1\x80:\x09TI\x18O4/\xe0\
\x9d\x85\xc4!\x89\xc3g\x09\x92i\xd8\x11\x89\xe2\x13\x87\
X\x8b\xefv\x91\xbc\x80\xbc\x03\xed\x02\xdfj#\xed\x02\
\xf2\x02\x9fwP\x1dE\xd5 x:\xebTx\x9b\x06\
\x9c3x\x0f\x03\x8f$\xbc\xfe\xf2\xf3wh\xe86h\
\xa4\xbe\xf1\xeb\xc6\xfc\xdf\xb1\x04R^\x82DM_\x84\
\x8f\x0d\xa58\xe7\xb6\xc5\x88\x9e\x18K\xb9v\xb3\x03\x08\
\x9dR\x11\xaa\x90\xb8P\xefZ\xc50}\xb1\xcb@\xc5\
\xb0\x0e\xf4&\xadW\xf9U.\xe1\xe1\xc6\xd22\xf5\xcc\
p}\xc9\x84-\xe9J\x19\x10\x9c\x1a\xc0s\xe5f\x97\
+7\xbb\xacQW?\xd7\xaad~\xc5'\xa2)\xac\
\x05\x15\xc3\x9c\x0b\xb5w\xa6l\x17\xa8\xc1\xa9 \xc8\x1a\
5\xaf\x9b5\x1a\x8fY1\x9e\xfe{\xe9\xef\x14\x00\xf1\
\x82\xef\x9bX0+WV\x02U!\xd1\x90\xfc\xe7S\
\xdf\xf2\xeb\x99\x13,-\xde\xb8\xa7\xfaWj\x03<\xf5\
\xecN\x9eya\x02\x0f\xa83[1\x10\x03|\x87\xf7\
\xf7\xbf\xc1\xc2\xc2\x02\xb7n\xdd\xa2(\x0aD\x04k-\
\xd6ZT\x15U\xc59\x87\xaab\xad\xc5\x98\xf0\xdf\xe5\
\xe5e\xf2<\xef\xf7#\xcd\xf9\xb8\xf2-\x18pVP\
\x17\x18\xdc1:\xb6rO8~\x9c\xe9\xe9i\x8c1\
x\xef\x99\x98\x98`rr\xf2\x8eY\xd81:\xd6\xdf\
\x86\xae\xd4\x09Up6\xac\xa2V\xaf\xf7k933\
\xc3\xd0\xd0\x10\xd6Z\xbc\xf74\x9b\xcd\xbb\x02P\xab\xd7\
p\xd1\x88\xb4\xd4\x88\x14\x9c\x0b'\x5c\xa0*\x00\xa8V\
\xabdY\xd6\xa7\xb87\xdeis\x1a\xa9\x17AK\xad\
8\x1e\xc7\xbd#\xb4\xd7\x8c1\x88D\xdf\x8f:\xb8\xab\
\x9b\xaf5\xa8\x0d\xf3\xf6\x18.=\x8e\x83)m\xe3\xd5\
\xdb\x12\xa9\xf7\xe5Vl\xad\xf4\x91\x0e\x8e\x0c\xc3\xf2\xef\
\xdb\x02\xe0\xa1\x91a\xd4\xc2\xb5+\x97Y\x9c\xbf\xbe\x05\
\x036\xf8\xc0`\xad\x02\x0b\xdb\xc3\xc0P\xad\xc2\xec\xc5\
K\x9c\xfd\xee\x1b\xce\x9f\x9c\x9e\x03\xa66\x04`$^\
J\x05\x12\x0b\xed\x91'\xa9=\x0co\x1f8\xc8f\xc7\
\x81':\xf1*\xe75\x1e2\x81\x14(\xbap\xf9\xea\
U\xce4\x8e\xd1\xfc\xfa\x8b\xb9\xd9\x1fN\x1d\x02\x0eo\
\x08\xe0\xb3\x8f>\xe0\xa7\xd3'W\x99\xe9\xda\xa3\x86U\
\xe6\xbb\x1e\x04\x1b<_\x1do|w\xee\x8f\xd9_\x0e\
\x01\x87\x1b\x8d\xc6_\x1b\x01\x98\x9a\xfe\xf4\xe3\x7f\xf5s\
l}\xf25\x00\xe2\xb7\xda\x81\xff\xdd\xd7\xf1?M\xf0\
K\xb9\xe8F\x89\xaf\x00\x00\x00\x00IEND\xaeB\
`\x82\
"
qt_resource_name = b"\
\x00\x06\
\x07\x03}\xc3\
\x00i\
\x00m\x00a\x00g\x00e\x00s\
\x00\x08\
\x06\xc1Y\x87\
\x00o\
\x00p\x00e\x00n\x00.\x00p\x00n\x00g\
\x00\x07\
\x04\xcaW\xa7\
\x00n\
\x00e\x00w\x00.\x00p\x00n\x00g\
\x00\x08\
\x06|Z\x07\
\x00c\
\x00o\x00p\x00y\x00.\x00p\x00n\x00g\
\x00\x07\
\x0a\xc7W\x87\
\x00c\
\x00u\x00t\x00.\x00p\x00n\x00g\
\x00\x09\
\x0a\xa8\xbaG\
\x00p\
\x00a\x00s\x00t\x00e\x00.\x00p\x00n\x00g\
\x00\x08\
\x08\xc8Xg\
\x00s\
\x00a\x00v\x00e\x00.\x00p\x00n\x00g\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\x00\x02\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00(\x00\x00\x00\x00\x00\x01\x00\x00\x08\x1d\
\x00\x00\x01yCj\xf6\xed\
\x00\x00\x00<\x00\x00\x00\x00\x00\x01\x00\x00\x0bu\
\x00\x00\x01yCj\xf6\xec\
\x00\x00\x00\x12\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01yCj\xf6\xee\
\x00\x00\x00~\x00\x00\x00\x00\x00\x01\x00\x00\x1cS\
\x00\x00\x01yCj\xf6\xf0\
\x00\x00\x00f\x00\x00\x00\x00\x00\x01\x00\x00\x15\xe2\
\x00\x00\x01yCj\xf6\xee\
\x00\x00\x00R\x00\x00\x00\x00\x00\x01\x00\x00\x10\xb3\
\x00\x00\x01yCj\xf6\xed\
"
def qInitResources():
QtCore.qRegisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| 44.648604 | 96 | 0.710603 |
from PySide6 import QtCore
qt_resource_data = b"\
\x00\x00\x08\x19\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x07\xabIDATX\xc3\xad\
W[P\x93g\x1a\xf6\xca\xce\xec\xcc\xf6b/\xbc\xd9\
\xe9\xce\xecn\xbd\xda\xd9\x9b\xb5\xce\xba;{\xb0\xad\xcc\
z\xb1\xce\xce:\xb3vTpu\xdb\xe2\x81\xd6\xb6T\
\x04\xbb\xa5 m\xc1\x82\x06\x08\x07QB\x80\x80\x80\x02\
!\x81\x10\x92@H\x10s$!gr\x80\x04B \
\x9c\x09G\xb5Tx\xf6\xfb~\x13\x160X\x8b}g\
\x9e\xf9/\x92\xfc\xcf\xfb>\xcf\xfb\xbe\xdf\x97]\x00v\
\xfd\x98 \xf1\x0b\x82\x14\x02\x03\xc1u\x82\x03\xcf\xfd\xfe\
\x8fH\xbc\x9b \xe1W\xaf\xef\xb5*\x8c\xd6e\xdb\x02\
`\x19\x1e[\x09'\xf13\xfa\x19\x81\x22\xfc\xdc>v\
H~\x8a\xa0\xb9\xb6Y\x1c2\xcf\xadB9\xfe\x1dD\
\xf6Q\xd8\xc7\xe6\xe8\x87\x86={\xf6XSR\xae,\
\xca::\x10N\xe2\xe5I\xc3\xc41\x04\xb7>I\xf9\
,`\x9b]YSM\x03M\xb6\x114\xeb\xfb 1\
y`\x19\x9d\xc5\xbb\xef\xbe?\xc5\xab\xbe\x83\xf1\x89)\
LO\xcf\xae\x92\xef\xd7\xbct\x02\x11\x9f\x0f\xbe\x1d\xe3\
\xb2\x04CO\xb43@\x8b{\x06\xcd=.4\xeb\xec\
\xa8W\xf6 \x87S\x852^5C\xbc\xb0\xf4\x90\x81\
\xc1`\x5c&\xbfK|\xe1\x04H\x1c$8A\xfd\xdd\
\xeas'\xf1\xb9'\x04H\x87\x97\xc1\xd7\xbb \x22U\
7\xdc7\xa2\xb8N\x88,V>\xccV\xdb:q\x04\
,\x16k,\xfc\xce\xe7'\x10\x916\x93\x95?F}\
\xa5\xfe\x12\xc4o\xf4Y1\xb6\x02~\xef Z{\x9c\
\xe0?0\xa1L(CF\x0e\x1b\xb2\x0e\xf9&\xd2\xf9\
\xc5e\xcc-,!4\xbf\x88\xbd{\xf7Z\xc9;~\
\xbam\x02$~C\x90F=5\x13iu\xb3\x80\xd2\
?\x0f\xcb\xc4\xe2\x9aP\xa1Z\xb4l\xf1Y\xa0\xb6\xa0\
\xa6]\x8d/\xb2sq\xb7\x9e\xff\x0c1%\x9d\x09\xcd\
cbj\x06\x83C\x81'\xe4\xdd\xbc-\xd3\xb0;\x92\
\x033&\xd4S\xb5\xd3\xfbXO\x88\xc5\x03!\x88,\
CP\xbaF\xd0\xed\x09B\xe5\x9bB\x9bs\xfc\xa9\xcf\
Z\x1b\xee*t\xc8\xbc\xc9E\x09\xa7l\x93\xcf\x9b\x88\
'\xa7\x11\x18\x1d\xc3\x80o\x08\xa2\xd6\xd6%\xc2Q\xdb\
(\x12\x87\xc6\x1f\xaf\x82/b\x94M\x89$\x90\x22\xea\
R-\x9aB\xab\xe8\x18y\x04\xa1\xc5\xcf\x10St\xf6\
\x0d\xa3\xd3\xe1\x87\xd4<\x80\x16\xbd\x03\x0d]\x06\x14\xd5\
\x0a\x90\x91\x95\x0d/y\xf1\xc6\xaa\xa9\xd4\xb3s\x0bL\
\xc5\x94\xd8\xdd\xef\x85\xc9b\x05\xb7\xbc\x12\xa5\xe5\x95K\
\x13\xf3\xcb\xab#\x0f\x017\xd9\x11\xe6\xd9\x15\x84\x97\x15\
\x13\x06\xcb<\xd0h\xf2\xa3\xdd\xee_'\x96;\x86 \
\xb3x\xd7}\xe6\x08\xa4\xf8<3\x1b*\x8d6\xaa\xdc\
S3!\x8c\x8e\x8d3\x15\xd3&\xe47\x09\xf1\xc1\xc5\
\x8fQs\xaf\x01\xbee`\xfc\x11\xa0#\x13#\xf2\xce\
\xa1\xbe]\xb9\xb8Q\x01\x83\x81ttM\xa7\x1e\x0ag\
\x80\xa9\xb8\xdd\xea\x83\xd8\xe8B\x93\xca\xcc\xf8|\xe5\xcb\
,\x88\xda$Q\x89\xa7g\xe7\x18\x1b\x86\x86G`w\
8I\x82:$|\xf8!\xae\xb3\x0b\xe1\x99\x5c\x80o\
\x09\xd0\x90\xde\xe1\x0f,\x81\xab\x1f\xc4}\xef\x04\xdd\x07\
\x1da\xeb\xff\x9f\xc0\x1d\xb9\x16\x1d\xf6!H\xcc\xfdO\
}\xee\xd4\x22\x9dU\x84\xaa\x9a\xbaM>G\xe4\x8e\xf8\
<<\x12\x84\xd3\xdd\x0f\xbd\xc1\x88\xc2\xe2b\x9c~/\
\x1e=\x03\x01\xf4/\x02\x83\x84\xbc\xc5\xff-\xee:C\
(Q\x91\xf7\xf6\x05\xf1N\xdc\xbf}\x843i\xe3 \
\x18\xf43\xab\xe0\xc9Th58\xd1\xd8\xdd\x0b\x9eX\
\x89\xac\x5c\xf63>G\xaa\x9e\x9c\x9ee\xe4\xee\xf7\x0e\
\xa2\xd7lAC\x03\x1f'b\xe3 \xe9\xd6\xc0E\xcf\
\x01R\x90$\xb8\x86\xb2\x9e\x00n\xb4\xdbP\xd1\x1bD\
\x85\xce\x8bJ~\x0bm\xbe\x9b['\xd1\xa0\x99\xf8\x16\
e\x22\x05\xee)\xf4(\x13\xc8\x90x5\x0b\x1a\xad>\
\xaa\xdcc\x13\x93\xf0\x0d\x0d\xc3f\xef\x83\xb4]\x8e\xc4\
K\x97\x90\xc3\xca\xc3\xd4c\xc0NzI1N\xfa\x89\
\x94\x7f[;\x84|\x85\x13%j\x1fJ\xd5\x03\xe8\xf2\
0\xa3(\x22\xf8\xf93\x09t\x8f.\xa1\xa8\xbe\x15\xa5\
|\x09\xb2J*\xf0\xcf\xe3qQ\xe5\xf6\x07F\xd1\xe7\
\xf2@\xab7 \xfdj\x06\x92\xbfH\x83\xcd7\x02'\
\xa9\xda@\x1aL\xe0{\x88R\x9d\x1fE\xdd\xfd\x0cq\
A\x97\x1b\xc5\xdd\x1e\x88\x9cA\xfc\xf9\xcd\xb7]\x84\xeb\
l\xb4C\xd0(\xf7N#\xa7\xfc\x1e\xb2K\xab\xf1Q\
\xeaWH\xfeo\xea\xfaXQ\xb9G\x82\xe3\xf0\x0c\xf8\
`4\x99Q\xc9\xab\xc2\xfbg\xcfA\xfe@\x03?\xe9\
n\xb2\x8d\x19\xb9oi\x06\x19\xd2\x9b*/r\xe5\x0e\
\xe4u\xf6\xa1\xf0\xbe\x1b\x1c\x95\x1b\xf9\x9c\xca)\xc2S\
\xb8\xdd)\xdc+v\x04\x90Q\xc8\xc5\x95ky8\x11\
\x9f\x80\x9b\xb7n3c\x15\x91\xdbjs@\x22m\xc7\
\x85\x84\x0fPt\xbb\x0c\xf3+\x80\x9f4X\xf7$ \
\x1c|\x84J\xd3\x188\xfaa\x86\x9cV\xfdU\xb3\x1e\
\xac\x0e;\xb8:\x1f\xd9!\x1ez/\xe0\x13\xbc\xba]\
\x02&\xbe\xc1\x83\x94o\xd88\x9f\x9c\x8a\x03\x7f=\x04\
c\xaf\x99\xe9n*\xb7F\xd7\x83\xa4\xcb\xc9H\xff:\
\x8b\x8c\xd5<S\xb5q\xf6\xa9\xdc5\xf6i\x5c\x97Y\
\x19\xd9\xbfn!\xa7\xa0\xd4\x82t\xbe\x1aW\x9b4`\
\xc9\xcc\x10\xbb\x82\xf8\xe5\xaf_\xa7g\xc0;\xe1u\x1f\
5\xcc5\xddf|\x94\x96\x85\xb8s\x17\xf1\x97C1\
L\xd5t\x99\xf0\xaa\xaaq\xfa\xf4\x19h\xcc\x0e\x8c\x92\
-6\x14\x1e\xabZ\xc7\x0cx\xe6qp\x0d#L\xa3\
e\x8a\x0c\x8c\xec\xb4\xfa\x9c\xb6^\x94t9\xd0f\xf7\
\xaf\x1e=\x11KG.o\xc3y\x135,\x5c\x99\x1a\
\xf1\x97>\xc7\xd1\xd83\xf881\x09\x86^\x13\x1a\x9b\
\x04\xf8\xdd\x1b\xfbQO\xd4\xf1\x90\x99\xee\x9a\x00\xaa\xad\
\x93`+]\x0c9\xf5\xbc\xf0\xbeg\xbd\xea\xcc\x16=\
JU\x1e\x08m\x01\x94\xd4\xf1C\xe1eS@\xf0\xca\
\xf7%`+nj\xc7\xa9\x84D\xc4\x1c9\x8a\xdc|\
6ZZ\xc58\x14\x13\x83/95\xc8\x14j\x98\xe6\
\xa2\xd5\xd2'\xf5\x9azL\x13\xa1Id\xb7\x99\x90\xdb\
nF\xb9\xda\x8d\x06\xa5v9,9=\xf9N\x13\xec\
\xd9r\xd4G\x0d;\xabF\x88c\xff9\x8f\xdf\xee\xfb\
=\x1a\xf9\x02\x9c\xbf\x90\x80\x93\xf1\x17p\xa3\xad\x07\x19\
\xc4OJ\x14\xe9n\xbaX\xa8\xef,\xfa\x94\x98P(\
\xb7@\xe9\x0e<\xf9W\xec)*w-\xc1g\x04\xfb\
\xb6\xb9\xe4D\x8d\xbe\xcc\xb2Z\xfc\xe3\xe4\x19\x1c<\xf4\
7\xb0r\xf3\xb0\xef\xc0\x1fP \xd1!\x89'e*\
\xa6K\x85>\xbf!\xd5F\xe4.\x90[!\xb0\x0c\xae\
\xe5\xdc\xe2\xd2\x11\x13\x13\xe4\x87o<\xaf<\xe7\x96\x15\
5\x9ciE\xe5\xf8\xfb\xb1X\x1c?\x19\x877\xf6\xef\
\xc7\x8d:\x11\x92\xab\xa4\x0c!\xedp\xea5U!\x8b\
4[\xc9\x037*4n\xd4I:\x17\xc3rs\x08\
\x8em\x95\xfb\x87$\xe0Jesp\xe4\xf8)\x1c>\
|\x98\x8cc.2\x05*\x5c\x22\xd5\xd3]~M\xdc\
\x0b6\xe9tv\xa7\x1dw\x8c\xe4\x88\xb6\xf9\x9e\x84\xb7\
\x1a\x95\xfb\x22\xbdI\xfd\x80\x0bm\xf4\x042JxL\
\x0f\x9cKI\xc3\xb5\xa6.|\xc2me6Y\xf1\x83\
\x01\x5c\x97\x9a\xc1Q{ \xf3\x04\xd7\xce%&\x056\
\xc8\xfd\xc7\x9d\xc8\x1d\xd5\x82\xdc\x1a\x01\xce^NE\x81\
X\x85x\xf6]\x5c\xa9U\x90\xaa\xfb\xc0\x96\xdbP\xad\
u\xe3\xaeTA/\x10\xca\x0dr\xbf\xba\xd3j\xa3\x05\
\xb7\xa2Q\xf8\x1d\xafC\x8dO\xb9-\x88\xcb\xe6\xe1\x9a\
H\x8f\xaa\x1e/\x9a5\xe6\xc7\x7fz\xf3-Wx\xac\
\xa8\xdc\xaf\xbd\xac\xdc\xd1\xe2\x08\xdd\x05\x5cu\x1f\xde\xcb\
\xafE\xb9v\x002g`\xf5\xc2\xa7\x97\xa9\xdc\xf7\x08\
\xd2\xa9\xdc;\xf8\x03\xf3\xc2\xf1\x13\x82\xca\x1c\xee\x9dP\
\x0b9\x94\xb8\x0d\xc2\xc8\x16\xa3\x17\x87\xc3/\x22\xf7\x0e\
\xff\xdam\x8a\xdda\x99\xd5\x1b\xb6\xd8k\xbb^2\xbe\
/\x89\xff\x01f\xb9_\xfc\x11\x80=\xcf\x00\x00\x00\x00\
IEND\xaeB`\x82\
\x00\x00\x03T\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x02\xe6IDATX\xc3\xd5\
\x97\xcdN\x13a\x14\x86\xeb5\x94\x95{q\xe1\xd2\xc4\
\xe0\x05\xb8\xe2\x0e\x5c\xb8\xf4\x02\x5c\xb10\xea\x05\x18\x96\
&bX\xb8\xb0\x91X \xd1\x9d\xbf\x89\xa4\x14\xb1R\
\xa4HE\x94\xfe\xd0\x02C\xff\xa6\x9d\x19\xa6e\x80\xe3\
y{\xfa\x85QJ\x82\xc9!\x86I\xde\x9c3\xa7\xf3\
\xcd\xfb\x9c\xf3M\x9bN\x84\x88\x22\xffS\x91s\x01\xc0\
\xc7\xd5\x90n\xff\xa5\xfb\xac\xc7==d\x0d\xa9\x02\xf0\
12<<\xbcj4::\xba\x19V<\x1e\xaf&\
\x93\xc9V:\x9dv\x13\x89Dk`` \xcdkn\
h\x02\xa48\xd2\xe1\xe1q\x99\xba\xef\xb7\xc9\xb2,\xda\
\xdf\xdf'\x86\xf1x\xcd\x18\xeb\x8a\x1a@?\xf3\xb0\x1c\
\xc7\xa5Lf\xb9\x0b\x14\x04\x01\xc5b\xb1:\xaf{p\
\x1a\x88S\x01\x1c\x1c\x10ww\xb2l\xdb\xa1\xf9\xf9\xcf\
d\x0e\xd7u\xe9\xf9\xc4D\x17B\x05\x00&{\xc1\xc9\
\xaa7\x1cJ\xce\xcdS\xf8p]\x0f\x8b\x17T\x00\x82\
\x10@gO\x14\xce\xed\xa6G\x1fgf\xe9\xf5\x9b\xb7\
\x14\x9f\x9c\xa4\xa9\xa9iz\xf7\xfe\x03E\xa3\xd1e^\
\x7fA\x05\xc0\xef\x10\xed\xb6%\x86\x85\x9a\xe3\x05\x94]\
\xcd\xd1\xe4\xf4+z2\xfe\x94\x9e\xc5^\xd0Lb\x0e\
\x8b\x17U\x00\xda\x81\x18\xf5\x13 <\xff\x90j\xcd6\
\x157\xab\x94/nS\x89c\x8d\xb7\x85\xd7~Q\x01\
\xf0y\xcc\xcd]\x1e\xb5\xc7{\xdb\xee\x9f;\xbe\xe4\x88\
]\xb8\xbd\xee\xe2\x94\xca3\xe0u\xe4\xc6uWb\xd8\
\x109\xea\xe63D\xd4\x01\xa7\x06\xe0\xf4:\xad9\x22\
\x98\x98hr\x80\x98kPS\x9d\x00\x00*-\xb91\
\xe2NS\x8c\x10\x0d\x04\xf2m\xfb(\xb6|E\x00\x9b\
;\xdbj\xfci\x8e<l\x88\x1a\xae9\x13\x80:\x8f\
\xb7T#*\xd7\xc5\x04\x06\x06\x005(\x9c\x17\xab\xbc\
%\xbb\xca\x13\xc0Ma\x0e\x15*rn\xcc~Z\x02\
hj\xdd\xad\xf1\x94'\x00S\xdc\x1cqm[@`\
\x9a\xab\x1cu\x9e\xeb\x81A\x15G\x11\xc0j\x891\x0c\
\xd6w\x04 \x0cd&b\xb6iu\x8b\xa8\xaa\x09P\
\xb6\xc5\xbc\xd0\x03\xf8\xbe)c\x87)`\x0c\x18\x84\x1c\
\x00[ME\x00t\x03S\x98\xad\x94\xc5\x1c\xe7F\xe6\
\x1c\x00\xc8q]\xa9\xa1\x08\x80\xfd\xfcV\x12s3\x01\
\x085\x18B\xe8\xda|\x8e)\xa8N\x00[\x00\x03\xc8\
\x98g6\x04\x002\xe6\x85\xde\xf8\x17\x0b\xfc,\xd8\x8a\
\x00\x18g:O\xb4T\x14#\x98\x02\x00\x02\x0c>\xfb\
\xc5S(\xf0C\xb8fI\xf7k\xf9R\x87\xd7\xbeT\
\x01\xc8U\x8f\xbaN\xadK\x0e\x90\xaf\x85\xde\xb7\xc2\x92\
=O\xa6\xb3\xde\xa3\xb1q\xeb\xda\xd0\xf5\x15\x98\xb3n\
\xa9\x00l4\xa4k\x18\xff\xe0\x11\x7fZ\x17S\xd4\x13\
\x0bYo\xe4\xee\xbd\xe2\xa5\xc1\xcbK|m\x8cu\x87\
5\xa8\xfa\xb7\x1c\xdde\xd9<\x8f\x1f\x19\xfe\x9e\xcf\x1e\
7\xbd\xc9\xbax&oF\x00h\xf2\xff\x81\x99\x94\x9e\
\xe9?\xbf\x19\x01B\xd3\xf4\xfc\xbd\x9c\x9e\xa5~\x03Q\
l%\xa1\x92\x95\x0aw\x00\x00\x00\x00IEND\xae\
B`\x82\
\x00\x00\x05:\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x04\xccIDATX\xc3\xb5\
\x97]L[e\x1c\xc6wo\xbc\xd9\xe5\x12I q\
\xd7&\xe3N\x13\xb8p\xd1\x85D\xbdP\xe3\x10\x18\xe5\
+.&J\x04'\x86\xaa\x8b\x99\xe0\xd0\xa2l\x19\x86\
9\x17\xdc\x1a\x16\x98\x80@l\xa6C\xca +\x83\x1e\
(\xcc\xda\xd1\x96\xd2\xd2J{\xfa\x01\xa5\xd0\xef\x16\x1e\
\xdf\xff\xdb\x1d\xc7\xcc\x04*\x87\x93<9o!\x9c\xe7\
\xf7<\xefG\x0f\x87\x00\x1c\xcaF\xcf\xbd\xfa\xe9\xbbL\
Z&a\x0fj`\xca\xd9\xe9y\xd9\x9a?]P\xf2\
\xa5\xc1\xe9\x8f\xa7W\xc3@0\x02\x84\xa2\x19\xad\xc72\
\x8a'\x81X\x22s\xbfyk\xdaK\x10r\x02\x1c{\
\xe7\xac\xda\x1c\xd8\xc8\x98\x12@\x84\x99\x85\xe3\x19\x911\
)\x1aKa%\x94D8\x9aBs\x87\xc6\xbe\x13\xc4\
\xff\x02\x90\x12\x93y$\xf1\xc8X\x92\xcf\x1f\x84]\x8c\
\xc2\xe5\x09\x22\x12K\xa3\xf4\xc3\xefM4uY\x01\xb0\
\xeb\xd86\xd5\x90\x9e:\xfc\xcc\xb9\xe7_.\x11?V\
\x9eEEU\x0d*\x99\xde\xaf\xad\xc3\x9d\xb1\x89\xc7\x00\
\xac\xb6%\xfc\xb9\xe8\x87k\x15X\xf6\x04\x10\x08\xc6\xd2\
\xaf\x9c\xbep\x9fA\x1c\xd9\x15\x80]\x87\x99\x1a\x8a\x8a\
\x8a\xcc\x92Z[[\xdd\xa4\xafU\xad\xfe\xafT\xdf\xa6\
\x06\x06\x06195\x85\xd9\xb99\xe8&&PPP\
\x80!\xcdo|\xdeI\xa6\xf9\x05\xcc\x98\x5c\x1c\xc0\xe1\
OA\xf4\x85\xf0C\xaf\xce\xcd\x00j\xf6\x02PCf\
\xd8\xe5\x8a\xc7\xe3\xf0z\xbdH\xa7\xd3\x98\x9c\x9cDe\
e5fg\x8d\xbc\x81\x07f\x1bt\xd3\x16\x0e@2\
-x\xf0\xdd\x8dQ\x8f\xac\x00\xe1p\x18F\xa3\x91\x8f\
S\xa9\x14~\xea\xedE\xe3'\x9fa\x86A8\x96\xdc\
Pwu\xe3LC#\xce5\x9d\xc7\xed\x91q\x5c\xbc\
>,/\xc0\xc6\xc6\x06\xf4z\xfdc@}}\xfdP\
2\x88\xd0F\x1cf\x9b\x0b\x82\xc1\x88\xa9\x19\x13\xac\x0e\
\x11\x97\xbadn\x80\x00\xa6\xd8:\xd8~E\x22\x11\x94\
+*0\xae\x13@\xe7\x04mW\xda\xaa4\xbe|S\
\xe65@f:\x9d\x0e\xc3\xc3\xc3\xe8e\xf5\xf7\xf7\xf7\
C\xab\xd5\xa2\xaa\xba\x06cw\xf5\x90\x0e*w\x90\xed\
\x04\xb6\x0e\xda\xbbe\x06\xa0y\xb7\xdb\xed\x18\x1a\x1aB\
gg'zzz8PIi\x19ni\xf5\x10\xd7\
\x00o\x08\xb0\xf9\x00g\x00\xb8\xd0%3\xc0\xd6\xd6\x16\
\xdf\x09\x81@\x00\xa2(\xc2\xef\xf7cmm\x0d\xa7\x14\
\x95\xd0\xfc\xae\xe7\xa9\xc9|\xc1\x0b\x98=@\x9b\xdc\x00\
\xdbA677\xf9v\xa4V\x14\x15\xd5\xe8\xfbU\xe0\
\xa9\x1d\x81G\x00\xe7;\x0f\x00\x80\xcc%\x80$3O\
$\x12(+\xaf\xe2\x00\x7f\xb8\x00\x8b\x98\x01\xa06Z\
\xd5\x070\x05\xff\x98'\x93<=MI\xc9\xa9J\x0e\
\xa0\xb7\xb3\x03\x89=\xc5\xf8\x170\xb1\x00|q\xf5\x00\
\x00\xa4\xea\xc9\x98\x14\x8b\xc5P\xa6\xa8\x82zH\xc0\x98\
\x19\xb8k\x05\xe6\x9c\x99\xfb\xe7Wd\x04\x90\xd2Sj\
\x02\x88F\xa3\xdc<\x14\x0a\xa1\xb8\xb4\x02\xd7\x06\x05\xdc\
f\x87\xe4\xa0\x01\x1cd\xc4\x04(;d\x06H=\x9c\
s\x12\x99\xd3\xb9@ \xc5eU\xb8\xd8-\xa0\x7f:\
c\xae}\x90i\xe0\xa3v\x99\x00\xfe]=\xa5&\xad\
\xae\xaer\x88\xb7J*p\xb9W\xc0=\x1b\xb8~\x9e\
\x01\xee\xcc\x03g.\xed\x13@\xaa\x9dD\x8b\x8e\x92\xd3\
qL\xdf\x01+++X__\xe7\x10'Y\x03\xdf\
t\x09PO\x00\xbf\xcce\x1a\xb82\x064\xec\xa7\x01\
\xc9X\xda\xebdNi)9\x1dD\x04@\xf5\xd3\xcf\
\xde|[\x81\x96\xeb\x02O~u\x1c\xb8q\x0f\xf8q\
,\x9e~\xbdNm\xa67\xaa\xac\x00\x9ed,m7\
2%\x00\xd1#\xf2\xe4\x12\xcc\x1b'\x15h\xef\x11\xa0\
\xbcf[\x7fO5\xe2<q\x9a\xbf\x8ei\xf7\xfcJ\
&\x01\x90\xa9$i\xb5SB2\x0f\x06\x83p\xb9\x5c\
\xdc\x90^J\xe8\xb3\xc7\xe3\x81\xdb\xed\xc6\xf1\x13\xaf%\
\x9f}\xa1\x9cL;\x98\x8a\x99\x8e>\xc9xG\x00\x95\
J\xc5\x01\xa4\x15.\xcd7\x19RR:\xf7)\xb5\xc3\
\xe1\xe0\x22\xe3\xc5\xc5E\x0e\xf5\xe2\xf1\x97\x5c\xf4\x1e\xb9\
\x93\xe9\xae\x00---n\xe9`\xa1\xd4\xd2\x97\x0d\x8d\
\x97\x97\x97\xe1\xf3\xf9`\xb3\xd9\xf8}ii\x89C\x10\
\x00\x8d\x0b\x0b\x0b\xcd\xb2\x00\xd0\xa2\x92R\x93\x11\x8d\xe9\
N\xdfxT;5`\xb5Zy\xf5\xd4\x0a\xfd\xce`\
0$\xf2\xf2\xf2\xee\xb3g\x1c\xd9\x17@SS\x93[\
\x9agJO\x22\x13\xaa\x9a\xc6\x16\x8b\x997@\x9fG\
GG#mmm\xde\xfc\xfc|\x13\xfb\xdbA\xa6\xb2\
\xbd\x9a\xff'@ss3\x9f\x02JG\x10T?U\
???\xcf\xeb\xd6h4\x91\xba\xba:\xe7\xc3\xb4]\
L\x1f0\x1d\xcd\xc6xG\x00\xa5R\xe9v:\x9d\xbc\
bJJo>\x94\xb4\xbe\xbe\xde\x99\x93\x93#\x99\x16\
gSuV\x00\x8d\x8d\x8dn\x8b\xc5\x82\x81\x81\x81H\
mm\xad377WV\xd3\xdd\x00\xf8\x7fFL\xc2\
A\x99n\xd7\xdfC9V\x18\x85p\xc8\x04\x00\x00\x00\
\x00IEND\xaeB`\x82\
\x00\x00\x05+\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x04\xbdIDATX\xc3\xed\
WkL\x93W\x18>#q\xc92\xe9\x16\x97\xa8T\
e8\x9d\x02\x15\xf6\x03\x872\x93\x01f,[p\xc4\
0\xff`\xa2.\x1a:\x1dN\x03\xba1\x89[\xb3\x80\
\xd9\x0c\x84\x02\x19X\x1c\x14\x8b\x85\xb2\x82\x95^\xe4f\
\x0b\x8e1\xf8\xc3F\xcb-\x81\x15\xdc\xa8\xc2\x1c\x1b\xb7\
ji\x91\xf2\xee\xbc\x87\xaf\x0c\xdc\xb8\x0da\xd9\xb2\x93\
<\xed\x97\xf3}\xfd\xde\xe7\xbc\xef\xf3^J\x00\x80\xfc\
\x93 \xff\x0a\x02t\x09(D\x14\xd9\x14q\x14\x01+\
F\x80\xae\xddd\xdd\xc6f\x22L\xf8\x95\xc4\x8bG\xc8\
\xa1\xd3\xf7\xc8\x8e\x97;82a+A \x85\x9c\xbe\
0H.\xdd\x80\x19@2\xabyM\xf4\xbe\xfbr\x13\
hd\x06\x91\x04^\xa3Q\xf4\x06\xee\x85G\xf5\xd0\xbd\
\x83\xcbM \x9b\x9d\xf6@t/\xbd\x162= \x89\
?H\xa5,\x1b\x01\x8c1y\xc1\xbb\x9d\x88K\xc6\xd7\
\xc6&\x0e\xa0\x10\xb9\xfdB\xfe\xc5+6F\x8c\x12\x5c\
N\x02\x93\xa7\xa7\xa7\x0d\xcc\xd39\xb9\x98c6\x14\x0a\
\xd2\xe4\xa3+A \x8c)\x9e*\xdf7G\xeb\xdc{\
\xb5\xcc\x89\x9e@D\x96T\x83+,\x0b6FH\x08\
\x13\xf5d*{.T\x03\x01\xf8\x037\xbf\xc0\x0e4\
*T\xdfb\x88R\xd5,X\x03t\x1d\x16\x08\x04z\
EU\xf5\xc8\xa0mt\xc2\xd4s\xf7!\xbesQ\x95\
\x90\xae\x8f\xd0\x13\xcf\xe5\x94\x83\x87\xb4\x02\x9e\xcc.\x03\
\xd4\x06\xdd\xaf\x99\xcb\xb0\xaf\xaf\xaf>\xbf\xd2`\xb5\xdb\
\xed\x80\xf8y\xe4>\xc4^\xab\xb4\xb9\x88/\x86\x80'\
\xd3\xc0g\xf9\x8e\x19\xf5`\xd7^3\xbav\xdas\xee\
h\xd8\xc7\xc7G\x9f\xab\xab\xb0\x0e\x0f\x0d\xc1\x10\x87\xb2\
\xf6.\xe7\x967\xf7wsa\xd8\xbd\xe8^\x80/f\
\x9a\xa0\x86\xdf\xa96B\xf7\xf0\x03\xd8\x19\x9f\xd4\xcf\xa5\
\xe7\x1a\x8a\x98-~\xfem\x97T\x1ak__\x1f\xb8\
\xd0\xd1s\x07br\x15VN\xc4\x87\x97\xd4\x8c0\x14\
\xe9\x15\xb7\x1e8\x1c\x0e@\xa4\xd6\x191\x9e\x85\x9b\x05\
~m\xa9%\x1a[\x97\xd9\x0c\xe6.\x0a\xf3$\x14\xdf\
6\x8e{\xbd\x1e\xd1\xcdB\xc8\x09o\xa9\x04<\xd1\xbd\
V\xab\x15\x10w\x7f\x1b\x84\xf3\x92\x5c\xbbR\xa9\x84\xfa\
\xfaz0\x99L\x0cu\xdf5\xc1Q\xb1d\x18\xc9Q\
D>\xb6v\xcc\xb4@O\x93_~\xd3\xd6\xdf\xdf\x0f\
2\x99\x0cD\x22\x11\xa8T*\x90J\xa5\xa0\xd1h \
K[9\xbe\xe9\x95\xe0\x1f\xb8S\xafy,\xf3\x00\x97\
\x8e\x22\x9e\xc7\x86\xe6S)\x19\xf6\x82\x82\x02\xe6\xe2\xa0\
\xa0 \xe0\xf1x`\xb1X@[^\x01\xfb\xcf&\x0c\
-\xa6S\xceg\x94\xcf\x09L\x83\xe2[{\xe6\xc2`\
\x9a\xb2\x14\x14\x0a\x05\x88\xc5b\xc8\xcc\xcc\x84\xa2\xa2\x22\
P\xab\xd5\xd0\xd9\xd9\xc9`\xec\xfe\xc9\xb9\xc9\xdb\xa7u\
.\xb7\xcfK\x80\xae\xb7\xd8)p\x0e\xc0j\x97\xacx\
\x88\xca\x7f\x82\xe2)\x89\x0e>\x97+![\x96\x0f\x07\
c\xe3G\x84\x1f&\xd8\x92rd\x8eo\x1a\xbf\x07\xa3\
\xd1\x08-\xad-\xf0\xcb\xc0 \x1c8\xf1\xbe\x05\xb3b\
\xc1\x04\x5ci\x84\x85\x85\x84F\xdc&\xe72\xac,\xcf\
3\xb5\x13\xec;\xe3\xba\xd33\xaf\x82\xe5\xfez\x89\x06\
\x9e\xde\xfcb\x1b\xf7<\x92\x8d{f\xabO[\xca5\
\xedXCC=444\x80\xa5\xb7\x172\x14\xc5\xc3\
\xf3\xe9\xc0e<\x92\xe5(\x9e6]\xe5\x9c*2x\
}\xf4\x83.Zl\x121\x0c\x1b%\xeaq\xf7/\xcb\
'\xef\x05\x87_\xfe\xd3\xe4D\x0bLh\xf4\xc9>u\
\x95\x1e\x0c\x06\x03\xb4\xb7\xb7\xc3\xd7\xc6\x961\xae\x81\x09\
f\xf16m8h<I::e\xf8b\x81\x83D\
\xbdWC\xb6\x0a^\x9b*\xc3\x94\x5c\xb0B\x0f\xab$\
\xb4\x04\x9fJ\xaa\x9bC71(\xd4O\xf2\x0a\xc7t\
:\x1d\xd4\xd6\xd6\x82\xc9|\xdb\xb9a\x9b\xf7_\xeab\
\xb2\xe5~\x9cu\x1f\x0d\xf3\xb2\xd4N\xf2\xf6\xb1\xeb.\
\xb6\xae\x94\xc3\x90l\x97U\xc1KW\xab\x80\x9cMn\
Z\xd0\x1cI\xbd\xb1\xe7\x88\xb0\xef\xcaW\xc5PZZ\
\x0a\x1d?\xf6L\x04\x06\x87t<\xaa\x0b\xc2\x84F\x8d\
\x07\xc8o\x02\xd9\xf9\xaa~\x9a\xf10F\x8e6 \xaf\
\xbcJxCi\x00\x92(\x1d\x98\xcd\x95\xb3y\xc3}\
=\xbf\xf9Dj\xa6].\x97CSK+D\x1c{\
\xf7\xce\xf4\x14%\xae\xf1\x8a\xf5w\x9c\xf5p\x02\xc2\xd9\
\x0f\x89\xd1\x81\x03O\x8e\xf7\xdc\xd2i\xe7\xf3\xdfu\xfc\
o\x14.6\xd2\xef\xd8\x17iI\xbe,\x9d\xc8\xd3\x96\
;\xa7\x0f1\x8c%\xc6\xdf\x9f\xbaw_q5\xa0A\
l\xb5\x08\x8c\xf9\x94\xf1\xe0\xf03K\x9a|h\x13Z\
\xbd\xce\xa3\xd9kOH\xf7\x0c\x0f\xb0\x0f\xfe\xf3\x87\xc8\
\xf9/\xee\xb9In\x00\xf6{>\xed\xf7\x08\x1e*>\
]\xe5X\xaa\xf1GZ\xf5\xb6Y\x0b\x11\x1d\xb3C\xc9\
\x918\x099\xf9\xa9\x96!\xfa\x5c\x1a\x0d\xcf\xb3\xff\xff\
7\xfcO\x13\xf8\x1d\xe7\x87\x19\xb9D\xc3\x01\xcf\x00\x00\
\x00\x00IEND\xaeB`\x82\
\x00\x00\x06m\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x064IDATx^\xad\x97[lT\xc7\
\x1d\xc6\x7fs\xce\xd9\x8b\xbd\xf6\xfa\x16\xa0\xbe\x00\x0e\xb2\
ic$BJ!\x22\xa1-\x95b\xa5/\xeeKh\
+\x95\xa6U\xa5\xc6`U\xaa\xda\xb4\xaa\xfaV\x09U\
\xca\x03\x94'\xda\x07\x84\x14)\xad\xc4\x8b\xa5R\x83y\
\x08\xc5\x189\x0ei\xd3\x84\x9a\x9bcj\xec\xb2\x04\x1b\
;\xbb\xf6z\x8f\xbd\xbb\xde\xb3g\xa6\xc3h\x85\xe5r\
l\x88\xc9'}\xfa\x9f\x9d\x87\xfd~\xf3\x9f\x99s\x11\
J)\x82$\x84x\x05x\x9e\xc7kH)\xf5w\xd6\
(' \xb8C\xbb\x01h\x97R\xbe\xc6cdY\xd6\
\x07\x1a\xf6\xbb@\xb7\x069\xff\x14\x00&\xfc\xb7\xed\xf5\
\xe2`]DDn\xce\x89\x8a+W\xaeP]S\x8d\
@\x00\xa0P\x08e(A)f\xd3i^\xa9\x17/\
\xbc\xb4Nl;\xf1\x1f\xb9G\x83|[CL<M\
\x07\xf6\xff`\x8b\xdd,%\xf8J2<<Lee\
%+\xc9u]\x1e\xc0n\xa9\xb0\x22\x1b\xa2*r?\
\xa7\xea\x81\xb5\x03\x08-\x05H\xa1\x0d\xf4]\xbcH.\
\x97\xc3/\x16QJ\x91\xcf\xe7Y\x5c\x5c\xa4P(P\
\xd4c\xb5\xb5\xb5\x94\x01X\x80\xf8\x82\xf6\x80\x01\x006\
D\x05\x1f\x0f\xbcK>;\x8f\x85D\x952\xe2\xb6\xc4\
\xb6\x04!!p>Sl\x8c;\x80D*\x04\xf0\x9c\
\x10\x02\xe0\xcb@\x05P\x0f4`\xc4Hi\x9f$\x02\
\x01N\x9c8!\x00\x81\x05\xd2\x87\x96\x96g\x09em\
\x14\xe5(\xa5\xb4A\x08XW\x19%\xe2\xd8DB\x16\
\xc3\x13s\x5c\xbc=A\xf7X\x8e\x5c$\xbe\xa9\xbd}\
\xf7\xef-\xcbZ\xdc\xb1cGYUU\x95\xd3\xd8\xd8\
\x18~\xe0\x86\x86\x86\xd0\xa5K\x97\xdc\xae\xae\xae\x08\xf0\
\xd6\xaa\x1d\x00\x13DU,\xc2s\xd51\xf2\x9eO\xa1\
(\x91Ja\x09A\xd8\xb1\x88\x86l\xe6r\x05\x12\xa2\
\x8e?\x9f\xff+\x0dM\x1b\x01\x22\xc0f\x96\x84\xef\xfb\
x\x9eGuu\xb5\x9ePK\xf4\xea\xd5\xab\x87\x84\x10\
(\xa5\xdeZ\x11\xc0\xb2A\x00\xb6-\x90\xda\xb6\x148\
\x08\xa4\x12X\xc2\x8c\x1b\x8fL\xb9\xec{\xf5;\xd47\
6\x11|/\xc1\x84g2\x19\xca\xcb\xcb\xcdf>v\
\xec\xd8&\xbd\x7f\x0e.A,\x01\xd0\xd9\xd9\xa9\x0e\x1d\
:\xa4l!\x08Y\x10\xb6-\x1c\xc7\xc6BP\xb4\xcd\
\x1a\x1b\x00\xc7\xb2\x888\x96\xae\x02`Yx\x10\xc0\xdc\
\xdc\x1c555\x06 \x1a\x8dr\xe4\xc8\x91\xcd\xc0\x03\
\x88\x1b\x1a\xa2\xc7b\xb9\xb0mt0f\x8d\xcb#6\
\xb1\xa8\xa3\xc7,2\x8b\x1e\x93\x99\x1cc\xa9y\xee\xcc\
.\xe8\xdfEr\xf9<\xab\xc8,A6\x9b5\xa7f\
\xe9\xffm\x0e\x1c8\xb0\x1e\xe8\x00X\x06\xa0\xb4t\x16\
\x8e\x0d\xe1\x90\xc0S\x8a\xb1\xa4\xcb\x8d\x8c\x83\xd3\xb2\x97\
\xa6}\xaf\xb3\xb5\xe3\x17\xac\xdb\xfb:\x0d/\xb4s\xfb\
\xce$\xfd\xfd\xfd$\x93I\x94R\xe6\xfa\xf8\xf1\xe3\xe8\
\xba\xac3\xe7\xce\x9d\xe3\xe8\xd1\xa3\x1c>|\x98\xde\xde\
^\x12\x89\x84\x04,\xa1\x15\xdc\x01\xed\xff\xce\xe6\xf8\xe7\
\x94Ok\xc7\xcf\xf8\xe6/\xdf&\xf6\xf57\x99|\xa6\
\x83k\xfe.\xae\xf1-dk\x17\xad{\x7fN^V\
s\xfaog\xd1wM\xee\xdc\x9d\xe2\x1b\xafvr\xfd\
\xfau\x03\xa0gk\xd6?\x16\x8b\x99\xebx<\x8e\xe3\
8%8\x04\xc0#\x00\x96%\x98\xcaA:\xde\xca\xfe\
\xdf\xbdM\xd5\xae\xd7(\x84b\x08\xdbBY\x82lA\
r\x7ff\x91O\xeef\x18\xb8\xear\xfa\x1fad\xd5\
^\xae\x8f\xdcg2\xd7\xc6\x85\x0f\xee\x9b\x00\xed\x87\xa1\
\xcd\xcd\xcd\xb4\xb5\xb5\x19755\xa1\xa1\x14 \x83\x1f\
F\x16\xdcq\x15\xdf\xff\xe9o\xa8l\xd8H\xe2\xec;\
L\x8f^\xc3\x89\x94\xb1\xb5y\x07\x9b[\xb6\xf3Iy\
%c\x09\x97\xcff\xf2\xdc\x9d\xce2\xa1\xed\x88\x0dL\
'\xe7\xd8\xb7+\xca\xfa%\x003{=k\xea\xea\xea\
\x00\xccu*\x952\x00J+\x10\xa0\xb9Zp\xe1\x9d\
c(,\xca\xe6\xc6\xd9\x10\x8fR\x94\x92{\xc3}$\
e\x05\xdb\xda\x7fLM\xdb\xcb|<\x9cf\xd2_\xc0\
\xcdx,\xcck/x \x00\xb5t:B\xa1\x90\x09\
-\xdd\xea\x1f\x8e\x01*\xf8>`\xc1\xc6\xb8\xa0P\x1c\
#\x1c\x8bS\xb7\xa5\x96\x92xv}\x05\xe9\xac\xc7h\
\xff\x9f\x98\xae\xbcL\xcb\xf6\x83\xb8\x0ba\xbc\x82\xa4X\
\x94x\xda!\xc7B-\xaa\x80\xe3i\xa0\x96\xd5\x15\x01\
\x00\xd6\xc7C\x84\xca#\xfc\xbfjc!\x9e\xa9\x0cs\
\xe1\xdf\x83\xec\xd9\xf9\x13\xca\xa3\x0e\xb92G\x03(\x03\
ak\x00\x16K!\xa5\x1c%0*\x15\xa4\x5c\x05@\
X\xa5*\xcc\xf5#\xfapl\x86\xf1Y\x8f\xef\xfd\xfa\
\x8f\xdc\xca\xd4\xe0D\x5c\xa2\x11\x1b\xcf\x93\x14=\x07\xd3\
\x01\xa5\x90R\xf2PjY\x01V\x05\x10\x08L\x0d\x04\
\x18\x9dv\xf9\xd5_\x86\x18\xbd\xb7\x80=\x93g\xd3\xba\
2\xf2y_\xbbh\xea\xce\xaf\xd4p\xf9\xdd\xe0%\x00\
\x9ex\x09L\xb8\x10<\xa2\xd6/U\xf2\x87\x1f>\xcf\
\xf5O3D\x1b\xb7\xb1\xf3\xc5\x97Y\x12\x5cN`\x8e\
\xdbS\x01(\xc0\x12%\x00m\xd4R}\xb1\xb5\x96\xdd\
[\xe2t\xbf\x97\xa5j\xf7W\xf9\xd1\x1bo\x10\xa0\xb5\
\x03\x98\xb57\xd5\xd8\x08\x01\xd2\xcbSpSx\xf33\
\x14\xb3i\x0a\x19\x1f%\xfd\xd5\x82\xd6\x08\xf0\xf0)\xe7\
\xe3\xe73\x14\xe6u\xa8\x0e\xd6\x00\xcb\xf7\x89\x10\xc13\
}\xfa\xd7r\x8c\xb2\x137\x03\xc7\x01\xb2\x1e\xfe\xad\x94\
\xcco\xf7DT\x03\xd8_p\x07\x08\x92\x09\xfd\xd7=\
?\xfd~B\xa6\xcf\xdf\xf6\xef\x02\xeev;\xfc\x92\x06\
\xa8\xe3s\xcau]\x1fpW\xed\x00@2\xab\x0a\x1f\
~*\xd3\xbd\xb7\xfc\xd4\xcdi9\x05\xf4\x03\x97th\
\xbf\x10\xa2\xd3\xb6\xed\xaf}\x9e%XXX\xf0\x07\x06\
\x06\xd2'O\x9e\x9c\x06\xba\x83\x00>\x1aI\xca\xad\xe3\
\xb3*\xd7;\xe2\xa7nL\xcb\xd1R\xe8Y\x1dt\x8b\
\x00=\x09\xc0\xd0\xd0\x90\xdb\xd3\xd3\x93\xd2N\xcf\xce\xce\
\x9e.\xbd\x1d\xdf\x08\x02\xe8\xee\xea)\x00\x8c\x04\x84\x06\
\x85\xaf\x08055U\xd0/\x22\xa9S\xa7N%\xc7\
\xc7\xc7/\x03g\x81~\x1d\xec\xae\xb8\x09K\xdfv\xda\
O&\x85\x01@\x08@aZ\xfc\xde\xe0`\xba\xbb\xbb\
;\xa5\xdf\x8a\xcc$\xd0^\xeds\xcda\xed\x9aw3\
n\x11`p\xf0\xfdt___\xfa\xcc\x993\xa6\xc5\
\xa5\xd0\x8fx\x02\x89\xb5\x9ec!D\x18x\x13\xd8O\
is\x06\xb4\xf8\xb1\xfa\x1f\xbd\xfa*_\xf2\xd8\x15\x9d\
\x00\x00\x00\x00IEND\xaeB`\x82\
\x00\x00\x04\xa3\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00 \x00\x00\x00 \x08\x06\x00\x00\x00szz\xf4\
\x00\x00\x00\x04gAMA\x00\x00\xd6\xd8\xd4OX2\
\x00\x00\x00\x19tEXtSoftware\
\x00Adobe ImageRead\
yq\xc9e<\x00\x00\x045IDATX\xc3\xe5\
\x97\xcd\x8fTE\x14\xc5\x7f\xb7\xea\xd6{\xaf\xdbn\xc7\
\xf9@\x9d\x89FM4\x99D\x8d\x1aH\x98\xc4\x8c\x1f\
\x1b\xfe\x02L\x5c\xf1\x07\x18\x16.M\x5ckX\xc3\x8e\
\xc4\x8d\x1b\x17\xce\x82htA\x5c\x18\x0d\xe2\xc4\xc6\x00\
=`PQ\x19`\x02\xa2\x0e\x0c\x83\xd3\xfd^\xf7\x94\
\x8b\xaa\xee\xf9`\xe6\x0d\x84Q\x16VR\xa9\xce{\xb7\
\xeb\x9e:\xf7\xd4\xa9z\xea\xbd\xe7~6\xe5>\xb7>\
\x80]\xbbv\xbd\x03\xec\xfd\x8f\xf2N5\x1a\x8d\x03\xeb\
\x19\xd8\xbb\xef\xbd\xa3;\x1f\x1fv\x00\x9c<:\xcf\xcc\
\x977X\x9c\xef\xdcS\xa6\xda\xa0\xf2\xdck\x03\xbc\xb8\
g\x10\x80\x8b\x7f\x16|\xf8\xee\x1e\x80\xdb\x00p\xfc\xec\
\x1c\xdf?0\x04x.\xfd\xb8\xc0\xfe\xb7\xceo\xcbr\
\x0f\x1dy\x9a\x0b#\x96\xd3\x9f\x1fd\xfc\xd5}\x9bk\
@E\xb0\x16@xp,#\xcb\xb2m\x0100\x96\
a\x8dP\x1b|\x14#%\x22\x14+\xd8\x18\x91\xd5\x95\
s\xe7\xce\x83*\xb8\x04\xd2\x14\xb2\x0c\xd2,\x8cI\x0a\
I\x12\xdew:\x90\xe7\x90\xb7\xa1\xd5\x82v+\x8em\
(r\xb2\xfa8\xd6\x0a\xe3\xaf\xbcIk\xf1\xfa\xe6\x00\
\xac\x15\xac\x15\x04\xb0F\xd8\xbd{\xe7\x16k\xeb\x86\xae\
\x80Z\xa8V\x81\xeamQ\x8d\xaf\x04\xb5\x82\xf7\xa0\xa6\
\x84\x01g\x055\x82\x08\xa8\x0a\x95,\xc3# \x1e\x08\
\xc0\xf0\x1e/\x02\xde#\x12&\x15|\x88#\xc4!\x1e\
<!^@MX\x18@\xd7J\x89\x06\xac\xa0\xdac\
\x00\x9a3\xbf\x05\x8aS\x07i\x02\x95\x04\xb24\xf6\x04\
\x12\x07N\xa1\xe8@^@+\x8f\xbd\x05K9\xb4s\
\xc8\x0bT\x87q=\x00*\xe5%p1@\xd509\
\xf9\xd2\xd6\x0a\xf3>\xd0\xaf\x16\xaa\x1b\x8b\xf6\xd8'a\
a\xbd\x1c%% \x00\xf0\x81\x8d4M\xa3:\xc3\xb3\
\x98\x11\x89l\x07\xdac\x09V\x98_)F\xfca\xcd\
r\x7fa\x1d-\xd1\x80:\x09TI\x18O4/\xe0\
\x9d\x85\xc4!\x89\xc3g\x09\x92i\xd8\x11\x89\xe2\x13\x87\
X\x8b\xefv\x91\xbc\x80\xbc\x03\xed\x02\xdfj#\xed\x02\
\xf2\x02\x9fwP\x1dE\xd5 x:\xebTx\x9b\x06\
\x9c3x\x0f\x03\x8f$\xbc\xfe\xf2\xf3wh\xe86h\
\xa4\xbe\xf1\xeb\xc6\xfc\xdf\xb1\x04R^\x82DM_\x84\
\x8f\x0d\xa58\xe7\xb6\xc5\x88\x9e\x18K\xb9v\xb3\x03\x08\
\x9dR\x11\xaa\x90\xb8P\xefZ\xc50}\xb1\xcb@\xc5\
\xb0\x0e\xf4&\xadW\xf9U.\xe1\xe1\xc6\xd22\xf5\xcc\
p}\xc9\x84-\xe9J\x19\x10\x9c\x1a\xc0s\xe5f\x97\
+7\xbb\xacQW?\xd7\xaad~\xc5'\xa2)\xac\
\x05\x15\xc3\x9c\x0b\xb5w\xa6l\x17\xa8\xc1\xa9 \xc8\x1a\
5\xaf\x9b5\x1a\x8fY1\x9e\xfe{\xe9\xef\x14\x00\xf1\
\x82\xef\x9bX0+WV\x02U!\xd1\x90\xfc\xe7S\
\xdf\xf2\xeb\x99\x13,-\xde\xb8\xa7\xfaWj\x03<\xf5\
\xecN\x9eya\x02\x0f\xa83[1\x10\x03|\x87\xf7\
\xf7\xbf\xc1\xc2\xc2\x02\xb7n\xdd\xa2(\x0aD\x04k-\
\xd6ZT\x15U\xc59\x87\xaab\xad\xc5\x98\xf0\xdf\xe5\
\xe5e\xf2<\xef\xf7#\xcd\xf9\xb8\xf2-\x18pVP\
\x17\x18\xdc1:\xb6rO8~\x9c\xe9\xe9i\x8c1\
x\xef\x99\x98\x98`rr\xf2\x8eY\xd81:\xd6\xdf\
\x86\xae\xd4\x09Up6\xac\xa2V\xaf\xf7k933\
\xc3\xd0\xd0\x10\xd6Z\xbc\xf74\x9b\xcd\xbb\x02P\xab\xd7\
p\xd1\x88\xb4\xd4\x88\x14\x9c\x0b'\x5c\xa0*\x00\xa8V\
\xabdY\xd6\xa7\xb87\xdeis\x1a\xa9\x17AK\xad\
8\x1e\xc7\xbd#\xb4\xd7\x8c1\x88D\xdf\x8f:\xb8\xab\
\x9b\xaf5\xa8\x0d\xf3\xf6\x18.=\x8e\x83)m\xe3\xd5\
\xdb\x12\xa9\xf7\xe5Vl\xad\xf4\x91\x0e\x8e\x0c\xc3\xf2\xef\
\xdb\x02\xe0\xa1\x91a\xd4\xc2\xb5+\x97Y\x9c\xbf\xbe\x05\
\x036\xf8\xc0`\xad\x02\x0b\xdb\xc3\xc0P\xad\xc2\xec\xc5\
K\x9c\xfd\xee\x1b\xce\x9f\x9c\x9e\x03\xa66\x04`$^\
J\x05\x12\x0b\xed\x91'\xa9=\x0co\x1f8\xc8f\xc7\
\x81':\xf1*\xe75\x1e2\x81\x14(\xbap\xf9\xea\
U\xce4\x8e\xd1\xfc\xfa\x8b\xb9\xd9\x1fN\x1d\x02\x0eo\
\x08\xe0\xb3\x8f>\xe0\xa7\xd3'W\x99\xe9\xda\xa3\x86U\
\xe6\xbb\x1e\x04\x1b<_\x1do|w\xee\x8f\xd9_\x0e\
\x01\x87\x1b\x8d\xc6_\x1b\x01\x98\x9a\xfe\xf4\xe3\x7f\xf5s\
l}\xf25\x00\xe2\xb7\xda\x81\xff\xdd\xd7\xf1?M\xf0\
K\xb9\xe8F\x89\xaf\x00\x00\x00\x00IEND\xaeB\
`\x82\
"
qt_resource_name = b"\
\x00\x06\
\x07\x03}\xc3\
\x00i\
\x00m\x00a\x00g\x00e\x00s\
\x00\x08\
\x06\xc1Y\x87\
\x00o\
\x00p\x00e\x00n\x00.\x00p\x00n\x00g\
\x00\x07\
\x04\xcaW\xa7\
\x00n\
\x00e\x00w\x00.\x00p\x00n\x00g\
\x00\x08\
\x06|Z\x07\
\x00c\
\x00o\x00p\x00y\x00.\x00p\x00n\x00g\
\x00\x07\
\x0a\xc7W\x87\
\x00c\
\x00u\x00t\x00.\x00p\x00n\x00g\
\x00\x09\
\x0a\xa8\xbaG\
\x00p\
\x00a\x00s\x00t\x00e\x00.\x00p\x00n\x00g\
\x00\x08\
\x08\xc8Xg\
\x00s\
\x00a\x00v\x00e\x00.\x00p\x00n\x00g\
"
qt_resource_struct = b"\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x06\x00\x00\x00\x02\
\x00\x00\x00\x00\x00\x00\x00\x00\
\x00\x00\x00(\x00\x00\x00\x00\x00\x01\x00\x00\x08\x1d\
\x00\x00\x01yCj\xf6\xed\
\x00\x00\x00<\x00\x00\x00\x00\x00\x01\x00\x00\x0bu\
\x00\x00\x01yCj\xf6\xec\
\x00\x00\x00\x12\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
\x00\x00\x01yCj\xf6\xee\
\x00\x00\x00~\x00\x00\x00\x00\x00\x01\x00\x00\x1cS\
\x00\x00\x01yCj\xf6\xf0\
\x00\x00\x00f\x00\x00\x00\x00\x00\x01\x00\x00\x15\xe2\
\x00\x00\x01yCj\xf6\xee\
\x00\x00\x00R\x00\x00\x00\x00\x00\x01\x00\x00\x10\xb3\
\x00\x00\x01yCj\xf6\xed\
"
def qInitResources():
QtCore.qRegisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x03, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
| true | true |
f72696fc0cf591521dd786bc37d9a5424a0b4f8b | 298 | py | Python | tests/test_singleton_container.py | ClanPlay/Python_IoC | fad7a3053a7a2193474caa5918508307cfd7b79a | [
"MIT"
] | 4 | 2019-02-20T19:44:32.000Z | 2019-02-22T13:32:25.000Z | tests/test_singleton_container.py | ClanPlay-Market/clanplay_Python_IoC | fad7a3053a7a2193474caa5918508307cfd7b79a | [
"MIT"
] | 1 | 2019-02-20T14:48:04.000Z | 2019-02-20T14:48:23.000Z | tests/test_singleton_container.py | ClanPlay/Python_IoC | fad7a3053a7a2193474caa5918508307cfd7b79a | [
"MIT"
] | null | null | null | from flying_ioc import IocManager
class TSingleton1:
def __init__(self):
pass
def test_singleton_container():
ioc = IocManager(stats=True)
ioc.set_class(name='singleton1', cls=TSingleton1, singleton=True)
assert ioc.singleton1 is ioc.singleton1
ioc.print_stats()
| 17.529412 | 69 | 0.721477 | from flying_ioc import IocManager
class TSingleton1:
def __init__(self):
pass
def test_singleton_container():
ioc = IocManager(stats=True)
ioc.set_class(name='singleton1', cls=TSingleton1, singleton=True)
assert ioc.singleton1 is ioc.singleton1
ioc.print_stats()
| true | true |
f72698682f1d9db8336712cdc43ed2619483c604 | 1,583 | py | Python | 61dust.py | krikor-s/homework | 63c6711fe0ea64f5d3087673ac931dd0503be546 | [
"MIT"
] | null | null | null | 61dust.py | krikor-s/homework | 63c6711fe0ea64f5d3087673ac931dd0503be546 | [
"MIT"
] | null | null | null | 61dust.py | krikor-s/homework | 63c6711fe0ea64f5d3087673ac931dd0503be546 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# 61dust.py
import argparse
from fileinput import filename
import mcb185 as mcb
# Write a program that finds and masks low entropy sequence
# Use argparse for the following parameters
# sequence file
# window size
# entropy threshold
# lowercase or N-based masking
# The program should output a FASTA file (but with Ns or lowercase)
# Use argparse
# Use the mcb185.read_fasta() function
# Put more functions in your mcb185.py library
parser = argparse.ArgumentParser(description='Outputs of masked low entropy sequence.')
# required arguments
parser.add_argument('--fasta', required=True, type=str,
metavar='<str>', help='required FASTA file')
parser.add_argument('--wins', required=True, type=int,
metavar='<int>', help='required window size')
parser.add_argument('--ethresh', required=True, type=float,
metavar='<float>', help='required entropy threshold')
# switches
parser.add_argument('--lowercase', action='store_true',
help='lowercase or N based masking. N-based default')
# finalization
arg = parser.parse_args()
file = arg.fasta
wins = arg.wins
ethresh = arg.ethresh
lcase = arg.lowercase
for name, seq in mcb.read_fasta(file):
seq = seq.upper()
#create mask sequence
output = ''
for i in range(0, len(seq)-wins+1, 1):
prob = mcb.ntprobs(seq[i:i+wins])
entropy = mcb.e_calc(prob)
if entropy > ethresh:
output += seq[i]
else:
if lcase:
output += seq[i].lower()
else:
output += 'n'
output += seq[-wins+1:]
#output fasta file
print(f'>{name}')
for i in range(0, len(output), 60):
print(output[i:i+60]) | 28.267857 | 87 | 0.713834 |
import argparse
from fileinput import filename
import mcb185 as mcb
parser = argparse.ArgumentParser(description='Outputs of masked low entropy sequence.')
parser.add_argument('--fasta', required=True, type=str,
metavar='<str>', help='required FASTA file')
parser.add_argument('--wins', required=True, type=int,
metavar='<int>', help='required window size')
parser.add_argument('--ethresh', required=True, type=float,
metavar='<float>', help='required entropy threshold')
parser.add_argument('--lowercase', action='store_true',
help='lowercase or N based masking. N-based default')
arg = parser.parse_args()
file = arg.fasta
wins = arg.wins
ethresh = arg.ethresh
lcase = arg.lowercase
for name, seq in mcb.read_fasta(file):
seq = seq.upper()
output = ''
for i in range(0, len(seq)-wins+1, 1):
prob = mcb.ntprobs(seq[i:i+wins])
entropy = mcb.e_calc(prob)
if entropy > ethresh:
output += seq[i]
else:
if lcase:
output += seq[i].lower()
else:
output += 'n'
output += seq[-wins+1:]
print(f'>{name}')
for i in range(0, len(output), 60):
print(output[i:i+60]) | true | true |
f726986d83879eef6d553b88636ef538361fe2f9 | 14,545 | py | Python | qa/rpc-tests/dip4-coinbasemerkleroots.py | Wildfire-new/Wildfire-MN-POW | 0434339c79fa8525408b8edd1ff003be4f367e1c | [
"MIT"
] | 1 | 2021-01-22T17:22:27.000Z | 2021-01-22T17:22:27.000Z | qa/rpc-tests/dip4-coinbasemerkleroots.py | Wildfire-new/Wildfire-MN-POW | 0434339c79fa8525408b8edd1ff003be4f367e1c | [
"MIT"
] | 4 | 2020-12-01T01:38:47.000Z | 2021-01-21T19:19:57.000Z | qa/rpc-tests/dip4-coinbasemerkleroots.py | Wildfire-new/Wildfire-MN-POW | 0434339c79fa8525408b8edd1ff003be4f367e1c | [
"MIT"
] | 1 | 2021-08-25T06:44:01.000Z | 2021-08-25T06:44:01.000Z | #!/usr/bin/env python3
# Copyright (c) 2015-2018 The Dash Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from collections import namedtuple
from test_framework.mininode import *
from test_framework.test_framework import WildfireTestFramework
from test_framework.util import *
from time import *
'''
dip4-coinbasemerkleroots.py
Checks DIP4 merkle roots in coinbases
'''
class TestNode(SingleNodeConnCB):
def __init__(self):
SingleNodeConnCB.__init__(self)
self.last_mnlistdiff = None
def on_mnlistdiff(self, conn, message):
self.last_mnlistdiff = message
def wait_for_mnlistdiff(self, timeout=30):
self.last_mnlistdiff = None
def received_mnlistdiff():
return self.last_mnlistdiff is not None
return wait_until(received_mnlistdiff, timeout=timeout)
def getmnlistdiff(self, baseBlockHash, blockHash):
msg = msg_getmnlistd(baseBlockHash, blockHash)
self.send_message(msg)
self.wait_for_mnlistdiff()
return self.last_mnlistdiff
class LLMQCoinbaseCommitmentsTest(WildfireTestFramework):
def __init__(self):
super().__init__(6, 5, [], fast_dip3_enforcement=True)
def run_test(self):
self.test_node = TestNode()
self.test_node.add_connection(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node))
NetworkThread().start() # Start up network handling in another thread
self.test_node.wait_for_verack()
self.confirm_mns()
null_hash = format(0, "064x")
# Check if a diff with the genesis block as base returns all MNs
expectedUpdated = [mn.proTxHash for mn in self.mninfo]
mnList = self.test_getmnlistdiff(null_hash, self.nodes[0].getbestblockhash(), {}, [], expectedUpdated)
expectedUpdated2 = expectedUpdated + []
# Register one more MN, but don't start it (that would fail as WildfireTestFramework doesn't support this atm)
baseBlockHash = self.nodes[0].getbestblockhash()
self.prepare_masternode(self.mn_count)
new_mn = self.mninfo[self.mn_count]
# Now test if that MN appears in a diff when the base block is the one just before MN registration
expectedDeleted = []
expectedUpdated = [new_mn.proTxHash]
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
assert(mnList[new_mn.proTxHash].confirmedHash == 0)
# Now let the MN get enough confirmations and verify that the MNLISTDIFF now has confirmedHash != 0
self.confirm_mns()
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
assert(mnList[new_mn.proTxHash].confirmedHash != 0)
# Spend the collateral of the previously added MN and test if it appears in "deletedMNs"
expectedDeleted = [new_mn.proTxHash]
expectedUpdated = []
baseBlockHash2 = self.nodes[0].getbestblockhash()
self.remove_mastermode(self.mn_count)
mnList = self.test_getmnlistdiff(baseBlockHash2, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
# When comparing genesis and best block, we shouldn't see the previously added and then deleted MN
mnList = self.test_getmnlistdiff(null_hash, self.nodes[0].getbestblockhash(), {}, [], expectedUpdated2)
#############################
# Now start testing quorum commitment merkle roots
self.nodes[0].generate(1)
oldhash = self.nodes[0].getbestblockhash()
# Test DIP8 activation once with a pre-existing quorum and once without (we don't know in which order it will activate on mainnet)
self.test_dip8_quorum_merkle_root_activation(True)
for n in self.nodes:
n.invalidateblock(oldhash)
self.sync_all()
first_quorum = self.test_dip8_quorum_merkle_root_activation(False)
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
# Verify that the first quorum appears in MNLISTDIFF
expectedDeleted = []
expectedNew = [QuorumId(100, int(first_quorum, 16))]
quorumList = self.test_getmnlistdiff_quorums(null_hash, self.nodes[0].getbestblockhash(), {}, expectedDeleted, expectedNew)
baseBlockHash = self.nodes[0].getbestblockhash()
second_quorum = self.mine_quorum()
# Verify that the second quorum appears in MNLISTDIFF
expectedDeleted = []
expectedNew = [QuorumId(100, int(second_quorum, 16))]
quorums_before_third = self.test_getmnlistdiff_quorums(baseBlockHash, self.nodes[0].getbestblockhash(), quorumList, expectedDeleted, expectedNew)
block_before_third = self.nodes[0].getbestblockhash()
third_quorum = self.mine_quorum()
# Verify that the first quorum is deleted and the third quorum is added in MNLISTDIFF (the first got inactive)
expectedDeleted = [QuorumId(100, int(first_quorum, 16))]
expectedNew = [QuorumId(100, int(third_quorum, 16))]
self.test_getmnlistdiff_quorums(block_before_third, self.nodes[0].getbestblockhash(), quorums_before_third, expectedDeleted, expectedNew)
# Verify that the diff between genesis and best block is the current active set (second and third quorum)
expectedDeleted = []
expectedNew = [QuorumId(100, int(second_quorum, 16)), QuorumId(100, int(third_quorum, 16))]
self.test_getmnlistdiff_quorums(null_hash, self.nodes[0].getbestblockhash(), {}, expectedDeleted, expectedNew)
# Now verify that diffs are correct around the block that mined the third quorum.
# This tests the logic in CalcCbTxMerkleRootQuorums, which has to manually add the commitment from the current
# block
mined_in_block = self.nodes[0].quorum("info", 100, third_quorum)["minedBlock"]
prev_block = self.nodes[0].getblock(mined_in_block)["previousblockhash"]
prev_block2 = self.nodes[0].getblock(prev_block)["previousblockhash"]
next_block = self.nodes[0].getblock(mined_in_block)["nextblockhash"]
next_block2 = self.nodes[0].getblock(mined_in_block)["nextblockhash"]
# The 2 block before the quorum was mined should both give an empty diff
expectedDeleted = []
expectedNew = []
self.test_getmnlistdiff_quorums(block_before_third, prev_block2, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, prev_block, quorums_before_third, expectedDeleted, expectedNew)
# The block in which the quorum was mined and the 2 after that should all give the same diff
expectedDeleted = [QuorumId(100, int(first_quorum, 16))]
expectedNew = [QuorumId(100, int(third_quorum, 16))]
quorums_with_third = self.test_getmnlistdiff_quorums(block_before_third, mined_in_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, next_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, next_block2, quorums_before_third, expectedDeleted, expectedNew)
# A diff between the two block that happened after the quorum was mined should give an empty diff
expectedDeleted = []
expectedNew = []
self.test_getmnlistdiff_quorums(mined_in_block, next_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(mined_in_block, next_block2, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block, next_block2, quorums_with_third, expectedDeleted, expectedNew)
# Using the same block for baseBlockHash and blockHash should give empty diffs
self.test_getmnlistdiff_quorums(prev_block, prev_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(prev_block2, prev_block2, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(mined_in_block, mined_in_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block, next_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block2, next_block2, quorums_with_third, expectedDeleted, expectedNew)
def test_getmnlistdiff(self, baseBlockHash, blockHash, baseMNList, expectedDeleted, expectedUpdated):
d = self.test_getmnlistdiff_base(baseBlockHash, blockHash)
# Assert that the deletedMNs and mnList fields are what we expected
assert_equal(set(d.deletedMNs), set([int(e, 16) for e in expectedDeleted]))
assert_equal(set([e.proRegTxHash for e in d.mnList]), set(int(e, 16) for e in expectedUpdated))
# Build a new list based on the old list and the info from the diff
newMNList = baseMNList.copy()
for e in d.deletedMNs:
newMNList.pop(format(e, '064x'))
for e in d.mnList:
newMNList[format(e.proRegTxHash, '064x')] = e
cbtx = CCbTx()
cbtx.deserialize(BytesIO(d.cbTx.vExtraPayload))
# Verify that the merkle root matches what we locally calculate
hashes = []
for mn in sorted(newMNList.values(), key=lambda mn: ser_uint256(mn.proRegTxHash)):
hashes.append(hash256(mn.serialize()))
merkleRoot = CBlock.get_merkle_root(hashes)
assert_equal(merkleRoot, cbtx.merkleRootMNList)
return newMNList
def test_getmnlistdiff_quorums(self, baseBlockHash, blockHash, baseQuorumList, expectedDeleted, expectedNew):
d = self.test_getmnlistdiff_base(baseBlockHash, blockHash)
assert_equal(set(d.deletedQuorums), set(expectedDeleted))
assert_equal(set([QuorumId(e.llmqType, e.quorumHash) for e in d.newQuorums]), set(expectedNew))
newQuorumList = baseQuorumList.copy()
for e in d.deletedQuorums:
newQuorumList.pop(e)
for e in d.newQuorums:
newQuorumList[QuorumId(e.llmqType, e.quorumHash)] = e
cbtx = CCbTx()
cbtx.deserialize(BytesIO(d.cbTx.vExtraPayload))
if cbtx.version >= 2:
hashes = []
for qc in newQuorumList.values():
hashes.append(hash256(qc.serialize()))
hashes.sort()
merkleRoot = CBlock.get_merkle_root(hashes)
assert_equal(merkleRoot, cbtx.merkleRootQuorums)
return newQuorumList
def test_getmnlistdiff_base(self, baseBlockHash, blockHash):
hexstr = self.nodes[0].getblockheader(blockHash, False)
header = FromHex(CBlockHeader(), hexstr)
d = self.test_node.getmnlistdiff(int(baseBlockHash, 16), int(blockHash, 16))
assert_equal(d.baseBlockHash, int(baseBlockHash, 16))
assert_equal(d.blockHash, int(blockHash, 16))
# Check that the merkle proof is valid
proof = CMerkleBlock(header, d.merkleProof)
proof = proof.serialize().hex()
assert_equal(self.nodes[0].verifytxoutproof(proof), [d.cbTx.hash])
# Check if P2P messages match with RPCs
d2 = self.nodes[0].protx("diff", baseBlockHash, blockHash)
assert_equal(d2["baseBlockHash"], baseBlockHash)
assert_equal(d2["blockHash"], blockHash)
assert_equal(d2["cbTxMerkleTree"], d.merkleProof.serialize().hex())
assert_equal(d2["cbTx"], d.cbTx.serialize().hex())
assert_equal(set([int(e, 16) for e in d2["deletedMNs"]]), set(d.deletedMNs))
assert_equal(set([int(e["proRegTxHash"], 16) for e in d2["mnList"]]), set([e.proRegTxHash for e in d.mnList]))
assert_equal(set([QuorumId(e["llmqType"], int(e["quorumHash"], 16)) for e in d2["deletedQuorums"]]), set(d.deletedQuorums))
assert_equal(set([QuorumId(e["llmqType"], int(e["quorumHash"], 16)) for e in d2["newQuorums"]]), set([QuorumId(e.llmqType, e.quorumHash) for e in d.newQuorums]))
return d
def test_dip8_quorum_merkle_root_activation(self, with_initial_quorum):
if with_initial_quorum:
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
# Mine one quorum before dip8 is activated
self.mine_quorum()
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 4070908800)
self.wait_for_sporks_same()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert(cbtx["cbTx"]["version"] == 1)
assert(self.nodes[0].getblockchaininfo()["bip9_softforks"]["dip0008"]["status"] != "active")
while self.nodes[0].getblockchaininfo()["bip9_softforks"]["dip0008"]["status"] != "active":
self.nodes[0].generate(4)
self.sync_all()
self.nodes[0].generate(1)
sync_blocks(self.nodes)
# Assert that merkleRootQuorums is present and 0 (we have no quorums yet)
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert_equal(cbtx["cbTx"]["version"], 2)
assert("merkleRootQuorums" in cbtx["cbTx"])
merkleRootQuorums = int(cbtx["cbTx"]["merkleRootQuorums"], 16)
if with_initial_quorum:
assert(merkleRootQuorums != 0)
else:
assert_equal(merkleRootQuorums, 0)
set_mocktime(get_mocktime() + 1)
set_node_times(self.nodes, get_mocktime())
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
# Mine quorum and verify that merkleRootQuorums has changed
quorum = self.mine_quorum()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert(int(cbtx["cbTx"]["merkleRootQuorums"], 16) != merkleRootQuorums)
return quorum
def confirm_mns(self):
while True:
diff = self.nodes[0].protx("diff", 1, self.nodes[0].getblockcount())
found_unconfirmed = False
for mn in diff["mnList"]:
if int(mn["confirmedHash"], 16) == 0:
found_unconfirmed = True
break
if not found_unconfirmed:
break
self.nodes[0].generate(1)
sync_blocks(self.nodes)
if __name__ == '__main__':
LLMQCoinbaseCommitmentsTest().main()
| 48.645485 | 169 | 0.691097 |
from collections import namedtuple
from test_framework.mininode import *
from test_framework.test_framework import WildfireTestFramework
from test_framework.util import *
from time import *
class TestNode(SingleNodeConnCB):
def __init__(self):
SingleNodeConnCB.__init__(self)
self.last_mnlistdiff = None
def on_mnlistdiff(self, conn, message):
self.last_mnlistdiff = message
def wait_for_mnlistdiff(self, timeout=30):
self.last_mnlistdiff = None
def received_mnlistdiff():
return self.last_mnlistdiff is not None
return wait_until(received_mnlistdiff, timeout=timeout)
def getmnlistdiff(self, baseBlockHash, blockHash):
msg = msg_getmnlistd(baseBlockHash, blockHash)
self.send_message(msg)
self.wait_for_mnlistdiff()
return self.last_mnlistdiff
class LLMQCoinbaseCommitmentsTest(WildfireTestFramework):
def __init__(self):
super().__init__(6, 5, [], fast_dip3_enforcement=True)
def run_test(self):
self.test_node = TestNode()
self.test_node.add_connection(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node))
NetworkThread().start()
self.test_node.wait_for_verack()
self.confirm_mns()
null_hash = format(0, "064x")
expectedUpdated = [mn.proTxHash for mn in self.mninfo]
mnList = self.test_getmnlistdiff(null_hash, self.nodes[0].getbestblockhash(), {}, [], expectedUpdated)
expectedUpdated2 = expectedUpdated + []
baseBlockHash = self.nodes[0].getbestblockhash()
self.prepare_masternode(self.mn_count)
new_mn = self.mninfo[self.mn_count]
expectedDeleted = []
expectedUpdated = [new_mn.proTxHash]
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
assert(mnList[new_mn.proTxHash].confirmedHash == 0)
self.confirm_mns()
mnList = self.test_getmnlistdiff(baseBlockHash, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
assert(mnList[new_mn.proTxHash].confirmedHash != 0)
expectedDeleted = [new_mn.proTxHash]
expectedUpdated = []
baseBlockHash2 = self.nodes[0].getbestblockhash()
self.remove_mastermode(self.mn_count)
mnList = self.test_getmnlistdiff(baseBlockHash2, self.nodes[0].getbestblockhash(), mnList, expectedDeleted, expectedUpdated)
mnList = self.test_getmnlistdiff(null_hash, self.nodes[0].getbestblockhash(), {}, [], expectedUpdated2)
#############################
# Now start testing quorum commitment merkle roots
self.nodes[0].generate(1)
oldhash = self.nodes[0].getbestblockhash()
# Test DIP8 activation once with a pre-existing quorum and once without (we don't know in which order it will activate on mainnet)
self.test_dip8_quorum_merkle_root_activation(True)
for n in self.nodes:
n.invalidateblock(oldhash)
self.sync_all()
first_quorum = self.test_dip8_quorum_merkle_root_activation(False)
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
expectedDeleted = []
expectedNew = [QuorumId(100, int(first_quorum, 16))]
quorumList = self.test_getmnlistdiff_quorums(null_hash, self.nodes[0].getbestblockhash(), {}, expectedDeleted, expectedNew)
baseBlockHash = self.nodes[0].getbestblockhash()
second_quorum = self.mine_quorum()
expectedDeleted = []
expectedNew = [QuorumId(100, int(second_quorum, 16))]
quorums_before_third = self.test_getmnlistdiff_quorums(baseBlockHash, self.nodes[0].getbestblockhash(), quorumList, expectedDeleted, expectedNew)
block_before_third = self.nodes[0].getbestblockhash()
third_quorum = self.mine_quorum()
expectedDeleted = [QuorumId(100, int(first_quorum, 16))]
expectedNew = [QuorumId(100, int(third_quorum, 16))]
self.test_getmnlistdiff_quorums(block_before_third, self.nodes[0].getbestblockhash(), quorums_before_third, expectedDeleted, expectedNew)
expectedDeleted = []
expectedNew = [QuorumId(100, int(second_quorum, 16)), QuorumId(100, int(third_quorum, 16))]
self.test_getmnlistdiff_quorums(null_hash, self.nodes[0].getbestblockhash(), {}, expectedDeleted, expectedNew)
mined_in_block = self.nodes[0].quorum("info", 100, third_quorum)["minedBlock"]
prev_block = self.nodes[0].getblock(mined_in_block)["previousblockhash"]
prev_block2 = self.nodes[0].getblock(prev_block)["previousblockhash"]
next_block = self.nodes[0].getblock(mined_in_block)["nextblockhash"]
next_block2 = self.nodes[0].getblock(mined_in_block)["nextblockhash"]
expectedDeleted = []
expectedNew = []
self.test_getmnlistdiff_quorums(block_before_third, prev_block2, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, prev_block, quorums_before_third, expectedDeleted, expectedNew)
expectedDeleted = [QuorumId(100, int(first_quorum, 16))]
expectedNew = [QuorumId(100, int(third_quorum, 16))]
quorums_with_third = self.test_getmnlistdiff_quorums(block_before_third, mined_in_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, next_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(block_before_third, next_block2, quorums_before_third, expectedDeleted, expectedNew)
expectedDeleted = []
expectedNew = []
self.test_getmnlistdiff_quorums(mined_in_block, next_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(mined_in_block, next_block2, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block, next_block2, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(prev_block, prev_block, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(prev_block2, prev_block2, quorums_before_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(mined_in_block, mined_in_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block, next_block, quorums_with_third, expectedDeleted, expectedNew)
self.test_getmnlistdiff_quorums(next_block2, next_block2, quorums_with_third, expectedDeleted, expectedNew)
def test_getmnlistdiff(self, baseBlockHash, blockHash, baseMNList, expectedDeleted, expectedUpdated):
d = self.test_getmnlistdiff_base(baseBlockHash, blockHash)
assert_equal(set(d.deletedMNs), set([int(e, 16) for e in expectedDeleted]))
assert_equal(set([e.proRegTxHash for e in d.mnList]), set(int(e, 16) for e in expectedUpdated))
newMNList = baseMNList.copy()
for e in d.deletedMNs:
newMNList.pop(format(e, '064x'))
for e in d.mnList:
newMNList[format(e.proRegTxHash, '064x')] = e
cbtx = CCbTx()
cbtx.deserialize(BytesIO(d.cbTx.vExtraPayload))
hashes = []
for mn in sorted(newMNList.values(), key=lambda mn: ser_uint256(mn.proRegTxHash)):
hashes.append(hash256(mn.serialize()))
merkleRoot = CBlock.get_merkle_root(hashes)
assert_equal(merkleRoot, cbtx.merkleRootMNList)
return newMNList
def test_getmnlistdiff_quorums(self, baseBlockHash, blockHash, baseQuorumList, expectedDeleted, expectedNew):
d = self.test_getmnlistdiff_base(baseBlockHash, blockHash)
assert_equal(set(d.deletedQuorums), set(expectedDeleted))
assert_equal(set([QuorumId(e.llmqType, e.quorumHash) for e in d.newQuorums]), set(expectedNew))
newQuorumList = baseQuorumList.copy()
for e in d.deletedQuorums:
newQuorumList.pop(e)
for e in d.newQuorums:
newQuorumList[QuorumId(e.llmqType, e.quorumHash)] = e
cbtx = CCbTx()
cbtx.deserialize(BytesIO(d.cbTx.vExtraPayload))
if cbtx.version >= 2:
hashes = []
for qc in newQuorumList.values():
hashes.append(hash256(qc.serialize()))
hashes.sort()
merkleRoot = CBlock.get_merkle_root(hashes)
assert_equal(merkleRoot, cbtx.merkleRootQuorums)
return newQuorumList
def test_getmnlistdiff_base(self, baseBlockHash, blockHash):
hexstr = self.nodes[0].getblockheader(blockHash, False)
header = FromHex(CBlockHeader(), hexstr)
d = self.test_node.getmnlistdiff(int(baseBlockHash, 16), int(blockHash, 16))
assert_equal(d.baseBlockHash, int(baseBlockHash, 16))
assert_equal(d.blockHash, int(blockHash, 16))
proof = CMerkleBlock(header, d.merkleProof)
proof = proof.serialize().hex()
assert_equal(self.nodes[0].verifytxoutproof(proof), [d.cbTx.hash])
d2 = self.nodes[0].protx("diff", baseBlockHash, blockHash)
assert_equal(d2["baseBlockHash"], baseBlockHash)
assert_equal(d2["blockHash"], blockHash)
assert_equal(d2["cbTxMerkleTree"], d.merkleProof.serialize().hex())
assert_equal(d2["cbTx"], d.cbTx.serialize().hex())
assert_equal(set([int(e, 16) for e in d2["deletedMNs"]]), set(d.deletedMNs))
assert_equal(set([int(e["proRegTxHash"], 16) for e in d2["mnList"]]), set([e.proRegTxHash for e in d.mnList]))
assert_equal(set([QuorumId(e["llmqType"], int(e["quorumHash"], 16)) for e in d2["deletedQuorums"]]), set(d.deletedQuorums))
assert_equal(set([QuorumId(e["llmqType"], int(e["quorumHash"], 16)) for e in d2["newQuorums"]]), set([QuorumId(e.llmqType, e.quorumHash) for e in d.newQuorums]))
return d
def test_dip8_quorum_merkle_root_activation(self, with_initial_quorum):
if with_initial_quorum:
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
self.mine_quorum()
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 4070908800)
self.wait_for_sporks_same()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert(cbtx["cbTx"]["version"] == 1)
assert(self.nodes[0].getblockchaininfo()["bip9_softforks"]["dip0008"]["status"] != "active")
while self.nodes[0].getblockchaininfo()["bip9_softforks"]["dip0008"]["status"] != "active":
self.nodes[0].generate(4)
self.sync_all()
self.nodes[0].generate(1)
sync_blocks(self.nodes)
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert_equal(cbtx["cbTx"]["version"], 2)
assert("merkleRootQuorums" in cbtx["cbTx"])
merkleRootQuorums = int(cbtx["cbTx"]["merkleRootQuorums"], 16)
if with_initial_quorum:
assert(merkleRootQuorums != 0)
else:
assert_equal(merkleRootQuorums, 0)
set_mocktime(get_mocktime() + 1)
set_node_times(self.nodes, get_mocktime())
self.nodes[0].spork("SPORK_17_QUORUM_DKG_ENABLED", 0)
self.wait_for_sporks_same()
quorum = self.mine_quorum()
cbtx = self.nodes[0].getblock(self.nodes[0].getbestblockhash(), 2)["tx"][0]
assert(int(cbtx["cbTx"]["merkleRootQuorums"], 16) != merkleRootQuorums)
return quorum
def confirm_mns(self):
while True:
diff = self.nodes[0].protx("diff", 1, self.nodes[0].getblockcount())
found_unconfirmed = False
for mn in diff["mnList"]:
if int(mn["confirmedHash"], 16) == 0:
found_unconfirmed = True
break
if not found_unconfirmed:
break
self.nodes[0].generate(1)
sync_blocks(self.nodes)
if __name__ == '__main__':
LLMQCoinbaseCommitmentsTest().main()
| true | true |
f72698df2982562089d403ee92680cbf783ca0e2 | 31,875 | py | Python | examples/pxScene2d/external/libnode-v6.9.0/tools/comtypes/typeinfo.py | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 46 | 2017-09-07T14:59:22.000Z | 2020-10-31T20:34:12.000Z | examples/pxScene2d/external/libnode-v6.9.0/tools/comtypes/typeinfo.py | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v6.9.0/tools/comtypes/typeinfo.py | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | # XXX Should convert from STDMETHOD to COMMETHOD.
# generated by 'xml2py'
# flags '..\tools\windows.xml -m comtypes -m comtypes.automation -w -r .*TypeLibEx -r .*TypeLib -o typeinfo.py'
# then hacked manually
import os
import sys
import weakref
from ctypes import *
from ctypes.wintypes import ULONG
from comtypes import STDMETHOD
from comtypes import COMMETHOD
from comtypes import _GUID, GUID
# XXX should import more stuff from ctypes.wintypes...
from comtypes.automation import BSTR
from comtypes.automation import DISPID
from comtypes.automation import DISPPARAMS
from comtypes.automation import DWORD
from comtypes.automation import EXCEPINFO
from comtypes.automation import HRESULT
from comtypes.automation import IID
from comtypes.automation import IUnknown
from comtypes.automation import LCID
from comtypes.automation import LONG
from comtypes.automation import SCODE
from comtypes.automation import UINT
from comtypes.automation import VARIANT
from comtypes.automation import VARIANTARG
from comtypes.automation import VARTYPE
from comtypes.automation import WCHAR
from comtypes.automation import WORD
from comtypes.automation import tagVARIANT
is_64_bit = sys.maxsize > 2**32
BOOL = c_int
HREFTYPE = DWORD
INT = c_int
MEMBERID = DISPID
OLECHAR = WCHAR
PVOID = c_void_p
SHORT = c_short
# See https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx#ULONG_PTR # noqa
ULONG_PTR = c_uint64 if is_64_bit else c_ulong
USHORT = c_ushort
LPOLESTR = POINTER(OLECHAR)
################################################################
# enums
tagSYSKIND = c_int # enum
SYS_WIN16 = 0
SYS_WIN32 = 1
SYS_MAC = 2
SYS_WIN64 = 3
SYSKIND = tagSYSKIND
tagREGKIND = c_int # enum
REGKIND_DEFAULT = 0
REGKIND_REGISTER = 1
REGKIND_NONE = 2
REGKIND = tagREGKIND
tagTYPEKIND = c_int # enum
TKIND_ENUM = 0
TKIND_RECORD = 1
TKIND_MODULE = 2
TKIND_INTERFACE = 3
TKIND_DISPATCH = 4
TKIND_COCLASS = 5
TKIND_ALIAS = 6
TKIND_UNION = 7
TKIND_MAX = 8
TYPEKIND = tagTYPEKIND
tagINVOKEKIND = c_int # enum
INVOKE_FUNC = 1
INVOKE_PROPERTYGET = 2
INVOKE_PROPERTYPUT = 4
INVOKE_PROPERTYPUTREF = 8
INVOKEKIND = tagINVOKEKIND
tagDESCKIND = c_int # enum
DESCKIND_NONE = 0
DESCKIND_FUNCDESC = 1
DESCKIND_VARDESC = 2
DESCKIND_TYPECOMP = 3
DESCKIND_IMPLICITAPPOBJ = 4
DESCKIND_MAX = 5
DESCKIND = tagDESCKIND
tagVARKIND = c_int # enum
VAR_PERINSTANCE = 0
VAR_STATIC = 1
VAR_CONST = 2
VAR_DISPATCH = 3
VARKIND = tagVARKIND
tagFUNCKIND = c_int # enum
FUNC_VIRTUAL = 0
FUNC_PUREVIRTUAL = 1
FUNC_NONVIRTUAL = 2
FUNC_STATIC = 3
FUNC_DISPATCH = 4
FUNCKIND = tagFUNCKIND
tagCALLCONV = c_int # enum
CC_FASTCALL = 0
CC_CDECL = 1
CC_MSCPASCAL = 2
CC_PASCAL = 2
CC_MACPASCAL = 3
CC_STDCALL = 4
CC_FPFASTCALL = 5
CC_SYSCALL = 6
CC_MPWCDECL = 7
CC_MPWPASCAL = 8
CC_MAX = 9
CALLCONV = tagCALLCONV
IMPLTYPEFLAG_FDEFAULT = 1
IMPLTYPEFLAG_FSOURCE = 2
IMPLTYPEFLAG_FRESTRICTED = 4
IMPLTYPEFLAG_FDEFAULTVTABLE = 8
tagTYPEFLAGS = c_int # enum
TYPEFLAG_FAPPOBJECT = 1
TYPEFLAG_FCANCREATE = 2
TYPEFLAG_FLICENSED = 4
TYPEFLAG_FPREDECLID = 8
TYPEFLAG_FHIDDEN = 16
TYPEFLAG_FCONTROL = 32
TYPEFLAG_FDUAL = 64
TYPEFLAG_FNONEXTENSIBLE = 128
TYPEFLAG_FOLEAUTOMATION = 256
TYPEFLAG_FRESTRICTED = 512
TYPEFLAG_FAGGREGATABLE = 1024
TYPEFLAG_FREPLACEABLE = 2048
TYPEFLAG_FDISPATCHABLE = 4096
TYPEFLAG_FREVERSEBIND = 8192
TYPEFLAG_FPROXY = 16384
TYPEFLAGS = tagTYPEFLAGS
tagFUNCFLAGS = c_int # enum
FUNCFLAG_FRESTRICTED = 1
FUNCFLAG_FSOURCE = 2
FUNCFLAG_FBINDABLE = 4
FUNCFLAG_FREQUESTEDIT = 8
FUNCFLAG_FDISPLAYBIND = 16
FUNCFLAG_FDEFAULTBIND = 32
FUNCFLAG_FHIDDEN = 64
FUNCFLAG_FUSESGETLASTERROR = 128
FUNCFLAG_FDEFAULTCOLLELEM = 256
FUNCFLAG_FUIDEFAULT = 512
FUNCFLAG_FNONBROWSABLE = 1024
FUNCFLAG_FREPLACEABLE = 2048
FUNCFLAG_FIMMEDIATEBIND = 4096
FUNCFLAGS = tagFUNCFLAGS
tagVARFLAGS = c_int # enum
VARFLAG_FREADONLY = 1
VARFLAG_FSOURCE = 2
VARFLAG_FBINDABLE = 4
VARFLAG_FREQUESTEDIT = 8
VARFLAG_FDISPLAYBIND = 16
VARFLAG_FDEFAULTBIND = 32
VARFLAG_FHIDDEN = 64
VARFLAG_FRESTRICTED = 128
VARFLAG_FDEFAULTCOLLELEM = 256
VARFLAG_FUIDEFAULT = 512
VARFLAG_FNONBROWSABLE = 1024
VARFLAG_FREPLACEABLE = 2048
VARFLAG_FIMMEDIATEBIND = 4096
VARFLAGS = tagVARFLAGS
PARAMFLAG_NONE = 0
PARAMFLAG_FIN = 1
PARAMFLAG_FOUT = 2
PARAMFLAG_FLCID = 4
PARAMFLAG_FRETVAL = 8
PARAMFLAG_FOPT = 16
PARAMFLAG_FHASDEFAULT = 32
PARAMFLAG_FHASCUSTDATA = 64
################################################################
# a helper
def _deref_with_release(ptr, release):
# Given a POINTER instance, return the pointed to value.
# Call the 'release' function with 'ptr' to release resources
# when the value is no longer needed.
result = ptr[0]
result.__ref__ = weakref.ref(result, lambda dead: release(ptr))
return result
# interfaces
class ITypeLib(IUnknown):
_iid_ = GUID("{00020402-0000-0000-C000-000000000046}")
# Commented out methods use the default implementation that comtypes
# automatically creates for COM methods.
## def GetTypeInfoCount(self):
## "Return the number of type informations"
## def GetTypeInfo(self, index):
## "Load type info by index"
## def GetTypeInfoType(self, index):
## "Return the TYPEKIND of type information"
## def GetTypeInfoOfGuid(self, guid):
## "Return type information for a guid"
def GetLibAttr(self):
"Return type library attributes"
return _deref_with_release(self._GetLibAttr(), self.ReleaseTLibAttr)
## def GetTypeComp(self):
## "Return an ITypeComp pointer."
## def GetDocumentation(self, index):
## "Return documentation for a type description."
def IsName(self, name, lHashVal=0):
"""Check if there is type information for this name.
Returns the name with capitalization found in the type
library, or None.
"""
from ctypes import create_unicode_buffer
namebuf = create_unicode_buffer(name)
found = BOOL()
self.__com_IsName(namebuf, lHashVal, byref(found))
if found.value:
return namebuf[:].split("\0", 1)[0]
return None
def FindName(self, name, lHashVal=0):
# Hm...
# Could search for more than one name - should we support this?
found = c_ushort(1)
tinfo = POINTER(ITypeInfo)()
memid = MEMBERID()
self.__com_FindName(name, lHashVal, byref(tinfo), byref(memid), byref(found))
if found.value:
return memid.value, tinfo
return None
## def ReleaseTLibAttr(self, ptla):
## "Release TLIBATTR"
################
def fix_name(name):
# Some typelibs contain BSTR with embedded NUL characters,
# probably the len of the BSTR is wrong.
if name is None:
return name
return name.split("\0")[0]
class ITypeInfo(IUnknown):
_iid_ = GUID("{00020401-0000-0000-C000-000000000046}")
def GetTypeAttr(self):
"Return the TYPEATTR for this type"
return _deref_with_release(self._GetTypeAttr(), self.ReleaseTypeAttr)
## def GetTypeComp(self):
## "Return ITypeComp pointer for this type"
def GetDocumentation(self, memid):
"""Return name, docstring, helpcontext, and helpfile for 'memid'."""
name, doc, helpcontext, helpfile = self._GetDocumentation(memid)
return fix_name(name), fix_name(doc), helpcontext, fix_name(helpfile)
def GetFuncDesc(self, index):
"Return FUNCDESC for index"
return _deref_with_release(self._GetFuncDesc(index), self.ReleaseFuncDesc)
def GetVarDesc(self, index):
"Return VARDESC for index"
return _deref_with_release(self._GetVarDesc(index), self.ReleaseVarDesc)
def GetNames(self, memid, count=1):
"Return names for memid"
names = (BSTR * count)()
cnames = c_uint()
self.__com_GetNames(memid, names, count, byref(cnames))
return names[:cnames.value]
## def GetRefTypeOfImplType(self, index):
## "Get the reftype of an implemented type"
## def GetImplTypeFlags(self, index):
## "Get IMPLTYPEFLAGS"
def GetIDsOfNames(self, *names):
"Maps function and argument names to identifiers"
rgsznames = (c_wchar_p * len(names))(*names)
ids = (MEMBERID * len(names))()
self.__com_GetIDsOfNames(rgsznames, len(names), ids)
return ids[:]
# not yet wrapped
## STDMETHOD(HRESULT, 'Invoke', [PVOID, MEMBERID, WORD, POINTER(DISPPARAMS), POINTER(VARIANT), POINTER(EXCEPINFO), POINTER(UINT)]),
## def GetDllEntry(self, memid, invkind):
## "Return the dll name, function name, and ordinal for a function and invkind."
## def GetRefTypeInfo(self, href):
## "Get type info for reftype"
def AddressOfMember(self, memid, invkind):
"Get the address of a function in a dll"
raise "Check Me"
p = c_void_p()
self.__com_AddressOfMember(memid, invkind, byref(p))
# XXX Would the default impl return the value of p?
return p.value
def CreateInstance(self, punkouter=None, interface=IUnknown, iid=None):
if iid is None:
iid = interface._iid_
return self._CreateInstance(punkouter, byref(interface._iid_))
## def GetMops(self, index):
## "Get marshalling opcodes (whatever that is...)"
## def GetContainingTypeLib(self):
## "Return index into and the containing type lib itself"
## def ReleaseTypeAttr(self, pta):
## def ReleaseFuncDesc(self, pfd):
## def ReleaseVarDesc(self, pvd):
################
class ITypeComp(IUnknown):
_iid_ = GUID("{00020403-0000-0000-C000-000000000046}")
def Bind(self, name, flags=0, lHashVal=0):
"Bind to a name"
bindptr = BINDPTR()
desckind = DESCKIND()
ti = POINTER(ITypeInfo)()
self.__com_Bind(name, lHashVal, flags, byref(ti), byref(desckind), byref(bindptr))
kind = desckind.value
if kind == DESCKIND_FUNCDESC:
fd = bindptr.lpfuncdesc[0]
fd.__ref__ = weakref.ref(fd, lambda dead: ti.ReleaseFuncDesc(bindptr.lpfuncdesc))
return "function", fd
elif kind == DESCKIND_VARDESC:
vd = bindptr.lpvardesc[0]
vd.__ref__ = weakref.ref(vd, lambda dead: ti.ReleaseVarDesc(bindptr.lpvardesc))
return "variable", vd
elif kind == DESCKIND_TYPECOMP:
return "type", bindptr.lptcomp
elif kind == DESCKIND_IMPLICITAPPOBJ:
raise NotImplementedError
elif kind == DESCKIND_NONE:
raise NameError("Name %s not found" % name)
def BindType(self, name, lHashVal=0):
"Bind a type, and return both the typeinfo and typecomp for it."
ti = POINTER(ITypeInfo)()
tc = POINTER(ITypeComp)()
self.__com_BindType(name, lHashVal, byref(ti), byref(tc))
return ti, tc
################
class ICreateTypeLib(IUnknown):
_iid_ = GUID("{00020406-0000-0000-C000-000000000046}")
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 2149
class ICreateTypeLib2(ICreateTypeLib):
_iid_ = GUID("{0002040F-0000-0000-C000-000000000046}")
class ICreateTypeInfo(IUnknown):
_iid_ = GUID("{00020405-0000-0000-C000-000000000046}")
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 915
def SetFuncAndParamNames(self, index, *names):
rgszNames = (c_wchar_p * len(names))()
for i, n in enumerate(names):
rgszNames[i] = n
return self._SetFuncAndParamNames(index, rgszNames, len(names))
class IRecordInfo(IUnknown):
# C:/vc98/include/OAIDL.H 5974
_iid_ = GUID("{0000002F-0000-0000-C000-000000000046}")
def GetFieldNames(self, *args):
count = c_ulong()
self.__com_GetFieldNames(count, None)
array = (BSTR * count.value)()
self.__com_GetFieldNames(count, array)
result = array[:]
# XXX Should SysFreeString the array contents. How to?
return result
IRecordInfo. _methods_ = [
COMMETHOD([], HRESULT, 'RecordInit',
(['in'], c_void_p, 'pvNew')),
COMMETHOD([], HRESULT, 'RecordClear',
(['in'], c_void_p, 'pvExisting')),
COMMETHOD([], HRESULT, 'RecordCopy',
(['in'], c_void_p, 'pvExisting'),
(['in'], c_void_p, 'pvNew')),
COMMETHOD([], HRESULT, 'GetGuid',
(['out'], POINTER(GUID), 'pguid')),
COMMETHOD([], HRESULT, 'GetName',
(['out'], POINTER(BSTR), 'pbstrName')),
COMMETHOD([], HRESULT, 'GetSize',
(['out'], POINTER(c_ulong), 'pcbSize')),
COMMETHOD([], HRESULT, 'GetTypeInfo',
(['out'], POINTER(POINTER(ITypeInfo)), 'ppTypeInfo')),
COMMETHOD([], HRESULT, 'GetField',
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['out'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'GetFieldNoCopy',
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['out'], POINTER(VARIANT), 'pvarField'),
(['out'], POINTER(c_void_p), 'ppvDataCArray')),
COMMETHOD([], HRESULT, 'PutField',
(['in'], c_ulong, 'wFlags'),
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['in'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'PutFieldNoCopy',
(['in'], c_ulong, 'wFlags'),
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['in'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'GetFieldNames',
(['in', 'out'], POINTER(c_ulong), 'pcNames'),
(['in'], POINTER(BSTR), 'rgBstrNames')),
COMMETHOD([], BOOL, 'IsMatchingType',
(['in'], POINTER(IRecordInfo))),
COMMETHOD([], HRESULT, 'RecordCreate'),
COMMETHOD([], HRESULT, 'RecordCreateCopy',
(['in'], c_void_p, 'pvSource'),
(['out'], POINTER(c_void_p), 'ppvDest')),
COMMETHOD([], HRESULT, 'RecordDestroy',
(['in'], c_void_p, 'pvRecord'))]
################################################################
# functions
_oleaut32 = oledll.oleaut32
def GetRecordInfoFromTypeInfo(tinfo):
"Return an IRecordInfo pointer to the UDT described in tinfo"
ri = POINTER(IRecordInfo)()
_oleaut32.GetRecordInfoFromTypeInfo(tinfo, byref(ri))
return ri
def GetRecordInfoFromGuids(rGuidTypeLib, verMajor, verMinor, lcid, rGuidTypeInfo):
ri = POINTER(IRecordInfo)()
_oleaut32.GetRecordInfoFromGuids(byref(GUID(rGuidTypeLib)),
verMajor, verMinor, lcid,
byref(GUID(rGuidTypeInfo)),
byref(ri))
return ri
def LoadRegTypeLib(guid, wMajorVerNum, wMinorVerNum, lcid=0):
"Load a registered type library"
tlib = POINTER(ITypeLib)()
_oleaut32.LoadRegTypeLib(byref(GUID(guid)), wMajorVerNum, wMinorVerNum, lcid, byref(tlib))
return tlib
if hasattr(_oleaut32, "LoadTypeLibEx"):
def LoadTypeLibEx(szFile, regkind=REGKIND_NONE):
"Load, and optionally register a type library file"
ptl = POINTER(ITypeLib)()
_oleaut32.LoadTypeLibEx(c_wchar_p(szFile), regkind, byref(ptl))
return ptl
else:
def LoadTypeLibEx(szFile, regkind=REGKIND_NONE):
"Load, and optionally register a type library file"
ptl = POINTER(ITypeLib)()
_oleaut32.LoadTypeLib(c_wchar_p(szFile), byref(ptl))
return ptl
def LoadTypeLib(szFile):
"Load and register a type library file"
tlib = POINTER(ITypeLib)()
_oleaut32.LoadTypeLib(c_wchar_p(szFile), byref(tlib))
return tlib
def UnRegisterTypeLib(libID, wVerMajor, wVerMinor, lcid=0, syskind=SYS_WIN32):
"Unregister a registered type library"
return _oleaut32.UnRegisterTypeLib(byref(GUID(libID)), wVerMajor, wVerMinor, lcid, syskind)
def RegisterTypeLib(tlib, fullpath, helpdir=None):
"Register a type library in the registry"
return _oleaut32.RegisterTypeLib(tlib, c_wchar_p(fullpath), c_wchar_p(helpdir))
def CreateTypeLib(filename, syskind=SYS_WIN32):
"Return a ICreateTypeLib2 pointer"
ctlib = POINTER(ICreateTypeLib2)()
_oleaut32.CreateTypeLib2(syskind, c_wchar_p(filename), byref(ctlib))
return ctlib
if os.name == "ce":
# See also:
# http://blogs.msdn.com/larryosterman/archive/2006/01/09/510856.aspx
#
# windows CE does not have QueryPathOfRegTypeLib. Emulate by reading the registry:
def QueryPathOfRegTypeLib(libid, wVerMajor, wVerMinor, lcid=0):
"Return the path of a registered type library"
import _winreg
try:
hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, r"Typelib\%s\%s.%s\%x\win32" % (libid, wVerMajor, wVerMinor, lcid))
except WindowsError:
# On CE, some typelib names are not in the ..\win32 subkey:
hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, r"Typelib\%s\%s.%s\%x" % (libid, wVerMajor, wVerMinor, lcid))
return _winreg.QueryValueEx(hkey, "")[0]
else:
def QueryPathOfRegTypeLib(libid, wVerMajor, wVerMinor, lcid=0):
"Return the path of a registered type library"
pathname = BSTR()
_oleaut32.QueryPathOfRegTypeLib(byref(GUID(libid)), wVerMajor, wVerMinor, lcid, byref(pathname))
return pathname.value.split("\0")[0]
################################################################
# Structures
class tagTLIBATTR(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 4437
def __repr__(self):
return "TLIBATTR(GUID=%s, Version=%s.%s, LCID=%s, FLags=0x%x)" % \
(self.guid, self.wMajorVerNum, self.wMinorVerNum, self.lcid, self.wLibFlags)
TLIBATTR = tagTLIBATTR
class tagTYPEATTR(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 672
def __repr__(self):
return "TYPEATTR(GUID=%s, typekind=%s, funcs=%s, vars=%s, impltypes=%s)" % \
(self.guid, self.typekind, self.cFuncs, self.cVars, self.cImplTypes)
TYPEATTR = tagTYPEATTR
class tagFUNCDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 769
def __repr__(self):
return "FUNCDESC(memid=%s, cParams=%s, cParamsOpt=%s, callconv=%s, invkind=%s, funckind=%s)" % \
(self.memid, self.cParams, self.cParamsOpt, self.callconv, self.invkind, self.funckind)
FUNCDESC = tagFUNCDESC
class tagVARDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 803
pass
VARDESC = tagVARDESC
class tagBINDPTR(Union):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 3075
pass
BINDPTR = tagBINDPTR
class tagTYPEDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 582
pass
TYPEDESC = tagTYPEDESC
class tagIDLDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 633
pass
IDLDESC = tagIDLDESC
class tagARRAYDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 594
pass
################################################################
# interface vtbl definitions
ICreateTypeLib._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 2149
COMMETHOD([], HRESULT, 'CreateTypeInfo',
(['in'], LPOLESTR, 'szName'),
(['in'], TYPEKIND, 'tkind'),
(['out'], POINTER(POINTER(ICreateTypeInfo)), 'ppCTInfo')),
STDMETHOD(HRESULT, 'SetName', [LPOLESTR]),
STDMETHOD(HRESULT, 'SetVersion', [WORD, WORD]),
STDMETHOD(HRESULT, 'SetGuid', [POINTER(GUID)]),
STDMETHOD(HRESULT, 'SetDocString', [LPOLESTR]),
STDMETHOD(HRESULT, 'SetHelpFileName', [LPOLESTR]),
STDMETHOD(HRESULT, 'SetHelpContext', [DWORD]),
STDMETHOD(HRESULT, 'SetLcid', [LCID]),
STDMETHOD(HRESULT, 'SetLibFlags', [UINT]),
STDMETHOD(HRESULT, 'SaveAllChanges', []),
]
ICreateTypeLib2._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 2444
STDMETHOD(HRESULT, 'DeleteTypeInfo', [POINTER(ITypeInfo)]),
STDMETHOD(HRESULT, 'SetCustData', [POINTER(GUID), POINTER(VARIANT)]),
STDMETHOD(HRESULT, 'SetHelpStringContext', [ULONG]),
STDMETHOD(HRESULT, 'SetHelpStringDll', [LPOLESTR]),
]
ITypeLib._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 4455
COMMETHOD([], UINT, 'GetTypeInfoCount'),
COMMETHOD([], HRESULT, 'GetTypeInfo',
(['in'], UINT, 'index'),
(['out'], POINTER(POINTER(ITypeInfo)))),
COMMETHOD([], HRESULT, 'GetTypeInfoType',
(['in'], UINT, 'index'),
(['out'], POINTER(TYPEKIND))),
COMMETHOD([], HRESULT, 'GetTypeInfoOfGuid',
(['in'], POINTER(GUID)),
(['out'], POINTER(POINTER(ITypeInfo)))),
COMMETHOD([], HRESULT, 'GetLibAttr',
(['out'], POINTER(POINTER(TLIBATTR)))),
COMMETHOD([], HRESULT, 'GetTypeComp',
(['out'], POINTER(POINTER(ITypeComp)))),
COMMETHOD([], HRESULT, 'GetDocumentation',
(['in'], INT, 'index'),
(['out'], POINTER(BSTR)),
(['out'], POINTER(BSTR)),
(['out'], POINTER(DWORD)),
(['out'], POINTER(BSTR))),
COMMETHOD([], HRESULT, 'IsName',
# IsName changes the casing of the passed in name to
# match that in the type library. In the automatically
# wrapped version of this method, ctypes would pass a
# Python unicode string which would then be changed -
# very bad. So we have (see above) to implement the
# IsName method manually.
(['in', 'out'], LPOLESTR, 'name'),
(['in', 'optional'], DWORD, 'lHashVal', 0),
(['out'], POINTER(BOOL))),
STDMETHOD(HRESULT, 'FindName', [LPOLESTR, DWORD, POINTER(POINTER(ITypeInfo)),
POINTER(MEMBERID), POINTER(USHORT)]),
COMMETHOD([], None, 'ReleaseTLibAttr',
(['in'], POINTER(TLIBATTR)))
]
ITypeInfo._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 3230
COMMETHOD([], HRESULT, 'GetTypeAttr',
(['out'], POINTER(POINTER(TYPEATTR)), 'ppTypeAttr')),
COMMETHOD([], HRESULT, 'GetTypeComp',
(['out'], POINTER(POINTER(ITypeComp)))),
COMMETHOD([], HRESULT, 'GetFuncDesc',
(['in'], UINT, 'index'),
(['out'], POINTER(POINTER(FUNCDESC)))),
COMMETHOD([], HRESULT, 'GetVarDesc',
(['in'], UINT, 'index'),
(['out'], POINTER(POINTER(VARDESC)))),
STDMETHOD(HRESULT, 'GetNames', [MEMBERID, POINTER(BSTR), UINT, POINTER(UINT)]),
COMMETHOD([], HRESULT, 'GetRefTypeOfImplType',
(['in'], UINT, 'index'),
(['out'], POINTER(HREFTYPE))),
COMMETHOD([], HRESULT, 'GetImplTypeFlags',
(['in'], UINT, 'index'),
(['out'], POINTER(INT))),
## STDMETHOD(HRESULT, 'GetIDsOfNames', [POINTER(LPOLESTR), UINT, POINTER(MEMBERID)]),
# this one changed, to accept c_wchar_p array
STDMETHOD(HRESULT, 'GetIDsOfNames', [POINTER(c_wchar_p), UINT, POINTER(MEMBERID)]),
STDMETHOD(HRESULT, 'Invoke', [PVOID, MEMBERID, WORD, POINTER(DISPPARAMS), POINTER(VARIANT), POINTER(EXCEPINFO), POINTER(UINT)]),
COMMETHOD([], HRESULT, 'GetDocumentation',
(['in'], MEMBERID, 'memid'),
(['out'], POINTER(BSTR), 'pBstrName'),
(['out'], POINTER(BSTR), 'pBstrDocString'),
(['out'], POINTER(DWORD), 'pdwHelpContext'),
(['out'], POINTER(BSTR), 'pBstrHelpFile')),
COMMETHOD([], HRESULT, 'GetDllEntry',
(['in'], MEMBERID, 'index'),
(['in'], INVOKEKIND, 'invkind'),
(['out'], POINTER(BSTR), 'pBstrDllName'),
(['out'], POINTER(BSTR), 'pBstrName'),
(['out'], POINTER(WORD), 'pwOrdinal')),
COMMETHOD([], HRESULT, 'GetRefTypeInfo',
(['in'], HREFTYPE, 'hRefType'),
(['out'], POINTER(POINTER(ITypeInfo)))),
STDMETHOD(HRESULT, 'AddressOfMember', [MEMBERID, INVOKEKIND, POINTER(PVOID)]),
COMMETHOD([], HRESULT, 'CreateInstance',
(['in'], POINTER(IUnknown), 'pUnkOuter'),
(['in'], POINTER(IID), 'refiid'),
(['out'], POINTER(POINTER(IUnknown)))),
COMMETHOD([], HRESULT, 'GetMops',
(['in'], MEMBERID, 'memid'),
(['out'], POINTER(BSTR))),
COMMETHOD([], HRESULT, 'GetContainingTypeLib',
(['out'], POINTER(POINTER(ITypeLib))),
(['out'], POINTER(UINT))),
COMMETHOD([], None, 'ReleaseTypeAttr',
(['in'], POINTER(TYPEATTR))),
COMMETHOD([], None, 'ReleaseFuncDesc',
(['in'], POINTER(FUNCDESC))),
COMMETHOD([], None, 'ReleaseVarDesc',
(['in'], POINTER(VARDESC))),
]
ITypeComp._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 3090
STDMETHOD(HRESULT, 'Bind',
[LPOLESTR, DWORD, WORD, POINTER(POINTER(ITypeInfo)),
POINTER(DESCKIND), POINTER(BINDPTR)]),
STDMETHOD(HRESULT, 'BindType',
[LPOLESTR, DWORD, POINTER(POINTER(ITypeInfo)), POINTER(POINTER(ITypeComp))]),
]
ICreateTypeInfo._methods_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 915
STDMETHOD(HRESULT, 'SetGuid', [POINTER(GUID)]),
STDMETHOD(HRESULT, 'SetTypeFlags', [UINT]),
STDMETHOD(HRESULT, 'SetDocString', [LPOLESTR]),
STDMETHOD(HRESULT, 'SetHelpContext', [DWORD]),
STDMETHOD(HRESULT, 'SetVersion', [WORD, WORD]),
# STDMETHOD(HRESULT, 'AddRefTypeInfo', [POINTER(ITypeInfo), POINTER(HREFTYPE)]),
COMMETHOD([], HRESULT, 'AddRefTypeInfo',
(['in'], POINTER(ITypeInfo)),
(['out'], POINTER(HREFTYPE))),
STDMETHOD(HRESULT, 'AddFuncDesc', [UINT, POINTER(FUNCDESC)]),
STDMETHOD(HRESULT, 'AddImplType', [UINT, HREFTYPE]),
STDMETHOD(HRESULT, 'SetImplTypeFlags', [UINT, INT]),
STDMETHOD(HRESULT, 'SetAlignment', [WORD]),
STDMETHOD(HRESULT, 'SetSchema', [LPOLESTR]),
STDMETHOD(HRESULT, 'AddVarDesc', [UINT, POINTER(VARDESC)]),
STDMETHOD(HRESULT, 'SetFuncAndParamNames', [UINT, POINTER(c_wchar_p), UINT]),
STDMETHOD(HRESULT, 'SetVarName', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetTypeDescAlias', [POINTER(TYPEDESC)]),
STDMETHOD(HRESULT, 'DefineFuncAsDllEntry', [UINT, LPOLESTR, LPOLESTR]),
STDMETHOD(HRESULT, 'SetFuncDocString', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetVarDocString', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetFuncHelpContext', [UINT, DWORD]),
STDMETHOD(HRESULT, 'SetVarHelpContext', [UINT, DWORD]),
STDMETHOD(HRESULT, 'SetMops', [UINT, BSTR]),
STDMETHOD(HRESULT, 'SetTypeIdldesc', [POINTER(IDLDESC)]),
STDMETHOD(HRESULT, 'LayOut', []),
]
class IProvideClassInfo(IUnknown):
_iid_ = GUID("{B196B283-BAB4-101A-B69C-00AA00341D07}")
_methods_ = [
# Returns the ITypeInfo interface for the object's coclass type information.
COMMETHOD([], HRESULT, "GetClassInfo",
( ['out'], POINTER(POINTER(ITypeInfo)), "ppTI" ) )
]
class IProvideClassInfo2(IProvideClassInfo):
_iid_ = GUID("{A6BC3AC0-DBAA-11CE-9DE3-00AA004BB851}")
_methods_ = [
# Returns the GUID for the object's outgoing IID for its default event set.
COMMETHOD([], HRESULT, "GetGUID",
( ['in'], DWORD, "dwGuidKind" ),
( ['out', 'retval'], POINTER(GUID), "pGUID" ))
]
################################################################
# Structure fields
tagTLIBATTR._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 4437
('guid', GUID),
('lcid', LCID),
('syskind', SYSKIND),
('wMajorVerNum', WORD),
('wMinorVerNum', WORD),
('wLibFlags', WORD),
]
class N11tagTYPEDESC5DOLLAR_203E(Union):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 584
pass
N11tagTYPEDESC5DOLLAR_203E._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 584
('lptdesc', POINTER(tagTYPEDESC)),
('lpadesc', POINTER(tagARRAYDESC)),
('hreftype', HREFTYPE),
]
tagTYPEDESC._anonymous_ = ('_',)
tagTYPEDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 582
# Unnamed field renamed to '_'
('_', N11tagTYPEDESC5DOLLAR_203E),
('vt', VARTYPE),
]
tagIDLDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 633
('dwReserved', ULONG_PTR),
('wIDLFlags', USHORT),
]
tagTYPEATTR._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 672
('guid', GUID),
('lcid', LCID),
('dwReserved', DWORD),
('memidConstructor', MEMBERID),
('memidDestructor', MEMBERID),
('lpstrSchema', LPOLESTR),
('cbSizeInstance', DWORD),
('typekind', TYPEKIND),
('cFuncs', WORD),
('cVars', WORD),
('cImplTypes', WORD),
('cbSizeVft', WORD),
('cbAlignment', WORD),
('wTypeFlags', WORD),
('wMajorVerNum', WORD),
('wMinorVerNum', WORD),
('tdescAlias', TYPEDESC),
('idldescType', IDLDESC),
]
class N10tagVARDESC5DOLLAR_205E(Union):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 807
pass
N10tagVARDESC5DOLLAR_205E._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 807
('oInst', DWORD),
('lpvarValue', POINTER(VARIANT)),
]
class tagELEMDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 661
pass
class N11tagELEMDESC5DOLLAR_204E(Union):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 663
pass
class tagPARAMDESC(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 609
pass
class tagPARAMDESCEX(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 601
pass
LPPARAMDESCEX = POINTER(tagPARAMDESCEX)
tagPARAMDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 609
('pparamdescex', LPPARAMDESCEX),
('wParamFlags', USHORT),
]
PARAMDESC = tagPARAMDESC
N11tagELEMDESC5DOLLAR_204E._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 663
('idldesc', IDLDESC),
('paramdesc', PARAMDESC),
]
tagELEMDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 661
('tdesc', TYPEDESC),
# Unnamed field renamed to '_'
('_', N11tagELEMDESC5DOLLAR_204E),
]
ELEMDESC = tagELEMDESC
tagVARDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 803
('memid', MEMBERID),
('lpstrSchema', LPOLESTR),
# Unnamed field renamed to '_'
('_', N10tagVARDESC5DOLLAR_205E),
('elemdescVar', ELEMDESC),
('wVarFlags', WORD),
('varkind', VARKIND),
]
tagBINDPTR._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 3075
('lpfuncdesc', POINTER(FUNCDESC)),
('lpvardesc', POINTER(VARDESC)),
('lptcomp', POINTER(ITypeComp)),
]
tagFUNCDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 769
('memid', MEMBERID),
('lprgscode', POINTER(SCODE)),
('lprgelemdescParam', POINTER(ELEMDESC)),
('funckind', FUNCKIND),
('invkind', INVOKEKIND),
('callconv', CALLCONV),
('cParams', SHORT),
('cParamsOpt', SHORT),
('oVft', SHORT),
('cScodes', SHORT),
('elemdescFunc', ELEMDESC),
('wFuncFlags', WORD),
]
tagPARAMDESCEX._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 601
('cBytes', DWORD),
('varDefaultValue', VARIANTARG),
]
class tagSAFEARRAYBOUND(Structure):
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 226
_fields_ = [
('cElements', DWORD),
('lLbound', LONG),
]
SAFEARRAYBOUND = tagSAFEARRAYBOUND
tagARRAYDESC._fields_ = [
# C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 594
('tdescElem', TYPEDESC),
('cDims', USHORT),
('rgbounds', SAFEARRAYBOUND * 1),
]
| 34.874179 | 134 | 0.637427 |
import os
import sys
import weakref
from ctypes import *
from ctypes.wintypes import ULONG
from comtypes import STDMETHOD
from comtypes import COMMETHOD
from comtypes import _GUID, GUID
from comtypes.automation import BSTR
from comtypes.automation import DISPID
from comtypes.automation import DISPPARAMS
from comtypes.automation import DWORD
from comtypes.automation import EXCEPINFO
from comtypes.automation import HRESULT
from comtypes.automation import IID
from comtypes.automation import IUnknown
from comtypes.automation import LCID
from comtypes.automation import LONG
from comtypes.automation import SCODE
from comtypes.automation import UINT
from comtypes.automation import VARIANT
from comtypes.automation import VARIANTARG
from comtypes.automation import VARTYPE
from comtypes.automation import WCHAR
from comtypes.automation import WORD
from comtypes.automation import tagVARIANT
is_64_bit = sys.maxsize > 2**32
BOOL = c_int
HREFTYPE = DWORD
INT = c_int
MEMBERID = DISPID
OLECHAR = WCHAR
PVOID = c_void_p
SHORT = c_short
is_64_bit else c_ulong
USHORT = c_ushort
LPOLESTR = POINTER(OLECHAR)
WSABLE = 1024
FUNCFLAG_FREPLACEABLE = 2048
FUNCFLAG_FIMMEDIATEBIND = 4096
FUNCFLAGS = tagFUNCFLAGS
tagVARFLAGS = c_int
VARFLAG_FREADONLY = 1
VARFLAG_FSOURCE = 2
VARFLAG_FBINDABLE = 4
VARFLAG_FREQUESTEDIT = 8
VARFLAG_FDISPLAYBIND = 16
VARFLAG_FDEFAULTBIND = 32
VARFLAG_FHIDDEN = 64
VARFLAG_FRESTRICTED = 128
VARFLAG_FDEFAULTCOLLELEM = 256
VARFLAG_FUIDEFAULT = 512
VARFLAG_FNONBROWSABLE = 1024
VARFLAG_FREPLACEABLE = 2048
VARFLAG_FIMMEDIATEBIND = 4096
VARFLAGS = tagVARFLAGS
PARAMFLAG_NONE = 0
PARAMFLAG_FIN = 1
PARAMFLAG_FOUT = 2
PARAMFLAG_FLCID = 4
PARAMFLAG_FRETVAL = 8
PARAMFLAG_FOPT = 16
PARAMFLAG_FHASDEFAULT = 32
PARAMFLAG_FHASCUSTDATA = 64
R(ITypeInfo)()
tc = POINTER(ITypeComp)()
self.__com_BindType(name, lHashVal, byref(ti), byref(tc))
return ti, tc
(ICreateTypeLib):
_iid_ = GUID("{0002040F-0000-0000-C000-000000000046}")
class ICreateTypeInfo(IUnknown):
_iid_ = GUID("{00020405-0000-0000-C000-000000000046}")
def SetFuncAndParamNames(self, index, *names):
rgszNames = (c_wchar_p * len(names))()
for i, n in enumerate(names):
rgszNames[i] = n
return self._SetFuncAndParamNames(index, rgszNames, len(names))
class IRecordInfo(IUnknown):
_iid_ = GUID("{0000002F-0000-0000-C000-000000000046}")
def GetFieldNames(self, *args):
count = c_ulong()
self.__com_GetFieldNames(count, None)
array = (BSTR * count.value)()
self.__com_GetFieldNames(count, array)
result = array[:]
return result
IRecordInfo. _methods_ = [
COMMETHOD([], HRESULT, 'RecordInit',
(['in'], c_void_p, 'pvNew')),
COMMETHOD([], HRESULT, 'RecordClear',
(['in'], c_void_p, 'pvExisting')),
COMMETHOD([], HRESULT, 'RecordCopy',
(['in'], c_void_p, 'pvExisting'),
(['in'], c_void_p, 'pvNew')),
COMMETHOD([], HRESULT, 'GetGuid',
(['out'], POINTER(GUID), 'pguid')),
COMMETHOD([], HRESULT, 'GetName',
(['out'], POINTER(BSTR), 'pbstrName')),
COMMETHOD([], HRESULT, 'GetSize',
(['out'], POINTER(c_ulong), 'pcbSize')),
COMMETHOD([], HRESULT, 'GetTypeInfo',
(['out'], POINTER(POINTER(ITypeInfo)), 'ppTypeInfo')),
COMMETHOD([], HRESULT, 'GetField',
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['out'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'GetFieldNoCopy',
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['out'], POINTER(VARIANT), 'pvarField'),
(['out'], POINTER(c_void_p), 'ppvDataCArray')),
COMMETHOD([], HRESULT, 'PutField',
(['in'], c_ulong, 'wFlags'),
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['in'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'PutFieldNoCopy',
(['in'], c_ulong, 'wFlags'),
(['in'], c_void_p, 'pvData'),
(['in'], c_wchar_p, 'szFieldName'),
(['in'], POINTER(VARIANT), 'pvarField')),
COMMETHOD([], HRESULT, 'GetFieldNames',
(['in', 'out'], POINTER(c_ulong), 'pcNames'),
(['in'], POINTER(BSTR), 'rgBstrNames')),
COMMETHOD([], BOOL, 'IsMatchingType',
(['in'], POINTER(IRecordInfo))),
COMMETHOD([], HRESULT, 'RecordCreate'),
COMMETHOD([], HRESULT, 'RecordCreateCopy',
(['in'], c_void_p, 'pvSource'),
(['out'], POINTER(c_void_p), 'ppvDest')),
COMMETHOD([], HRESULT, 'RecordDestroy',
(['in'], c_void_p, 'pvRecord'))]
ASSES_ROOT, r"Typelib\%s\%s.%s\%x\win32" % (libid, wVerMajor, wVerMinor, lcid))
except WindowsError:
hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, r"Typelib\%s\%s.%s\%x" % (libid, wVerMajor, wVerMinor, lcid))
return _winreg.QueryValueEx(hkey, "")[0]
else:
def QueryPathOfRegTypeLib(libid, wVerMajor, wVerMinor, lcid=0):
"Return the path of a registered type library"
pathname = BSTR()
_oleaut32.QueryPathOfRegTypeLib(byref(GUID(libid)), wVerMajor, wVerMinor, lcid, byref(pathname))
return pathname.value.split("\0")[0]
, 'GetNames', [MEMBERID, POINTER(BSTR), UINT, POINTER(UINT)]),
COMMETHOD([], HRESULT, 'GetRefTypeOfImplType',
(['in'], UINT, 'index'),
(['out'], POINTER(HREFTYPE))),
COMMETHOD([], HRESULT, 'GetImplTypeFlags',
(['in'], UINT, 'index'),
(['out'], POINTER(INT))),
ID)]),
STDMETHOD(HRESULT, 'Invoke', [PVOID, MEMBERID, WORD, POINTER(DISPPARAMS), POINTER(VARIANT), POINTER(EXCEPINFO), POINTER(UINT)]),
COMMETHOD([], HRESULT, 'GetDocumentation',
(['in'], MEMBERID, 'memid'),
(['out'], POINTER(BSTR), 'pBstrName'),
(['out'], POINTER(BSTR), 'pBstrDocString'),
(['out'], POINTER(DWORD), 'pdwHelpContext'),
(['out'], POINTER(BSTR), 'pBstrHelpFile')),
COMMETHOD([], HRESULT, 'GetDllEntry',
(['in'], MEMBERID, 'index'),
(['in'], INVOKEKIND, 'invkind'),
(['out'], POINTER(BSTR), 'pBstrDllName'),
(['out'], POINTER(BSTR), 'pBstrName'),
(['out'], POINTER(WORD), 'pwOrdinal')),
COMMETHOD([], HRESULT, 'GetRefTypeInfo',
(['in'], HREFTYPE, 'hRefType'),
(['out'], POINTER(POINTER(ITypeInfo)))),
STDMETHOD(HRESULT, 'AddressOfMember', [MEMBERID, INVOKEKIND, POINTER(PVOID)]),
COMMETHOD([], HRESULT, 'CreateInstance',
(['in'], POINTER(IUnknown), 'pUnkOuter'),
(['in'], POINTER(IID), 'refiid'),
(['out'], POINTER(POINTER(IUnknown)))),
COMMETHOD([], HRESULT, 'GetMops',
(['in'], MEMBERID, 'memid'),
(['out'], POINTER(BSTR))),
COMMETHOD([], HRESULT, 'GetContainingTypeLib',
(['out'], POINTER(POINTER(ITypeLib))),
(['out'], POINTER(UINT))),
COMMETHOD([], None, 'ReleaseTypeAttr',
(['in'], POINTER(TYPEATTR))),
COMMETHOD([], None, 'ReleaseFuncDesc',
(['in'], POINTER(FUNCDESC))),
COMMETHOD([], None, 'ReleaseVarDesc',
(['in'], POINTER(VARDESC))),
]
ITypeComp._methods_ = [
STDMETHOD(HRESULT, 'Bind',
[LPOLESTR, DWORD, WORD, POINTER(POINTER(ITypeInfo)),
POINTER(DESCKIND), POINTER(BINDPTR)]),
STDMETHOD(HRESULT, 'BindType',
[LPOLESTR, DWORD, POINTER(POINTER(ITypeInfo)), POINTER(POINTER(ITypeComp))]),
]
ICreateTypeInfo._methods_ = [
STDMETHOD(HRESULT, 'SetGuid', [POINTER(GUID)]),
STDMETHOD(HRESULT, 'SetTypeFlags', [UINT]),
STDMETHOD(HRESULT, 'SetDocString', [LPOLESTR]),
STDMETHOD(HRESULT, 'SetHelpContext', [DWORD]),
STDMETHOD(HRESULT, 'SetVersion', [WORD, WORD]),
COMMETHOD([], HRESULT, 'AddRefTypeInfo',
(['in'], POINTER(ITypeInfo)),
(['out'], POINTER(HREFTYPE))),
STDMETHOD(HRESULT, 'AddFuncDesc', [UINT, POINTER(FUNCDESC)]),
STDMETHOD(HRESULT, 'AddImplType', [UINT, HREFTYPE]),
STDMETHOD(HRESULT, 'SetImplTypeFlags', [UINT, INT]),
STDMETHOD(HRESULT, 'SetAlignment', [WORD]),
STDMETHOD(HRESULT, 'SetSchema', [LPOLESTR]),
STDMETHOD(HRESULT, 'AddVarDesc', [UINT, POINTER(VARDESC)]),
STDMETHOD(HRESULT, 'SetFuncAndParamNames', [UINT, POINTER(c_wchar_p), UINT]),
STDMETHOD(HRESULT, 'SetVarName', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetTypeDescAlias', [POINTER(TYPEDESC)]),
STDMETHOD(HRESULT, 'DefineFuncAsDllEntry', [UINT, LPOLESTR, LPOLESTR]),
STDMETHOD(HRESULT, 'SetFuncDocString', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetVarDocString', [UINT, LPOLESTR]),
STDMETHOD(HRESULT, 'SetFuncHelpContext', [UINT, DWORD]),
STDMETHOD(HRESULT, 'SetVarHelpContext', [UINT, DWORD]),
STDMETHOD(HRESULT, 'SetMops', [UINT, BSTR]),
STDMETHOD(HRESULT, 'SetTypeIdldesc', [POINTER(IDLDESC)]),
STDMETHOD(HRESULT, 'LayOut', []),
]
class IProvideClassInfo(IUnknown):
_iid_ = GUID("{B196B283-BAB4-101A-B69C-00AA00341D07}")
_methods_ = [
COMMETHOD([], HRESULT, "GetClassInfo",
( ['out'], POINTER(POINTER(ITypeInfo)), "ppTI" ) )
]
class IProvideClassInfo2(IProvideClassInfo):
_iid_ = GUID("{A6BC3AC0-DBAA-11CE-9DE3-00AA004BB851}")
_methods_ = [
# Returns the GUID for the object's outgoing IID for its default event set.
COMMETHOD([], HRESULT, "GetGUID",
( ['in'], DWORD, "dwGuidKind" ),
( ['out', 'retval'], POINTER(GUID), "pGUID" ))
]
emdescVar', ELEMDESC),
('wVarFlags', WORD),
('varkind', VARKIND),
]
tagBINDPTR._fields_ = [
('lpfuncdesc', POINTER(FUNCDESC)),
('lpvardesc', POINTER(VARDESC)),
('lptcomp', POINTER(ITypeComp)),
]
tagFUNCDESC._fields_ = [
('memid', MEMBERID),
('lprgscode', POINTER(SCODE)),
('lprgelemdescParam', POINTER(ELEMDESC)),
('funckind', FUNCKIND),
('invkind', INVOKEKIND),
('callconv', CALLCONV),
('cParams', SHORT),
('cParamsOpt', SHORT),
('oVft', SHORT),
('cScodes', SHORT),
('elemdescFunc', ELEMDESC),
('wFuncFlags', WORD),
]
tagPARAMDESCEX._fields_ = [
('cBytes', DWORD),
('varDefaultValue', VARIANTARG),
]
class tagSAFEARRAYBOUND(Structure):
_fields_ = [
('cElements', DWORD),
('lLbound', LONG),
]
SAFEARRAYBOUND = tagSAFEARRAYBOUND
tagARRAYDESC._fields_ = [
('tdescElem', TYPEDESC),
('cDims', USHORT),
('rgbounds', SAFEARRAYBOUND * 1),
]
| true | true |
f72698ecbc016f7724c2386a1d6649e19cd6da72 | 5,206 | py | Python | manimlib/animation/growing.py | SidewayOutput/Basic-Manim | 4dea4b00daa7b6f66ed7b26659045f67609d83b6 | [
"MIT"
] | null | null | null | manimlib/animation/growing.py | SidewayOutput/Basic-Manim | 4dea4b00daa7b6f66ed7b26659045f67609d83b6 | [
"MIT"
] | null | null | null | manimlib/animation/growing.py | SidewayOutput/Basic-Manim | 4dea4b00daa7b6f66ed7b26659045f67609d83b6 | [
"MIT"
] | null | null | null | from manimlib.animation.transform import Transform
from manimlib.basic.basic_function import to_expand_lists, to_get_point
from manimlib.constants import PI
from manimlib.utils.config_ops import generate_args, merge_config_kwargs
class GrowFromPoint(Transform):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
self.mobject_or_point = to_get_point(mobject_or_point, mobject)
self.args_name = ["point_color", "scale"]
self.args = [None, 0]
[self.point_color, self.scale] = \
generate_args(self, args, self.args)
kwargs = merge_config_kwargs(self, kwargs, self.args_name)
super().__init__(mobject, **kwargs)
def create_target(self):
return self.mobject
def create_starting_mobject(self):
mobject = self.create_initial_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_initial_mobject(self):
mobject = super().create_starting_mobject()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class GrowFromCenter(GrowFromPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class GrowFromEdge(GrowFromPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class GrowFromSide(GrowFromPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_initial_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class DiminishToPoint(GrowFromPoint):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
super().__init__(mobject, mobject_or_point, *args, **kwargs)
def create_target(self):
mobject = self.create_final_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_starting_mobject(self):
mobject = self.mobject.copy()
return mobject
def create_final_mobject(self):
mobject = self.mobject.copy()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class DiminishToCenter(DiminishToPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class DiminishToEdge(DiminishToPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class DiminishToSide(DiminishToPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_final_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class GrowArrow(GrowFromPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class ExpandArrow(GrowArrow):
def __init__(self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class DiminishArrow(DiminishToPoint):
def __init__(self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class RetractArrow(DiminishToPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class SpinInFromNothing(GrowFromCenter):
CONFIG = {
"path_arc": PI,
}
class SpinInFrom(GrowFromPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutFrom(SpinInFrom):
CONFIG = {
"path_arc": -PI,
}
class SpinInTo(DiminishToPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutTo(SpinInTo):
CONFIG = {
"path_arc": -PI,
}
| 32.135802 | 84 | 0.664426 | from manimlib.animation.transform import Transform
from manimlib.basic.basic_function import to_expand_lists, to_get_point
from manimlib.constants import PI
from manimlib.utils.config_ops import generate_args, merge_config_kwargs
class GrowFromPoint(Transform):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
self.mobject_or_point = to_get_point(mobject_or_point, mobject)
self.args_name = ["point_color", "scale"]
self.args = [None, 0]
[self.point_color, self.scale] = \
generate_args(self, args, self.args)
kwargs = merge_config_kwargs(self, kwargs, self.args_name)
super().__init__(mobject, **kwargs)
def create_target(self):
return self.mobject
def create_starting_mobject(self):
mobject = self.create_initial_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_initial_mobject(self):
mobject = super().create_starting_mobject()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class GrowFromCenter(GrowFromPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class GrowFromEdge(GrowFromPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class GrowFromSide(GrowFromPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_initial_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class DiminishToPoint(GrowFromPoint):
def __init__(self, mobject, mobject_or_point="get_center()", *args, **kwargs):
super().__init__(mobject, mobject_or_point, *args, **kwargs)
def create_target(self):
mobject = self.create_final_mobject()
mobject.set_stroke(
width=(mobject.stroke_width*self.scale))
if self.point_color:
mobject.set_color(self.point_color)
return mobject
def create_starting_mobject(self):
mobject = self.mobject.copy()
return mobject
def create_final_mobject(self):
mobject = self.mobject.copy()
return mobject.scale(self.scale).move_to(self.mobject_or_point)
class DiminishToCenter(DiminishToPoint):
def __init__(self, mobject, *args, **kwargs):
super().__init__(mobject, mobject.get_center(), *args, **kwargs)
class DiminishToEdge(DiminishToPoint):
def __init__(self, mobject, edge=[-1, 1, 0], *args, **kwargs):
super().__init__(mobject, mobject.get_critical_point(edge), *args, **kwargs)
class DiminishToSide(DiminishToPoint):
def __init__(self, mobject, side=[0, 1, 0], center=False, *args, **kwargs):
self.side = side
self.center = center
super().__init__(mobject, mobject.get_critical_point(side), *args, **kwargs)
def create_final_mobject(self):
mobject = self.mobject.copy()
dim = [i for i, each in enumerate(self.side) if each]
mobject.stretch_to_fit(to_expand_lists(self.scale, dim), dim)
if not self.center:
mobject.move_to(self.mobject_or_point)
else:
mobject.move_to(self.mobject.get_center())
return mobject
class GrowArrow(GrowFromPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class ExpandArrow(GrowArrow):
def __init__(self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class DiminishArrow(DiminishToPoint):
def __init__(self, arrow, point_by_ratio=1, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class RetractArrow(DiminishToPoint):
def __init__(self, arrow, point_by_ratio=0, *args, **kwargs):
super().__init__(arrow, point_by_ratio, *args, **kwargs)
class SpinInFromNothing(GrowFromCenter):
CONFIG = {
"path_arc": PI,
}
class SpinInFrom(GrowFromPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutFrom(SpinInFrom):
CONFIG = {
"path_arc": -PI,
}
class SpinInTo(DiminishToPoint):
CONFIG = {
"path_arc": PI,
}
def __init__(self, mobject, point="get_center()", *args, **kwargs):
super().__init__(mobject, point, *args, **kwargs)
class SpinOutTo(SpinInTo):
CONFIG = {
"path_arc": -PI,
}
| true | true |
f726991caedc24166bb6ed9a085571aa0555465e | 4,333 | py | Python | sdks/python/appcenter_sdk/models/InternalHockeyAppCutoverStatusResponse.py | Brantone/appcenter-sdks | eeb063ecf79908b6e341fb00196d2cd9dc8f3262 | [
"MIT"
] | null | null | null | sdks/python/appcenter_sdk/models/InternalHockeyAppCutoverStatusResponse.py | Brantone/appcenter-sdks | eeb063ecf79908b6e341fb00196d2cd9dc8f3262 | [
"MIT"
] | 6 | 2019-10-23T06:38:53.000Z | 2022-01-22T07:57:58.000Z | sdks/python/appcenter_sdk/models/InternalHockeyAppCutoverStatusResponse.py | Brantone/appcenter-sdks | eeb063ecf79908b6e341fb00196d2cd9dc8f3262 | [
"MIT"
] | 2 | 2019-10-23T06:31:05.000Z | 2021-08-21T17:32:47.000Z | # coding: utf-8
"""
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: benedetto.abbenanti@gmail.com
Project Repository: https://github.com/b3nab/appcenter-sdks
"""
import pprint
import re # noqa: F401
import six
class InternalHockeyAppCutoverStatusResponse(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
allowed enum values
"""
not_requested = "not_requested"
requested = "requested"
in_progress = "in_progress"
completed = "completed"
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'string',
'status': 'string'
}
attribute_map = {
'id': 'id',
'status': 'status'
}
def __init__(self, id=None, status=None): # noqa: E501
"""InternalHockeyAppCutoverStatusResponse - a model defined in Swagger""" # noqa: E501
self._id = None
self._status = None
self.discriminator = None
self.id = id
if status is not None:
self.status = status
@property
def id(self):
"""Gets the id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
The ID of the app # noqa: E501
:return: The id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:rtype: string
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this InternalHockeyAppCutoverStatusResponse.
The ID of the app # noqa: E501
:param id: The id of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:type: string
"""
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
self._id = id
@property
def status(self):
"""Gets the status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
Does the HockeyApp app have crashes from within the last 90 days? # noqa: E501
:return: The status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:rtype: string
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this InternalHockeyAppCutoverStatusResponse.
Does the HockeyApp app have crashes from within the last 90 days? # noqa: E501
:param status: The status of this InternalHockeyAppCutoverStatusResponse. # noqa: E501
:type: string
"""
allowed_values = [undefinedundefinedundefinedundefined] # noqa: E501
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InternalHockeyAppCutoverStatusResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 29.080537 | 95 | 0.587122 |
import pprint
import re
import six
class InternalHockeyAppCutoverStatusResponse(object):
not_requested = "not_requested"
requested = "requested"
in_progress = "in_progress"
completed = "completed"
swagger_types = {
'id': 'string',
'status': 'string'
}
attribute_map = {
'id': 'id',
'status': 'status'
}
def __init__(self, id=None, status=None):
self._id = None
self._status = None
self.discriminator = None
self.id = id
if status is not None:
self.status = status
@property
def id(self):
return self._id
@id.setter
def id(self, id):
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
self._id = id
@property
def status(self):
return self._status
@status.setter
def status(self, status):
allowed_values = [undefinedundefinedundefinedundefined]
self._status = status
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, InternalHockeyAppCutoverStatusResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f7269945af61fa78d01b7ddd1fc00faa4eb56f7f | 8,120 | py | Python | utils/swift_build_support/swift_build_support/targets.py | DougGregor/swift | 16b686989c12bb1acf9d1a490c1f301d71428f47 | [
"Apache-2.0"
] | 11 | 2016-01-26T22:56:55.000Z | 2022-03-28T05:57:56.000Z | utils/swift_build_support/swift_build_support/targets.py | danielgalasko/swift | e2501ad9f9e53a7156148d6da5c7796e487723f8 | [
"Apache-2.0"
] | 2 | 2019-04-11T21:36:21.000Z | 2021-04-14T06:09:10.000Z | utils/swift_build_support/swift_build_support/targets.py | DougGregor/swift | 16b686989c12bb1acf9d1a490c1f301d71428f47 | [
"Apache-2.0"
] | 1 | 2016-08-24T17:30:38.000Z | 2016-08-24T17:30:38.000Z | # swift_build_support/targets.py - Build target helpers -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt for license information
# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
import os
import platform
class Platform(object):
"""
Abstract representation of a platform Swift can run on.
"""
def __init__(self, name, archs, sdk_name=None):
"""
Create a platform with the given name and list of architectures.
"""
self.name = name
self.targets = [Target(self, arch) for arch in archs]
# FIXME: Eliminate this argument; apparently the SDK names are
# internally a private implementation detail of the build script, so we
# should just make them the same as the platform name.
self.sdk_name = name.upper() if sdk_name is None else sdk_name
# Add a property for each arch.
for target in self.targets:
setattr(self, target.arch, target)
@property
def is_darwin(self):
"""Convenience function for checking if this is a Darwin platform."""
return isinstance(self, DarwinPlatform)
@property
def supports_benchmark(self):
# By default, we don't support benchmarks on most platforms.
return False
def contains(self, target_name):
"""
Returns True if the given target name belongs to a one of this
platform's targets.
"""
for target in self.targets:
if target.name == target_name:
return True
return False
class DarwinPlatform(Platform):
def __init__(self, name, archs, sdk_name=None, is_simulator=False):
self.is_simulator = is_simulator
super(DarwinPlatform, self).__init__(name, archs, sdk_name)
@property
def is_embedded(self):
"""Check if this is a Darwin platform for embedded devices."""
return self.name != "macosx"
@property
def supports_benchmark(self):
# By default, on Darwin we support benchmarks on all non-simulator
# platforms.
return not self.is_simulator
class Target(object):
"""
Abstract representation of a target Swift can run on.
"""
def __init__(self, platform, arch):
self.platform = platform
self.arch = arch
# Delegate to the platform, this is usually not arch specific.
self.supports_benchmark = self.platform.supports_benchmark
@property
def name(self):
return "{}-{}".format(self.platform.name, self.arch)
class StdlibDeploymentTarget(object):
OSX = DarwinPlatform("macosx", archs=["x86_64"],
sdk_name="OSX")
iOS = DarwinPlatform("iphoneos", archs=["armv7", "armv7s", "arm64"],
sdk_name="IOS")
iOSSimulator = DarwinPlatform("iphonesimulator", archs=["i386", "x86_64"],
sdk_name="IOS_SIMULATOR",
is_simulator=True)
# Never build/test benchmarks on iOS armv7s.
iOS.armv7s.supports_benchmark = False
AppleTV = DarwinPlatform("appletvos", archs=["arm64"],
sdk_name="TVOS")
AppleTVSimulator = DarwinPlatform("appletvsimulator", archs=["x86_64"],
sdk_name="TVOS_SIMULATOR",
is_simulator=True)
AppleWatch = DarwinPlatform("watchos", archs=["armv7k"],
sdk_name="WATCHOS")
AppleWatchSimulator = DarwinPlatform("watchsimulator", archs=["i386"],
sdk_name="WATCHOS_SIMULATOR",
is_simulator=True)
Linux = Platform("linux", archs=[
"x86_64",
"armv6",
"armv7",
"aarch64",
"ppc64",
"ppc64le",
"s390x"])
FreeBSD = Platform("freebsd", archs=["x86_64"])
Cygwin = Platform("cygwin", archs=["x86_64"])
Android = Platform("android", archs=["armv7"])
# The list of known platforms.
known_platforms = [
OSX,
iOS, iOSSimulator,
AppleTV, AppleTVSimulator,
AppleWatch, AppleWatchSimulator,
Linux,
FreeBSD,
Cygwin,
Android]
# Cache of targets by name.
_targets_by_name = dict((target.name, target)
for platform in known_platforms
for target in platform.targets)
@staticmethod
def host_target():
"""
Return the host target for the build machine, if it is one of
the recognized targets. Otherwise, return None.
"""
system = platform.system()
machine = platform.machine()
if system == 'Linux':
if machine == 'x86_64':
return StdlibDeploymentTarget.Linux.x86_64
elif machine.startswith('armv7'):
# linux-armv7* is canonicalized to 'linux-armv7'
return StdlibDeploymentTarget.Linux.armv7
elif machine.startswith('armv6'):
# linux-armv6* is canonicalized to 'linux-armv6'
return StdlibDeploymentTarget.Linux.armv6
elif machine == 'aarch64':
return StdlibDeploymentTarget.Linux.aarch64
elif machine == 'ppc64':
return StdlibDeploymentTarget.Linux.ppc64
elif machine == 'ppc64le':
return StdlibDeploymentTarget.Linux.ppc64le
elif machine == 's390x':
return StdlibDeploymentTarget.Linux.s390x
elif system == 'Darwin':
if machine == 'x86_64':
return StdlibDeploymentTarget.OSX.x86_64
elif system == 'FreeBSD':
if machine == 'amd64':
return StdlibDeploymentTarget.FreeBSD.x86_64
elif system == 'CYGWIN_NT-10.0':
if machine == 'x86_64':
return StdlibDeploymentTarget.Cygwin.x86_64
return None
@staticmethod
def default_stdlib_deployment_targets():
"""
Return targets for the Swift stdlib, based on the build machine.
If the build machine is not one of the recognized ones, return None.
"""
host_target = StdlibDeploymentTarget.host_target()
if host_target is None:
return None
# OS X build machines configure all Darwin platforms by default.
# Put iOS native targets last so that we test them last
# (it takes a long time).
if host_target == StdlibDeploymentTarget.OSX.x86_64:
return [host_target] + \
StdlibDeploymentTarget.iOSSimulator.targets + \
StdlibDeploymentTarget.AppleTVSimulator.targets + \
StdlibDeploymentTarget.AppleWatchSimulator.targets + \
StdlibDeploymentTarget.iOS.targets + \
StdlibDeploymentTarget.AppleTV.targets + \
StdlibDeploymentTarget.AppleWatch.targets
else:
# All other machines only configure their host stdlib by default.
return [host_target]
@classmethod
def get_target_for_name(cls, name):
return cls._targets_by_name.get(name)
def install_prefix():
"""
Returns the default path at which built Swift products (like bin, lib,
and include) will be installed, based on the host machine's operating
system.
"""
if platform.system() == 'Darwin':
return '/Applications/Xcode.app/Contents/Developer/Toolchains/' + \
'XcodeDefault.xctoolchain/usr'
else:
return '/usr'
def darwin_toolchain_prefix(darwin_install_prefix):
"""
Given the install prefix for a Darwin system, and assuming that that path
is to a .xctoolchain directory, return the path to the .xctoolchain
directory.
"""
return os.path.split(darwin_install_prefix)[0]
| 34.261603 | 79 | 0.607759 |
import os
import platform
class Platform(object):
def __init__(self, name, archs, sdk_name=None):
self.name = name
self.targets = [Target(self, arch) for arch in archs]
self.sdk_name = name.upper() if sdk_name is None else sdk_name
for target in self.targets:
setattr(self, target.arch, target)
@property
def is_darwin(self):
return isinstance(self, DarwinPlatform)
@property
def supports_benchmark(self):
return False
def contains(self, target_name):
for target in self.targets:
if target.name == target_name:
return True
return False
class DarwinPlatform(Platform):
def __init__(self, name, archs, sdk_name=None, is_simulator=False):
self.is_simulator = is_simulator
super(DarwinPlatform, self).__init__(name, archs, sdk_name)
@property
def is_embedded(self):
return self.name != "macosx"
@property
def supports_benchmark(self):
# By default, on Darwin we support benchmarks on all non-simulator
# platforms.
return not self.is_simulator
class Target(object):
def __init__(self, platform, arch):
self.platform = platform
self.arch = arch
# Delegate to the platform, this is usually not arch specific.
self.supports_benchmark = self.platform.supports_benchmark
@property
def name(self):
return "{}-{}".format(self.platform.name, self.arch)
class StdlibDeploymentTarget(object):
OSX = DarwinPlatform("macosx", archs=["x86_64"],
sdk_name="OSX")
iOS = DarwinPlatform("iphoneos", archs=["armv7", "armv7s", "arm64"],
sdk_name="IOS")
iOSSimulator = DarwinPlatform("iphonesimulator", archs=["i386", "x86_64"],
sdk_name="IOS_SIMULATOR",
is_simulator=True)
# Never build/test benchmarks on iOS armv7s.
iOS.armv7s.supports_benchmark = False
AppleTV = DarwinPlatform("appletvos", archs=["arm64"],
sdk_name="TVOS")
AppleTVSimulator = DarwinPlatform("appletvsimulator", archs=["x86_64"],
sdk_name="TVOS_SIMULATOR",
is_simulator=True)
AppleWatch = DarwinPlatform("watchos", archs=["armv7k"],
sdk_name="WATCHOS")
AppleWatchSimulator = DarwinPlatform("watchsimulator", archs=["i386"],
sdk_name="WATCHOS_SIMULATOR",
is_simulator=True)
Linux = Platform("linux", archs=[
"x86_64",
"armv6",
"armv7",
"aarch64",
"ppc64",
"ppc64le",
"s390x"])
FreeBSD = Platform("freebsd", archs=["x86_64"])
Cygwin = Platform("cygwin", archs=["x86_64"])
Android = Platform("android", archs=["armv7"])
# The list of known platforms.
known_platforms = [
OSX,
iOS, iOSSimulator,
AppleTV, AppleTVSimulator,
AppleWatch, AppleWatchSimulator,
Linux,
FreeBSD,
Cygwin,
Android]
# Cache of targets by name.
_targets_by_name = dict((target.name, target)
for platform in known_platforms
for target in platform.targets)
@staticmethod
def host_target():
system = platform.system()
machine = platform.machine()
if system == 'Linux':
if machine == 'x86_64':
return StdlibDeploymentTarget.Linux.x86_64
elif machine.startswith('armv7'):
# linux-armv7* is canonicalized to 'linux-armv7'
return StdlibDeploymentTarget.Linux.armv7
elif machine.startswith('armv6'):
# linux-armv6* is canonicalized to 'linux-armv6'
return StdlibDeploymentTarget.Linux.armv6
elif machine == 'aarch64':
return StdlibDeploymentTarget.Linux.aarch64
elif machine == 'ppc64':
return StdlibDeploymentTarget.Linux.ppc64
elif machine == 'ppc64le':
return StdlibDeploymentTarget.Linux.ppc64le
elif machine == 's390x':
return StdlibDeploymentTarget.Linux.s390x
elif system == 'Darwin':
if machine == 'x86_64':
return StdlibDeploymentTarget.OSX.x86_64
elif system == 'FreeBSD':
if machine == 'amd64':
return StdlibDeploymentTarget.FreeBSD.x86_64
elif system == 'CYGWIN_NT-10.0':
if machine == 'x86_64':
return StdlibDeploymentTarget.Cygwin.x86_64
return None
@staticmethod
def default_stdlib_deployment_targets():
host_target = StdlibDeploymentTarget.host_target()
if host_target is None:
return None
# OS X build machines configure all Darwin platforms by default.
# Put iOS native targets last so that we test them last
# (it takes a long time).
if host_target == StdlibDeploymentTarget.OSX.x86_64:
return [host_target] + \
StdlibDeploymentTarget.iOSSimulator.targets + \
StdlibDeploymentTarget.AppleTVSimulator.targets + \
StdlibDeploymentTarget.AppleWatchSimulator.targets + \
StdlibDeploymentTarget.iOS.targets + \
StdlibDeploymentTarget.AppleTV.targets + \
StdlibDeploymentTarget.AppleWatch.targets
else:
# All other machines only configure their host stdlib by default.
return [host_target]
@classmethod
def get_target_for_name(cls, name):
return cls._targets_by_name.get(name)
def install_prefix():
if platform.system() == 'Darwin':
return '/Applications/Xcode.app/Contents/Developer/Toolchains/' + \
'XcodeDefault.xctoolchain/usr'
else:
return '/usr'
def darwin_toolchain_prefix(darwin_install_prefix):
return os.path.split(darwin_install_prefix)[0]
| true | true |
f7269969627b886f2d9ff179c1f78a4abf30f3d0 | 1,426 | py | Python | Python/DataStructures/Trie.py | AndrewMcShane/DevMakingSource | fe58fa093e0ce2d2748cb3826d27be6b0ac34149 | [
"MIT"
] | 3 | 2021-03-22T14:13:56.000Z | 2022-03-01T03:06:22.000Z | Python/DataStructures/Trie.py | AndrewMcShane/DevMakingSource | fe58fa093e0ce2d2748cb3826d27be6b0ac34149 | [
"MIT"
] | null | null | null | Python/DataStructures/Trie.py | AndrewMcShane/DevMakingSource | fe58fa093e0ce2d2748cb3826d27be6b0ac34149 | [
"MIT"
] | null | null | null | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def put(self, word):
current = self.root
for i in range(0, len(word)):
child = word[i]
tmp = None
try:
tmp = current.children[child]
except KeyError:
tmp = TrieNode()
current.children[child] = tmp
current = tmp
current.isWord = True
def contains(self, word):
current = self.root
for i in range(0, len(word)):
child = word[i]
try:
current = current.children[child]
except KeyError:
return False
return current.isWord
def remove(self, word):
self._removeRecursive(self.root, word, 0)
def _removeRecursive(self, current, word, depth):
if current is None:
return None
if depth == len(word):
current.isWord = False
else:
child = word[depth]
if child in current.children:
self._removeRecursive(current.children[child], word, depth + 1)
else:
del current.children[child]
if not bool(current.children):
return current
return None
| 26.90566 | 80 | 0.497896 | class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def put(self, word):
current = self.root
for i in range(0, len(word)):
child = word[i]
tmp = None
try:
tmp = current.children[child]
except KeyError:
tmp = TrieNode()
current.children[child] = tmp
current = tmp
current.isWord = True
def contains(self, word):
current = self.root
for i in range(0, len(word)):
child = word[i]
try:
current = current.children[child]
except KeyError:
return False
return current.isWord
def remove(self, word):
self._removeRecursive(self.root, word, 0)
def _removeRecursive(self, current, word, depth):
if current is None:
return None
if depth == len(word):
current.isWord = False
else:
child = word[depth]
if child in current.children:
self._removeRecursive(current.children[child], word, depth + 1)
else:
del current.children[child]
if not bool(current.children):
return current
return None
| true | true |
f72699b30c150ef217cd9689772840359f84dd62 | 8,999 | py | Python | sunpy/coordinates/wcs_utils.py | LaudateCorpus1/sunpy | f7bdf22e5229a577c5851c1e05502f0d68b4b369 | [
"BSD-2-Clause"
] | 628 | 2015-01-14T17:34:10.000Z | 2022-03-29T06:07:50.000Z | sunpy/coordinates/wcs_utils.py | wtbarnes/sunpy | f7bdf22e5229a577c5851c1e05502f0d68b4b369 | [
"BSD-2-Clause"
] | 3,983 | 2015-01-03T11:16:21.000Z | 2022-03-31T16:55:38.000Z | sunpy/coordinates/wcs_utils.py | wtbarnes/sunpy | f7bdf22e5229a577c5851c1e05502f0d68b4b369 | [
"BSD-2-Clause"
] | 582 | 2015-01-14T10:09:24.000Z | 2022-03-29T06:07:12.000Z | import numpy as np
import astropy.units as u
import astropy.wcs.utils
from astropy.coordinates import (
ITRS,
BaseCoordinateFrame,
CartesianRepresentation,
SkyCoord,
SphericalRepresentation,
)
from astropy.wcs import WCS
from sunpy import log
from .frames import (
BaseCoordinateFrame,
Heliocentric,
HeliographicCarrington,
HeliographicStonyhurst,
Helioprojective,
SunPyBaseCoordinateFrame,
)
__all__ = ['solar_wcs_frame_mapping', 'solar_frame_to_wcs_mapping']
try:
# TODO: Remove vendored version after Astropy 5.0
from astropy.wcs.utils import obsgeo_to_frame
except ImportError:
def obsgeo_to_frame(obsgeo, obstime):
"""
Convert a WCS obsgeo property into an `~builtin_frames.ITRS` coordinate frame.
Parameters
----------
obsgeo : array-like
A shape ``(6, )`` array representing ``OBSGEO-[XYZ], OBSGEO-[BLH]`` as
returned by ``WCS.wcs.obsgeo``.
obstime : time-like
The time assiociated with the coordinate, will be passed to
`~.builtin_frames.ITRS` as the obstime keyword.
Returns
-------
`~.builtin_frames.ITRS`
An `~.builtin_frames.ITRS` coordinate frame
representing the coordinates.
Notes
-----
The obsgeo array as accessed on a `.WCS` object is a length 6 numpy array
where the first three elements are the coordinate in a cartesian
representation and the second 3 are the coordinate in a spherical
representation.
This function priorities reading the cartesian coordinates, and will only
read the spherical coordinates if the cartesian coordinates are either all
zero or any of the cartesian coordinates are non-finite.
In the case where both the spherical and cartesian coordinates have some
non-finite values the spherical coordinates will be returned with the
non-finite values included.
"""
if (obsgeo is None
or len(obsgeo) != 6
or np.all(np.array(obsgeo) == 0)
or np.all(~np.isfinite(obsgeo))
): # NOQA
raise ValueError(f"Can not parse the 'obsgeo' location ({obsgeo}). "
"obsgeo should be a length 6 non-zero, finite numpy array")
# If the cartesian coords are zero or have NaNs in them use the spherical ones
if np.all(obsgeo[:3] == 0) or np.any(~np.isfinite(obsgeo[:3])):
data = SphericalRepresentation(*(obsgeo[3:] * (u.deg, u.deg, u.m)))
# Otherwise we assume the cartesian ones are valid
else:
data = CartesianRepresentation(*obsgeo[:3] * u.m)
return ITRS(data, obstime=obstime)
def solar_wcs_frame_mapping(wcs):
"""
This function registers the coordinates frames to their FITS-WCS coordinate
type values in the `astropy.wcs.utils.wcs_to_celestial_frame` registry.
Parameters
----------
wcs : astropy.wcs.WCS
Returns
-------
astropy.coordinates.BaseCoordinateFrame
"""
if hasattr(wcs, "coordinate_frame"):
return wcs.coordinate_frame
dateobs = wcs.wcs.dateobs or None
# Get observer coordinate from the WCS auxillary information
required_attrs = {HeliographicStonyhurst: ['hgln_obs', 'hglt_obs', 'dsun_obs'],
HeliographicCarrington: ['crln_obs', 'hglt_obs', 'dsun_obs']}
# Get rsun from the WCS auxillary information
rsun = wcs.wcs.aux.rsun_ref
if rsun is not None:
rsun *= u.m
# TODO: remove these errors in sunpy 4.1
bad_attrs = [f'.{attr}' for attr in ['rsun', 'heliographic_observer']
if hasattr(wcs, attr)]
if len(bad_attrs):
raise ValueError(f"The {' and '.join(bad_attrs)} attribute(s) on a WCS "
"are no longer supported.")
observer = None
for frame, attr_names in required_attrs.items():
attrs = [getattr(wcs.wcs.aux, attr_name) for attr_name in attr_names]
if all([attr is not None for attr in attrs]):
kwargs = {'obstime': dateobs}
if rsun is not None:
kwargs['rsun'] = rsun
if issubclass(frame, HeliographicCarrington):
kwargs['observer'] = 'self'
observer = frame(attrs[0] * u.deg,
attrs[1] * u.deg,
attrs[2] * u.m,
**kwargs)
# Read the observer out of obsgeo for ground based observers
if observer is None:
try:
observer = obsgeo_to_frame(wcs.wcs.obsgeo, dateobs)
observer = SkyCoord(observer, rsun=rsun)
except ValueError as e:
# The helper function assumes you know the obsgeo coords you are
# parsing are good, we are not sure, so catch the error.
# This approach could lead to an invalid observer (i.e. one of the
# coords being NaN), but only if the WCS has been constructed like that.
log.debug(f"Could not parse obsgeo coordinates from WCS:\n{e}")
# Collect all of the possible frame attributes, although some may be removed later
frame_args = {'obstime': dateobs}
if observer is not None:
frame_args['observer'] = observer
if rsun is not None:
frame_args['rsun'] = rsun
frame_class = _sunpy_frame_class_from_ctypes(wcs.wcs.ctype)
if frame_class:
if frame_class == HeliographicStonyhurst:
frame_args.pop('observer', None)
if frame_class == Heliocentric:
frame_args.pop('rsun', None)
return frame_class(**frame_args)
def _sunpy_frame_class_from_ctypes(ctypes):
# Truncate the ctype to the first four letters
ctypes = {c[:4] for c in ctypes}
mapping = {
Helioprojective: {'HPLN', 'HPLT'},
HeliographicStonyhurst: {'HGLN', 'HGLT'},
HeliographicCarrington: {'CRLN', 'CRLT'},
Heliocentric: {'SOLX', 'SOLY'},
}
for frame_class, ctype_pair in mapping.items():
if ctype_pair <= ctypes:
return frame_class
def _set_wcs_aux_obs_coord(wcs, obs_frame):
"""
Set (in-place) observer coordinate information on a WCS.
Parameters
----------
wcs : astropy.wcs.WCS
obs_frame : astropy.coordinates.SkyCoord, astropy.coordinates.CoordinateFrame
"""
# Sometimes obs_coord can be a SkyCoord, so convert down to a frame
if hasattr(obs_frame, 'frame'):
obs_frame = obs_frame.frame
if isinstance(obs_frame, HeliographicStonyhurst):
wcs.wcs.aux.hgln_obs = obs_frame.lon.to_value(u.deg)
elif isinstance(obs_frame, HeliographicCarrington):
wcs.wcs.aux.crln_obs = obs_frame.lon.to_value(u.deg)
else:
raise ValueError('obs_coord must be in a Stonyhurst or Carrington frame')
# These two keywords are the same for Carrington and Stonyhurst
wcs.wcs.aux.hglt_obs = obs_frame.lat.to_value(u.deg)
wcs.wcs.aux.dsun_obs = obs_frame.radius.to_value(u.m)
def solar_frame_to_wcs_mapping(frame, projection='TAN'):
"""
For a given frame, this function returns the corresponding WCS object.
It registers the WCS coordinates types from their associated frame in the
`astropy.wcs.utils.celestial_frame_to_wcs` registry.
Parameters
----------
frame : astropy.coordinates.BaseCoordinateFrame
projection : str, optional
Returns
-------
astropy.wcs.WCS
"""
wcs = WCS(naxis=2)
if hasattr(frame, 'rsun'):
wcs.wcs.aux.rsun_ref = frame.rsun.to_value(u.m)
if hasattr(frame, 'observer') and frame.observer is not None:
if isinstance(frame.observer, BaseCoordinateFrame):
observer = frame.observer
elif frame.observer == 'self':
observer = frame
_set_wcs_aux_obs_coord(wcs, observer)
if isinstance(frame, SunPyBaseCoordinateFrame):
if frame.obstime:
wcs.wcs.dateobs = frame.obstime.utc.isot
if isinstance(frame, Helioprojective):
xcoord = 'HPLN' + '-' + projection
ycoord = 'HPLT' + '-' + projection
wcs.wcs.cunit = ['arcsec', 'arcsec']
elif isinstance(frame, Heliocentric):
xcoord = 'SOLX'
ycoord = 'SOLY'
wcs.wcs.cunit = ['deg', 'deg']
elif isinstance(frame, HeliographicCarrington):
xcoord = 'CRLN' + '-' + projection
ycoord = 'CRLT' + '-' + projection
wcs.wcs.cunit = ['deg', 'deg']
elif isinstance(frame, HeliographicStonyhurst):
xcoord = 'HGLN' + '-' + projection
ycoord = 'HGLT' + '-' + projection
wcs.wcs.cunit = ['deg', 'deg']
else:
return None
wcs.wcs.ctype = [xcoord, ycoord]
return wcs
astropy.wcs.utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping])
astropy.wcs.utils.FRAME_WCS_MAPPINGS.append([solar_frame_to_wcs_mapping])
| 33.830827 | 88 | 0.628737 | import numpy as np
import astropy.units as u
import astropy.wcs.utils
from astropy.coordinates import (
ITRS,
BaseCoordinateFrame,
CartesianRepresentation,
SkyCoord,
SphericalRepresentation,
)
from astropy.wcs import WCS
from sunpy import log
from .frames import (
BaseCoordinateFrame,
Heliocentric,
HeliographicCarrington,
HeliographicStonyhurst,
Helioprojective,
SunPyBaseCoordinateFrame,
)
__all__ = ['solar_wcs_frame_mapping', 'solar_frame_to_wcs_mapping']
try:
from astropy.wcs.utils import obsgeo_to_frame
except ImportError:
def obsgeo_to_frame(obsgeo, obstime):
"""
Convert a WCS obsgeo property into an `~builtin_frames.ITRS` coordinate frame.
Parameters
----------
obsgeo : array-like
A shape ``(6, )`` array representing ``OBSGEO-[XYZ], OBSGEO-[BLH]`` as
returned by ``WCS.wcs.obsgeo``.
obstime : time-like
The time assiociated with the coordinate, will be passed to
`~.builtin_frames.ITRS` as the obstime keyword.
Returns
-------
`~.builtin_frames.ITRS`
An `~.builtin_frames.ITRS` coordinate frame
representing the coordinates.
Notes
-----
The obsgeo array as accessed on a `.WCS` object is a length 6 numpy array
where the first three elements are the coordinate in a cartesian
representation and the second 3 are the coordinate in a spherical
representation.
This function priorities reading the cartesian coordinates, and will only
read the spherical coordinates if the cartesian coordinates are either all
zero or any of the cartesian coordinates are non-finite.
In the case where both the spherical and cartesian coordinates have some
non-finite values the spherical coordinates will be returned with the
non-finite values included.
"""
if (obsgeo is None
or len(obsgeo) != 6
or np.all(np.array(obsgeo) == 0)
or np.all(~np.isfinite(obsgeo))
):
raise ValueError(f"Can not parse the 'obsgeo' location ({obsgeo}). "
"obsgeo should be a length 6 non-zero, finite numpy array")
if np.all(obsgeo[:3] == 0) or np.any(~np.isfinite(obsgeo[:3])):
data = SphericalRepresentation(*(obsgeo[3:] * (u.deg, u.deg, u.m)))
else:
data = CartesianRepresentation(*obsgeo[:3] * u.m)
return ITRS(data, obstime=obstime)
def solar_wcs_frame_mapping(wcs):
if hasattr(wcs, "coordinate_frame"):
return wcs.coordinate_frame
dateobs = wcs.wcs.dateobs or None
required_attrs = {HeliographicStonyhurst: ['hgln_obs', 'hglt_obs', 'dsun_obs'],
HeliographicCarrington: ['crln_obs', 'hglt_obs', 'dsun_obs']}
rsun = wcs.wcs.aux.rsun_ref
if rsun is not None:
rsun *= u.m
bad_attrs = [f'.{attr}' for attr in ['rsun', 'heliographic_observer']
if hasattr(wcs, attr)]
if len(bad_attrs):
raise ValueError(f"The {' and '.join(bad_attrs)} attribute(s) on a WCS "
"are no longer supported.")
observer = None
for frame, attr_names in required_attrs.items():
attrs = [getattr(wcs.wcs.aux, attr_name) for attr_name in attr_names]
if all([attr is not None for attr in attrs]):
kwargs = {'obstime': dateobs}
if rsun is not None:
kwargs['rsun'] = rsun
if issubclass(frame, HeliographicCarrington):
kwargs['observer'] = 'self'
observer = frame(attrs[0] * u.deg,
attrs[1] * u.deg,
attrs[2] * u.m,
**kwargs)
if observer is None:
try:
observer = obsgeo_to_frame(wcs.wcs.obsgeo, dateobs)
observer = SkyCoord(observer, rsun=rsun)
except ValueError as e:
log.debug(f"Could not parse obsgeo coordinates from WCS:\n{e}")
frame_args = {'obstime': dateobs}
if observer is not None:
frame_args['observer'] = observer
if rsun is not None:
frame_args['rsun'] = rsun
frame_class = _sunpy_frame_class_from_ctypes(wcs.wcs.ctype)
if frame_class:
if frame_class == HeliographicStonyhurst:
frame_args.pop('observer', None)
if frame_class == Heliocentric:
frame_args.pop('rsun', None)
return frame_class(**frame_args)
def _sunpy_frame_class_from_ctypes(ctypes):
ctypes = {c[:4] for c in ctypes}
mapping = {
Helioprojective: {'HPLN', 'HPLT'},
HeliographicStonyhurst: {'HGLN', 'HGLT'},
HeliographicCarrington: {'CRLN', 'CRLT'},
Heliocentric: {'SOLX', 'SOLY'},
}
for frame_class, ctype_pair in mapping.items():
if ctype_pair <= ctypes:
return frame_class
def _set_wcs_aux_obs_coord(wcs, obs_frame):
if hasattr(obs_frame, 'frame'):
obs_frame = obs_frame.frame
if isinstance(obs_frame, HeliographicStonyhurst):
wcs.wcs.aux.hgln_obs = obs_frame.lon.to_value(u.deg)
elif isinstance(obs_frame, HeliographicCarrington):
wcs.wcs.aux.crln_obs = obs_frame.lon.to_value(u.deg)
else:
raise ValueError('obs_coord must be in a Stonyhurst or Carrington frame')
wcs.wcs.aux.hglt_obs = obs_frame.lat.to_value(u.deg)
wcs.wcs.aux.dsun_obs = obs_frame.radius.to_value(u.m)
def solar_frame_to_wcs_mapping(frame, projection='TAN'):
wcs = WCS(naxis=2)
if hasattr(frame, 'rsun'):
wcs.wcs.aux.rsun_ref = frame.rsun.to_value(u.m)
if hasattr(frame, 'observer') and frame.observer is not None:
if isinstance(frame.observer, BaseCoordinateFrame):
observer = frame.observer
elif frame.observer == 'self':
observer = frame
_set_wcs_aux_obs_coord(wcs, observer)
if isinstance(frame, SunPyBaseCoordinateFrame):
if frame.obstime:
wcs.wcs.dateobs = frame.obstime.utc.isot
if isinstance(frame, Helioprojective):
xcoord = 'HPLN' + '-' + projection
ycoord = 'HPLT' + '-' + projection
wcs.wcs.cunit = ['arcsec', 'arcsec']
elif isinstance(frame, Heliocentric):
xcoord = 'SOLX'
ycoord = 'SOLY'
wcs.wcs.cunit = ['deg', 'deg']
elif isinstance(frame, HeliographicCarrington):
xcoord = 'CRLN' + '-' + projection
ycoord = 'CRLT' + '-' + projection
wcs.wcs.cunit = ['deg', 'deg']
elif isinstance(frame, HeliographicStonyhurst):
xcoord = 'HGLN' + '-' + projection
ycoord = 'HGLT' + '-' + projection
wcs.wcs.cunit = ['deg', 'deg']
else:
return None
wcs.wcs.ctype = [xcoord, ycoord]
return wcs
astropy.wcs.utils.WCS_FRAME_MAPPINGS.append([solar_wcs_frame_mapping])
astropy.wcs.utils.FRAME_WCS_MAPPINGS.append([solar_frame_to_wcs_mapping])
| true | true |
f7269bbfbe9e6440da662f049b38c023e316d1dd | 17,900 | py | Python | backend/main.py | Plane-walker/fabric-draw | 7a3b4baef4d59a47c046e68d1fc5f20aeddd4c11 | [
"MIT"
] | 1 | 2021-09-01T06:31:26.000Z | 2021-09-01T06:31:26.000Z | backend/main.py | Plane-walker/fabric-draw | 7a3b4baef4d59a47c046e68d1fc5f20aeddd4c11 | [
"MIT"
] | 20 | 2021-09-22T13:04:07.000Z | 2021-10-11T12:27:12.000Z | backend/main.py | Plane-walker/fabric-draw | 7a3b4baef4d59a47c046e68d1fc5f20aeddd4c11 | [
"MIT"
] | null | null | null | import paramiko
import time
import io
import os
import stat
from yaml_generator import CAYamlGenerator, OrderYamlGenerator, PeerYamlGenerator, ConfigTXYamlGenerator
def sftp_get_r(sftp_client, remote_path, local_path):
try:
sftp_client.stat(remote_path)
except IOError:
return
if not os.path.exists(local_path):
os.mkdir(local_path)
for item in sftp_client.listdir(remote_path):
if stat.S_ISDIR(sftp_client.stat(f'{remote_path}/{item}').st_mode):
sftp_get_r(sftp_client, f'{remote_path}/{item}', os.path.join(local_path, item))
else:
sftp_client.get(f'{remote_path}/{item}', os.path.join(local_path, item))
def sftp_put_r(sftp_client, local_path, remote_path):
if not os.path.exists(local_path):
return
path = ""
for dir in remote_path.split("/"):
if dir == "":
continue
path += f"/{dir}"
try:
sftp_client.listdir(path)
except IOError:
sftp_client.mkdir(path)
try:
sftp_client.stat(remote_path)
except IOError:
sftp_client.mkdir(remote_path)
for item in os.listdir(local_path):
if os.path.isfile(os.path.join(local_path, item)):
sftp_client.put(os.path.join(local_path, item), f'{remote_path}/{item}')
else:
sftp_put_r(sftp_client, os.path.join(local_path, item), f'{remote_path}/{item}')
def generate_ca(ca_id, ca_information, fabric_name, target_host, crypto_base):
node_name, group_name, domain = ca_id.split('.', 2)
address = ca_information['address']
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base} ]; then mkdir -p {crypto_base}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
if group_name == 'orderer':
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name init_docker_swarm {target_host} {fabric_name} {crypto_base}')
stdout.channel.recv_exit_status()
ftp_client.get(f'{crypto_base}/token', 'token')
else:
try:
ftp_client.stat(f'{crypto_base}/token')
except IOError:
node_host = address['host']
ftp_client.put('token', f'{crypto_base}/token')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name join_docker_swarm {node_host} {target_host} {crypto_base}')
stdout.channel.recv_exit_status()
ca_yaml_generator = CAYamlGenerator()
file_name = ca_yaml_generator.generate(ca_id, group_name, fabric_name, address['fabric_port'], crypto_base)
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{file_name} up -d')
stdout.channel.recv_exit_status()
time.sleep(4)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
if not os.path.exists(tls_cert_path):
os.makedirs(tls_cert_path)
ftp_client.get(f'{crypto_base}/{tls_cert_path}/tls-cert.pem', f'{tls_cert_path}/tls-cert.pem')
ftp_client.close()
ssh.close()
def generate_order_msp(order_id, order_information, ca_port, crypto_base):
node_name, group_name, domain = order_id.split('.', 2)
address = order_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_cert_path} ]; then mkdir -p {crypto_base}/{tls_cert_path}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
ftp_client.put(f'{tls_cert_path}/tls-cert.pem', f'{crypto_base}/{tls_cert_path}/tls-cert.pem')
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name org_msp_generate {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
# print(stdout.readlines(), stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name peer_msp_generate {node_name} {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
# print(stdout.readlines(), stderr.readlines())
tls_ca_path = f'organizations/{group_name}.{domain}/tlsca'
if not os.path.exists(tls_ca_path):
os.makedirs(tls_ca_path)
ftp_client.get(f'{crypto_base}/{tls_ca_path}/tlsca.{group_name}.{domain}-cert.pem', f'{tls_ca_path}/tlsca.{group_name}.{domain}-cert.pem')
server_path = f'organizations/{group_name}.{domain}/peers/{order_id}/tls'
if not os.path.exists(server_path):
os.makedirs(server_path)
ftp_client.get(f'{crypto_base}/{server_path}/server.crt', f'{server_path}/server.crt')
ftp_client.close()
def generate_peer(peer_id, peer_information, order_group_id, fabric_name, target_host, ca_port, crypto_base):
node_name, group_name, domain = peer_id.split('.', 2)
address = peer_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_cert_path} ]; then mkdir -p {crypto_base}/{tls_cert_path}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
ftp_client.put(f'{tls_cert_path}/tls-cert.pem', f'{crypto_base}/{tls_cert_path}/tls-cert.pem')
tls_ca_path = f'organizations/{order_group_id}/tlsca'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_ca_path} ]; then mkdir -p {crypto_base}/{tls_ca_path}; fi')
stdout.channel.recv_exit_status()
ftp_client.put(f'{tls_ca_path}/tlsca.{order_group_id}-cert.pem', f'{crypto_base}/{tls_ca_path}/tlsca.{order_group_id}-cert.pem')
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
try:
ftp_client.stat(f'{crypto_base}/token')
except IOError:
node_host = address['host']
ftp_client.put('token', f'{crypto_base}/token')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name join_docker_swarm {node_host} {target_host} {crypto_base}')
stdout.channel.recv_exit_status()
peer_yaml_generator = PeerYamlGenerator()
file_name = peer_yaml_generator.generate(peer_id, fabric_name, address['fabric_port'], crypto_base)
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name org_msp_generate {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name peer_msp_generate {node_name} {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{file_name} up -d')
stdout.channel.recv_exit_status()
print(stderr.readlines())
time.sleep(3)
peer_path = f'organizations/{group_name}.{domain}'
if not os.path.exists(peer_path):
os.makedirs(peer_path)
sftp_get_r(ftp_client, f'{crypto_base}/{peer_path}', peer_path)
ftp_client.close()
def generate_order(order_id, order_information, fabric_name, channel_id, peer_group_ids, configtx_filename: str, crypto_base='/root/opt'):
node_name, group_name, domain = order_id.split('.', 2)
address = order_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
ssh.exec_command(f'if [ ! -d {crypto_base}/channel-artifacts ]; then mkdir -p {crypto_base}/channel-artifacts; fi')
ftp_client = ssh.open_sftp()
sftp_put_r(ftp_client, f"organizations/{group_name}.{domain}/peers", f"{crypto_base}/organizations/{group_name}.{domain}/peers")
for peer in peer_group_ids:
sftp_put_r(ftp_client, f"organizations/{peer}/msp/cacerts", f"{crypto_base}/organizations/{peer}/msp/cacerts")
ftp_client.put(f"organizations/{peer}/msp/config.yaml", f"{crypto_base}/organizations/{peer}/msp/config.yaml")
orderer_yaml_generator = OrderYamlGenerator()
filename = orderer_yaml_generator.generate(order_id, group_name, node_name, fabric_name, address["fabric_port"], crypto_base)
ftp_client.put(filename, f"{crypto_base}/{filename}")
ftp_client.put(configtx_filename, f'{crypto_base}/{configtx_filename}')
while True:
try:
ftp_client.stat(f'{crypto_base}/{configtx_filename}')
ftp_client.stat(f'{crypto_base}/{filename}')
print("File exists.")
break
except IOError:
print("File not exists.")
time.sleep(2)
ftp_client.close()
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name init_channel_artifacts {fabric_name} {channel_id} "{crypto_base}" {peer_group_ids} ')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{filename} up -d')
stdout.channel.recv_exit_status()
print(stderr.readlines())
time.sleep(4)
ssh.close()
def generate_configtx(groups: dict, nodes: dict, orderers: dict, net_name: str, crypto_base: str):
configtx = ConfigTXYamlGenerator(net_name, crypto_base)
return configtx.input_from("./template/configtx.yaml")\
.generate(groups, nodes, orderers)\
.output_to("./configtx.yaml")\
.get_filename()
def parse_json(network_topology_json):
order_group_id = ''
order_ca_port = ''
target_host = ''
peer_group_ids = []
for group_id, group_information in network_topology_json['groups'].items():
if group_id.split('.', 1)[0] == 'orderer':
order_group_id = group_id
order_ca_port = network_topology_json['nodes'][group_information['nodes']['ca']]['address']['fabric_port']
target_host = network_topology_json['nodes'][network_topology_json['groups'][group_id]['nodes']['ca']]['address']['host']
else:
peer_group_ids.append(group_id)
generate_ca(group_information['nodes']['ca'], network_topology_json['nodes'][group_information['nodes']['ca']], network_topology_json['blockchains']['fabric-1']['name'], target_host, '/root/opt')
for order_id in network_topology_json['groups'][order_group_id]['nodes']['orderer']:
generate_order_msp(order_id, network_topology_json['nodes'][order_id], order_ca_port, '/root/opt')
for org_id in peer_group_ids:
peer_ca_port = network_topology_json['nodes'][network_topology_json['groups'][org_id]['nodes']['ca']]['address']['fabric_port']
leader_peers_ids = network_topology_json['groups'][org_id]['nodes']['leader_peers']
anchor_peers_ids = network_topology_json['groups'][org_id]['nodes']['anchor_peers']
committing_peers_ids = network_topology_json['groups'][org_id]['nodes']['committing_peers']
endorsing_peers_ids = network_topology_json['groups'][org_id]['nodes']['endorsing_peers']
peer_ids = list(set(leader_peers_ids).union(set(anchor_peers_ids).union(set(committing_peers_ids)).union(set(endorsing_peers_ids))))
for peer_id in peer_ids:
generate_peer(peer_id, network_topology_json['nodes'][peer_id], order_group_id, network_topology_json['blockchains']['fabric-1']['name'], target_host, peer_ca_port, '/root/opt')
orderers = dict()
for node in network_topology_json["nodes"]:
if "orderer" in network_topology_json["nodes"][node]["type"]:
orderers[node] = network_topology_json["nodes"][node]
configtx_filename = generate_configtx(network_topology_json["groups"], network_topology_json["nodes"], orderers, network_topology_json["blockchains"]["fabric-1"]["name"], "/root/opt")
for order_id in network_topology_json['groups'][order_group_id]['nodes']['orderer']:
generate_order(order_id, network_topology_json['nodes'][order_id], network_topology_json['blockchains']['fabric-1']['name'], network_topology_json['blockchains']['fabric-1']['channels'][0], peer_group_ids, configtx_filename)
if __name__ == '__main__':
network_json = {
"groups": {
"orderer.test.com": {
"nodes": {
"ca": "ca.orderer.test.com",
"orderer": ["orderer0.orderer.test.com", "orderer1.orderer.test.com", "orderer2.orderer.test.com"]
},
"blockchains": "fabric-1"
},
"org0.test.com": {
"nodes": {
"ca": "ca.org0.test.com",
"leader_peers": ["peer0.org0.test.com"],
"anchor_peers": ["peer0.org0.test.com"],
"committing_peers": ["peer0.org0.test.com"],
"endorsing_peers": ["peer0.org0.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
},
"org1.test.com": {
"nodes": {
"ca": "ca.org1.test.com",
"leader_peers": ["peer0.org1.test.com"],
"anchor_peers": ["peer0.org1.test.com"],
"committing_peers": ["peer0.org1.test.com"],
"endorsing_peers": ["peer0.org1.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
},
"org2.test.com": {
"nodes": {
"ca": "ca.org2.test.com",
"leader_peers": ["peer0.org2.test.com"],
"anchor_peers": ["peer0.org2.test.com"],
"committing_peers": ["peer0.org2.test.com"],
"endorsing_peers": ["peer0.org2.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
}
},
"nodes": {
"ca.orderer.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"orderer0.orderer.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"orderer1.orderer.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"orderer2.orderer.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"ca.org0.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "8054", "sk": ""},
"type": ["ca"]
},
"peer0.org0.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
"ca.org1.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"peer0.org1.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
"ca.org2.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"peer0.org2.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
},
"blockchains": {
"fabric-1": {
"name": "FabricDraw",
"channels": ["channel-1"]
}
}
}
with open('id_rsa', 'r') as file:
sk = file.read()
for node_id in network_json['nodes'].keys():
network_json['nodes'][node_id]['address']['sk'] = sk
parse_json(network_json)
| 52.339181 | 232 | 0.632458 | import paramiko
import time
import io
import os
import stat
from yaml_generator import CAYamlGenerator, OrderYamlGenerator, PeerYamlGenerator, ConfigTXYamlGenerator
def sftp_get_r(sftp_client, remote_path, local_path):
try:
sftp_client.stat(remote_path)
except IOError:
return
if not os.path.exists(local_path):
os.mkdir(local_path)
for item in sftp_client.listdir(remote_path):
if stat.S_ISDIR(sftp_client.stat(f'{remote_path}/{item}').st_mode):
sftp_get_r(sftp_client, f'{remote_path}/{item}', os.path.join(local_path, item))
else:
sftp_client.get(f'{remote_path}/{item}', os.path.join(local_path, item))
def sftp_put_r(sftp_client, local_path, remote_path):
if not os.path.exists(local_path):
return
path = ""
for dir in remote_path.split("/"):
if dir == "":
continue
path += f"/{dir}"
try:
sftp_client.listdir(path)
except IOError:
sftp_client.mkdir(path)
try:
sftp_client.stat(remote_path)
except IOError:
sftp_client.mkdir(remote_path)
for item in os.listdir(local_path):
if os.path.isfile(os.path.join(local_path, item)):
sftp_client.put(os.path.join(local_path, item), f'{remote_path}/{item}')
else:
sftp_put_r(sftp_client, os.path.join(local_path, item), f'{remote_path}/{item}')
def generate_ca(ca_id, ca_information, fabric_name, target_host, crypto_base):
node_name, group_name, domain = ca_id.split('.', 2)
address = ca_information['address']
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base} ]; then mkdir -p {crypto_base}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
if group_name == 'orderer':
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name init_docker_swarm {target_host} {fabric_name} {crypto_base}')
stdout.channel.recv_exit_status()
ftp_client.get(f'{crypto_base}/token', 'token')
else:
try:
ftp_client.stat(f'{crypto_base}/token')
except IOError:
node_host = address['host']
ftp_client.put('token', f'{crypto_base}/token')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name join_docker_swarm {node_host} {target_host} {crypto_base}')
stdout.channel.recv_exit_status()
ca_yaml_generator = CAYamlGenerator()
file_name = ca_yaml_generator.generate(ca_id, group_name, fabric_name, address['fabric_port'], crypto_base)
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{file_name} up -d')
stdout.channel.recv_exit_status()
time.sleep(4)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
if not os.path.exists(tls_cert_path):
os.makedirs(tls_cert_path)
ftp_client.get(f'{crypto_base}/{tls_cert_path}/tls-cert.pem', f'{tls_cert_path}/tls-cert.pem')
ftp_client.close()
ssh.close()
def generate_order_msp(order_id, order_information, ca_port, crypto_base):
node_name, group_name, domain = order_id.split('.', 2)
address = order_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_cert_path} ]; then mkdir -p {crypto_base}/{tls_cert_path}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
ftp_client.put(f'{tls_cert_path}/tls-cert.pem', f'{crypto_base}/{tls_cert_path}/tls-cert.pem')
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name org_msp_generate {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name peer_msp_generate {node_name} {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
tls_ca_path = f'organizations/{group_name}.{domain}/tlsca'
if not os.path.exists(tls_ca_path):
os.makedirs(tls_ca_path)
ftp_client.get(f'{crypto_base}/{tls_ca_path}/tlsca.{group_name}.{domain}-cert.pem', f'{tls_ca_path}/tlsca.{group_name}.{domain}-cert.pem')
server_path = f'organizations/{group_name}.{domain}/peers/{order_id}/tls'
if not os.path.exists(server_path):
os.makedirs(server_path)
ftp_client.get(f'{crypto_base}/{server_path}/server.crt', f'{server_path}/server.crt')
ftp_client.close()
def generate_peer(peer_id, peer_information, order_group_id, fabric_name, target_host, ca_port, crypto_base):
node_name, group_name, domain = peer_id.split('.', 2)
address = peer_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
tls_cert_path = f'organizations/fabric-ca/{group_name}'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_cert_path} ]; then mkdir -p {crypto_base}/{tls_cert_path}; fi')
stdout.channel.recv_exit_status()
ftp_client = ssh.open_sftp()
ftp_client.put(f'{tls_cert_path}/tls-cert.pem', f'{crypto_base}/{tls_cert_path}/tls-cert.pem')
tls_ca_path = f'organizations/{order_group_id}/tlsca'
stdin, stdout, stderr = ssh.exec_command(f'if [ ! -d {crypto_base}/{tls_ca_path} ]; then mkdir -p {crypto_base}/{tls_ca_path}; fi')
stdout.channel.recv_exit_status()
ftp_client.put(f'{tls_ca_path}/tlsca.{order_group_id}-cert.pem', f'{crypto_base}/{tls_ca_path}/tlsca.{order_group_id}-cert.pem')
file_name = 'node_build.py'
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
try:
ftp_client.stat(f'{crypto_base}/token')
except IOError:
node_host = address['host']
ftp_client.put('token', f'{crypto_base}/token')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name join_docker_swarm {node_host} {target_host} {crypto_base}')
stdout.channel.recv_exit_status()
peer_yaml_generator = PeerYamlGenerator()
file_name = peer_yaml_generator.generate(peer_id, fabric_name, address['fabric_port'], crypto_base)
ftp_client.put(file_name, f'{crypto_base}/{file_name}')
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name org_msp_generate {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name peer_msp_generate {node_name} {group_name} {domain} {ca_port} {crypto_base}')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{file_name} up -d')
stdout.channel.recv_exit_status()
print(stderr.readlines())
time.sleep(3)
peer_path = f'organizations/{group_name}.{domain}'
if not os.path.exists(peer_path):
os.makedirs(peer_path)
sftp_get_r(ftp_client, f'{crypto_base}/{peer_path}', peer_path)
ftp_client.close()
def generate_order(order_id, order_information, fabric_name, channel_id, peer_group_ids, configtx_filename: str, crypto_base='/root/opt'):
node_name, group_name, domain = order_id.split('.', 2)
address = order_information['address']
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key_file = io.StringIO(address['sk'])
private_key = paramiko.RSAKey.from_private_key(key_file)
ssh.connect(hostname=address['host'], port=address['ssh_port'], username='root', pkey=private_key)
ssh.exec_command(f'if [ ! -d {crypto_base}/channel-artifacts ]; then mkdir -p {crypto_base}/channel-artifacts; fi')
ftp_client = ssh.open_sftp()
sftp_put_r(ftp_client, f"organizations/{group_name}.{domain}/peers", f"{crypto_base}/organizations/{group_name}.{domain}/peers")
for peer in peer_group_ids:
sftp_put_r(ftp_client, f"organizations/{peer}/msp/cacerts", f"{crypto_base}/organizations/{peer}/msp/cacerts")
ftp_client.put(f"organizations/{peer}/msp/config.yaml", f"{crypto_base}/organizations/{peer}/msp/config.yaml")
orderer_yaml_generator = OrderYamlGenerator()
filename = orderer_yaml_generator.generate(order_id, group_name, node_name, fabric_name, address["fabric_port"], crypto_base)
ftp_client.put(filename, f"{crypto_base}/{filename}")
ftp_client.put(configtx_filename, f'{crypto_base}/{configtx_filename}')
while True:
try:
ftp_client.stat(f'{crypto_base}/{configtx_filename}')
ftp_client.stat(f'{crypto_base}/{filename}')
print("File exists.")
break
except IOError:
print("File not exists.")
time.sleep(2)
ftp_client.close()
stdin, stdout, stderr = ssh.exec_command(f'python {crypto_base}/node_build.py --func_name init_channel_artifacts {fabric_name} {channel_id} "{crypto_base}" {peer_group_ids} ')
stdout.channel.recv_exit_status()
print(stderr.readlines())
stdin, stdout, stderr = ssh.exec_command(f'docker-compose -f {crypto_base}/{filename} up -d')
stdout.channel.recv_exit_status()
print(stderr.readlines())
time.sleep(4)
ssh.close()
def generate_configtx(groups: dict, nodes: dict, orderers: dict, net_name: str, crypto_base: str):
configtx = ConfigTXYamlGenerator(net_name, crypto_base)
return configtx.input_from("./template/configtx.yaml")\
.generate(groups, nodes, orderers)\
.output_to("./configtx.yaml")\
.get_filename()
def parse_json(network_topology_json):
order_group_id = ''
order_ca_port = ''
target_host = ''
peer_group_ids = []
for group_id, group_information in network_topology_json['groups'].items():
if group_id.split('.', 1)[0] == 'orderer':
order_group_id = group_id
order_ca_port = network_topology_json['nodes'][group_information['nodes']['ca']]['address']['fabric_port']
target_host = network_topology_json['nodes'][network_topology_json['groups'][group_id]['nodes']['ca']]['address']['host']
else:
peer_group_ids.append(group_id)
generate_ca(group_information['nodes']['ca'], network_topology_json['nodes'][group_information['nodes']['ca']], network_topology_json['blockchains']['fabric-1']['name'], target_host, '/root/opt')
for order_id in network_topology_json['groups'][order_group_id]['nodes']['orderer']:
generate_order_msp(order_id, network_topology_json['nodes'][order_id], order_ca_port, '/root/opt')
for org_id in peer_group_ids:
peer_ca_port = network_topology_json['nodes'][network_topology_json['groups'][org_id]['nodes']['ca']]['address']['fabric_port']
leader_peers_ids = network_topology_json['groups'][org_id]['nodes']['leader_peers']
anchor_peers_ids = network_topology_json['groups'][org_id]['nodes']['anchor_peers']
committing_peers_ids = network_topology_json['groups'][org_id]['nodes']['committing_peers']
endorsing_peers_ids = network_topology_json['groups'][org_id]['nodes']['endorsing_peers']
peer_ids = list(set(leader_peers_ids).union(set(anchor_peers_ids).union(set(committing_peers_ids)).union(set(endorsing_peers_ids))))
for peer_id in peer_ids:
generate_peer(peer_id, network_topology_json['nodes'][peer_id], order_group_id, network_topology_json['blockchains']['fabric-1']['name'], target_host, peer_ca_port, '/root/opt')
orderers = dict()
for node in network_topology_json["nodes"]:
if "orderer" in network_topology_json["nodes"][node]["type"]:
orderers[node] = network_topology_json["nodes"][node]
configtx_filename = generate_configtx(network_topology_json["groups"], network_topology_json["nodes"], orderers, network_topology_json["blockchains"]["fabric-1"]["name"], "/root/opt")
for order_id in network_topology_json['groups'][order_group_id]['nodes']['orderer']:
generate_order(order_id, network_topology_json['nodes'][order_id], network_topology_json['blockchains']['fabric-1']['name'], network_topology_json['blockchains']['fabric-1']['channels'][0], peer_group_ids, configtx_filename)
if __name__ == '__main__':
network_json = {
"groups": {
"orderer.test.com": {
"nodes": {
"ca": "ca.orderer.test.com",
"orderer": ["orderer0.orderer.test.com", "orderer1.orderer.test.com", "orderer2.orderer.test.com"]
},
"blockchains": "fabric-1"
},
"org0.test.com": {
"nodes": {
"ca": "ca.org0.test.com",
"leader_peers": ["peer0.org0.test.com"],
"anchor_peers": ["peer0.org0.test.com"],
"committing_peers": ["peer0.org0.test.com"],
"endorsing_peers": ["peer0.org0.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
},
"org1.test.com": {
"nodes": {
"ca": "ca.org1.test.com",
"leader_peers": ["peer0.org1.test.com"],
"anchor_peers": ["peer0.org1.test.com"],
"committing_peers": ["peer0.org1.test.com"],
"endorsing_peers": ["peer0.org1.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
},
"org2.test.com": {
"nodes": {
"ca": "ca.org2.test.com",
"leader_peers": ["peer0.org2.test.com"],
"anchor_peers": ["peer0.org2.test.com"],
"committing_peers": ["peer0.org2.test.com"],
"endorsing_peers": ["peer0.org2.test.com"]
},
"blockchains": "fabric-1",
"channel": ["channel-1"]
}
},
"nodes": {
"ca.orderer.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"orderer0.orderer.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"orderer1.orderer.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"orderer2.orderer.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7050", "sk": ""},
"type": ["orderer"]
},
"ca.org0.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "8054", "sk": ""},
"type": ["ca"]
},
"peer0.org0.test.com": {
"address": {"host": "10.134.68.98", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
"ca.org1.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"peer0.org1.test.com": {
"address": {"host": "10.134.50.142", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
"ca.org2.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7054", "sk": ""},
"type": ["ca"]
},
"peer0.org2.test.com": {
"address": {"host": "10.134.50.70", "ssh_port": "22", "fabric_port": "7051", "sk": ""},
"bootstrap": ["127.0.0.1:7051"],
"type": ["leader_peer", "anchor_peer", "committing_peer", "endorsing_peers"]
},
},
"blockchains": {
"fabric-1": {
"name": "FabricDraw",
"channels": ["channel-1"]
}
}
}
with open('id_rsa', 'r') as file:
sk = file.read()
for node_id in network_json['nodes'].keys():
network_json['nodes'][node_id]['address']['sk'] = sk
parse_json(network_json)
| true | true |
f7269dbe969bf3a3bdd44ac8ab46929aa9601789 | 2,670 | py | Python | import_metadata.py | arru/plex-utilities | b5ea04c090f1fdc008ae39239c1b03b435036acb | [
"BSD-3-Clause"
] | 1 | 2020-12-26T14:45:53.000Z | 2020-12-26T14:45:53.000Z | import_metadata.py | arru/plex-utilities | b5ea04c090f1fdc008ae39239c1b03b435036acb | [
"BSD-3-Clause"
] | null | null | null | import_metadata.py | arru/plex-utilities | b5ea04c090f1fdc008ae39239c1b03b435036acb | [
"BSD-3-Clause"
] | null | null | null | #!/usr/local/bin/python3
# https://python-plexapi.readthedocs.io/en/latest/modules/media.html
# https://github.com/liamks/libpytunes/blob/master/README.md
from os import path
import ImportUtils
CONFIGURATION = ImportUtils.get_configuration()
class FakePlexTrack:
originalTitle = ""
userRating = 0.0
year = None
addedAt = ImportUtils.CURRENT_DATE
index = 0
lastViewedAt = None
title = ""
titleSort = None
viewCount = 0
def __init__(self, plex_track):
self.originalTitle = plex_track.originalTitle
self.userRating = plex_track.userRating
self.year = plex_track.year
self.addedAt = plex_track.addedAt
self.index = plex_track.index
self.lastViewedAt = plex_track.lastViewedAt
self.title = plex_track.title
self.titleSort = plex_track.titleSort
self.viewCount = plex_track.viewCount
plex = ImportUtils.PlexWrapper(CONFIGURATION)
PLEX_TRACKS = plex.server.library.section('Music').searchTracks()
itunes = ImportUtils.ItunesWrapper(CONFIGURATION)
itunes_tracks = itunes.get_tracks_dict()
del itunes
libraryMisses = 0
for plex_track_real in PLEX_TRACKS:
plex_path = plex_track_real.media[0].parts[0].file
if not plex_path in itunes_tracks:
# print("'%s' not found in itunes_tracks" % plex_path)
libraryMisses += 1
continue
itunesTrack = itunes_tracks[plex_path]
assert path.isfile(plex_path)
# plex_track = FakePlexTrack(plex_track_real)
plex_track = plex_track_real
ImportUtils.validatePlexTrack(plex_track)
if itunesTrack.rating:
plex_rating = float(itunesTrack.rating)/10.0
# (float) - Rating of this track (0.0 - 10.0) equaling (0 stars - 5 stars)
#.value
plex_track.edit(**{'userRating.value': plex_rating})
# (int) - Year this track was released.
if itunesTrack.year:
plex_track.edit(**{'year.value': itunesTrack.year})
# addedAt (datetime) - Datetime this item was added to the library.
# index (sting) - Index Number (often the track number).
if itunesTrack.track_number:
plex_track.edit(**{'index.value': itunesTrack.track_number})
# lastViewedAt (datetime) - Datetime item was last accessed.
# title (str) - Artist, Album or Track title. (Jason Mraz, We Sing, Lucky, etc.)
# originalTitle (str) - Track artist.
# titleSort (str) - Title to use when sorting (defaults to title).
# viewCount (int) - Count of times this item was accessed.
ImportUtils.validatePlexTrack(plex_track)
if libraryMisses > 0:
print ("[WARNING] %d Plex tracks not found in iTunes metadata" % libraryMisses)
| 30.689655 | 84 | 0.696629 |
from os import path
import ImportUtils
CONFIGURATION = ImportUtils.get_configuration()
class FakePlexTrack:
originalTitle = ""
userRating = 0.0
year = None
addedAt = ImportUtils.CURRENT_DATE
index = 0
lastViewedAt = None
title = ""
titleSort = None
viewCount = 0
def __init__(self, plex_track):
self.originalTitle = plex_track.originalTitle
self.userRating = plex_track.userRating
self.year = plex_track.year
self.addedAt = plex_track.addedAt
self.index = plex_track.index
self.lastViewedAt = plex_track.lastViewedAt
self.title = plex_track.title
self.titleSort = plex_track.titleSort
self.viewCount = plex_track.viewCount
plex = ImportUtils.PlexWrapper(CONFIGURATION)
PLEX_TRACKS = plex.server.library.section('Music').searchTracks()
itunes = ImportUtils.ItunesWrapper(CONFIGURATION)
itunes_tracks = itunes.get_tracks_dict()
del itunes
libraryMisses = 0
for plex_track_real in PLEX_TRACKS:
plex_path = plex_track_real.media[0].parts[0].file
if not plex_path in itunes_tracks:
libraryMisses += 1
continue
itunesTrack = itunes_tracks[plex_path]
assert path.isfile(plex_path)
plex_track = plex_track_real
ImportUtils.validatePlexTrack(plex_track)
if itunesTrack.rating:
plex_rating = float(itunesTrack.rating)/10.0
plex_track.edit(**{'userRating.value': plex_rating})
if itunesTrack.year:
plex_track.edit(**{'year.value': itunesTrack.year})
if itunesTrack.track_number:
plex_track.edit(**{'index.value': itunesTrack.track_number})
ImportUtils.validatePlexTrack(plex_track)
if libraryMisses > 0:
print ("[WARNING] %d Plex tracks not found in iTunes metadata" % libraryMisses)
| true | true |
f7269e3d1d7c351c9df854a7024d0200b141ab6d | 5,084 | py | Python | sdk/python/pulumi_azure_nextgen/authorization/latest/get_management_lock_at_resource_level.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/authorization/latest/get_management_lock_at_resource_level.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_nextgen/authorization/latest/get_management_lock_at_resource_level.py | test-wiz-sec/pulumi-azure-nextgen | 20a695af0d020b34b0f1c336e1b69702755174cc | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetManagementLockAtResourceLevelResult',
'AwaitableGetManagementLockAtResourceLevelResult',
'get_management_lock_at_resource_level',
]
@pulumi.output_type
class GetManagementLockAtResourceLevelResult:
"""
The lock information.
"""
def __init__(__self__, level=None, name=None, notes=None, owners=None, type=None):
if level and not isinstance(level, str):
raise TypeError("Expected argument 'level' to be a str")
pulumi.set(__self__, "level", level)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if notes and not isinstance(notes, str):
raise TypeError("Expected argument 'notes' to be a str")
pulumi.set(__self__, "notes", notes)
if owners and not isinstance(owners, list):
raise TypeError("Expected argument 'owners' to be a list")
pulumi.set(__self__, "owners", owners)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def level(self) -> str:
"""
The level of the lock. Possible values are: NotSpecified, CanNotDelete, ReadOnly. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it.
"""
return pulumi.get(self, "level")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the lock.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def notes(self) -> Optional[str]:
"""
Notes about the lock. Maximum of 512 characters.
"""
return pulumi.get(self, "notes")
@property
@pulumi.getter
def owners(self) -> Optional[Sequence['outputs.ManagementLockOwnerResponse']]:
"""
The owners of the lock.
"""
return pulumi.get(self, "owners")
@property
@pulumi.getter
def type(self) -> str:
"""
The resource type of the lock - Microsoft.Authorization/locks.
"""
return pulumi.get(self, "type")
class AwaitableGetManagementLockAtResourceLevelResult(GetManagementLockAtResourceLevelResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetManagementLockAtResourceLevelResult(
level=self.level,
name=self.name,
notes=self.notes,
owners=self.owners,
type=self.type)
def get_management_lock_at_resource_level(lock_name: Optional[str] = None,
parent_resource_path: Optional[str] = None,
resource_group_name: Optional[str] = None,
resource_name: Optional[str] = None,
resource_provider_namespace: Optional[str] = None,
resource_type: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetManagementLockAtResourceLevelResult:
"""
Use this data source to access information about an existing resource.
:param str lock_name: The name of lock.
:param str parent_resource_path: An extra path parameter needed in some services, like SQL Databases.
:param str resource_group_name: The name of the resource group.
:param str resource_name: The name of the resource.
:param str resource_provider_namespace: The namespace of the resource provider.
:param str resource_type: The type of the resource.
"""
__args__ = dict()
__args__['lockName'] = lock_name
__args__['parentResourcePath'] = parent_resource_path
__args__['resourceGroupName'] = resource_group_name
__args__['resourceName'] = resource_name
__args__['resourceProviderNamespace'] = resource_provider_namespace
__args__['resourceType'] = resource_type
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:authorization/latest:getManagementLockAtResourceLevel', __args__, opts=opts, typ=GetManagementLockAtResourceLevelResult).value
return AwaitableGetManagementLockAtResourceLevelResult(
level=__ret__.level,
name=__ret__.name,
notes=__ret__.notes,
owners=__ret__.owners,
type=__ret__.type)
| 39.107692 | 283 | 0.648308 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetManagementLockAtResourceLevelResult',
'AwaitableGetManagementLockAtResourceLevelResult',
'get_management_lock_at_resource_level',
]
@pulumi.output_type
class GetManagementLockAtResourceLevelResult:
def __init__(__self__, level=None, name=None, notes=None, owners=None, type=None):
if level and not isinstance(level, str):
raise TypeError("Expected argument 'level' to be a str")
pulumi.set(__self__, "level", level)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if notes and not isinstance(notes, str):
raise TypeError("Expected argument 'notes' to be a str")
pulumi.set(__self__, "notes", notes)
if owners and not isinstance(owners, list):
raise TypeError("Expected argument 'owners' to be a list")
pulumi.set(__self__, "owners", owners)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def level(self) -> str:
return pulumi.get(self, "level")
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def notes(self) -> Optional[str]:
return pulumi.get(self, "notes")
@property
@pulumi.getter
def owners(self) -> Optional[Sequence['outputs.ManagementLockOwnerResponse']]:
return pulumi.get(self, "owners")
@property
@pulumi.getter
def type(self) -> str:
return pulumi.get(self, "type")
class AwaitableGetManagementLockAtResourceLevelResult(GetManagementLockAtResourceLevelResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetManagementLockAtResourceLevelResult(
level=self.level,
name=self.name,
notes=self.notes,
owners=self.owners,
type=self.type)
def get_management_lock_at_resource_level(lock_name: Optional[str] = None,
parent_resource_path: Optional[str] = None,
resource_group_name: Optional[str] = None,
resource_name: Optional[str] = None,
resource_provider_namespace: Optional[str] = None,
resource_type: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetManagementLockAtResourceLevelResult:
__args__ = dict()
__args__['lockName'] = lock_name
__args__['parentResourcePath'] = parent_resource_path
__args__['resourceGroupName'] = resource_group_name
__args__['resourceName'] = resource_name
__args__['resourceProviderNamespace'] = resource_provider_namespace
__args__['resourceType'] = resource_type
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:authorization/latest:getManagementLockAtResourceLevel', __args__, opts=opts, typ=GetManagementLockAtResourceLevelResult).value
return AwaitableGetManagementLockAtResourceLevelResult(
level=__ret__.level,
name=__ret__.name,
notes=__ret__.notes,
owners=__ret__.owners,
type=__ret__.type)
| true | true |
f7269ea2093e6b0c5b7f64bb94961bc815827e61 | 6,713 | py | Python | misc/webdriver-w3c-tests/client/driver.py | zhuyongyong/crosswalk-test-suite | 24f3f8cfa663a365b0a22685d5bd096a637f72db | [
"BSD-3-Clause"
] | null | null | null | misc/webdriver-w3c-tests/client/driver.py | zhuyongyong/crosswalk-test-suite | 24f3f8cfa663a365b0a22685d5bd096a637f72db | [
"BSD-3-Clause"
] | null | null | null | misc/webdriver-w3c-tests/client/driver.py | zhuyongyong/crosswalk-test-suite | 24f3f8cfa663a365b0a22685d5bd096a637f72db | [
"BSD-3-Clause"
] | null | null | null | """Entry point for WebDriver."""
import alert
import command
import searchcontext
import webelement
import base64
class WebDriver(searchcontext.SearchContext):
"""Controls a web browser."""
def __init__(self, host, required, desired, mode='strict'):
args = {'desiredCapabilities': desired}
if required:
args['requiredCapabilities'] = required
self._executor = command.CommandExecutor(host, mode)
resp = self._executor.execute(
'POST', '/session', None, 'newSession', args)
self.capabilities = resp['value']
self._session_id = resp['sessionId']
self.mode = mode
def execute(self, method, path, name, parameters=None):
"""Execute a command against the current WebDriver session."""
data = self._executor.execute(
method,
'/session/' + self._session_id + path,
self._session_id,
name,
parameters,
self._object_hook)
if data:
return data['value']
def get(self, url):
"""Navigate to url."""
self.execute('POST', '/url', 'get', {'url': url})
def get_current_url(self):
"""Get the current value of the location bar."""
return self.execute('GET', '/url', 'getCurrentUrl')
def go_back(self):
"""Hit the browser back button."""
self.execute('POST', '/back', 'goBack')
def go_forward(self):
"""Hit the browser forward button."""
self.execute('POST', '/forward', 'goForward')
def refresh(self):
"""Refresh the current page in the browser."""
self.execute('POST', '/refresh', 'refresh')
def quit(self):
"""Shutdown the current WebDriver session."""
self.execute('DELETE', '', 'quit')
def get_window_handle(self):
"""Get the handle for the browser window/tab currently accepting
commands.
"""
return self.execute('GET', '/window_handle', 'getWindowHandle')
def get_window_handles(self):
"""Get handles for all open windows/tabs."""
return self.execute('GET', '/window_handles', 'getWindowHandles')
def close(self):
"""Close the current tab or window.
If this is the last tab or window, then this is the same as
calling quit.
"""
self.execute('DELETE', '/window', 'close')
def maximize_window(self):
"""Maximize the current window."""
return self._window_command('POST', '/maximize', 'maximize')
def get_window_size(self):
"""Get the dimensions of the current window."""
result = self._window_command('GET', '/size', 'getWindowSize')
return {'height': result[height], 'width': result[width]}
def set_window_size(self, height, width):
"""Set the size of the current window."""
self._window_command(
'POST',
'/size',
'setWindowSize',
{'height': height, 'width': width})
def fullscreen_window(self):
"""Make the current window fullscreen."""
pass # implement when end point is defined
def switch_to_window(self, name):
"""Switch to the window with the given handle or name."""
self.execute('POST', '/window', 'switchToWindow', {'name': name})
def switch_to_frame(self, id):
"""Switch to a frame.
id can be either a WebElement or an integer.
"""
self.execute('POST', '/frame', 'switchToFrame', {'id': id})
def switch_to_parent_frame(self):
"""Move to the browsing context containing the currently selected frame.
If in the top-level browsing context, this is a no-op.
"""
self.execute('POST', '/frame/parent', 'switchToParentFrame')
def switch_to_alert(self):
"""Return an Alert object to interact with a modal dialog."""
alert_ = alert.Alert(self)
alert_.get_text()
return alert_
def execute_script(self, script, args=[]):
"""Execute a Javascript script in the current browsing context."""
return self.execute(
'POST',
'/execute',
'executeScript',
{'script': script, 'args': args})
def execute_script_async(self, script, args=[]):
"""Execute a Javascript script in the current browsing context."""
return self.execute(
'POST',
'/execute_async',
'executeScriptAsync',
{'script': script, 'args': args})
def take_screenshot(self, element=None):
"""Take a screenshot.
If element is not provided, the screenshot should be of the
current page, otherwise the screenshot should be of the given element.
"""
if self.mode == 'strict':
pass # implement when endpoint is defined
elif self.mode == 'compatibility':
if element:
pass # element screenshots are unsupported in compatibility
else:
return base64.standard_b64decode(
self.execute('GET', '/screenshot', 'takeScreenshot'))
def add_cookie(self, cookie):
"""Add a cookie to the browser."""
self.execute('POST', '/cookie', 'addCookie', {'cookie': cookie})
def get_cookie(self, name=None):
"""Get the cookies accessible from the current page."""
if self.mode == 'compatibility':
cookies = self.execute('GET', '/cookie', 'getCookie')
if name:
cookies_ = []
for cookie in cookies:
if cookie['name'] == name:
cookies_.append(cookie)
return cookies_
return cookies
elif self.mode == 'strict':
pass # implement when wire protocol for this has been defined
def set_implicit_timeout(self, ms):
self._set_timeout('implicit', ms)
def set_page_load_timeout(self, ms):
self._set_timeout('page load', ms)
def set_script_timeout(self, ms):
self._set_timeout('script', ms)
def _set_timeout(self, type, ms):
params = {'type': type, 'ms': ms}
self.execute('POST', '/timeouts', 'timeouts', params)
def _window_command(self, method, path, name, parameters=None):
if self.mode == 'compatibility':
return self.execute(
method, '/window/current' + path, name, parameters)
elif self.mode == 'strict':
pass # implement this when end-points are defined in doc
def _object_hook(self, obj):
if 'ELEMENT' in obj:
return webelement.WebElement(self, obj['ELEMENT'])
return obj
| 33.565 | 80 | 0.58558 |
import alert
import command
import searchcontext
import webelement
import base64
class WebDriver(searchcontext.SearchContext):
def __init__(self, host, required, desired, mode='strict'):
args = {'desiredCapabilities': desired}
if required:
args['requiredCapabilities'] = required
self._executor = command.CommandExecutor(host, mode)
resp = self._executor.execute(
'POST', '/session', None, 'newSession', args)
self.capabilities = resp['value']
self._session_id = resp['sessionId']
self.mode = mode
def execute(self, method, path, name, parameters=None):
data = self._executor.execute(
method,
'/session/' + self._session_id + path,
self._session_id,
name,
parameters,
self._object_hook)
if data:
return data['value']
def get(self, url):
self.execute('POST', '/url', 'get', {'url': url})
def get_current_url(self):
return self.execute('GET', '/url', 'getCurrentUrl')
def go_back(self):
self.execute('POST', '/back', 'goBack')
def go_forward(self):
self.execute('POST', '/forward', 'goForward')
def refresh(self):
self.execute('POST', '/refresh', 'refresh')
def quit(self):
self.execute('DELETE', '', 'quit')
def get_window_handle(self):
return self.execute('GET', '/window_handle', 'getWindowHandle')
def get_window_handles(self):
return self.execute('GET', '/window_handles', 'getWindowHandles')
def close(self):
self.execute('DELETE', '/window', 'close')
def maximize_window(self):
return self._window_command('POST', '/maximize', 'maximize')
def get_window_size(self):
result = self._window_command('GET', '/size', 'getWindowSize')
return {'height': result[height], 'width': result[width]}
def set_window_size(self, height, width):
self._window_command(
'POST',
'/size',
'setWindowSize',
{'height': height, 'width': width})
def fullscreen_window(self):
pass
def switch_to_window(self, name):
self.execute('POST', '/window', 'switchToWindow', {'name': name})
def switch_to_frame(self, id):
self.execute('POST', '/frame', 'switchToFrame', {'id': id})
def switch_to_parent_frame(self):
self.execute('POST', '/frame/parent', 'switchToParentFrame')
def switch_to_alert(self):
alert_ = alert.Alert(self)
alert_.get_text()
return alert_
def execute_script(self, script, args=[]):
return self.execute(
'POST',
'/execute',
'executeScript',
{'script': script, 'args': args})
def execute_script_async(self, script, args=[]):
return self.execute(
'POST',
'/execute_async',
'executeScriptAsync',
{'script': script, 'args': args})
def take_screenshot(self, element=None):
if self.mode == 'strict':
pass
elif self.mode == 'compatibility':
if element:
pass
else:
return base64.standard_b64decode(
self.execute('GET', '/screenshot', 'takeScreenshot'))
def add_cookie(self, cookie):
self.execute('POST', '/cookie', 'addCookie', {'cookie': cookie})
def get_cookie(self, name=None):
if self.mode == 'compatibility':
cookies = self.execute('GET', '/cookie', 'getCookie')
if name:
cookies_ = []
for cookie in cookies:
if cookie['name'] == name:
cookies_.append(cookie)
return cookies_
return cookies
elif self.mode == 'strict':
pass
def set_implicit_timeout(self, ms):
self._set_timeout('implicit', ms)
def set_page_load_timeout(self, ms):
self._set_timeout('page load', ms)
def set_script_timeout(self, ms):
self._set_timeout('script', ms)
def _set_timeout(self, type, ms):
params = {'type': type, 'ms': ms}
self.execute('POST', '/timeouts', 'timeouts', params)
def _window_command(self, method, path, name, parameters=None):
if self.mode == 'compatibility':
return self.execute(
method, '/window/current' + path, name, parameters)
elif self.mode == 'strict':
pass
def _object_hook(self, obj):
if 'ELEMENT' in obj:
return webelement.WebElement(self, obj['ELEMENT'])
return obj
| true | true |
f7269ecfb8cc07dc1f1a6af43bc49083c18df9d2 | 938 | py | Python | mobilecoind/clients/python/lib/setup.py | mccobr/mobilecoin | cd7753a0aed838097b456d230151fb34e8cff034 | [
"Apache-2.0"
] | 140 | 2020-04-15T17:51:12.000Z | 2020-10-02T19:51:57.000Z | mobilecoind/clients/python/lib/setup.py | mccobr/mobilecoin | cd7753a0aed838097b456d230151fb34e8cff034 | [
"Apache-2.0"
] | 292 | 2020-10-22T00:34:35.000Z | 2022-03-29T09:29:14.000Z | mobilecoind/clients/python/lib/setup.py | mccobr/mobilecoin | cd7753a0aed838097b456d230151fb34e8cff034 | [
"Apache-2.0"
] | 32 | 2020-04-15T18:17:07.000Z | 2020-10-19T23:25:42.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mobilecoin",
version="0.3.3",
author="MobileCoin",
author_email="support@mobilecoin.com",
description="Python bindings for the MobileCoin daemon API.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/mobilecoinfoundation/mobilecoin/tree/master/mobilecoind/clients/python/lib",
package_data={'mobilecoin': ['py.typed']},
packages=['mobilecoin'],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
test_suite='nose.collector',
tests_require=['nose'],
install_requires=['grpcio', 'grpcio-tools'],
)
| 31.266667 | 104 | 0.670576 |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mobilecoin",
version="0.3.3",
author="MobileCoin",
author_email="support@mobilecoin.com",
description="Python bindings for the MobileCoin daemon API.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/mobilecoinfoundation/mobilecoin/tree/master/mobilecoind/clients/python/lib",
package_data={'mobilecoin': ['py.typed']},
packages=['mobilecoin'],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
test_suite='nose.collector',
tests_require=['nose'],
install_requires=['grpcio', 'grpcio-tools'],
)
| true | true |
f7269f404c1a317ded575623966d09871ec4b217 | 9,554 | py | Python | samsungtvws/remote.py | chemelli74/samsung-tv-ws-api | bffbdd1796c95d5147117a5fc6583a803c310cd4 | [
"MIT"
] | null | null | null | samsungtvws/remote.py | chemelli74/samsung-tv-ws-api | bffbdd1796c95d5147117a5fc6583a803c310cd4 | [
"MIT"
] | null | null | null | samsungtvws/remote.py | chemelli74/samsung-tv-ws-api | bffbdd1796c95d5147117a5fc6583a803c310cd4 | [
"MIT"
] | null | null | null | """
SamsungTVWS - Samsung Smart TV WS API wrapper
Copyright (C) 2019 Xchwarze
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1335 USA
"""
import base64
import json
import logging
import time
import ssl
import websocket
import requests
from . import exceptions
from . import shortcuts
_LOGGING = logging.getLogger(__name__)
class SamsungTVWS:
_URL_FORMAT = 'ws://{host}:{port}/api/v2/channels/samsung.remote.control?name={name}'
_SSL_URL_FORMAT = 'wss://{host}:{port}/api/v2/channels/samsung.remote.control?name={name}&token={token}'
_REST_URL_FORMAT = '{protocol}://{host}:{port}/api/v2/{route}'
def __init__(self, host, token=None, token_file=None, port=8001, timeout=None, key_press_delay=1,
name='SamsungTvRemote'):
self.host = host
self.token = token
self.token_file = token_file
self.port = port
self.timeout = None if timeout == 0 else timeout
self.key_press_delay = key_press_delay
self.name = name
self.connection = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def _serialize_string(self, string):
if isinstance(string, str):
string = str.encode(string)
return base64.b64encode(string).decode('utf-8')
def _is_ssl_connection(self):
return self.port == 8002
def _format_websocket_url(self):
params = {
'host': self.host,
'port': self.port,
'name': self._serialize_string(self.name),
'token': self._get_token(),
}
if self._is_ssl_connection():
return self._SSL_URL_FORMAT.format(**params)
else:
return self._URL_FORMAT.format(**params)
def _format_rest_url(self, route=''):
params = {
'protocol': 'https' if self._is_ssl_connection() else 'http',
'host': self.host,
'port': self.port,
'route': route,
}
return self._REST_URL_FORMAT.format(**params)
def _get_token(self):
if self.token_file is not None:
try:
with open(self.token_file, 'r') as token_file:
return token_file.readline()
except:
return ''
else:
return self.token
def _set_token(self, token):
_LOGGING.info('New token %s', token)
if self.token_file is not None:
_LOGGING.debug('Save token to file: %s', token)
with open(self.token_file, 'w') as token_file:
token_file.write(token)
else:
self.token = token
def _ws_send(self, command, key_press_delay=None):
if self.connection is None:
self.open()
payload = json.dumps(command)
self.connection.send(payload)
delay = self.key_press_delay if key_press_delay is None else key_press_delay
time.sleep(delay)
def _rest_request(self, target, method='GET'):
url = self._format_rest_url(target)
try:
if method == 'POST':
return requests.post(url, timeout=self.timeout, verify=False)
elif method == 'PUT':
return requests.put(url, timeout=self.timeout, verify=False)
elif method == 'DELETE':
return requests.delete(url, timeout=self.timeout, verify=False)
else:
return requests.get(url, timeout=self.timeout, verify=False)
except requests.ConnectionError:
raise exceptions.HttpApiError('TV unreachable or feature not supported on this model.')
def _process_api_response(self, response):
try:
return json.loads(response)
except json.JSONDecodeError:
_LOGGING.debug('Failed to parse response from TV. response text: %s', response)
raise exceptions.ResponseError('Failed to parse response from TV. Maybe feature not supported on this model')
def open(self):
url = self._format_websocket_url()
sslopt = {'cert_reqs': ssl.CERT_NONE} if self._is_ssl_connection() else {}
_LOGGING.debug('WS url %s', url)
# Only for debug use!
# websocket.enableTrace(True)
self.connection = websocket.create_connection(
url,
self.timeout,
sslopt=sslopt,
# Use 'connection' for fix websocket-client 0.57 bug
# header={'Connection': 'Upgrade'}
connection='Connection: Upgrade'
)
response = self._process_api_response(self.connection.recv())
if response.get('data') and response.get('data').get('token'):
token = response.get('data').get('token')
_LOGGING.debug('Got token %s', token)
self._set_token(token)
if response['event'] != 'ms.channel.connect':
self.close()
raise exceptions.ConnectionFailure(response)
def close(self):
if self.connection:
self.connection.close()
self.connection = None
_LOGGING.debug('Connection closed.')
def send_key(self, key, times=1, key_press_delay=None, cmd='Click'):
for _ in range(times):
_LOGGING.debug('Sending key %s', key)
self._ws_send(
{
'method': 'ms.remote.control',
'params': {
'Cmd': cmd,
'DataOfCmd': key,
'Option': 'false',
'TypeOfRemote': 'SendRemoteKey'
}
},
key_press_delay
)
def hold_key(self, key, seconds):
self.send_key(key, cmd='Press')
time.sleep(seconds)
self.send_key(key, cmd='Release')
def move_cursor(self, x, y, duration=0):
self._ws_send(
{
'method': 'ms.remote.control',
'params': {
'Cmd': 'Move',
'Position': {
'x': x,
'y': y,
'Time': str(duration)
},
'TypeOfRemote': 'ProcessMouseDevice'
}
},
key_press_delay=0
)
def run_app(self, app_id, app_type='DEEP_LINK', meta_tag=''):
_LOGGING.debug('Sending run app app_id: %s app_type: %s meta_tag: %s', app_id, app_type, meta_tag)
self._ws_send({
'method': 'ms.channel.emit',
'params': {
'event': 'ed.apps.launch',
'to': 'host',
'data': {
# action_type: NATIVE_LAUNCH / DEEP_LINK
# app_type == 2 ? 'DEEP_LINK' : 'NATIVE_LAUNCH',
'action_type': app_type,
'appId': app_id,
'metaTag': meta_tag
}
}
})
def open_browser(self, url):
_LOGGING.debug('Opening url in browser %s', url)
self.run_app(
'org.tizen.browser',
'NATIVE_LAUNCH',
url
)
def app_list(self):
_LOGGING.debug('Get app list')
self._ws_send({
'method': 'ms.channel.emit',
'params': {
'event': 'ed.installedApp.get',
'to': 'host'
}
})
response = self._process_api_response(self.connection.recv())
if response.get('data') and response.get('data').get('data'):
return response.get('data').get('data')
else:
return response
def rest_device_info(self):
_LOGGING.debug('Get device info via rest api')
response = self._rest_request('')
return self._process_api_response(response.text)
def rest_app_status(self, app_id):
_LOGGING.debug('Get app %s status via rest api', app_id)
response = self._rest_request('applications/' + app_id)
return self._process_api_response(response.text)
def rest_app_run(self, app_id):
_LOGGING.debug('Run app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'POST')
return self._process_api_response(response.text)
def rest_app_close(self, app_id):
_LOGGING.debug('Close app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'DELETE')
return self._process_api_response(response.text)
def rest_app_install(self, app_id):
_LOGGING.debug('Install app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'PUT')
return self._process_api_response(response.text)
def shortcuts(self):
return shortcuts.SamsungTVShortcuts(self)
| 34.366906 | 121 | 0.57578 | import base64
import json
import logging
import time
import ssl
import websocket
import requests
from . import exceptions
from . import shortcuts
_LOGGING = logging.getLogger(__name__)
class SamsungTVWS:
_URL_FORMAT = 'ws://{host}:{port}/api/v2/channels/samsung.remote.control?name={name}'
_SSL_URL_FORMAT = 'wss://{host}:{port}/api/v2/channels/samsung.remote.control?name={name}&token={token}'
_REST_URL_FORMAT = '{protocol}://{host}:{port}/api/v2/{route}'
def __init__(self, host, token=None, token_file=None, port=8001, timeout=None, key_press_delay=1,
name='SamsungTvRemote'):
self.host = host
self.token = token
self.token_file = token_file
self.port = port
self.timeout = None if timeout == 0 else timeout
self.key_press_delay = key_press_delay
self.name = name
self.connection = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def _serialize_string(self, string):
if isinstance(string, str):
string = str.encode(string)
return base64.b64encode(string).decode('utf-8')
def _is_ssl_connection(self):
return self.port == 8002
def _format_websocket_url(self):
params = {
'host': self.host,
'port': self.port,
'name': self._serialize_string(self.name),
'token': self._get_token(),
}
if self._is_ssl_connection():
return self._SSL_URL_FORMAT.format(**params)
else:
return self._URL_FORMAT.format(**params)
def _format_rest_url(self, route=''):
params = {
'protocol': 'https' if self._is_ssl_connection() else 'http',
'host': self.host,
'port': self.port,
'route': route,
}
return self._REST_URL_FORMAT.format(**params)
def _get_token(self):
if self.token_file is not None:
try:
with open(self.token_file, 'r') as token_file:
return token_file.readline()
except:
return ''
else:
return self.token
def _set_token(self, token):
_LOGGING.info('New token %s', token)
if self.token_file is not None:
_LOGGING.debug('Save token to file: %s', token)
with open(self.token_file, 'w') as token_file:
token_file.write(token)
else:
self.token = token
def _ws_send(self, command, key_press_delay=None):
if self.connection is None:
self.open()
payload = json.dumps(command)
self.connection.send(payload)
delay = self.key_press_delay if key_press_delay is None else key_press_delay
time.sleep(delay)
def _rest_request(self, target, method='GET'):
url = self._format_rest_url(target)
try:
if method == 'POST':
return requests.post(url, timeout=self.timeout, verify=False)
elif method == 'PUT':
return requests.put(url, timeout=self.timeout, verify=False)
elif method == 'DELETE':
return requests.delete(url, timeout=self.timeout, verify=False)
else:
return requests.get(url, timeout=self.timeout, verify=False)
except requests.ConnectionError:
raise exceptions.HttpApiError('TV unreachable or feature not supported on this model.')
def _process_api_response(self, response):
try:
return json.loads(response)
except json.JSONDecodeError:
_LOGGING.debug('Failed to parse response from TV. response text: %s', response)
raise exceptions.ResponseError('Failed to parse response from TV. Maybe feature not supported on this model')
def open(self):
url = self._format_websocket_url()
sslopt = {'cert_reqs': ssl.CERT_NONE} if self._is_ssl_connection() else {}
_LOGGING.debug('WS url %s', url)
self.connection = websocket.create_connection(
url,
self.timeout,
sslopt=sslopt,
connection='Connection: Upgrade'
)
response = self._process_api_response(self.connection.recv())
if response.get('data') and response.get('data').get('token'):
token = response.get('data').get('token')
_LOGGING.debug('Got token %s', token)
self._set_token(token)
if response['event'] != 'ms.channel.connect':
self.close()
raise exceptions.ConnectionFailure(response)
def close(self):
if self.connection:
self.connection.close()
self.connection = None
_LOGGING.debug('Connection closed.')
def send_key(self, key, times=1, key_press_delay=None, cmd='Click'):
for _ in range(times):
_LOGGING.debug('Sending key %s', key)
self._ws_send(
{
'method': 'ms.remote.control',
'params': {
'Cmd': cmd,
'DataOfCmd': key,
'Option': 'false',
'TypeOfRemote': 'SendRemoteKey'
}
},
key_press_delay
)
def hold_key(self, key, seconds):
self.send_key(key, cmd='Press')
time.sleep(seconds)
self.send_key(key, cmd='Release')
def move_cursor(self, x, y, duration=0):
self._ws_send(
{
'method': 'ms.remote.control',
'params': {
'Cmd': 'Move',
'Position': {
'x': x,
'y': y,
'Time': str(duration)
},
'TypeOfRemote': 'ProcessMouseDevice'
}
},
key_press_delay=0
)
def run_app(self, app_id, app_type='DEEP_LINK', meta_tag=''):
_LOGGING.debug('Sending run app app_id: %s app_type: %s meta_tag: %s', app_id, app_type, meta_tag)
self._ws_send({
'method': 'ms.channel.emit',
'params': {
'event': 'ed.apps.launch',
'to': 'host',
'data': {
'action_type': app_type,
'appId': app_id,
'metaTag': meta_tag
}
}
})
def open_browser(self, url):
_LOGGING.debug('Opening url in browser %s', url)
self.run_app(
'org.tizen.browser',
'NATIVE_LAUNCH',
url
)
def app_list(self):
_LOGGING.debug('Get app list')
self._ws_send({
'method': 'ms.channel.emit',
'params': {
'event': 'ed.installedApp.get',
'to': 'host'
}
})
response = self._process_api_response(self.connection.recv())
if response.get('data') and response.get('data').get('data'):
return response.get('data').get('data')
else:
return response
def rest_device_info(self):
_LOGGING.debug('Get device info via rest api')
response = self._rest_request('')
return self._process_api_response(response.text)
def rest_app_status(self, app_id):
_LOGGING.debug('Get app %s status via rest api', app_id)
response = self._rest_request('applications/' + app_id)
return self._process_api_response(response.text)
def rest_app_run(self, app_id):
_LOGGING.debug('Run app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'POST')
return self._process_api_response(response.text)
def rest_app_close(self, app_id):
_LOGGING.debug('Close app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'DELETE')
return self._process_api_response(response.text)
def rest_app_install(self, app_id):
_LOGGING.debug('Install app %s via rest api', app_id)
response = self._rest_request('applications/' + app_id, 'PUT')
return self._process_api_response(response.text)
def shortcuts(self):
return shortcuts.SamsungTVShortcuts(self)
| true | true |
f726a064dd1bdc39f3586c546ec4b50d380b3919 | 2,492 | py | Python | tests/components/spc/test_init.py | tuxbox/home-assistant | df74272ba6311d527fd07198929c80a45d9fed15 | [
"Apache-2.0"
] | 1 | 2019-12-26T15:06:02.000Z | 2019-12-26T15:06:02.000Z | tests/components/spc/test_init.py | tuxbox/home-assistant | df74272ba6311d527fd07198929c80a45d9fed15 | [
"Apache-2.0"
] | null | null | null | tests/components/spc/test_init.py | tuxbox/home-assistant | df74272ba6311d527fd07198929c80a45d9fed15 | [
"Apache-2.0"
] | null | null | null | """Tests for Vanderbilt SPC component."""
from unittest.mock import patch, PropertyMock, Mock
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.spc import DATA_API
from homeassistant.const import STATE_ALARM_ARMED_AWAY, STATE_ALARM_DISARMED
from tests.common import mock_coro
async def test_valid_device_config(hass, monkeypatch):
"""Test valid device config."""
config = {"spc": {"api_url": "http://localhost/", "ws_url": "ws://localhost/"}}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is True
async def test_invalid_device_config(hass, monkeypatch):
"""Test valid device config."""
config = {"spc": {"api_url": "http://localhost/"}}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is False
async def test_update_alarm_device(hass):
"""Test that alarm panel state changes on incoming websocket data."""
import pyspcwebgw
from pyspcwebgw.const import AreaMode
config = {"spc": {"api_url": "http://localhost/", "ws_url": "ws://localhost/"}}
area_mock = Mock(
spec=pyspcwebgw.area.Area,
id="1",
mode=AreaMode.FULL_SET,
last_changed_by="Sven",
)
area_mock.name = "House"
area_mock.verified_alarm = False
with patch(
"homeassistant.components.spc.SpcWebGateway.areas", new_callable=PropertyMock
) as mock_areas:
mock_areas.return_value = {"1": area_mock}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is True
await hass.async_block_till_done()
entity_id = "alarm_control_panel.house"
assert hass.states.get(entity_id).state == STATE_ALARM_ARMED_AWAY
assert hass.states.get(entity_id).attributes["changed_by"] == "Sven"
area_mock.mode = AreaMode.UNSET
area_mock.last_changed_by = "Anna"
await hass.data[DATA_API]._async_callback(area_mock)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_ALARM_DISARMED
assert hass.states.get(entity_id).attributes["changed_by"] == "Anna"
| 34.136986 | 85 | 0.702648 | from unittest.mock import patch, PropertyMock, Mock
from homeassistant.bootstrap import async_setup_component
from homeassistant.components.spc import DATA_API
from homeassistant.const import STATE_ALARM_ARMED_AWAY, STATE_ALARM_DISARMED
from tests.common import mock_coro
async def test_valid_device_config(hass, monkeypatch):
config = {"spc": {"api_url": "http://localhost/", "ws_url": "ws://localhost/"}}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is True
async def test_invalid_device_config(hass, monkeypatch):
config = {"spc": {"api_url": "http://localhost/"}}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is False
async def test_update_alarm_device(hass):
import pyspcwebgw
from pyspcwebgw.const import AreaMode
config = {"spc": {"api_url": "http://localhost/", "ws_url": "ws://localhost/"}}
area_mock = Mock(
spec=pyspcwebgw.area.Area,
id="1",
mode=AreaMode.FULL_SET,
last_changed_by="Sven",
)
area_mock.name = "House"
area_mock.verified_alarm = False
with patch(
"homeassistant.components.spc.SpcWebGateway.areas", new_callable=PropertyMock
) as mock_areas:
mock_areas.return_value = {"1": area_mock}
with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True),
):
assert await async_setup_component(hass, "spc", config) is True
await hass.async_block_till_done()
entity_id = "alarm_control_panel.house"
assert hass.states.get(entity_id).state == STATE_ALARM_ARMED_AWAY
assert hass.states.get(entity_id).attributes["changed_by"] == "Sven"
area_mock.mode = AreaMode.UNSET
area_mock.last_changed_by = "Anna"
await hass.data[DATA_API]._async_callback(area_mock)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_ALARM_DISARMED
assert hass.states.get(entity_id).attributes["changed_by"] == "Anna"
| true | true |
f726a0e6a992cdb370f4db8314ec60bd087084f1 | 13,279 | py | Python | game-simulation/ctf01d-assistent.py | freehackquest/fhq-jury-ad | c839eefe98e5a6ccec6b182417f13929ebfe733a | [
"MIT"
] | 12 | 2018-09-28T10:57:10.000Z | 2020-03-30T15:53:05.000Z | game-simulation/ctf01d-assistent.py | freehackquest/fhq-jury-ad | c839eefe98e5a6ccec6b182417f13929ebfe733a | [
"MIT"
] | 32 | 2018-09-28T14:10:51.000Z | 2020-08-31T08:54:21.000Z | game-simulation/ctf01d-assistent.py | freehackquest/fhq-jury-ad | c839eefe98e5a6ccec6b182417f13929ebfe733a | [
"MIT"
] | 3 | 2018-09-28T14:21:41.000Z | 2019-11-02T14:14:34.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import docker
import sys
import os
import time
import datetime
# https://docker-py.readthedocs.io/en/latest/
client = docker.from_env()
progname = sys.argv[0]
# TODO read from data/config.yml
teams = [
{
"name": "team1",
"ip_prefix": "10.10.11"
}, {
"name": "team2",
"ip_prefix": "10.10.12"
}, {
"name": "team3",
"ip_prefix": "10.10.13"
}
]
jury_net_prefix = "10.10.100"
ntwrk_name_prefix = "ctf01d_net_"
services_list = ["service1_py", "service2_go", "service3_php", "service4_cpp"]
img_name_prefix = "ctf01d-game-simulation/"
watchdog_containers_list = []
def printHelp():
print("\n"
+ progname + " - assistent for manupulate game-simulation\n"
"commands:\n"
"\t clean - remove all containers, images, networks and etc...\n"
"\t start - prepare networks, images, containers and etc \n"
"\n"
)
if len(sys.argv) < 2:
printHelp()
exit(1)
command = sys.argv[1]
def stopAndRemoveAllContainers():
cntrs = client.containers.list(all=True)
# print(cntrs)
for c in cntrs:
if c.name.startswith("ctf01d_"):
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
def createNetwork(network_list, network_name, ip_prefix):
for n in network_list:
if n.name == network_name:
print("Network already exists " + network_name)
return
print("Creating network " + network_name)
ipam_pool = docker.types.IPAMPool(
subnet=ip_prefix + '.0/24',
iprange=ip_prefix + '.0/24',
gateway=ip_prefix + '.1',
aux_addresses={
'vuln_server': ip_prefix + '.2'
}
)
ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
ret = client.networks.create(
network_name,
driver="bridge",
check_duplicate=True,
ipam=ipam_config
)
"""
simular command:
$ docker network create \
--driver bridge \
--gateway 10.10.11.1 \
--subnet=10.10.11.0/24 \
--ip-range=10.10.11.3/24 \
"ctf01d_net_team1"
"""
print(" -> Done." + str(ret))
def createTeamAndJuryNetworks():
print("\n ===> Create networks")
ntwrks = client.networks.list()
createNetwork(ntwrks, ntwrk_name_prefix + "jury", jury_net_prefix)
for t in teams:
# print(t)
network_name_team = ntwrk_name_prefix + t['name']
createNetwork(ntwrks, network_name_team, t['ip_prefix'])
def buildImage(images_list, image_tag, pathWithDockerfile):
if not os.path.isdir(pathWithDockerfile):
print(pathWithDockerfile + " - not exists")
exit(-1)
return
path_dockerfile = pathWithDockerfile + "/Dockerfile"
if not os.path.isfile(path_dockerfile):
print(path_dockerfile + " - not exists")
exit(-1)
return
for i in images_list:
tag = ""
if len(i.tags) > 0:
tag = i.tags[0]
if tag == image_tag:
print(image_tag + " - Skip. Image already exists.")
return
# TODO redesing to command line build
"""
simular command:
docker build -t ctf01d-game-simulation/service2_go:latest ./vulnbox/service2_go/
"""
print("Building image " + image_tag + "...")
ret = client.images.build(
path=pathWithDockerfile,
tag=image_tag,
forcerm=True # Always remove intermediate containers, even after unsuccessful builds
)
print(" -> Done." + str(ret))
def buildJuryAndServiceImages():
print("\n ===> Docker images for Services")
imgs = client.images.list()
# basic image with jury
buildImage(imgs, "sea5kg/ctf01d:latest", "..")
for service_name in services_list:
img_tag = img_name_prefix + service_name + ":latest"
buildImage(imgs, img_tag, "./vulnbox/" + service_name)
def runAllService1Py():
print(" ===> Starting all service1_py")
service_name = "service1_py"
img_name = img_name_prefix + service_name + ":latest"
for t in teams:
dirname_flags = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_flags"
if not os.path.isdir(dirname_flags):
os.mkdir(dirname_flags)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_flags = docker.types.Mount(
target="/root/flags",
source=dirname_flags,
type="bind"
)
container = client.containers.run(
img_name,
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_flags],
network=network_name_team,
ports={"4101/tcp": (t['ip_prefix'] + ".1", 4101) },
name=container_name,
detach=True
)
"""
simular command:
docker run \
-d \
--memory 128MB \
--memory-swap 128MB \
-p "10.10.11.1:4101":4101 \
-v `pwd`/vulnbox/service1_py/flags:/root/flags \
--net "ctf01d_net_team1" \
--name "ctf01d_team1_service1_py" \
ctf01d-game-simulation/service1_py:latest
"""
watchdog_containers_list.append(container_name)
print(container)
def runAllService2GoDatabase():
print(" ===> Starting all service2_go_db")
service_name = "service2_go_db"
# img_name = img_name_prefix + service_name + ":latest"
for t in teams:
dirname_mysql = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_mysql"
if not os.path.isdir(dirname_mysql):
os.mkdir(dirname_mysql)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_mysql = docker.types.Mount(
target="/var/lib/mysql",
source=dirname_mysql,
type="bind"
)
mount_sql = docker.types.Mount(
target="/docker-entrypoint-initdb.d",
source=os.getcwd() + "/./vulnbox/service2_go/sql",
type="bind"
)
container = client.containers.run(
"mysql:5.7",
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_mysql, mount_sql],
environment={
"MYSQL_ROOT_PASSWORD": "service2_go",
"MYSQL_DATABASE": "service2_go",
"MYSQL_USER": "service2_go",
"MYSQL_PASSWORD": "service2_go",
},
network=network_name_team,
# ports={"4101/tcp": (t['ip_prefix'] + ".1", 4101) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def runAllService2Go():
print(" ===> Starting all service2_go")
service_name = "service2_go"
img_name = img_name_prefix + service_name + ":latest"
for t in teams:
dirname_flags = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_flags"
if not os.path.isdir(dirname_flags):
os.mkdir(dirname_flags)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
container = client.containers.run(
img_name,
mem_limit="128M",
memswap_limit="128M",
network=network_name_team,
environment={
"SERVICE2_GO_MYSQL_HOST": container_name + "_db",
"SERVICE2_GO_MYSQL_DBNAME": "service2_go",
"SERVICE2_GO_MYSQL_USER": "service2_go",
"SERVICE2_GO_MYSQL_PASSWORD": "service2_go",
},
ports={"4102/tcp": (t['ip_prefix'] + ".1", 4102) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def runCtf01dJuryDb():
print(" ===> Starting ctf01d-jury db")
dirname_mysql = os.getcwd() + "/./tmp/jury_db_mysql"
if not os.path.isdir(dirname_mysql):
os.mkdir(dirname_mysql)
network_name_team = ntwrk_name_prefix + "jury"
container_name = "ctf01d_jury_db"
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_mysql = docker.types.Mount(
target="/var/lib/mysql",
source=dirname_mysql,
type="bind"
)
container = client.containers.run(
"mysql:8",
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_mysql],
environment={
"MYSQL_ROOT_PASSWORD": "KzhyntJxwt",
"MYSQL_DATABASE": "ctf01d",
"MYSQL_USER": "ctf01d",
"MYSQL_PASSWORD": "ctf01d",
},
network=network_name_team,
# ports={"4101/tcp": (t['ip_prefix'] + ".1", 4101) },
name=container_name,
detach=True,
command="mysqld --default-authentication-plugin=mysql_native_password"
)
"""
simular command:
docker run -d \
--name ctf01d-mysql \
-e MYSQL_ROOT_PASSWORD=KzhyntJxwt \
-e MYSQL_DATABASE=ctf01d \
-e MYSQL_USER=ctf01d \
-e MYSQL_PASSWORD=ctf01d \
--network ctf01d_net \
mysql:8 \
mysqld --default-authentication-plugin=mysql_native_password
"""
watchdog_containers_list.append(container_name)
print(container)
def runCtf01dJury():
print(" ===> Starting ctf01d-jury")
dirname_data = os.getcwd() + "/data/"
network_name_jury = ntwrk_name_prefix + "jury"
container_name = "ctf01d_jury"
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_data = docker.types.Mount(
target="/root/data",
source=dirname_data,
type="bind"
)
container = client.containers.run(
"sea5kg/ctf01d:latest",
mem_limit="256M",
memswap_limit="256M",
mounts=[mount_data],
network=network_name_jury,
ports={"8080/tcp": ("localhost", 8080) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def startWatchDog():
try:
print(" ===> Starting watch dog")
while True:
cntrs = client.containers.list(all=True)
for wc in watchdog_containers_list:
for c in cntrs:
if c.name == wc and c.status == "exited":
today = datetime.datetime.today()
print(today.strftime("%Y%m%d-%H%M%S") + " Container " + wc + " is exited. Try start again")
c.start()
time.sleep(15)
except KeyboardInterrupt:
print('Bye! Write me letters!')
stopAndRemoveAllContainers()
if command == "stop":
stopAndRemoveAllContainers()
if command == "clean":
stopAndRemoveAllContainers()
ntwrks = client.networks.list()
for n in ntwrks:
if n.name.startswith(ntwrk_name_prefix):
print("Removing network " + n.name)
n.remove()
# find and remove images
imgs = client.images.list()
for i in imgs:
tag = ""
if len(i.tags) > 0:
tag = i.tags[0]
if tag.startswith(img_name_prefix):
print("Removing image " + tag)
client.images.remove(image=tag)
exit(0)
if command == "start":
if not os.path.isdir("./tmp"):
os.mkdir("./tmp")
createTeamAndJuryNetworks()
buildJuryAndServiceImages()
runAllService1Py()
runAllService2GoDatabase()
runAllService2Go()
runCtf01dJuryDb()
runCtf01dJury()
startWatchDog() | 31.318396 | 115 | 0.568416 |
import docker
import sys
import os
import time
import datetime
client = docker.from_env()
progname = sys.argv[0]
teams = [
{
"name": "team1",
"ip_prefix": "10.10.11"
}, {
"name": "team2",
"ip_prefix": "10.10.12"
}, {
"name": "team3",
"ip_prefix": "10.10.13"
}
]
jury_net_prefix = "10.10.100"
ntwrk_name_prefix = "ctf01d_net_"
services_list = ["service1_py", "service2_go", "service3_php", "service4_cpp"]
img_name_prefix = "ctf01d-game-simulation/"
watchdog_containers_list = []
def printHelp():
print("\n"
+ progname + " - assistent for manupulate game-simulation\n"
"commands:\n"
"\t clean - remove all containers, images, networks and etc...\n"
"\t start - prepare networks, images, containers and etc \n"
"\n"
)
if len(sys.argv) < 2:
printHelp()
exit(1)
command = sys.argv[1]
def stopAndRemoveAllContainers():
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name.startswith("ctf01d_"):
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
def createNetwork(network_list, network_name, ip_prefix):
for n in network_list:
if n.name == network_name:
print("Network already exists " + network_name)
return
print("Creating network " + network_name)
ipam_pool = docker.types.IPAMPool(
subnet=ip_prefix + '.0/24',
iprange=ip_prefix + '.0/24',
gateway=ip_prefix + '.1',
aux_addresses={
'vuln_server': ip_prefix + '.2'
}
)
ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
ret = client.networks.create(
network_name,
driver="bridge",
check_duplicate=True,
ipam=ipam_config
)
print(" -> Done." + str(ret))
def createTeamAndJuryNetworks():
print("\n ===> Create networks")
ntwrks = client.networks.list()
createNetwork(ntwrks, ntwrk_name_prefix + "jury", jury_net_prefix)
for t in teams:
network_name_team = ntwrk_name_prefix + t['name']
createNetwork(ntwrks, network_name_team, t['ip_prefix'])
def buildImage(images_list, image_tag, pathWithDockerfile):
if not os.path.isdir(pathWithDockerfile):
print(pathWithDockerfile + " - not exists")
exit(-1)
return
path_dockerfile = pathWithDockerfile + "/Dockerfile"
if not os.path.isfile(path_dockerfile):
print(path_dockerfile + " - not exists")
exit(-1)
return
for i in images_list:
tag = ""
if len(i.tags) > 0:
tag = i.tags[0]
if tag == image_tag:
print(image_tag + " - Skip. Image already exists.")
return
print("Building image " + image_tag + "...")
ret = client.images.build(
path=pathWithDockerfile,
tag=image_tag,
forcerm=True
)
print(" -> Done." + str(ret))
def buildJuryAndServiceImages():
print("\n ===> Docker images for Services")
imgs = client.images.list()
buildImage(imgs, "sea5kg/ctf01d:latest", "..")
for service_name in services_list:
img_tag = img_name_prefix + service_name + ":latest"
buildImage(imgs, img_tag, "./vulnbox/" + service_name)
def runAllService1Py():
print(" ===> Starting all service1_py")
service_name = "service1_py"
img_name = img_name_prefix + service_name + ":latest"
for t in teams:
dirname_flags = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_flags"
if not os.path.isdir(dirname_flags):
os.mkdir(dirname_flags)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_flags = docker.types.Mount(
target="/root/flags",
source=dirname_flags,
type="bind"
)
container = client.containers.run(
img_name,
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_flags],
network=network_name_team,
ports={"4101/tcp": (t['ip_prefix'] + ".1", 4101) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def runAllService2GoDatabase():
print(" ===> Starting all service2_go_db")
service_name = "service2_go_db"
for t in teams:
dirname_mysql = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_mysql"
if not os.path.isdir(dirname_mysql):
os.mkdir(dirname_mysql)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_mysql = docker.types.Mount(
target="/var/lib/mysql",
source=dirname_mysql,
type="bind"
)
mount_sql = docker.types.Mount(
target="/docker-entrypoint-initdb.d",
source=os.getcwd() + "/./vulnbox/service2_go/sql",
type="bind"
)
container = client.containers.run(
"mysql:5.7",
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_mysql, mount_sql],
environment={
"MYSQL_ROOT_PASSWORD": "service2_go",
"MYSQL_DATABASE": "service2_go",
"MYSQL_USER": "service2_go",
"MYSQL_PASSWORD": "service2_go",
},
network=network_name_team,
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def runAllService2Go():
print(" ===> Starting all service2_go")
service_name = "service2_go"
img_name = img_name_prefix + service_name + ":latest"
for t in teams:
dirname_flags = os.getcwd() + "/./tmp/" + t['name'] + "_" + service_name + "_flags"
if not os.path.isdir(dirname_flags):
os.mkdir(dirname_flags)
network_name_team = ntwrk_name_prefix + t['name']
container_name = "ctf01d_" + t['name'] + "_" + service_name
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
container = client.containers.run(
img_name,
mem_limit="128M",
memswap_limit="128M",
network=network_name_team,
environment={
"SERVICE2_GO_MYSQL_HOST": container_name + "_db",
"SERVICE2_GO_MYSQL_DBNAME": "service2_go",
"SERVICE2_GO_MYSQL_USER": "service2_go",
"SERVICE2_GO_MYSQL_PASSWORD": "service2_go",
},
ports={"4102/tcp": (t['ip_prefix'] + ".1", 4102) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def runCtf01dJuryDb():
print(" ===> Starting ctf01d-jury db")
dirname_mysql = os.getcwd() + "/./tmp/jury_db_mysql"
if not os.path.isdir(dirname_mysql):
os.mkdir(dirname_mysql)
network_name_team = ntwrk_name_prefix + "jury"
container_name = "ctf01d_jury_db"
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_mysql = docker.types.Mount(
target="/var/lib/mysql",
source=dirname_mysql,
type="bind"
)
container = client.containers.run(
"mysql:8",
mem_limit="128M",
memswap_limit="128M",
mounts=[mount_mysql],
environment={
"MYSQL_ROOT_PASSWORD": "KzhyntJxwt",
"MYSQL_DATABASE": "ctf01d",
"MYSQL_USER": "ctf01d",
"MYSQL_PASSWORD": "ctf01d",
},
network=network_name_team,
name=container_name,
detach=True,
command="mysqld --default-authentication-plugin=mysql_native_password"
)
watchdog_containers_list.append(container_name)
print(container)
def runCtf01dJury():
print(" ===> Starting ctf01d-jury")
dirname_data = os.getcwd() + "/data/"
network_name_jury = ntwrk_name_prefix + "jury"
container_name = "ctf01d_jury"
cntrs = client.containers.list(all=True)
for c in cntrs:
if c.name == container_name:
print("Stopping container " + c.name)
c.stop()
print("Removing container " + c.name)
c.remove()
print("Starting " + container_name)
mount_data = docker.types.Mount(
target="/root/data",
source=dirname_data,
type="bind"
)
container = client.containers.run(
"sea5kg/ctf01d:latest",
mem_limit="256M",
memswap_limit="256M",
mounts=[mount_data],
network=network_name_jury,
ports={"8080/tcp": ("localhost", 8080) },
name=container_name,
detach=True
)
watchdog_containers_list.append(container_name)
print(container)
def startWatchDog():
try:
print(" ===> Starting watch dog")
while True:
cntrs = client.containers.list(all=True)
for wc in watchdog_containers_list:
for c in cntrs:
if c.name == wc and c.status == "exited":
today = datetime.datetime.today()
print(today.strftime("%Y%m%d-%H%M%S") + " Container " + wc + " is exited. Try start again")
c.start()
time.sleep(15)
except KeyboardInterrupt:
print('Bye! Write me letters!')
stopAndRemoveAllContainers()
if command == "stop":
stopAndRemoveAllContainers()
if command == "clean":
stopAndRemoveAllContainers()
ntwrks = client.networks.list()
for n in ntwrks:
if n.name.startswith(ntwrk_name_prefix):
print("Removing network " + n.name)
n.remove()
imgs = client.images.list()
for i in imgs:
tag = ""
if len(i.tags) > 0:
tag = i.tags[0]
if tag.startswith(img_name_prefix):
print("Removing image " + tag)
client.images.remove(image=tag)
exit(0)
if command == "start":
if not os.path.isdir("./tmp"):
os.mkdir("./tmp")
createTeamAndJuryNetworks()
buildJuryAndServiceImages()
runAllService1Py()
runAllService2GoDatabase()
runAllService2Go()
runCtf01dJuryDb()
runCtf01dJury()
startWatchDog() | true | true |
f726a156e670ac369a860bc003d31ce52ead8fb6 | 9,807 | py | Python | sickbeard/lib/subliminal/services/itasa.py | Branlala/docker-sickbeardfr | 3ac85092dc4cc8a4171fb3c83e9682162245e13e | [
"MIT"
] | null | null | null | sickbeard/lib/subliminal/services/itasa.py | Branlala/docker-sickbeardfr | 3ac85092dc4cc8a4171fb3c83e9682162245e13e | [
"MIT"
] | null | null | null | sickbeard/lib/subliminal/services/itasa.py | Branlala/docker-sickbeardfr | 3ac85092dc4cc8a4171fb3c83e9682162245e13e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2012 Mr_Orange <mr_orange@hotmail.it>
#
# This file is part of subliminal.
#
# subliminal is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# subliminal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with subliminal. If not, see <http://www.gnu.org/licenses/>.
from . import ServiceBase
from ..exceptions import DownloadFailedError, ServiceError
from ..cache import cachedmethod
from ..language import language_set, Language
from ..subtitles import get_subtitle_path, ResultSubtitle, EXTENSIONS
from ..utils import get_keywords
from ..videos import Episode
from bs4 import BeautifulSoup
import logging
import re
import os
import requests
import zipfile
import StringIO
import guessit
from sickbeard.common import Quality
logger = logging.getLogger("subliminal")
class Itasa(ServiceBase):
server_url = 'http://www.italiansubs.net/'
site_url = 'http://www.italiansubs.net/'
api_based = False
languages = language_set(['it'])
videos = [Episode]
require_video = False
required_features = ['permissive']
quality_dict = {Quality.SDTV : '',
Quality.SDDVD : 'dvdrip',
Quality.RAWHDTV : '1080i',
Quality.HDTV : '720p',
Quality.FULLHDTV : ('1080p','720p'),
Quality.HDWEBDL : 'web-dl',
Quality.FULLHDWEBDL : 'web-dl',
Quality.HDBLURAY : ('bdrip', 'bluray'),
Quality.FULLHDBLURAY : ('bdrip', 'bluray'),
Quality.UNKNOWN : 'unknown' #Any subtitle will be downloaded
}
def init(self):
super(Itasa, self).init()
login_pattern = '<input type="hidden" name="return" value="([^\n\r\t ]+?)" /><input type="hidden" name="([^\n\r\t ]+?)" value="([^\n\r\t ]+?)" />'
response = requests.get(self.server_url + 'index.php')
if response.status_code != 200:
raise ServiceError('Initiate failed')
match = re.search(login_pattern, response.content, re.IGNORECASE | re.DOTALL)
if not match:
raise ServiceError('Can not find unique id parameter on page')
login_parameter = {'username': 'sickbeard',
'passwd': 'subliminal',
'remember': 'yes',
'Submit': 'Login',
'remember': 'yes',
'option': 'com_user',
'task': 'login',
'silent': 'true',
'return': match.group(1),
match.group(2): match.group(3)
}
self.session = requests.session()
r = self.session.post(self.server_url + 'index.php', data=login_parameter)
if not re.search('logouticon.png', r.content, re.IGNORECASE | re.DOTALL):
raise ServiceError('Itasa Login Failed')
@cachedmethod
def get_series_id(self, name):
"""Get the show page and cache every show found in it"""
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=9')
soup = BeautifulSoup(r.content, self.required_features)
all_series = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for tv_series in all_series.find_all(href=re.compile('func=select')):
series_name = tv_series.text.lower().strip().replace(':','')
match = re.search('&id=([0-9]+)', tv_series['href'])
if match is None:
continue
series_id = int(match.group(1))
self.cache_for(self.get_series_id, args=(series_name,), result=series_id)
return self.cached_value(self.get_series_id, args=(name,))
def get_episode_id(self, series, series_id, season, episode, quality):
"""Get the id subtitle for episode with the given quality"""
season_link = None
quality_link = None
episode_id = None
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=select&id=' + str(series_id))
soup = BeautifulSoup(r.content, self.required_features)
all_seasons = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for seasons in all_seasons.find_all(href=re.compile('func=select')):
if seasons.text.lower().strip() == 'stagione %s' % str(season):
season_link = seasons['href']
break
if not season_link:
logger.debug(u'Could not find season %s for series %s' % (series, str(season)))
return None
r = self.session.get(season_link)
soup = BeautifulSoup(r.content, self.required_features)
all_qualities = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for qualities in all_qualities.find_all(href=re.compile('func=select')):
if qualities.text.lower().strip() in self.quality_dict[quality]:
quality_link = qualities['href']
r = self.session.get(qualities['href'])
soup = BeautifulSoup(r.content, self.required_features)
break
#If we want SDTV we are just on the right page so quality link will be None
if not quality == Quality.SDTV and not quality_link:
logger.debug(u'Could not find a subtitle with required quality for series %s season %s' % (series, str(season)))
return None
all_episodes = soup.find('div', attrs = {'id' : 'remositoryfilelisting'})
for episodes in all_episodes.find_all(href=re.compile('func=fileinfo')):
ep_string = "%(seasonnumber)dx%(episodenumber)02d" % {'seasonnumber': season, 'episodenumber': episode}
if re.search(ep_string, episodes.text, re.I) or re.search('completa$', episodes.text, re.I):
match = re.search('&id=([0-9]+)', episodes['href'])
if match:
episode_id = match.group(1)
return episode_id
return episode_id
def list_checked(self, video, languages):
return self.query(video.path or video.release, languages, get_keywords(video.guess), video.series, video.season, video.episode)
def query(self, filepath, languages, keywords, series, season, episode):
logger.debug(u'Getting subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
self.init_cache()
try:
series = series.lower().replace('(','').replace(')','')
series_id = self.get_series_id(series)
except KeyError:
logger.debug(u'Could not find series id for %s' % series)
return []
episode_id = self.get_episode_id(series, series_id, season, episode, Quality.nameQuality(filepath))
if not episode_id:
logger.debug(u'Could not find subtitle for series %s' % series)
return []
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=fileinfo&id=' + episode_id)
soup = BeautifulSoup(r.content)
sub_link = soup.find('div', attrs = {'id' : 'remositoryfileinfo'}).find(href=re.compile('func=download'))['href']
sub_language = self.get_language('it')
path = get_subtitle_path(filepath, sub_language, self.config.multi)
subtitle = ResultSubtitle(path, sub_language, self.__class__.__name__.lower(), sub_link)
return [subtitle]
def download(self, subtitle):
logger.info(u'Downloading %s in %s' % (subtitle.link, subtitle.path))
try:
r = self.session.get(subtitle.link, headers={'Referer': self.server_url, 'User-Agent': self.user_agent})
zipcontent = StringIO.StringIO(r.content)
zipsub = zipfile.ZipFile(zipcontent)
# if not zipsub.is_zipfile(zipcontent):
# raise DownloadFailedError('Downloaded file is not a zip file')
subfile = ''
if len(zipsub.namelist()) == 1:
subfile = zipsub.namelist()[0]
else:
#Season Zip Retrive Season and episode Numbers from path
guess = guessit.guess_file_info(subtitle.path, 'episode')
ep_string = "s%(seasonnumber)02de%(episodenumber)02d" % {'seasonnumber': guess['season'], 'episodenumber': guess['episodeNumber']}
for file in zipsub.namelist():
if re.search(ep_string, file, re.I):
subfile = file
break
if os.path.splitext(subfile)[1] in EXTENSIONS:
with open(subtitle.path, 'wb') as f:
f.write(zipsub.open(subfile).read())
else:
zipsub.close()
raise DownloadFailedError('No subtitles found in zip file')
zipsub.close()
except Exception as e:
if os.path.exists(subtitle.path):
os.remove(subtitle.path)
raise DownloadFailedError(str(e))
logger.debug(u'Download finished')
Service = Itasa | 45.402778 | 154 | 0.593862 |
from . import ServiceBase
from ..exceptions import DownloadFailedError, ServiceError
from ..cache import cachedmethod
from ..language import language_set, Language
from ..subtitles import get_subtitle_path, ResultSubtitle, EXTENSIONS
from ..utils import get_keywords
from ..videos import Episode
from bs4 import BeautifulSoup
import logging
import re
import os
import requests
import zipfile
import StringIO
import guessit
from sickbeard.common import Quality
logger = logging.getLogger("subliminal")
class Itasa(ServiceBase):
server_url = 'http://www.italiansubs.net/'
site_url = 'http://www.italiansubs.net/'
api_based = False
languages = language_set(['it'])
videos = [Episode]
require_video = False
required_features = ['permissive']
quality_dict = {Quality.SDTV : '',
Quality.SDDVD : 'dvdrip',
Quality.RAWHDTV : '1080i',
Quality.HDTV : '720p',
Quality.FULLHDTV : ('1080p','720p'),
Quality.HDWEBDL : 'web-dl',
Quality.FULLHDWEBDL : 'web-dl',
Quality.HDBLURAY : ('bdrip', 'bluray'),
Quality.FULLHDBLURAY : ('bdrip', 'bluray'),
Quality.UNKNOWN : 'unknown'
}
def init(self):
super(Itasa, self).init()
login_pattern = '<input type="hidden" name="return" value="([^\n\r\t ]+?)" /><input type="hidden" name="([^\n\r\t ]+?)" value="([^\n\r\t ]+?)" />'
response = requests.get(self.server_url + 'index.php')
if response.status_code != 200:
raise ServiceError('Initiate failed')
match = re.search(login_pattern, response.content, re.IGNORECASE | re.DOTALL)
if not match:
raise ServiceError('Can not find unique id parameter on page')
login_parameter = {'username': 'sickbeard',
'passwd': 'subliminal',
'remember': 'yes',
'Submit': 'Login',
'remember': 'yes',
'option': 'com_user',
'task': 'login',
'silent': 'true',
'return': match.group(1),
match.group(2): match.group(3)
}
self.session = requests.session()
r = self.session.post(self.server_url + 'index.php', data=login_parameter)
if not re.search('logouticon.png', r.content, re.IGNORECASE | re.DOTALL):
raise ServiceError('Itasa Login Failed')
@cachedmethod
def get_series_id(self, name):
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=9')
soup = BeautifulSoup(r.content, self.required_features)
all_series = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for tv_series in all_series.find_all(href=re.compile('func=select')):
series_name = tv_series.text.lower().strip().replace(':','')
match = re.search('&id=([0-9]+)', tv_series['href'])
if match is None:
continue
series_id = int(match.group(1))
self.cache_for(self.get_series_id, args=(series_name,), result=series_id)
return self.cached_value(self.get_series_id, args=(name,))
def get_episode_id(self, series, series_id, season, episode, quality):
season_link = None
quality_link = None
episode_id = None
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=select&id=' + str(series_id))
soup = BeautifulSoup(r.content, self.required_features)
all_seasons = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for seasons in all_seasons.find_all(href=re.compile('func=select')):
if seasons.text.lower().strip() == 'stagione %s' % str(season):
season_link = seasons['href']
break
if not season_link:
logger.debug(u'Could not find season %s for series %s' % (series, str(season)))
return None
r = self.session.get(season_link)
soup = BeautifulSoup(r.content, self.required_features)
all_qualities = soup.find('div', attrs = {'id' : 'remositorycontainerlist'})
for qualities in all_qualities.find_all(href=re.compile('func=select')):
if qualities.text.lower().strip() in self.quality_dict[quality]:
quality_link = qualities['href']
r = self.session.get(qualities['href'])
soup = BeautifulSoup(r.content, self.required_features)
break
if not quality == Quality.SDTV and not quality_link:
logger.debug(u'Could not find a subtitle with required quality for series %s season %s' % (series, str(season)))
return None
all_episodes = soup.find('div', attrs = {'id' : 'remositoryfilelisting'})
for episodes in all_episodes.find_all(href=re.compile('func=fileinfo')):
ep_string = "%(seasonnumber)dx%(episodenumber)02d" % {'seasonnumber': season, 'episodenumber': episode}
if re.search(ep_string, episodes.text, re.I) or re.search('completa$', episodes.text, re.I):
match = re.search('&id=([0-9]+)', episodes['href'])
if match:
episode_id = match.group(1)
return episode_id
return episode_id
def list_checked(self, video, languages):
return self.query(video.path or video.release, languages, get_keywords(video.guess), video.series, video.season, video.episode)
def query(self, filepath, languages, keywords, series, season, episode):
logger.debug(u'Getting subtitles for %s season %d episode %d with languages %r' % (series, season, episode, languages))
self.init_cache()
try:
series = series.lower().replace('(','').replace(')','')
series_id = self.get_series_id(series)
except KeyError:
logger.debug(u'Could not find series id for %s' % series)
return []
episode_id = self.get_episode_id(series, series_id, season, episode, Quality.nameQuality(filepath))
if not episode_id:
logger.debug(u'Could not find subtitle for series %s' % series)
return []
r = self.session.get(self.server_url + 'index.php?option=com_remository&Itemid=6&func=fileinfo&id=' + episode_id)
soup = BeautifulSoup(r.content)
sub_link = soup.find('div', attrs = {'id' : 'remositoryfileinfo'}).find(href=re.compile('func=download'))['href']
sub_language = self.get_language('it')
path = get_subtitle_path(filepath, sub_language, self.config.multi)
subtitle = ResultSubtitle(path, sub_language, self.__class__.__name__.lower(), sub_link)
return [subtitle]
def download(self, subtitle):
logger.info(u'Downloading %s in %s' % (subtitle.link, subtitle.path))
try:
r = self.session.get(subtitle.link, headers={'Referer': self.server_url, 'User-Agent': self.user_agent})
zipcontent = StringIO.StringIO(r.content)
zipsub = zipfile.ZipFile(zipcontent)
subfile = ''
if len(zipsub.namelist()) == 1:
subfile = zipsub.namelist()[0]
else:
guess = guessit.guess_file_info(subtitle.path, 'episode')
ep_string = "s%(seasonnumber)02de%(episodenumber)02d" % {'seasonnumber': guess['season'], 'episodenumber': guess['episodeNumber']}
for file in zipsub.namelist():
if re.search(ep_string, file, re.I):
subfile = file
break
if os.path.splitext(subfile)[1] in EXTENSIONS:
with open(subtitle.path, 'wb') as f:
f.write(zipsub.open(subfile).read())
else:
zipsub.close()
raise DownloadFailedError('No subtitles found in zip file')
zipsub.close()
except Exception as e:
if os.path.exists(subtitle.path):
os.remove(subtitle.path)
raise DownloadFailedError(str(e))
logger.debug(u'Download finished')
Service = Itasa | true | true |
f726a158af6f84e4cbe621f9839c0a52a862440f | 478 | py | Python | Data Science With Python/06-importing-data-in-python-(part-2)/1-importing-data-from-the-internet/parsing-html-with-beautifulsoup.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
] | 3 | 2019-05-12T04:49:24.000Z | 2020-05-06T00:40:28.000Z | Data Science With Python/06-importing-data-in-python-(part-2)/1-importing-data-from-the-internet/parsing-html-with-beautifulsoup.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
] | null | null | null | Data Science With Python/06-importing-data-in-python-(part-2)/1-importing-data-from-the-internet/parsing-html-with-beautifulsoup.py | aimanahmedmoin1997/DataCamp | c6a6c4d59b83f14854bd76ed5c0c7f2dddd6de1d | [
"MIT"
] | 7 | 2018-11-06T17:43:31.000Z | 2020-11-07T21:08:16.000Z | # Import packages
import requests
from bs4 import BeautifulSoup
# Specify url: url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Extracts the response as html: html_doc
html_doc = r.text
# Create a BeautifulSoup object from the HTML: soup
soup = BeautifulSoup(html_doc)
# Prettify the BeautifulSoup object: pretty_soup
pretty_soup = soup.prettify()
# Print the response
print(pretty_soup)
| 21.727273 | 65 | 0.76569 |
import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/~guido/'
r = requests.get(url)
html_doc = r.text
soup = BeautifulSoup(html_doc)
pretty_soup = soup.prettify()
print(pretty_soup)
| true | true |
f726a169158c8afc5ef59a42f7606019f51270fd | 7,006 | py | Python | experiments/vitchyr/goal_distribution/representation_learning/exps_20_08_14/exp1_oracle_pygame_latent_reward_1ob.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | 1 | 2020-10-23T14:40:09.000Z | 2020-10-23T14:40:09.000Z | experiments/vitchyr/goal_distribution/representation_learning/exps_20_08_14/exp1_oracle_pygame_latent_reward_1ob.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | null | null | null | experiments/vitchyr/goal_distribution/representation_learning/exps_20_08_14/exp1_oracle_pygame_latent_reward_1ob.py | Asap7772/railrl_evalsawyer | baba8ce634d32a48c7dfe4dc03b123e18e96e0a3 | [
"MIT"
] | 1 | 2021-05-27T20:38:45.000Z | 2021-05-27T20:38:45.000Z | import rlkit.misc.hyperparameter as hyp
from multiworld.envs.pygame import PickAndPlaceEnv
from rlkit.launchers.launcher_util import run_experiment
from rlkit.torch.sets.rl_launcher import disco_experiment
if __name__ == "__main__":
variant = dict(
env_class=PickAndPlaceEnv,
env_kwargs=dict(
# Environment dynamics
action_scale=1.0,
boundary_dist=4,
ball_radius=1.5,
object_radius=1.,
ball_visual_radius=1.5,
object_visual_radius=1.,
min_grab_distance=1.,
walls=None,
# Rewards
action_l2norm_penalty=0,
reward_type="dense",
success_threshold=0.60,
# Reset settings
fixed_goal=None,
# Visualization settings
images_are_rgb=True,
render_dt_msec=0,
render_onscreen=False,
render_size=84,
show_goal=False,
goal_samplers=None,
goal_sampling_mode='random',
num_presampled_goals=10000,
object_reward_only=False,
init_position_strategy='random',
num_objects=1,
),
qf_kwargs=dict(
hidden_sizes=[400, 300],
),
policy_kwargs=dict(
hidden_sizes=[400, 300],
),
sac_trainer_kwargs=dict(
discount=0.99,
soft_target_tau=1e-3,
target_update_period=1,
use_automatic_entropy_tuning=True,
reward_scale='auto_normalize_by_max_magnitude',
),
max_path_length=100,
algo_kwargs=dict(
batch_size=128,
num_epochs=501,
num_eval_steps_per_epoch=3000,
num_expl_steps_per_train_loop=1000,
num_trains_per_train_loop=1000,
min_num_steps_before_training=1000,
),
# max_path_length=2,
# algo_kwargs=dict(
# batch_size=5,
# num_epochs=1,
# num_eval_steps_per_epoch=2*20,
# num_expl_steps_per_train_loop=2*20,
# num_trains_per_train_loop=10,
# min_num_steps_before_training=10,
# ),
replay_buffer_kwargs=dict(
fraction_future_context=0.0,
fraction_distribution_context=0.8,
max_size=int(1e6),
),
save_video=True,
save_video_kwargs=dict(
save_video_period=10,
pad_color=50,
subpad_length=1,
pad_length=1,
num_columns_per_rollout=2,
num_imgs=8,
# rows=2,
# columns=9,
),
renderer_kwargs=dict(
# create_image_format='HWC',
# output_image_format='CWH',
output_image_format='CHW',
# flatten_image=True,
# normalize_image=False,
),
create_vae_kwargs=dict(
latent_dim=128,
encoder_cnn_kwargs=dict(
kernel_sizes=[5, 3, 3],
n_channels=[16, 32, 64],
strides=[3, 2, 2],
paddings=[0, 0, 0],
pool_type='none',
hidden_activation='relu',
normalization_type='layer',
),
encoder_mlp_kwargs=dict(
hidden_sizes=[],
),
decoder_dcnn_kwargs=dict(
kernel_sizes=[3, 3, 6],
n_channels=[32, 16, 3],
strides=[2, 2, 3],
paddings=[0, 0, 0],
),
decoder_mlp_kwargs=dict(
hidden_sizes=[256, 256],
),
use_fancy_architecture=True,
decoder_distribution='gaussian_learned_global_scalar_variance',
),
vae_trainer_kwargs=dict(
vae_lr=1e-3,
vae_visualization_config=dict(
num_recons=5,
num_samples=20,
# debug_period=50,
debug_period=20,
unnormalize_images=True,
image_format='CHW',
),
beta=1,
set_loss_weight=0,
),
data_loader_kwargs=dict(
batch_size=128,
),
vae_algo_kwargs=dict(
num_iters=501,
num_epochs_per_iter=1,
progress_csv_file_name='vae_progress.csv',
),
generate_set_for_vae_pretraining_kwargs=dict(
num_sets=3,
num_samples_per_set=128,
),
generate_set_for_rl_kwargs=dict(
num_sets=3,
num_samples_per_set=128,
# save_to_filename='3sets128samples_2objs.pickle',
saved_filename='/global/scratch/vitchyr/doodad-log-since-07-10-2020/manual-upload/sets/hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.pickle',
),
num_ungrouped_images=12800,
reward_fn_kwargs=dict(
drop_log_det_term=True,
sqrt_reward=True,
),
rig=False,
rig_goal_setter_kwargs=dict(
use_random_goal=True,
),
use_ground_truth_reward=True,
)
n_seeds = 1
mode = 'local'
exp_prefix = 'dev-{}'.format(
__file__.replace('/', '-').replace('_', '-').split('.')[0]
)
n_seeds = 3
mode = 'sss'
exp_prefix = 'exp2-oracle-pygame-latent-reward-1-obj'
search_space = {
'vae_algo_kwargs.num_iters': [501],
# 'algo_kwargs.num_epochs': [1],
'observation_key': [
'state_observation',
],
'use_ground_truth_reward': [
False,
],
'use_onehot_set_embedding': [
True,
],
'use_dummy_model': [
False,
],
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
)
variants = list(sweeper.iterate_hyperparameters())
for _ in range(n_seeds):
for exp_id, variant in enumerate(variants):
if mode == 'local':
variant['vae_algo_kwargs']['num_iters'] = 0
variant['generate_set_for_rl_kwargs']['saved_filename'] = (
'manual-upload/sets/hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.pickle'
)
variant['algo_kwargs'] = dict(
batch_size=5,
num_epochs=1,
num_eval_steps_per_epoch=2*20,
num_expl_steps_per_train_loop=2*20,
num_trains_per_train_loop=10,
min_num_steps_before_training=10,
)
variant['max_path_length'] = 2
run_experiment(
disco_experiment,
exp_name=exp_prefix,
num_exps_per_instance=2,
mode=mode,
variant=variant,
# slurm_config_name='cpu',
use_gpu=True,
# gpu_id=1,
)
| 32.137615 | 148 | 0.529403 | import rlkit.misc.hyperparameter as hyp
from multiworld.envs.pygame import PickAndPlaceEnv
from rlkit.launchers.launcher_util import run_experiment
from rlkit.torch.sets.rl_launcher import disco_experiment
if __name__ == "__main__":
variant = dict(
env_class=PickAndPlaceEnv,
env_kwargs=dict(
action_scale=1.0,
boundary_dist=4,
ball_radius=1.5,
object_radius=1.,
ball_visual_radius=1.5,
object_visual_radius=1.,
min_grab_distance=1.,
walls=None,
action_l2norm_penalty=0,
reward_type="dense",
success_threshold=0.60,
fixed_goal=None,
images_are_rgb=True,
render_dt_msec=0,
render_onscreen=False,
render_size=84,
show_goal=False,
goal_samplers=None,
goal_sampling_mode='random',
num_presampled_goals=10000,
object_reward_only=False,
init_position_strategy='random',
num_objects=1,
),
qf_kwargs=dict(
hidden_sizes=[400, 300],
),
policy_kwargs=dict(
hidden_sizes=[400, 300],
),
sac_trainer_kwargs=dict(
discount=0.99,
soft_target_tau=1e-3,
target_update_period=1,
use_automatic_entropy_tuning=True,
reward_scale='auto_normalize_by_max_magnitude',
),
max_path_length=100,
algo_kwargs=dict(
batch_size=128,
num_epochs=501,
num_eval_steps_per_epoch=3000,
num_expl_steps_per_train_loop=1000,
num_trains_per_train_loop=1000,
min_num_steps_before_training=1000,
),
replay_buffer_kwargs=dict(
fraction_future_context=0.0,
fraction_distribution_context=0.8,
max_size=int(1e6),
),
save_video=True,
save_video_kwargs=dict(
save_video_period=10,
pad_color=50,
subpad_length=1,
pad_length=1,
num_columns_per_rollout=2,
num_imgs=8,
),
renderer_kwargs=dict(
output_image_format='CHW',
),
create_vae_kwargs=dict(
latent_dim=128,
encoder_cnn_kwargs=dict(
kernel_sizes=[5, 3, 3],
n_channels=[16, 32, 64],
strides=[3, 2, 2],
paddings=[0, 0, 0],
pool_type='none',
hidden_activation='relu',
normalization_type='layer',
),
encoder_mlp_kwargs=dict(
hidden_sizes=[],
),
decoder_dcnn_kwargs=dict(
kernel_sizes=[3, 3, 6],
n_channels=[32, 16, 3],
strides=[2, 2, 3],
paddings=[0, 0, 0],
),
decoder_mlp_kwargs=dict(
hidden_sizes=[256, 256],
),
use_fancy_architecture=True,
decoder_distribution='gaussian_learned_global_scalar_variance',
),
vae_trainer_kwargs=dict(
vae_lr=1e-3,
vae_visualization_config=dict(
num_recons=5,
num_samples=20,
debug_period=20,
unnormalize_images=True,
image_format='CHW',
),
beta=1,
set_loss_weight=0,
),
data_loader_kwargs=dict(
batch_size=128,
),
vae_algo_kwargs=dict(
num_iters=501,
num_epochs_per_iter=1,
progress_csv_file_name='vae_progress.csv',
),
generate_set_for_vae_pretraining_kwargs=dict(
num_sets=3,
num_samples_per_set=128,
),
generate_set_for_rl_kwargs=dict(
num_sets=3,
num_samples_per_set=128,
saved_filename='/global/scratch/vitchyr/doodad-log-since-07-10-2020/manual-upload/sets/hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.pickle',
),
num_ungrouped_images=12800,
reward_fn_kwargs=dict(
drop_log_det_term=True,
sqrt_reward=True,
),
rig=False,
rig_goal_setter_kwargs=dict(
use_random_goal=True,
),
use_ground_truth_reward=True,
)
n_seeds = 1
mode = 'local'
exp_prefix = 'dev-{}'.format(
__file__.replace('/', '-').replace('_', '-').split('.')[0]
)
n_seeds = 3
mode = 'sss'
exp_prefix = 'exp2-oracle-pygame-latent-reward-1-obj'
search_space = {
'vae_algo_kwargs.num_iters': [501],
'observation_key': [
'state_observation',
],
'use_ground_truth_reward': [
False,
],
'use_onehot_set_embedding': [
True,
],
'use_dummy_model': [
False,
],
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
)
variants = list(sweeper.iterate_hyperparameters())
for _ in range(n_seeds):
for exp_id, variant in enumerate(variants):
if mode == 'local':
variant['vae_algo_kwargs']['num_iters'] = 0
variant['generate_set_for_rl_kwargs']['saved_filename'] = (
'manual-upload/sets/hand2xy_hand2x_1obj2xy_1obj2x_num_objs_1.pickle'
)
variant['algo_kwargs'] = dict(
batch_size=5,
num_epochs=1,
num_eval_steps_per_epoch=2*20,
num_expl_steps_per_train_loop=2*20,
num_trains_per_train_loop=10,
min_num_steps_before_training=10,
)
variant['max_path_length'] = 2
run_experiment(
disco_experiment,
exp_name=exp_prefix,
num_exps_per_instance=2,
mode=mode,
variant=variant,
use_gpu=True,
)
| true | true |
f726a1bf8f792d5b4f9b9594c9f703b8b87a1151 | 1,391 | py | Python | geniza/footnotes/migrations/0015_add_footnote_location_pp.py | kmcelwee/geniza | 0e59134e35357d4f80d85bf1e423edbc29d1edfb | [
"Apache-2.0"
] | null | null | null | geniza/footnotes/migrations/0015_add_footnote_location_pp.py | kmcelwee/geniza | 0e59134e35357d4f80d85bf1e423edbc29d1edfb | [
"Apache-2.0"
] | 5 | 2020-09-22T17:35:24.000Z | 2020-09-22T19:45:46.000Z | geniza/footnotes/migrations/0015_add_footnote_location_pp.py | kmcelwee/geniza | 0e59134e35357d4f80d85bf1e423edbc29d1edfb | [
"Apache-2.0"
] | null | null | null | # Generated by Django 3.2.6 on 2021-12-15 21:28
from django.db import migrations
from django.db.models import F, Value
from django.db.models.functions import Concat
def add_pp_to_footnote_pages(apps, schema_editor):
# for footnotes that start with with a numeric location,
# we want to add pp. to make the meaning clearer
# on the front end
Footnote = apps.get_model("footnotes", "Footnote")
# find and update footnotes to based on location contents
# first, find footnotes with purely numeric location (i.e., single page number)
# prefix with p.
Footnote.objects.filter(location__regex=r"^\d+$").update(
location=Concat(Value("p. "), F("location"))
)
# next, find footnotes that start with numeric values
# - exclude location that starts with numeric followed by a hebrew letter
# (currently only one, 49ב) — this is a document location, not a page number
# - find all other footnotes with locations that start with a number
Footnote.objects.exclude(location__regex=r"^\d+[\u0590-\u05fe]").filter(
location__regex=r"^\d"
).update(location=Concat(Value("pp. "), F("location")))
class Migration(migrations.Migration):
dependencies = [
("footnotes", "0014_alter_source_edition"),
]
operations = [
migrations.RunPython(add_pp_to_footnote_pages, migrations.RunPython.noop)
]
| 34.775 | 83 | 0.700216 |
from django.db import migrations
from django.db.models import F, Value
from django.db.models.functions import Concat
def add_pp_to_footnote_pages(apps, schema_editor):
Footnote = apps.get_model("footnotes", "Footnote")
Footnote.objects.filter(location__regex=r"^\d+$").update(
location=Concat(Value("p. "), F("location"))
)
Footnote.objects.exclude(location__regex=r"^\d+[\u0590-\u05fe]").filter(
location__regex=r"^\d"
).update(location=Concat(Value("pp. "), F("location")))
class Migration(migrations.Migration):
dependencies = [
("footnotes", "0014_alter_source_edition"),
]
operations = [
migrations.RunPython(add_pp_to_footnote_pages, migrations.RunPython.noop)
]
| true | true |
f726a26cfd9c320455025cb39ec2e30c2b3335a0 | 76,817 | py | Python | spyder/plugins/ipythonconsole/tests/test_ipythonconsole.py | dan123456-eng/spyder | e57751e01d09a35b8f0583f9efd8dce318b17b4e | [
"MIT"
] | 1 | 2022-02-23T16:50:02.000Z | 2022-02-23T16:50:02.000Z | spyder/plugins/ipythonconsole/tests/test_ipythonconsole.py | dan123456-eng/spyder | e57751e01d09a35b8f0583f9efd8dce318b17b4e | [
"MIT"
] | null | null | null | spyder/plugins/ipythonconsole/tests/test_ipythonconsole.py | dan123456-eng/spyder | e57751e01d09a35b8f0583f9efd8dce318b17b4e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""
Tests for the IPython console plugin.
"""
# Standard library imports
import codecs
import glob
import os
import os.path as osp
import psutil
import shutil
import sys
import tempfile
from textwrap import dedent
import threading
import traceback
from unittest.mock import Mock
# Third party imports
import IPython
from IPython.core import release as ipy_release
from IPython.core.application import get_ipython_dir
from flaky import flaky
from pkg_resources import parse_version
from pygments.token import Name
import pytest
from qtpy import PYQT5
from qtpy.QtCore import Qt
from qtpy.QtWebEngineWidgets import WEBENGINE
from qtpy.QtWidgets import QMessageBox, QMainWindow
import sympy
# Local imports
from spyder.config.base import get_home_dir, running_in_ci
from spyder.config.gui import get_color_scheme
from spyder.config.manager import ConfigurationManager
from spyder.py3compat import PY2, to_text_string
from spyder.plugins.help.tests.test_plugin import check_text
from spyder.plugins.help.utils.sphinxify import CSS_PATH
from spyder.plugins.ipythonconsole.plugin import IPythonConsole
from spyder.plugins.ipythonconsole.utils.style import create_style_class
from spyder.plugins.ipythonconsole.widgets import ClientWidget
from spyder.utils.programs import get_temp_dir
from spyder.utils.conda import is_conda_env
# =============================================================================
# Constants
# =============================================================================
SHELL_TIMEOUT = 20000
TEMP_DIRECTORY = tempfile.gettempdir()
NON_ASCII_DIR = osp.join(TEMP_DIRECTORY, u'測試', u'اختبار')
NEW_DIR = 'new_workingdir'
# =============================================================================
# Utillity Functions
# =============================================================================
def get_console_font_color(syntax_style):
styles = create_style_class(syntax_style).styles
font_color = styles[Name]
return font_color
def get_console_background_color(style_sheet):
background_color = style_sheet.split('background-color:')[1]
background_color = background_color.split(';')[0]
return background_color
def get_conda_test_env(test_env_name=u'spytest-ž'):
"""Return the full prefix path of the given `test_env_name`."""
if 'envs' in sys.prefix:
root_prefix = os.path.dirname(os.path.dirname(sys.prefix))
else:
root_prefix = sys.prefix
test_env_prefix = os.path.join(root_prefix, 'envs', test_env_name)
if os.name == 'nt':
test_env_executable = os.path.join(test_env_prefix, 'python.exe')
else:
test_env_executable = os.path.join(test_env_prefix, 'bin', 'python')
return test_env_executable
# =============================================================================
# Qt Test Fixtures
# =============================================================================
@pytest.fixture
def ipyconsole(qtbot, request, tmpdir):
"""IPython console fixture."""
configuration = ConfigurationManager(conf_path=str(tmpdir))
class MainWindowMock(QMainWindow):
def get_spyder_pythonpath(self):
return configuration.get('main', 'spyder_pythonpath', [])
def __getattr__(self, attr):
if attr == 'consoles_menu_actions':
return []
elif attr == 'editor':
return None
else:
return Mock()
# Tests assume inline backend
configuration.set('ipython_console', 'pylab/backend', 0)
# Start in a new working directory the console
use_startup_wdir = request.node.get_closest_marker('use_startup_wdir')
if use_startup_wdir:
new_wdir = osp.join(os.getcwd(), NEW_DIR)
if not osp.exists(new_wdir):
os.mkdir(new_wdir)
configuration.set('workingdir', 'console/use_fixed_directory', True)
configuration.set('workingdir', 'console/fixed_directory', new_wdir)
else:
configuration.set('workingdir', 'console/use_fixed_directory', False)
configuration.set(
'workingdir', 'console/fixed_directory', get_home_dir())
# Test the console with a non-ascii temp dir
non_ascii_dir = request.node.get_closest_marker('non_ascii_dir')
if non_ascii_dir:
test_dir = NON_ASCII_DIR
else:
test_dir = ''
# Instruct the console to not use a stderr file
no_stderr_file = request.node.get_closest_marker('no_stderr_file')
if no_stderr_file:
test_no_stderr = 'True'
else:
test_no_stderr = ''
# Use the automatic backend if requested
auto_backend = request.node.get_closest_marker('auto_backend')
if auto_backend:
configuration.set('ipython_console', 'pylab/backend', 1)
# Use the Tkinter backend if requested
tk_backend = request.node.get_closest_marker('tk_backend')
if tk_backend:
configuration.set('ipython_console', 'pylab/backend', 8)
# Start a Pylab client if requested
pylab_client = request.node.get_closest_marker('pylab_client')
is_pylab = True if pylab_client else False
# Start a Sympy client if requested
sympy_client = request.node.get_closest_marker('sympy_client')
is_sympy = True if sympy_client else False
# Start a Cython client if requested
cython_client = request.node.get_closest_marker('cython_client')
is_cython = True if cython_client else False
# Use an external interpreter if requested
external_interpreter = request.node.get_closest_marker(
'external_interpreter')
if external_interpreter:
configuration.set('main_interpreter', 'default', False)
configuration.set('main_interpreter', 'executable', sys.executable)
else:
configuration.set('main_interpreter', 'default', True)
configuration.set('main_interpreter', 'executable', '')
# Use the test environment interpreter if requested
test_environment_interpreter = request.node.get_closest_marker(
'test_environment_interpreter')
if test_environment_interpreter:
configuration.set('main_interpreter', 'default', False)
configuration.set(
'main_interpreter', 'executable', get_conda_test_env())
else:
configuration.set('main_interpreter', 'default', True)
configuration.set('main_interpreter', 'executable', '')
# Conf css_path in the Appeareance plugin
configuration.set('appearance', 'css_path', CSS_PATH)
# Create the console and a new client and set environment
os.environ['IPYCONSOLE_TESTING'] = 'True'
os.environ['IPYCONSOLE_TEST_DIR'] = test_dir
os.environ['IPYCONSOLE_TEST_NO_STDERR'] = test_no_stderr
window = MainWindowMock()
console = IPythonConsole(parent=window, configuration=configuration)
console._register()
console.create_new_client(is_pylab=is_pylab,
is_sympy=is_sympy,
is_cython=is_cython)
window.setCentralWidget(console.get_widget())
# Set exclamation mark to True
configuration.set('ipython_console', 'pdb_use_exclamation_mark', True)
# This segfaults on macOS
if not sys.platform == "darwin":
qtbot.addWidget(window)
window.resize(640, 480)
window.show()
# Wait until the window is fully up
shell = console.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Check for thread or open file leaks
known_leak = request.node.get_closest_marker('known_leak')
if os.name != 'nt' and not known_leak:
# _DummyThread are created if current_thread() is called from them.
# They will always leak (From python doc) so we ignore them.
init_threads = [
repr(thread) for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
proc = psutil.Process()
init_files = [repr(f) for f in proc.open_files()]
init_subprocesses = [repr(f) for f in proc.children()]
yield console
# Print shell content if failed
if request.node.rep_setup.passed:
if request.node.rep_call.failed:
# Print content of shellwidget and close window
print(console.get_current_shellwidget(
)._control.toPlainText())
client = console.get_current_client()
if client.info_page != client.blank_page:
print('info_page')
print(client.info_page)
# Close
console.on_close()
window.close()
os.environ.pop('IPYCONSOLE_TESTING')
os.environ.pop('IPYCONSOLE_TEST_DIR')
os.environ.pop('IPYCONSOLE_TEST_NO_STDERR')
if os.name == 'nt' or known_leak:
# Do not test for leaks
return
def show_diff(init_list, now_list, name):
sys.stderr.write(f"Extra {name} before test:\n")
for item in init_list:
if item in now_list:
now_list.remove(item)
else:
sys.stderr.write(item + "\n")
sys.stderr.write(f"Extra {name} after test:\n")
for item in now_list:
sys.stderr.write(item + "\n")
# The test is not allowed to open new files or threads.
try:
def threads_condition():
threads = [
thread for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
return (len(init_threads) >= len(threads))
qtbot.waitUntil(threads_condition, timeout=SHELL_TIMEOUT)
except Exception:
now_threads = [
thread for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
threads = [repr(t) for t in now_threads]
show_diff(init_threads, threads, "thread")
sys.stderr.write("Running Threads stacks:\n")
now_thread_ids = [t.ident for t in now_threads]
for threadId, frame in sys._current_frames().items():
if threadId in now_thread_ids:
sys.stderr.write("\nThread " + str(threads) + ":\n")
traceback.print_stack(frame)
raise
try:
# -1 from closed client
qtbot.waitUntil(lambda: (
len(init_subprocesses) - 1 >= len(proc.children())),
timeout=SHELL_TIMEOUT)
except Exception:
subprocesses = [repr(f) for f in proc.children()]
show_diff(init_subprocesses, subprocesses, "processes")
raise
try:
qtbot.waitUntil(
lambda: (len(init_files) >= len(proc.open_files())),
timeout=SHELL_TIMEOUT)
except Exception:
files = [repr(f) for f in proc.open_files()]
show_diff(init_files, files, "files")
raise
# =============================================================================
# Tests
# =============================================================================
@flaky(max_runs=3)
@pytest.mark.external_interpreter
def test_banners(ipyconsole, qtbot):
"""Test that console banners are generated correctly."""
shell = ipyconsole.get_current_shellwidget()
control = shell._control
# Long banner
text = control.toPlainText().splitlines()
if "Update LANGUAGE_CODES" in text[0]:
text = text[1:]
while not text[0].strip():
text = text[1:]
py_ver = sys.version.splitlines()[0].strip()
assert py_ver in text[0] # Python version in first line
assert 'license' in text[1] # 'license' mention in second line
assert '' == text[2] # Third line is empty
assert ipy_release.version in text[3] # Fourth line is IPython
# Short banner
short_banner = shell.short_banner()
py_ver = sys.version.split(' ')[0]
expected = 'Python %s -- IPython %s' % (py_ver, ipy_release.version)
assert expected == short_banner
@flaky(max_runs=3)
@pytest.mark.parametrize(
"function,signature,documentation",
[("arange",
["start", "stop"],
["Return evenly spaced values within a given interval.<br>",
"<br>Python built-in `range` function, but returns an ndarray ..."]),
("vectorize",
["pyfunc", "otype", "signature"],
["Generalized function class.<br>",
"Define a vectorized function which takes a nested sequence ..."]),
("absolute",
["x", "/", "out"],
["Parameters<br>", "x : array_like ..."])]
)
@pytest.mark.skipif(not os.name == 'nt',
reason="Times out on macOS and fails on Linux")
def test_get_calltips(ipyconsole, qtbot, function, signature, documentation):
"""Test that calltips show the documentation."""
shell = ipyconsole.get_current_shellwidget()
control = shell._control
# Import numpy
with qtbot.waitSignal(shell.executed):
shell.execute('import numpy as np')
# Write an object in the console that should generate a calltip
# and wait for the kernel to send its response.
with qtbot.waitSignal(shell.kernel_client.shell_channel.message_received):
qtbot.keyClicks(control, 'np.' + function + '(')
# Wait a little bit for the calltip to appear
qtbot.waitUntil(lambda: control.calltip_widget.isVisible())
# Assert we displayed a calltip
assert control.calltip_widget.isVisible()
# Hide the calltip to avoid focus problems on Linux
control.calltip_widget.hide()
# Check spected elements for signature and documentation
for element in signature:
assert element in control.calltip_widget.text()
for element in documentation:
assert element in control.calltip_widget.text()
@flaky(max_runs=3)
@pytest.mark.auto_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_auto_backend(ipyconsole, qtbot):
"""Test that the automatic backend was set correctly."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute("ip = get_ipython(); ip.kernel.eventloop")
# Assert there are no errors in the console and we set the right
# backend.
control = ipyconsole.get_widget().get_focus_widget()
assert 'NOTE' not in control.toPlainText()
assert 'Error' not in control.toPlainText()
assert 'loop_qt5' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.tk_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_tk_backend(ipyconsole, qtbot):
"""Test that the Tkinter backend was set correctly."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(shell.executed):
shell.execute("ip = get_ipython(); ip.kernel.eventloop")
# Assert we set the right backend in the kernel.
control = ipyconsole.get_widget().get_focus_widget()
assert 'loop_tk' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.pylab_client
def test_pylab_client(ipyconsole, qtbot):
"""Test that the Pylab console is working correctly."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# This is here to generate further errors
with qtbot.waitSignal(shell.executed):
shell.execute("e")
# Assert there are no errors in the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
# Reset the console namespace
shell.reset_namespace()
qtbot.wait(1000)
# See that `e` is still defined from numpy after reset
with qtbot.waitSignal(shell.executed):
shell.execute("e")
# Assert there are no errors after restting the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.sympy_client
@pytest.mark.xfail('1.0' < sympy.__version__ < '1.2',
reason="A bug with sympy 1.1.1 and IPython-Qtconsole")
def test_sympy_client(ipyconsole, qtbot):
"""Test that the SymPy console is working correctly."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# This is here to generate further errors
with qtbot.waitSignal(shell.executed):
shell.execute("x")
# Assert there are no errors in the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'NameError' not in control.toPlainText()
# Reset the console namespace
shell.reset_namespace()
qtbot.wait(1000)
# See that `e` is still defined from sympy after reset
with qtbot.waitSignal(shell.executed):
shell.execute("x")
# Assert there are no errors after resetting the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'NameError' not in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.cython_client
@pytest.mark.skipif(
(not sys.platform.startswith('linux') or
parse_version(ipy_release.version) == parse_version('7.11.0')),
reason="It only works reliably on Linux and fails for IPython 7.11.0")
def test_cython_client(ipyconsole, qtbot):
"""Test that the Cython console is working correctly."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# This is here to generate further errors
with qtbot.waitSignal(shell.executed, timeout=SHELL_TIMEOUT):
shell.execute("%%cython\n"
"cdef int ctest(int x, int y):\n"
" return x + y")
# Assert there are no errors in the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
# Reset the console namespace
shell.reset_namespace()
qtbot.wait(1000)
# See that cython is still enabled after reset
with qtbot.waitSignal(shell.executed, timeout=SHELL_TIMEOUT):
shell.execute("%%cython\n"
"cdef int ctest(int x, int y):\n"
" return x + y")
# Assert there are no errors after restting the console
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
@flaky(max_runs=3)
def test_tab_rename_for_slaves(ipyconsole, qtbot):
"""Test slave clients are renamed correctly."""
cf = ipyconsole.get_current_client().connection_file
ipyconsole.get_widget()._create_client_for_kernel(cf, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
# Rename slave
ipyconsole.get_widget().rename_tabs_after_change('foo')
# Assert both clients have the same name
assert 'foo' in ipyconsole.get_clients()[0].get_name()
assert 'foo' in ipyconsole.get_clients()[1].get_name()
@flaky(max_runs=3)
def test_no_repeated_tabs_name(ipyconsole, qtbot):
"""Test that tabs can't have repeated given names."""
# Rename first client
ipyconsole.get_widget().rename_tabs_after_change('foo')
# Create a new client and try to rename it
ipyconsole.create_new_client()
ipyconsole.get_widget().rename_tabs_after_change('foo')
# Assert the rename didn't take place
client_name = ipyconsole.get_current_client().get_name()
assert '2' in client_name
@flaky(max_runs=3)
@pytest.mark.skipif(
running_in_ci() and sys.platform == 'darwin',
reason="Hangs sometimes on macOS")
def test_tabs_preserve_name_after_move(ipyconsole, qtbot):
"""Test that tabs preserve their names after they are moved."""
# Create a new client
ipyconsole.create_new_client()
# Move tabs
ipyconsole.get_widget().tabwidget.tabBar().moveTab(0, 1)
# Assert the second client is in the first position
client_name = ipyconsole.get_clients()[0].get_name()
assert '2' in client_name
@flaky(max_runs=3)
def test_conf_env_vars(ipyconsole, qtbot):
"""Test that kernels have env vars set by our kernel spec."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Get a CONF env var
with qtbot.waitSignal(shell.executed):
shell.execute("import os; a = os.environ.get('SPY_SYMPY_O')")
# Assert we get the assigned value correctly
assert shell.get_value('a') == 'False'
@flaky(max_runs=3)
@pytest.mark.no_stderr_file
def test_no_stderr_file(ipyconsole, qtbot):
"""Test that consoles can run without an stderr."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Execute a simple assignment
with qtbot.waitSignal(shell.executed):
shell.execute('a = 1')
# Assert we get the assigned value correctly
assert shell.get_value('a') == 1
@pytest.mark.non_ascii_dir
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="It fails on Windows")
def test_non_ascii_stderr_file(ipyconsole, qtbot):
"""Test the creation of a console with a stderr file in a non-ascii dir."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Execute a simple assignment
with qtbot.waitSignal(shell.executed):
shell.execute('a = 1')
# Assert we get the assigned value
assert shell.get_value('a') == 1
@flaky(max_runs=3)
@pytest.mark.skipif(PY2 and sys.platform == 'darwin',
reason="It hangs frequently on Python 2.7 and macOS")
def test_console_import_namespace(ipyconsole, qtbot):
"""Test an import of the form 'from foo import *'."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Import numpy
with qtbot.waitSignal(shell.executed):
shell.execute('from numpy import *')
# Assert we get the e value correctly
assert shell.get_value('e') == 2.718281828459045
@flaky(max_runs=3)
def test_console_disambiguation(ipyconsole, qtbot):
"""Test the disambiguation of dedicated consoles."""
# Create directories and file for TEMP_DIRECTORY/a/b/c.py
# and TEMP_DIRECTORY/a/d/c.py
dir_b = osp.join(TEMP_DIRECTORY, 'a', 'b')
filename_b = osp.join(dir_b, 'c.py')
if not osp.isdir(dir_b):
os.makedirs(dir_b)
if not osp.isfile(filename_b):
file_c = open(filename_b, 'w+')
file_c.close()
dir_d = osp.join(TEMP_DIRECTORY, 'a', 'd')
filename_d = osp.join(dir_d, 'c.py')
if not osp.isdir(dir_d):
os.makedirs(dir_d)
if not osp.isfile(filename_d):
file_e = open(filename_d, 'w+')
file_e.close()
# Create new client and assert name without disambiguation
ipyconsole.create_client_for_file(filename_b)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py/A'
# Create new client and assert name with disambiguation
ipyconsole.create_client_for_file(filename_d)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py - d/A'
ipyconsole.get_widget().tabwidget.setCurrentIndex(1)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py - b/A'
@flaky(max_runs=3)
def test_console_coloring(ipyconsole, qtbot):
"""Test that console gets the same coloring present in the Editor."""
config_options = ipyconsole.get_widget().config_options()
syntax_style = config_options.JupyterWidget.syntax_style
style_sheet = config_options.JupyterWidget.style_sheet
console_font_color = get_console_font_color(syntax_style)
console_background_color = get_console_background_color(style_sheet)
selected_color_scheme = ipyconsole.get_conf(
'selected', section='appearance')
color_scheme = get_color_scheme(selected_color_scheme)
editor_background_color = color_scheme['background']
editor_font_color = color_scheme['normal'][0]
console_background_color = console_background_color.replace("'", "")
editor_background_color = editor_background_color.replace("'", "")
console_font_color = console_font_color.replace("'", "")
editor_font_color = editor_font_color.replace("'", "")
assert console_background_color.strip() == editor_background_color.strip()
assert console_font_color.strip() == editor_font_color.strip()
@flaky(max_runs=3)
def test_set_cwd(ipyconsole, qtbot, tmpdir):
"""Test kernel when changing cwd."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# spyder-ide/spyder#6451.
savetemp = shell._cwd
tempdir = to_text_string(tmpdir.mkdir("queen's"))
shell.set_cwd(tempdir)
# Get current directory.
with qtbot.waitSignal(shell.executed):
shell.execute("import os; cwd = os.getcwd()")
# Assert we get the assigned value correctly
assert shell.get_value('cwd') == tempdir
# Restore original.
shell.set_cwd(savetemp)
@flaky(max_runs=3)
def test_get_cwd(ipyconsole, qtbot, tmpdir):
"""Test current working directory."""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# spyder-ide/spyder#6451.
savetemp = shell._cwd
tempdir = to_text_string(tmpdir.mkdir("queen's"))
assert shell._cwd != tempdir
# Need to escape \ on Windows.
if os.name == 'nt':
tempdir = tempdir.replace(u"\\", u"\\\\")
# Change directory in the console.
with qtbot.waitSignal(shell.executed):
shell.execute(u"import os; os.chdir(u'''{}''')".format(tempdir))
# Ask for directory.
with qtbot.waitSignal(shell.sig_working_directory_changed):
shell.update_cwd()
if os.name == 'nt':
tempdir = tempdir.replace(u"\\\\", u"\\")
assert shell._cwd == tempdir
shell.set_cwd(savetemp)
@flaky(max_runs=3)
def test_request_env(ipyconsole, qtbot):
"""Test that getting env vars from the kernel is working as expected."""
shell = ipyconsole.get_current_shellwidget()
# Add a new entry to os.environ
with qtbot.waitSignal(shell.executed):
shell.execute("import os; os.environ['FOO'] = 'bar'" )
# Ask for os.environ contents
with qtbot.waitSignal(shell.sig_show_env) as blocker:
shell.request_env()
# Get env contents from the signal
env_contents = blocker.args[0]
# Assert that our added entry is part of os.environ
assert env_contents['FOO'] == 'bar'
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt',
reason="Fails due to differences in path handling")
def test_request_syspath(ipyconsole, qtbot, tmpdir):
"""
Test that getting sys.path contents from the kernel is working as
expected.
"""
shell = ipyconsole.get_current_shellwidget()
# Add a new entry to sys.path
with qtbot.waitSignal(shell.executed):
tmp_dir = to_text_string(tmpdir)
shell.execute("import sys; sys.path.append('%s')" % tmp_dir)
# Ask for sys.path contents
with qtbot.waitSignal(shell.sig_show_syspath) as blocker:
shell.request_syspath()
# Get sys.path contents from the signal
syspath_contents = blocker.args[0]
# Assert that our added entry is part of sys.path
assert tmp_dir in syspath_contents
@flaky(max_runs=10)
@pytest.mark.skipif(os.name == 'nt', reason="It doesn't work on Windows")
def test_save_history_dbg(ipyconsole, qtbot):
"""Test that browsing command history is working while debugging."""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Enter an expression
with qtbot.waitSignal(shell.executed):
qtbot.keyClicks(control, 'aa = 10')
qtbot.keyClick(control, Qt.Key_Enter)
# Add a pdb command to make sure it is not saved
with qtbot.waitSignal(shell.executed):
qtbot.keyClicks(control, '!u')
qtbot.keyClick(control, Qt.Key_Enter)
# Add an empty line to make sure it is not saved
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Clear console (for some reason using shell.clear_console
# doesn't work here)
shell.reset(clear=True)
qtbot.waitUntil(lambda: shell.is_waiting_pdb_input())
# Make sure we are debugging
assert shell.is_waiting_pdb_input()
# Press Up arrow button and assert we get the last
# introduced command
qtbot.keyClick(control, Qt.Key_Up)
assert 'aa = 10' in control.toPlainText()
# Open new widget
ipyconsole.create_new_client()
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Press Up arrow button and assert we get the last
# introduced command
qtbot.keyClick(control, Qt.Key_Up)
assert 'aa = 10' in control.toPlainText()
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Add a multiline statment and ckeck we can browse it correctly
shell._pdb_history.append('if True:\n print(1)')
shell._pdb_history.append('print(2)')
shell._pdb_history.append('if True:\n print(10)')
shell._pdb_history_index = len(shell._pdb_history)
# The continuation prompt is here
qtbot.keyClick(control, Qt.Key_Up)
assert '...: print(10)' in control.toPlainText()
shell._control.set_cursor_position(shell._control.get_position('eof') - 25)
qtbot.keyClick(control, Qt.Key_Up)
assert '...: print(1)' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(PY2 or IPython.version_info < (7, 17),
reason="insert is not the same in py2")
def test_dbg_input(ipyconsole, qtbot):
"""Test that spyder doesn't send pdb commands to unrelated input calls."""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Debug with input
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print('Hello', input('name'))")
# Reach the 'name' input
shell.pdb_execute('!n')
qtbot.wait(100)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'name')
# Execute some code and make sure that it doesn't work
# as this is not a pdb prompt
shell.pdb_execute('!n')
shell.pdb_execute('aa = 10')
qtbot.wait(500)
assert control.toPlainText().split()[-1] == 'name'
shell.kernel_client.input('test')
qtbot.waitUntil(lambda: 'Hello test' in control.toPlainText())
@flaky(max_runs=3)
@pytest.mark.skipif(PY2, reason="It doesn't work on PY2")
def test_unicode_vars(ipyconsole, qtbot):
"""
Test that the Variable Explorer Works with unicode variables.
"""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Set value for a Unicode variable
with qtbot.waitSignal(shell.executed):
shell.execute('д = 10')
# Assert we get its value correctly
assert shell.get_value('д') == 10
# Change its value and verify
shell.set_value('д', 20)
qtbot.waitUntil(lambda: shell.get_value('д') == 20)
assert shell.get_value('д') == 20
@flaky(max_runs=3)
def test_read_stderr(ipyconsole, qtbot):
"""
Test the read operation of the stderr file of the kernel
"""
client = ipyconsole.get_current_client()
# Set contents of the stderr file of the kernel
content = 'Test text'
stderr_file = client.stderr_obj.filename
codecs.open(stderr_file, 'w', 'cp437').write(content)
# Assert that content is correct
assert content == client.stderr_obj.get_contents()
@flaky(max_runs=10)
@pytest.mark.no_xvfb
@pytest.mark.skipif(running_in_ci() and os.name == 'nt',
reason="Times out on Windows")
def test_values_dbg(ipyconsole, qtbot):
"""
Test that getting, setting, copying and removing values is working while
debugging.
"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Get value
with qtbot.waitSignal(shell.executed):
shell.execute('aa = 10')
assert 'aa = 10' in control.toPlainText()
assert shell.get_value('aa') == 10
# Set value
shell.set_value('aa', 20)
qtbot.waitUntil(lambda: shell.get_value('aa') == 20)
assert shell.get_value('aa') == 20
# Copy value
shell.copy_value('aa', 'bb')
qtbot.waitUntil(lambda: shell.get_value('bb') == 20)
assert shell.get_value('bb') == 20
# Remove value
shell.remove_value('aa')
def is_defined(val):
try:
shell.get_value(val)
return True
except KeyError:
return False
qtbot.waitUntil(lambda: not is_defined('aa'))
with qtbot.waitSignal(shell.executed):
shell.execute('aa')
# Wait until the message is recieved
assert "*** NameError: name 'aa' is not defined" in control.toPlainText()
@flaky(max_runs=3)
def test_execute_events_dbg(ipyconsole, qtbot):
"""Test execute events while debugging"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Import Matplotlib
with qtbot.waitSignal(shell.executed):
shell.execute('import matplotlib.pyplot as plt')
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Set processing events to True
ipyconsole.set_conf('pdb_execute_events', True)
shell.set_pdb_execute_events(True)
# Test reset magic
qtbot.keyClicks(control, 'plt.plot(range(10))')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Assert that there's a plot in the console
assert shell._control.toHtml().count('img src') == 1
# Set processing events to False
ipyconsole.set_conf('pdb_execute_events', False)
shell.set_pdb_execute_events(False)
# Test reset magic
qtbot.keyClicks(control, 'plt.plot(range(10))')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Assert that there's no new plots in the console
assert shell._control.toHtml().count('img src') == 1
# Test if the plot is shown with plt.show()
qtbot.keyClicks(control, 'plt.show()')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Assert that there's a new plots in the console
assert shell._control.toHtml().count('img src') == 2
@flaky(max_runs=3)
def test_run_doctest(ipyconsole, qtbot):
"""
Test that doctests can be run without problems
"""
shell = ipyconsole.get_current_shellwidget()
code = dedent('''
def add(x, y):
"""
>>> add(1, 2)
3
>>> add(5.1, 2.2)
7.3
"""
return x + y
''')
# Run code
with qtbot.waitSignal(shell.executed):
shell.execute(code)
# Import doctest
with qtbot.waitSignal(shell.executed):
shell.execute('import doctest')
# Run doctest
with qtbot.waitSignal(shell.executed):
shell.execute('doctest.testmod()')
# Assert that doctests were run correctly
assert "TestResults(failed=0, attempted=2)" in shell._control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt' or (PY2 and PYQT5),
reason="It times out frequently")
def test_mpl_backend_change(ipyconsole, qtbot):
"""
Test that Matplotlib backend is changed correctly when
using the %matplotlib magic
"""
shell = ipyconsole.get_current_shellwidget()
# Import Matplotlib
with qtbot.waitSignal(shell.executed):
shell.execute('import matplotlib.pyplot as plt')
# Generate a plot
with qtbot.waitSignal(shell.executed):
shell.execute('plt.plot(range(10))')
# Change backends
with qtbot.waitSignal(shell.executed):
shell.execute('%matplotlib tk')
# Generate another plot
with qtbot.waitSignal(shell.executed):
shell.execute('plt.plot(range(10))')
# Assert that there's a single inline plot in the console
assert shell._control.toHtml().count('img src') == 1
@flaky(max_runs=10)
@pytest.mark.skipif(running_in_ci(), reason="Fails frequently in CI")
def test_ctrl_c_dbg(ipyconsole, qtbot):
"""
Test that Ctrl+C works while debugging
"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Test Ctrl+C
qtbot.keyClick(control, Qt.Key_C, modifier=Qt.ControlModifier)
qtbot.waitUntil(
lambda: 'For copying text while debugging, use Ctrl+Shift+C' in
control.toPlainText(), timeout=2000)
assert 'For copying text while debugging, use Ctrl+Shift+C' in control.toPlainText()
@flaky(max_runs=10)
@pytest.mark.skipif(os.name == 'nt', reason="It doesn't work on Windows")
def test_clear_and_reset_magics_dbg(ipyconsole, qtbot):
"""
Test that clear and reset magics are working while debugging
"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Test clear magic
shell.clear_console()
qtbot.waitUntil(lambda: '\nIPdb [2]: ' == control.toPlainText())
# Test reset magic
qtbot.keyClicks(control, 'bb = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert shell.get_value('bb') == 10
shell.reset_namespace()
qtbot.wait(1000)
qtbot.keyClicks(control, 'bb')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert "*** NameError: name 'bb' is not defined" in control.toPlainText()
@flaky(max_runs=3)
def test_restart_kernel(ipyconsole, mocker, qtbot):
"""
Test that kernel is restarted correctly
"""
# Mock method we want to check
mocker.patch.object(ClientWidget, "_show_mpl_backend_errors")
ipyconsole.create_new_client()
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Do an assignment to verify that it's not there after restarting
with qtbot.waitSignal(shell.executed):
shell.execute('a = 10')
# Write something to stderr to verify that it's not there after restarting
with qtbot.waitSignal(shell.executed):
shell.execute('import sys; sys.__stderr__.write("HEL"+"LO")')
qtbot.waitUntil(
lambda: 'HELLO' in shell._control.toPlainText(), timeout=SHELL_TIMEOUT)
# Restart kernel and wait until it's up again
shell._prompt_html = None
ipyconsole.restart_kernel()
qtbot.waitUntil(
lambda: shell._prompt_html is not None, timeout=SHELL_TIMEOUT)
assert 'Restarting kernel...' in shell._control.toPlainText()
assert 'HELLO' not in shell._control.toPlainText()
assert not shell.is_defined('a')
# Check that we try to show Matplotlib backend errors at the beginning and
# after the restart.
assert ClientWidget._show_mpl_backend_errors.call_count == 2
@flaky(max_runs=3)
def test_load_kernel_file_from_id(ipyconsole, qtbot):
"""
Test that a new client is created using its id
"""
client = ipyconsole.get_current_client()
connection_file = osp.basename(client.connection_file)
id_ = connection_file.split('kernel-')[-1].split('.json')[0]
ipyconsole.get_widget()._create_client_for_kernel(id_, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
new_client = ipyconsole.get_clients()[1]
assert new_client.id_ == dict(int_id='1', str_id='B')
@flaky(max_runs=3)
def test_load_kernel_file_from_location(ipyconsole, qtbot, tmpdir):
"""
Test that a new client is created using a connection file
placed in a different location from jupyter_runtime_dir
"""
client = ipyconsole.get_current_client()
fname = osp.basename(client.connection_file)
connection_file = to_text_string(tmpdir.join(fname))
shutil.copy2(client.connection_file, connection_file)
ipyconsole.get_widget()._create_client_for_kernel(connection_file, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
assert len(ipyconsole.get_clients()) == 2
@flaky(max_runs=3)
def test_load_kernel_file(ipyconsole, qtbot, tmpdir):
"""
Test that a new client is created using the connection file
of an existing client
"""
shell = ipyconsole.get_current_shellwidget()
client = ipyconsole.get_current_client()
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
new_client = ipyconsole.get_clients()[1]
new_shell = new_client.shellwidget
qtbot.waitUntil(lambda: new_shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(new_shell.executed):
new_shell.execute('a = 10')
assert new_client.id_ == dict(int_id='1', str_id='B')
assert shell.get_value('a') == new_shell.get_value('a')
@flaky(max_runs=3)
def test_sys_argv_clear(ipyconsole, qtbot):
"""Test that sys.argv is cleared up correctly"""
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute('import sys; A = sys.argv')
argv = shell.get_value("A")
assert argv == ['']
@flaky(max_runs=5)
@pytest.mark.skipif(os.name == 'nt', reason="Fails sometimes on Windows")
def test_set_elapsed_time(ipyconsole, qtbot):
"""Test that the IPython console elapsed timer is set correctly."""
client = ipyconsole.get_current_client()
# Show time label.
ipyconsole.get_widget().set_show_elapsed_time_current_client(True)
# Set time to 2 minutes ago.
client.t0 -= 120
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
ipyconsole.get_widget().set_client_elapsed_time(client)
assert ('00:02:00' in client.time_label.text() or
'00:02:01' in client.time_label.text())
# Wait for a second to pass, to ensure timer is counting up
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
pass
assert ('00:02:01' in client.time_label.text() or
'00:02:02' in client.time_label.text())
# Make previous time later than current time.
client.t0 += 2000
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
pass
assert '00:00:00' in client.time_label.text()
client.timer.timeout.disconnect(client.show_time)
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on Windows")
def test_stderr_file_is_removed_one_kernel(ipyconsole, qtbot, monkeypatch):
"""Test that consoles removes stderr when client is closed."""
client = ipyconsole.get_current_client()
# In a normal situation file should exist
monkeypatch.setattr(QMessageBox, 'question',
classmethod(lambda *args: QMessageBox.Yes))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert not osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(
not sys.platform.startswith('linux'),
reason="Doesn't work on Windows and hangs sometimes on Mac")
def test_stderr_file_is_removed_two_kernels(ipyconsole, qtbot, monkeypatch):
"""Test that console removes stderr when client and related clients
are closed."""
client = ipyconsole.get_current_client()
# New client with the same kernel
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
assert len(ipyconsole.get_widget().get_related_clients(client)) == 1
other_client = ipyconsole.get_widget().get_related_clients(client)[0]
assert client.stderr_obj.filename == other_client.stderr_obj.filename
# In a normal situation file should exist
monkeypatch.setattr(QMessageBox, 'question',
classmethod(lambda *args: QMessageBox.Yes))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert not osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on Windows")
def test_stderr_file_remains_two_kernels(ipyconsole, qtbot, monkeypatch):
"""Test that console doesn't remove stderr when a related client is not
closed."""
client = ipyconsole.get_current_client()
# New client with the same kernel
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
assert len(ipyconsole.get_widget().get_related_clients(client)) == 1
other_client = ipyconsole.get_widget().get_related_clients(client)[0]
assert client.stderr_obj.filename == other_client.stderr_obj.filename
# In a normal situation file should exist
monkeypatch.setattr(QMessageBox, "question",
classmethod(lambda *args: QMessageBox.No))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'darwin',
reason="Fails sometimes on macOS")
def test_kernel_crash(ipyconsole, qtbot):
"""Test that we show an error message when a kernel crash occurs."""
# Create an IPython kernel config file with a bad config
ipy_kernel_cfg = osp.join(get_ipython_dir(), 'profile_default',
'ipython_kernel_config.py')
with open(ipy_kernel_cfg, 'w') as f:
# This option must be a string, not an int
f.write("c.InteractiveShellApp.extra_extension = 1")
ipyconsole.create_new_client()
# Assert that the console is showing an error
qtbot.waitUntil(lambda: ipyconsole.get_clients()[-1].is_error_shown,
timeout=6000)
error_client = ipyconsole.get_clients()[-1]
assert error_client.is_error_shown
# Assert the error contains the text we expect
webview = error_client.infowidget
if WEBENGINE:
webpage = webview.page()
else:
webpage = webview.page().mainFrame()
qtbot.waitUntil(
lambda: check_text(webpage, "Bad config encountered"),
timeout=6000)
# Remove bad kernel config file
os.remove(ipy_kernel_cfg)
@flaky(max_runs=3)
@pytest.mark.skipif(not os.name == 'nt', reason="Only necessary on Windows")
def test_remove_old_std_files(ipyconsole, qtbot):
"""Test that we are removing old std files."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Create empty std files in our temp dir to see if they are removed
# correctly.
tmpdir = get_temp_dir()
open(osp.join(tmpdir, 'foo.stderr'), 'a').close()
open(osp.join(tmpdir, 'foo.stdout'), 'a').close()
# Assert that only old std files are removed
ipyconsole._remove_old_std_files()
assert not osp.isfile(osp.join(tmpdir, 'foo.stderr'))
assert not osp.isfile(osp.join(tmpdir, 'foo.stdout'))
# The current kernel std files should be present
for fname in glob.glob(osp.join(tmpdir, '*')):
assert osp.basename(fname).startswith('kernel')
assert any(
[osp.basename(fname).endswith(ext)
for ext in ('.stderr', '.stdout', '.fault')]
)
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
@pytest.mark.skipif(os.name == 'nt', reason="Too flaky on Windows")
def test_console_working_directory(ipyconsole, qtbot):
"""Test for checking the working directory."""
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute('import os; cwd = os.getcwd()')
current_wdir = shell.get_value('cwd')
folders = osp.split(current_wdir)
assert folders[-1] == NEW_DIR
@flaky(max_runs=3)
@pytest.mark.skipif(not sys.platform.startswith('linux') or PY2,
reason="It only works on Linux with python 3.")
def test_console_complete(ipyconsole, qtbot, tmpdir):
"""Test code completions in the console."""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
def check_value(name, value):
try:
return shell.get_value(name) == value
except KeyError:
return False
# test complete with one result
with qtbot.waitSignal(shell.executed):
shell.execute('cbs = 1')
qtbot.waitUntil(lambda: check_value('cbs', 1))
qtbot.wait(500)
qtbot.keyClicks(control, 'cb')
qtbot.keyClick(control, Qt.Key_Tab)
# Jedi completion takes time to start up the first time
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'cbs',
timeout=6000)
# test complete with several result
with qtbot.waitSignal(shell.executed):
shell.execute('cbba = 1')
qtbot.waitUntil(lambda: check_value('cbba', 1))
qtbot.keyClicks(control, 'cb')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(shell._completion_widget.isVisible)
# cbs is another solution, so not completed yet
assert control.toPlainText().split()[-1] == 'cb'
qtbot.keyClick(shell._completion_widget, Qt.Key_Enter)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'cbba')
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Test complete in debug mode
# check abs is completed twice (as the cursor moves)
qtbot.keyClicks(control, 'ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abs')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# A second time to check a function call doesn't cause a problem
qtbot.keyClicks(control, 'print(ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(
lambda: control.toPlainText().split()[-1] == 'print(abs')
qtbot.keyClicks(control, ')')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Enter an expression
qtbot.keyClicks(control, 'baab = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: check_value('baab', 10))
# Check baab is completed
qtbot.keyClicks(control, 'baa')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'baab')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check the completion widget is shown for abba, abs
qtbot.keyClicks(control, 'abba = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: check_value('abba', 10))
qtbot.keyClicks(control, 'ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(shell._completion_widget.isVisible)
assert control.toPlainText().split()[-1] == 'ab'
qtbot.keyClick(shell._completion_widget, Qt.Key_Enter)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abba')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Create a class
qtbot.keyClicks(control, 'class A(): baba = 1')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: shell.is_defined('A'))
qtbot.keyClicks(control, 'a = A()')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: shell.is_defined('a'))
# Check we can complete attributes
qtbot.keyClicks(control, 'a.ba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'a.baba')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can complete pdb command names
qtbot.keyClicks(control, '!longl')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == '!longlist')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can use custom complete for pdb
test_file = tmpdir.join('test.py')
test_file.write('stuff\n')
# Set a breakpoint in the new file
qtbot.keyClicks(control, '!b ' + str(test_file) + ':1')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can complete the breakpoint number
qtbot.keyClicks(control, '!ignore ')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == '1')
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
def test_pdb_multiline(ipyconsole, qtbot):
"""Test entering a multiline statment into pdb"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
assert '\nIPdb [' in control.toPlainText()
# Test reset magic
qtbot.keyClicks(control, 'if True:')
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClicks(control, 'bb = 10')
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
assert shell.get_value('bb') == 10
assert "if True:\n ...: bb = 10\n" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.parametrize(
"show_lib", [True, False])
def test_pdb_ignore_lib(ipyconsole, qtbot, show_lib):
"""Test that pdb can avoid closed files."""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Tests assume inline backend
ipyconsole.set_conf('pdb_ignore_lib', not show_lib)
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
qtbot.keyClicks(control, '!s')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClicks(control, '!q')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
if show_lib:
assert 'iostream.py' in control.toPlainText()
else:
assert 'iostream.py' not in control.toPlainText()
ipyconsole.set_conf('pdb_ignore_lib', True)
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'darwin', reason="Times out on macOS")
def test_calltip(ipyconsole, qtbot):
"""
Test Calltip.
See spyder-ide/spyder#10842
"""
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute('a = {"a": 1}')
qtbot.keyClicks(control, 'a.keys(', delay=100)
qtbot.wait(1000)
assert control.calltip_widget.isVisible()
@flaky(max_runs=3)
@pytest.mark.order(1)
@pytest.mark.test_environment_interpreter
def test_conda_env_activation(ipyconsole, qtbot):
"""
Test that the conda environment associated with an external interpreter
is activated before a kernel is created for it.
"""
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Get conda activation environment variable
with qtbot.waitSignal(shell.executed):
shell.execute(
"import os; conda_prefix = os.environ.get('CONDA_PREFIX')")
expected_output = get_conda_test_env().replace('\\', '/')
if is_conda_env(expected_output):
output = shell.get_value('conda_prefix').replace('\\', '/')
assert expected_output == output
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="no SIGTERM on Windows")
def test_kernel_kill(ipyconsole, qtbot):
"""
Test that the kernel correctly restarts after a kill.
"""
shell = ipyconsole.get_current_shellwidget()
# Wait for the restarter to start
qtbot.wait(3000)
crash_string = 'import os, signal; os.kill(os.getpid(), signal.SIGTERM)'
# Check only one comm is open
old_open_comms = list(shell.spyder_kernel_comm._comms.keys())
assert len(old_open_comms) == 1
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(crash_string)
assert crash_string in shell._control.toPlainText()
assert "Restarting kernel..." in shell._control.toPlainText()
# Check a new comm replaced the old one
new_open_comms = list(shell.spyder_kernel_comm._comms.keys())
assert len(new_open_comms) == 1
assert old_open_comms[0] != new_open_comms[0]
# Wait until the comm replies
qtbot.waitUntil(
lambda: shell.spyder_kernel_comm._comms[new_open_comms[0]][
'status'] == 'ready')
assert shell.spyder_kernel_comm._comms[new_open_comms[0]][
'status'] == 'ready'
@flaky(max_runs=3)
@pytest.mark.parametrize("spyder_pythonpath", [True, False])
def test_wrong_std_module(ipyconsole, qtbot, tmpdir, spyder_pythonpath):
"""
Test that a file with the same name of a standard library module in
the current working directory doesn't break the console.
"""
# Create an empty file called random.py in the cwd
if spyder_pythonpath:
wrong_random_mod = tmpdir.join('random.py')
wrong_random_mod.write('')
wrong_random_mod = str(wrong_random_mod)
ipyconsole.set_conf('spyder_pythonpath', [str(tmpdir)], section='main')
else:
wrong_random_mod = osp.join(os.getcwd(), 'random.py')
with open(wrong_random_mod, 'w') as f:
f.write('')
# Create a new client to see if its kernel starts despite the
# faulty module.
ipyconsole.create_new_client()
# A prompt should be created if the kernel didn't crash.
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Assert the extra path from spyder_pythonpath was added
if spyder_pythonpath:
check_sys_path = (
"import sys; path_added = r'{}' in sys.path".format(str(tmpdir))
)
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(check_sys_path)
assert shell.get_value('path_added')
# Remove wrong module
os.remove(wrong_random_mod)
# Restore CONF
ipyconsole.set_conf('spyder_pythonpath', [], section='main')
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="no SIGTERM on Windows")
def test_kernel_restart_after_manual_restart_and_crash(ipyconsole, qtbot):
"""
Test that the kernel restarts correctly after being restarted
manually and then it crashes.
This is a regresion for spyder-ide/spyder#12972.
"""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Restart kernel and wait until it's up again
shell._prompt_html = None
ipyconsole.restart_kernel()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Wait for the restarter to start
qtbot.wait(3000)
# Generate a crash
crash_string = 'import os, signal; os.kill(os.getpid(), signal.SIGTERM)'
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(crash_string)
assert crash_string in shell._control.toPlainText()
# Evaluate an expression to be sure the restart was successful
with qtbot.waitSignal(shell.executed):
shell.execute('a = 10')
assert shell.is_defined('a')
# Wait until the comm replies
open_comms = list(shell.spyder_kernel_comm._comms.keys())
qtbot.waitUntil(
lambda: shell.spyder_kernel_comm._comms[open_comms[0]][
'status'] == 'ready')
@flaky(max_runs=3)
def test_stderr_poll(ipyconsole, qtbot):
"""Test if the content of stderr is printed to the console."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
client = ipyconsole.get_current_client()
client.stderr_obj.handle.flush()
with open(client.stderr_obj.filename, 'a') as f:
f.write("test_test")
# Wait for the poll
qtbot.waitUntil(lambda: "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText())
assert "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText()
# Write a second time, makes sure it is not duplicated
client.stderr_obj.handle.flush()
with open(client.stderr_obj.filename, 'a') as f:
f.write("\ntest_test")
# Wait for the poll
qtbot.waitUntil(lambda: ipyconsole.get_widget().get_focus_widget(
).toPlainText().count("test_test") == 2)
assert ipyconsole.get_widget().get_focus_widget().toPlainText(
).count("test_test") == 2
@flaky(max_runs=3)
def test_stdout_poll(ipyconsole, qtbot):
"""Test if the content of stdout is printed to the console."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
client = ipyconsole.get_current_client()
client.stdout_obj.handle.flush()
with open(client.stdout_obj.filename, 'a') as f:
f.write("test_test")
# Wait for the poll
qtbot.waitUntil(lambda: "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText(), timeout=5000)
assert "test_test" in ipyconsole.get_widget().get_focus_widget(
).toPlainText()
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
def test_startup_code_pdb(ipyconsole, qtbot):
"""Test that startup code for pdb works."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Run a line on startup
ipyconsole.set_conf(
'startup/pdb_run_lines',
'abba = 12; print("Hello")'
)
shell.execute('%debug print()')
qtbot.waitUntil(lambda: 'Hello' in control.toPlainText())
# Verify that the line was executed
assert shell.get_value('abba') == 12
# Reset setting
ipyconsole.set_conf('startup/pdb_run_lines', '')
@flaky(max_runs=3)
@pytest.mark.parametrize(
"backend",
['inline', 'qt5', 'tk', 'osx']
)
def test_pdb_eventloop(ipyconsole, qtbot, backend):
"""Check if setting an event loop while debugging works."""
# Skip failing tests
if backend == 'tk' and os.name == 'nt':
return
if backend == 'osx' and sys.platform != "darwin":
return
if backend == 'qt5' and not os.name == "nt" and running_in_ci():
return
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%matplotlib " + backend)
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
with qtbot.waitSignal(shell.executed):
shell.execute("print('Two: ' + str(1+1))")
assert "Two: 2" in control.toPlainText()
@flaky(max_runs=3)
def test_recursive_pdb(ipyconsole, qtbot):
"""Check commands and code are separted."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("abab = 10")
# Check that we can't use magic twice
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("%debug print()")
assert "Please don't use '%debug'" in control.toPlainText()
# Check we can enter the recursive debugger twice
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!debug print()")
assert "(IPdb [1]):" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!debug print()")
assert "((IPdb [1])):" in control.toPlainText()
# quit one layer
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
assert control.toPlainText().split()[-2:] == ["(IPdb", "[2]):"]
# Check completion works
qtbot.keyClicks(control, 'aba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abab',
timeout=SHELL_TIMEOUT)
# quit one layer
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
assert control.toPlainText().split()[-2:] == ["IPdb", "[4]:"]
# Check completion works
qtbot.keyClicks(control, 'aba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abab',
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
with qtbot.waitSignal(shell.executed):
shell.execute("1 + 1")
assert control.toPlainText().split()[-2:] == ["In", "[3]:"]
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on windows")
def test_stop_pdb(ipyconsole, qtbot):
"""Test if we can stop pdb"""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
stop_button = ipyconsole.get_widget().stop_button
# Enter pdb
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
# Start and interrupt a long execution
shell.execute("import time; time.sleep(10)")
qtbot.wait(500)
with qtbot.waitSignal(shell.executed, timeout=1000):
qtbot.mouseClick(stop_button, Qt.LeftButton)
assert "KeyboardInterrupt" in control.toPlainText()
# We are still in the debugger
assert "IPdb [2]:" in control.toPlainText()
assert "In [2]:" not in control.toPlainText()
# Leave the debugger
with qtbot.waitSignal(shell.executed):
qtbot.mouseClick(stop_button, Qt.LeftButton)
assert "In [2]:" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'nt', reason="Times out on Windows")
def test_code_cache(ipyconsole, qtbot):
"""
Test that code sent to execute is properly cached
and that the cache is empited on interrupt.
"""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
def check_value(name, value):
try:
return shell.get_value(name) == value
except KeyError:
return False
# Send two execute requests and make sure the second one is executed
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 142')
qtbot.wait(500)
qtbot.waitUntil(lambda: check_value('var', 142))
assert shell.get_value('var') == 142
# Send two execute requests and cancel the second one
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 1000')
shell.interrupt_kernel()
qtbot.wait(1000)
# Make sure the value of var didn't change
assert shell.get_value('var') == 142
# Same for debugging
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
assert 'IPdb [' in shell._control.toPlainText()
# Send two execute requests and make sure the second one is executed
shell.execute('time.sleep(.5)')
shell.execute('var = 318')
qtbot.wait(500)
qtbot.waitUntil(lambda: check_value('var', 318))
assert shell.get_value('var') == 318
# Send two execute requests and cancel the second one
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 1000')
shell.interrupt_kernel()
qtbot.wait(1000)
# Make sure the value of var didn't change
assert shell.get_value('var') == 318
@flaky(max_runs=3)
@pytest.mark.skipif(PY2, reason="Doesn't work on Python 2.7")
def test_pdb_code_and_cmd_separation(ipyconsole, qtbot):
"""Check commands and code are separted."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
assert "Error" not in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("e")
assert "name 'e' is not defined" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("!n")
assert "--Return--" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("a")
assert ("*** NameError: name 'a' is not defined"
not in control.toPlainText())
with qtbot.waitSignal(shell.executed):
shell.execute("abba")
assert "name 'abba' is not defined" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("!abba")
assert "Unknown command 'abba'" in control.toPlainText()
@flaky(max_runs=3)
def test_breakpoint_builtin(ipyconsole, qtbot, tmpdir):
"""Check that the breakpoint builtin is working."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
# Code to run
code = dedent("""
print('foo')
breakpoint()
""")
# Write code to file on disk
file = tmpdir.join('test_breakpoint.py')
file.write(code)
# Run file
with qtbot.waitSignal(shell.executed):
shell.execute(f"runfile(filename=r'{str(file)}')")
# Assert we entered debugging after the print statement
qtbot.wait(5000)
assert 'foo' in control.toPlainText()
assert 'IPdb [1]:' in control.toPlainText()
def test_pdb_out(ipyconsole, qtbot):
"""Test that browsing command history is working while debugging."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Generate some output
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 12 + 1; a')
assert "[1]: 13" in control.toPlainText()
# Generate hide output
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 14 + 1; a;')
assert "[2]: 15" not in control.toPlainText()
# Multiline
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 16 + 1\na')
assert "[3]: 17" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 18 + 1\na;')
assert "[4]: 19" not in control.toPlainText()
assert "IPdb [4]:" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.auto_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_shutdown_kernel(ipyconsole, qtbot):
"""
Check that the kernel is shutdown after creating plots with the
automatic backend.
This is a regression test for issue spyder-ide/spyder#17011
"""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Create a Matplotlib plot
with qtbot.waitSignal(shell.executed):
shell.execute("import matplotlib.pyplot as plt; plt.plot(range(10))")
# Get kernel pid
with qtbot.waitSignal(shell.executed):
shell.execute("import os; pid = os.getpid()")
kernel_pid = shell.get_value('pid')
# Close current tab
ipyconsole.get_widget().close_client()
# Wait until new client is created and previous kernel is shutdown
qtbot.wait(5000)
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Detect if previous kernel was killed
with qtbot.waitSignal(shell.executed):
shell.execute(
f"import psutil; kernel_exists = psutil.pid_exists({kernel_pid})"
)
assert not shell.get_value('kernel_exists')
def test_pdb_comprehension_namespace(ipyconsole, qtbot, tmpdir):
"""Check that the debugger handles the namespace of a comprehension."""
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
# Code to run
code = "locals = 1\nx = [locals + i for i in range(2)]"
# Write code to file on disk
file = tmpdir.join('test_breakpoint.py')
file.write(code)
# Run file
with qtbot.waitSignal(shell.executed):
shell.execute(f"debugfile(filename=r'{str(file)}')")
# steps 4 times
for i in range(4):
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("s")
assert "Error" not in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("print('test', locals + i + 10)")
assert "Error" not in control.toPlainText()
assert "test 11" in control.toPlainText()
settings = {
'check_all': False,
'exclude_callables_and_modules': True,
'exclude_capitalized': False,
'exclude_private': True,
'exclude_unsupported': False,
'exclude_uppercase': True,
'excluded_names': [],
'minmax': False,
'show_callable_attributes': True,
'show_special_attributes': False}
shell.call_kernel(
interrupt=True
).set_namespace_view_settings(settings)
namespace = shell.call_kernel(blocking=True).get_namespace_view()
for key in namespace:
assert "_spyderpdb" not in key
if __name__ == "__main__":
pytest.main()
| 34.743103 | 88 | 0.676777 |
import codecs
import glob
import os
import os.path as osp
import psutil
import shutil
import sys
import tempfile
from textwrap import dedent
import threading
import traceback
from unittest.mock import Mock
import IPython
from IPython.core import release as ipy_release
from IPython.core.application import get_ipython_dir
from flaky import flaky
from pkg_resources import parse_version
from pygments.token import Name
import pytest
from qtpy import PYQT5
from qtpy.QtCore import Qt
from qtpy.QtWebEngineWidgets import WEBENGINE
from qtpy.QtWidgets import QMessageBox, QMainWindow
import sympy
from spyder.config.base import get_home_dir, running_in_ci
from spyder.config.gui import get_color_scheme
from spyder.config.manager import ConfigurationManager
from spyder.py3compat import PY2, to_text_string
from spyder.plugins.help.tests.test_plugin import check_text
from spyder.plugins.help.utils.sphinxify import CSS_PATH
from spyder.plugins.ipythonconsole.plugin import IPythonConsole
from spyder.plugins.ipythonconsole.utils.style import create_style_class
from spyder.plugins.ipythonconsole.widgets import ClientWidget
from spyder.utils.programs import get_temp_dir
from spyder.utils.conda import is_conda_env
SHELL_TIMEOUT = 20000
TEMP_DIRECTORY = tempfile.gettempdir()
NON_ASCII_DIR = osp.join(TEMP_DIRECTORY, u'測試', u'اختبار')
NEW_DIR = 'new_workingdir'
def get_console_font_color(syntax_style):
styles = create_style_class(syntax_style).styles
font_color = styles[Name]
return font_color
def get_console_background_color(style_sheet):
background_color = style_sheet.split('background-color:')[1]
background_color = background_color.split(';')[0]
return background_color
def get_conda_test_env(test_env_name=u'spytest-ž'):
if 'envs' in sys.prefix:
root_prefix = os.path.dirname(os.path.dirname(sys.prefix))
else:
root_prefix = sys.prefix
test_env_prefix = os.path.join(root_prefix, 'envs', test_env_name)
if os.name == 'nt':
test_env_executable = os.path.join(test_env_prefix, 'python.exe')
else:
test_env_executable = os.path.join(test_env_prefix, 'bin', 'python')
return test_env_executable
@pytest.fixture
def ipyconsole(qtbot, request, tmpdir):
configuration = ConfigurationManager(conf_path=str(tmpdir))
class MainWindowMock(QMainWindow):
def get_spyder_pythonpath(self):
return configuration.get('main', 'spyder_pythonpath', [])
def __getattr__(self, attr):
if attr == 'consoles_menu_actions':
return []
elif attr == 'editor':
return None
else:
return Mock()
configuration.set('ipython_console', 'pylab/backend', 0)
use_startup_wdir = request.node.get_closest_marker('use_startup_wdir')
if use_startup_wdir:
new_wdir = osp.join(os.getcwd(), NEW_DIR)
if not osp.exists(new_wdir):
os.mkdir(new_wdir)
configuration.set('workingdir', 'console/use_fixed_directory', True)
configuration.set('workingdir', 'console/fixed_directory', new_wdir)
else:
configuration.set('workingdir', 'console/use_fixed_directory', False)
configuration.set(
'workingdir', 'console/fixed_directory', get_home_dir())
non_ascii_dir = request.node.get_closest_marker('non_ascii_dir')
if non_ascii_dir:
test_dir = NON_ASCII_DIR
else:
test_dir = ''
no_stderr_file = request.node.get_closest_marker('no_stderr_file')
if no_stderr_file:
test_no_stderr = 'True'
else:
test_no_stderr = ''
auto_backend = request.node.get_closest_marker('auto_backend')
if auto_backend:
configuration.set('ipython_console', 'pylab/backend', 1)
tk_backend = request.node.get_closest_marker('tk_backend')
if tk_backend:
configuration.set('ipython_console', 'pylab/backend', 8)
pylab_client = request.node.get_closest_marker('pylab_client')
is_pylab = True if pylab_client else False
sympy_client = request.node.get_closest_marker('sympy_client')
is_sympy = True if sympy_client else False
cython_client = request.node.get_closest_marker('cython_client')
is_cython = True if cython_client else False
external_interpreter = request.node.get_closest_marker(
'external_interpreter')
if external_interpreter:
configuration.set('main_interpreter', 'default', False)
configuration.set('main_interpreter', 'executable', sys.executable)
else:
configuration.set('main_interpreter', 'default', True)
configuration.set('main_interpreter', 'executable', '')
test_environment_interpreter = request.node.get_closest_marker(
'test_environment_interpreter')
if test_environment_interpreter:
configuration.set('main_interpreter', 'default', False)
configuration.set(
'main_interpreter', 'executable', get_conda_test_env())
else:
configuration.set('main_interpreter', 'default', True)
configuration.set('main_interpreter', 'executable', '')
configuration.set('appearance', 'css_path', CSS_PATH)
os.environ['IPYCONSOLE_TESTING'] = 'True'
os.environ['IPYCONSOLE_TEST_DIR'] = test_dir
os.environ['IPYCONSOLE_TEST_NO_STDERR'] = test_no_stderr
window = MainWindowMock()
console = IPythonConsole(parent=window, configuration=configuration)
console._register()
console.create_new_client(is_pylab=is_pylab,
is_sympy=is_sympy,
is_cython=is_cython)
window.setCentralWidget(console.get_widget())
configuration.set('ipython_console', 'pdb_use_exclamation_mark', True)
if not sys.platform == "darwin":
qtbot.addWidget(window)
window.resize(640, 480)
window.show()
shell = console.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
known_leak = request.node.get_closest_marker('known_leak')
if os.name != 'nt' and not known_leak:
init_threads = [
repr(thread) for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
proc = psutil.Process()
init_files = [repr(f) for f in proc.open_files()]
init_subprocesses = [repr(f) for f in proc.children()]
yield console
if request.node.rep_setup.passed:
if request.node.rep_call.failed:
print(console.get_current_shellwidget(
)._control.toPlainText())
client = console.get_current_client()
if client.info_page != client.blank_page:
print('info_page')
print(client.info_page)
console.on_close()
window.close()
os.environ.pop('IPYCONSOLE_TESTING')
os.environ.pop('IPYCONSOLE_TEST_DIR')
os.environ.pop('IPYCONSOLE_TEST_NO_STDERR')
if os.name == 'nt' or known_leak:
return
def show_diff(init_list, now_list, name):
sys.stderr.write(f"Extra {name} before test:\n")
for item in init_list:
if item in now_list:
now_list.remove(item)
else:
sys.stderr.write(item + "\n")
sys.stderr.write(f"Extra {name} after test:\n")
for item in now_list:
sys.stderr.write(item + "\n")
try:
def threads_condition():
threads = [
thread for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
return (len(init_threads) >= len(threads))
qtbot.waitUntil(threads_condition, timeout=SHELL_TIMEOUT)
except Exception:
now_threads = [
thread for thread in threading.enumerate()
if not isinstance(thread, threading._DummyThread)]
threads = [repr(t) for t in now_threads]
show_diff(init_threads, threads, "thread")
sys.stderr.write("Running Threads stacks:\n")
now_thread_ids = [t.ident for t in now_threads]
for threadId, frame in sys._current_frames().items():
if threadId in now_thread_ids:
sys.stderr.write("\nThread " + str(threads) + ":\n")
traceback.print_stack(frame)
raise
try:
qtbot.waitUntil(lambda: (
len(init_subprocesses) - 1 >= len(proc.children())),
timeout=SHELL_TIMEOUT)
except Exception:
subprocesses = [repr(f) for f in proc.children()]
show_diff(init_subprocesses, subprocesses, "processes")
raise
try:
qtbot.waitUntil(
lambda: (len(init_files) >= len(proc.open_files())),
timeout=SHELL_TIMEOUT)
except Exception:
files = [repr(f) for f in proc.open_files()]
show_diff(init_files, files, "files")
raise
@flaky(max_runs=3)
@pytest.mark.external_interpreter
def test_banners(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
control = shell._control
text = control.toPlainText().splitlines()
if "Update LANGUAGE_CODES" in text[0]:
text = text[1:]
while not text[0].strip():
text = text[1:]
py_ver = sys.version.splitlines()[0].strip()
assert py_ver in text[0]
assert 'license' in text[1]
assert '' == text[2]
assert ipy_release.version in text[3]
short_banner = shell.short_banner()
py_ver = sys.version.split(' ')[0]
expected = 'Python %s -- IPython %s' % (py_ver, ipy_release.version)
assert expected == short_banner
@flaky(max_runs=3)
@pytest.mark.parametrize(
"function,signature,documentation",
[("arange",
["start", "stop"],
["Return evenly spaced values within a given interval.<br>",
"<br>Python built-in `range` function, but returns an ndarray ..."]),
("vectorize",
["pyfunc", "otype", "signature"],
["Generalized function class.<br>",
"Define a vectorized function which takes a nested sequence ..."]),
("absolute",
["x", "/", "out"],
["Parameters<br>", "x : array_like ..."])]
)
@pytest.mark.skipif(not os.name == 'nt',
reason="Times out on macOS and fails on Linux")
def test_get_calltips(ipyconsole, qtbot, function, signature, documentation):
shell = ipyconsole.get_current_shellwidget()
control = shell._control
with qtbot.waitSignal(shell.executed):
shell.execute('import numpy as np')
with qtbot.waitSignal(shell.kernel_client.shell_channel.message_received):
qtbot.keyClicks(control, 'np.' + function + '(')
qtbot.waitUntil(lambda: control.calltip_widget.isVisible())
assert control.calltip_widget.isVisible()
control.calltip_widget.hide()
for element in signature:
assert element in control.calltip_widget.text()
for element in documentation:
assert element in control.calltip_widget.text()
@flaky(max_runs=3)
@pytest.mark.auto_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_auto_backend(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute("ip = get_ipython(); ip.kernel.eventloop")
control = ipyconsole.get_widget().get_focus_widget()
assert 'NOTE' not in control.toPlainText()
assert 'Error' not in control.toPlainText()
assert 'loop_qt5' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.tk_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_tk_backend(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(shell.executed):
shell.execute("ip = get_ipython(); ip.kernel.eventloop")
control = ipyconsole.get_widget().get_focus_widget()
assert 'loop_tk' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.pylab_client
def test_pylab_client(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute("e")
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
shell.reset_namespace()
qtbot.wait(1000)
with qtbot.waitSignal(shell.executed):
shell.execute("e")
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.sympy_client
@pytest.mark.xfail('1.0' < sympy.__version__ < '1.2',
reason="A bug with sympy 1.1.1 and IPython-Qtconsole")
def test_sympy_client(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute("x")
control = ipyconsole.get_widget().get_focus_widget()
assert 'NameError' not in control.toPlainText()
shell.reset_namespace()
qtbot.wait(1000)
with qtbot.waitSignal(shell.executed):
shell.execute("x")
control = ipyconsole.get_widget().get_focus_widget()
assert 'NameError' not in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.cython_client
@pytest.mark.skipif(
(not sys.platform.startswith('linux') or
parse_version(ipy_release.version) == parse_version('7.11.0')),
reason="It only works reliably on Linux and fails for IPython 7.11.0")
def test_cython_client(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed, timeout=SHELL_TIMEOUT):
shell.execute("%%cython\n"
"cdef int ctest(int x, int y):\n"
" return x + y")
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
shell.reset_namespace()
qtbot.wait(1000)
with qtbot.waitSignal(shell.executed, timeout=SHELL_TIMEOUT):
shell.execute("%%cython\n"
"cdef int ctest(int x, int y):\n"
" return x + y")
control = ipyconsole.get_widget().get_focus_widget()
assert 'Error' not in control.toPlainText()
@flaky(max_runs=3)
def test_tab_rename_for_slaves(ipyconsole, qtbot):
cf = ipyconsole.get_current_client().connection_file
ipyconsole.get_widget()._create_client_for_kernel(cf, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
ipyconsole.get_widget().rename_tabs_after_change('foo')
assert 'foo' in ipyconsole.get_clients()[0].get_name()
assert 'foo' in ipyconsole.get_clients()[1].get_name()
@flaky(max_runs=3)
def test_no_repeated_tabs_name(ipyconsole, qtbot):
ipyconsole.get_widget().rename_tabs_after_change('foo')
ipyconsole.create_new_client()
ipyconsole.get_widget().rename_tabs_after_change('foo')
client_name = ipyconsole.get_current_client().get_name()
assert '2' in client_name
@flaky(max_runs=3)
@pytest.mark.skipif(
running_in_ci() and sys.platform == 'darwin',
reason="Hangs sometimes on macOS")
def test_tabs_preserve_name_after_move(ipyconsole, qtbot):
# Create a new client
ipyconsole.create_new_client()
# Move tabs
ipyconsole.get_widget().tabwidget.tabBar().moveTab(0, 1)
# Assert the second client is in the first position
client_name = ipyconsole.get_clients()[0].get_name()
assert '2' in client_name
@flaky(max_runs=3)
def test_conf_env_vars(ipyconsole, qtbot):
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Get a CONF env var
with qtbot.waitSignal(shell.executed):
shell.execute("import os; a = os.environ.get('SPY_SYMPY_O')")
# Assert we get the assigned value correctly
assert shell.get_value('a') == 'False'
@flaky(max_runs=3)
@pytest.mark.no_stderr_file
def test_no_stderr_file(ipyconsole, qtbot):
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Execute a simple assignment
with qtbot.waitSignal(shell.executed):
shell.execute('a = 1')
# Assert we get the assigned value correctly
assert shell.get_value('a') == 1
@pytest.mark.non_ascii_dir
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="It fails on Windows")
def test_non_ascii_stderr_file(ipyconsole, qtbot):
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Execute a simple assignment
with qtbot.waitSignal(shell.executed):
shell.execute('a = 1')
# Assert we get the assigned value
assert shell.get_value('a') == 1
@flaky(max_runs=3)
@pytest.mark.skipif(PY2 and sys.platform == 'darwin',
reason="It hangs frequently on Python 2.7 and macOS")
def test_console_import_namespace(ipyconsole, qtbot):
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# Import numpy
with qtbot.waitSignal(shell.executed):
shell.execute('from numpy import *')
# Assert we get the e value correctly
assert shell.get_value('e') == 2.718281828459045
@flaky(max_runs=3)
def test_console_disambiguation(ipyconsole, qtbot):
# Create directories and file for TEMP_DIRECTORY/a/b/c.py
# and TEMP_DIRECTORY/a/d/c.py
dir_b = osp.join(TEMP_DIRECTORY, 'a', 'b')
filename_b = osp.join(dir_b, 'c.py')
if not osp.isdir(dir_b):
os.makedirs(dir_b)
if not osp.isfile(filename_b):
file_c = open(filename_b, 'w+')
file_c.close()
dir_d = osp.join(TEMP_DIRECTORY, 'a', 'd')
filename_d = osp.join(dir_d, 'c.py')
if not osp.isdir(dir_d):
os.makedirs(dir_d)
if not osp.isfile(filename_d):
file_e = open(filename_d, 'w+')
file_e.close()
# Create new client and assert name without disambiguation
ipyconsole.create_client_for_file(filename_b)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py/A'
# Create new client and assert name with disambiguation
ipyconsole.create_client_for_file(filename_d)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py - d/A'
ipyconsole.get_widget().tabwidget.setCurrentIndex(1)
client = ipyconsole.get_current_client()
assert client.get_name() == 'c.py - b/A'
@flaky(max_runs=3)
def test_console_coloring(ipyconsole, qtbot):
config_options = ipyconsole.get_widget().config_options()
syntax_style = config_options.JupyterWidget.syntax_style
style_sheet = config_options.JupyterWidget.style_sheet
console_font_color = get_console_font_color(syntax_style)
console_background_color = get_console_background_color(style_sheet)
selected_color_scheme = ipyconsole.get_conf(
'selected', section='appearance')
color_scheme = get_color_scheme(selected_color_scheme)
editor_background_color = color_scheme['background']
editor_font_color = color_scheme['normal'][0]
console_background_color = console_background_color.replace("'", "")
editor_background_color = editor_background_color.replace("'", "")
console_font_color = console_font_color.replace("'", "")
editor_font_color = editor_font_color.replace("'", "")
assert console_background_color.strip() == editor_background_color.strip()
assert console_font_color.strip() == editor_font_color.strip()
@flaky(max_runs=3)
def test_set_cwd(ipyconsole, qtbot, tmpdir):
# Wait until the window is fully up
shell = ipyconsole.get_current_shellwidget()
# spyder-ide/spyder#6451.
savetemp = shell._cwd
tempdir = to_text_string(tmpdir.mkdir("queen's"))
shell.set_cwd(tempdir)
with qtbot.waitSignal(shell.executed):
shell.execute("import os; cwd = os.getcwd()")
assert shell.get_value('cwd') == tempdir
shell.set_cwd(savetemp)
@flaky(max_runs=3)
def test_get_cwd(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
avetemp = shell._cwd
tempdir = to_text_string(tmpdir.mkdir("queen's"))
assert shell._cwd != tempdir
# Need to escape \ on Windows.
if os.name == 'nt':
tempdir = tempdir.replace(u"\\", u"\\\\")
# Change directory in the console.
with qtbot.waitSignal(shell.executed):
shell.execute(u"import os; os.chdir(u'''{}''')".format(tempdir))
# Ask for directory.
with qtbot.waitSignal(shell.sig_working_directory_changed):
shell.update_cwd()
if os.name == 'nt':
tempdir = tempdir.replace(u"\\\\", u"\\")
assert shell._cwd == tempdir
shell.set_cwd(savetemp)
@flaky(max_runs=3)
def test_request_env(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Add a new entry to os.environ
with qtbot.waitSignal(shell.executed):
shell.execute("import os; os.environ['FOO'] = 'bar'" )
# Ask for os.environ contents
with qtbot.waitSignal(shell.sig_show_env) as blocker:
shell.request_env()
# Get env contents from the signal
env_contents = blocker.args[0]
# Assert that our added entry is part of os.environ
assert env_contents['FOO'] == 'bar'
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt',
reason="Fails due to differences in path handling")
def test_request_syspath(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
# Add a new entry to sys.path
with qtbot.waitSignal(shell.executed):
tmp_dir = to_text_string(tmpdir)
shell.execute("import sys; sys.path.append('%s')" % tmp_dir)
# Ask for sys.path contents
with qtbot.waitSignal(shell.sig_show_syspath) as blocker:
shell.request_syspath()
# Get sys.path contents from the signal
syspath_contents = blocker.args[0]
# Assert that our added entry is part of sys.path
assert tmp_dir in syspath_contents
@flaky(max_runs=10)
@pytest.mark.skipif(os.name == 'nt', reason="It doesn't work on Windows")
def test_save_history_dbg(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Enter an expression
with qtbot.waitSignal(shell.executed):
qtbot.keyClicks(control, 'aa = 10')
qtbot.keyClick(control, Qt.Key_Enter)
# Add a pdb command to make sure it is not saved
with qtbot.waitSignal(shell.executed):
qtbot.keyClicks(control, '!u')
qtbot.keyClick(control, Qt.Key_Enter)
# Add an empty line to make sure it is not saved
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Clear console (for some reason using shell.clear_console
# doesn't work here)
shell.reset(clear=True)
qtbot.waitUntil(lambda: shell.is_waiting_pdb_input())
assert shell.is_waiting_pdb_input()
qtbot.keyClick(control, Qt.Key_Up)
assert 'aa = 10' in control.toPlainText()
ipyconsole.create_new_client()
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Press Up arrow button and assert we get the last
# introduced command
qtbot.keyClick(control, Qt.Key_Up)
assert 'aa = 10' in control.toPlainText()
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Add a multiline statment and ckeck we can browse it correctly
shell._pdb_history.append('if True:\n print(1)')
shell._pdb_history.append('print(2)')
shell._pdb_history.append('if True:\n print(10)')
shell._pdb_history_index = len(shell._pdb_history)
# The continuation prompt is here
qtbot.keyClick(control, Qt.Key_Up)
assert '...: print(10)' in control.toPlainText()
shell._control.set_cursor_position(shell._control.get_position('eof') - 25)
qtbot.keyClick(control, Qt.Key_Up)
assert '...: print(1)' in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(PY2 or IPython.version_info < (7, 17),
reason="insert is not the same in py2")
def test_dbg_input(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print('Hello', input('name'))")
shell.pdb_execute('!n')
qtbot.wait(100)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'name')
# as this is not a pdb prompt
shell.pdb_execute('!n')
shell.pdb_execute('aa = 10')
qtbot.wait(500)
assert control.toPlainText().split()[-1] == 'name'
shell.kernel_client.input('test')
qtbot.waitUntil(lambda: 'Hello test' in control.toPlainText())
@flaky(max_runs=3)
@pytest.mark.skipif(PY2, reason="It doesn't work on PY2")
def test_unicode_vars(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute('д = 10')
assert shell.get_value('д') == 10
shell.set_value('д', 20)
qtbot.waitUntil(lambda: shell.get_value('д') == 20)
assert shell.get_value('д') == 20
@flaky(max_runs=3)
def test_read_stderr(ipyconsole, qtbot):
client = ipyconsole.get_current_client()
content = 'Test text'
stderr_file = client.stderr_obj.filename
codecs.open(stderr_file, 'w', 'cp437').write(content)
assert content == client.stderr_obj.get_contents()
@flaky(max_runs=10)
@pytest.mark.no_xvfb
@pytest.mark.skipif(running_in_ci() and os.name == 'nt',
reason="Times out on Windows")
def test_values_dbg(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Get value
with qtbot.waitSignal(shell.executed):
shell.execute('aa = 10')
assert 'aa = 10' in control.toPlainText()
assert shell.get_value('aa') == 10
# Set value
shell.set_value('aa', 20)
qtbot.waitUntil(lambda: shell.get_value('aa') == 20)
assert shell.get_value('aa') == 20
# Copy value
shell.copy_value('aa', 'bb')
qtbot.waitUntil(lambda: shell.get_value('bb') == 20)
assert shell.get_value('bb') == 20
# Remove value
shell.remove_value('aa')
def is_defined(val):
try:
shell.get_value(val)
return True
except KeyError:
return False
qtbot.waitUntil(lambda: not is_defined('aa'))
with qtbot.waitSignal(shell.executed):
shell.execute('aa')
# Wait until the message is recieved
assert "*** NameError: name 'aa' is not defined" in control.toPlainText()
@flaky(max_runs=3)
def test_execute_events_dbg(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute('import matplotlib.pyplot as plt')
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
ipyconsole.set_conf('pdb_execute_events', True)
shell.set_pdb_execute_events(True)
qtbot.keyClicks(control, 'plt.plot(range(10))')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert shell._control.toHtml().count('img src') == 1
# Set processing events to False
ipyconsole.set_conf('pdb_execute_events', False)
shell.set_pdb_execute_events(False)
# Test reset magic
qtbot.keyClicks(control, 'plt.plot(range(10))')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Assert that there's no new plots in the console
assert shell._control.toHtml().count('img src') == 1
qtbot.keyClicks(control, 'plt.show()')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert shell._control.toHtml().count('img src') == 2
@flaky(max_runs=3)
def test_run_doctest(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
code = dedent('''
def add(x, y):
"""
>>> add(1, 2)
3
>>> add(5.1, 2.2)
7.3
"""
return x + y
''')
# Run code
with qtbot.waitSignal(shell.executed):
shell.execute(code)
# Import doctest
with qtbot.waitSignal(shell.executed):
shell.execute('import doctest')
# Run doctest
with qtbot.waitSignal(shell.executed):
shell.execute('doctest.testmod()')
# Assert that doctests were run correctly
assert "TestResults(failed=0, attempted=2)" in shell._control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt' or (PY2 and PYQT5),
reason="It times out frequently")
def test_mpl_backend_change(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Import Matplotlib
with qtbot.waitSignal(shell.executed):
shell.execute('import matplotlib.pyplot as plt')
# Generate a plot
with qtbot.waitSignal(shell.executed):
shell.execute('plt.plot(range(10))')
# Change backends
with qtbot.waitSignal(shell.executed):
shell.execute('%matplotlib tk')
# Generate another plot
with qtbot.waitSignal(shell.executed):
shell.execute('plt.plot(range(10))')
# Assert that there's a single inline plot in the console
assert shell._control.toHtml().count('img src') == 1
@flaky(max_runs=10)
@pytest.mark.skipif(running_in_ci(), reason="Fails frequently in CI")
def test_ctrl_c_dbg(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Test Ctrl+C
qtbot.keyClick(control, Qt.Key_C, modifier=Qt.ControlModifier)
qtbot.waitUntil(
lambda: 'For copying text while debugging, use Ctrl+Shift+C' in
control.toPlainText(), timeout=2000)
assert 'For copying text while debugging, use Ctrl+Shift+C' in control.toPlainText()
@flaky(max_runs=10)
@pytest.mark.skipif(os.name == 'nt', reason="It doesn't work on Windows")
def test_clear_and_reset_magics_dbg(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Test clear magic
shell.clear_console()
qtbot.waitUntil(lambda: '\nIPdb [2]: ' == control.toPlainText())
# Test reset magic
qtbot.keyClicks(control, 'bb = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert shell.get_value('bb') == 10
shell.reset_namespace()
qtbot.wait(1000)
qtbot.keyClicks(control, 'bb')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
assert "*** NameError: name 'bb' is not defined" in control.toPlainText()
@flaky(max_runs=3)
def test_restart_kernel(ipyconsole, mocker, qtbot):
# Mock method we want to check
mocker.patch.object(ClientWidget, "_show_mpl_backend_errors")
ipyconsole.create_new_client()
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Do an assignment to verify that it's not there after restarting
with qtbot.waitSignal(shell.executed):
shell.execute('a = 10')
with qtbot.waitSignal(shell.executed):
shell.execute('import sys; sys.__stderr__.write("HEL"+"LO")')
qtbot.waitUntil(
lambda: 'HELLO' in shell._control.toPlainText(), timeout=SHELL_TIMEOUT)
# Restart kernel and wait until it's up again
shell._prompt_html = None
ipyconsole.restart_kernel()
qtbot.waitUntil(
lambda: shell._prompt_html is not None, timeout=SHELL_TIMEOUT)
assert 'Restarting kernel...' in shell._control.toPlainText()
assert 'HELLO' not in shell._control.toPlainText()
assert not shell.is_defined('a')
assert ClientWidget._show_mpl_backend_errors.call_count == 2
@flaky(max_runs=3)
def test_load_kernel_file_from_id(ipyconsole, qtbot):
client = ipyconsole.get_current_client()
connection_file = osp.basename(client.connection_file)
id_ = connection_file.split('kernel-')[-1].split('.json')[0]
ipyconsole.get_widget()._create_client_for_kernel(id_, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
new_client = ipyconsole.get_clients()[1]
assert new_client.id_ == dict(int_id='1', str_id='B')
@flaky(max_runs=3)
def test_load_kernel_file_from_location(ipyconsole, qtbot, tmpdir):
client = ipyconsole.get_current_client()
fname = osp.basename(client.connection_file)
connection_file = to_text_string(tmpdir.join(fname))
shutil.copy2(client.connection_file, connection_file)
ipyconsole.get_widget()._create_client_for_kernel(connection_file, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
assert len(ipyconsole.get_clients()) == 2
@flaky(max_runs=3)
def test_load_kernel_file(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
client = ipyconsole.get_current_client()
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
qtbot.waitUntil(lambda: len(ipyconsole.get_clients()) == 2)
new_client = ipyconsole.get_clients()[1]
new_shell = new_client.shellwidget
qtbot.waitUntil(lambda: new_shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(new_shell.executed):
new_shell.execute('a = 10')
assert new_client.id_ == dict(int_id='1', str_id='B')
assert shell.get_value('a') == new_shell.get_value('a')
@flaky(max_runs=3)
def test_sys_argv_clear(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute('import sys; A = sys.argv')
argv = shell.get_value("A")
assert argv == ['']
@flaky(max_runs=5)
@pytest.mark.skipif(os.name == 'nt', reason="Fails sometimes on Windows")
def test_set_elapsed_time(ipyconsole, qtbot):
client = ipyconsole.get_current_client()
ipyconsole.get_widget().set_show_elapsed_time_current_client(True)
client.t0 -= 120
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
ipyconsole.get_widget().set_client_elapsed_time(client)
assert ('00:02:00' in client.time_label.text() or
'00:02:01' in client.time_label.text())
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
pass
assert ('00:02:01' in client.time_label.text() or
'00:02:02' in client.time_label.text())
client.t0 += 2000
with qtbot.waitSignal(client.timer.timeout, timeout=5000):
pass
assert '00:00:00' in client.time_label.text()
client.timer.timeout.disconnect(client.show_time)
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on Windows")
def test_stderr_file_is_removed_one_kernel(ipyconsole, qtbot, monkeypatch):
client = ipyconsole.get_current_client()
# In a normal situation file should exist
monkeypatch.setattr(QMessageBox, 'question',
classmethod(lambda *args: QMessageBox.Yes))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert not osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(
not sys.platform.startswith('linux'),
reason="Doesn't work on Windows and hangs sometimes on Mac")
def test_stderr_file_is_removed_two_kernels(ipyconsole, qtbot, monkeypatch):
client = ipyconsole.get_current_client()
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
assert len(ipyconsole.get_widget().get_related_clients(client)) == 1
other_client = ipyconsole.get_widget().get_related_clients(client)[0]
assert client.stderr_obj.filename == other_client.stderr_obj.filename
monkeypatch.setattr(QMessageBox, 'question',
classmethod(lambda *args: QMessageBox.Yes))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert not osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on Windows")
def test_stderr_file_remains_two_kernels(ipyconsole, qtbot, monkeypatch):
client = ipyconsole.get_current_client()
# New client with the same kernel
ipyconsole.get_widget()._create_client_for_kernel(
client.connection_file, None, None, None)
assert len(ipyconsole.get_widget().get_related_clients(client)) == 1
other_client = ipyconsole.get_widget().get_related_clients(client)[0]
assert client.stderr_obj.filename == other_client.stderr_obj.filename
# In a normal situation file should exist
monkeypatch.setattr(QMessageBox, "question",
classmethod(lambda *args: QMessageBox.No))
assert osp.exists(client.stderr_obj.filename)
ipyconsole.close_client(client=client)
assert osp.exists(client.stderr_obj.filename)
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'darwin',
reason="Fails sometimes on macOS")
def test_kernel_crash(ipyconsole, qtbot):
# Create an IPython kernel config file with a bad config
ipy_kernel_cfg = osp.join(get_ipython_dir(), 'profile_default',
'ipython_kernel_config.py')
with open(ipy_kernel_cfg, 'w') as f:
# This option must be a string, not an int
f.write("c.InteractiveShellApp.extra_extension = 1")
ipyconsole.create_new_client()
# Assert that the console is showing an error
qtbot.waitUntil(lambda: ipyconsole.get_clients()[-1].is_error_shown,
timeout=6000)
error_client = ipyconsole.get_clients()[-1]
assert error_client.is_error_shown
# Assert the error contains the text we expect
webview = error_client.infowidget
if WEBENGINE:
webpage = webview.page()
else:
webpage = webview.page().mainFrame()
qtbot.waitUntil(
lambda: check_text(webpage, "Bad config encountered"),
timeout=6000)
# Remove bad kernel config file
os.remove(ipy_kernel_cfg)
@flaky(max_runs=3)
@pytest.mark.skipif(not os.name == 'nt', reason="Only necessary on Windows")
def test_remove_old_std_files(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Create empty std files in our temp dir to see if they are removed
# correctly.
tmpdir = get_temp_dir()
open(osp.join(tmpdir, 'foo.stderr'), 'a').close()
open(osp.join(tmpdir, 'foo.stdout'), 'a').close()
# Assert that only old std files are removed
ipyconsole._remove_old_std_files()
assert not osp.isfile(osp.join(tmpdir, 'foo.stderr'))
assert not osp.isfile(osp.join(tmpdir, 'foo.stdout'))
# The current kernel std files should be present
for fname in glob.glob(osp.join(tmpdir, '*')):
assert osp.basename(fname).startswith('kernel')
assert any(
[osp.basename(fname).endswith(ext)
for ext in ('.stderr', '.stdout', '.fault')]
)
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
@pytest.mark.skipif(os.name == 'nt', reason="Too flaky on Windows")
def test_console_working_directory(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute('import os; cwd = os.getcwd()')
current_wdir = shell.get_value('cwd')
folders = osp.split(current_wdir)
assert folders[-1] == NEW_DIR
@flaky(max_runs=3)
@pytest.mark.skipif(not sys.platform.startswith('linux') or PY2,
reason="It only works on Linux with python 3.")
def test_console_complete(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
def check_value(name, value):
try:
return shell.get_value(name) == value
except KeyError:
return False
with qtbot.waitSignal(shell.executed):
shell.execute('cbs = 1')
qtbot.waitUntil(lambda: check_value('cbs', 1))
qtbot.wait(500)
qtbot.keyClicks(control, 'cb')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'cbs',
timeout=6000)
with qtbot.waitSignal(shell.executed):
shell.execute('cbba = 1')
qtbot.waitUntil(lambda: check_value('cbba', 1))
qtbot.keyClicks(control, 'cb')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(shell._completion_widget.isVisible)
assert control.toPlainText().split()[-1] == 'cb'
qtbot.keyClick(shell._completion_widget, Qt.Key_Enter)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'cbba')
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
qtbot.keyClicks(control, 'ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abs')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.keyClicks(control, 'print(ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(
lambda: control.toPlainText().split()[-1] == 'print(abs')
qtbot.keyClicks(control, ')')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Enter an expression
qtbot.keyClicks(control, 'baab = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: check_value('baab', 10))
# Check baab is completed
qtbot.keyClicks(control, 'baa')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'baab')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check the completion widget is shown for abba, abs
qtbot.keyClicks(control, 'abba = 10')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: check_value('abba', 10))
qtbot.keyClicks(control, 'ab')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(shell._completion_widget.isVisible)
assert control.toPlainText().split()[-1] == 'ab'
qtbot.keyClick(shell._completion_widget, Qt.Key_Enter)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abba')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Create a class
qtbot.keyClicks(control, 'class A(): baba = 1')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: shell.is_defined('A'))
qtbot.keyClicks(control, 'a = A()')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(100)
qtbot.waitUntil(lambda: shell.is_defined('a'))
# Check we can complete attributes
qtbot.keyClicks(control, 'a.ba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'a.baba')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can complete pdb command names
qtbot.keyClicks(control, '!longl')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == '!longlist')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can use custom complete for pdb
test_file = tmpdir.join('test.py')
test_file.write('stuff\n')
# Set a breakpoint in the new file
qtbot.keyClicks(control, '!b ' + str(test_file) + ':1')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
# Check we can complete the breakpoint number
qtbot.keyClicks(control, '!ignore ')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == '1')
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
def test_pdb_multiline(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
assert '\nIPdb [' in control.toPlainText()
qtbot.keyClicks(control, 'if True:')
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClicks(control, 'bb = 10')
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
assert shell.get_value('bb') == 10
assert "if True:\n ...: bb = 10\n" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.parametrize(
"show_lib", [True, False])
def test_pdb_ignore_lib(ipyconsole, qtbot, show_lib):
shell = ipyconsole.get_current_shellwidget()
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Tests assume inline backend
ipyconsole.set_conf('pdb_ignore_lib', not show_lib)
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
qtbot.keyClicks(control, '!s')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
qtbot.wait(500)
qtbot.keyClicks(control, '!q')
with qtbot.waitSignal(shell.executed):
qtbot.keyClick(control, Qt.Key_Enter)
if show_lib:
assert 'iostream.py' in control.toPlainText()
else:
assert 'iostream.py' not in control.toPlainText()
ipyconsole.set_conf('pdb_ignore_lib', True)
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'darwin', reason="Times out on macOS")
def test_calltip(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
# Give focus to the widget that's going to receive clicks
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
with qtbot.waitSignal(shell.executed):
shell.execute('a = {"a": 1}')
qtbot.keyClicks(control, 'a.keys(', delay=100)
qtbot.wait(1000)
assert control.calltip_widget.isVisible()
@flaky(max_runs=3)
@pytest.mark.order(1)
@pytest.mark.test_environment_interpreter
def test_conda_env_activation(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
with qtbot.waitSignal(shell.executed):
shell.execute(
"import os; conda_prefix = os.environ.get('CONDA_PREFIX')")
expected_output = get_conda_test_env().replace('\\', '/')
if is_conda_env(expected_output):
output = shell.get_value('conda_prefix').replace('\\', '/')
assert expected_output == output
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="no SIGTERM on Windows")
def test_kernel_kill(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.wait(3000)
crash_string = 'import os, signal; os.kill(os.getpid(), signal.SIGTERM)'
old_open_comms = list(shell.spyder_kernel_comm._comms.keys())
assert len(old_open_comms) == 1
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(crash_string)
assert crash_string in shell._control.toPlainText()
assert "Restarting kernel..." in shell._control.toPlainText()
new_open_comms = list(shell.spyder_kernel_comm._comms.keys())
assert len(new_open_comms) == 1
assert old_open_comms[0] != new_open_comms[0]
qtbot.waitUntil(
lambda: shell.spyder_kernel_comm._comms[new_open_comms[0]][
'status'] == 'ready')
assert shell.spyder_kernel_comm._comms[new_open_comms[0]][
'status'] == 'ready'
@flaky(max_runs=3)
@pytest.mark.parametrize("spyder_pythonpath", [True, False])
def test_wrong_std_module(ipyconsole, qtbot, tmpdir, spyder_pythonpath):
if spyder_pythonpath:
wrong_random_mod = tmpdir.join('random.py')
wrong_random_mod.write('')
wrong_random_mod = str(wrong_random_mod)
ipyconsole.set_conf('spyder_pythonpath', [str(tmpdir)], section='main')
else:
wrong_random_mod = osp.join(os.getcwd(), 'random.py')
with open(wrong_random_mod, 'w') as f:
f.write('')
ipyconsole.create_new_client()
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Assert the extra path from spyder_pythonpath was added
if spyder_pythonpath:
check_sys_path = (
"import sys; path_added = r'{}' in sys.path".format(str(tmpdir))
)
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(check_sys_path)
assert shell.get_value('path_added')
# Remove wrong module
os.remove(wrong_random_mod)
# Restore CONF
ipyconsole.set_conf('spyder_pythonpath', [], section='main')
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="no SIGTERM on Windows")
def test_kernel_restart_after_manual_restart_and_crash(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Restart kernel and wait until it's up again
shell._prompt_html = None
ipyconsole.restart_kernel()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
qtbot.wait(3000)
crash_string = 'import os, signal; os.kill(os.getpid(), signal.SIGTERM)'
with qtbot.waitSignal(shell.sig_prompt_ready, timeout=30000):
shell.execute(crash_string)
assert crash_string in shell._control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute('a = 10')
assert shell.is_defined('a')
open_comms = list(shell.spyder_kernel_comm._comms.keys())
qtbot.waitUntil(
lambda: shell.spyder_kernel_comm._comms[open_comms[0]][
'status'] == 'ready')
@flaky(max_runs=3)
def test_stderr_poll(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
client = ipyconsole.get_current_client()
client.stderr_obj.handle.flush()
with open(client.stderr_obj.filename, 'a') as f:
f.write("test_test")
qtbot.waitUntil(lambda: "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText())
assert "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText()
client.stderr_obj.handle.flush()
with open(client.stderr_obj.filename, 'a') as f:
f.write("\ntest_test")
qtbot.waitUntil(lambda: ipyconsole.get_widget().get_focus_widget(
).toPlainText().count("test_test") == 2)
assert ipyconsole.get_widget().get_focus_widget().toPlainText(
).count("test_test") == 2
@flaky(max_runs=3)
def test_stdout_poll(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
client = ipyconsole.get_current_client()
client.stdout_obj.handle.flush()
with open(client.stdout_obj.filename, 'a') as f:
f.write("test_test")
qtbot.waitUntil(lambda: "test_test" in ipyconsole.get_widget(
).get_focus_widget().toPlainText(), timeout=5000)
assert "test_test" in ipyconsole.get_widget().get_focus_widget(
).toPlainText()
@flaky(max_runs=10)
@pytest.mark.use_startup_wdir
def test_startup_code_pdb(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Run a line on startup
ipyconsole.set_conf(
'startup/pdb_run_lines',
'abba = 12; print("Hello")'
)
shell.execute('%debug print()')
qtbot.waitUntil(lambda: 'Hello' in control.toPlainText())
# Verify that the line was executed
assert shell.get_value('abba') == 12
# Reset setting
ipyconsole.set_conf('startup/pdb_run_lines', '')
@flaky(max_runs=3)
@pytest.mark.parametrize(
"backend",
['inline', 'qt5', 'tk', 'osx']
)
def test_pdb_eventloop(ipyconsole, qtbot, backend):
# Skip failing tests
if backend == 'tk' and os.name == 'nt':
return
if backend == 'osx' and sys.platform != "darwin":
return
if backend == 'qt5' and not os.name == "nt" and running_in_ci():
return
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%matplotlib " + backend)
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
with qtbot.waitSignal(shell.executed):
shell.execute("print('Two: ' + str(1+1))")
assert "Two: 2" in control.toPlainText()
@flaky(max_runs=3)
def test_recursive_pdb(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("abab = 10")
# Check that we can't use magic twice
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("%debug print()")
assert "Please don't use '%debug'" in control.toPlainText()
# Check we can enter the recursive debugger twice
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!debug print()")
assert "(IPdb [1]):" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!debug print()")
assert "((IPdb [1])):" in control.toPlainText()
# quit one layer
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
assert control.toPlainText().split()[-2:] == ["(IPdb", "[2]):"]
# Check completion works
qtbot.keyClicks(control, 'aba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abab',
timeout=SHELL_TIMEOUT)
# quit one layer
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
assert control.toPlainText().split()[-2:] == ["IPdb", "[4]:"]
# Check completion works
qtbot.keyClicks(control, 'aba')
qtbot.keyClick(control, Qt.Key_Tab)
qtbot.waitUntil(lambda: control.toPlainText().split()[-1] == 'abab',
timeout=SHELL_TIMEOUT)
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("!quit")
with qtbot.waitSignal(shell.executed):
shell.execute("1 + 1")
assert control.toPlainText().split()[-2:] == ["In", "[3]:"]
@flaky(max_runs=3)
@pytest.mark.skipif(os.name == 'nt', reason="Doesn't work on windows")
def test_stop_pdb(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
stop_button = ipyconsole.get_widget().stop_button
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
shell.execute("import time; time.sleep(10)")
qtbot.wait(500)
with qtbot.waitSignal(shell.executed, timeout=1000):
qtbot.mouseClick(stop_button, Qt.LeftButton)
assert "KeyboardInterrupt" in control.toPlainText()
assert "IPdb [2]:" in control.toPlainText()
assert "In [2]:" not in control.toPlainText()
with qtbot.waitSignal(shell.executed):
qtbot.mouseClick(stop_button, Qt.LeftButton)
assert "In [2]:" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.skipif(sys.platform == 'nt', reason="Times out on Windows")
def test_code_cache(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
def check_value(name, value):
try:
return shell.get_value(name) == value
except KeyError:
return False
# Send two execute requests and make sure the second one is executed
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 142')
qtbot.wait(500)
qtbot.waitUntil(lambda: check_value('var', 142))
assert shell.get_value('var') == 142
# Send two execute requests and cancel the second one
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 1000')
shell.interrupt_kernel()
qtbot.wait(1000)
# Make sure the value of var didn't change
assert shell.get_value('var') == 142
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
assert 'IPdb [' in shell._control.toPlainText()
shell.execute('time.sleep(.5)')
shell.execute('var = 318')
qtbot.wait(500)
qtbot.waitUntil(lambda: check_value('var', 318))
assert shell.get_value('var') == 318
shell.execute('import time; time.sleep(.5)')
shell.execute('var = 1000')
shell.interrupt_kernel()
qtbot.wait(1000)
assert shell.get_value('var') == 318
@flaky(max_runs=3)
@pytest.mark.skipif(PY2, reason="Doesn't work on Python 2.7")
def test_pdb_code_and_cmd_separation(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
with qtbot.waitSignal(shell.executed):
shell.execute("%debug print()")
assert "Error" not in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("e")
assert "name 'e' is not defined" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("!n")
assert "--Return--" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("a")
assert ("*** NameError: name 'a' is not defined"
not in control.toPlainText())
with qtbot.waitSignal(shell.executed):
shell.execute("abba")
assert "name 'abba' is not defined" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.execute("!abba")
assert "Unknown command 'abba'" in control.toPlainText()
@flaky(max_runs=3)
def test_breakpoint_builtin(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
code = dedent("""
print('foo')
breakpoint()
""")
file = tmpdir.join('test_breakpoint.py')
file.write(code)
with qtbot.waitSignal(shell.executed):
shell.execute(f"runfile(filename=r'{str(file)}')")
qtbot.wait(5000)
assert 'foo' in control.toPlainText()
assert 'IPdb [1]:' in control.toPlainText()
def test_pdb_out(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
control.setFocus()
# Enter debugging mode
with qtbot.waitSignal(shell.executed):
shell.execute('%debug print()')
# Generate some output
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 12 + 1; a')
assert "[1]: 13" in control.toPlainText()
# Generate hide output
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 14 + 1; a;')
assert "[2]: 15" not in control.toPlainText()
# Multiline
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 16 + 1\na')
assert "[3]: 17" in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute('a = 18 + 1\na;')
assert "[4]: 19" not in control.toPlainText()
assert "IPdb [4]:" in control.toPlainText()
@flaky(max_runs=3)
@pytest.mark.auto_backend
@pytest.mark.skipif(
running_in_ci() and not os.name == 'nt',
reason="Times out on Linux and macOS")
def test_shutdown_kernel(ipyconsole, qtbot):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Create a Matplotlib plot
with qtbot.waitSignal(shell.executed):
shell.execute("import matplotlib.pyplot as plt; plt.plot(range(10))")
# Get kernel pid
with qtbot.waitSignal(shell.executed):
shell.execute("import os; pid = os.getpid()")
kernel_pid = shell.get_value('pid')
# Close current tab
ipyconsole.get_widget().close_client()
# Wait until new client is created and previous kernel is shutdown
qtbot.wait(5000)
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
# Detect if previous kernel was killed
with qtbot.waitSignal(shell.executed):
shell.execute(
f"import psutil; kernel_exists = psutil.pid_exists({kernel_pid})"
)
assert not shell.get_value('kernel_exists')
def test_pdb_comprehension_namespace(ipyconsole, qtbot, tmpdir):
shell = ipyconsole.get_current_shellwidget()
qtbot.waitUntil(lambda: shell._prompt_html is not None,
timeout=SHELL_TIMEOUT)
control = ipyconsole.get_widget().get_focus_widget()
# Code to run
code = "locals = 1\nx = [locals + i for i in range(2)]"
# Write code to file on disk
file = tmpdir.join('test_breakpoint.py')
file.write(code)
# Run file
with qtbot.waitSignal(shell.executed):
shell.execute(f"debugfile(filename=r'{str(file)}')")
# steps 4 times
for i in range(4):
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("s")
assert "Error" not in control.toPlainText()
with qtbot.waitSignal(shell.executed):
shell.pdb_execute("print('test', locals + i + 10)")
assert "Error" not in control.toPlainText()
assert "test 11" in control.toPlainText()
settings = {
'check_all': False,
'exclude_callables_and_modules': True,
'exclude_capitalized': False,
'exclude_private': True,
'exclude_unsupported': False,
'exclude_uppercase': True,
'excluded_names': [],
'minmax': False,
'show_callable_attributes': True,
'show_special_attributes': False}
shell.call_kernel(
interrupt=True
).set_namespace_view_settings(settings)
namespace = shell.call_kernel(blocking=True).get_namespace_view()
for key in namespace:
assert "_spyderpdb" not in key
if __name__ == "__main__":
pytest.main()
| true | true |
f726a2f4cad617630bb938793f65f75b2ac968fa | 5,832 | py | Python | src/ruvsarpur/ruv_client.py | HaukurPall/ruvsarpur | bf9befe37aa8c38e7b056372e11bb0f6450497a2 | [
"MIT"
] | null | null | null | src/ruvsarpur/ruv_client.py | HaukurPall/ruvsarpur | bf9befe37aa8c38e7b056372e11bb0f6450497a2 | [
"MIT"
] | null | null | null | src/ruvsarpur/ruv_client.py | HaukurPall/ruvsarpur | bf9befe37aa8c38e7b056372e11bb0f6450497a2 | [
"MIT"
] | null | null | null | import asyncio
import json
import logging
from pathlib import Path
from typing import Dict, List, TypedDict
from gql import Client, gql
from gql.client import AsyncClientSession
from gql.transport.aiohttp import AIOHTTPTransport
log = logging.getLogger(__name__)
class Episode(TypedDict):
id: str
title: str
file: str
class Program(TypedDict):
id: str
title: str
foreign_title: str
short_description: str
episodes: List[Episode]
Programs = Dict[str, Program]
class RUVClient:
"""An HTTP client to gather a program list from ruv.is."""
def __init__(self) -> None:
self.url = "https://www.ruv.is/gql/"
transport = AIOHTTPTransport(self.url)
self.client = Client(transport=transport, execute_timeout=30)
@staticmethod
async def _query_categories(session: AsyncClientSession) -> List[str]:
query = gql(
"""
query getCategorys($station: StationSearch!) {
Category(station: $station) {
categories {
title
slug
}
}
}
"""
)
params = {
"station": "tv",
}
result = await session.execute(query, variable_values=params)
category_slugs = [category["slug"] for category in result["Category"]["categories"]] # type: ignore
return category_slugs
@staticmethod
async def _query_category(session: AsyncClientSession, category: str) -> List[Program]:
query = gql(
"""
query getKrakkaRUVCategories($station: StationSearch!, $category: String!) {
Category(station: $station, category: $category) {
categories {
programs {
short_description
episodes {
id
title
file
}
title
foreign_title
short_description
id
}
}
}
}
"""
)
params = {
"station": "tv",
"category": category,
}
result = await session.execute(query, variable_values=params)
return [
program for category in result["Category"]["categories"] for program in category["programs"] # type: ignore
]
async def _get_all_categories(self) -> List[Program]:
async with self.client as session:
categories = await self._query_categories(session)
list_of_programs_lists = await asyncio.gather(
*[asyncio.create_task(self._query_category(session, category=category)) for category in categories]
)
return [program for program_list in list_of_programs_lists for program in program_list]
@staticmethod
async def _query_all_programs(session: AsyncClientSession) -> List[Program]:
query = gql(
"""
query {
Programs {
short_description
episodes {
id
title
file
}
title
foreign_title
short_description
id
}
}
"""
)
result = await session.execute(query)
return [program for program in result["Programs"]] # type: ignore
async def _get_all_programs(self) -> Programs:
async with self.client as session:
programs = await self._query_all_programs(session)
programs_dict = {program["id"]: program for program in programs}
categories = await self._query_categories(session)
list_of_programs_lists = await asyncio.gather(
*[asyncio.create_task(self._query_category(session, category=category)) for category in categories]
)
programs_with_extra_info = {
program["id"]: program for program_list in list_of_programs_lists for program in program_list
}
self._add_extra_info(programs_dict, programs_with_extra_info)
return programs_dict
def get_all_programs(self) -> Programs:
return asyncio.run(self._get_all_programs())
@staticmethod
def _add_extra_info(programs: Programs, programs_extra_info: Programs) -> None:
"""Adds extra information from another program list to the first one."""
for p_id, program in programs.items():
if p_id in programs_extra_info:
for key in ["short_description", "foreign_title"]:
program[key] = programs_extra_info[program["id"]][key] # type: ignore
def save_programs(file_path: Path, programs: Programs):
with file_path.open("w") as f:
json.dump(programs, f)
def load_programs_cache(file_path: Path) -> Programs:
with file_path.open("r") as f:
return json.load(f)
def load_programs(force_reload, cache: Path) -> Programs:
"""Load the programs by either loading from cache or by querying ruv.is."""
if force_reload:
programs = RUVClient().get_all_programs()
else:
try:
return load_programs_cache(cache)
except FileNotFoundError:
programs = RUVClient().get_all_programs()
save_programs(cache, programs)
log.info(
f"Loaded {len(programs)} programs and {sum([len(program['episodes']) for program in programs.values()])} episodes"
)
return programs
| 33.325714 | 122 | 0.558471 | import asyncio
import json
import logging
from pathlib import Path
from typing import Dict, List, TypedDict
from gql import Client, gql
from gql.client import AsyncClientSession
from gql.transport.aiohttp import AIOHTTPTransport
log = logging.getLogger(__name__)
class Episode(TypedDict):
id: str
title: str
file: str
class Program(TypedDict):
id: str
title: str
foreign_title: str
short_description: str
episodes: List[Episode]
Programs = Dict[str, Program]
class RUVClient:
def __init__(self) -> None:
self.url = "https://www.ruv.is/gql/"
transport = AIOHTTPTransport(self.url)
self.client = Client(transport=transport, execute_timeout=30)
@staticmethod
async def _query_categories(session: AsyncClientSession) -> List[str]:
query = gql(
"""
query getCategorys($station: StationSearch!) {
Category(station: $station) {
categories {
title
slug
}
}
}
"""
)
params = {
"station": "tv",
}
result = await session.execute(query, variable_values=params)
category_slugs = [category["slug"] for category in result["Category"]["categories"]]
return category_slugs
@staticmethod
async def _query_category(session: AsyncClientSession, category: str) -> List[Program]:
query = gql(
"""
query getKrakkaRUVCategories($station: StationSearch!, $category: String!) {
Category(station: $station, category: $category) {
categories {
programs {
short_description
episodes {
id
title
file
}
title
foreign_title
short_description
id
}
}
}
}
"""
)
params = {
"station": "tv",
"category": category,
}
result = await session.execute(query, variable_values=params)
return [
program for category in result["Category"]["categories"] for program in category["programs"]
]
async def _get_all_categories(self) -> List[Program]:
async with self.client as session:
categories = await self._query_categories(session)
list_of_programs_lists = await asyncio.gather(
*[asyncio.create_task(self._query_category(session, category=category)) for category in categories]
)
return [program for program_list in list_of_programs_lists for program in program_list]
@staticmethod
async def _query_all_programs(session: AsyncClientSession) -> List[Program]:
query = gql(
"""
query {
Programs {
short_description
episodes {
id
title
file
}
title
foreign_title
short_description
id
}
}
"""
)
result = await session.execute(query)
return [program for program in result["Programs"]]
async def _get_all_programs(self) -> Programs:
async with self.client as session:
programs = await self._query_all_programs(session)
programs_dict = {program["id"]: program for program in programs}
categories = await self._query_categories(session)
list_of_programs_lists = await asyncio.gather(
*[asyncio.create_task(self._query_category(session, category=category)) for category in categories]
)
programs_with_extra_info = {
program["id"]: program for program_list in list_of_programs_lists for program in program_list
}
self._add_extra_info(programs_dict, programs_with_extra_info)
return programs_dict
def get_all_programs(self) -> Programs:
return asyncio.run(self._get_all_programs())
@staticmethod
def _add_extra_info(programs: Programs, programs_extra_info: Programs) -> None:
for p_id, program in programs.items():
if p_id in programs_extra_info:
for key in ["short_description", "foreign_title"]:
program[key] = programs_extra_info[program["id"]][key]
def save_programs(file_path: Path, programs: Programs):
with file_path.open("w") as f:
json.dump(programs, f)
def load_programs_cache(file_path: Path) -> Programs:
with file_path.open("r") as f:
return json.load(f)
def load_programs(force_reload, cache: Path) -> Programs:
if force_reload:
programs = RUVClient().get_all_programs()
else:
try:
return load_programs_cache(cache)
except FileNotFoundError:
programs = RUVClient().get_all_programs()
save_programs(cache, programs)
log.info(
f"Loaded {len(programs)} programs and {sum([len(program['episodes']) for program in programs.values()])} episodes"
)
return programs
| true | true |
f726a329312efb2fda886586854705d5e3adad9f | 6,532 | py | Python | listWrangler_20191216.py | LukeHebert/genelist_overlap | 5275e9b1d8d5dae2a78b76aed42925bdd4914418 | [
"MIT"
] | null | null | null | listWrangler_20191216.py | LukeHebert/genelist_overlap | 5275e9b1d8d5dae2a78b76aed42925bdd4914418 | [
"MIT"
] | null | null | null | listWrangler_20191216.py | LukeHebert/genelist_overlap | 5275e9b1d8d5dae2a78b76aed42925bdd4914418 | [
"MIT"
] | null | null | null | '''
Author: Luke Hebert
Date begun: December 16th, 2019
Description: finds either the intersection, union, or unique items from a set of n lists
especially useful for comparing lists of genes
inputs for unique option need to be .txt files; this could be easily tweaked though
all input and output are forced to upper case; can be easily tweaked
'''
import os, sys
def getContents(paths_list):
'''reads multiple files and assigns them to a dictionary with filepaths as keys and content lists as values'''
contents_dict = {}
for file in paths_list:
contents_dict[file] = []
with open(file, 'r') as inFile:
for line in inFile:
line = line.strip('\n').strip('\r')
contents_dict[file].append(line.upper())
return contents_dict
slash = '\\' if os.name == 'nt' else '/'
arguments_list = sys.argv[:]
#INTERSECTION OF N LISTS
if "-i" in arguments_list:
#remove python program and -i arguments to make a pathway list
inPaths_list = list(arguments_list)
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-i') or ('.py' in path):
inPaths_list.remove(path)
#print out the pathway indexes so that user can select one as the output pathway directory
print('\n')
for i, path in enumerate(inPaths_list):
print(str(i) + '\t' + path)
#ask user to select output file name and directory
outFileName = raw_input("\nPlease enter the name (not the path) of the output txt file (include the file suffix):")
outPath_index = int(raw_input("\nPlease enter index of the file whose path will be used for the output file (an integer):"))
if len(inPaths_list) < 2: #user must specify at least two input files for this option
print('\nUser must specify at least two lists in order to find the intersection.')
else:
print("\nYou chose to find the intersection of " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list) #read the input files into a dictionary
intersection_list = [] #will fill this with intersection data only
for key, val in contents_dict.iteritems(): #for each input file's list data
if len(intersection_list) == 0: #if this is the first file's data evaluated, just copy it to output list
intersection_list = list(val)
else: #the heart of the algorithm
temp_list = [item for item in val if item in intersection_list] #this should create the intersection of val and intersection_list
intersection_list = list(temp_list) #update intersection_list using a deep copy
completeOutPath = slash.join(inPaths_list[outPath_index].split(slash)[:-1] + [outFileName]) #not the most readable, but this is the output path/name
#write intersection_list to the output file as a single column of data
with open(completeOutPath, 'w') as outFile:
for item in intersection_list:
outFile.write(item + '\n')
#UNION OF N LISTS
elif "-n" in arguments_list:
#remove python program and -n arguments to make a pathway list
inPaths_list = list(arguments_list)
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-n') or ('.py' in path):
inPaths_list.remove(path)
#print out the pathway indexes so that user can select one as the output pathway directory
print('\n')
for i, path in enumerate(inPaths_list):
print(str(i) + '\t' + path)
#ask user to select output file name and directory
outFileName = raw_input("\nPlease enter the name (not the path) of the output txt file (include the file suffix):")
outPath_index = int(raw_input("\nPlease enter index of the file whose path will be used for the output file (an integer):"))
if len(inPaths_list) < 2: #user must specify at least two input files for this option
print('\nUser must specify at least two lists in order to find the union.')
else:
print("\nYou chose to find the union of " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list) #read the input files into a dictionary
union_list = [] #will fill this with intersection data only
for key, val in contents_dict.iteritems(): #for each input file's list data
if len(union_list) == 0: #if this is the first file's data evaluated, just copy it to output list
union_list = list(val)
else: #the hearth of the algorithm
temp_list = union_list + val #update union list with current file's data/list
union_list = list(set(temp_list)) #remove any duplicates
completeOutPath = slash.join(inPaths_list[outPath_index].split(slash)[:-1] + [outFileName]) #not the most readable, but this is the output path/name
#write union_list to the output file as a single column of data
with open(completeOutPath, 'w') as outFile:
for item in union_list:
outFile.write(item + '\n')
#ITEMS UNIQUE TO EACH OF N LISTS
elif "-o" in arguments_list:
inPaths_list = list(arguments_list)
#remove python program file and selection arguments from arguments list
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-o') or ('.py' in path):
inPaths_list.remove(path)
if len(inPaths_list) < 2: #user must specify at least two input files for this option
print('\nUser must specify at least two lists in order to find the uniques.')
else:
print("\nYou chose to find the unnique values from " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list) #read the input files into a dictionary
union_list = [] #will fill this with intersection data only
for key, val in contents_dict.iteritems(): #for each input file's list data
unique_list = list(val)
temp_dict = contents_dict.copy()
del temp_dict[key] #we want to check current list against all other lists, but not itself
for key2, val2 in temp_dict.iteritems(): #go through all the lists except the current list of interest
unique_list = [item for item in unique_list if item not in val2] #keep only those that are unique to unique_list
outFilePath = key.replace(".txt", "_uniques.txt")
with open(outFilePath, 'w') as outFile:
for item in unique_list:
outFile.write(item + '\n')
#SET OF ONE LIST
elif "-s" in arguments_list:
print('\nYou have chosen to take the set of a single list.')
inPath = ''
for argument in arguments_list:
if ('.py' not in argument) and ('-s' not in argument):
inPath = str(argument) #deep copy
outList = []
with open(inPath, 'r') as inFile:
for line in inFile:
outList.append(line.strip('\n'))
outSet = set(outList)
outPath = inPath.replace(".txt", "_set.txt")
with open(outPath, 'w') as outFile:
for item in outSet:
outFile.write(item.upper() + '\n') | 48.746269 | 150 | 0.729026 |
import os, sys
def getContents(paths_list):
contents_dict = {}
for file in paths_list:
contents_dict[file] = []
with open(file, 'r') as inFile:
for line in inFile:
line = line.strip('\n').strip('\r')
contents_dict[file].append(line.upper())
return contents_dict
slash = '\\' if os.name == 'nt' else '/'
arguments_list = sys.argv[:]
if "-i" in arguments_list:
inPaths_list = list(arguments_list)
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-i') or ('.py' in path):
inPaths_list.remove(path)
print('\n')
for i, path in enumerate(inPaths_list):
print(str(i) + '\t' + path)
outFileName = raw_input("\nPlease enter the name (not the path) of the output txt file (include the file suffix):")
outPath_index = int(raw_input("\nPlease enter index of the file whose path will be used for the output file (an integer):"))
if len(inPaths_list) < 2:
print('\nUser must specify at least two lists in order to find the intersection.')
else:
print("\nYou chose to find the intersection of " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list)
intersection_list = []
for key, val in contents_dict.iteritems():
if len(intersection_list) == 0: #if this is the first file's data evaluated, just copy it to output list
intersection_list = list(val)
else:
temp_list = [item for item in val if item in intersection_list]
intersection_list = list(temp_list)
completeOutPath = slash.join(inPaths_list[outPath_index].split(slash)[:-1] + [outFileName])
with open(completeOutPath, 'w') as outFile:
for item in intersection_list:
outFile.write(item + '\n')
elif "-n" in arguments_list:
inPaths_list = list(arguments_list)
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-n') or ('.py' in path):
inPaths_list.remove(path)
print('\n')
for i, path in enumerate(inPaths_list):
print(str(i) + '\t' + path)
outFileName = raw_input("\nPlease enter the name (not the path) of the output txt file (include the file suffix):")
outPath_index = int(raw_input("\nPlease enter index of the file whose path will be used for the output file (an integer):"))
if len(inPaths_list) < 2:
print('\nUser must specify at least two lists in order to find the union.')
else:
print("\nYou chose to find the union of " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list)
union_list = []
for key, val in contents_dict.iteritems():
if len(union_list) == 0: #if this is the first file's data evaluated, just copy it to output list
union_list = list(val)
else:
temp_list = union_list + val
union_list = list(set(temp_list)) #remove any duplicates
completeOutPath = slash.join(inPaths_list[outPath_index].split(slash)[:-1] + [outFileName]) #not the most readable, but this is the output path/name
#write union_list to the output file as a single column of data
with open(completeOutPath, 'w') as outFile:
for item in union_list:
outFile.write(item + '\n')
#ITEMS UNIQUE TO EACH OF N LISTS
elif "-o" in arguments_list:
inPaths_list = list(arguments_list)
#remove python program file and selection arguments from arguments list
temp_pathsList = list(inPaths_list)
for path in temp_pathsList:
if (path == '-o') or ('.py' in path):
inPaths_list.remove(path)
if len(inPaths_list) < 2: #user must specify at least two input files for this option
print('\nUser must specify at least two lists in order to find the uniques.')
else:
print("\nYou chose to find the unnique values from " + str(len(inPaths_list)) + " lists.")
contents_dict = getContents(inPaths_list) #read the input files into a dictionary
union_list = [] #will fill this with intersection data only
for key, val in contents_dict.iteritems(): #for each input file's list data
unique_list = list(val)
temp_dict = contents_dict.copy()
del temp_dict[key]
for key2, val2 in temp_dict.iteritems():
unique_list = [item for item in unique_list if item not in val2]
outFilePath = key.replace(".txt", "_uniques.txt")
with open(outFilePath, 'w') as outFile:
for item in unique_list:
outFile.write(item + '\n')
elif "-s" in arguments_list:
print('\nYou have chosen to take the set of a single list.')
inPath = ''
for argument in arguments_list:
if ('.py' not in argument) and ('-s' not in argument):
inPath = str(argument)
outList = []
with open(inPath, 'r') as inFile:
for line in inFile:
outList.append(line.strip('\n'))
outSet = set(outList)
outPath = inPath.replace(".txt", "_set.txt")
with open(outPath, 'w') as outFile:
for item in outSet:
outFile.write(item.upper() + '\n') | true | true |
f726a386b1ac9288db05e33cf07f7a65824e7d28 | 1,805 | py | Python | dataset_utils/check_bg_layer.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | dataset_utils/check_bg_layer.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | dataset_utils/check_bg_layer.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | import os
from PIL import Image, ImageDraw
from tqdm import tqdm
def label_bg_layer(img_path, label_path, img_type):
bg_data_list = os.listdir(img_path)
label_list = os.listdir(label_path)
label_prefix_list = []
for label in label_list:
label = os.path.splitext(label)[0]
label_prefix_list.append(label)
# find backgound label
for bg_data in tqdm(bg_data_list):
bg_data_withoutnew = bg_data[4:]
if bg_data_withoutnew in label_prefix_list:
single_label_path = os.path.join(label_path, bg_data_withoutnew + '.txt')
single_img_path = os.path.join(img_path, bg_data, img_type)
with open(single_label_path, 'r') as label_fp:
label_list = [
(float(x.split(" ")[1]), float(x.split(" ")[2]),
float(x.split(" ")[3]), float(x.split(" ")[4]),)
for x in label_fp.readlines()
]
image = Image.open(single_img_path)
h, w = image.size
image_draw = ImageDraw.Draw(image)
for label in label_list:
# draw label
image_draw.rectangle(
[(label[0] - label[2] / 2) * w, (label[1] - label[3] / 2) * h, (label[0] + label[2] / 2) * w,
(label[1] + label[3] / 2) * h],
fill=None, outline='red', width=3
)
# save labeled image
image.save(os.path.splitext(single_img_path)[
0] + '-labeled' + os.path.splitext(single_img_path)[1])
if __name__ == '__main__':
label_bg_layer('my-dataset/merge_background_images',
'my-dataset/labels',
img_type='filled.png')
| 41.022727 | 117 | 0.532964 | import os
from PIL import Image, ImageDraw
from tqdm import tqdm
def label_bg_layer(img_path, label_path, img_type):
bg_data_list = os.listdir(img_path)
label_list = os.listdir(label_path)
label_prefix_list = []
for label in label_list:
label = os.path.splitext(label)[0]
label_prefix_list.append(label)
for bg_data in tqdm(bg_data_list):
bg_data_withoutnew = bg_data[4:]
if bg_data_withoutnew in label_prefix_list:
single_label_path = os.path.join(label_path, bg_data_withoutnew + '.txt')
single_img_path = os.path.join(img_path, bg_data, img_type)
with open(single_label_path, 'r') as label_fp:
label_list = [
(float(x.split(" ")[1]), float(x.split(" ")[2]),
float(x.split(" ")[3]), float(x.split(" ")[4]),)
for x in label_fp.readlines()
]
image = Image.open(single_img_path)
h, w = image.size
image_draw = ImageDraw.Draw(image)
for label in label_list:
image_draw.rectangle(
[(label[0] - label[2] / 2) * w, (label[1] - label[3] / 2) * h, (label[0] + label[2] / 2) * w,
(label[1] + label[3] / 2) * h],
fill=None, outline='red', width=3
)
image.save(os.path.splitext(single_img_path)[
0] + '-labeled' + os.path.splitext(single_img_path)[1])
if __name__ == '__main__':
label_bg_layer('my-dataset/merge_background_images',
'my-dataset/labels',
img_type='filled.png')
| true | true |
f726a3f0bc85a62b7c621cc217d1f66bc6ba1017 | 4,272 | py | Python | etl/deaths.py | icane/demographic-indicators | b1c394a4497e8e4c0189bf4c0518ce38fb873d4c | [
"Apache-2.0"
] | null | null | null | etl/deaths.py | icane/demographic-indicators | b1c394a4497e8e4c0189bf4c0518ce38fb873d4c | [
"Apache-2.0"
] | 1 | 2022-01-18T11:01:29.000Z | 2022-01-18T11:01:29.000Z | etl/deaths.py | icane/demographic-indicators | b1c394a4497e8e4c0189bf4c0518ce38fb873d4c | [
"Apache-2.0"
] | null | null | null | """Deaths indicators."""
from etl.common import to_json_stat, write_to_file
from etl.config_deaths import deaths_cfg as cfg
from etlstat.extractor.extractor import xlsx
import json
import pandas as pd
def transform(df, periods, prefix=''):
"""Slice dataframe. Generate time period column.
df (dataframe): dataset
periods (int): number of time periods
prefix (str): prefix for time periods
"""
for i in range(0, len(df)):
period1 = str(df.loc[i, 'Año'])
period2 = '{:0>2}'.format(df.loc[i, 'Mes'])
df.loc[i, 'period'] = prefix + period1 + '-' + period2
df.drop(columns={'Año', 'Mes'}, axis=1, inplace=True)
df.rename(columns={'period': 'Mes'}, inplace=True)
df = df.tail(periods)
df = df.round(2)
return df
def replace_month(json_str):
"""Replace month number by its name."""
json_str = json_str.replace('-01"', '-Ene"')
json_str = json_str.replace('-02"', '-Feb"')
json_str = json_str.replace('-03"', '-Mar"')
json_str = json_str.replace('-04"', '-Abr"')
json_str = json_str.replace('-05"', '-May"')
json_str = json_str.replace('-06"', '-Jun"')
json_str = json_str.replace('-07"', '-Jul"')
json_str = json_str.replace('-08"', '-Ago"')
json_str = json_str.replace('-09"', '-Sep"')
json_str = json_str.replace('-10"', '-Oct"')
json_str = json_str.replace('-11"', '-Nov"')
json_str = json_str.replace('-12"', '-Dic"')
return json_str
# Read input files
data = xlsx(cfg.path.input)
# Datasets
df_global = pd.DataFrame()
indicators = []
for key in cfg.series:
print(key)
variables = [
'Año', 'Mes',
cfg.series[key].variables[0],
cfg.series[key].moving_avg[0]]
if (len(cfg.series[key].variables) == 2):
variables.append(cfg.series[key].variables[1])
variables.append(cfg.series[key].moving_avg[1])
df = data[cfg.file]\
[cfg.series[key].sheet][variables].copy()
# Drop NA rows, if any
df.dropna(axis=0, how='all', inplace=True)
# Rename variables
df.rename(
columns={
cfg.series[key].variables[0]: 'Cantabria',
cfg.series[key].moving_avg[0]: 'Cantabria_MM'},
inplace=True)
if (len(cfg.series[key].variables) == 2):
df.rename(
columns={
cfg.series[key].variables[1]: 'España',
cfg.series[key].moving_avg[1]: 'España_MM'},
inplace=True)
# Remove .0 from Año and Mes
df['Año'] = df['Año'].astype(str).replace('\.0', '', regex=True)
df['Mes'] = df['Mes'].astype(str).replace('\.0', '', regex=True)
# Merge global dataset
df_cant = df[['Año', 'Mes', 'Cantabria']].copy()
df_cant = transform(df_cant, cfg.periods.global_deaths, 'Cantabria - ')
df_cant.set_index('Mes', inplace=True)
df_cant = df_cant.transpose()
df_cant.insert(0, 'Categoria', cfg.series[key].category)
df_cant[' - Indicadores'] = cfg.series[key].label
if (len(cfg.series[key].variables) == 2):
df_esp = df[['Año', 'Mes', 'España']].copy()
df_esp = transform(df_esp, cfg.periods.global_deaths, 'España - ')
df_esp.set_index('Mes', inplace=True)
df_esp = df_esp.transpose()
df_esp[' - Indicadores'] = cfg.series[key].label
df_cant = df_cant.merge(df_esp, on=' - Indicadores')
indicators.append(df_cant)
# Generate JSON-Stat dataset
df = transform(df, cfg.periods.deaths)
vars = ['Cantabria', 'Cantabria_MM']
if (len(cfg.series[key].variables) == 2):
vars.append('España')
vars.append('España_MM')
json_file = to_json_stat(
df,
['Mes'],
vars,
cfg.series[key].source)
json_obj = json.loads(json_file)
json_obj['dimension']['Variables']['category']['unit'] = \
cfg.series[key].unit
json_obj['note'] = cfg.series[key].note
json_file = json.dumps(json_obj)
json_file = replace_month(json_file)
write_to_file(json_file, cfg.path.output + cfg.series[key].json)
# Generate CSV global dataset
df_global = pd.concat(indicators, axis=0, verify_integrity=False)
df_global.to_csv(cfg.path.output + cfg.globals.csv, index=False)
print('\nEnd of process. Files generated successfully.')
| 33.637795 | 75 | 0.612125 |
from etl.common import to_json_stat, write_to_file
from etl.config_deaths import deaths_cfg as cfg
from etlstat.extractor.extractor import xlsx
import json
import pandas as pd
def transform(df, periods, prefix=''):
for i in range(0, len(df)):
period1 = str(df.loc[i, 'Año'])
period2 = '{:0>2}'.format(df.loc[i, 'Mes'])
df.loc[i, 'period'] = prefix + period1 + '-' + period2
df.drop(columns={'Año', 'Mes'}, axis=1, inplace=True)
df.rename(columns={'period': 'Mes'}, inplace=True)
df = df.tail(periods)
df = df.round(2)
return df
def replace_month(json_str):
json_str = json_str.replace('-01"', '-Ene"')
json_str = json_str.replace('-02"', '-Feb"')
json_str = json_str.replace('-03"', '-Mar"')
json_str = json_str.replace('-04"', '-Abr"')
json_str = json_str.replace('-05"', '-May"')
json_str = json_str.replace('-06"', '-Jun"')
json_str = json_str.replace('-07"', '-Jul"')
json_str = json_str.replace('-08"', '-Ago"')
json_str = json_str.replace('-09"', '-Sep"')
json_str = json_str.replace('-10"', '-Oct"')
json_str = json_str.replace('-11"', '-Nov"')
json_str = json_str.replace('-12"', '-Dic"')
return json_str
data = xlsx(cfg.path.input)
df_global = pd.DataFrame()
indicators = []
for key in cfg.series:
print(key)
variables = [
'Año', 'Mes',
cfg.series[key].variables[0],
cfg.series[key].moving_avg[0]]
if (len(cfg.series[key].variables) == 2):
variables.append(cfg.series[key].variables[1])
variables.append(cfg.series[key].moving_avg[1])
df = data[cfg.file]\
[cfg.series[key].sheet][variables].copy()
df.dropna(axis=0, how='all', inplace=True)
df.rename(
columns={
cfg.series[key].variables[0]: 'Cantabria',
cfg.series[key].moving_avg[0]: 'Cantabria_MM'},
inplace=True)
if (len(cfg.series[key].variables) == 2):
df.rename(
columns={
cfg.series[key].variables[1]: 'España',
cfg.series[key].moving_avg[1]: 'España_MM'},
inplace=True)
df['Año'] = df['Año'].astype(str).replace('\.0', '', regex=True)
df['Mes'] = df['Mes'].astype(str).replace('\.0', '', regex=True)
df_cant = df[['Año', 'Mes', 'Cantabria']].copy()
df_cant = transform(df_cant, cfg.periods.global_deaths, 'Cantabria - ')
df_cant.set_index('Mes', inplace=True)
df_cant = df_cant.transpose()
df_cant.insert(0, 'Categoria', cfg.series[key].category)
df_cant[' - Indicadores'] = cfg.series[key].label
if (len(cfg.series[key].variables) == 2):
df_esp = df[['Año', 'Mes', 'España']].copy()
df_esp = transform(df_esp, cfg.periods.global_deaths, 'España - ')
df_esp.set_index('Mes', inplace=True)
df_esp = df_esp.transpose()
df_esp[' - Indicadores'] = cfg.series[key].label
df_cant = df_cant.merge(df_esp, on=' - Indicadores')
indicators.append(df_cant)
df = transform(df, cfg.periods.deaths)
vars = ['Cantabria', 'Cantabria_MM']
if (len(cfg.series[key].variables) == 2):
vars.append('España')
vars.append('España_MM')
json_file = to_json_stat(
df,
['Mes'],
vars,
cfg.series[key].source)
json_obj = json.loads(json_file)
json_obj['dimension']['Variables']['category']['unit'] = \
cfg.series[key].unit
json_obj['note'] = cfg.series[key].note
json_file = json.dumps(json_obj)
json_file = replace_month(json_file)
write_to_file(json_file, cfg.path.output + cfg.series[key].json)
df_global = pd.concat(indicators, axis=0, verify_integrity=False)
df_global.to_csv(cfg.path.output + cfg.globals.csv, index=False)
print('\nEnd of process. Files generated successfully.')
| true | true |
f726a514c5af450b08e924325a355027db5b2bb3 | 2,355 | py | Python | tests/test_payment_chargebacks.py | elcolumbio/mollie-api-python | 743c7c10df5916bfa14e2c4e82ad5cca17bc2ae3 | [
"BSD-2-Clause"
] | null | null | null | tests/test_payment_chargebacks.py | elcolumbio/mollie-api-python | 743c7c10df5916bfa14e2c4e82ad5cca17bc2ae3 | [
"BSD-2-Clause"
] | 3 | 2018-09-21T12:02:44.000Z | 2018-09-26T12:01:00.000Z | tests/test_payment_chargebacks.py | elcolumbio/mollie-api-python | 743c7c10df5916bfa14e2c4e82ad5cca17bc2ae3 | [
"BSD-2-Clause"
] | null | null | null | from mollie.api.objects.chargeback import Chargeback
from .utils import assert_list_object
PAYMENT_ID = 'tr_7UhSN1zuXS'
CHARGEBACK_ID = 'chb_n9z0tp'
def test_get_payment_chargebacks_by_payment_id(client, response):
"""Get chargebacks relevant to payment by payment id."""
response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list')
chargebacks = client.payment_chargebacks.with_parent_id(PAYMENT_ID).list()
assert_list_object(chargebacks, Chargeback)
def test_get_single_payment_chargeback(client, response):
"""Get a single chargeback relevant to payment by payment id."""
response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID),
'chargeback_single')
chargeback = client.payment_chargebacks.with_parent_id(PAYMENT_ID).get(CHARGEBACK_ID)
assert isinstance(chargeback, Chargeback)
assert chargeback.id == CHARGEBACK_ID
assert chargeback.amount == {'currency': 'USD', 'value': '43.38'}
assert chargeback.settlement_amount == {'currency': 'EUR', 'value': '-35.07'}
assert chargeback.created_at == '2018-03-14T17:00:52.0Z'
assert chargeback.reversed_at == '2018-03-14T17:00:55.0Z'
assert chargeback.payment_id == PAYMENT_ID
def test_list_payment_chargebacks_by_payment_object(client, response):
"""Get a list of chargebacks relevant to payment object."""
response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list')
response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single')
payment = client.payments.get(PAYMENT_ID)
chargebacks = client.payment_chargebacks.on(payment).list()
assert_list_object(chargebacks, Chargeback)
def test_get_single_payment_chargeback_by_payment_object(client, response):
"""Get a single chargeback relevant to payment object."""
response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID),
'chargeback_single')
response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single')
payment = client.payments.get(PAYMENT_ID)
chargeback = client.payment_chargebacks.on(payment).get(CHARGEBACK_ID)
assert isinstance(chargeback, Chargeback)
assert chargeback.payment_id == PAYMENT_ID
| 45.288462 | 102 | 0.745648 | from mollie.api.objects.chargeback import Chargeback
from .utils import assert_list_object
PAYMENT_ID = 'tr_7UhSN1zuXS'
CHARGEBACK_ID = 'chb_n9z0tp'
def test_get_payment_chargebacks_by_payment_id(client, response):
response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list')
chargebacks = client.payment_chargebacks.with_parent_id(PAYMENT_ID).list()
assert_list_object(chargebacks, Chargeback)
def test_get_single_payment_chargeback(client, response):
response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID),
'chargeback_single')
chargeback = client.payment_chargebacks.with_parent_id(PAYMENT_ID).get(CHARGEBACK_ID)
assert isinstance(chargeback, Chargeback)
assert chargeback.id == CHARGEBACK_ID
assert chargeback.amount == {'currency': 'USD', 'value': '43.38'}
assert chargeback.settlement_amount == {'currency': 'EUR', 'value': '-35.07'}
assert chargeback.created_at == '2018-03-14T17:00:52.0Z'
assert chargeback.reversed_at == '2018-03-14T17:00:55.0Z'
assert chargeback.payment_id == PAYMENT_ID
def test_list_payment_chargebacks_by_payment_object(client, response):
response.get('https://api.mollie.com/v2/payments/%s/chargebacks' % PAYMENT_ID, 'chargebacks_list')
response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single')
payment = client.payments.get(PAYMENT_ID)
chargebacks = client.payment_chargebacks.on(payment).list()
assert_list_object(chargebacks, Chargeback)
def test_get_single_payment_chargeback_by_payment_object(client, response):
response.get('https://api.mollie.com/v2/payments/%s/chargebacks/%s' % (PAYMENT_ID, CHARGEBACK_ID),
'chargeback_single')
response.get('https://api.mollie.com/v2/payments/%s' % PAYMENT_ID, 'payment_single')
payment = client.payments.get(PAYMENT_ID)
chargeback = client.payment_chargebacks.on(payment).get(CHARGEBACK_ID)
assert isinstance(chargeback, Chargeback)
assert chargeback.payment_id == PAYMENT_ID
| true | true |
f726a8242f8fd6b97a2dbc1d66d1b2ffa30955db | 4,308 | py | Python | probability_combinatorics/linear_regression.py | codecakes/random_games | 1e670021ec97a196726e937e658878dc63ba9d34 | [
"MIT"
] | null | null | null | probability_combinatorics/linear_regression.py | codecakes/random_games | 1e670021ec97a196726e937e658878dc63ba9d34 | [
"MIT"
] | null | null | null | probability_combinatorics/linear_regression.py | codecakes/random_games | 1e670021ec97a196726e937e658878dc63ba9d34 | [
"MIT"
] | null | null | null | from math import sqrt
from itertools import izip
from numpy import mean
from py_variance_std import t_percentile
def calc_slope(r, sdy, sdx): return r * (float(sdy)/sdx)
def line_fitting(x_arr, y_arr):
"""
using straight line y = mx + c;
m(of a sample data points) = Covariance(X,Y)/Covariance(X,X) =
E[(X - E(X))(Y - E(Y))]/E[(X - E(X))^2]
Another way: Look at calc_slope given STD Y and STD X and r
"""
xbar = mean(x_arr)
ybar = mean(y_arr)
xsqr_bar = mean([i**2 for i in x_arr])
xybar = mean([i*j for i,j in izip(x_arr, y_arr)])
#calcuate the slope m
m = (xbar*ybar - xybar)/(xbar**2 - xsqr_bar)
#calculate the y intercept
c = ybar - m*xbar
return ybar,m,xbar,c
def trace_line(x_arr, y_arr, x_start = 0):
y, m, x, c = line_fitting(x_arr, y_arr)
return [(i, (m*i)+c) for i in [x_start]+list(x_arr)]
def line_error(**params):
"""
The least squares estimates represent the minimum value;
http://www.pmean.com/10/LeastSquares.html
params: x_arr, y_arr, m,c
"""
if 'x_arr' in params and 'y_arr' in params:
if ('m' in params and 'c' in params):
m,c = params['m'], params['c']
else:
y, m, x, c = line_fitting(params['x_arr'], params['y_arr'])
#return difference magnitude between y,actual - y,calculated/predicted
return [(yi - ((m*xi)+c))**2 for yi,xi in izip(params['y_arr'], params['x_arr'])]
def std_error_y_estimate(n, y_line_error_var):
"""
To construct a confidence interval for the slope of the regression line, we need to know the standard error of the sampling distribution of the slope;
n: total samples in x or y;
y_line_error_var: sum(line_error(**params))
df = n-2 since two variables while calculating linear regression.
#calculate \summ(yi - y_cap)^2 variance
line_error_var = line_error(**params)
"""
return sqrt(float(y_line_error_var)/(n-2))
def x_line_std(x_arr):
xbar = mean(x_arr)
return sqrt(sum([(xi - xbar)**2 for xi in x_arr]))
def std_error_linear(se_y, x_line_std):
"""
se_y: from std_error_y_estimate(n, y_line_error_var)
#calculate x - xbar variance and then STD
xbar = mean(x_arr)
x_line_std: x_line_std(x_arr, xbar)
"""
return se_y/x_line_std
def find_std_err_linear(x_arr, y_arr, n_sample):
#Find SE of SEy/SEx
#find descriptive params
ybar,m,xbar,c = line_fitting(x_arr, y_arr)
#find error in x
se_x = x_line_std(x_arr)
#find error in y
y_line_error = sum(line_error(**dict(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))
se_y = std_error_y_estimate(n_sample, y_line_error)
#return standard error
return std_error_linear(se_y, se_x)
def r_squared(x_arr, y_arr):
"""
Literally Trying to do sqrt() of scipy.stats import pearsonr val
using functions in this module: linear_regression.py.
Also called Coefficient of Determination.
It simply means total_variation_line: How much the best fit line is
"fit" Or Away from the scattered points. High value means good fit.
How much % is explained by the Fitted Line.
High R^2 = good model, probably profitable,
Low R^2 = bad model, probably dangerous
"""
y, m, x, c = line_fitting(x_arr, y_arr)
total_var_y = ([(i-y)**2 for i in y_arr]) #(y-ybar)^2
#print sum(total_var_y)
#\summ(yi - mxi * c)^2/\summ(yi - ybar)^2
variation_not_by_line = float(sum(line_error(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))/sum(total_var_y)
#R sqaured
return 1 - variation_not_by_line #total variation in x, variation in line
def calc_tscore_from_r(r2,n):
"""
Hypothesis Testing if relationship is due to sampling error.
r: coefficient of determination
n: number of elements in a sample
Returns: t score
For looking at critical t val and comparing the t score,
df = n-2 since there are 2 variables for correlation under test.
"""
return sqrt(r2*float(n-2)/(1 - r2))
def calc_p_from_tval_from_r(r,n, one_tailed= 0 ):
return t_percentile(calc_tscore_from_r(r,n), n-2, one_tailed= one_tailed)
def margin_error_linear(tscore, se): return tscore * se
def ci_linear(slope, tscore, se):
margin_error = margin_error_linear(tscore, se)
return (slope - margin_error, slope + margin_error)
| 35.311475 | 154 | 0.669452 | from math import sqrt
from itertools import izip
from numpy import mean
from py_variance_std import t_percentile
def calc_slope(r, sdy, sdx): return r * (float(sdy)/sdx)
def line_fitting(x_arr, y_arr):
xbar = mean(x_arr)
ybar = mean(y_arr)
xsqr_bar = mean([i**2 for i in x_arr])
xybar = mean([i*j for i,j in izip(x_arr, y_arr)])
m = (xbar*ybar - xybar)/(xbar**2 - xsqr_bar)
c = ybar - m*xbar
return ybar,m,xbar,c
def trace_line(x_arr, y_arr, x_start = 0):
y, m, x, c = line_fitting(x_arr, y_arr)
return [(i, (m*i)+c) for i in [x_start]+list(x_arr)]
def line_error(**params):
if 'x_arr' in params and 'y_arr' in params:
if ('m' in params and 'c' in params):
m,c = params['m'], params['c']
else:
y, m, x, c = line_fitting(params['x_arr'], params['y_arr'])
return [(yi - ((m*xi)+c))**2 for yi,xi in izip(params['y_arr'], params['x_arr'])]
def std_error_y_estimate(n, y_line_error_var):
return sqrt(float(y_line_error_var)/(n-2))
def x_line_std(x_arr):
xbar = mean(x_arr)
return sqrt(sum([(xi - xbar)**2 for xi in x_arr]))
def std_error_linear(se_y, x_line_std):
return se_y/x_line_std
def find_std_err_linear(x_arr, y_arr, n_sample):
ybar,m,xbar,c = line_fitting(x_arr, y_arr)
se_x = x_line_std(x_arr)
y_line_error = sum(line_error(**dict(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))
se_y = std_error_y_estimate(n_sample, y_line_error)
return std_error_linear(se_y, se_x)
def r_squared(x_arr, y_arr):
y, m, x, c = line_fitting(x_arr, y_arr)
total_var_y = ([(i-y)**2 for i in y_arr])
variation_not_by_line = float(sum(line_error(x_arr=x_arr, y_arr=y_arr, m=m, c=c)))/sum(total_var_y)
return 1 - variation_not_by_line
def calc_tscore_from_r(r2,n):
return sqrt(r2*float(n-2)/(1 - r2))
def calc_p_from_tval_from_r(r,n, one_tailed= 0 ):
return t_percentile(calc_tscore_from_r(r,n), n-2, one_tailed= one_tailed)
def margin_error_linear(tscore, se): return tscore * se
def ci_linear(slope, tscore, se):
margin_error = margin_error_linear(tscore, se)
return (slope - margin_error, slope + margin_error)
| true | true |
f726a835b02eb3b1ea4dadc3134351ab0143ad58 | 1,806 | py | Python | tools/photon_yield.py | LeoRoweBrown/ckvpy | fff27847f5577750ae5860e3fdff81877fa4455a | [
"MIT"
] | null | null | null | tools/photon_yield.py | LeoRoweBrown/ckvpy | fff27847f5577750ae5860e3fdff81877fa4455a | [
"MIT"
] | null | null | null | tools/photon_yield.py | LeoRoweBrown/ckvpy | fff27847f5577750ae5860e3fdff81877fa4455a | [
"MIT"
] | null | null | null | import numpy as np
from scipy.integrate import simps
import scipy.constants as const
def compute(theta_in, f, beta, L, n=None):
"""compute number of photons due to Frank-Tamm and Fresen equations
theta (ndarray/list[float]): Angles in chosen wavelength range
f (ndarray/list[float]): Frequencies in chosen wavelength range
n (ndarray/list[float]): Refractive index in chosen wavelength range
beta (float): Ratio of electron speed to speed of light
TODO: replace n = 1/(beta*np.cos(theta_in)) with actual n_eff
"""
if n is None:
print("Using Cherenkov angle to derive n instead of d(omega)/dk")
n = 1/(beta*np.cos(theta_in))
r_s = np.absolute(
(n*np.cos(theta_in) - np.sqrt(1-(n*np.sin(theta_in)**2.)))/ \
(n*np.cos(theta_in) + np.sqrt(1-(n*np.sin(theta_in)**2.)))
)
r_p = np.absolute(
(n*np.sqrt(1-(n*np.sin(theta_in)**2.)) - np.cos(theta_in))/ \
(n*np.sqrt(1-(n*np.sin(theta_in)**2.)) + np.cos(theta_in))
)
r_eff =(r_p + r_s)/2.
# print(r_eff)
t_eff = 1-r_eff
print("Transmission coeff:", t_eff)
# derive angles inside medium with snell's law for Fresnel equation
# theta_in = np.arcsin(n*np.sin(theta))
# n_photons = \
# (const*fine_structure/(const.hbar*const.c**2.))*\
# simps((1-1./(beta**2.*n**2.))*t_eff, x=const.h*f)
# need even spaced intervals -> interpolate
# integral is over f
f_interp = np.linspace(np.min(f), np.max(f), num=30)
theta_interp = np.interp(f_interp, f, theta_in)
t_eff_interp = np.interp(f_interp, f, t_eff)
n_photons = \
L*(const.fine_structure/(const.hbar*const.c))* \
simps(np.sin(theta_interp)**2.*t_eff_interp*const.h, x=f_interp)
print(n_photons, "photons")
return n_photons | 42 | 73 | 0.633444 | import numpy as np
from scipy.integrate import simps
import scipy.constants as const
def compute(theta_in, f, beta, L, n=None):
if n is None:
print("Using Cherenkov angle to derive n instead of d(omega)/dk")
n = 1/(beta*np.cos(theta_in))
r_s = np.absolute(
(n*np.cos(theta_in) - np.sqrt(1-(n*np.sin(theta_in)**2.)))/ \
(n*np.cos(theta_in) + np.sqrt(1-(n*np.sin(theta_in)**2.)))
)
r_p = np.absolute(
(n*np.sqrt(1-(n*np.sin(theta_in)**2.)) - np.cos(theta_in))/ \
(n*np.sqrt(1-(n*np.sin(theta_in)**2.)) + np.cos(theta_in))
)
r_eff =(r_p + r_s)/2.
t_eff = 1-r_eff
print("Transmission coeff:", t_eff)
# theta_in = np.arcsin(n*np.sin(theta))
# n_photons = \
# (const*fine_structure/(const.hbar*const.c**2.))*\
# simps((1-1./(beta**2.*n**2.))*t_eff, x=const.h*f)
# need even spaced intervals -> interpolate
# integral is over f
f_interp = np.linspace(np.min(f), np.max(f), num=30)
theta_interp = np.interp(f_interp, f, theta_in)
t_eff_interp = np.interp(f_interp, f, t_eff)
n_photons = \
L*(const.fine_structure/(const.hbar*const.c))* \
simps(np.sin(theta_interp)**2.*t_eff_interp*const.h, x=f_interp)
print(n_photons, "photons")
return n_photons | true | true |
f726a842f0367a5bce40537953cbd52aa33b1909 | 4,830 | py | Python | model/network.py | andrewschreiber/numpy-saliency | 2e788a1150f6e160f2271cbb4f20747559f243c0 | [
"MIT"
] | 10 | 2019-07-30T02:36:21.000Z | 2020-12-22T06:35:40.000Z | model/network.py | andrewschreiber/numpy-saliency | 2e788a1150f6e160f2271cbb4f20747559f243c0 | [
"MIT"
] | 6 | 2019-08-09T02:17:38.000Z | 2022-03-11T23:56:24.000Z | model/network.py | andrewschreiber/numpy-saliency | 2e788a1150f6e160f2271cbb4f20747559f243c0 | [
"MIT"
] | 2 | 2019-08-03T08:38:26.000Z | 2020-06-29T12:58:47.000Z | import numpy as np
import pickle
from model.loss import cross_entropy
from model.layers import Conv2D, Maxpool2D, Dense, Flatten, ReLu, Softmax
class LeNet5:
"""Implementation of LeNet 5 for MNIST
http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf
"""
def __init__(self, weights_path=None):
lr = 0.01
layers = []
layers.append(Conv2D(n_filter=6, n_channel=1,
kernel_size=5, padding=2, stride=1,
learning_rate=lr, name='conv1'))
layers.append(ReLu())
layers.append(Maxpool2D(
pool_size=2, stride=2, name='maxpool2'))
layers.append(Conv2D(n_filter=16, n_channel=6,
kernel_size=5, padding=0, stride=1,
learning_rate=lr, name='conv3'))
layers.append(ReLu())
layers.append(Maxpool2D(
pool_size=2, stride=2, name='maxpool4'))
layers.append(Conv2D(n_filter=120, n_channel=16,
kernel_size=5, padding=0, stride=1,
learning_rate=lr, name='conv5'))
layers.append(ReLu())
layers.append(Flatten())
layers.append(Dense(
num_inputs=120, num_outputs=84, learning_rate=lr, name='dense6'))
layers.append(ReLu())
layers.append(Dense(
num_inputs=84, num_outputs=10, learning_rate=lr, name='dense7'))
layers.append(Softmax())
self.layers = layers
if weights_path is not None:
self._load(weights_path)
def _load(self, weights_path):
with open(weights_path, 'rb') as handle:
b = pickle.load(handle)
self.layers[0].load(b[0]['conv1.weights'], b[0]['conv1.bias'])
self.layers[3].load(b[3]['conv3.weights'], b[3]['conv3.bias'])
self.layers[6].load(b[6]['conv5.weights'], b[6]['conv5.bias'])
self.layers[9].load(b[9]['dense6.weights'], b[9]['dense6.bias'])
self.layers[11].load(b[11]['dense7.weights'], b[11]['dense7.bias'])
def train(self, training_data, training_labels, batch_size, epochs,
weights_path):
print("Training LeNet...")
total_acc = 0
for epoch in range(epochs):
# batch training data
for batch_index in range(0, training_data.shape[0], batch_size):
loss = 0
acc = 0
data = training_data[batch_index:batch_index+batch_size]
labels = training_labels[batch_index:batch_index+batch_size]
# iterate over batch
for b in range(len(data)):
x = data[b]
y = labels[b]
# forward pass
output = self.forward(x)
if np.argmax(output) == np.argmax(y):
acc += 1
total_acc += 1
loss += cross_entropy(output, y)
# backward pass
# update network on each datapoint for simplicity
dy = y
for l in range(len(self.layers)-1, -1, -1):
dout = self.layers[l].backward(dy)
dy = dout
# print performance
loss /= len(data)
batch_acc = float(acc)/float(len(data))
train_acc = float(total_acc) / \
float((batch_index+len(data)+epoch*len(training_data)))
print(('| Epoch: {0:d}/{1:d} | Iter:{2:d} | Loss: {3:.2f} | ' +
'BatchAcc: {4:.2f} | TrainAcc: {5:.2f} |')
.format(epoch+1, epochs, batch_index+len(data),
loss, batch_acc, train_acc))
# save parameters after each epoch
print("Saving model to", weights_path)
layers = [layer.parameters() for layer in self.layers]
with open(weights_path, 'wb') as handle:
pickle.dump(layers, handle, protocol=pickle.HIGHEST_PROTOCOL)
def forward(self, x):
for l in range(len(self.layers)):
output = self.layers[l].forward(x)
x = output
return output
def predict(self, x):
output = self.forward(x)
digit = np.argmax(output)
probability = output[0, digit]
return digit, probability
def test(self, data, labels):
print("Testing LeNet...")
total_acc = 0
test_size = len(data)
for i in range(test_size):
x = data[i]
y = labels[i]
if np.argmax(self.forward(x)) == np.argmax(y):
total_acc += 1
print("== Correct: {}/{}. Accuracy: {} =="
.format(total_acc, test_size, total_acc/test_size))
| 38.951613 | 79 | 0.522774 | import numpy as np
import pickle
from model.loss import cross_entropy
from model.layers import Conv2D, Maxpool2D, Dense, Flatten, ReLu, Softmax
class LeNet5:
def __init__(self, weights_path=None):
lr = 0.01
layers = []
layers.append(Conv2D(n_filter=6, n_channel=1,
kernel_size=5, padding=2, stride=1,
learning_rate=lr, name='conv1'))
layers.append(ReLu())
layers.append(Maxpool2D(
pool_size=2, stride=2, name='maxpool2'))
layers.append(Conv2D(n_filter=16, n_channel=6,
kernel_size=5, padding=0, stride=1,
learning_rate=lr, name='conv3'))
layers.append(ReLu())
layers.append(Maxpool2D(
pool_size=2, stride=2, name='maxpool4'))
layers.append(Conv2D(n_filter=120, n_channel=16,
kernel_size=5, padding=0, stride=1,
learning_rate=lr, name='conv5'))
layers.append(ReLu())
layers.append(Flatten())
layers.append(Dense(
num_inputs=120, num_outputs=84, learning_rate=lr, name='dense6'))
layers.append(ReLu())
layers.append(Dense(
num_inputs=84, num_outputs=10, learning_rate=lr, name='dense7'))
layers.append(Softmax())
self.layers = layers
if weights_path is not None:
self._load(weights_path)
def _load(self, weights_path):
with open(weights_path, 'rb') as handle:
b = pickle.load(handle)
self.layers[0].load(b[0]['conv1.weights'], b[0]['conv1.bias'])
self.layers[3].load(b[3]['conv3.weights'], b[3]['conv3.bias'])
self.layers[6].load(b[6]['conv5.weights'], b[6]['conv5.bias'])
self.layers[9].load(b[9]['dense6.weights'], b[9]['dense6.bias'])
self.layers[11].load(b[11]['dense7.weights'], b[11]['dense7.bias'])
def train(self, training_data, training_labels, batch_size, epochs,
weights_path):
print("Training LeNet...")
total_acc = 0
for epoch in range(epochs):
for batch_index in range(0, training_data.shape[0], batch_size):
loss = 0
acc = 0
data = training_data[batch_index:batch_index+batch_size]
labels = training_labels[batch_index:batch_index+batch_size]
for b in range(len(data)):
x = data[b]
y = labels[b]
output = self.forward(x)
if np.argmax(output) == np.argmax(y):
acc += 1
total_acc += 1
loss += cross_entropy(output, y)
dy = y
for l in range(len(self.layers)-1, -1, -1):
dout = self.layers[l].backward(dy)
dy = dout
loss /= len(data)
batch_acc = float(acc)/float(len(data))
train_acc = float(total_acc) / \
float((batch_index+len(data)+epoch*len(training_data)))
print(('| Epoch: {0:d}/{1:d} | Iter:{2:d} | Loss: {3:.2f} | ' +
'BatchAcc: {4:.2f} | TrainAcc: {5:.2f} |')
.format(epoch+1, epochs, batch_index+len(data),
loss, batch_acc, train_acc))
print("Saving model to", weights_path)
layers = [layer.parameters() for layer in self.layers]
with open(weights_path, 'wb') as handle:
pickle.dump(layers, handle, protocol=pickle.HIGHEST_PROTOCOL)
def forward(self, x):
for l in range(len(self.layers)):
output = self.layers[l].forward(x)
x = output
return output
def predict(self, x):
output = self.forward(x)
digit = np.argmax(output)
probability = output[0, digit]
return digit, probability
def test(self, data, labels):
print("Testing LeNet...")
total_acc = 0
test_size = len(data)
for i in range(test_size):
x = data[i]
y = labels[i]
if np.argmax(self.forward(x)) == np.argmax(y):
total_acc += 1
print("== Correct: {}/{}. Accuracy: {} =="
.format(total_acc, test_size, total_acc/test_size))
| true | true |
f726aa04174ce7bf2f5c510516bdd17021d883d8 | 6,175 | py | Python | deepecg/training/model/disc/model.py | Seb-Good/deepecg | c99fbe80718ee9969936154ae2c1a04d81c9b246 | [
"MIT"
] | 56 | 2019-02-20T04:47:25.000Z | 2022-03-23T01:12:43.000Z | deepecg/training/model/disc/model.py | vivektalwar13071999/deepecg | c99fbe80718ee9969936154ae2c1a04d81c9b246 | [
"MIT"
] | 7 | 2019-12-16T20:59:36.000Z | 2022-02-09T23:48:59.000Z | deepecg/training/model/disc/model.py | vivektalwar13071999/deepecg | c99fbe80718ee9969936154ae2c1a04d81c9b246 | [
"MIT"
] | 22 | 2019-02-24T02:57:20.000Z | 2022-03-23T01:12:49.000Z | """
model.py
--------
This module provides a class and methods for building and managing a model with tensorflow.
By: Sebastian D. Goodfellow, Ph.D., 2018
"""
# Compatibility imports
from __future__ import absolute_import, division, print_function
# 3rd party imports
import os
import sys
import json
import pickle
import tensorflow as tf
# Local imports
from deepecg.training.model.disc.graph import Graph
from deepecg.training.networks.deep_ecg_v1 import DeepECGV1
from deepecg.training.networks.deep_ecg_v2 import DeepECGV2
from deepecg.training.networks.deep_ecg_v3 import DeepECGV3
from deepecg.training.networks.deep_ecg_v4 import DeepECGV4
from deepecg.training.networks.deep_ecg_v5 import DeepECGV5
from deepecg.training.networks.deep_ecg_v6 import DeepECGV6
from deepecg.training.networks.deep_ecg_v7 import DeepECGV7
class Model(object):
"""A class for managing a model through training."""
def __init__(self, model_name, network_name, network_parameters, save_path, data_path, max_to_keep):
# Set input parameters
self.model_name = model_name
self.network_name = network_name
self.network_parameters = network_parameters
self.save_path = os.path.join(save_path, self.model_name)
self.data_path = data_path
self.max_to_keep = max_to_keep
# Set attributes
self.sess = None
self.graph = None
self.network = None
# Create project file structure
self._create_folder_structure()
# Save parameters
self._save_parameters()
# Initialize graph
self.initialize_graph()
def initialize_graph(self):
# Get neural network
self.network = self._get_neural_network()
# Save network object
self._pickle_network()
# Build computational graph
self.graph = Graph(network=self.network, save_path=self.save_path, data_path=self.data_path,
max_to_keep=self.max_to_keep)
# Start session
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
# Initialize global variables
self.sess.run(self.graph.init_global)
@classmethod
def build_training_graph(cls, save_path):
"""Build training graph."""
# Import model parameters
model_parameters = cls._import_model_parameters(save_path=save_path)
# Import network parameters
network_parameters = cls._import_network_parameters(save_path=save_path)
# Initialize Model
return cls(model_name=model_parameters['model_name'], network_name=model_parameters['network_name'],
network_parameters=network_parameters, save_path=os.path.dirname(save_path),
data_path=model_parameters['data_path'], max_to_keep=model_parameters['max_to_keep'])
def restore(self, global_step):
"""Restore model from checkpoint."""
# Initialize graph
if self.sess._closed:
self.initialize_graph()
# Restore checkpoint
self.graph.saver.restore(sess=self.sess, save_path=os.path.join(self.save_path, 'checkpoints', global_step))
def close_session(self):
"""Close any active sessions."""
try:
self.sess.close()
except AttributeError:
print('No active Tensorflow session.')
def _save_parameters(self):
"""Save model and network parameters to JSON."""
# Save model parameters
self._save_model_parameters()
# Save network parameters
self._save_network_parameters()
def _save_model_parameters(self):
"""Save model parameters to JSON."""
# Get model parameters
model_parameters = dict(model_name=self.model_name, network_name=self.network_name, save_path=self.save_path,
data_path=self.data_path, max_to_keep=self.max_to_keep)
# Save model parameters to JSON
if not os.path.exists(os.path.join(self.save_path, 'parameters', 'model_parameters.json')):
with open(os.path.join(self.save_path, 'parameters', 'model_parameters.json'), 'w') as file:
json.dump(model_parameters, file)
def _save_network_parameters(self):
"""Save network parameters to JSON."""
if not os.path.exists(os.path.join(self.save_path, 'parameters', 'network_parameters.json')):
with open(os.path.join(self.save_path, 'parameters', 'network_parameters.json'), 'w') as file:
json.dump(self.network_parameters, file)
def _get_neural_network(self):
"""Instantiate neural network."""
# Convert string to class
network = getattr(sys.modules[__name__], self.network_name)
# Instantiate network class with network parameters
network = network(**self.network_parameters)
return network
def _create_folder_structure(self):
# Set list of folders
folders = ['train', 'val', 'checkpoints', 'network', 'graph', 'logs', 'parameters']
# Main project directory
if not os.path.exists(self.save_path):
os.makedirs(self.save_path)
# Loop through and create project folders
for folder in folders:
self._create_folder(folder=folder)
def _create_folder(self, folder):
"""Create folder."""
if not os.path.exists(os.path.join(self.save_path, folder)):
os.makedirs(os.path.join(self.save_path, folder))
def _pickle_network(self):
"""Pickle graph."""
with open(os.path.join(self.save_path, 'network', 'network.obj'), 'wb') as file:
pickle.dump(obj=self.network, file=file)
@staticmethod
def _import_model_parameters(save_path):
"""Import model parameters."""
with open(os.path.join(save_path, 'parameters', 'model_parameters.json')) as file:
return json.load(file)
@staticmethod
def _import_network_parameters(save_path):
"""Import network parameters."""
with open(os.path.join(save_path, 'parameters', 'network_parameters.json')) as file:
return json.load(file)
| 35.488506 | 117 | 0.674494 |
from __future__ import absolute_import, division, print_function
import os
import sys
import json
import pickle
import tensorflow as tf
from deepecg.training.model.disc.graph import Graph
from deepecg.training.networks.deep_ecg_v1 import DeepECGV1
from deepecg.training.networks.deep_ecg_v2 import DeepECGV2
from deepecg.training.networks.deep_ecg_v3 import DeepECGV3
from deepecg.training.networks.deep_ecg_v4 import DeepECGV4
from deepecg.training.networks.deep_ecg_v5 import DeepECGV5
from deepecg.training.networks.deep_ecg_v6 import DeepECGV6
from deepecg.training.networks.deep_ecg_v7 import DeepECGV7
class Model(object):
def __init__(self, model_name, network_name, network_parameters, save_path, data_path, max_to_keep):
self.model_name = model_name
self.network_name = network_name
self.network_parameters = network_parameters
self.save_path = os.path.join(save_path, self.model_name)
self.data_path = data_path
self.max_to_keep = max_to_keep
self.sess = None
self.graph = None
self.network = None
self._create_folder_structure()
self._save_parameters()
self.initialize_graph()
def initialize_graph(self):
self.network = self._get_neural_network()
self._pickle_network()
self.graph = Graph(network=self.network, save_path=self.save_path, data_path=self.data_path,
max_to_keep=self.max_to_keep)
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(self.graph.init_global)
@classmethod
def build_training_graph(cls, save_path):
model_parameters = cls._import_model_parameters(save_path=save_path)
network_parameters = cls._import_network_parameters(save_path=save_path)
return cls(model_name=model_parameters['model_name'], network_name=model_parameters['network_name'],
network_parameters=network_parameters, save_path=os.path.dirname(save_path),
data_path=model_parameters['data_path'], max_to_keep=model_parameters['max_to_keep'])
def restore(self, global_step):
if self.sess._closed:
self.initialize_graph()
self.graph.saver.restore(sess=self.sess, save_path=os.path.join(self.save_path, 'checkpoints', global_step))
def close_session(self):
try:
self.sess.close()
except AttributeError:
print('No active Tensorflow session.')
def _save_parameters(self):
self._save_model_parameters()
self._save_network_parameters()
def _save_model_parameters(self):
model_parameters = dict(model_name=self.model_name, network_name=self.network_name, save_path=self.save_path,
data_path=self.data_path, max_to_keep=self.max_to_keep)
if not os.path.exists(os.path.join(self.save_path, 'parameters', 'model_parameters.json')):
with open(os.path.join(self.save_path, 'parameters', 'model_parameters.json'), 'w') as file:
json.dump(model_parameters, file)
def _save_network_parameters(self):
if not os.path.exists(os.path.join(self.save_path, 'parameters', 'network_parameters.json')):
with open(os.path.join(self.save_path, 'parameters', 'network_parameters.json'), 'w') as file:
json.dump(self.network_parameters, file)
def _get_neural_network(self):
network = getattr(sys.modules[__name__], self.network_name)
network = network(**self.network_parameters)
return network
def _create_folder_structure(self):
folders = ['train', 'val', 'checkpoints', 'network', 'graph', 'logs', 'parameters']
if not os.path.exists(self.save_path):
os.makedirs(self.save_path)
for folder in folders:
self._create_folder(folder=folder)
def _create_folder(self, folder):
if not os.path.exists(os.path.join(self.save_path, folder)):
os.makedirs(os.path.join(self.save_path, folder))
def _pickle_network(self):
with open(os.path.join(self.save_path, 'network', 'network.obj'), 'wb') as file:
pickle.dump(obj=self.network, file=file)
@staticmethod
def _import_model_parameters(save_path):
with open(os.path.join(save_path, 'parameters', 'model_parameters.json')) as file:
return json.load(file)
@staticmethod
def _import_network_parameters(save_path):
with open(os.path.join(save_path, 'parameters', 'network_parameters.json')) as file:
return json.load(file)
| true | true |
f726aa89dee842342ea1bd383144960b734ac342 | 607 | py | Python | setup.py | Yoshiki443/weather_parameters | ae2c9ed02f68968cb6ea0610d556f3c68bbc923e | [
"MIT"
] | 17 | 2020-04-26T20:25:56.000Z | 2022-03-10T09:41:54.000Z | setup.py | Yoshiki443/weather_parameters | ae2c9ed02f68968cb6ea0610d556f3c68bbc923e | [
"MIT"
] | null | null | null | setup.py | Yoshiki443/weather_parameters | ae2c9ed02f68968cb6ea0610d556f3c68bbc923e | [
"MIT"
] | 1 | 2020-06-08T04:54:30.000Z | 2020-06-08T04:54:30.000Z | import setuptools
setuptools.setup(
name="wxparams",
version="1.5",
author="Yoshiki Kato",
# author_email="",
description="Weather Parameters Calculator",
long_description="This is a python module for calculating meteorological parameters.",
long_description_content_type="text/markdown",
url="https://github.com/Yoshiki443/weather_parameters",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
license='MIT'
)
| 30.35 | 90 | 0.678748 | import setuptools
setuptools.setup(
name="wxparams",
version="1.5",
author="Yoshiki Kato",
description="Weather Parameters Calculator",
long_description="This is a python module for calculating meteorological parameters.",
long_description_content_type="text/markdown",
url="https://github.com/Yoshiki443/weather_parameters",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
license='MIT'
)
| true | true |
f726aacd3954efc8b82de1b378ebd375941886de | 6,348 | py | Python | Testing/ND-Testing.py | garibaldu/boundary-seekers | 441fea01e93de882bf22e0deb411f0b10602fa37 | [
"MIT"
] | null | null | null | Testing/ND-Testing.py | garibaldu/boundary-seekers | 441fea01e93de882bf22e0deb411f0b10602fa37 | [
"MIT"
] | null | null | null | Testing/ND-Testing.py | garibaldu/boundary-seekers | 441fea01e93de882bf22e0deb411f0b10602fa37 | [
"MIT"
] | null | null | null | import numpy as np
import tensorflow as tf
def __perms(n):
if not n:
return
p = []
for i in range(0, 2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
s_prime = np.array(list(map(lambda x: int(x), list(s))))
p.append(s_prime)
return p
def care(normal, bias, example):
z = np.dot(normal, example) + bias
return 1.0/(1.0 + np.exp(-z))
def deci(normal, bias, example):
z = np.dot(normal, example) + bias
return 1.0/(1.0 + np.exp(-z))
def sigmoid(phi):
return 1.0/(1.0 + tf.exp(-phi))
def compute_penalty(weights, size):
mask = np.concatenate((np.array([0], dtype=np.float32), np.ones(size, dtype=np.float32)))
return tf.reduce_sum(tf.abs(tf.multiply(mask, weights)))
def train_boundary_hunter(points, out, iterations):
in_size = len(points[0])
out_size = 1
inputs = tf.placeholder('float32', [in_size])
targets = tf.placeholder('float32', [out_size])
hidden_weights = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1, in_size+1)), dtype='float32')
gate_weights = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1, in_size+1)), dtype='float32')
byas = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1)), dtype='float32')
#output_weights = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(out_size, num_centroids + 1)), dtype='float32')
inputs_prime = tf.concat([[1.0], inputs], axis=0)
# Peform Computation
# Peform Computation
prob = tf.reduce_sum(tf.multiply(inputs_prime, hidden_weights), 1)
g = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, gate_weights), 1))
#hidden_out = tf.add(byas, tf.multiply(g, tf.subtract(prob, byas)))
hidden_out = sigmoid(tf.add(g * prob, (1-g) * byas))
reward = tf.log(compute_penalty(hidden_weights, in_size) + compute_penalty(gate_weights, in_size))
targets_prime = tf.expand_dims(targets, 1)
output = hidden_out
errors = -(targets_prime * tf.log(output) + (1 -targets_prime) * tf.log(1 - output))#tf.pow(tf.subtract(tf.expand_dims(targets, 1), output), 2.0)
error = tf.reduce_sum(errors)
minimize = error - 0.02 * reward
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(minimize)
#clip_byas = tf.assign(byas, tf.clip_by_value(byas, 0, 1))
model = tf.global_variables_initializer()
with tf.Session() as session:
session.run(model)
for e in range(iterations):
for d in range(len(points)):
session.run(train_op, feed_dict={inputs: points[d], targets: [out[d]]})
#session.run(clip_byas)
if e % 10 == 0:
print(session.run(byas))
err = 0
for d in range(len(points)):
err += session.run(error, feed_dict={inputs: points[d], targets: [out[d]]})
print(err)
print(session.run(reward))
print()
gates = session.run(gate_weights)[0]
byas = session.run(byas)[0]
boundarys = session.run(hidden_weights)[0]
return (boundarys, gates, byas)
def get_final_class(predictions):
tally_0 = 0
tally_1 = 0
for p in predictions:
if (not p == None) and p >= 0.5:
tally_1 += 1
elif (not p == None) and p < 0.5:
tally_0 += 1
if tally_0 == 0 and tally_1 == 0:
return None
return 0 if tally_0 > tally_1 else 1
def run_boundary_hunters(boundarys, gates, points, out):
in_size = len(points[0])
out_size = 1
inputs = tf.placeholder('float32', [in_size])
targets = tf.placeholder('float32', [out_size])
hidden_weights = tf.placeholder('float32', [None])
gate_weights = tf.placeholder('float32', [None])
inputs_prime = tf.concat([[1.0], inputs], axis=0)
g = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, gate_weights)))
prob = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, hidden_weights)))
model = tf.global_variables_initializer()
unsure = 0
guessed = 0
correct = 0
with tf.Session() as session:
session.run(model)
for d in range(len(points)):
predictions = []
for b in range(len(boundarys)):
prediction = None
care = session.run(g, feed_dict={inputs: points[d], hidden_weights: boundarys[b], gate_weights: gates[b]})
if care > 0.5:
prediction = session.run(prob, feed_dict={inputs: points[d], hidden_weights: boundarys[b], gate_weights: gates[b]})
predictions.append(prediction)
p = get_final_class(predictions)
#print(predictions, ": ", p)
if not p == None:
guessed += 1
if p == out[d]:
correct += 1
elif p == None:
unsure += 1
return float(correct)/float(guessed), float(unsure)/float(len(points))
N = 7
# Generate All Points On Hypercube
examples = __perms(N)
targets = []
# Generate Boundary Hunter
bias = np.random.uniform(0, 1, 1)
decision = np.random.uniform(-1, 1, N)
decision_b = np.random.uniform(-1, 1, 1)
caring = np.random.uniform(-1, 1, N)
caring_b = np.random.uniform(-1, 1, 1)
uncertian = 0
class1 = 0
class0 = 0
for example in examples:
clas = None
c = care(caring, caring_b, example)
if c < 0.5:
uncertian += 1
r = np.random.rand(1)
if r > bias:
clas = 1
else:
clas = 0
else:
d = deci(decision, decision_b, example)
if d >= 0.5:
clas = 1
class1 += 1
else:
clas=0
class0 += 1
targets.append(clas)
if class0 == 0 or class1 == 0:
print("Class 0: ", class0)
print("Class 1: ", class1)
print("Err")
raise "GSFE"
bh = train_boundary_hunter(examples, targets, 20000)
print("Uncertian: ", uncertian)
print("Class 0: ", class0)
print("Class 1: ", class1)
print("Bias: ", bias)
print("{}, {}".format(decision_b, decision))
print("{}, {}".format(caring_b, caring))
print(run_boundary_hunters([np.concatenate((decision_b, decision))], [np.concatenate((caring_b, caring))], examples, targets))
print()
print(bh)
print(run_boundary_hunters([bh[0]], [bh[1]], examples, targets))
| 29.943396 | 150 | 0.594045 | import numpy as np
import tensorflow as tf
def __perms(n):
if not n:
return
p = []
for i in range(0, 2**n):
s = bin(i)[2:]
s = "0" * (n-len(s)) + s
s_prime = np.array(list(map(lambda x: int(x), list(s))))
p.append(s_prime)
return p
def care(normal, bias, example):
z = np.dot(normal, example) + bias
return 1.0/(1.0 + np.exp(-z))
def deci(normal, bias, example):
z = np.dot(normal, example) + bias
return 1.0/(1.0 + np.exp(-z))
def sigmoid(phi):
return 1.0/(1.0 + tf.exp(-phi))
def compute_penalty(weights, size):
mask = np.concatenate((np.array([0], dtype=np.float32), np.ones(size, dtype=np.float32)))
return tf.reduce_sum(tf.abs(tf.multiply(mask, weights)))
def train_boundary_hunter(points, out, iterations):
in_size = len(points[0])
out_size = 1
inputs = tf.placeholder('float32', [in_size])
targets = tf.placeholder('float32', [out_size])
hidden_weights = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1, in_size+1)), dtype='float32')
gate_weights = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1, in_size+1)), dtype='float32')
byas = tf.Variable(np.random.uniform(low=-0.5, high=0.5, size=(1)), dtype='float32')
inputs_prime = tf.concat([[1.0], inputs], axis=0)
prob = tf.reduce_sum(tf.multiply(inputs_prime, hidden_weights), 1)
g = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, gate_weights), 1))
hidden_out = sigmoid(tf.add(g * prob, (1-g) * byas))
reward = tf.log(compute_penalty(hidden_weights, in_size) + compute_penalty(gate_weights, in_size))
targets_prime = tf.expand_dims(targets, 1)
output = hidden_out
errors = -(targets_prime * tf.log(output) + (1 -targets_prime) * tf.log(1 - output))
error = tf.reduce_sum(errors)
minimize = error - 0.02 * reward
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(minimize)
model = tf.global_variables_initializer()
with tf.Session() as session:
session.run(model)
for e in range(iterations):
for d in range(len(points)):
session.run(train_op, feed_dict={inputs: points[d], targets: [out[d]]})
if e % 10 == 0:
print(session.run(byas))
err = 0
for d in range(len(points)):
err += session.run(error, feed_dict={inputs: points[d], targets: [out[d]]})
print(err)
print(session.run(reward))
print()
gates = session.run(gate_weights)[0]
byas = session.run(byas)[0]
boundarys = session.run(hidden_weights)[0]
return (boundarys, gates, byas)
def get_final_class(predictions):
tally_0 = 0
tally_1 = 0
for p in predictions:
if (not p == None) and p >= 0.5:
tally_1 += 1
elif (not p == None) and p < 0.5:
tally_0 += 1
if tally_0 == 0 and tally_1 == 0:
return None
return 0 if tally_0 > tally_1 else 1
def run_boundary_hunters(boundarys, gates, points, out):
in_size = len(points[0])
out_size = 1
inputs = tf.placeholder('float32', [in_size])
targets = tf.placeholder('float32', [out_size])
hidden_weights = tf.placeholder('float32', [None])
gate_weights = tf.placeholder('float32', [None])
inputs_prime = tf.concat([[1.0], inputs], axis=0)
g = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, gate_weights)))
prob = sigmoid(tf.reduce_sum(tf.multiply(inputs_prime, hidden_weights)))
model = tf.global_variables_initializer()
unsure = 0
guessed = 0
correct = 0
with tf.Session() as session:
session.run(model)
for d in range(len(points)):
predictions = []
for b in range(len(boundarys)):
prediction = None
care = session.run(g, feed_dict={inputs: points[d], hidden_weights: boundarys[b], gate_weights: gates[b]})
if care > 0.5:
prediction = session.run(prob, feed_dict={inputs: points[d], hidden_weights: boundarys[b], gate_weights: gates[b]})
predictions.append(prediction)
p = get_final_class(predictions)
if not p == None:
guessed += 1
if p == out[d]:
correct += 1
elif p == None:
unsure += 1
return float(correct)/float(guessed), float(unsure)/float(len(points))
N = 7
examples = __perms(N)
targets = []
bias = np.random.uniform(0, 1, 1)
decision = np.random.uniform(-1, 1, N)
decision_b = np.random.uniform(-1, 1, 1)
caring = np.random.uniform(-1, 1, N)
caring_b = np.random.uniform(-1, 1, 1)
uncertian = 0
class1 = 0
class0 = 0
for example in examples:
clas = None
c = care(caring, caring_b, example)
if c < 0.5:
uncertian += 1
r = np.random.rand(1)
if r > bias:
clas = 1
else:
clas = 0
else:
d = deci(decision, decision_b, example)
if d >= 0.5:
clas = 1
class1 += 1
else:
clas=0
class0 += 1
targets.append(clas)
if class0 == 0 or class1 == 0:
print("Class 0: ", class0)
print("Class 1: ", class1)
print("Err")
raise "GSFE"
bh = train_boundary_hunter(examples, targets, 20000)
print("Uncertian: ", uncertian)
print("Class 0: ", class0)
print("Class 1: ", class1)
print("Bias: ", bias)
print("{}, {}".format(decision_b, decision))
print("{}, {}".format(caring_b, caring))
print(run_boundary_hunters([np.concatenate((decision_b, decision))], [np.concatenate((caring_b, caring))], examples, targets))
print()
print(bh)
print(run_boundary_hunters([bh[0]], [bh[1]], examples, targets))
| true | true |
f726aafdc70d344f7835f59ea676ff8263ce502c | 6,600 | py | Python | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/plugins/xh_gizmos.py | ekkipermana/robotframework-test | 243ca26f69962f8cf20cd7d054e0ff3e709bc7f4 | [
"bzip2-1.0.6"
] | 27 | 2020-11-12T19:24:54.000Z | 2022-03-27T23:10:45.000Z | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/plugins/xh_gizmos.py | ekkipermana/robotframework-test | 243ca26f69962f8cf20cd7d054e0ff3e709bc7f4 | [
"bzip2-1.0.6"
] | 2 | 2020-11-02T06:30:39.000Z | 2022-02-23T18:39:55.000Z | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/XRCed/plugins/xh_gizmos.py | ekkipermana/robotframework-test | 243ca26f69962f8cf20cd7d054e0ff3e709bc7f4 | [
"bzip2-1.0.6"
] | 7 | 2018-02-13T10:22:39.000Z | 2019-07-04T07:39:28.000Z | # Name: gizmos.py
# Purpose: XML handlers for wx.gismos classes
# Author: Roman Rolinsky <rolinsky@femagsoft.com>
# Created: 09.07.2007
# RCS-ID: $Id$
import wx
import wx.xrc as xrc
import wx.gizmos as gizmos
class LEDNumberCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxLED_ALIGN_LEFT', gizmos.LED_ALIGN_LEFT)
self.AddStyle('wxLED_ALIGN_RIGHT', gizmos.LED_ALIGN_RIGHT)
self.AddStyle('wxLED_ALIGN_CENTER', gizmos.LED_ALIGN_CENTER)
self.AddStyle('wxLED_DRAW_FADED', gizmos.LED_DRAW_FADED)
def CanHandle(self,node):
return self.IsOfClass(node, 'LEDNumberCtrl')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.LEDNumberCtrl(self.GetParentAsWindow(),
self.GetID(),
self.GetPosition(),
self.GetSize(),
self.GetStyle())
# wxLED_ALIGN_MASK was incorrect
align = self.GetStyle() & 7
if align: w.SetAlignment(self.GetStyle() & 7)
w.SetValue(self.GetText('value'))
self.SetupWindow(w)
return w
class EditableListBoxXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxEL_ALLOW_NEW', gizmos.EL_ALLOW_NEW)
self.AddStyle('wxEL_ALLOW_EDIT', gizmos.EL_ALLOW_EDIT)
self.AddStyle('wxEL_ALLOW_DELETE', gizmos.EL_ALLOW_DELETE)
def CanHandle(self, node):
return self.IsOfClass(node, 'EditableListBox')
# return self.IsOfClass(node, 'EditableListBox') or \
# self.insideBox and node.GetName() == 'item'
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.EditableListBox(self.GetParentAsWindow(),
self.GetID(),
self.GetText("label"),
self.GetPosition(),
self.GetSize(),
self.GetStyle(),
self.GetName())
# Doesn't work
#self.insideBox = True
#self.CreateChildrenPrivately(None, self.GetParamNode('content'))
#self.insideBox = False
# Long way
strings = []
n = self.GetParamNode('content')
if n: n = n.GetChildren()
while n:
if n.GetType() != xrc.XML_ELEMENT_NODE or n.GetName() != "item":
n = n.GetNext()
continue
strings.append(n.GetNodeContent())
n = n.GetNext()
w.SetStrings(strings)
self.SetupWindow(w)
return w
class TreeListCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxDEFAULT_COL_WIDTH', gizmos.DEFAULT_COL_WIDTH)
self.AddStyle('wxTL_MODE_NAV_FULLTREE', gizmos.TL_MODE_NAV_FULLTREE)
self.AddStyle('wxTL_MODE_NAV_EXPANDED', gizmos.TL_MODE_NAV_EXPANDED)
self.AddStyle('wxTL_MODE_NAV_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)
self.AddStyle('wxTL_MODE_NAV_LEVEL', gizmos.TL_MODE_NAV_LEVEL)
self.AddStyle('wxTL_MODE_FIND_EXACT', gizmos.TL_MODE_FIND_EXACT)
self.AddStyle('wxTL_MODE_FIND_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)
self.AddStyle('wxTL_MODE_FIND_NOCASE', gizmos.TL_MODE_FIND_NOCASE)
self.AddStyle('wxTREE_HITTEST_ONITEMCOLUMN', gizmos.TREE_HITTEST_ONITEMCOLUMN)
self.AddStyle('wxTR_COLUMN_LINES', gizmos.TR_COLUMN_LINES)
self.AddStyle('wxTR_VIRTUAL', gizmos.TR_VIRTUAL)
self.AddStyle('wxTL_ALIGN_LEFT ', wx.ALIGN_LEFT)
self.AddStyle('wxTL_ALIGN_RIGHT ', wx.ALIGN_RIGHT)
self.AddStyle('wxTL_ALIGN_CENTER', wx.ALIGN_CENTER)
self.AddStyle('wxTL_SEARCH_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)
self.AddStyle('wxTL_SEARCH_LEVEL ', gizmos.TL_MODE_NAV_LEVEL)
self.AddStyle('wxTL_SEARCH_FULL ', gizmos.TL_MODE_FIND_EXACT)
self.AddStyle('wxTL_SEARCH_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)
self.AddStyle('wxTL_SEARCH_NOCASE ', gizmos.TL_MODE_FIND_NOCASE)
self.AddStyle('wxTR_DONT_ADJUST_MAC', gizmos.TR_DONT_ADJUST_MAC)
self.AddStyle('wxTR_DEFAULT_STYLE', wx.TR_DEFAULT_STYLE)
def CanHandle(self, node):
return self.IsOfClass(node, 'TreeListCtrl')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.TreeListCtrl(self.GetParentAsWindow(),
self.GetID(),
style=self.GetStyle(),
name=self.GetName())
w.AddColumn("Main column")
w.AddColumn('Column 1')
w.SetMainColumn(0)
w.SetColumnWidth(0, 50)
w.SetColumnWidth(1, 50)
root = w.AddRoot('Root')
w.SetItemText(root, "col 1", 1)
item1 = w.AppendItem(root, 'item 1')
w.SetItemText(item1, "col 1", 1)
w.Expand(root)
return w
class DynamicSashWindowXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxDS_MANAGE_SCROLLBARS', gizmos.DS_MANAGE_SCROLLBARS)
self.AddStyle('wxDS_DRAG_CORNER', gizmos.DS_DRAG_CORNER)
def CanHandle(self, node):
return self.IsOfClass(node, 'DynamicSashWindow')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.DynamicSashWindow(self.GetParentAsWindow(),
self.GetID(),
self.GetPosition(),
self.GetSize(),
self.GetStyle(),
self.GetName())
self.SetupWindow(w)
return w
| 39.285714 | 86 | 0.601667 |
import wx
import wx.xrc as xrc
import wx.gizmos as gizmos
class LEDNumberCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
self.AddWindowStyles()
self.AddStyle('wxLED_ALIGN_LEFT', gizmos.LED_ALIGN_LEFT)
self.AddStyle('wxLED_ALIGN_RIGHT', gizmos.LED_ALIGN_RIGHT)
self.AddStyle('wxLED_ALIGN_CENTER', gizmos.LED_ALIGN_CENTER)
self.AddStyle('wxLED_DRAW_FADED', gizmos.LED_DRAW_FADED)
def CanHandle(self,node):
return self.IsOfClass(node, 'LEDNumberCtrl')
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.LEDNumberCtrl(self.GetParentAsWindow(),
self.GetID(),
self.GetPosition(),
self.GetSize(),
self.GetStyle())
align = self.GetStyle() & 7
if align: w.SetAlignment(self.GetStyle() & 7)
w.SetValue(self.GetText('value'))
self.SetupWindow(w)
return w
class EditableListBoxXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
self.AddWindowStyles()
self.AddStyle('wxEL_ALLOW_NEW', gizmos.EL_ALLOW_NEW)
self.AddStyle('wxEL_ALLOW_EDIT', gizmos.EL_ALLOW_EDIT)
self.AddStyle('wxEL_ALLOW_DELETE', gizmos.EL_ALLOW_DELETE)
def CanHandle(self, node):
return self.IsOfClass(node, 'EditableListBox')
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.EditableListBox(self.GetParentAsWindow(),
self.GetID(),
self.GetText("label"),
self.GetPosition(),
self.GetSize(),
self.GetStyle(),
self.GetName())
#self.insideBox = True
#self.CreateChildrenPrivately(None, self.GetParamNode('content'))
#self.insideBox = False
# Long way
strings = []
n = self.GetParamNode('content')
if n: n = n.GetChildren()
while n:
if n.GetType() != xrc.XML_ELEMENT_NODE or n.GetName() != "item":
n = n.GetNext()
continue
strings.append(n.GetNodeContent())
n = n.GetNext()
w.SetStrings(strings)
self.SetupWindow(w)
return w
class TreeListCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxDEFAULT_COL_WIDTH', gizmos.DEFAULT_COL_WIDTH)
self.AddStyle('wxTL_MODE_NAV_FULLTREE', gizmos.TL_MODE_NAV_FULLTREE)
self.AddStyle('wxTL_MODE_NAV_EXPANDED', gizmos.TL_MODE_NAV_EXPANDED)
self.AddStyle('wxTL_MODE_NAV_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)
self.AddStyle('wxTL_MODE_NAV_LEVEL', gizmos.TL_MODE_NAV_LEVEL)
self.AddStyle('wxTL_MODE_FIND_EXACT', gizmos.TL_MODE_FIND_EXACT)
self.AddStyle('wxTL_MODE_FIND_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)
self.AddStyle('wxTL_MODE_FIND_NOCASE', gizmos.TL_MODE_FIND_NOCASE)
self.AddStyle('wxTREE_HITTEST_ONITEMCOLUMN', gizmos.TREE_HITTEST_ONITEMCOLUMN)
self.AddStyle('wxTR_COLUMN_LINES', gizmos.TR_COLUMN_LINES)
self.AddStyle('wxTR_VIRTUAL', gizmos.TR_VIRTUAL)
self.AddStyle('wxTL_ALIGN_LEFT ', wx.ALIGN_LEFT)
self.AddStyle('wxTL_ALIGN_RIGHT ', wx.ALIGN_RIGHT)
self.AddStyle('wxTL_ALIGN_CENTER', wx.ALIGN_CENTER)
self.AddStyle('wxTL_SEARCH_VISIBLE', gizmos.TL_MODE_NAV_VISIBLE)
self.AddStyle('wxTL_SEARCH_LEVEL ', gizmos.TL_MODE_NAV_LEVEL)
self.AddStyle('wxTL_SEARCH_FULL ', gizmos.TL_MODE_FIND_EXACT)
self.AddStyle('wxTL_SEARCH_PARTIAL', gizmos.TL_MODE_FIND_PARTIAL)
self.AddStyle('wxTL_SEARCH_NOCASE ', gizmos.TL_MODE_FIND_NOCASE)
self.AddStyle('wxTR_DONT_ADJUST_MAC', gizmos.TR_DONT_ADJUST_MAC)
self.AddStyle('wxTR_DEFAULT_STYLE', wx.TR_DEFAULT_STYLE)
def CanHandle(self, node):
return self.IsOfClass(node, 'TreeListCtrl')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.TreeListCtrl(self.GetParentAsWindow(),
self.GetID(),
style=self.GetStyle(),
name=self.GetName())
w.AddColumn("Main column")
w.AddColumn('Column 1')
w.SetMainColumn(0)
w.SetColumnWidth(0, 50)
w.SetColumnWidth(1, 50)
root = w.AddRoot('Root')
w.SetItemText(root, "col 1", 1)
item1 = w.AppendItem(root, 'item 1')
w.SetItemText(item1, "col 1", 1)
w.Expand(root)
return w
class DynamicSashWindowXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
self.AddStyle('wxDS_MANAGE_SCROLLBARS', gizmos.DS_MANAGE_SCROLLBARS)
self.AddStyle('wxDS_DRAG_CORNER', gizmos.DS_DRAG_CORNER)
def CanHandle(self, node):
return self.IsOfClass(node, 'DynamicSashWindow')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = gizmos.DynamicSashWindow(self.GetParentAsWindow(),
self.GetID(),
self.GetPosition(),
self.GetSize(),
self.GetStyle(),
self.GetName())
self.SetupWindow(w)
return w
| true | true |
f726ab4ccfc111179e65303e6251acccc8a648d5 | 4,241 | py | Python | loot_tables.py | Battlecats59/MCBELootRandomizer | de5c49c65fb12c1e3ec391b665bdfd9a5c64c7cc | [
"MIT"
] | null | null | null | loot_tables.py | Battlecats59/MCBELootRandomizer | de5c49c65fb12c1e3ec391b665bdfd9a5c64c7cc | [
"MIT"
] | null | null | null | loot_tables.py | Battlecats59/MCBELootRandomizer | de5c49c65fb12c1e3ec391b665bdfd9a5c64c7cc | [
"MIT"
] | null | null | null | import os
import json
import yaml
from typing import OrderedDict
from yaml.loader import FullLoader
from paths import RANDO_ROOT_PATH
class loot_tables:
def get_loot_tables(self, options):
with (RANDO_ROOT_PATH / 'loot_table_categories.yaml').open('r') as loot_tables:
self.loot_table_list = yaml.load(loot_tables, Loader=FullLoader)
self.randomized_mob_loot_table_list = []
self.unrandomized_mob_loot_table_list = []
self.randomized_chest_loot_table_list = []
self.unrandomized_chest_loot_table_list = []
for mob_lt in self.loot_table_list['entities']:
if options['version'] in [str(ver) for ver in mob_lt['versions']]:
if options['randomized_' + mob_lt['type']] == True:
self.randomized_mob_loot_table_list.append(mob_lt)
else:
self.unrandomized_mob_loot_table_list.append(mob_lt)
else:
continue
for chest_lt in self.loot_table_list['chests']:
if options['version'] in [str(ver) for ver in chest_lt['versions']]:
if options['randomized_' + chest_lt['type'] + '_chests'] == True:
self.randomized_chest_loot_table_list.append(chest_lt)
else:
self.unrandomized_chest_loot_table_list.append(chest_lt)
else:
continue
self.mob_loot_tables_list = self.randomized_mob_loot_table_list + self.unrandomized_mob_loot_table_list
self.chest_loot_tables_list = self.randomized_chest_loot_table_list + self.unrandomized_chest_loot_table_list
return self.randomized_mob_loot_table_list, self.unrandomized_mob_loot_table_list, self.randomized_chest_loot_table_list, self.unrandomized_chest_loot_table_list
def read_loot_tables(self, mob_loot_table_list, chest_loot_table_list):
self.loot_table_path = 'loot_tables'
self.mob_r_loot_tables = []
self.mob_s_loot_tables = []
self.chest_r_loot_tables = []
self.chest_s_loot_tables = []
self.patched_mob_loot_table_list = []
for m in mob_loot_table_list:
with (RANDO_ROOT_PATH / self.loot_table_path / 'entities' / m['file']).open('r') as mlt:
self.mob_loot_table = json.load(mlt)
self.mob_r_loot_tables.append(self.mob_loot_table)
if self.mob_loot_table == {}:
m['empty'] = True
else:
m['empty'] = False
self.mob_s_loot_tables.append(m['name'])
self.patched_mob_loot_table_list.append(m)
for c in chest_loot_table_list:
with (RANDO_ROOT_PATH / self.loot_table_path / 'chests' / c['file']).open('r') as clt:
self.chest_r_loot_tables.append(json.load(clt))
self.chest_s_loot_tables.append(c['name'])
return self.mob_r_loot_tables, self.mob_s_loot_tables, self.chest_r_loot_tables, self.chest_s_loot_tables, self.patched_mob_loot_table_list
def write_loot_tables(self, mob_loot_tables, mob_s_loot_tables, chest_loot_tables, chest_s_loot_tables):
self.mob_loot_tables_names = []
self.mob_loot_tables_files = []
self.chest_loot_tables_names = []
self.chest_loot_tables_files = []
for mlt in self.mob_loot_tables_list:
self.mob_loot_tables_names.append(mlt['name'])
self.mob_loot_tables_files.append(mlt['file'])
for clt in self.chest_loot_tables_list:
self.chest_loot_tables_names.append(clt['name'])
self.chest_loot_tables_files.append(clt['file'])
self.patched_mob_loot_tables = OrderedDict(zip(self.mob_loot_tables_files, mob_loot_tables))
self.spoiler_mob_loot_tables = OrderedDict(zip(self.mob_loot_tables_names, mob_s_loot_tables))
self.patched_chest_loot_tables = OrderedDict(zip(self.chest_loot_tables_files, chest_loot_tables))
self.spoiler_chest_loot_tables = OrderedDict(zip(self.chest_loot_tables_names, chest_s_loot_tables))
return self.patched_mob_loot_tables, self.spoiler_mob_loot_tables, self.patched_chest_loot_tables, self.spoiler_chest_loot_tables | 47.651685 | 169 | 0.680736 | import os
import json
import yaml
from typing import OrderedDict
from yaml.loader import FullLoader
from paths import RANDO_ROOT_PATH
class loot_tables:
def get_loot_tables(self, options):
with (RANDO_ROOT_PATH / 'loot_table_categories.yaml').open('r') as loot_tables:
self.loot_table_list = yaml.load(loot_tables, Loader=FullLoader)
self.randomized_mob_loot_table_list = []
self.unrandomized_mob_loot_table_list = []
self.randomized_chest_loot_table_list = []
self.unrandomized_chest_loot_table_list = []
for mob_lt in self.loot_table_list['entities']:
if options['version'] in [str(ver) for ver in mob_lt['versions']]:
if options['randomized_' + mob_lt['type']] == True:
self.randomized_mob_loot_table_list.append(mob_lt)
else:
self.unrandomized_mob_loot_table_list.append(mob_lt)
else:
continue
for chest_lt in self.loot_table_list['chests']:
if options['version'] in [str(ver) for ver in chest_lt['versions']]:
if options['randomized_' + chest_lt['type'] + '_chests'] == True:
self.randomized_chest_loot_table_list.append(chest_lt)
else:
self.unrandomized_chest_loot_table_list.append(chest_lt)
else:
continue
self.mob_loot_tables_list = self.randomized_mob_loot_table_list + self.unrandomized_mob_loot_table_list
self.chest_loot_tables_list = self.randomized_chest_loot_table_list + self.unrandomized_chest_loot_table_list
return self.randomized_mob_loot_table_list, self.unrandomized_mob_loot_table_list, self.randomized_chest_loot_table_list, self.unrandomized_chest_loot_table_list
def read_loot_tables(self, mob_loot_table_list, chest_loot_table_list):
self.loot_table_path = 'loot_tables'
self.mob_r_loot_tables = []
self.mob_s_loot_tables = []
self.chest_r_loot_tables = []
self.chest_s_loot_tables = []
self.patched_mob_loot_table_list = []
for m in mob_loot_table_list:
with (RANDO_ROOT_PATH / self.loot_table_path / 'entities' / m['file']).open('r') as mlt:
self.mob_loot_table = json.load(mlt)
self.mob_r_loot_tables.append(self.mob_loot_table)
if self.mob_loot_table == {}:
m['empty'] = True
else:
m['empty'] = False
self.mob_s_loot_tables.append(m['name'])
self.patched_mob_loot_table_list.append(m)
for c in chest_loot_table_list:
with (RANDO_ROOT_PATH / self.loot_table_path / 'chests' / c['file']).open('r') as clt:
self.chest_r_loot_tables.append(json.load(clt))
self.chest_s_loot_tables.append(c['name'])
return self.mob_r_loot_tables, self.mob_s_loot_tables, self.chest_r_loot_tables, self.chest_s_loot_tables, self.patched_mob_loot_table_list
def write_loot_tables(self, mob_loot_tables, mob_s_loot_tables, chest_loot_tables, chest_s_loot_tables):
self.mob_loot_tables_names = []
self.mob_loot_tables_files = []
self.chest_loot_tables_names = []
self.chest_loot_tables_files = []
for mlt in self.mob_loot_tables_list:
self.mob_loot_tables_names.append(mlt['name'])
self.mob_loot_tables_files.append(mlt['file'])
for clt in self.chest_loot_tables_list:
self.chest_loot_tables_names.append(clt['name'])
self.chest_loot_tables_files.append(clt['file'])
self.patched_mob_loot_tables = OrderedDict(zip(self.mob_loot_tables_files, mob_loot_tables))
self.spoiler_mob_loot_tables = OrderedDict(zip(self.mob_loot_tables_names, mob_s_loot_tables))
self.patched_chest_loot_tables = OrderedDict(zip(self.chest_loot_tables_files, chest_loot_tables))
self.spoiler_chest_loot_tables = OrderedDict(zip(self.chest_loot_tables_names, chest_s_loot_tables))
return self.patched_mob_loot_tables, self.spoiler_mob_loot_tables, self.patched_chest_loot_tables, self.spoiler_chest_loot_tables | true | true |
f726ad04313fae09750869fe143024d0fb1c7b02 | 1,794 | py | Python | release/stubs.min/System/Drawing/__init___parts/CopyPixelOperation.py | tranconbv/ironpython-stubs | a601759e6c6819beff8e6b639d18a24b7e351851 | [
"MIT"
] | null | null | null | release/stubs.min/System/Drawing/__init___parts/CopyPixelOperation.py | tranconbv/ironpython-stubs | a601759e6c6819beff8e6b639d18a24b7e351851 | [
"MIT"
] | null | null | null | release/stubs.min/System/Drawing/__init___parts/CopyPixelOperation.py | tranconbv/ironpython-stubs | a601759e6c6819beff8e6b639d18a24b7e351851 | [
"MIT"
] | null | null | null | class CopyPixelOperation(Enum,IComparable,IFormattable,IConvertible):
"""
Determines how the source color in a copy pixel operation is combined with the destination color to result in a final color.
enum CopyPixelOperation,values: Blackness (66),CaptureBlt (1073741824),DestinationInvert (5570569),MergeCopy (12583114),MergePaint (12255782),NoMirrorBitmap (-2147483648),NotSourceCopy (3342344),NotSourceErase (1114278),PatCopy (15728673),PatInvert (5898313),PatPaint (16452105),SourceAnd (8913094),SourceCopy (13369376),SourceErase (4457256),SourceInvert (6684742),SourcePaint (15597702),Whiteness (16711778)
"""
def Instance(self):
""" This function has been arbitrarily put into the stubs"""
return CopyPixelOperation()
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Blackness=None
CaptureBlt=None
DestinationInvert=None
MergeCopy=None
MergePaint=None
NoMirrorBitmap=None
NotSourceCopy=None
NotSourceErase=None
PatCopy=None
PatInvert=None
PatPaint=None
SourceAnd=None
SourceCopy=None
SourceErase=None
SourceInvert=None
SourcePaint=None
value__=None
Whiteness=None
| 33.849057 | 411 | 0.726867 | class CopyPixelOperation(Enum,IComparable,IFormattable,IConvertible):
return CopyPixelOperation()
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
""" __format__(formattable: IFormattable,format: str) -> str """
pass
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Blackness=None
CaptureBlt=None
DestinationInvert=None
MergeCopy=None
MergePaint=None
NoMirrorBitmap=None
NotSourceCopy=None
NotSourceErase=None
PatCopy=None
PatInvert=None
PatPaint=None
SourceAnd=None
SourceCopy=None
SourceErase=None
SourceInvert=None
SourcePaint=None
value__=None
Whiteness=None
| true | true |
f726ad8c7093593009fdde16473a6c6d5e036bd8 | 11,476 | py | Python | python/GUI/__main__.py | andreehultgren/soduko | aae2d174e417d00ed60206f4567e554d25aa4311 | [
"MIT"
] | null | null | null | python/GUI/__main__.py | andreehultgren/soduko | aae2d174e417d00ed60206f4567e554d25aa4311 | [
"MIT"
] | null | null | null | python/GUI/__main__.py | andreehultgren/soduko | aae2d174e417d00ed60206f4567e554d25aa4311 | [
"MIT"
] | null | null | null | import pygame
from random import sample, randint, random
from tabulate import tabulate
config = {
"cell_width" : 50,
"cell_height" : 50,
"cell_color" : (235,235,235),
"cell_color_hover" : (220,220,255),
"cell_color_locked" : (255,220,220),
"cell_color_editing" : (220,255,220),
"cell_color_wrong" : (255,120,120),
"cell_padding" : 3,
"background" : (0,0,0),
"color_number" : (0,0,0),
"window_name" : "Soduko!",
"difficulty" : 0.5,
}
class Game(object):
def __init__(self, config):
self.config = config
#Initiate pygame
pygame.init()
#Configure pygame according to the config file.
self.configure_window()
self.configure_clock()
self.configure_fonts()
#Generate the soduko-board
self.generate_board()
#Finally, some descriptive parameters
self.win = False
self.running = True
def configure_fonts(self):
font_big = int(config['cell_height']*0.8)
font_small = int(config['cell_height']*0.4)
self.font = pygame.font.SysFont('comicsansms', font_big)
self.font_initial = pygame.font.SysFont('comicsansms', font_big, True)
self.font_predicted = pygame.font.SysFont('comicsansms', font_small)
def configure_clock(self):
self.clock = pygame.time.Clock()
def configure_window(self):
pygame.display.set_caption(config['window_name'])
window_width = 9*config['cell_width' ]+14*config['cell_padding']
window_height = 9*config['cell_height']+14*config['cell_padding']
self.view = pygame.display.set_mode((window_width, window_height))
def check_mouse(self):
self.pos = pygame.mouse.get_pos()
self.pressed,_,_= pygame.mouse.get_pressed()
def draw_board(self):
for row in self.cell_board:
for cell in row:
cell.draw()
def draw_background(self):
self.view.fill(self.config['background'])
def generate_board(self):
#Generate a solution of the board. Convert to cell structure.
solution = self.generate_board_full()
self.cell_board = [[Cell(self,i,j,value) if random()>config['difficulty'] else Cell(self,i,j,0) for j,value in enumerate(row)] for i,row in enumerate(solution)]
def generate_board_full(self):
#Not my code. Taken from https://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python/#answer-56581709
base = 3
# pattern for a baseline valid solution
def pattern(r,c): return (base*(r%base)+r//base+c)%(base**2)
# randomize rows, columns and numbers (of valid base pattern)
def shuffle(s): return sample(s,len(s))
rBase = range(base)
rows = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ]
cols = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
nums = shuffle(range(1,base*base+1))
# produce board using randomized baseline pattern
board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
return board
def check_keyboard(self):
#Keyboard commands that applies to the whole board.
pressed = pygame.key.get_pressed()
if pressed[pygame.K_SPACE]:
self.solve(self.cell_board)
self.check_for_win()
def check_for_win(self):
validity = self.check_validity(self.cell_board)
all_entry = True
for row in self.cell_board:
for cell in row:
if cell.value is 0: all_entry = False
self.win = validity*all_entry
def check_validity(self, board):
combinations = []
squares = [[0,1,2], [3,4,5], [6,7,8]]
valid = True
#Add columns and rows
for i in range(9):
combinations.append([ 9*i+k for k in range(9)])
combinations.append([ i+k*9 for k in range(9)])
#Add squares
for row in squares:
for col in squares:
combinations.append([a*9+b for b in col for a in row])
#Check combinations
for combination in combinations:
#Count the amount of occurences of each number
counter = [0 for _ in range(9)]
for position in combination:
row, col = position//9, position%9
value = board[row][col].value
if value is not 0:
counter[value-1] += 1
#Check if it exceeds one
for count in counter:
if count >1:
valid=False
return valid
def solve(self, board, position=0):
#At each step, update the board
self.draw_background()
self.draw_board()
pygame.display.update()
#Set the framerate to alot.
self.clock.tick(10000)
row, col = position//9, position%9
sol_found = False
#Check the if we are at the end
if position>=81:
return True, board
#Skip if it is an initial value
if board[row][col].initial_value != 0:
sol_found, board = self.solve(board, position+1)
if sol_found:
return True, board
else:
return False, board
#Try all different values:
for value in range(1,10):
board[row][col].value = value
valid_solution = self.check_validity(board)
if valid_solution:
sol_found, board = self.solve(board, position+1)
if sol_found:
return True, board
board[row][col].value = 0
return False, board
class Cell(object):
def __init__(self, parent, row, col, value):
self.value = value
self.row = row
self.col = col
self.initial_value = value
self.parent = parent
self.clicked = False
self.hover = False
self.predicted = []
self.correct = None
def draw(self):
#Plot the square. Fix the formatting after
square = self.draw_cell(self.parent.config['cell_color'])
color = self.pick_color(square)
square = self.draw_cell(self.parent.config[color])
self.add_text(square)
def pick_color(self, square):
color = 'cell_color'
#Check if it's correct
if self.correct==False:
color = 'cell_color_wrong'
#Check hover
if square.collidepoint(self.parent.pos):
self.hover = True
color = 'cell_color_hover'
else:
self.hover = False
self.clicked= False
#Check click
if self.hover and self.parent.pressed:
self.clicked = True
#Update value if clicked
if self.clicked and self.hover:
if self.initial_value!=0:
color = 'cell_color_locked'
else:
color = 'cell_color_editing'
self.listen_for_number()
return color
def add_text(self, square):
#Stringify the value. Don't show a number
if self.value != 0:
cell_data = str(self.value)
else:
cell_data = ''
for digit in self.predicted:
cell_data += str(digit)
if self.initial_value!=0:
text = self.parent.font_initial.render(cell_data, True, self.parent.config['color_number'])
elif len(self.predicted)>0:
text = self.parent.font_predicted.render(cell_data, True, self.parent.config['color_number'])
else:
text = self.parent.font.render(cell_data, True, self.parent.config['color_number'])
#Add text to the square
textRect = text.get_rect()
textRect.center = square.center
self.parent.view.blit(text, textRect)
def draw_cell(self, color):
#Compute position of the square
x_pos = self.col*(self.parent.config['cell_width']+self.parent.config['cell_padding'])+(1+self.col//3)*self.parent.config['cell_padding']
y_pos = self.row*(self.parent.config['cell_height']+self.parent.config['cell_padding'])+(1+self.row//3)*self.parent.config['cell_padding']
return pygame.draw.rect(self.parent.view, color, (x_pos, y_pos, self.parent.config['cell_width'], self.parent.config['cell_height']))
def listen_for_number(self):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] or pressed[pygame.K_KP1]: self.predict(1)
if pressed[pygame.K_2] or pressed[pygame.K_KP2]: self.predict(2)
if pressed[pygame.K_3] or pressed[pygame.K_KP3]: self.predict(3)
if pressed[pygame.K_4] or pressed[pygame.K_KP4]: self.predict(4)
if pressed[pygame.K_5] or pressed[pygame.K_KP5]: self.predict(5)
if pressed[pygame.K_6] or pressed[pygame.K_KP6]: self.predict(6)
if pressed[pygame.K_7] or pressed[pygame.K_KP7]: self.predict(7)
if pressed[pygame.K_8] or pressed[pygame.K_KP8]: self.predict(8)
if pressed[pygame.K_9] or pressed[pygame.K_KP9]: self.predict(9)
if pressed[pygame.K_DELETE] or pressed[pygame.K_BACKSPACE]:
try:
self.predicted.remove(self.predicted[-1])
except:
pass
self.set_number(0)
if pressed[pygame.K_RETURN] or pressed[pygame.K_KP_ENTER]:
if len(self.predicted) == 1:
self.set_number(self.predicted[0])
self.predicted=[]
self.parent.check_for_win()
def set_number(self, number):
self.parent.pressed = True
self.correct = None
valid_input = self.parent.check_validity(self.parent.cell_board)
if not valid_input:
self.correct = False
self.value = number
def predict(self, number):
self.parent.pressed = True
if self.value == 0:
if number not in self.predicted:
self.predicted.append(number)
# Draw Once
game = Game(config)
while game.running:
#Get input
game.check_mouse()
game.check_keyboard()
if not game.win:
#Draw the board
game.draw_background()
game.draw_board()
else:
print("WIN")
print(game.win)
exit()
#Update view
pygame.display.update()
#Limit framerate to 15 fps.
game.clock.tick(15)
#Handle quitting the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
game.running = False
| 36.08805 | 174 | 0.548013 | import pygame
from random import sample, randint, random
from tabulate import tabulate
config = {
"cell_width" : 50,
"cell_height" : 50,
"cell_color" : (235,235,235),
"cell_color_hover" : (220,220,255),
"cell_color_locked" : (255,220,220),
"cell_color_editing" : (220,255,220),
"cell_color_wrong" : (255,120,120),
"cell_padding" : 3,
"background" : (0,0,0),
"color_number" : (0,0,0),
"window_name" : "Soduko!",
"difficulty" : 0.5,
}
class Game(object):
def __init__(self, config):
self.config = config
pygame.init()
self.configure_window()
self.configure_clock()
self.configure_fonts()
self.generate_board()
self.win = False
self.running = True
def configure_fonts(self):
font_big = int(config['cell_height']*0.8)
font_small = int(config['cell_height']*0.4)
self.font = pygame.font.SysFont('comicsansms', font_big)
self.font_initial = pygame.font.SysFont('comicsansms', font_big, True)
self.font_predicted = pygame.font.SysFont('comicsansms', font_small)
def configure_clock(self):
self.clock = pygame.time.Clock()
def configure_window(self):
pygame.display.set_caption(config['window_name'])
window_width = 9*config['cell_width' ]+14*config['cell_padding']
window_height = 9*config['cell_height']+14*config['cell_padding']
self.view = pygame.display.set_mode((window_width, window_height))
def check_mouse(self):
self.pos = pygame.mouse.get_pos()
self.pressed,_,_= pygame.mouse.get_pressed()
def draw_board(self):
for row in self.cell_board:
for cell in row:
cell.draw()
def draw_background(self):
self.view.fill(self.config['background'])
def generate_board(self):
solution = self.generate_board_full()
self.cell_board = [[Cell(self,i,j,value) if random()>config['difficulty'] else Cell(self,i,j,0) for j,value in enumerate(row)] for i,row in enumerate(solution)]
def generate_board_full(self):
= 3
def pattern(r,c): return (base*(r%base)+r//base+c)%(base**2)
def shuffle(s): return sample(s,len(s))
rBase = range(base)
rows = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ]
cols = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
nums = shuffle(range(1,base*base+1))
board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
return board
def check_keyboard(self):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_SPACE]:
self.solve(self.cell_board)
self.check_for_win()
def check_for_win(self):
validity = self.check_validity(self.cell_board)
all_entry = True
for row in self.cell_board:
for cell in row:
if cell.value is 0: all_entry = False
self.win = validity*all_entry
def check_validity(self, board):
combinations = []
squares = [[0,1,2], [3,4,5], [6,7,8]]
valid = True
for i in range(9):
combinations.append([ 9*i+k for k in range(9)])
combinations.append([ i+k*9 for k in range(9)])
for row in squares:
for col in squares:
combinations.append([a*9+b for b in col for a in row])
for combination in combinations:
counter = [0 for _ in range(9)]
for position in combination:
row, col = position//9, position%9
value = board[row][col].value
if value is not 0:
counter[value-1] += 1
for count in counter:
if count >1:
valid=False
return valid
def solve(self, board, position=0):
self.draw_background()
self.draw_board()
pygame.display.update()
self.clock.tick(10000)
row, col = position//9, position%9
sol_found = False
if position>=81:
return True, board
if board[row][col].initial_value != 0:
sol_found, board = self.solve(board, position+1)
if sol_found:
return True, board
else:
return False, board
for value in range(1,10):
board[row][col].value = value
valid_solution = self.check_validity(board)
if valid_solution:
sol_found, board = self.solve(board, position+1)
if sol_found:
return True, board
board[row][col].value = 0
return False, board
class Cell(object):
def __init__(self, parent, row, col, value):
self.value = value
self.row = row
self.col = col
self.initial_value = value
self.parent = parent
self.clicked = False
self.hover = False
self.predicted = []
self.correct = None
def draw(self):
square = self.draw_cell(self.parent.config['cell_color'])
color = self.pick_color(square)
square = self.draw_cell(self.parent.config[color])
self.add_text(square)
def pick_color(self, square):
color = 'cell_color'
if self.correct==False:
color = 'cell_color_wrong'
#Check hover
if square.collidepoint(self.parent.pos):
self.hover = True
color = 'cell_color_hover'
else:
self.hover = False
self.clicked= False
#Check click
if self.hover and self.parent.pressed:
self.clicked = True
#Update value if clicked
if self.clicked and self.hover:
if self.initial_value!=0:
color = 'cell_color_locked'
else:
color = 'cell_color_editing'
self.listen_for_number()
return color
def add_text(self, square):
#Stringify the value. Don't show a number
if self.value != 0:
cell_data = str(self.value)
else:
cell_data = ''
for digit in self.predicted:
cell_data += str(digit)
if self.initial_value!=0:
text = self.parent.font_initial.render(cell_data, True, self.parent.config['color_number'])
elif len(self.predicted)>0:
text = self.parent.font_predicted.render(cell_data, True, self.parent.config['color_number'])
else:
text = self.parent.font.render(cell_data, True, self.parent.config['color_number'])
textRect = text.get_rect()
textRect.center = square.center
self.parent.view.blit(text, textRect)
def draw_cell(self, color):
x_pos = self.col*(self.parent.config['cell_width']+self.parent.config['cell_padding'])+(1+self.col//3)*self.parent.config['cell_padding']
y_pos = self.row*(self.parent.config['cell_height']+self.parent.config['cell_padding'])+(1+self.row//3)*self.parent.config['cell_padding']
return pygame.draw.rect(self.parent.view, color, (x_pos, y_pos, self.parent.config['cell_width'], self.parent.config['cell_height']))
def listen_for_number(self):
pressed = pygame.key.get_pressed()
if pressed[pygame.K_1] or pressed[pygame.K_KP1]: self.predict(1)
if pressed[pygame.K_2] or pressed[pygame.K_KP2]: self.predict(2)
if pressed[pygame.K_3] or pressed[pygame.K_KP3]: self.predict(3)
if pressed[pygame.K_4] or pressed[pygame.K_KP4]: self.predict(4)
if pressed[pygame.K_5] or pressed[pygame.K_KP5]: self.predict(5)
if pressed[pygame.K_6] or pressed[pygame.K_KP6]: self.predict(6)
if pressed[pygame.K_7] or pressed[pygame.K_KP7]: self.predict(7)
if pressed[pygame.K_8] or pressed[pygame.K_KP8]: self.predict(8)
if pressed[pygame.K_9] or pressed[pygame.K_KP9]: self.predict(9)
if pressed[pygame.K_DELETE] or pressed[pygame.K_BACKSPACE]:
try:
self.predicted.remove(self.predicted[-1])
except:
pass
self.set_number(0)
if pressed[pygame.K_RETURN] or pressed[pygame.K_KP_ENTER]:
if len(self.predicted) == 1:
self.set_number(self.predicted[0])
self.predicted=[]
self.parent.check_for_win()
def set_number(self, number):
self.parent.pressed = True
self.correct = None
valid_input = self.parent.check_validity(self.parent.cell_board)
if not valid_input:
self.correct = False
self.value = number
def predict(self, number):
self.parent.pressed = True
if self.value == 0:
if number not in self.predicted:
self.predicted.append(number)
game = Game(config)
while game.running:
game.check_mouse()
game.check_keyboard()
if not game.win:
game.draw_background()
game.draw_board()
else:
print("WIN")
print(game.win)
exit()
pygame.display.update()
game.clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game.running = False
| true | true |
f726af04dc7785db1b54ef4a6b8f7b5c33ebd894 | 878 | py | Python | server/fadzmaq.py | lachierussell/FadZmaq | deb89c35df05603552ce95627ac8400c6788fbcb | [
"BSD-2-Clause"
] | 2 | 2019-09-02T06:56:46.000Z | 2019-09-15T08:43:54.000Z | server/fadzmaq.py | lachierussell/FadZmaq | deb89c35df05603552ce95627ac8400c6788fbcb | [
"BSD-2-Clause"
] | 11 | 2019-08-27T19:08:24.000Z | 2019-10-18T01:45:54.000Z | server/fadzmaq.py | lachierussell/FadZmaq | deb89c35df05603552ce95627ac8400c6788fbcb | [
"BSD-2-Clause"
] | 1 | 2019-10-25T05:42:48.000Z | 2019-10-25T05:42:48.000Z | # @file
# The application entry point. Run this file to use the FadZmaq Server.
#
# FadZmaq Project
# Professional Computing. Semester 2 2019
#
# Copyright FadZmaq © 2019 All rights reserved.
# @author Lachlan Russell 22414249@student.uwa.edu.au
# @author Jordan Russell jordanrussell@live.com
# @author Thiren Naidoo 22257963@student.uwa.edu.au
# @author Beining Chen 22384298@student.uwa.edu.au
# entry point for the api
from fadzmaq import create_app
import fadzmaq
import firebase_admin
from sqlalchemy import create_engine
app = create_app()
cred = firebase_admin.credentials.Certificate(app.config['CERT'])
fadzmaq.auth_app = firebase_admin.initialize_app(cred)
fadzmaq.engine = create_engine(app.config['DATABASE_URI'])
# only run if we are executing this script, otherwise handled by WSGI
if __name__ == "__main__":
app.run()
| 30.275862 | 71 | 0.750569 |
from fadzmaq import create_app
import fadzmaq
import firebase_admin
from sqlalchemy import create_engine
app = create_app()
cred = firebase_admin.credentials.Certificate(app.config['CERT'])
fadzmaq.auth_app = firebase_admin.initialize_app(cred)
fadzmaq.engine = create_engine(app.config['DATABASE_URI'])
if __name__ == "__main__":
app.run()
| true | true |
f726b000f7751f551512bc88f402ed4f784b69c2 | 6,428 | py | Python | dev/breeze/src/airflow_breeze/build_image/ci/build_ci_params.py | npodewitz/airflow | 511ea702d5f732582d018dad79754b54d5e53f9d | [
"Apache-2.0"
] | null | null | null | dev/breeze/src/airflow_breeze/build_image/ci/build_ci_params.py | npodewitz/airflow | 511ea702d5f732582d018dad79754b54d5e53f9d | [
"Apache-2.0"
] | null | null | null | dev/breeze/src/airflow_breeze/build_image/ci/build_ci_params.py | npodewitz/airflow | 511ea702d5f732582d018dad79754b54d5e53f9d | [
"Apache-2.0"
] | null | null | null | # 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.
"""Parameters for Build CI Image."""
import os
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from airflow_breeze.branch_defaults import AIRFLOW_BRANCH, DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
from airflow_breeze.global_constants import get_airflow_version
from airflow_breeze.utils.console import console
from airflow_breeze.utils.path_utils import BUILD_CACHE_DIR
@dataclass
class BuildCiParams:
"""
CI build parameters. Those parameters are used to determine command issued to build CI image.
"""
upgrade_to_newer_dependencies: str = "false"
python: str = "3.7"
airflow_branch: str = AIRFLOW_BRANCH
build_id: int = 0
docker_cache: str = "pulled"
airflow_extras: str = "devel_ci"
install_providers_from_sources: bool = True
additional_airflow_extras: str = ""
additional_python_deps: str = ""
github_repository: str = "apache/airflow"
constraints_github_repository: str = "apache/airflow"
default_constraints_branch: str = DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
airflow_constraints: str = "constraints-source-providers"
airflow_constraints_reference: Optional[str] = "constraints-main"
airflow_constraints_location: Optional[str] = ""
airflow_pre_cached_pip_packages: str = "true"
login_to_github_registry: str = "false"
github_username: str = ""
dev_apt_command: str = ""
dev_apt_deps: str = ""
image_tag: Optional[str] = None
github_token: str = ""
additional_dev_apt_command: str = ""
additional_dev_apt_deps: str = ""
additional_dev_apt_env: str = ""
runtime_apt_command: str = ""
runtime_apt_deps: str = ""
additional_runtime_apt_command: str = ""
additional_runtime_apt_deps: str = ""
additional_runtime_apt_env: str = ""
platform: str = f"linux/{os.uname().machine}"
debian_version: str = "bullseye"
prepare_buildx_cache: bool = False
push_image: bool = False
empty_image: bool = False
force_build: bool = False
skip_rebuild_check: bool = False
answer: Optional[str] = None
@property
def the_image_type(self) -> str:
return 'CI'
@property
def airflow_base_image_name(self):
image = f'ghcr.io/{self.github_repository.lower()}'
return image
@property
def airflow_image_name(self):
"""Construct CI image link"""
image = f'{self.airflow_base_image_name}/{self.airflow_branch}/ci/python{self.python}'
return image
@property
def airflow_image_name_with_tag(self):
"""Construct CI image link"""
image = f'{self.airflow_base_image_name}/{self.airflow_branch}/ci/python{self.python}'
return image if self.image_tag is None else image + f":{self.image_tag}"
@property
def airflow_image_repository(self):
return f'https://github.com/{self.github_repository}'
@property
def python_base_image(self):
"""Construct Python Base Image"""
return f'python:{self.python}-slim-{self.debian_version}'
@property
def airflow_ci_local_manifest_image(self):
"""Construct CI Local Manifest Image"""
return f'local-airflow-ci-manifest/{self.airflow_branch}/python{self.python}'
@property
def airflow_ci_remote_manifest_image(self):
"""Construct CI Remote Manifest Image"""
return f'{self.airflow_image_name}/{self.airflow_branch}/ci-manifest//python:{self.python}'
@property
def airflow_image_date_created(self):
now = datetime.now()
return now.strftime("%Y-%m-%dT%H:%M:%SZ")
@property
def airflow_version(self):
return get_airflow_version()
@property
def docker_cache_directive(self) -> List[str]:
docker_cache_directive = []
if self.docker_cache == "pulled":
docker_cache_directive.append(f"--cache-from={self.airflow_image_name}")
elif self.docker_cache == "disabled":
docker_cache_directive.append("--no-cache")
else:
docker_cache_directive = []
if self.prepare_buildx_cache:
docker_cache_directive.extend(["--cache-to=type=inline,mode=max", "--push"])
return docker_cache_directive
@property
def extra_docker_build_flags(self) -> List[str]:
extra_ci_flags = []
if self.airflow_constraints_location is not None and len(self.airflow_constraints_location) > 0:
extra_ci_flags.extend(
["--build-arg", f"AIRFLOW_CONSTRAINTS_LOCATION={self.airflow_constraints_location}"]
)
return extra_ci_flags
@property
def md5sum_cache_dir(self) -> Path:
return Path(BUILD_CACHE_DIR, self.airflow_branch, self.python, "CI")
def print_info(self):
console.print(f"CI Image: {self.airflow_version} Python: {self.python}.")
REQUIRED_CI_IMAGE_ARGS = [
"python_base_image",
"airflow_version",
"airflow_branch",
"airflow_extras",
"airflow_pre_cached_pip_packages",
"additional_airflow_extras",
"additional_python_deps",
"additional_dev_apt_command",
"additional_dev_apt_deps",
"additional_dev_apt_env",
"additional_runtime_apt_command",
"additional_runtime_apt_deps",
"additional_runtime_apt_env",
"upgrade_to_newer_dependencies",
"constraints_github_repository",
"airflow_constraints_reference",
"airflow_constraints",
"airflow_image_repository",
"airflow_image_date_created",
"build_id",
]
OPTIONAL_CI_IMAGE_ARGS = [
"dev_apt_command",
"dev_apt_deps",
"runtime_apt_command",
"runtime_apt_deps",
]
| 35.125683 | 104 | 0.706752 |
import os
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from airflow_breeze.branch_defaults import AIRFLOW_BRANCH, DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
from airflow_breeze.global_constants import get_airflow_version
from airflow_breeze.utils.console import console
from airflow_breeze.utils.path_utils import BUILD_CACHE_DIR
@dataclass
class BuildCiParams:
upgrade_to_newer_dependencies: str = "false"
python: str = "3.7"
airflow_branch: str = AIRFLOW_BRANCH
build_id: int = 0
docker_cache: str = "pulled"
airflow_extras: str = "devel_ci"
install_providers_from_sources: bool = True
additional_airflow_extras: str = ""
additional_python_deps: str = ""
github_repository: str = "apache/airflow"
constraints_github_repository: str = "apache/airflow"
default_constraints_branch: str = DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
airflow_constraints: str = "constraints-source-providers"
airflow_constraints_reference: Optional[str] = "constraints-main"
airflow_constraints_location: Optional[str] = ""
airflow_pre_cached_pip_packages: str = "true"
login_to_github_registry: str = "false"
github_username: str = ""
dev_apt_command: str = ""
dev_apt_deps: str = ""
image_tag: Optional[str] = None
github_token: str = ""
additional_dev_apt_command: str = ""
additional_dev_apt_deps: str = ""
additional_dev_apt_env: str = ""
runtime_apt_command: str = ""
runtime_apt_deps: str = ""
additional_runtime_apt_command: str = ""
additional_runtime_apt_deps: str = ""
additional_runtime_apt_env: str = ""
platform: str = f"linux/{os.uname().machine}"
debian_version: str = "bullseye"
prepare_buildx_cache: bool = False
push_image: bool = False
empty_image: bool = False
force_build: bool = False
skip_rebuild_check: bool = False
answer: Optional[str] = None
@property
def the_image_type(self) -> str:
return 'CI'
@property
def airflow_base_image_name(self):
image = f'ghcr.io/{self.github_repository.lower()}'
return image
@property
def airflow_image_name(self):
image = f'{self.airflow_base_image_name}/{self.airflow_branch}/ci/python{self.python}'
return image
@property
def airflow_image_name_with_tag(self):
image = f'{self.airflow_base_image_name}/{self.airflow_branch}/ci/python{self.python}'
return image if self.image_tag is None else image + f":{self.image_tag}"
@property
def airflow_image_repository(self):
return f'https://github.com/{self.github_repository}'
@property
def python_base_image(self):
return f'python:{self.python}-slim-{self.debian_version}'
@property
def airflow_ci_local_manifest_image(self):
return f'local-airflow-ci-manifest/{self.airflow_branch}/python{self.python}'
@property
def airflow_ci_remote_manifest_image(self):
return f'{self.airflow_image_name}/{self.airflow_branch}/ci-manifest//python:{self.python}'
@property
def airflow_image_date_created(self):
now = datetime.now()
return now.strftime("%Y-%m-%dT%H:%M:%SZ")
@property
def airflow_version(self):
return get_airflow_version()
@property
def docker_cache_directive(self) -> List[str]:
docker_cache_directive = []
if self.docker_cache == "pulled":
docker_cache_directive.append(f"--cache-from={self.airflow_image_name}")
elif self.docker_cache == "disabled":
docker_cache_directive.append("--no-cache")
else:
docker_cache_directive = []
if self.prepare_buildx_cache:
docker_cache_directive.extend(["--cache-to=type=inline,mode=max", "--push"])
return docker_cache_directive
@property
def extra_docker_build_flags(self) -> List[str]:
extra_ci_flags = []
if self.airflow_constraints_location is not None and len(self.airflow_constraints_location) > 0:
extra_ci_flags.extend(
["--build-arg", f"AIRFLOW_CONSTRAINTS_LOCATION={self.airflow_constraints_location}"]
)
return extra_ci_flags
@property
def md5sum_cache_dir(self) -> Path:
return Path(BUILD_CACHE_DIR, self.airflow_branch, self.python, "CI")
def print_info(self):
console.print(f"CI Image: {self.airflow_version} Python: {self.python}.")
REQUIRED_CI_IMAGE_ARGS = [
"python_base_image",
"airflow_version",
"airflow_branch",
"airflow_extras",
"airflow_pre_cached_pip_packages",
"additional_airflow_extras",
"additional_python_deps",
"additional_dev_apt_command",
"additional_dev_apt_deps",
"additional_dev_apt_env",
"additional_runtime_apt_command",
"additional_runtime_apt_deps",
"additional_runtime_apt_env",
"upgrade_to_newer_dependencies",
"constraints_github_repository",
"airflow_constraints_reference",
"airflow_constraints",
"airflow_image_repository",
"airflow_image_date_created",
"build_id",
]
OPTIONAL_CI_IMAGE_ARGS = [
"dev_apt_command",
"dev_apt_deps",
"runtime_apt_command",
"runtime_apt_deps",
]
| true | true |
f726b031d40348c933768960ba80fab387456438 | 356 | py | Python | src/grasshopper_combat.py | hcodydibble/code-katas | f02599a76ac5c3719b1e3831208126eb4b72e98d | [
"MIT"
] | null | null | null | src/grasshopper_combat.py | hcodydibble/code-katas | f02599a76ac5c3719b1e3831208126eb4b72e98d | [
"MIT"
] | null | null | null | src/grasshopper_combat.py | hcodydibble/code-katas | f02599a76ac5c3719b1e3831208126eb4b72e98d | [
"MIT"
] | null | null | null | """Grasshopper - Terminal game combat function - Return remaining health after
taking damage.
# 1 Best Practices solution by ZozoFouchtra and others
def combat(health, damage):
return max(0, health-damage)
"""
def combat(health, damage):
"""Find remaining health after taking damage."""
return 0 if health - damage < 0 else health - damage
| 25.428571 | 78 | 0.724719 |
def combat(health, damage):
return 0 if health - damage < 0 else health - damage
| true | true |
f726b1139d55db10b37ce1d0847019a581954a25 | 4,460 | py | Python | sdks/python/apache_beam/io/gcp/bigquery_avro_tools.py | eyal0/beam | 9c6922976cc2a5c6a2ef836c1986ff769cda99a5 | [
"Apache-2.0"
] | 2 | 2017-12-19T18:34:54.000Z | 2019-05-14T21:50:06.000Z | sdks/python/apache_beam/io/gcp/bigquery_avro_tools.py | eyal0/beam | 9c6922976cc2a5c6a2ef836c1986ff769cda99a5 | [
"Apache-2.0"
] | 80 | 2020-01-16T09:55:09.000Z | 2020-10-03T13:43:07.000Z | sdks/python/apache_beam/io/gcp/bigquery_avro_tools.py | eyal0/beam | 9c6922976cc2a5c6a2ef836c1986ff769cda99a5 | [
"Apache-2.0"
] | 1 | 2020-04-29T20:09:40.000Z | 2020-04-29T20:09:40.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.
#
"""Tools used tool work with Avro files in the context of BigQuery.
Classes, constants and functions in this file are experimental and have no
backwards compatibility guarantees.
NOTHING IN THIS FILE HAS BACKWARDS COMPATIBILITY GUARANTEES.
"""
from __future__ import absolute_import
from __future__ import division
# BigQuery types as listed in
# https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types
# with aliases (RECORD, BOOLEAN, FLOAT, INTEGER) as defined in
# https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/java/latest/com/google/api/services/bigquery/model/TableFieldSchema.html#setType-java.lang.String-
BIG_QUERY_TO_AVRO_TYPES = {
"STRUCT": "record",
"RECORD": "record",
"STRING": "string",
"BOOL": "boolean",
"BOOLEAN": "boolean",
"BYTES": "bytes",
"FLOAT64": "double",
"FLOAT": "double",
"INT64": "long",
"INTEGER": "long",
"TIME": {
"type": "long",
"logicalType": "time-micros",
},
"TIMESTAMP": {
"type": "long",
"logicalType": "timestamp-micros",
},
"DATE": {
"type": "int",
"logicalType": "date",
},
"DATETIME": "string",
"NUMERIC": {
"type": "bytes",
"logicalType": "decimal",
# https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#numeric-type
"precision": 38,
"scale": 9,
},
"GEOGRAPHY": "string",
}
def get_record_schema_from_dict_table_schema(
schema_name, table_schema, namespace="apache_beam.io.gcp.bigquery"):
# type: (Text, Dict[Text, Any], Text) -> Dict[Text, Any]
"""Convert a table schema into an Avro schema.
Args:
schema_name (Text): The name of the record.
table_schema (Dict[Text, Any]): A BigQuery table schema in dict form.
namespace (Text): The namespace of the Avro schema.
Returns:
Dict[Text, Any]: The schema as an Avro RecordSchema.
"""
avro_fields = [
table_field_to_avro_field(field, ".".join((namespace, schema_name)))
for field in table_schema["fields"]
]
return {
"type": "record",
"name": schema_name,
"fields": avro_fields,
"doc": "Translated Avro Schema for {}".format(schema_name),
"namespace": namespace,
}
def table_field_to_avro_field(table_field, namespace):
# type: (Dict[Text, Any], str) -> Dict[Text, Any]
"""Convert a BigQuery field to an avro field.
Args:
table_field (Dict[Text, Any]): A BigQuery field in dict form.
Returns:
Dict[Text, Any]: An equivalent Avro field in dict form.
"""
assert "type" in table_field, \
"Unable to get type for table field {}".format(table_field)
assert table_field["type"] in BIG_QUERY_TO_AVRO_TYPES, \
"Unable to map BigQuery field type {} to avro type".format(
table_field["type"])
avro_type = BIG_QUERY_TO_AVRO_TYPES[table_field["type"]]
if avro_type == "record":
element_type = get_record_schema_from_dict_table_schema(
table_field["name"],
table_field,
namespace=".".join((namespace, table_field["name"])))
else:
element_type = avro_type
field_mode = table_field.get("mode", "NULLABLE")
if field_mode in (None, "NULLABLE"):
field_type = ["null", element_type]
elif field_mode == "REQUIRED":
field_type = element_type
elif field_mode == "REPEATED":
field_type = {"type": "array", "items": element_type}
else:
raise ValueError("Unkown BigQuery field mode: {}".format(field_mode))
avro_field = {"type": field_type, "name": table_field["name"]}
doc = table_field.get("description")
if doc:
avro_field["doc"] = doc
return avro_field
| 31.631206 | 180 | 0.679596 |
from __future__ import absolute_import
from __future__ import division
{
"STRUCT": "record",
"RECORD": "record",
"STRING": "string",
"BOOL": "boolean",
"BOOLEAN": "boolean",
"BYTES": "bytes",
"FLOAT64": "double",
"FLOAT": "double",
"INT64": "long",
"INTEGER": "long",
"TIME": {
"type": "long",
"logicalType": "time-micros",
},
"TIMESTAMP": {
"type": "long",
"logicalType": "timestamp-micros",
},
"DATE": {
"type": "int",
"logicalType": "date",
},
"DATETIME": "string",
"NUMERIC": {
"type": "bytes",
"logicalType": "decimal",
cision": 38,
"scale": 9,
},
"GEOGRAPHY": "string",
}
def get_record_schema_from_dict_table_schema(
schema_name, table_schema, namespace="apache_beam.io.gcp.bigquery"):
avro_fields = [
table_field_to_avro_field(field, ".".join((namespace, schema_name)))
for field in table_schema["fields"]
]
return {
"type": "record",
"name": schema_name,
"fields": avro_fields,
"doc": "Translated Avro Schema for {}".format(schema_name),
"namespace": namespace,
}
def table_field_to_avro_field(table_field, namespace):
assert "type" in table_field, \
"Unable to get type for table field {}".format(table_field)
assert table_field["type"] in BIG_QUERY_TO_AVRO_TYPES, \
"Unable to map BigQuery field type {} to avro type".format(
table_field["type"])
avro_type = BIG_QUERY_TO_AVRO_TYPES[table_field["type"]]
if avro_type == "record":
element_type = get_record_schema_from_dict_table_schema(
table_field["name"],
table_field,
namespace=".".join((namespace, table_field["name"])))
else:
element_type = avro_type
field_mode = table_field.get("mode", "NULLABLE")
if field_mode in (None, "NULLABLE"):
field_type = ["null", element_type]
elif field_mode == "REQUIRED":
field_type = element_type
elif field_mode == "REPEATED":
field_type = {"type": "array", "items": element_type}
else:
raise ValueError("Unkown BigQuery field mode: {}".format(field_mode))
avro_field = {"type": field_type, "name": table_field["name"]}
doc = table_field.get("description")
if doc:
avro_field["doc"] = doc
return avro_field
| true | true |
f726b1967d8348b9c13635036359c128ffc392c3 | 750 | py | Python | src/language/Perl.py | fearless-spider/repo_info_extractor | fd9301d9ea637df19dcc015e70c300e2eea54a45 | [
"MIT"
] | 2 | 2019-11-27T15:21:42.000Z | 2020-12-12T15:17:42.000Z | src/language/Perl.py | fearless-spider/repo_info_extractor | fd9301d9ea637df19dcc015e70c300e2eea54a45 | [
"MIT"
] | null | null | null | src/language/Perl.py | fearless-spider/repo_info_extractor | fd9301d9ea637df19dcc015e70c300e2eea54a45 | [
"MIT"
] | null | null | null | import re
def extract_libraries(files):
"""Extracts a list of imports that were used in the files
Parameters
----------
files : []string
Full paths to files that need to be analysed
Returns
-------
dict
imports that were used in the provided files, mapped against the language
"""
res = []
# regex to find imports
regex = re.compile(r"(?:[^#]\s+)(?:use|require)[^\S\n]+(?:if.*,\s+)?[\"']?([a-zA-Z][a-zA-Z0-9:]*)[\"']?(?:\s+.*)?;")
for f in files:
with open(file=f, mode='r', errors='ignore') as fr:
contents = ' '.join(fr.readlines())
matches = regex.findall(contents)
if matches:
res.extend(matches)
return {"Perl": res}
| 24.193548 | 120 | 0.536 | import re
def extract_libraries(files):
res = []
regex = re.compile(r"(?:[^#]\s+)(?:use|require)[^\S\n]+(?:if.*,\s+)?[\"']?([a-zA-Z][a-zA-Z0-9:]*)[\"']?(?:\s+.*)?;")
for f in files:
with open(file=f, mode='r', errors='ignore') as fr:
contents = ' '.join(fr.readlines())
matches = regex.findall(contents)
if matches:
res.extend(matches)
return {"Perl": res}
| true | true |
f726b22a3876f904a6f1d950541f05c40c664edb | 4,607 | py | Python | python_gyg/tests/test_location.py | fukac99/python_gyg | 2722da1b2a858336fff584af5acc3e78135ab8a1 | [
"MIT"
] | 1 | 2019-05-22T19:37:16.000Z | 2019-05-22T19:37:16.000Z | python_gyg/tests/test_location.py | fukac99/python_gyg | 2722da1b2a858336fff584af5acc3e78135ab8a1 | [
"MIT"
] | null | null | null | python_gyg/tests/test_location.py | fukac99/python_gyg | 2722da1b2a858336fff584af5acc3e78135ab8a1 | [
"MIT"
] | null | null | null | from unittest import TestCase
import python_gyg
import datetime
GYG_API_KEY = "<your_api_key>"
class TestLocation(TestCase):
def test_is_GetYourGuide_isntance(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s, python_gyg.GetYourGuide))
# def test_get_location_param_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.RequiredParameterError, s.get_location())
#
# def test_get_location_gyg_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.GetYourGuideError, s.get_location(10000000))
def test_get_location_newyork(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue((s.get_location(59))["data"]["locations"][0]["name"] == "New York")
class TestTour(TestCase):
# def test_get_tour_param_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.RequiredParameterError, s.get_tour())
#
# def test_get_tour_gyg_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.GetYourGuideError, s.get_tour(10000000))
def test_get_tour_newyork(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue((s.get_tour(20434))["data"]["tours"][0]["title"] == "New York Photography Experience by Night")
class TestSearchTours(TestCase):
# def test_search_tour_param_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.RequiredParameterError, s.search_tours())
#
# def test_search_tour_bad_param_error(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.BadParameterError, s.search_tours(q="New York", date=332))
#
# def test_search_tour_bad_param_error2(self):
# s = python_gyg.GetYourGuide(GYG_API_KEY)
# self.assertRaises(python_gyg.BadParameterError, s.search_tours(q="New York", date=[42, 42]))
#
def test_search_tour_one_date(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(q="New York", date=datetime.datetime.now()), dict))
def test_search_tour_two_dates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(q="New York",
date=[datetime.datetime.now(),
datetime.datetime.now()]),
dict))
def test_search_tour_by_coordinates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10]), dict))
def test_search_tour_by_categories(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(categories=[1,2]), dict))
def test_search_tour_by_location(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(location=[59, 109]), dict))
def test_search_tour_by_one_price(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], price=30), dict))
def test_search_tour_by_price_range(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], price=[30, 60]), dict))
def test_search_tour_by_max_duration(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], duration=120), dict))
def test_search_tour_by_duration_range(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], duration=[30, 260]), dict))
class TestSearchLocations(TestCase):
def test_search_locations_by_coordinates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(coordinates=[40.75, -73.97, 10]), dict))
def test_search_locations_by_query(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(q="New York"), dict))
def test_search_locations_by_location(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(location=59), dict))
| 45.166667 | 119 | 0.682223 | from unittest import TestCase
import python_gyg
import datetime
GYG_API_KEY = "<your_api_key>"
class TestLocation(TestCase):
def test_is_GetYourGuide_isntance(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s, python_gyg.GetYourGuide))
def test_get_location_newyork(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue((s.get_location(59))["data"]["locations"][0]["name"] == "New York")
class TestTour(TestCase):
def test_get_tour_newyork(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue((s.get_tour(20434))["data"]["tours"][0]["title"] == "New York Photography Experience by Night")
class TestSearchTours(TestCase):
def test_search_tour_one_date(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(q="New York", date=datetime.datetime.now()), dict))
def test_search_tour_two_dates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(q="New York",
date=[datetime.datetime.now(),
datetime.datetime.now()]),
dict))
def test_search_tour_by_coordinates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10]), dict))
def test_search_tour_by_categories(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(categories=[1,2]), dict))
def test_search_tour_by_location(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(location=[59, 109]), dict))
def test_search_tour_by_one_price(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], price=30), dict))
def test_search_tour_by_price_range(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], price=[30, 60]), dict))
def test_search_tour_by_max_duration(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], duration=120), dict))
def test_search_tour_by_duration_range(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_tours(coordinates=[40.75, -73.97, 10], duration=[30, 260]), dict))
class TestSearchLocations(TestCase):
def test_search_locations_by_coordinates(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(coordinates=[40.75, -73.97, 10]), dict))
def test_search_locations_by_query(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(q="New York"), dict))
def test_search_locations_by_location(self):
s = python_gyg.GetYourGuide(GYG_API_KEY)
self.assertTrue(isinstance(s.search_locations(location=59), dict))
| true | true |
f726b366c9cf2b7cd4cfde6038b4f205fcd52e43 | 1,036 | py | Python | vyperlogix/zlib/zlibCompressor.py | raychorn/chrome_gui | f1fade70b61af12ee43c55c075aa9cfd32caa962 | [
"CC0-1.0"
] | 1 | 2020-09-29T01:36:33.000Z | 2020-09-29T01:36:33.000Z | vyperlogix/zlib/zlibCompressor.py | raychorn/chrome_gui | f1fade70b61af12ee43c55c075aa9cfd32caa962 | [
"CC0-1.0"
] | null | null | null | vyperlogix/zlib/zlibCompressor.py | raychorn/chrome_gui | f1fade70b61af12ee43c55c075aa9cfd32caa962 | [
"CC0-1.0"
] | null | null | null | import gzip, zlib, base64
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
__copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-commercial educational use only.,
http://www.VyperLogix.com for details
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
USE AT YOUR OWN RISK.
"""
def decompress_zlib(s):
return zlib.decompress(base64.decodestring(s), 15)
def zlib_compress(s):
return base64.encodestring(zlib.compress(s, 9))
| 31.393939 | 70 | 0.779923 | import gzip, zlib, base64
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
__copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-commercial educational use only.,
http://www.VyperLogix.com for details
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
USE AT YOUR OWN RISK.
"""
def decompress_zlib(s):
return zlib.decompress(base64.decodestring(s), 15)
def zlib_compress(s):
return base64.encodestring(zlib.compress(s, 9))
| true | true |
f726b54f3a46ebdee086c417557534ca46be6aee | 1,875 | py | Python | examples/pacman/independent.py | okkhoy/rlpy | af25d2011fff1d61cb7c5cc8992549808f0c6103 | [
"BSD-3-Clause"
] | 265 | 2015-01-21T08:11:12.000Z | 2021-12-21T08:06:21.000Z | examples/pacman/independent.py | okkhoy/rlpy | af25d2011fff1d61cb7c5cc8992549808f0c6103 | [
"BSD-3-Clause"
] | 22 | 2015-03-26T17:41:43.000Z | 2019-12-19T08:47:36.000Z | examples/pacman/independent.py | okkhoy/rlpy | af25d2011fff1d61cb7c5cc8992549808f0c6103 | [
"BSD-3-Clause"
] | 85 | 2015-02-18T00:25:15.000Z | 2021-11-15T11:10:00.000Z | """
Cart-pole balancing with independent discretization
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from rlpy.Domains import Pacman
from rlpy.Agents import Q_Learning
from rlpy.Representations import *
from rlpy.Policies import eGreedy
from rlpy.Experiments import Experiment
import numpy as np
from hyperopt import hp
param_space = {'discretization': hp.quniform("discretization", 3, 50, 1),
'lambda_': hp.uniform("lambda_", 0., 1.),
'boyan_N0': hp.loguniform("boyan_N0", np.log(1e1), np.log(1e5)),
'initial_learn_rate': hp.loguniform("initial_learn_rate", np.log(5e-2), np.log(1))}
def make_experiment(
exp_id=1, path="./Results/Temp/{domain}/{agent}/{representation}/",
lambda_=0.9,
boyan_N0=22.36,
initial_learn_rate=.068,
discretization=9):
opt = {}
opt["path"] = path
opt["exp_id"] = exp_id
opt["max_steps"] = 150000
opt["num_policy_checks"] = 30
opt["checks_per_policy"] = 1
domain = Pacman()
opt["domain"] = domain
representation = IncrementalTabular(
domain,
discretization=discretization)
policy = eGreedy(representation, epsilon=0.1)
opt["agent"] = Q_Learning(
policy, representation, discount_factor=domain.discount_factor,
lambda_=0.9, initial_learn_rate=initial_learn_rate,
learn_rate_decay_mode="boyan", boyan_N0=boyan_N0)
experiment = Experiment(**opt)
return experiment
if __name__ == '__main__':
#from Tools.run import run_profiled
# run_profiled(make_experiment)
experiment = make_experiment(1)
experiment.run(visualize_steps=True)
experiment.plot()
# experiment.save()
| 32.894737 | 98 | 0.700267 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from rlpy.Domains import Pacman
from rlpy.Agents import Q_Learning
from rlpy.Representations import *
from rlpy.Policies import eGreedy
from rlpy.Experiments import Experiment
import numpy as np
from hyperopt import hp
param_space = {'discretization': hp.quniform("discretization", 3, 50, 1),
'lambda_': hp.uniform("lambda_", 0., 1.),
'boyan_N0': hp.loguniform("boyan_N0", np.log(1e1), np.log(1e5)),
'initial_learn_rate': hp.loguniform("initial_learn_rate", np.log(5e-2), np.log(1))}
def make_experiment(
exp_id=1, path="./Results/Temp/{domain}/{agent}/{representation}/",
lambda_=0.9,
boyan_N0=22.36,
initial_learn_rate=.068,
discretization=9):
opt = {}
opt["path"] = path
opt["exp_id"] = exp_id
opt["max_steps"] = 150000
opt["num_policy_checks"] = 30
opt["checks_per_policy"] = 1
domain = Pacman()
opt["domain"] = domain
representation = IncrementalTabular(
domain,
discretization=discretization)
policy = eGreedy(representation, epsilon=0.1)
opt["agent"] = Q_Learning(
policy, representation, discount_factor=domain.discount_factor,
lambda_=0.9, initial_learn_rate=initial_learn_rate,
learn_rate_decay_mode="boyan", boyan_N0=boyan_N0)
experiment = Experiment(**opt)
return experiment
if __name__ == '__main__':
experiment = make_experiment(1)
experiment.run(visualize_steps=True)
experiment.plot()
| true | true |
f726b5f40791ce2171ac294bd9cf1073746baf44 | 2,896 | py | Python | saleor/checkout/views/discount.py | dedhio/bellastore | 03cad4d11c039c6c33291021def812570c09fe36 | [
"BSD-3-Clause"
] | 3 | 2019-06-09T18:00:54.000Z | 2019-06-18T10:07:39.000Z | saleor/checkout/views/discount.py | dedhio/bellastore | 03cad4d11c039c6c33291021def812570c09fe36 | [
"BSD-3-Clause"
] | 2 | 2019-07-03T21:08:32.000Z | 2019-08-06T02:09:26.000Z | saleor/checkout/views/discount.py | dedhio/bellastore | 03cad4d11c039c6c33291021def812570c09fe36 | [
"BSD-3-Clause"
] | 1 | 2021-04-03T10:47:36.000Z | 2021-04-03T10:47:36.000Z | from datetime import date
from functools import wraps
from django.contrib import messages
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext
from django.views.decorators.http import require_POST
from ...discount.models import Voucher
from ..forms import CheckoutVoucherForm
from ..models import Checkout
from ..utils import (
get_or_empty_db_checkout,
get_taxes_for_checkout,
recalculate_checkout_discount,
remove_voucher_from_checkout,
)
def add_voucher_form(view):
"""Decorate a view injecting a voucher form and handling its submission."""
@wraps(view)
def func(request, checkout):
prefix = "discount"
data = {k: v for k, v in request.POST.items() if k.startswith(prefix)}
voucher_form = CheckoutVoucherForm(
data or None, prefix=prefix, instance=checkout
)
if voucher_form.is_bound:
if voucher_form.is_valid():
voucher_form.save()
next_url = request.GET.get("next", request.META["HTTP_REFERER"])
return redirect(next_url)
else:
remove_voucher_from_checkout(checkout)
# if only discount form was used we clear post for other forms
request.POST = {}
else:
taxes = get_taxes_for_checkout(checkout, request.taxes)
recalculate_checkout_discount(checkout, request.discounts, taxes)
response = view(request, checkout)
if isinstance(response, TemplateResponse):
response.context_data["voucher_form"] = voucher_form
return response
return func
def validate_voucher(view):
"""Decorate a view making it check whether a discount voucher is valid.
If the voucher is invalid it will be removed and the user will be
redirected to the checkout summary view.
"""
@wraps(view)
def func(request, checkout):
if checkout.voucher_code:
try:
Voucher.objects.active(date=date.today()).get(
code=checkout.voucher_code
)
except Voucher.DoesNotExist:
remove_voucher_from_checkout(checkout)
msg = pgettext(
"Checkout warning",
"This voucher has expired. Please review your checkout.",
)
messages.warning(request, msg)
return redirect("checkout:summary")
return view(request, checkout)
return func
@require_POST
@get_or_empty_db_checkout(Checkout.objects.for_display())
def remove_voucher_view(request, checkout):
"""Clear the discount and remove the voucher."""
next_url = request.GET.get("next", request.META["HTTP_REFERER"])
remove_voucher_from_checkout(checkout)
return redirect(next_url)
| 34.070588 | 80 | 0.658494 | from datetime import date
from functools import wraps
from django.contrib import messages
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext
from django.views.decorators.http import require_POST
from ...discount.models import Voucher
from ..forms import CheckoutVoucherForm
from ..models import Checkout
from ..utils import (
get_or_empty_db_checkout,
get_taxes_for_checkout,
recalculate_checkout_discount,
remove_voucher_from_checkout,
)
def add_voucher_form(view):
@wraps(view)
def func(request, checkout):
prefix = "discount"
data = {k: v for k, v in request.POST.items() if k.startswith(prefix)}
voucher_form = CheckoutVoucherForm(
data or None, prefix=prefix, instance=checkout
)
if voucher_form.is_bound:
if voucher_form.is_valid():
voucher_form.save()
next_url = request.GET.get("next", request.META["HTTP_REFERER"])
return redirect(next_url)
else:
remove_voucher_from_checkout(checkout)
request.POST = {}
else:
taxes = get_taxes_for_checkout(checkout, request.taxes)
recalculate_checkout_discount(checkout, request.discounts, taxes)
response = view(request, checkout)
if isinstance(response, TemplateResponse):
response.context_data["voucher_form"] = voucher_form
return response
return func
def validate_voucher(view):
@wraps(view)
def func(request, checkout):
if checkout.voucher_code:
try:
Voucher.objects.active(date=date.today()).get(
code=checkout.voucher_code
)
except Voucher.DoesNotExist:
remove_voucher_from_checkout(checkout)
msg = pgettext(
"Checkout warning",
"This voucher has expired. Please review your checkout.",
)
messages.warning(request, msg)
return redirect("checkout:summary")
return view(request, checkout)
return func
@require_POST
@get_or_empty_db_checkout(Checkout.objects.for_display())
def remove_voucher_view(request, checkout):
next_url = request.GET.get("next", request.META["HTTP_REFERER"])
remove_voucher_from_checkout(checkout)
return redirect(next_url)
| true | true |
f726b60b2e30efcf835322d9c0d038acf405f3ab | 895 | py | Python | 086.py | zlsun/ProjectEuler | 813ec545484924a052f1bd7fd90a4c676eea3bba | [
"MIT"
] | null | null | null | 086.py | zlsun/ProjectEuler | 813ec545484924a052f1bd7fd90a4c676eea3bba | [
"MIT"
] | null | null | null | 086.py | zlsun/ProjectEuler | 813ec545484924a052f1bd7fd90a4c676eea3bba | [
"MIT"
] | null | null | null | #-*- encoding: utf-8 -*-
"""
Cuboid route
A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10 and the path is shown on the diagram.
However, there are up to three "shortest" path candidates for any given cuboid and the shortest route doesn't always have integer length.
It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with integer dimensions, up to a maximum size of M by M by M, for which the shortest route has integer length when M = 100. This is the least value of M for which the number of solutions first exceeds two thousand; the number of solutions when M = 99 is 1975.
Find the least value of M such that the number of solutions first exceeds one million.
"""
from utils import *
#
| 49.722222 | 341 | 0.75419 |
from utils import *
| true | true |
f726b71c0d372ca68b0e214f1e0ae937fead58bb | 642 | py | Python | url_migration/management/commands/remove_expired_redirects.py | riklaunim/django-url-migration | 0d1115d02b64a895934ecdd7387e65b34b3d68e7 | [
"BSD-3-Clause"
] | 4 | 2017-04-28T18:58:31.000Z | 2017-10-04T07:32:47.000Z | url_migration/management/commands/remove_expired_redirects.py | riklaunim/django-url-migration | 0d1115d02b64a895934ecdd7387e65b34b3d68e7 | [
"BSD-3-Clause"
] | 3 | 2021-04-23T11:30:49.000Z | 2021-04-26T14:12:29.000Z | url_migration/management/commands/remove_expired_redirects.py | riklaunim/django-url-migration | 0d1115d02b64a895934ecdd7387e65b34b3d68e7 | [
"BSD-3-Clause"
] | 1 | 2021-04-23T11:07:36.000Z | 2021-04-23T11:07:36.000Z | from django.core.management.base import BaseCommand
from django.utils import timezone
from url_migration import models
class Command(BaseCommand):
def handle(self, **options):
for rule in models.UrlRegexpMapping.objects.filter(last_usage__isnull=False):
self._remove_if_unused(rule)
for rule in models.UrlMapping.objects.filter(last_usage__isnull=False):
self._remove_if_unused(rule)
def _remove_if_unused(self, rule):
if rule.last_usage.used_date + rule.expire_after < timezone.now():
self.stdout.write('Removing expired rule %s' % str(rule))
rule.delete()
| 35.666667 | 85 | 0.71028 | from django.core.management.base import BaseCommand
from django.utils import timezone
from url_migration import models
class Command(BaseCommand):
def handle(self, **options):
for rule in models.UrlRegexpMapping.objects.filter(last_usage__isnull=False):
self._remove_if_unused(rule)
for rule in models.UrlMapping.objects.filter(last_usage__isnull=False):
self._remove_if_unused(rule)
def _remove_if_unused(self, rule):
if rule.last_usage.used_date + rule.expire_after < timezone.now():
self.stdout.write('Removing expired rule %s' % str(rule))
rule.delete()
| true | true |
f726b73d345c483e69c29ca4afc5bfc2e99d7b7f | 4,201 | py | Python | fellowship/contract_generator.py | nokia/contract-test-framework | 67976b3361b1bb28639059720d247987ff203224 | [
"BSD-3-Clause"
] | 2 | 2021-10-05T06:47:07.000Z | 2022-03-03T23:34:50.000Z | fellowship/contract_generator.py | nokia/contract-test-framework | 67976b3361b1bb28639059720d247987ff203224 | [
"BSD-3-Clause"
] | 10 | 2021-09-02T06:58:55.000Z | 2021-12-03T19:21:39.000Z | fellowship/contract_generator.py | nokia/contract-test-framework | 67976b3361b1bb28639059720d247987ff203224 | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2021 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
import json
import logging
import os
from urllib.parse import urlparse
from genson import SchemaBuilder
from .contract_renderer import ContractRenderer
from .strict_schema_builder import StrictSchemaBuilder
LOGGER = logging.getLogger(__name__)
class ContractGenerator:
"""Generates a json contract based on a request and its expected output.
Attributes:
contract_path (str): The path of file that will be generated
type_of_contract (str): The type to write to contract in field contract_type
can be either rest or grpc. Default value: rest
"""
def __init__(self, output_path: str, type_of_contract: str = "rest") -> None:
self.contract_path = output_path
self.type_of_contract = type_of_contract
self.contract_renderer = ContractRenderer(os.path.dirname(output_path))
self.schema_builder = SchemaBuilder()
def set_type_of_schema_builder(self, type_of_schema_builder: str = "type") -> None:
"""Sets the type of schema builder can be either type or strict
Type builder is the default and generates the contract with type validation. The
Other type of builder supported is strict which will generate contract with
expected value for each field.
Args:
type_of_schema_builder (str): The type of builder to use when generating
schema can be either type or strict. Default value: type
"""
if type_of_schema_builder == "strict":
self.schema_builder = StrictSchemaBuilder()
else:
self.schema_builder = SchemaBuilder()
def generate_and_save_contract(self, request_kwargs: dict, expected_json: dict) \
-> None:
""" Function that generates a new contract and saves it to specified location
Args:
request_kwargs (dict): A dictionary that describes the request that should
return the expected_json. The dictionary needs to contain url (at least
endpoint) and method. Optional parameters include headers and data
expected_json (dict): Is the Json response that is expected when the request
from the request_kwargs dictionary is sent.
"""
contract_json = self._generate_contract(request_kwargs, expected_json)
self._save_contract(contract_json)
def _generate_contract(self, request_kwargs, expected_json):
if self.type_of_contract.lower() == "rest":
self._check_request_kwargs(request_kwargs)
self.schema_builder.add_schema({'contract_type': self.type_of_contract,
'request': {**request_kwargs}})
self.schema_builder.add_object(expected_json)
LOGGER.info("The generated schema: %s \nSaved to file: %s",
self.schema_builder.to_json(indent=4), self.contract_path)
return self.schema_builder.to_schema()
def _save_contract(self, contract_json):
with open(self.contract_path, 'w', encoding="UTF-8") as contract_file:
contract_file.write(json.dumps(contract_json,
indent=4))
self.contract_renderer.render_and_validate_contract(
os.path.basename(self.contract_path)
)
def _check_request_kwargs(self, request_kwargs):
if 'headers' not in request_kwargs:
self._add_default_headers(request_kwargs)
self._add_protocol_and_host(request_kwargs)
@staticmethod
def _add_default_headers(request_kwargs):
request_kwargs['headers'] = "{{ config.default_headers }}"
@staticmethod
def _add_protocol_and_host(request_kwargs):
uri = urlparse(request_kwargs['url'])
if not uri.netloc:
request_kwargs['url'] = "{{ config.host }}" + request_kwargs['url']
if not uri.scheme:
request_kwargs['url'] = "{{ config.protocol }}://" + request_kwargs['url']
return request_kwargs
| 42.434343 | 89 | 0.660081 |
import json
import logging
import os
from urllib.parse import urlparse
from genson import SchemaBuilder
from .contract_renderer import ContractRenderer
from .strict_schema_builder import StrictSchemaBuilder
LOGGER = logging.getLogger(__name__)
class ContractGenerator:
def __init__(self, output_path: str, type_of_contract: str = "rest") -> None:
self.contract_path = output_path
self.type_of_contract = type_of_contract
self.contract_renderer = ContractRenderer(os.path.dirname(output_path))
self.schema_builder = SchemaBuilder()
def set_type_of_schema_builder(self, type_of_schema_builder: str = "type") -> None:
if type_of_schema_builder == "strict":
self.schema_builder = StrictSchemaBuilder()
else:
self.schema_builder = SchemaBuilder()
def generate_and_save_contract(self, request_kwargs: dict, expected_json: dict) \
-> None:
contract_json = self._generate_contract(request_kwargs, expected_json)
self._save_contract(contract_json)
def _generate_contract(self, request_kwargs, expected_json):
if self.type_of_contract.lower() == "rest":
self._check_request_kwargs(request_kwargs)
self.schema_builder.add_schema({'contract_type': self.type_of_contract,
'request': {**request_kwargs}})
self.schema_builder.add_object(expected_json)
LOGGER.info("The generated schema: %s \nSaved to file: %s",
self.schema_builder.to_json(indent=4), self.contract_path)
return self.schema_builder.to_schema()
def _save_contract(self, contract_json):
with open(self.contract_path, 'w', encoding="UTF-8") as contract_file:
contract_file.write(json.dumps(contract_json,
indent=4))
self.contract_renderer.render_and_validate_contract(
os.path.basename(self.contract_path)
)
def _check_request_kwargs(self, request_kwargs):
if 'headers' not in request_kwargs:
self._add_default_headers(request_kwargs)
self._add_protocol_and_host(request_kwargs)
@staticmethod
def _add_default_headers(request_kwargs):
request_kwargs['headers'] = "{{ config.default_headers }}"
@staticmethod
def _add_protocol_and_host(request_kwargs):
uri = urlparse(request_kwargs['url'])
if not uri.netloc:
request_kwargs['url'] = "{{ config.host }}" + request_kwargs['url']
if not uri.scheme:
request_kwargs['url'] = "{{ config.protocol }}://" + request_kwargs['url']
return request_kwargs
| true | true |
f726b7dadf4efb4ce13b43f57fed824b080e01f6 | 387 | py | Python | nifty/wsgi.py | waynekyamamoto/jakobia | 04b82f620267f500d7b19937ef2631c6a840c42a | [
"Apache-2.0"
] | null | null | null | nifty/wsgi.py | waynekyamamoto/jakobia | 04b82f620267f500d7b19937ef2631c6a840c42a | [
"Apache-2.0"
] | null | null | null | nifty/wsgi.py | waynekyamamoto/jakobia | 04b82f620267f500d7b19937ef2631c6a840c42a | [
"Apache-2.0"
] | null | null | null | """
WSGI config for nifty project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nifty.settings')
application = get_wsgi_application()
| 22.764706 | 78 | 0.782946 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nifty.settings')
application = get_wsgi_application()
| true | true |
f726b86af605e3f6febf6ed5b3e113bf41b88604 | 1,158 | py | Python | tests/metrics/test_statsd_metrics.py | bear8421/thumbor | 00a0c44d44b8fa5f06c38deee7123793addda404 | [
"MIT"
] | 1 | 2021-12-24T02:01:52.000Z | 2021-12-24T02:01:52.000Z | tests/metrics/test_statsd_metrics.py | bear8421/thumbor | 00a0c44d44b8fa5f06c38deee7123793addda404 | [
"MIT"
] | 2 | 2022-03-10T22:11:18.000Z | 2022-03-16T22:42:04.000Z | tests/metrics/test_statsd_metrics.py | bear8421/thumbor | 00a0c44d44b8fa5f06c38deee7123793addda404 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from preggy import expect
import thumbor.metrics
from tests.base import TestCase
from thumbor.config import Config
from thumbor.context import Context
from thumbor.importer import Importer
class StatsdMetricsTestCase(TestCase):
def get_context(self):
conf = Config()
conf.METRICS = "thumbor.metrics.statsd_metrics"
imp = Importer(conf)
imp.import_modules()
return Context(None, conf, imp)
def test_should_initialize_metrics(self):
expect(self.context.metrics).to_be_instance_of(
thumbor.metrics.statsd_metrics.Metrics
)
def test_should_not_fail_on_use(self):
expect(self.context.metrics.incr("test.count")).not_to_be_an_error()
expect(self.context.metrics.incr("test.count", 2)).not_to_be_an_error()
expect(
self.context.metrics.timing("test.time", 100)
).not_to_be_an_error()
| 29.692308 | 79 | 0.707254 |
from preggy import expect
import thumbor.metrics
from tests.base import TestCase
from thumbor.config import Config
from thumbor.context import Context
from thumbor.importer import Importer
class StatsdMetricsTestCase(TestCase):
def get_context(self):
conf = Config()
conf.METRICS = "thumbor.metrics.statsd_metrics"
imp = Importer(conf)
imp.import_modules()
return Context(None, conf, imp)
def test_should_initialize_metrics(self):
expect(self.context.metrics).to_be_instance_of(
thumbor.metrics.statsd_metrics.Metrics
)
def test_should_not_fail_on_use(self):
expect(self.context.metrics.incr("test.count")).not_to_be_an_error()
expect(self.context.metrics.incr("test.count", 2)).not_to_be_an_error()
expect(
self.context.metrics.timing("test.time", 100)
).not_to_be_an_error()
| true | true |
f726b86fa3b46ca58a327fc2e1c4d7a5610f5095 | 1,055 | py | Python | processing/gray-scale-processing.py | rsampaths16/ReRes | 51089c806c57087eb94d9a659036ebed88e96f13 | [
"Apache-2.0"
] | 2 | 2017-12-19T07:50:25.000Z | 2018-03-26T05:59:54.000Z | processing/gray-scale-processing.py | rsampaths16/ReRes | 51089c806c57087eb94d9a659036ebed88e96f13 | [
"Apache-2.0"
] | null | null | null | processing/gray-scale-processing.py | rsampaths16/ReRes | 51089c806c57087eb94d9a659036ebed88e96f13 | [
"Apache-2.0"
] | 1 | 2020-04-26T03:12:35.000Z | 2020-04-26T03:12:35.000Z | import numpy
import scipy
import glob
from matplotlib import pyplot
from scipy import misc
from numpy import random
random.seed(0)
SIZE = 128
ORIGINAL = '../data/offline-data/black-and-white-images/original'
HIGH = '../data/offline-data/black-and-white-images/train/high'
LOW = '../data/offline-data/black-and-white-images/train/low'
def sample_patch(image):
x = random.randint(0, image.shape[0] - SIZE, dtype=numpy.int)
y = random.randint(0, image.shape[1] - SIZE, dtype=numpy.int)
high = numpy.copy(image[x:x+SIZE, y:y+SIZE])
low = numpy.copy(high)
low = misc.imresize(low, (SIZE // 4, SIZE // 4))
low = misc.imresize(low, (SIZE, SIZE))
return low, high
unique_id = 1
for image_path in glob.glob(ORIGINAL + '/*.jpg'):
print(image_path)
sample = 1
image = misc.imread(image_path)
while sample > 0:
low, high = sample_patch(image)
misc.imsave(HIGH + '/' + str(unique_id) + '.jpg', high)
misc.imsave(LOW + '/' + str(unique_id) + '.jpg', low)
sample -= 1
unique_id += 1
| 31.029412 | 65 | 0.649289 | import numpy
import scipy
import glob
from matplotlib import pyplot
from scipy import misc
from numpy import random
random.seed(0)
SIZE = 128
ORIGINAL = '../data/offline-data/black-and-white-images/original'
HIGH = '../data/offline-data/black-and-white-images/train/high'
LOW = '../data/offline-data/black-and-white-images/train/low'
def sample_patch(image):
x = random.randint(0, image.shape[0] - SIZE, dtype=numpy.int)
y = random.randint(0, image.shape[1] - SIZE, dtype=numpy.int)
high = numpy.copy(image[x:x+SIZE, y:y+SIZE])
low = numpy.copy(high)
low = misc.imresize(low, (SIZE // 4, SIZE // 4))
low = misc.imresize(low, (SIZE, SIZE))
return low, high
unique_id = 1
for image_path in glob.glob(ORIGINAL + '/*.jpg'):
print(image_path)
sample = 1
image = misc.imread(image_path)
while sample > 0:
low, high = sample_patch(image)
misc.imsave(HIGH + '/' + str(unique_id) + '.jpg', high)
misc.imsave(LOW + '/' + str(unique_id) + '.jpg', low)
sample -= 1
unique_id += 1
| true | true |
f726b8d12a6a6783daf22dfc04e130655b135796 | 5,213 | py | Python | training_3DMatch.py | aosheng1996/D3Feat | d005f3811c12764c16d4f5e9a01c6720e7e72392 | [
"MIT"
] | 1 | 2020-05-11T15:49:34.000Z | 2020-05-11T15:49:34.000Z | training_3DMatch.py | aosheng1996/D3Feat | d005f3811c12764c16d4f5e9a01c6720e7e72392 | [
"MIT"
] | null | null | null | training_3DMatch.py | aosheng1996/D3Feat | d005f3811c12764c16d4f5e9a01c6720e7e72392 | [
"MIT"
] | null | null | null | # Common libs
import time
import os
import sys
# Custom libs
from utils.config import Config
from utils.trainer import ModelTrainer
from models.KPFCNN_model import KernelPointFCNN
# Dataset
from datasets.ThreeDMatch import ThreeDMatchDataset
# ----------------------------------------------------------------------------------------------------------------------
#
# Config Class
# \******************/
#
class ThreeDMatchConfig(Config):
"""
Override the parameters you want to modify for this dataset
"""
####################
# Dataset parameters
####################
is_test = False
gpu_id = 0
dataset = '3DMatch'
# Number of CPU threads for the input pipeline
input_threads = 8
#########################
# Architecture definition
#########################
architecture = ['simple',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb_strided',
'resnetb',
'resnetb_strided',
'resnetb',
'nearest_upsample',
'unary',
'nearest_upsample',
'unary',
'nearest_upsample',
'unary',
'nearest_upsample',
'unary',
'last_unary']
# KPConv specific parameters
num_kernel_points = 15
first_subsampling_dl = 0.03
# Density of neighborhoods for deformable convs (which need bigger radiuses). For normal conv we use KP_extent
density_parameter = 5.0
# Influence function of KPConv in ('constant', 'linear', gaussian)
KP_influence = 'linear'
KP_extent = 1.0
# Aggregation function of KPConv in ('closest', 'sum')
convolution_mode = 'sum'
# Can the network learn modulations in addition to deformations
modulated = False
# detector loss weight
det_loss_weight = 1
# Offset loss
# 'permissive' only constrains offsets inside the big radius
# 'fitting' helps deformed kernels to adapt to the geometry by penalizing distance to input points
offsets_loss = 'fitting'
offsets_decay = 0.1
# Choice of input features
in_features_dim = 1
# Batch normalization parameters
use_batch_norm = True
batch_norm_momentum = 0.98
# batch hard loss safe radius
safe_radius = 0.1
#####################
# Training parameters
#####################
# Maximal number of epochs
max_epoch = 200
# Learning rate management
learning_rate = 1e-1
momentum = 0.98
lr_decays = {i: 0.1 ** (1 / 80) for i in range(1, max_epoch)}
grad_clip_norm = 100.0
# Number of batch
batch_num = 1
# Number of keypoints
keypts_num = 64
# Number of steps per epochs (cannot be None for this dataset)
epoch_steps = 5000
# Number of validation examples per epoch
validation_size = 500
# Number of epoch between each snapshot
snapshot_gap = 1
# Augmentations
augment_scale_anisotropic = True
augment_symmetries = [False, False, False]
augment_rotation = 1
augment_scale_min = 0.9
augment_scale_max = 1.1
augment_noise = 0.005
augment_occlusion = 'none'
# Do we nee to save convergence
saving = True
saving_path = None
# ----------------------------------------------------------------------------------------------------------------------
#
# Main Call
# \***************/
#
if __name__ == '__main__':
##########################
# Initiate the environment
##########################
# Enable/Disable warnings (set level to '0'/'3')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
###########################
# Load the model parameters
###########################
config = ThreeDMatchConfig()
##############
# Prepare Data
##############
print()
print('Dataset Preparation')
print('*******************')
# Initiate dataset configuration
dataset = ThreeDMatchDataset(config.input_threads, voxel_size=config.first_subsampling_dl)
# Create subsampled input clouds
dl0 = config.first_subsampling_dl
# dataset.load_subsampled_clouds(dl0)
# Initialize input pipelines
dataset.init_input_pipeline(config)
# Test the input pipeline alone with this debug function
# dataset.check_input_pipeline_timing(config)
##############
# Define Model
##############
print('Creating Model')
print('**************\n')
t1 = time.time()
# Model class
model = KernelPointFCNN(dataset.flat_inputs, config)
# Trainer class
trainer = ModelTrainer(model)
# trainer = ModelTrainer(model, restore_snap='results/Log_/snapshots/snap-')
t2 = time.time()
print('\n----------------')
print('Done in {:.1f} s'.format(t2 - t1))
print('----------------\n')
################
# Start training
################
print('Start Training')
print('**************\n')
trainer.train(model, dataset)
| 25.0625 | 120 | 0.531939 |
import time
import os
import sys
from utils.config import Config
from utils.trainer import ModelTrainer
from models.KPFCNN_model import KernelPointFCNN
from datasets.ThreeDMatch import ThreeDMatchDataset
class ThreeDMatchConfig(Config):
False
det_loss_weight = 1
offsets_loss = 'fitting'
offsets_decay = 0.1
in_features_dim = 1
use_batch_norm = True
batch_norm_momentum = 0.98
safe_radius = 0.1
rotation = 1
augment_scale_min = 0.9
augment_scale_max = 1.1
augment_noise = 0.005
augment_occlusion = 'none'
saving = True
saving_path = None
if __name__ == '__main__':
| true | true |
f726b9d13411d60ad6b93cfd0a6545aa3baa5701 | 367 | py | Python | tests/test_models.py | inmagik/django-rest-admin | 61c0d1a993ebcf144352e0ee0f916d9e63c1ccf7 | [
"BSD-3-Clause"
] | 15 | 2015-11-13T00:22:11.000Z | 2020-02-04T12:07:05.000Z | tests/test_models.py | inmagik/django-rest-admin | 61c0d1a993ebcf144352e0ee0f916d9e63c1ccf7 | [
"BSD-3-Clause"
] | null | null | null | tests/test_models.py | inmagik/django-rest-admin | 61c0d1a993ebcf144352e0ee0f916d9e63c1ccf7 | [
"BSD-3-Clause"
] | 5 | 2015-11-13T11:23:19.000Z | 2019-08-06T18:43:58.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-rest-admin
------------
Tests for `django-rest-admin` models module.
"""
from django.test import TestCase
from django_rest_admin import models
class TestDjango_rest_admin(TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
| 14.115385 | 44 | 0.640327 |
from django.test import TestCase
from django_rest_admin import models
class TestDjango_rest_admin(TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
| true | true |
f726b9d6bccaaeb47166b01a9fa17fc6f824bd62 | 3,497 | py | Python | pypureclient/flasharray/FA_2_11/models/maintenance_window_post.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 14 | 2018-12-07T18:30:27.000Z | 2022-02-22T09:12:33.000Z | pypureclient/flasharray/FA_2_11/models/maintenance_window_post.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 28 | 2019-09-17T21:03:52.000Z | 2022-03-29T22:07:35.000Z | pypureclient/flasharray/FA_2_11/models/maintenance_window_post.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 15 | 2020-06-11T15:50:08.000Z | 2022-03-21T09:27:25.000Z | # coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.11
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_11 import models
class MaintenanceWindowPost(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'timeout': 'int'
}
attribute_map = {
'timeout': 'timeout'
}
required_args = {
}
def __init__(
self,
timeout=None, # type: int
):
"""
Keyword args:
timeout (int): The specified length of time that alerts are suppressed during a maintenance window, measured in milliseconds. The maintenance window timeout value must be between `60000` (1 minute) and `86400000` (24 hours). The value entered is rounded down to the nearest minute. The `names` and `timeout` parameters must be set together, and the `names` parameter must be set to `environment`.
"""
if timeout is not None:
self.timeout = timeout
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `MaintenanceWindowPost`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(MaintenanceWindowPost, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, MaintenanceWindowPost):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 31.223214 | 408 | 0.571061 |
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_11 import models
class MaintenanceWindowPost(object):
swagger_types = {
'timeout': 'int'
}
attribute_map = {
'timeout': 'timeout'
}
required_args = {
}
def __init__(
self,
timeout=None,
):
if timeout is not None:
self.timeout = timeout
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `MaintenanceWindowPost`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(MaintenanceWindowPost, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, MaintenanceWindowPost):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f726ba59f261a358f8d57550d94c95d42ecd6359 | 1,276 | py | Python | tests/util.py | ecoal95/saltfs | 4d2596794a70919c2887688d6d116f2f5bb5cf1e | [
"Apache-2.0",
"MIT"
] | 1 | 2021-01-07T18:49:38.000Z | 2021-01-07T18:49:38.000Z | tests/util.py | ecoal95/saltfs | 4d2596794a70919c2887688d6d116f2f5bb5cf1e | [
"Apache-2.0",
"MIT"
] | null | null | null | tests/util.py | ecoal95/saltfs | 4d2596794a70919c2887688d6d116f2f5bb5cf1e | [
"Apache-2.0",
"MIT"
] | null | null | null | import os
RED = 31
GREEN = 32
BLUE = 34
MAGENTA = 35
def color(code, string):
return '\033[' + str(code) + 'm' + string + '\033[0m'
def display_path(path):
return color(MAGENTA, path)
def colon():
return color(BLUE, ':')
EXCLUDE_DIRS = ['.git', '.vagrant']
def project_path():
# One dirname for tests dir, another for project dir
project_dir = os.path.dirname(os.path.dirname(__file__))
common = os.path.commonpath([project_dir, os.getcwd()])
return project_dir.replace(common, '.', 1) # Only replace once
def paths():
for root, dirs, files in os.walk(project_path(), topdown=True):
for exclude_dir in EXCLUDE_DIRS:
if exclude_dir in dirs:
dirs.remove(exclude_dir)
for filename in files:
yield os.path.join(root, filename)
class TestResult(object):
pass
class Success(TestResult):
def __init__(self, message):
self.message = message
def is_success(self):
return True
def is_failure(self):
return False
class Failure(TestResult):
def __init__(self, message, output):
self.message = message
self.output = output
def is_success(self):
return False
def is_failure(self):
return True
| 19.333333 | 67 | 0.630094 | import os
RED = 31
GREEN = 32
BLUE = 34
MAGENTA = 35
def color(code, string):
return '\033[' + str(code) + 'm' + string + '\033[0m'
def display_path(path):
return color(MAGENTA, path)
def colon():
return color(BLUE, ':')
EXCLUDE_DIRS = ['.git', '.vagrant']
def project_path():
project_dir = os.path.dirname(os.path.dirname(__file__))
common = os.path.commonpath([project_dir, os.getcwd()])
return project_dir.replace(common, '.', 1)
def paths():
for root, dirs, files in os.walk(project_path(), topdown=True):
for exclude_dir in EXCLUDE_DIRS:
if exclude_dir in dirs:
dirs.remove(exclude_dir)
for filename in files:
yield os.path.join(root, filename)
class TestResult(object):
pass
class Success(TestResult):
def __init__(self, message):
self.message = message
def is_success(self):
return True
def is_failure(self):
return False
class Failure(TestResult):
def __init__(self, message, output):
self.message = message
self.output = output
def is_success(self):
return False
def is_failure(self):
return True
| true | true |
f726bab48ffce3b6ae7271247b2fa10be660d332 | 488 | py | Python | challenges/insertion/test_insertion.py | glasscharlie/data-structures-and-algorithms | 4546a0606334c6e3156b567d8cc82d39fb183c58 | [
"MIT"
] | null | null | null | challenges/insertion/test_insertion.py | glasscharlie/data-structures-and-algorithms | 4546a0606334c6e3156b567d8cc82d39fb183c58 | [
"MIT"
] | 4 | 2019-12-02T22:28:03.000Z | 2019-12-09T04:17:53.000Z | challenges/insertion/test_insertion.py | glasscharlie/data-structures-and-algorithms | 4546a0606334c6e3156b567d8cc82d39fb183c58 | [
"MIT"
] | null | null | null | from insertion import insertion
def test_unique_values():
lst = [8,4,23,42,16,15]
expected = [4,8,15,16,23,42]
actual = insertion(lst)
assert actual == expected
def test_duplicate_value():
lst = [8,4,23,42,16,15,8,23]
expected = [4,8,8,15,16,23,23,42]
actual = insertion(lst)
assert actual == expected
def test_negative_values():
lst = [8,4,23,-42,16,-15]
expected = [-42,-15,4,8,16,23]
actual = insertion(lst)
assert actual == expected
| 24.4 | 37 | 0.631148 | from insertion import insertion
def test_unique_values():
lst = [8,4,23,42,16,15]
expected = [4,8,15,16,23,42]
actual = insertion(lst)
assert actual == expected
def test_duplicate_value():
lst = [8,4,23,42,16,15,8,23]
expected = [4,8,8,15,16,23,23,42]
actual = insertion(lst)
assert actual == expected
def test_negative_values():
lst = [8,4,23,-42,16,-15]
expected = [-42,-15,4,8,16,23]
actual = insertion(lst)
assert actual == expected
| true | true |
f726bd9b22797e229793a51530000a11ef85bb1c | 3,516 | py | Python | src/dss/server/dss_logger.py | akraino-edge-stack/ta-distributed-state-server | bd5a0a173f1ae9c64782fbf47565cc26ed23b448 | [
"Apache-2.0"
] | null | null | null | src/dss/server/dss_logger.py | akraino-edge-stack/ta-distributed-state-server | bd5a0a173f1ae9c64782fbf47565cc26ed23b448 | [
"Apache-2.0"
] | null | null | null | src/dss/server/dss_logger.py | akraino-edge-stack/ta-distributed-state-server | bd5a0a173f1ae9c64782fbf47565cc26ed23b448 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Nokia
#
# 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 sys
import logging
import logging.handlers
from dss.api import dss_error
class Logger:
levels = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.error}
DEST_CONSOLE = 1
DEST_SYSLOG = 2
dests = {'console': DEST_CONSOLE,
'syslog': DEST_SYSLOG}
def __init__(self, dest, verbose, level):
self.verbose = verbose
self.dest = Logger.str_to_dest(dest)
self.level = Logger.str_to_level(level)
self.init()
def init(self):
args = {}
if self.level not in Logger.levels.values():
raise dss_error.Error('Invalid level value, possible values are %s' % str(Logger.levels))
if self.dest not in Logger.dests.values():
raise dss_error.Error('Invalid destination value, possible values are %s' % str(Logger.dests))
if self.verbose:
if self.dest is Logger.DEST_CONSOLE:
args['format'] = '[%(asctime)s %(levelname)7s %(module)s(%(lineno)3s)] %(message)s'
else:
args['format'] = '[%(module)s(%(lineno)3s)] %(message)s'
else:
args['format'] = '%(message)s'
if self.dest is Logger.DEST_CONSOLE:
args['stream'] = sys.stdout
elif self.dest is Logger.DEST_SYSLOG:
logging.getLogger('').addHandler(logging.handlers.SysLogHandler(address='/dev/log'))
args['level'] = self.level
logging.basicConfig(**args)
def set_level(self, level):
self.level = Logger.str_to_level(level)
self.init()
def set_dest(self, dest):
self.dest = Logger.str_to_dest(dest)
self.init()
@staticmethod
def str_to_level(level):
ret = None
try:
ret = Logger.levels[level]
except KeyError as exp:
raise dss_error.Error('Invalid log level, possible values %s' % str(Logger.levels.keys()))
return ret
@staticmethod
def str_to_dest(dest):
ret = None
try:
ret = Logger.dests[dest]
except KeyError as exp:
raise dss_error.Error('Invalid destination, possible values %s' % str(Logger.dests.keys()))
return ret
@staticmethod
def level_to_str(level):
for key, value in Logger.levels.iteritems():
if value is level:
return key
return None
@staticmethod
def dest_to_str(dest):
for key, value in Logger.dests.iteritems():
if value is dest:
return key
return None
if __name__ == '__main__':
dest = Logger.str_to_dest('console')
level = Logger.str_to_level('debug')
logger = Logger(dest, True, level)
world='world'
logging.error('hello %s!' % world)
logging.warn('hello %s!' % world)
logging.info('hello %s!' % world)
logging.debug('hello %s!' % world)
| 30.842105 | 106 | 0.614903 |
import sys
import logging
import logging.handlers
from dss.api import dss_error
class Logger:
levels = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.error}
DEST_CONSOLE = 1
DEST_SYSLOG = 2
dests = {'console': DEST_CONSOLE,
'syslog': DEST_SYSLOG}
def __init__(self, dest, verbose, level):
self.verbose = verbose
self.dest = Logger.str_to_dest(dest)
self.level = Logger.str_to_level(level)
self.init()
def init(self):
args = {}
if self.level not in Logger.levels.values():
raise dss_error.Error('Invalid level value, possible values are %s' % str(Logger.levels))
if self.dest not in Logger.dests.values():
raise dss_error.Error('Invalid destination value, possible values are %s' % str(Logger.dests))
if self.verbose:
if self.dest is Logger.DEST_CONSOLE:
args['format'] = '[%(asctime)s %(levelname)7s %(module)s(%(lineno)3s)] %(message)s'
else:
args['format'] = '[%(module)s(%(lineno)3s)] %(message)s'
else:
args['format'] = '%(message)s'
if self.dest is Logger.DEST_CONSOLE:
args['stream'] = sys.stdout
elif self.dest is Logger.DEST_SYSLOG:
logging.getLogger('').addHandler(logging.handlers.SysLogHandler(address='/dev/log'))
args['level'] = self.level
logging.basicConfig(**args)
def set_level(self, level):
self.level = Logger.str_to_level(level)
self.init()
def set_dest(self, dest):
self.dest = Logger.str_to_dest(dest)
self.init()
@staticmethod
def str_to_level(level):
ret = None
try:
ret = Logger.levels[level]
except KeyError as exp:
raise dss_error.Error('Invalid log level, possible values %s' % str(Logger.levels.keys()))
return ret
@staticmethod
def str_to_dest(dest):
ret = None
try:
ret = Logger.dests[dest]
except KeyError as exp:
raise dss_error.Error('Invalid destination, possible values %s' % str(Logger.dests.keys()))
return ret
@staticmethod
def level_to_str(level):
for key, value in Logger.levels.iteritems():
if value is level:
return key
return None
@staticmethod
def dest_to_str(dest):
for key, value in Logger.dests.iteritems():
if value is dest:
return key
return None
if __name__ == '__main__':
dest = Logger.str_to_dest('console')
level = Logger.str_to_level('debug')
logger = Logger(dest, True, level)
world='world'
logging.error('hello %s!' % world)
logging.warn('hello %s!' % world)
logging.info('hello %s!' % world)
logging.debug('hello %s!' % world)
| true | true |
f726be4df3aac1b1ae5b316e7cceff2b07cb123a | 38 | py | Python | files2md/structure_objects/structurable_directory/__init__.py | KacperKotlewski/file_structure_to_markdown | aad0e1c80f88e0b3d079cf242d43fdc4b7a369f7 | [
"MIT"
] | 1 | 2020-02-22T00:41:04.000Z | 2020-02-22T00:41:04.000Z | files2md/structure_objects/structurable_directory/__init__.py | KacperKotlewski/file_structure_to_markdown | aad0e1c80f88e0b3d079cf242d43fdc4b7a369f7 | [
"MIT"
] | null | null | null | files2md/structure_objects/structurable_directory/__init__.py | KacperKotlewski/file_structure_to_markdown | aad0e1c80f88e0b3d079cf242d43fdc4b7a369f7 | [
"MIT"
] | null | null | null | from .directoryObj import DirectoryObj | 38 | 38 | 0.894737 | from .directoryObj import DirectoryObj | true | true |
f726be65d2d58a2e1ead974e840eb9718283079e | 335 | py | Python | database/table_objects/ping_targets.py | Timo-Meinhof/friedrich-py | 025e45fe23aba0980762af779161626477c567b0 | [
"MIT"
] | 1 | 2021-08-07T12:18:48.000Z | 2021-08-07T12:18:48.000Z | database/table_objects/ping_targets.py | Timo-Meinhof/friedrich-py | 025e45fe23aba0980762af779161626477c567b0 | [
"MIT"
] | null | null | null | database/table_objects/ping_targets.py | Timo-Meinhof/friedrich-py | 025e45fe23aba0980762af779161626477c567b0 | [
"MIT"
] | null | null | null | class User:
def __init__(self, id: str, name: str, color: str, studon: str):
self.id = id
self.name = name
self.color = color
self.studon = studon
class Role:
def __init__(self, id: str, name: str, color: str):
self.id = id
self.name = name
self.color = color | 27.916667 | 69 | 0.540299 | class User:
def __init__(self, id: str, name: str, color: str, studon: str):
self.id = id
self.name = name
self.color = color
self.studon = studon
class Role:
def __init__(self, id: str, name: str, color: str):
self.id = id
self.name = name
self.color = color | true | true |
f726bec39c5c25f3abb108a6dd36bed1b16fe8f7 | 12,303 | py | Python | lenstronomy/PointSource/point_source_types.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | lenstronomy/PointSource/point_source_types.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | lenstronomy/PointSource/point_source_types.py | franyancr/lenstronomy | 3a7b33512a474bf1796d23276d9028b580580cf1 | [
"MIT"
] | null | null | null | import numpy as np
from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver
class Unlensed(object):
"""
class of a single point source in the image plane, aka star
parameters: ra_image, dec_image, point_amp
"""
def __init__(self):
pass
def image_position(self, kwargs_ps, kwargs_lens=None, **kwargs): # kwargs_lens=None, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
"""
:param ra_image:
:param dec_image:
:param point_amp:
:return:
"""
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def source_position(self, kwargs_ps, kwargs_lens=None):
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, **kwargs): # , x_pos=None, y_pos=None, min_distance=0.01, search_window=5, precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
point_amp = kwargs_ps['point_amp']
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
point_amp = kwargs_ps['point_amp']
return np.array(point_amp)
def update_lens_model(self, lens_model_class):
pass
class LensedPositions(object):
"""
class of a single point source in the image plane, aka star
parameters: ra_image, dec_image, point_amp
"""
def __init__(self, lensModel, fixed_magnification=False, additional_image=False):
self._lensModel = lensModel
self._solver = LensEquationSolver(lensModel)
self._fixed_magnification = fixed_magnification
self._additional_image = additional_image
if fixed_magnification is True and additional_image is True:
Warning('The combination of fixed_magnification=True and additional_image=True is not optimal for the current computation.'
'If you see this warning, please approach the developers.')
def image_position(self, kwargs_ps, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
"""
:param ra_image:
:param dec_image:
:param point_amp:
:return:
"""
if self._additional_image is True:
ra_source, dec_source = self.source_position(kwargs_ps, kwargs_lens)
ra_image, dec_image = self._solver.image_position_from_source(ra_source, dec_source, kwargs_lens,
min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
else:
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def source_position(self, kwargs_ps, kwargs_lens):
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
x_source, y_source = self._lensModel.ray_shooting(ra_image, dec_image, kwargs_lens)
x_source = np.mean(x_source)
y_source = np.mean(y_source)
return np.array(x_source), np.array(y_source)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, **kwargs): # min_distance=0.01, search_window=5, precision_limit=10**(-10),num_iter_max=100, x_center=0, y_center=0):
if self._fixed_magnification:
if x_pos is not None and y_pos is not None:
ra_image, dec_image = x_pos, y_pos
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['source_amp'] * np.abs(mag)
else:
point_amp = kwargs_ps['point_amp']
if x_pos is not None:
point_amp = _expand_to_array(point_amp, len(x_pos))
#if np.atleast_1d(point_amp):
# pass
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
if self._fixed_magnification:
source_amp = kwargs_ps['source_amp']
else:
ra_image, dec_image = kwargs_ps['ra_image'], kwargs_ps['dec_image']
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['point_amp']
source_amp = np.mean(np.array(point_amp) / np.array(np.abs(mag)))
return np.array(source_amp)
def update_lens_model(self, lens_model_class):
self._lensModel = lens_model_class
self._solver = LensEquationSolver(lens_model_class)
class SourcePositions(object):
"""
class of a single point source in the image plane, aka star
parameters: ra_image, dec_image, point_amp
"""
def __init__(self, lensModel, fixed_magnification=True):
self._lensModel = lensModel
self._solver = LensEquationSolver(lensModel)
self._fixed_magnification = fixed_magnification
def image_position(self, kwargs_ps, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
"""
:param ra_image:
:param dec_image:
:param point_amp:
:return:
"""
ra_source, dec_source = self.source_position(kwargs_ps, kwargs_lens)
ra_image, dec_image = self._solver.image_position_from_source(ra_source, dec_source, kwargs_lens,
min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return ra_image, dec_image
def source_position(self, kwargs_ps, kwargs_lens=None):
ra_source = kwargs_ps['ra_source']
dec_source = kwargs_ps['dec_source']
return np.array(ra_source), np.array(dec_source)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, min_distance=0.01, search_window=5,
precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
if self._fixed_magnification:
if x_pos is not None and y_pos is not None:
ra_image, dec_image = x_pos, y_pos
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['source_amp'] * np.abs(mag)
else:
point_amp = kwargs_ps['point_amp']
if x_pos is not None:
point_amp = _expand_to_array(point_amp, len(x_pos))
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
if self._fixed_magnification:
source_amp = kwargs_ps['source_amp']
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['point_amp']
source_amp = np.mean(np.array(point_amp) / np.array(mag))
return np.array(source_amp)
def update_lens_model(self, lens_model_class):
self._lensModel = lens_model_class
self._solver = LensEquationSolver(lens_model_class)
class PointSourceCached(object):
"""
"""
def __init__(self, point_source_model, save_cache=False):
self._model = point_source_model
self._save_cache = save_cache
def delete_lens_model_cache(self):
if hasattr(self, '_x_image'):
del self._x_image
if hasattr(self, '_y_image'):
del self._y_image
if hasattr(self, '_x_source'):
del self._x_source
if hasattr(self, '_y_source'):
del self._y_source
def set_save_cache(self, bool):
self._save_cache = bool
def update_lens_model(self, lens_model_class):
self._model.update_lens_model(lens_model_class)
def image_position(self, kwargs_ps, kwargs_lens=None, min_distance=0.05, search_window=10,
precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
"""
:param ra_image:
:param dec_image:
:param point_amp:
:return:
"""
if not self._save_cache or not hasattr(self, '_x_image') or not hasattr(self, '_y_image'):
self._x_image, self._y_image = self._model.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return self._x_image, self._y_image
def source_position(self, kwargs_ps, kwargs_lens=None):
if not self._save_cache or not hasattr(self, '_x_source') or not hasattr(self, '_y_source'):
self._x_source, self._y_source = self._model.source_position(kwargs_ps, kwargs_lens)
return self._x_source, self._y_source
def image_amplitude(self, kwargs_ps, kwargs_lens=None, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
x_pos, y_pos = self.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return self._model.image_amplitude(kwargs_ps, kwargs_lens, x_pos=x_pos, y_pos=y_pos)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
return self._model.source_amplitude(kwargs_ps, kwargs_lens)
def _expand_to_array(array, num):
"""
:param array: float/int or numpy array
:param num: number of array entries expected in array
:return: array of size num
"""
if np.isscalar(array):
return np.ones(num) * array
elif len(array) < num:
out = np.zeros(num)
out[0:len(array)] = array
return out
else:
return array | 47.137931 | 231 | 0.599366 | import numpy as np
from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver
class Unlensed(object):
def __init__(self):
pass
def image_position(self, kwargs_ps, kwargs_lens=None, **kwargs):
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def source_position(self, kwargs_ps, kwargs_lens=None):
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, **kwargs):
point_amp = kwargs_ps['point_amp']
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
point_amp = kwargs_ps['point_amp']
return np.array(point_amp)
def update_lens_model(self, lens_model_class):
pass
class LensedPositions(object):
def __init__(self, lensModel, fixed_magnification=False, additional_image=False):
self._lensModel = lensModel
self._solver = LensEquationSolver(lensModel)
self._fixed_magnification = fixed_magnification
self._additional_image = additional_image
if fixed_magnification is True and additional_image is True:
Warning('The combination of fixed_magnification=True and additional_image=True is not optimal for the current computation.'
'If you see this warning, please approach the developers.')
def image_position(self, kwargs_ps, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
if self._additional_image is True:
ra_source, dec_source = self.source_position(kwargs_ps, kwargs_lens)
ra_image, dec_image = self._solver.image_position_from_source(ra_source, dec_source, kwargs_lens,
min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
else:
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
return np.array(ra_image), np.array(dec_image)
def source_position(self, kwargs_ps, kwargs_lens):
ra_image = kwargs_ps['ra_image']
dec_image = kwargs_ps['dec_image']
x_source, y_source = self._lensModel.ray_shooting(ra_image, dec_image, kwargs_lens)
x_source = np.mean(x_source)
y_source = np.mean(y_source)
return np.array(x_source), np.array(y_source)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, **kwargs):
if self._fixed_magnification:
if x_pos is not None and y_pos is not None:
ra_image, dec_image = x_pos, y_pos
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['source_amp'] * np.abs(mag)
else:
point_amp = kwargs_ps['point_amp']
if x_pos is not None:
point_amp = _expand_to_array(point_amp, len(x_pos))
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
if self._fixed_magnification:
source_amp = kwargs_ps['source_amp']
else:
ra_image, dec_image = kwargs_ps['ra_image'], kwargs_ps['dec_image']
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['point_amp']
source_amp = np.mean(np.array(point_amp) / np.array(np.abs(mag)))
return np.array(source_amp)
def update_lens_model(self, lens_model_class):
self._lensModel = lens_model_class
self._solver = LensEquationSolver(lens_model_class)
class SourcePositions(object):
def __init__(self, lensModel, fixed_magnification=True):
self._lensModel = lensModel
self._solver = LensEquationSolver(lensModel)
self._fixed_magnification = fixed_magnification
def image_position(self, kwargs_ps, kwargs_lens, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
ra_source, dec_source = self.source_position(kwargs_ps, kwargs_lens)
ra_image, dec_image = self._solver.image_position_from_source(ra_source, dec_source, kwargs_lens,
min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return ra_image, dec_image
def source_position(self, kwargs_ps, kwargs_lens=None):
ra_source = kwargs_ps['ra_source']
dec_source = kwargs_ps['dec_source']
return np.array(ra_source), np.array(dec_source)
def image_amplitude(self, kwargs_ps, kwargs_lens=None, x_pos=None, y_pos=None, min_distance=0.01, search_window=5,
precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
if self._fixed_magnification:
if x_pos is not None and y_pos is not None:
ra_image, dec_image = x_pos, y_pos
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['source_amp'] * np.abs(mag)
else:
point_amp = kwargs_ps['point_amp']
if x_pos is not None:
point_amp = _expand_to_array(point_amp, len(x_pos))
return np.array(point_amp)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
if self._fixed_magnification:
source_amp = kwargs_ps['source_amp']
else:
ra_image, dec_image = self.image_position(kwargs_ps, kwargs_lens)
mag = self._lensModel.magnification(ra_image, dec_image, kwargs_lens)
point_amp = kwargs_ps['point_amp']
source_amp = np.mean(np.array(point_amp) / np.array(mag))
return np.array(source_amp)
def update_lens_model(self, lens_model_class):
self._lensModel = lens_model_class
self._solver = LensEquationSolver(lens_model_class)
class PointSourceCached(object):
def __init__(self, point_source_model, save_cache=False):
self._model = point_source_model
self._save_cache = save_cache
def delete_lens_model_cache(self):
if hasattr(self, '_x_image'):
del self._x_image
if hasattr(self, '_y_image'):
del self._y_image
if hasattr(self, '_x_source'):
del self._x_source
if hasattr(self, '_y_source'):
del self._y_source
def set_save_cache(self, bool):
self._save_cache = bool
def update_lens_model(self, lens_model_class):
self._model.update_lens_model(lens_model_class)
def image_position(self, kwargs_ps, kwargs_lens=None, min_distance=0.05, search_window=10,
precision_limit=10**(-10), num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
if not self._save_cache or not hasattr(self, '_x_image') or not hasattr(self, '_y_image'):
self._x_image, self._y_image = self._model.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return self._x_image, self._y_image
def source_position(self, kwargs_ps, kwargs_lens=None):
if not self._save_cache or not hasattr(self, '_x_source') or not hasattr(self, '_y_source'):
self._x_source, self._y_source = self._model.source_position(kwargs_ps, kwargs_lens)
return self._x_source, self._y_source
def image_amplitude(self, kwargs_ps, kwargs_lens=None, min_distance=0.01, search_window=5, precision_limit=10**(-10),
num_iter_max=100, x_center=0, y_center=0, magnification_limit=None):
x_pos, y_pos = self.image_position(kwargs_ps, kwargs_lens, min_distance=min_distance,
search_window=search_window,
precision_limit=precision_limit,
num_iter_max=num_iter_max, x_center=x_center,
y_center=y_center, magnification_limit=magnification_limit)
return self._model.image_amplitude(kwargs_ps, kwargs_lens, x_pos=x_pos, y_pos=y_pos)
def source_amplitude(self, kwargs_ps, kwargs_lens=None):
return self._model.source_amplitude(kwargs_ps, kwargs_lens)
def _expand_to_array(array, num):
if np.isscalar(array):
return np.ones(num) * array
elif len(array) < num:
out = np.zeros(num)
out[0:len(array)] = array
return out
else:
return array | true | true |
f726bf47700172a8e614d87926cc30cfdb491818 | 2,508 | py | Python | linkedlist.py | jerrybelmonte/DataStructures-Python | 553a156f685d83291e73e0c35b85167e6b114379 | [
"MIT"
] | null | null | null | linkedlist.py | jerrybelmonte/DataStructures-Python | 553a156f685d83291e73e0c35b85167e6b114379 | [
"MIT"
] | null | null | null | linkedlist.py | jerrybelmonte/DataStructures-Python | 553a156f685d83291e73e0c35b85167e6b114379 | [
"MIT"
] | null | null | null | # LinkedList implementation using a helper Element class
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def get_position(self, position):
index = 1
current = self.head
if self.head:
while current.next and index < position:
current = current.next
index += 1
if index == position:
return current
else:
return None
def insert(self, new_element, position):
index = 1
current = self.head
previous = current
if position != 1:
while current.next and index < position:
previous = current
current = current.next
index += 1
if index == position:
new_element.next = current
previous.next = new_element
else:
if self.head:
new_element.next = current
self.head = new_element
else:
self.head = new_element
def delete(self, value):
current = self.head
if self.head:
if current.value == value:
self.head = current.next
current.next = None
else:
while current.next:
previous = current
current = current.next
if current.value == value:
previous.next = current.next
current.next = None
# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Start setting up a LinkedList
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Test get_position
# Output should print 3
print(ll.head.next.next.value)
# Output should also print 3
print(ll.get_position(3).value)
# Test insert
ll.insert(e4, 3)
# Output should print 4 now
print(ll.get_position(3).value)
# Test delete
ll.delete(1)
# Output should print 2 now
print(ll.get_position(1).value)
# Output should print 4 now
print(ll.get_position(2).value)
# Should print 3 now
print(ll.get_position(3).value)
| 25.591837 | 56 | 0.555821 |
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def get_position(self, position):
index = 1
current = self.head
if self.head:
while current.next and index < position:
current = current.next
index += 1
if index == position:
return current
else:
return None
def insert(self, new_element, position):
index = 1
current = self.head
previous = current
if position != 1:
while current.next and index < position:
previous = current
current = current.next
index += 1
if index == position:
new_element.next = current
previous.next = new_element
else:
if self.head:
new_element.next = current
self.head = new_element
else:
self.head = new_element
def delete(self, value):
current = self.head
if self.head:
if current.value == value:
self.head = current.next
current.next = None
else:
while current.next:
previous = current
current = current.next
if current.value == value:
previous.next = current.next
current.next = None
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
print(ll.head.next.next.value)
print(ll.get_position(3).value)
ll.insert(e4, 3)
print(ll.get_position(3).value)
ll.delete(1)
print(ll.get_position(1).value)
print(ll.get_position(2).value)
print(ll.get_position(3).value)
| true | true |
f726c0fcd2d691576e784c9f9ad8d9f54ceb42ec | 4,000 | py | Python | benchmarks/supervectorizer_tuning.py | dirty-cat/categorical-encoding | fb0a1c4216533034e7516efc0698c7e4477b0243 | [
"BSD-3-Clause"
] | 374 | 2018-03-16T09:00:55.000Z | 2022-03-31T14:07:43.000Z | benchmarks/supervectorizer_tuning.py | dirty-cat/categorical-encoding | fb0a1c4216533034e7516efc0698c7e4477b0243 | [
"BSD-3-Clause"
] | 195 | 2018-03-14T13:56:25.000Z | 2022-03-31T11:49:49.000Z | benchmarks/supervectorizer_tuning.py | dirty-cat/categorical-encoding | fb0a1c4216533034e7516efc0698c7e4477b0243 | [
"BSD-3-Clause"
] | 52 | 2018-03-13T13:23:01.000Z | 2022-03-17T09:56:56.000Z | """
Performs a GridSearch to find the best parameters for the SuperVectorizer
among a selection.
"""
import logging
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from dirty_cat import SuperVectorizer
from dirty_cat.datasets import fetch_open_payments, fetch_drug_directory, \
fetch_road_safety, fetch_midwest_survey, fetch_medical_charge, \
fetch_employee_salaries, fetch_traffic_violations
from pathlib import Path
from functools import wraps
from datetime import datetime
from typing import List, Tuple
def get_classification_datasets() -> List[Tuple[dict, str]]:
return [
(fetch_open_payments(), 'open_payments'),
# (fetch_drug_directory(), 'drug_directory),
(fetch_road_safety(), 'road_safety'),
(fetch_midwest_survey(), 'midwest_survey'),
(fetch_traffic_violations(), 'traffic_violations'),
]
def get_regression_datasets() -> List[Tuple[dict, str]]:
return [
(fetch_medical_charge(), 'medical_charge'),
(fetch_employee_salaries(), 'employee_salaries'),
]
def get_dataset(info) -> Tuple[pd.DataFrame, pd.Series]:
df = pd.read_csv(info['path'], **info['read_csv_kwargs'])
y = df[info['y']]
X = df.drop(info['y'], axis=1).astype(str)
return X, y
def set_logging(func):
@wraps(func)
def wrapper(*args, **kwargs):
logging_level = logging.DEBUG
logger = logging.getLogger()
logger.setLevel(logging_level)
formatter = logging.Formatter('%(asctime)s - [%(levelname)s] %(message)s')
formatter.datefmt = '%m/%d/%Y %H:%M:%S'
path = Path(__file__).parent / f'tuning_{str(datetime.now())[:10]}.log'
fh = logging.FileHandler(filename=path, mode='w')
fh.setLevel(logging_level)
fh.setFormatter(formatter)
# sh = logging.StreamHandler(sys.stdout)
# sh.setLevel(logging_level)
# sh.setFormatter(formatter)
logger.addHandler(fh)
# logger.addHandler(sh)
return func(*args, **kwargs)
return wrapper
@set_logging
def main():
logging.info('Launching !')
card_possibilities = [20, 30, 40, 50]
n_comp_possibilities = [10, 30, 50]
logging.debug('Creating pipelines')
regression_pipeline = Pipeline([
('sv', SuperVectorizer()),
('estimator', RandomForestRegressor()),
])
classification_pipeline = Pipeline([
('sv', SuperVectorizer()),
('estimator', RandomForestClassifier()),
])
logging.debug(f'With cardinality possibilities: {card_possibilities} '
f'and n_components possibilities: {n_comp_possibilities}')
for pipeline, datasets in zip(
[
regression_pipeline,
classification_pipeline,
],
[
get_regression_datasets(),
get_classification_datasets(),
]
):
for info, name in datasets:
X, y = get_dataset(info)
if name != 'traffic_violations':
continue
csv_path = Path('.').resolve() / f'{name}_results.csv'
if csv_path.exists():
# If the results already exist, we'll skip to the next
logging.debug(f'Skipping {name} as {csv_path!s} was found')
continue
logging.debug(f'Running search on {name}')
grid = GridSearchCV(
estimator=pipeline,
param_grid={
'sv__cardinality_threshold': card_possibilities,
'sv__high_card_str_transformer__n_components': n_comp_possibilities,
},
n_jobs=30,
)
grid.fit(X, y)
df = pd.DataFrame(grid.cv_results_)
df.to_csv(csv_path)
logging.info(f'Saved search results in {csv_path!s}')
if __name__ == '__main__':
main()
| 29.850746 | 88 | 0.6265 |
import logging
import pandas as pd
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from dirty_cat import SuperVectorizer
from dirty_cat.datasets import fetch_open_payments, fetch_drug_directory, \
fetch_road_safety, fetch_midwest_survey, fetch_medical_charge, \
fetch_employee_salaries, fetch_traffic_violations
from pathlib import Path
from functools import wraps
from datetime import datetime
from typing import List, Tuple
def get_classification_datasets() -> List[Tuple[dict, str]]:
return [
(fetch_open_payments(), 'open_payments'),
(fetch_road_safety(), 'road_safety'),
(fetch_midwest_survey(), 'midwest_survey'),
(fetch_traffic_violations(), 'traffic_violations'),
]
def get_regression_datasets() -> List[Tuple[dict, str]]:
return [
(fetch_medical_charge(), 'medical_charge'),
(fetch_employee_salaries(), 'employee_salaries'),
]
def get_dataset(info) -> Tuple[pd.DataFrame, pd.Series]:
df = pd.read_csv(info['path'], **info['read_csv_kwargs'])
y = df[info['y']]
X = df.drop(info['y'], axis=1).astype(str)
return X, y
def set_logging(func):
@wraps(func)
def wrapper(*args, **kwargs):
logging_level = logging.DEBUG
logger = logging.getLogger()
logger.setLevel(logging_level)
formatter = logging.Formatter('%(asctime)s - [%(levelname)s] %(message)s')
formatter.datefmt = '%m/%d/%Y %H:%M:%S'
path = Path(__file__).parent / f'tuning_{str(datetime.now())[:10]}.log'
fh = logging.FileHandler(filename=path, mode='w')
fh.setLevel(logging_level)
fh.setFormatter(formatter)
# sh = logging.StreamHandler(sys.stdout)
# sh.setLevel(logging_level)
# sh.setFormatter(formatter)
logger.addHandler(fh)
# logger.addHandler(sh)
return func(*args, **kwargs)
return wrapper
@set_logging
def main():
logging.info('Launching !')
card_possibilities = [20, 30, 40, 50]
n_comp_possibilities = [10, 30, 50]
logging.debug('Creating pipelines')
regression_pipeline = Pipeline([
('sv', SuperVectorizer()),
('estimator', RandomForestRegressor()),
])
classification_pipeline = Pipeline([
('sv', SuperVectorizer()),
('estimator', RandomForestClassifier()),
])
logging.debug(f'With cardinality possibilities: {card_possibilities} '
f'and n_components possibilities: {n_comp_possibilities}')
for pipeline, datasets in zip(
[
regression_pipeline,
classification_pipeline,
],
[
get_regression_datasets(),
get_classification_datasets(),
]
):
for info, name in datasets:
X, y = get_dataset(info)
if name != 'traffic_violations':
continue
csv_path = Path('.').resolve() / f'{name}_results.csv'
if csv_path.exists():
# If the results already exist, we'll skip to the next
logging.debug(f'Skipping {name} as {csv_path!s} was found')
continue
logging.debug(f'Running search on {name}')
grid = GridSearchCV(
estimator=pipeline,
param_grid={
'sv__cardinality_threshold': card_possibilities,
'sv__high_card_str_transformer__n_components': n_comp_possibilities,
},
n_jobs=30,
)
grid.fit(X, y)
df = pd.DataFrame(grid.cv_results_)
df.to_csv(csv_path)
logging.info(f'Saved search results in {csv_path!s}')
if __name__ == '__main__':
main()
| true | true |
f726c100e03118fe63b2ed7bad2293c84c8e95ee | 282 | py | Python | scripts/batch_stop.py | oretoise/slate | cfbf629417680cd0fe6d745f7d8a50275aef00a9 | [
"MIT"
] | null | null | null | scripts/batch_stop.py | oretoise/slate | cfbf629417680cd0fe6d745f7d8a50275aef00a9 | [
"MIT"
] | null | null | null | scripts/batch_stop.py | oretoise/slate | cfbf629417680cd0fe6d745f7d8a50275aef00a9 | [
"MIT"
] | null | null | null | import pyautogui
pyautogui.PAUSE = 5
while True:
# Click first email in list.
pyautogui.click(640, 345)
# Stop it
pyautogui.click(1760, 430)
pyautogui.click(980, 1020)
pyautogui.typewrite("STOP")
pyautogui.press('enter')
pyautogui.click(580, 220) | 18.8 | 32 | 0.670213 | import pyautogui
pyautogui.PAUSE = 5
while True:
pyautogui.click(640, 345)
pyautogui.click(1760, 430)
pyautogui.click(980, 1020)
pyautogui.typewrite("STOP")
pyautogui.press('enter')
pyautogui.click(580, 220) | true | true |
f726c15fd0c5805fefb311e2ad443ac3c19afea2 | 802 | py | Python | manage.py | guanqingqi/dove | f8681f144e44369bf9e0c9ea76e1994920a14cfb | [
"Apache-2.0"
] | null | null | null | manage.py | guanqingqi/dove | f8681f144e44369bf9e0c9ea76e1994920a14cfb | [
"Apache-2.0"
] | null | null | null | manage.py | guanqingqi/dove | f8681f144e44369bf9e0c9ea76e1994920a14cfb | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dove.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| 34.869565 | 77 | 0.640898 |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dove.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| true | true |
f726c16c09d5ab1fb493fbccc82d1e44044c2174 | 11,918 | py | Python | flan/export.py | bretlowery/flan | b79319044fcdb2230ac090232e9056719cb09f17 | [
"MIT"
] | 3 | 2019-08-03T13:27:31.000Z | 2021-06-08T16:25:31.000Z | flan/export.py | bretlowery/flan | b79319044fcdb2230ac090232e9056719cb09f17 | [
"MIT"
] | 2 | 2020-09-24T10:44:55.000Z | 2021-06-25T15:31:24.000Z | flan/export.py | bretlowery/flan | b79319044fcdb2230ac090232e9056719cb09f17 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#
# Copyright 2012 Splunk, 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.
"""
This software exports a splunk index using the streaming export endpoint
using a parameterized chunking mechanism.
"""
# installation support files
from __future__ import absolute_import
from __future__ import print_function
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import time
from os import path
# splunk support files
from splunklib.binding import connect
try:
from utils import parse
except ImportError:
raise Exception("Add the SDK repository to your PYTHONPATH to run the examples "
"(e.g., export PYTHONPATH=~/splunk-sdk-python.")
# hidden file
OUTPUT_FILE = "./export.out"
OUTPUT_MODE = "xml"
OUTPUT_MODES = ["csv", "xml", "json"]
CLIRULES = {
'end': {
'flags': ["--endtime"],
'default': "",
'help': "Start time of export (default is start of index)"
},
'index': {
'flags': ["--index"],
'default': "*",
'help': "Index to export (default is all user defined indices)"
},
'omode': {
'flags': ["--omode"],
'default': OUTPUT_MODE,
'help': "output format %s default is %s" % (OUTPUT_MODES, OUTPUT_MODE)
},
'output': {
'flags': ["--output"],
'default': OUTPUT_FILE,
'help': "Output file name (default is %s)" % OUTPUT_FILE
},
'recover': {
'flags': ["--recover"],
'default': False,
'help': "Export attempts to recover from end of existing export"
},
'search': {
'flags': ["--search"],
'default': "search *",
'help': "search string (default 'search *')"
},
'start': {
'flags': ["--starttime"],
'default': "",
'help': "Start time of export (default is start of index)"
}
}
def get_csv_next_event_start(location, event_buffer):
""" determin the event start and end of *any* valid event """
start = -1
end = -1
event_start = event_buffer.find("\n", location + 1)
event_end = event_buffer.find('"\n', event_start + 1)
while (event_end > 0):
parts = event_buffer[event_start:event_end].split(",")
# test parts 0 and 1 of CSV. Format should be time.qqq, anything
# else is not time stamp to keep moving.
try:
int(parts[0].replace('\n', ""))
timestamp = parts[1].replace('"', "")
timeparts = timestamp.split('.')
int(timeparts[0])
int(timeparts[1])
return (event_start, event_end)
except:
event_start = event_buffer.find("\n", event_end + 2)
event_end = event_buffer.find('"\n', event_start + 1)
return (start, end)
def get_csv_event_start(event_buffer):
""" get the event start of an event that is different (in time)from the
adjoining event, in CSV format """
(start, end) = get_csv_next_event_start(0, event_buffer)
if start < 0:
return (-1, -1, "")
print(event_buffer[start:end])
tstart = event_buffer.find(",", start)
tend = event_buffer.find(",", tstart + 1)
print(event_buffer[tstart:tend])
last_time = event_buffer[tstart + 1:tend].replace('"', "")
while end > 0:
(start, end) = get_csv_next_event_start(start, event_buffer)
if end < 0:
return (-1, -1, "")
tstart = event_buffer.find(",", start)
tend = event_buffer.find(",", tstart + 1)
this_time = event_buffer[tstart + 1:tend].replace('"', "")
if this_time != last_time:
return (start, end + 1, last_time)
return (-1, -1, "")
def get_xml_event_start(event_buffer):
""" get the event start of an event that is different (in time)from the
adjoining event, in XML format """
result_pattern = "<result offset='"
time_key_pattern = "<field k='_time'>"
time_start_pattern = "<value><text>"
time_end_pattern = "<"
event_end_pattern = "</result>"
event_start = event_buffer.find(result_pattern)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
return (-1, -1, "")
time_key_start = event_buffer.find(time_key_pattern, event_start)
time_start = event_buffer.find(time_start_pattern, time_key_start) + \
len(time_start_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
last_time = event_buffer[time_start:time_end]
# wallk through events until time changes
event_start = event_end
while event_end > 0:
event_start = event_buffer.find(result_pattern, event_start + 1)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
return (-1, -1, "")
time_key_start = event_buffer.find(time_key_pattern, event_start)
time_start = event_buffer.find(time_start_pattern, time_key_start)
time_end = event_buffer.find(time_end_pattern, time_start)
this_time = event_buffer[time_start:time_end]
if this_time != last_time:
return (event_start, event_end, last_time)
event_start = event_end
return (-1, -1, "")
def get_json_event_start(event_buffer):
""" get the event start of an event that is different (in time)from the
adjoining event, in XML format """
event_start_pattern = '{"_cd":"'
time_key_pattern = '"_time":"'
time_end_pattern = '"'
event_end_pattern = '"},\n'
event_end_pattern2 = '"}[]' # old json output format bug
event_start = event_buffer.find(event_start_pattern)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
event_end = event_buffer.find(event_end_pattern2, event_start) + \
len(event_end_pattern2)
if (event_end < 0):
return (-1, -1, "")
time_start = event_buffer.find(time_key_pattern, event_start) + \
len(time_key_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
last_time = event_buffer[time_start:time_end]
event_start = event_end
while event_end > 0:
event_start = event_buffer.find(event_start_pattern, event_start + 1)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
event_end = event_buffer.find(event_end_pattern2, event_start) + \
len(event_end_pattern2)
if (event_end < 0):
return (-1, -1, "")
time_start = event_buffer.find(time_key_pattern, event_start) + \
len(time_key_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
this_time = event_buffer[time_start:time_end]
if this_time != last_time:
return (event_start - 2, event_end, last_time)
event_start = event_end
return (-1, -1, "")
def get_event_start(event_buffer, event_format):
""" dispatch event start method based on event format type """
if event_format == "csv":
return get_csv_event_start(event_buffer)
elif event_format == "xml":
return get_xml_event_start(event_buffer)
else:
return get_json_event_start(event_buffer)
def recover(options):
""" recover from an existing export run. We do this by
finding the last time change between events, truncate the file
and restart from there """
event_format = options.kwargs['omode']
buffer_size = 64 * 1024
fpd = open(options.kwargs['output'], "r+")
fpd.seek(0, 2) # seek to end
fptr = max(fpd.tell() - buffer_size, 0)
fptr_eof = 0
while (fptr > 0):
fpd.seek(fptr)
event_buffer = fpd.read(buffer_size)
(event_start, next_event_start, last_time) = \
get_event_start(event_buffer, event_format)
if (event_start != -1):
fptr_eof = event_start + fptr
break
fptr = fptr - buffer_size
if fptr < 0:
# didn't find a valid event, so start over
fptr_eof = 0
last_time = 0
# truncate file here
fpd.truncate(fptr_eof)
fpd.seek(fptr_eof)
fpd.write("\n")
fpd.close()
return last_time
def cleanup_tail(options):
""" cleanup the tail of a recovery """
if options.kwargs['omode'] == "csv":
options.kwargs['fd'].write("\n")
elif options.kwargs['omode'] == "xml":
options.kwargs['fd'].write("\n</results>\n")
else:
options.kwargs['fd'].write("\n]\n")
def export(options, service):
""" main export method: export any number of indexes """
start = options.kwargs['start']
end = options.kwargs['end']
fixtail = options.kwargs['fixtail']
once = True
squery = options.kwargs['search']
squery = squery + " index=%s" % options.kwargs['index']
if (start != ""):
squery = squery + " earliest_time=%s" % start
if (end != ""):
squery = squery + " latest_time=%s" % end
success = False
while not success:
# issue query to splunkd
# count=0 overrides the maximum number of events
# returned (normally 50K) regardless of what the .conf
# file for splunkd says.
result = service.get('search/jobs/export',
search=squery,
output_mode=options.kwargs['omode'],
timeout=60,
earliest_time="0.000",
time_format="%s.%Q",
count=0)
if result.status != 200:
print("warning: export job failed: %d, sleep/retry" % result.status)
time.sleep(60)
else:
success = True
# write export file
while True:
if fixtail and once:
cleanup_tail(options)
once = False
content = result.body.read()
if len(content) == 0:
break
options.kwargs['fd'].write(content)
options.kwargs['fd'].write("\n")
options.kwargs['fd'].flush()
def main():
""" main entry """
options = parse(sys.argv[1:], CLIRULES, ".splunkrc")
if options.kwargs['omode'] not in OUTPUT_MODES:
print("output mode must be one of %s, found %s" % (OUTPUT_MODES,
options.kwargs['omode']))
sys.exit(1)
service = connect(**options.kwargs)
if path.exists(options.kwargs['output']):
if not options.kwargs['recover']:
print("Export file %s exists, and recover option nor specified" % \
options.kwargs['output'])
sys.exit(1)
else:
options.kwargs['end'] = recover(options)
options.kwargs['fixtail'] = True
openmode = "a"
else:
openmode = "w"
options.kwargs['fixtail'] = False
try:
options.kwargs['fd'] = open(options.kwargs['output'], openmode)
except IOError:
print("Failed to open output file %s w/ mode %s" % \
(options.kwargs['output'], openmode))
sys.exit(1)
export(options, service)
if __name__ == '__main__':
main() | 32.38587 | 84 | 0.601275 |
from __future__ import absolute_import
from __future__ import print_function
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import time
from os import path
from splunklib.binding import connect
try:
from utils import parse
except ImportError:
raise Exception("Add the SDK repository to your PYTHONPATH to run the examples "
"(e.g., export PYTHONPATH=~/splunk-sdk-python.")
OUTPUT_FILE = "./export.out"
OUTPUT_MODE = "xml"
OUTPUT_MODES = ["csv", "xml", "json"]
CLIRULES = {
'end': {
'flags': ["--endtime"],
'default': "",
'help': "Start time of export (default is start of index)"
},
'index': {
'flags': ["--index"],
'default': "*",
'help': "Index to export (default is all user defined indices)"
},
'omode': {
'flags': ["--omode"],
'default': OUTPUT_MODE,
'help': "output format %s default is %s" % (OUTPUT_MODES, OUTPUT_MODE)
},
'output': {
'flags': ["--output"],
'default': OUTPUT_FILE,
'help': "Output file name (default is %s)" % OUTPUT_FILE
},
'recover': {
'flags': ["--recover"],
'default': False,
'help': "Export attempts to recover from end of existing export"
},
'search': {
'flags': ["--search"],
'default': "search *",
'help': "search string (default 'search *')"
},
'start': {
'flags': ["--starttime"],
'default': "",
'help': "Start time of export (default is start of index)"
}
}
def get_csv_next_event_start(location, event_buffer):
start = -1
end = -1
event_start = event_buffer.find("\n", location + 1)
event_end = event_buffer.find('"\n', event_start + 1)
while (event_end > 0):
parts = event_buffer[event_start:event_end].split(",")
# test parts 0 and 1 of CSV. Format should be time.qqq, anything
# else is not time stamp to keep moving.
try:
int(parts[0].replace('\n', ""))
timestamp = parts[1].replace('"', "")
timeparts = timestamp.split('.')
int(timeparts[0])
int(timeparts[1])
return (event_start, event_end)
except:
event_start = event_buffer.find("\n", event_end + 2)
event_end = event_buffer.find('"\n', event_start + 1)
return (start, end)
def get_csv_event_start(event_buffer):
(start, end) = get_csv_next_event_start(0, event_buffer)
if start < 0:
return (-1, -1, "")
print(event_buffer[start:end])
tstart = event_buffer.find(",", start)
tend = event_buffer.find(",", tstart + 1)
print(event_buffer[tstart:tend])
last_time = event_buffer[tstart + 1:tend].replace('"', "")
while end > 0:
(start, end) = get_csv_next_event_start(start, event_buffer)
if end < 0:
return (-1, -1, "")
tstart = event_buffer.find(",", start)
tend = event_buffer.find(",", tstart + 1)
this_time = event_buffer[tstart + 1:tend].replace('"', "")
if this_time != last_time:
return (start, end + 1, last_time)
return (-1, -1, "")
def get_xml_event_start(event_buffer):
result_pattern = "<result offset='"
time_key_pattern = "<field k='_time'>"
time_start_pattern = "<value><text>"
time_end_pattern = "<"
event_end_pattern = "</result>"
event_start = event_buffer.find(result_pattern)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
return (-1, -1, "")
time_key_start = event_buffer.find(time_key_pattern, event_start)
time_start = event_buffer.find(time_start_pattern, time_key_start) + \
len(time_start_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
last_time = event_buffer[time_start:time_end]
# wallk through events until time changes
event_start = event_end
while event_end > 0:
event_start = event_buffer.find(result_pattern, event_start + 1)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
return (-1, -1, "")
time_key_start = event_buffer.find(time_key_pattern, event_start)
time_start = event_buffer.find(time_start_pattern, time_key_start)
time_end = event_buffer.find(time_end_pattern, time_start)
this_time = event_buffer[time_start:time_end]
if this_time != last_time:
return (event_start, event_end, last_time)
event_start = event_end
return (-1, -1, "")
def get_json_event_start(event_buffer):
event_start_pattern = '{"_cd":"'
time_key_pattern = '"_time":"'
time_end_pattern = '"'
event_end_pattern = '"},\n'
event_end_pattern2 = '"}[]' # old json output format bug
event_start = event_buffer.find(event_start_pattern)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
event_end = event_buffer.find(event_end_pattern2, event_start) + \
len(event_end_pattern2)
if (event_end < 0):
return (-1, -1, "")
time_start = event_buffer.find(time_key_pattern, event_start) + \
len(time_key_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
last_time = event_buffer[time_start:time_end]
event_start = event_end
while event_end > 0:
event_start = event_buffer.find(event_start_pattern, event_start + 1)
event_end = event_buffer.find(event_end_pattern, event_start) + \
len(event_end_pattern)
if event_end < 0:
event_end = event_buffer.find(event_end_pattern2, event_start) + \
len(event_end_pattern2)
if (event_end < 0):
return (-1, -1, "")
time_start = event_buffer.find(time_key_pattern, event_start) + \
len(time_key_pattern)
time_end = event_buffer.find(time_end_pattern, time_start + 1)
this_time = event_buffer[time_start:time_end]
if this_time != last_time:
return (event_start - 2, event_end, last_time)
event_start = event_end
return (-1, -1, "")
def get_event_start(event_buffer, event_format):
if event_format == "csv":
return get_csv_event_start(event_buffer)
elif event_format == "xml":
return get_xml_event_start(event_buffer)
else:
return get_json_event_start(event_buffer)
def recover(options):
event_format = options.kwargs['omode']
buffer_size = 64 * 1024
fpd = open(options.kwargs['output'], "r+")
fpd.seek(0, 2) # seek to end
fptr = max(fpd.tell() - buffer_size, 0)
fptr_eof = 0
while (fptr > 0):
fpd.seek(fptr)
event_buffer = fpd.read(buffer_size)
(event_start, next_event_start, last_time) = \
get_event_start(event_buffer, event_format)
if (event_start != -1):
fptr_eof = event_start + fptr
break
fptr = fptr - buffer_size
if fptr < 0:
# didn't find a valid event, so start over
fptr_eof = 0
last_time = 0
fpd.truncate(fptr_eof)
fpd.seek(fptr_eof)
fpd.write("\n")
fpd.close()
return last_time
def cleanup_tail(options):
if options.kwargs['omode'] == "csv":
options.kwargs['fd'].write("\n")
elif options.kwargs['omode'] == "xml":
options.kwargs['fd'].write("\n</results>\n")
else:
options.kwargs['fd'].write("\n]\n")
def export(options, service):
start = options.kwargs['start']
end = options.kwargs['end']
fixtail = options.kwargs['fixtail']
once = True
squery = options.kwargs['search']
squery = squery + " index=%s" % options.kwargs['index']
if (start != ""):
squery = squery + " earliest_time=%s" % start
if (end != ""):
squery = squery + " latest_time=%s" % end
success = False
while not success:
result = service.get('search/jobs/export',
search=squery,
output_mode=options.kwargs['omode'],
timeout=60,
earliest_time="0.000",
time_format="%s.%Q",
count=0)
if result.status != 200:
print("warning: export job failed: %d, sleep/retry" % result.status)
time.sleep(60)
else:
success = True
while True:
if fixtail and once:
cleanup_tail(options)
once = False
content = result.body.read()
if len(content) == 0:
break
options.kwargs['fd'].write(content)
options.kwargs['fd'].write("\n")
options.kwargs['fd'].flush()
def main():
options = parse(sys.argv[1:], CLIRULES, ".splunkrc")
if options.kwargs['omode'] not in OUTPUT_MODES:
print("output mode must be one of %s, found %s" % (OUTPUT_MODES,
options.kwargs['omode']))
sys.exit(1)
service = connect(**options.kwargs)
if path.exists(options.kwargs['output']):
if not options.kwargs['recover']:
print("Export file %s exists, and recover option nor specified" % \
options.kwargs['output'])
sys.exit(1)
else:
options.kwargs['end'] = recover(options)
options.kwargs['fixtail'] = True
openmode = "a"
else:
openmode = "w"
options.kwargs['fixtail'] = False
try:
options.kwargs['fd'] = open(options.kwargs['output'], openmode)
except IOError:
print("Failed to open output file %s w/ mode %s" % \
(options.kwargs['output'], openmode))
sys.exit(1)
export(options, service)
if __name__ == '__main__':
main() | true | true |
f726c1f060b031498baf48c9527e53700f69bbf2 | 6,961 | py | Python | virt/ansible-latest/lib/python2.7/site-packages/ansible/modules/network/aos/_aos_device.py | lakhlaifi/RedHat-Ansible | 27c5077cced9d416081fcd5d69ea44bca0317fa4 | [
"Apache-2.0"
] | 1 | 2020-03-29T18:41:01.000Z | 2020-03-29T18:41:01.000Z | ansible/ansible/modules/network/aos/_aos_device.py | SergeyCherepanov/ansible | 875711cd2fd6b783c812241c2ed7a954bf6f670f | [
"MIT"
] | 7 | 2020-09-07T17:27:56.000Z | 2022-03-02T06:25:46.000Z | ansible/ansible/modules/network/aos/_aos_device.py | SergeyCherepanov/ansible | 875711cd2fd6b783c812241c2ed7a954bf6f670f | [
"MIT"
] | 1 | 2020-03-22T01:04:48.000Z | 2020-03-22T01:04:48.000Z | #!/usr/bin/python
#
# (c) 2017 Apstra Inc, <community@apstra.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: aos_device
author: Damien Garros (@dgarros)
version_added: "2.3"
short_description: Manage Devices on AOS Server
deprecated:
removed_in: "2.9"
why: This module does not support AOS 2.1 or later
alternative: See new modules at U(https://www.ansible.com/ansible-apstra).
description:
- Apstra AOS Device module let you manage your devices in AOS easily. You can
approve devices and define in which state the device should be. Currently
only the state I(normal) is supported but the goal is to extend this module
with additional state. This module is idempotent and support the I(check) mode.
It's using the AOS REST API.
requirements:
- "aos-pyez >= 0.6.0"
options:
session:
description:
- An existing AOS session as obtained by M(aos_login) module.
required: true
name:
description:
- The device serial-number; i.e. uniquely identifies the device in the
AOS system. Only one of I(name) or I(id) can be set.
id:
description:
- The AOS internal id for a device; i.e. uniquely identifies the device in the
AOS system. Only one of I(name) or I(id) can be set.
state:
description:
- Define in which state the device should be. Currently only I(normal)
is supported but the goal is to add I(maint) and I(decomm).
default: normal
choices: ['normal']
approve:
description:
- The approve argument instruct the module to convert a device in quarantine
mode into approved mode.
default: "no"
type: bool
location:
description:
- When approving a device using the I(approve) argument, it's possible
define the location of the device.
'''
EXAMPLES = '''
- name: Approve a new device
aos_device:
session: "{{ aos_session }}"
name: D2060B2F105429GDABCD123
state: 'normal'
approve: true
location: "rack-45, ru-18"
'''
RETURNS = '''
name:
description: Name of the Device, usually the serial-number.
returned: always
type: str
sample: Server-IpAddrs
id:
description: AOS unique ID assigned to the Device
returned: always
type: str
sample: fcc4ac1c-e249-4fe7-b458-2138bfb44c06
value:
description: Value of the object as returned by the AOS Server
returned: always
type: dict
sample: {'...'}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aos.aos import HAS_AOS_PYEZ, get_aos_session, check_aos_version, find_collection_item
if HAS_AOS_PYEZ:
from apstra.aosom.exc import SessionError, SessionRqstError
def aos_device_normal(module, aos, dev):
margs = module.params
# If approve is define, check if the device needs to be approved or not
if margs['approve'] is not None:
if dev.is_approved:
module.exit_json(changed=False,
name=dev.name,
id=dev.id,
value=dev.value)
if not module.check_mode:
try:
dev.approve(location=margs['location'])
except (SessionError, SessionRqstError):
module.fail_json(msg="Unable to approve device")\
module.exit_json(changed=True,
name=dev.name,
id=dev.id,
value=dev.value)
else:
# Check if the device is online
if dev.state in ('OOS-READY', 'IS-READY'):
module.exit_json(changed=False,
name=dev.name,
id=dev.id,
value=dev.value)
else:
module.fail_json(msg="Device is in '%s' state" % dev.state)
def aos_device(module):
margs = module.params
try:
aos = get_aos_session(module, margs['session'])
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
item_name = False
item_id = False
if margs['id'] is not None:
item_id = margs['id']
elif margs['name'] is not None:
item_name = margs['name']
# ----------------------------------------------------
# Find Object if available based on ID or Name
# ----------------------------------------------------
dev = find_collection_item(aos.Devices,
item_name=item_name,
item_id=item_id)
if dev.exists is False:
module.fail_json(msg="unknown device '%s'" % margs['name'])
# ----------------------------------------------------
# Valid device state for reference
# ----------------------------------------------------
# DEVICE_STATE_IS_ACTIVE = 1;
# DEVICE_STATE_IS_READY = 2;
# DEVICE_STATE_IS_NOCOMMS = 3;
# DEVICE_STATE_IS_MAINT = 4;
# DEVICE_STATE_IS_REBOOTING = 5;
# DEVICE_STATE_OOS_STOCKED = 6;
# DEVICE_STATE_OOS_QUARANTINED = 7;
# DEVICE_STATE_OOS_READY = 8;
# DEVICE_STATE_OOS_NOCOMMS = 9;
# DEVICE_STATE_OOS_DECOMM = 10;
# DEVICE_STATE_OOS_MAINT = 11;
# DEVICE_STATE_OOS_REBOOTING = 12;
# DEVICE_STATE_ERROR = 13;
# ----------------------------------------------------
# State == Normal
# ----------------------------------------------------
if margs['state'] == 'normal':
aos_device_normal(module, aos, dev)
def main():
module = AnsibleModule(
argument_spec=dict(
session=dict(required=True, type="dict"),
name=dict(required=False),
id=dict(required=False),
state=dict(choices=['normal'],
default='normal'),
approve=dict(required=False, type='bool'),
location=dict(required=False, default='')
),
mutually_exclusive=[('name', 'id')],
required_one_of=[('name', 'id')],
supports_check_mode=True
)
# Check if aos-pyez is present and match the minimum version
check_aos_version(module, '0.6.0')
aos_device(module)
if __name__ == "__main__":
main()
| 31.215247 | 119 | 0.598046 |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: aos_device
author: Damien Garros (@dgarros)
version_added: "2.3"
short_description: Manage Devices on AOS Server
deprecated:
removed_in: "2.9"
why: This module does not support AOS 2.1 or later
alternative: See new modules at U(https://www.ansible.com/ansible-apstra).
description:
- Apstra AOS Device module let you manage your devices in AOS easily. You can
approve devices and define in which state the device should be. Currently
only the state I(normal) is supported but the goal is to extend this module
with additional state. This module is idempotent and support the I(check) mode.
It's using the AOS REST API.
requirements:
- "aos-pyez >= 0.6.0"
options:
session:
description:
- An existing AOS session as obtained by M(aos_login) module.
required: true
name:
description:
- The device serial-number; i.e. uniquely identifies the device in the
AOS system. Only one of I(name) or I(id) can be set.
id:
description:
- The AOS internal id for a device; i.e. uniquely identifies the device in the
AOS system. Only one of I(name) or I(id) can be set.
state:
description:
- Define in which state the device should be. Currently only I(normal)
is supported but the goal is to add I(maint) and I(decomm).
default: normal
choices: ['normal']
approve:
description:
- The approve argument instruct the module to convert a device in quarantine
mode into approved mode.
default: "no"
type: bool
location:
description:
- When approving a device using the I(approve) argument, it's possible
define the location of the device.
'''
EXAMPLES = '''
- name: Approve a new device
aos_device:
session: "{{ aos_session }}"
name: D2060B2F105429GDABCD123
state: 'normal'
approve: true
location: "rack-45, ru-18"
'''
RETURNS = '''
name:
description: Name of the Device, usually the serial-number.
returned: always
type: str
sample: Server-IpAddrs
id:
description: AOS unique ID assigned to the Device
returned: always
type: str
sample: fcc4ac1c-e249-4fe7-b458-2138bfb44c06
value:
description: Value of the object as returned by the AOS Server
returned: always
type: dict
sample: {'...'}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aos.aos import HAS_AOS_PYEZ, get_aos_session, check_aos_version, find_collection_item
if HAS_AOS_PYEZ:
from apstra.aosom.exc import SessionError, SessionRqstError
def aos_device_normal(module, aos, dev):
margs = module.params
if margs['approve'] is not None:
if dev.is_approved:
module.exit_json(changed=False,
name=dev.name,
id=dev.id,
value=dev.value)
if not module.check_mode:
try:
dev.approve(location=margs['location'])
except (SessionError, SessionRqstError):
module.fail_json(msg="Unable to approve device")\
module.exit_json(changed=True,
name=dev.name,
id=dev.id,
value=dev.value)
else:
if dev.state in ('OOS-READY', 'IS-READY'):
module.exit_json(changed=False,
name=dev.name,
id=dev.id,
value=dev.value)
else:
module.fail_json(msg="Device is in '%s' state" % dev.state)
def aos_device(module):
margs = module.params
try:
aos = get_aos_session(module, margs['session'])
except Exception:
module.fail_json(msg="Unable to login to the AOS server")
item_name = False
item_id = False
if margs['id'] is not None:
item_id = margs['id']
elif margs['name'] is not None:
item_name = margs['name']
dev = find_collection_item(aos.Devices,
item_name=item_name,
item_id=item_id)
if dev.exists is False:
module.fail_json(msg="unknown device '%s'" % margs['name'])
if margs['state'] == 'normal':
aos_device_normal(module, aos, dev)
def main():
module = AnsibleModule(
argument_spec=dict(
session=dict(required=True, type="dict"),
name=dict(required=False),
id=dict(required=False),
state=dict(choices=['normal'],
default='normal'),
approve=dict(required=False, type='bool'),
location=dict(required=False, default='')
),
mutually_exclusive=[('name', 'id')],
required_one_of=[('name', 'id')],
supports_check_mode=True
)
check_aos_version(module, '0.6.0')
aos_device(module)
if __name__ == "__main__":
main()
| true | true |
f726c4efcbe41267a6d7cd4f11809971061e72b5 | 15,902 | py | Python | python/ccxt/async_support/base/exchange.py | halfjuice/ccxt | cc702efbaafba547c3bc973895bd817b3308d072 | [
"MIT"
] | null | null | null | python/ccxt/async_support/base/exchange.py | halfjuice/ccxt | cc702efbaafba547c3bc973895bd817b3308d072 | [
"MIT"
] | null | null | null | python/ccxt/async_support/base/exchange.py | halfjuice/ccxt | cc702efbaafba547c3bc973895bd817b3308d072 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
__version__ = '1.61.55'
# -----------------------------------------------------------------------------
import asyncio
import concurrent.futures
import socket
import certifi
import aiohttp
import ssl
import sys
import yarl
# -----------------------------------------------------------------------------
from ccxt.async_support.base.throttler import Throttler
# -----------------------------------------------------------------------------
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.errors import NotSupported
from ccxt.base.errors import BadSymbol
# -----------------------------------------------------------------------------
from ccxt.base.exchange import Exchange as BaseExchange
# -----------------------------------------------------------------------------
__all__ = [
'BaseExchange',
'Exchange',
]
# -----------------------------------------------------------------------------
class Exchange(BaseExchange):
synchronous = False
def __init__(self, config={}):
if 'asyncio_loop' in config:
self.asyncio_loop = config['asyncio_loop']
self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env)
self.verify = config.get('verify', self.verify)
self.own_session = 'session' not in config
self.cafile = config.get('cafile', certifi.where())
super(Exchange, self).__init__(config)
self.throttle = None
self.init_rest_rate_limiter()
self.markets_loading = None
self.reloading_markets = False
def init_rest_rate_limiter(self):
self.throttle = Throttler(self.tokenBucket, self.asyncio_loop)
def __del__(self):
if self.session is not None:
self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add exchange.close() to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).")
if sys.version_info >= (3, 5):
async def __aenter__(self):
self.open()
return self
async def __aexit__(self, exc_type, exc, tb):
await self.close()
def open(self):
if self.asyncio_loop is None:
if sys.version_info >= (3, 7):
self.asyncio_loop = asyncio.get_running_loop()
else:
self.asyncio_loop = asyncio.get_event_loop()
self.throttle.loop = self.asyncio_loop
if self.own_session and self.session is None:
# Create our SSL context object with our CA cert file
context = ssl.create_default_context(cafile=self.cafile) if self.verify else self.verify
# Pass this SSL context to aiohttp and create a TCPConnector
connector = aiohttp.TCPConnector(ssl=context, loop=self.asyncio_loop, enable_cleanup_closed=True)
self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector, trust_env=self.aiohttp_trust_env)
async def close(self):
if self.session is not None:
if self.own_session:
await self.session.close()
self.session = None
async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None, config={}, context={}):
"""A better wrapper over request for deferred signing"""
if self.enableRateLimit:
cost = self.calculate_rate_limiter_cost(api, method, path, params, config, context)
# insert cost into here...
await self.throttle(cost)
self.lastRestRequestTimestamp = self.milliseconds()
request = self.sign(path, api, method, params, headers, body)
return await self.fetch(request['url'], request['method'], request['headers'], request['body'])
async def fetch(self, url, method='GET', headers=None, body=None):
"""Perform a HTTP request and return decoded JSON data"""
request_headers = self.prepare_request_headers(headers)
url = self.proxy + url
if self.verbose:
self.log("\nRequest:", method, url, headers, body)
self.logger.debug("%s %s, Request: %s %s", method, url, headers, body)
request_body = body
encoded_body = body.encode() if body else None
self.open()
session_method = getattr(self.session, method.lower())
http_response = None
http_status_code = None
http_status_text = None
json_response = None
try:
async with session_method(yarl.URL(url, encoded=True),
data=encoded_body,
headers=request_headers,
timeout=(self.timeout / 1000),
proxy=self.aiohttp_proxy) as response:
http_response = await response.text(errors='replace')
# CIMultiDictProxy
raw_headers = response.headers
headers = {}
for header in raw_headers:
if header in headers:
headers[header] = headers[header] + ', ' + raw_headers[header]
else:
headers[header] = raw_headers[header]
http_status_code = response.status
http_status_text = response.reason
http_response = self.on_rest_response(http_status_code, http_status_text, url, method, headers, http_response, request_headers, request_body)
json_response = self.parse_json(http_response)
if self.enableLastHttpResponse:
self.last_http_response = http_response
if self.enableLastResponseHeaders:
self.last_response_headers = headers
if self.enableLastJsonResponse:
self.last_json_response = json_response
if self.verbose:
self.log("\nResponse:", method, url, http_status_code, headers, http_response)
self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response)
except socket.gaierror as e:
details = ' '.join([self.id, method, url])
raise ExchangeNotAvailable(details) from e
except (concurrent.futures.TimeoutError, asyncio.TimeoutError) as e:
details = ' '.join([self.id, method, url])
raise RequestTimeout(details) from e
except aiohttp.ClientConnectionError as e:
details = ' '.join([self.id, method, url])
raise ExchangeNotAvailable(details) from e
except aiohttp.ClientError as e: # base exception class
details = ' '.join([self.id, method, url])
raise ExchangeError(details) from e
self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
if json_response is not None:
return json_response
if self.is_text_response(headers):
return http_response
return response.content
async def load_markets_helper(self, reload=False, params={}):
if not reload:
if self.markets:
if not self.markets_by_id:
return self.set_markets(self.markets)
return self.markets
currencies = None
if self.has['fetchCurrencies']:
currencies = await self.fetch_currencies()
markets = await self.fetch_markets(params)
return self.set_markets(markets, currencies)
async def load_markets(self, reload=False, params={}):
if (reload and not self.reloading_markets) or not self.markets_loading:
self.reloading_markets = True
coroutine = self.load_markets_helper(reload, params)
# coroutines can only be awaited once so we wrap it in a task
self.markets_loading = asyncio.ensure_future(coroutine)
try:
result = await self.markets_loading
except Exception as e:
self.reloading_markets = False
self.markets_loading = None
raise e
self.reloading_markets = False
return result
async def fetch_fees(self):
trading = {}
funding = {}
if self.has['fetchTradingFees']:
trading = await self.fetch_trading_fees()
if self.has['fetchFundingFees']:
funding = await self.fetch_funding_fees()
return {
'trading': trading,
'funding': funding,
}
async def load_fees(self, reload=False):
if not reload:
if self.loaded_fees != Exchange.loaded_fees:
return self.loaded_fees
self.loaded_fees = self.deep_extend(self.loaded_fees, await self.fetch_fees())
return self.loaded_fees
async def fetch_markets(self, params={}):
# markets are returned as a list
# currencies are returned as a dict
# this is for historical reasons
# and may be changed for consistency later
return self.to_array(self.markets)
async def fetch_currencies(self, params={}):
# markets are returned as a list
# currencies are returned as a dict
# this is for historical reasons
# and may be changed for consistency later
return self.currencies
async def fetch_status(self, params={}):
if self.has['fetchTime']:
updated = await self.fetch_time(params)
self.status['updated'] = updated
return self.status
async def fetch_order_status(self, id, symbol=None, params={}):
order = await self.fetch_order(id, symbol, params)
return order['status']
async def fetch_partial_balance(self, part, params={}):
balance = await self.fetch_balance(params)
return balance[part]
async def fetch_l2_order_book(self, symbol, limit=None, params={}):
orderbook = await self.fetch_order_book(symbol, limit, params)
return self.extend(orderbook, {
'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True),
'asks': self.sort_by(self.aggregate(orderbook['asks']), 0),
})
async def perform_order_book_request(self, market, limit=None, params={}):
raise NotSupported(self.id + ' performOrderBookRequest not supported yet')
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
orderbook = await self.perform_order_book_request(market, limit, params)
return self.parse_order_book(orderbook, market, limit, params)
async def fetch_ohlcvc(self, symbol, timeframe='1m', since=None, limit=None, params={}):
if not self.has['fetchTrades']:
raise NotSupported('fetch_ohlcv() not implemented yet')
await self.load_markets()
trades = await self.fetch_trades(symbol, since, limit, params)
return self.build_ohlcvc(trades, timeframe, since, limit)
async def fetchOHLCVC(self, symbol, timeframe='1m', since=None, limit=None, params={}):
return await self.fetch_ohlcvc(symbol, timeframe, since, limit, params)
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
ohlcvs = await self.fetch_ohlcvc(symbol, timeframe, since, limit, params)
return [ohlcv[0:-1] for ohlcv in ohlcvs]
async def fetchOHLCV(self, symbol, timeframe='1m', since=None, limit=None, params={}):
return await self.fetch_ohlcv(symbol, timeframe, since, limit, params)
async def fetch_full_tickers(self, symbols=None, params={}):
return await self.fetch_tickers(symbols, params)
async def edit_order(self, id, symbol, *args):
if not self.enableRateLimit:
raise ExchangeError('updateOrder() requires enableRateLimit = true')
await self.cancel_order(id, symbol)
return await self.create_order(symbol, *args)
async def fetch_balance(self, params={}):
raise NotSupported('fetch_balance() not supported yet')
async def create_order(self, symbol, type, side, amount, price=None, params={}):
raise NotSupported('create_order() not supported yet')
async def cancel_order(self, id, symbol=None, params={}):
raise NotSupported('cancel_order() not supported yet')
async def fetch_trading_fees(self, params={}):
raise NotSupported('fetch_trading_fees() not supported yet')
async def fetch_trading_fee(self, symbol, params={}):
if not self.has['fetchTradingFees']:
raise NotSupported('fetch_trading_fee() not supported yet')
return await self.fetch_trading_fees(params)
async def load_trading_limits(self, symbols=None, reload=False, params={}):
if self.has['fetchTradingLimits']:
if reload or not('limitsLoaded' in list(self.options.keys())):
response = await self.fetch_trading_limits(symbols)
for i in range(0, len(symbols)):
symbol = symbols[i]
self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol])
self.options['limitsLoaded'] = self.milliseconds()
return self.markets
async def load_accounts(self, reload=False, params={}):
if reload:
self.accounts = await self.fetch_accounts(params)
else:
if self.accounts:
return self.accounts
else:
self.accounts = await self.fetch_accounts(params)
self.accountsById = self.index_by(self.accounts, 'id')
return self.accounts
async def fetch_ticker(self, symbol, params={}):
if self.has['fetchTickers']:
tickers = await self.fetch_tickers([symbol], params)
ticker = self.safe_value(tickers, symbol)
if ticker is None:
raise BadSymbol(self.id + ' fetchTickers could not find a ticker for ' + symbol)
else:
return ticker
else:
raise NotSupported(self.id + ' fetchTicker not supported yet')
async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_transactions() is not supported yet')
async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_deposits() is not supported yet')
async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_withdrawals() is not supported yet')
async def fetch_deposit_address(self, code, params={}):
if self.has['fetchDepositAddresses']:
deposit_addresses = await self.fetch_deposit_addresses([code], params)
deposit_address = self.safe_value(deposit_addresses, code)
if deposit_address is None:
raise NotSupported(self.id + ' fetch_deposit_address could not find a deposit address for ' + code + ', make sure you have created a corresponding deposit address in your wallet on the exchange website')
else:
return deposit_address
else:
raise NotSupported(self.id + ' fetchDepositAddress not supported yet')
async def sleep(self, milliseconds):
return await asyncio.sleep(milliseconds / 1000)
| 43.807163 | 355 | 0.617029 |
__version__ = '1.61.55'
import asyncio
import concurrent.futures
import socket
import certifi
import aiohttp
import ssl
import sys
import yarl
from ccxt.async_support.base.throttler import Throttler
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import RequestTimeout
from ccxt.base.errors import NotSupported
from ccxt.base.errors import BadSymbol
from ccxt.base.exchange import Exchange as BaseExchange
__all__ = [
'BaseExchange',
'Exchange',
]
class Exchange(BaseExchange):
synchronous = False
def __init__(self, config={}):
if 'asyncio_loop' in config:
self.asyncio_loop = config['asyncio_loop']
self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env)
self.verify = config.get('verify', self.verify)
self.own_session = 'session' not in config
self.cafile = config.get('cafile', certifi.where())
super(Exchange, self).__init__(config)
self.throttle = None
self.init_rest_rate_limiter()
self.markets_loading = None
self.reloading_markets = False
def init_rest_rate_limiter(self):
self.throttle = Throttler(self.tokenBucket, self.asyncio_loop)
def __del__(self):
if self.session is not None:
self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add exchange.close() to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).")
if sys.version_info >= (3, 5):
async def __aenter__(self):
self.open()
return self
async def __aexit__(self, exc_type, exc, tb):
await self.close()
def open(self):
if self.asyncio_loop is None:
if sys.version_info >= (3, 7):
self.asyncio_loop = asyncio.get_running_loop()
else:
self.asyncio_loop = asyncio.get_event_loop()
self.throttle.loop = self.asyncio_loop
if self.own_session and self.session is None:
context = ssl.create_default_context(cafile=self.cafile) if self.verify else self.verify
connector = aiohttp.TCPConnector(ssl=context, loop=self.asyncio_loop, enable_cleanup_closed=True)
self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector, trust_env=self.aiohttp_trust_env)
async def close(self):
if self.session is not None:
if self.own_session:
await self.session.close()
self.session = None
async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None, config={}, context={}):
if self.enableRateLimit:
cost = self.calculate_rate_limiter_cost(api, method, path, params, config, context)
await self.throttle(cost)
self.lastRestRequestTimestamp = self.milliseconds()
request = self.sign(path, api, method, params, headers, body)
return await self.fetch(request['url'], request['method'], request['headers'], request['body'])
async def fetch(self, url, method='GET', headers=None, body=None):
request_headers = self.prepare_request_headers(headers)
url = self.proxy + url
if self.verbose:
self.log("\nRequest:", method, url, headers, body)
self.logger.debug("%s %s, Request: %s %s", method, url, headers, body)
request_body = body
encoded_body = body.encode() if body else None
self.open()
session_method = getattr(self.session, method.lower())
http_response = None
http_status_code = None
http_status_text = None
json_response = None
try:
async with session_method(yarl.URL(url, encoded=True),
data=encoded_body,
headers=request_headers,
timeout=(self.timeout / 1000),
proxy=self.aiohttp_proxy) as response:
http_response = await response.text(errors='replace')
raw_headers = response.headers
headers = {}
for header in raw_headers:
if header in headers:
headers[header] = headers[header] + ', ' + raw_headers[header]
else:
headers[header] = raw_headers[header]
http_status_code = response.status
http_status_text = response.reason
http_response = self.on_rest_response(http_status_code, http_status_text, url, method, headers, http_response, request_headers, request_body)
json_response = self.parse_json(http_response)
if self.enableLastHttpResponse:
self.last_http_response = http_response
if self.enableLastResponseHeaders:
self.last_response_headers = headers
if self.enableLastJsonResponse:
self.last_json_response = json_response
if self.verbose:
self.log("\nResponse:", method, url, http_status_code, headers, http_response)
self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response)
except socket.gaierror as e:
details = ' '.join([self.id, method, url])
raise ExchangeNotAvailable(details) from e
except (concurrent.futures.TimeoutError, asyncio.TimeoutError) as e:
details = ' '.join([self.id, method, url])
raise RequestTimeout(details) from e
except aiohttp.ClientConnectionError as e:
details = ' '.join([self.id, method, url])
raise ExchangeNotAvailable(details) from e
except aiohttp.ClientError as e:
details = ' '.join([self.id, method, url])
raise ExchangeError(details) from e
self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
if json_response is not None:
return json_response
if self.is_text_response(headers):
return http_response
return response.content
async def load_markets_helper(self, reload=False, params={}):
if not reload:
if self.markets:
if not self.markets_by_id:
return self.set_markets(self.markets)
return self.markets
currencies = None
if self.has['fetchCurrencies']:
currencies = await self.fetch_currencies()
markets = await self.fetch_markets(params)
return self.set_markets(markets, currencies)
async def load_markets(self, reload=False, params={}):
if (reload and not self.reloading_markets) or not self.markets_loading:
self.reloading_markets = True
coroutine = self.load_markets_helper(reload, params)
self.markets_loading = asyncio.ensure_future(coroutine)
try:
result = await self.markets_loading
except Exception as e:
self.reloading_markets = False
self.markets_loading = None
raise e
self.reloading_markets = False
return result
async def fetch_fees(self):
trading = {}
funding = {}
if self.has['fetchTradingFees']:
trading = await self.fetch_trading_fees()
if self.has['fetchFundingFees']:
funding = await self.fetch_funding_fees()
return {
'trading': trading,
'funding': funding,
}
async def load_fees(self, reload=False):
if not reload:
if self.loaded_fees != Exchange.loaded_fees:
return self.loaded_fees
self.loaded_fees = self.deep_extend(self.loaded_fees, await self.fetch_fees())
return self.loaded_fees
async def fetch_markets(self, params={}):
return self.to_array(self.markets)
async def fetch_currencies(self, params={}):
return self.currencies
async def fetch_status(self, params={}):
if self.has['fetchTime']:
updated = await self.fetch_time(params)
self.status['updated'] = updated
return self.status
async def fetch_order_status(self, id, symbol=None, params={}):
order = await self.fetch_order(id, symbol, params)
return order['status']
async def fetch_partial_balance(self, part, params={}):
balance = await self.fetch_balance(params)
return balance[part]
async def fetch_l2_order_book(self, symbol, limit=None, params={}):
orderbook = await self.fetch_order_book(symbol, limit, params)
return self.extend(orderbook, {
'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True),
'asks': self.sort_by(self.aggregate(orderbook['asks']), 0),
})
async def perform_order_book_request(self, market, limit=None, params={}):
raise NotSupported(self.id + ' performOrderBookRequest not supported yet')
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
orderbook = await self.perform_order_book_request(market, limit, params)
return self.parse_order_book(orderbook, market, limit, params)
async def fetch_ohlcvc(self, symbol, timeframe='1m', since=None, limit=None, params={}):
if not self.has['fetchTrades']:
raise NotSupported('fetch_ohlcv() not implemented yet')
await self.load_markets()
trades = await self.fetch_trades(symbol, since, limit, params)
return self.build_ohlcvc(trades, timeframe, since, limit)
async def fetchOHLCVC(self, symbol, timeframe='1m', since=None, limit=None, params={}):
return await self.fetch_ohlcvc(symbol, timeframe, since, limit, params)
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
ohlcvs = await self.fetch_ohlcvc(symbol, timeframe, since, limit, params)
return [ohlcv[0:-1] for ohlcv in ohlcvs]
async def fetchOHLCV(self, symbol, timeframe='1m', since=None, limit=None, params={}):
return await self.fetch_ohlcv(symbol, timeframe, since, limit, params)
async def fetch_full_tickers(self, symbols=None, params={}):
return await self.fetch_tickers(symbols, params)
async def edit_order(self, id, symbol, *args):
if not self.enableRateLimit:
raise ExchangeError('updateOrder() requires enableRateLimit = true')
await self.cancel_order(id, symbol)
return await self.create_order(symbol, *args)
async def fetch_balance(self, params={}):
raise NotSupported('fetch_balance() not supported yet')
async def create_order(self, symbol, type, side, amount, price=None, params={}):
raise NotSupported('create_order() not supported yet')
async def cancel_order(self, id, symbol=None, params={}):
raise NotSupported('cancel_order() not supported yet')
async def fetch_trading_fees(self, params={}):
raise NotSupported('fetch_trading_fees() not supported yet')
async def fetch_trading_fee(self, symbol, params={}):
if not self.has['fetchTradingFees']:
raise NotSupported('fetch_trading_fee() not supported yet')
return await self.fetch_trading_fees(params)
async def load_trading_limits(self, symbols=None, reload=False, params={}):
if self.has['fetchTradingLimits']:
if reload or not('limitsLoaded' in list(self.options.keys())):
response = await self.fetch_trading_limits(symbols)
for i in range(0, len(symbols)):
symbol = symbols[i]
self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol])
self.options['limitsLoaded'] = self.milliseconds()
return self.markets
async def load_accounts(self, reload=False, params={}):
if reload:
self.accounts = await self.fetch_accounts(params)
else:
if self.accounts:
return self.accounts
else:
self.accounts = await self.fetch_accounts(params)
self.accountsById = self.index_by(self.accounts, 'id')
return self.accounts
async def fetch_ticker(self, symbol, params={}):
if self.has['fetchTickers']:
tickers = await self.fetch_tickers([symbol], params)
ticker = self.safe_value(tickers, symbol)
if ticker is None:
raise BadSymbol(self.id + ' fetchTickers could not find a ticker for ' + symbol)
else:
return ticker
else:
raise NotSupported(self.id + ' fetchTicker not supported yet')
async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_transactions() is not supported yet')
async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_deposits() is not supported yet')
async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
raise NotSupported('fetch_withdrawals() is not supported yet')
async def fetch_deposit_address(self, code, params={}):
if self.has['fetchDepositAddresses']:
deposit_addresses = await self.fetch_deposit_addresses([code], params)
deposit_address = self.safe_value(deposit_addresses, code)
if deposit_address is None:
raise NotSupported(self.id + ' fetch_deposit_address could not find a deposit address for ' + code + ', make sure you have created a corresponding deposit address in your wallet on the exchange website')
else:
return deposit_address
else:
raise NotSupported(self.id + ' fetchDepositAddress not supported yet')
async def sleep(self, milliseconds):
return await asyncio.sleep(milliseconds / 1000)
| true | true |
f726c5d759f5490c1ae882cd36b4a8678f29a3ed | 4,451 | py | Python | dark/process.py | UdoGi/dark-matter | 3d49e89fa5e81f83144119f6216c5774176d203b | [
"MIT"
] | 10 | 2016-03-09T09:43:14.000Z | 2021-04-03T21:46:12.000Z | dark/process.py | terrycojones/dark-matter | 67d16f870db6b4239e17e542bc6e3f072dc29c75 | [
"MIT"
] | 332 | 2015-01-07T12:37:30.000Z | 2022-01-20T15:48:11.000Z | dark/process.py | terrycojones/dark-matter | 67d16f870db6b4239e17e542bc6e3f072dc29c75 | [
"MIT"
] | 4 | 2016-03-08T14:56:39.000Z | 2021-01-27T08:11:27.000Z | from __future__ import division, print_function
import six
from time import time, ctime
from subprocess import PIPE, CalledProcessError
if six.PY3:
from subprocess import run
else:
from subprocess import check_call
class Executor(object):
"""
Log and execute shell commands.
@param dryRun: If C{True}, do not execute commands, just log them.
This sets the default and can be overidden for a specific command
by passing C{dryRun} to the C{execute} method.
"""
def __init__(self, dryRun=False):
self.dryRun = dryRun
self.log = [
'# Executor created at %s. Dry run = %s.' % (ctime(time()), dryRun)
]
def dryRun(self):
"""
Is this a dry run?
@return: A Boolean indicating whether this is a dry run.
"""
return self._dryRun
def execute(self, command, dryRun=None, useStderr=True, **kwargs):
"""
Execute (or simulate) a command. Add to our log.
@param command: Either a C{str} command (which will be passed to the
shell) or a C{list} of command arguments (including the executable
name), in which case the shell is not used.
@param dryRun: If C{True}, do not execute commands, just log them.
If C{False}, execute the commands. If not given or C{None}, use
the default setting (in C{self.dryRun}).
@param useStderr: If C{True} print a summary of the command standard
output and standard error to sys.stderr if the command results in
an exception. If a function is passed, the exception is passed to
the function and the summary is printed to sys.stderr if the
function returns C{True}.
@param kwargs: Keyword arguments that will be passed to subprocess.run
(or subprocess.check_call for Python version 2). Note that keyword
arguments are not currently logged (the logging is slightly
problematic since a keyword argument might be an environment
dictionary).
@raise CalledProcessError: If the command results in an error.
@return: A C{CompletedProcess} instance. This has attributes such as
C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess.
If C{dryRun} is C{True}, C{None} is returned.
"""
if isinstance(command, six.string_types):
# Can't have newlines in a command given to the shell.
strCommand = command = command.replace('\n', ' ').strip()
shell = True
else:
strCommand = ' '.join(command)
shell = False
dryRun = self.dryRun if dryRun is None else dryRun
if dryRun:
self.log.append('$ ' + strCommand)
return
start = time()
self.log.extend([
'# Start command (shell=%s) at %s' % (shell, ctime(start)),
'$ ' + strCommand,
])
if six.PY3:
try:
result = run(command, check=True, stdout=PIPE, stderr=PIPE,
shell=shell, universal_newlines=True, **kwargs)
except CalledProcessError as e:
if callable(useStderr):
useStderr = useStderr(e)
if useStderr:
import sys
print('CalledProcessError:', e, file=sys.stderr)
print('STDOUT:\n%s' % e.stdout, file=sys.stderr)
print('STDERR:\n%s' % e.stderr, file=sys.stderr)
raise
else:
try:
result = check_call(command, stdout=PIPE, stderr=PIPE,
shell=shell, universal_newlines=True,
**kwargs)
except CalledProcessError as e:
if callable(useStderr):
useStderr = useStderr(e)
if useStderr:
import sys
print('CalledProcessError:', e, file=sys.stderr)
print('Return code: %s' % e.returncode, file=sys.stderr)
print('Output:\n%s' % e.output, file=sys.stderr)
raise
stop = time()
elapsed = (stop - start)
self.log.extend([
'# Stop command at %s' % ctime(stop),
'# Elapsed = %f seconds' % elapsed,
])
return result
| 38.37069 | 79 | 0.560324 | from __future__ import division, print_function
import six
from time import time, ctime
from subprocess import PIPE, CalledProcessError
if six.PY3:
from subprocess import run
else:
from subprocess import check_call
class Executor(object):
def __init__(self, dryRun=False):
self.dryRun = dryRun
self.log = [
'# Executor created at %s. Dry run = %s.' % (ctime(time()), dryRun)
]
def dryRun(self):
return self._dryRun
def execute(self, command, dryRun=None, useStderr=True, **kwargs):
if isinstance(command, six.string_types):
strCommand = command = command.replace('\n', ' ').strip()
shell = True
else:
strCommand = ' '.join(command)
shell = False
dryRun = self.dryRun if dryRun is None else dryRun
if dryRun:
self.log.append('$ ' + strCommand)
return
start = time()
self.log.extend([
'
'$ ' + strCommand,
])
if six.PY3:
try:
result = run(command, check=True, stdout=PIPE, stderr=PIPE,
shell=shell, universal_newlines=True, **kwargs)
except CalledProcessError as e:
if callable(useStderr):
useStderr = useStderr(e)
if useStderr:
import sys
print('CalledProcessError:', e, file=sys.stderr)
print('STDOUT:\n%s' % e.stdout, file=sys.stderr)
print('STDERR:\n%s' % e.stderr, file=sys.stderr)
raise
else:
try:
result = check_call(command, stdout=PIPE, stderr=PIPE,
shell=shell, universal_newlines=True,
**kwargs)
except CalledProcessError as e:
if callable(useStderr):
useStderr = useStderr(e)
if useStderr:
import sys
print('CalledProcessError:', e, file=sys.stderr)
print('Return code: %s' % e.returncode, file=sys.stderr)
print('Output:\n%s' % e.output, file=sys.stderr)
raise
stop = time()
elapsed = (stop - start)
self.log.extend([
'
'
])
return result
| true | true |
f726c61ee010e4614285c7fc75b5c47cb8f51c57 | 318 | py | Python | Preprocessing/scripts/dec_user_id.py | udhavsethi/contentNCF | d11273956bf9c793eb616cde9c3da01c70e5403b | [
"Apache-2.0"
] | 2 | 2021-09-16T02:14:57.000Z | 2022-02-02T01:16:26.000Z | Preprocessing/scripts/dec_user_id.py | udhavsethi/contentNCF | d11273956bf9c793eb616cde9c3da01c70e5403b | [
"Apache-2.0"
] | null | null | null | Preprocessing/scripts/dec_user_id.py | udhavsethi/contentNCF | d11273956bf9c793eb616cde9c3da01c70e5403b | [
"Apache-2.0"
] | null | null | null | infile = open('500_users_to_images.train', 'r')
outfile = open('pinterest.data', 'w')
for line in infile.readlines():
user_id, img_id, img_url = line.strip().split('\t')
dec_user_id = str(int(user_id) - 1)
outfile.write("{}\t{}\t{}\n".format(dec_user_id, img_id, img_url))
infile.close()
outfile.close()
| 28.909091 | 70 | 0.666667 | infile = open('500_users_to_images.train', 'r')
outfile = open('pinterest.data', 'w')
for line in infile.readlines():
user_id, img_id, img_url = line.strip().split('\t')
dec_user_id = str(int(user_id) - 1)
outfile.write("{}\t{}\t{}\n".format(dec_user_id, img_id, img_url))
infile.close()
outfile.close()
| true | true |
f726c69eef6c7661033f52ac8cc3885f33c80910 | 686 | py | Python | app/core/migrations/0003_ingredient.py | amaurycoudr/recipe-app-api | ab4da3d5553230d9b15ddc6f97091e3f01cc348e | [
"MIT"
] | null | null | null | app/core/migrations/0003_ingredient.py | amaurycoudr/recipe-app-api | ab4da3d5553230d9b15ddc6f97091e3f01cc348e | [
"MIT"
] | null | null | null | app/core/migrations/0003_ingredient.py | amaurycoudr/recipe-app-api | ab4da3d5553230d9b15ddc6f97091e3f01cc348e | [
"MIT"
] | null | null | null | # Generated by Django 2.1.15 on 2020-08-24 07:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
name='Ingredient',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| 28.583333 | 118 | 0.618076 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
name='Ingredient',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| true | true |
f726c7af66c2d6b8cae93c16306362700e6e476b | 2,702 | py | Python | examples/face_recognition_svm.py | viettriit2110/face_recognition | 0e1821af6538c573ed4a87acc361c44900f849eb | [
"MIT"
] | 2 | 2019-11-12T06:22:45.000Z | 2019-11-12T14:30:00.000Z | examples/face_recognition_svm.py | viettriit2110/face_recognition | 0e1821af6538c573ed4a87acc361c44900f849eb | [
"MIT"
] | null | null | null | examples/face_recognition_svm.py | viettriit2110/face_recognition | 0e1821af6538c573ed4a87acc361c44900f849eb | [
"MIT"
] | null | null | null | # Train multiple images per person
# Find and recognize faces in an image using a SVC with scikit-learn
"""
Structure:
<test_image>.jpg
<train_dir>/
<person_1>/
<person_1_face-1>.jpg
<person_1_face-2>.jpg
.
.
<person_1_face-n>.jpg
<person_2>/
<person_2_face-1>.jpg
<person_2_face-2>.jpg
.
.
<person_2_face-n>.jpg
.
.
<person_n>/
<person_n_face-1>.jpg
<person_n_face-2>.jpg
.
.
<person_n_face-n>.jpg
"""
import face_recognition
from sklearn import svm
import os
# Training the SVC classifier
# The training data would be all the face encodings from all the known images and the labels are their names
encodings = []
names = []
# Training directory
train_dir = os.listdir('/train_dir/')
# Loop through each person in the training directory
for person in train_dir:
pix = os.listdir("/train_dir/" + person)
# Loop through each training image for the current person
for person_img in pix:
# Get the face encodings for the face in each image file
face = face_recognition.load_image_file("/train_dir/" + person + "/" + person_img)
face_bounding_boxes = face_recognition.face_locations(face)
#If training image contains none or more than faces, print an error message and exit
if len(face_bounding_boxes) != 1:
print(person + "/" + person_img + " contains none or more than one faces and can't be used for training.")
exit()
else:
face_enc = face_recognition.face_encodings(face)[0]
# Add face encoding for current image with corresponding label (name) to the training data
encodings.append(face_enc)
names.append(person)
# Create and train the SVC classifier
clf = svm.SVC(gamma='scale')
clf.fit(encodings,names)
# Load the test image with unknown faces into a numpy array
test_image = face_recognition.load_image_file('test_image.jpg')
# Find all the faces in the test image using the default HOG-based model
face_locations = face_recognition.face_locations(test_image)
no = len(face_locations)
print("Number of faces detected: ", no)
# Predict all the faces in the test image using the trained classifier
print("Found:")
for i in range(no):
test_image_enc = face_recognition.face_encodings(test_image)[i]
name = clf.predict([test_image_enc])
print(*name)
| 33.358025 | 119 | 0.611769 |
import face_recognition
from sklearn import svm
import os
encodings = []
names = []
train_dir = os.listdir('/train_dir/')
for person in train_dir:
pix = os.listdir("/train_dir/" + person)
for person_img in pix:
face = face_recognition.load_image_file("/train_dir/" + person + "/" + person_img)
face_bounding_boxes = face_recognition.face_locations(face)
if len(face_bounding_boxes) != 1:
print(person + "/" + person_img + " contains none or more than one faces and can't be used for training.")
exit()
else:
face_enc = face_recognition.face_encodings(face)[0]
# Add face encoding for current image with corresponding label (name) to the training data
encodings.append(face_enc)
names.append(person)
# Create and train the SVC classifier
clf = svm.SVC(gamma='scale')
clf.fit(encodings,names)
# Load the test image with unknown faces into a numpy array
test_image = face_recognition.load_image_file('test_image.jpg')
# Find all the faces in the test image using the default HOG-based model
face_locations = face_recognition.face_locations(test_image)
no = len(face_locations)
print("Number of faces detected: ", no)
# Predict all the faces in the test image using the trained classifier
print("Found:")
for i in range(no):
test_image_enc = face_recognition.face_encodings(test_image)[i]
name = clf.predict([test_image_enc])
print(*name)
| true | true |
f726c7e3f9f0e96210a1b6a0a5aa57076aacdff1 | 17,093 | py | Python | aldryn_newsblog/south_migrations/0010_auto__add_unique_articletranslation_language_code_slug__del_field_arti.py | what-digital/aldryn-newsblog-blog-teaser-size | c52cb256fe3b608838f2184de9575b6cbbfd5f8e | [
"BSD-3-Clause"
] | null | null | null | aldryn_newsblog/south_migrations/0010_auto__add_unique_articletranslation_language_code_slug__del_field_arti.py | what-digital/aldryn-newsblog-blog-teaser-size | c52cb256fe3b608838f2184de9575b6cbbfd5f8e | [
"BSD-3-Clause"
] | null | null | null | aldryn_newsblog/south_migrations/0010_auto__add_unique_articletranslation_language_code_slug__del_field_arti.py | what-digital/aldryn-newsblog-blog-teaser-size | c52cb256fe3b608838f2184de9575b6cbbfd5f8e | [
"BSD-3-Clause"
] | 2 | 2019-10-22T04:30:28.000Z | 2019-10-22T05:09:16.000Z | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from aldryn_newsblog.utils.migration import rename_tables_old_to_new, rename_tables_new_to_old
class Migration(SchemaMigration):
def forwards(self, orm):
rename_tables_old_to_new(db)
# Adding unique constraint on 'ArticleTranslation', fields ['language_code', 'slug']
db.create_unique(u'aldryn_newsblog_article_translation', ['language_code', 'slug'])
# Deleting field 'Article.slug'
db.delete_column(u'aldryn_newsblog_article', 'slug')
def backwards(self, orm):
rename_tables_new_to_old(db)
# Removing unique constraint on 'ArticleTranslation', fields ['language_code', 'slug']
db.delete_unique(u'aldryn_newsblog_article_translation', ['language_code', 'slug'])
# Adding field 'Article.slug'
db.add_column(u'aldryn_newsblog_article', 'slug',
self.gf('django.db.models.fields.SlugField')(default='', max_length=255, blank=True),
keep_default=False)
models = {
u'aldryn_categories.category': {
'Meta': {'object_name': 'Category'},
'depth': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'rgt': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
u'aldryn_newsblog.article': {
'Meta': {'ordering': "[u'-publishing_date']", 'object_name': 'Article'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_people.Person']", 'null': 'True', 'blank': 'True'}),
'categories': ('aldryn_categories.fields.CategoryManyToManyField', [], {'to': u"orm['aldryn_categories.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'aldryn_newsblog_articles'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Placeholder']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'namespace': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_newsblog.NewsBlogConfig']"}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'publishing_date': ('django.db.models.fields.DateTimeField', [], {})
},
u'aldryn_newsblog.articletranslation': {
'Meta': {'unique_together': "[(u'language_code', u'slug'), (u'language_code', u'master')]", 'object_name': 'ArticleTranslation', 'db_table': "u'aldryn_newsblog_article_translation'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'lead_in': ('djangocms_text_ckeditor.fields.HTMLField', [], {'default': "u''"}),
u'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'null': 'True', 'to': u"orm['aldryn_newsblog.Article']"}),
'meta_description': ('django.db.models.fields.TextField', [], {'default': "u''", 'blank': 'True'}),
'meta_keywords': ('django.db.models.fields.TextField', [], {'default': "u''", 'blank': 'True'}),
'meta_title': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '234'})
},
u'aldryn_newsblog.latestentriesplugin': {
'Meta': {'object_name': 'LatestEntriesPlugin', '_ormbases': ['cms.CMSPlugin']},
u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'latest_entries': ('django.db.models.fields.IntegerField', [], {'default': '5'})
},
u'aldryn_newsblog.newsblogconfig': {
'Meta': {'unique_together': "(('type', 'namespace'),)", 'object_name': 'NewsBlogConfig'},
'app_data': ('app_data.fields.AppDataField', [], {'default': "'{}'"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'namespace': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '100'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'aldryn_people.group': {
'Meta': {'object_name': 'Group'},
'address': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'default': "''", 'max_length': '75', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'aldryn_people.person': {
'Meta': {'object_name': 'Person'},
'email': ('django.db.models.fields.EmailField', [], {'default': "''", 'max_length': '75', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_people.Group']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mobile': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'vcard_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'visual': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['filer.Image']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'filer.file': {
'Meta': {'object_name': 'File'},
'_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'all_files'", 'null': 'True', 'to': u"orm['filer.Folder']"}),
'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'owned_files'", 'null': 'True', 'to': u"orm['auth.User']"}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_filer.file_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'sha1': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '40', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
u'filer.folder': {
'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'parent', u'name'),)", 'object_name': 'Folder'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'filer_owned_folders'", 'null': 'True', 'to': u"orm['auth.User']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'children'", 'null': 'True', 'to': u"orm['filer.Folder']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.image': {
'Meta': {'object_name': 'Image', '_ormbases': [u'filer.File']},
'_height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'_width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'default_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'default_caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
u'file_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['filer.File']", 'unique': 'True', 'primary_key': 'True'}),
'must_always_publish_author_credit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'must_always_publish_copyright': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'subject_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '64', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['aldryn_newsblog'] | 83.789216 | 195 | 0.572398 |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from aldryn_newsblog.utils.migration import rename_tables_old_to_new, rename_tables_new_to_old
class Migration(SchemaMigration):
def forwards(self, orm):
rename_tables_old_to_new(db)
db.create_unique(u'aldryn_newsblog_article_translation', ['language_code', 'slug'])
db.delete_column(u'aldryn_newsblog_article', 'slug')
def backwards(self, orm):
rename_tables_new_to_old(db)
db.delete_unique(u'aldryn_newsblog_article_translation', ['language_code', 'slug'])
db.add_column(u'aldryn_newsblog_article', 'slug',
self.gf('django.db.models.fields.SlugField')(default='', max_length=255, blank=True),
keep_default=False)
models = {
u'aldryn_categories.category': {
'Meta': {'object_name': 'Category'},
'depth': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'rgt': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
u'aldryn_newsblog.article': {
'Meta': {'ordering': "[u'-publishing_date']", 'object_name': 'Article'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_people.Person']", 'null': 'True', 'blank': 'True'}),
'categories': ('aldryn_categories.fields.CategoryManyToManyField', [], {'to': u"orm['aldryn_categories.Category']", 'symmetrical': 'False', 'blank': 'True'}),
'content': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'aldryn_newsblog_articles'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.Placeholder']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'namespace': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_newsblog.NewsBlogConfig']"}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'publishing_date': ('django.db.models.fields.DateTimeField', [], {})
},
u'aldryn_newsblog.articletranslation': {
'Meta': {'unique_together': "[(u'language_code', u'slug'), (u'language_code', u'master')]", 'object_name': 'ArticleTranslation', 'db_table': "u'aldryn_newsblog_article_translation'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'lead_in': ('djangocms_text_ckeditor.fields.HTMLField', [], {'default': "u''"}),
u'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'translations'", 'null': 'True', 'to': u"orm['aldryn_newsblog.Article']"}),
'meta_description': ('django.db.models.fields.TextField', [], {'default': "u''", 'blank': 'True'}),
'meta_keywords': ('django.db.models.fields.TextField', [], {'default': "u''", 'blank': 'True'}),
'meta_title': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '234'})
},
u'aldryn_newsblog.latestentriesplugin': {
'Meta': {'object_name': 'LatestEntriesPlugin', '_ormbases': ['cms.CMSPlugin']},
u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'latest_entries': ('django.db.models.fields.IntegerField', [], {'default': '5'})
},
u'aldryn_newsblog.newsblogconfig': {
'Meta': {'unique_together': "(('type', 'namespace'),)", 'object_name': 'NewsBlogConfig'},
'app_data': ('app_data.fields.AppDataField', [], {'default': "'{}'"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'namespace': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '100'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'aldryn_people.group': {
'Meta': {'object_name': 'Group'},
'address': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'default': "''", 'max_length': '75', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'aldryn_people.person': {
'Meta': {'object_name': 'Person'},
'email': ('django.db.models.fields.EmailField', [], {'default': "''", 'max_length': '75', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_people.Group']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mobile': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'vcard_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'visual': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['filer.Image']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'filer.file': {
'Meta': {'object_name': 'File'},
'_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'all_files'", 'null': 'True', 'to': u"orm['filer.Folder']"}),
'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'owned_files'", 'null': 'True', 'to': u"orm['auth.User']"}),
'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'polymorphic_filer.file_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
'sha1': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '40', 'blank': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
u'filer.folder': {
'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'parent', u'name'),)", 'object_name': 'Folder'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'filer_owned_folders'", 'null': 'True', 'to': u"orm['auth.User']"}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'children'", 'null': 'True', 'to': u"orm['filer.Folder']"}),
u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'filer.image': {
'Meta': {'object_name': 'Image', '_ormbases': [u'filer.File']},
'_height': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'_width': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'author': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'date_taken': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'default_alt_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'default_caption': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
u'file_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['filer.File']", 'unique': 'True', 'primary_key': 'True'}),
'must_always_publish_author_credit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'must_always_publish_copyright': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'subject_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '64', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['aldryn_newsblog'] | true | true |
f726c922dcd0dfb1fe6fe59bdb40b901325c9e0a | 33,645 | py | Python | ambassador/ambassador/config/resourcefetcher.py | Andrei-Predoiu/ambassador | efbd0ac8d65e36eab68997051167bc3eea165f35 | [
"Apache-2.0"
] | null | null | null | ambassador/ambassador/config/resourcefetcher.py | Andrei-Predoiu/ambassador | efbd0ac8d65e36eab68997051167bc3eea165f35 | [
"Apache-2.0"
] | null | null | null | ambassador/ambassador/config/resourcefetcher.py | Andrei-Predoiu/ambassador | efbd0ac8d65e36eab68997051167bc3eea165f35 | [
"Apache-2.0"
] | null | null | null | from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
# from typing import cast as typecast
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[str, List[AnyDict]]]
# Some thoughts:
# - loading a bunch of Ambassador resources is different from loading a bunch of K8s
# services, because we should assume that if we're being a fed a bunch of Ambassador
# resources, we'll get a full set. The whole 'secret loader' thing needs to have the
# concept of a TLSSecret resource that can be force-fed to us, or that can be fetched
# through the loader if needed.
# - If you're running a debug-loop Ambassador, you should just have a flat (or
# recursive, I don't care) directory full of Ambassador YAML, including TLSSecrets
# and Endpoints and whatnot, as needed. All of it will get read by
# load_from_filesystem and end up in the elements array.
# - If you're running expecting to be fed by kubewatch, at present kubewatch will
# send over K8s Service records, and anything annotated in there will end up in
# elements. This may include TLSSecrets or Endpoints. Any TLSSecret mentioned that
# isn't already in elements will need to be fetched.
# - Ambassador resources do not have namespaces. They have the ambassador_id. That's
# it. The ambassador_id is completely orthogonal to the namespace. No element with
# the wrong ambassador_id will end up in elements. It would be nice if they were
# never sent by kubewatch, but, well, y'know.
# - TLSSecret resources are not TLSContexts. TLSSecrets only have a name, a private
# half, and a public half. They do _not_ have other TLSContext information.
# - Endpoint resources probably have just a name, a service name, and an endpoint
# address.
class ResourceFetcher:
def __init__(self, logger: logging.Logger, aconf: 'Config') -> None:
self.aconf = aconf
self.logger = logger
self.elements: List[ACResource] = []
self.filename: Optional[str] = None
self.ocount: int = 1
self.saved: List[Tuple[Optional[str], int]] = []
self.k8s_endpoints: Dict[str, AnyDict] = {}
self.k8s_services: Dict[str, AnyDict] = {}
self.services: Dict[str, AnyDict] = {}
@property
def location(self):
return "%s.%d" % (self.filename or "anonymous YAML", self.ocount)
def push_location(self, filename: Optional[str], ocount: int) -> None:
self.saved.append((self.filename, self.ocount))
self.filename = filename
self.ocount = ocount
def pop_location(self) -> None:
self.filename, self.ocount = self.saved.pop()
def load_from_filesystem(self, config_dir_path, recurse: bool=False, k8s: bool=False):
inputs: List[Tuple[str, str]] = []
if os.path.isdir(config_dir_path):
dirs = [ config_dir_path ]
while dirs:
dirpath = dirs.pop(0)
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
if recurse and os.path.isdir(filepath):
# self.logger.debug("%s: RECURSE" % filepath)
dirs.append(filepath)
continue
if not os.path.isfile(filepath):
# self.logger.debug("%s: SKIP non-file" % filepath)
continue
if not filename.lower().endswith('.yaml'):
# self.logger.debug("%s: SKIP non-YAML" % filepath)
continue
# self.logger.debug("%s: SAVE configuration file" % filepath)
inputs.append((filepath, filename))
else:
# this allows a file to be passed into the ambassador cli
# rather than just a directory
inputs.append((config_dir_path, os.path.basename(config_dir_path)))
for filepath, filename in inputs:
self.logger.info("reading %s (%s)" % (filename, filepath))
try:
serialization = open(filepath, "r").read()
self.parse_yaml(serialization, k8s=k8s, filename=filename)
except IOError as e:
self.aconf.post_error("could not read YAML from %s: %s" % (filepath, e))
self.finalize()
def parse_yaml(self, serialization: str, k8s=False, rkey: Optional[str]=None,
filename: Optional[str]=None) -> None:
# self.logger.debug("%s: parsing %d byte%s of YAML:\n%s" %
# (self.location, len(serialization), "" if (len(serialization) == 1) else "s",
# serialization))
try:
objects = parse_yaml(serialization)
self.parse_object(objects=objects, k8s=k8s, rkey=rkey, filename=filename)
except yaml.error.YAMLError as e:
self.aconf.post_error("%s: could not parse YAML: %s" % (self.location, e))
self.finalize()
def parse_json(self, serialization: str, k8s=False, rkey: Optional[str]=None,
filename: Optional[str]=None) -> None:
# self.logger.debug("%s: parsing %d byte%s of YAML:\n%s" %
# (self.location, len(serialization), "" if (len(serialization) == 1) else "s",
# serialization))
try:
objects = json.loads(serialization)
self.parse_object(objects=objects, k8s=k8s, rkey=rkey, filename=filename)
except json.decoder.JSONDecodeError as e:
self.aconf.post_error("%s: could not parse YAML: %s" % (self.location, e))
self.finalize()
def parse_watt(self, serialization: str) -> None:
basedir = os.environ.get('AMBASSADOR_CONFIG_BASE_DIR', '/ambassador')
if os.path.isfile(os.path.join(basedir, '.ambassador_ignore_crds')):
self.aconf.post_error("Ambassador could not find core CRD definitions. Please visit https://www.getambassador.io/reference/core/crds/ for more information. You can continue using Ambassador via Kubernetes annotations, any configuration via CRDs will be ignored...")
if os.path.isfile(os.path.join(basedir, '.ambassador_ignore_crds_2')):
self.aconf.post_error("Ambassador could not find Resolver type CRD definitions. Please visit https://www.getambassador.io/reference/core/crds/ for more information. You can continue using Ambassador via Kubernetes annotations, any configuration via CRDs will be ignored...")
try:
watt_dict = json.loads(serialization)
watt_k8s = watt_dict.get('Kubernetes', {})
# Handle normal Kube objects...
for key in [ 'service', 'endpoints', 'secret' ]:
for obj in watt_k8s.get(key) or []:
self.handle_k8s(obj)
# ...then handle Ambassador CRDs.
for key in [ 'AuthService', 'ConsulResolver',
'KubernetesEndpointResolver', 'KubernetesServiceResolver',
'Mapping', 'Module', 'RateLimitService',
'TCPMapping', 'TLSContext', 'TracingService']:
for obj in watt_k8s.get(key) or []:
self.handle_k8s_crd(obj)
watt_consul = watt_dict.get('Consul', {})
consul_endpoints = watt_consul.get('Endpoints', {})
for consul_rkey, consul_object in consul_endpoints.items():
result = self.handle_consul_service(consul_rkey, consul_object)
if result:
rkey, parsed_objects = result
self.parse_object(parsed_objects, k8s=False,
filename=self.filename, rkey=rkey)
except json.decoder.JSONDecodeError as e:
self.aconf.post_error("%s: could not parse WATT: %s" % (self.location, e))
self.finalize()
def handle_k8s(self, obj: dict) -> None:
# self.logger.debug("handle_k8s obj %s" % json.dumps(obj, indent=4, sort_keys=True))
kind = obj.get('kind')
if not kind:
# self.logger.debug("%s: ignoring K8s object, no kind" % self.location)
return
handler_name = f'handle_k8s_{kind.lower()}'
handler = getattr(self, handler_name, None)
if not handler:
# self.logger.debug("%s: ignoring K8s object, no kind" % self.location)
return
result = handler(obj)
if result:
rkey, parsed_objects = result
self.parse_object(parsed_objects, k8s=False,
filename=self.filename, rkey=rkey)
def handle_k8s_crd(self, obj: dict) -> None:
# CRDs are _not_ allowed to have embedded objects in annotations, because ew.
kind = obj.get('kind')
if not kind:
self.logger.debug("%s: ignoring K8s CRD, no kind" % self.location)
return
apiVersion = obj.get('apiVersion')
metadata = obj.get('metadata') or {}
name = metadata.get('name')
namespace = metadata.get('namespace') or 'default'
spec = obj.get('spec') or {}
if not name:
self.logger.debug(f'{self.location}: ignoring K8s {kind} CRD, no name')
return
if not apiVersion:
self.logger.debug(f'{self.location}: ignoring K8s {kind} CRD {name}: no apiVersion')
return
# if not spec:
# self.logger.debug(f'{self.location}: ignoring K8s {kind} CRD {name}: no spec')
# return
# We use this resource identifier as a key into self.k8s_services, and of course for logging .
resource_identifier = f'{name}.{namespace}'
# OK. Shallow copy 'spec'...
amb_object = dict(spec)
# ...and then stuff in a couple of other things.
amb_object['apiVersion'] = apiVersion
amb_object['name'] = name
amb_object['kind'] = kind
# Done. Parse it.
self.parse_object([ amb_object ], k8s=False, filename=self.filename, rkey=resource_identifier)
def parse_object(self, objects, k8s=False, rkey: Optional[str]=None, filename: Optional[str]=None):
self.push_location(filename, 1)
# self.logger.debug("PARSE_OBJECT: incoming %d" % len(objects))
for obj in objects:
self.logger.debug("PARSE_OBJECT: checking %s" % obj)
if k8s:
self.handle_k8s(obj)
else:
# if not obj:
# self.logger.debug("%s: empty object from %s" % (self.location, serialization))
self.process_object(obj, rkey=rkey)
self.ocount += 1
self.pop_location()
def process_object(self, obj: dict, rkey: Optional[str]=None) -> None:
if not isinstance(obj, dict):
# Bug!!
if not obj:
self.aconf.post_error("%s is empty" % self.location)
else:
self.aconf.post_error("%s is not a dictionary? %s" %
(self.location, json.dumps(obj, indent=4, sort_keys=4)))
return
if not self.aconf.good_ambassador_id(obj):
# self.logger.debug("%s ignoring K8s Service with mismatched ambassador_id" % self.location)
return
if 'kind' not in obj:
# Bug!!
self.aconf.post_error("%s is missing 'kind'?? %s" %
(self.location, json.dumps(obj, indent=4, sort_keys=True)))
return
# self.logger.debug("%s PROCESS %s initial rkey %s" % (self.location, obj['kind'], rkey))
# Is this a pragma object?
if obj['kind'] == 'Pragma':
# Why did I think this was a good idea? [ :) ]
new_source = obj.get('source', None)
if new_source:
# We don't save the old self.filename here, so this change will last until
# the next input source (or the next Pragma).
self.filename = new_source
# Don't count Pragma objects, since the user generally doesn't write them.
self.ocount -= 1
return
if not rkey:
rkey = self.filename
rkey = "%s.%d" % (rkey, self.ocount)
# self.logger.debug("%s PROCESS %s updated rkey to %s" % (self.location, obj['kind'], rkey))
# Fine. Fine fine fine.
serialization = dump_yaml(obj, default_flow_style=False)
r = ACResource.from_dict(rkey, rkey, serialization, obj)
self.elements.append(r)
# self.logger.debug("%s PROCESS %s save %s: %s" % (self.location, obj['kind'], rkey, serialization))
def sorted(self, key=lambda x: x.rkey): # returns an iterator, probably
return sorted(self.elements, key=key)
def handle_k8s_endpoints(self, k8s_object: AnyDict) -> HandlerResult:
# Don't include Endpoints unless endpoint routing is enabled.
if not Config.enable_endpoints:
return None
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
resource_subsets = k8s_object.get('subsets', None)
skip = False
if not metadata:
self.logger.debug("ignoring K8s Endpoints with no metadata")
skip = True
if not resource_name:
self.logger.debug("ignoring K8s Endpoints with no name")
skip = True
if not resource_subsets:
self.logger.debug(f"ignoring K8s Endpoints {resource_name}.{resource_namespace} with no subsets")
skip = True
if skip:
return None
# We use this resource identifier as a key into self.k8s_services, and of course for logging .
resource_identifier = '{name}.{namespace}'.format(namespace=resource_namespace, name=resource_name)
# K8s Endpoints resources are _stupid_ in that they give you a vector of
# IP addresses and a vector of ports, and you have to assume that every
# IP address listens on every port, and that the semantics of each port
# are identical. The first is usually a good assumption. The second is not:
# people routinely list 80 and 443 for the same service, for example,
# despite the fact that one is HTTP and the other is HTTPS.
#
# By the time the ResourceFetcher is done, we want to be working with
# Ambassador Service resources, which have an array of address:port entries
# for endpoints. So we're going to extract the address and port numbers
# as arrays of tuples and stash them for later.
#
# In Kubernetes-speak, the Endpoints resource has some metadata and a set
# of "subsets" (though I've personally never seen more than one subset in
# one of these things).
for subset in resource_subsets:
# K8s subset addresses have some node info in with the IP address.
# May as well save that too.
addresses = []
for address in subset.get('addresses', []):
addr = {}
ip = address.get('ip', None)
if ip is not None:
addr['ip'] = ip
node = address.get('nodeName', None)
if node is not None:
addr['node'] = node
target_ref = address.get('targetRef', None)
if target_ref is not None:
target_kind = target_ref.get('kind', None)
if target_kind is not None:
addr['target_kind'] = target_kind
target_name = target_ref.get('name', None)
if target_name is not None:
addr['target_name'] = target_name
target_namespace = target_ref.get('namespace', None)
if target_namespace is not None:
addr['target_namespace'] = target_namespace
if len(addr) > 0:
addresses.append(addr)
# If we got no addresses, there's no point in messing with ports.
if len(addresses) == 0:
continue
ports = subset.get('ports', [])
# A service can reference a port either by name or by port number.
port_dict = {}
for port in ports:
port_name = port.get('name', None)
port_number = port.get('port', None)
port_proto = port.get('protocol', 'TCP').upper()
if port_proto != 'TCP':
continue
if port_number is None:
# WTFO.
continue
port_dict[str(port_number)] = port_number
if port_name:
port_dict[port_name] = port_number
if port_dict:
# We're not going to actually return this: we'll just stash it for our
# later resolution pass.
self.k8s_endpoints[resource_identifier] = {
'name': resource_name,
'namespace': resource_namespace,
'addresses': addresses,
'ports': port_dict
}
else:
self.logger.debug(f"ignoring K8s Endpoints {resource_identifier} with no routable ports")
return None
def handle_k8s_service(self, k8s_object: AnyDict) -> HandlerResult:
# The annoying bit about K8s Service resources is that not only do we have to look
# inside them for Ambassador resources, but we also have to save their info for
# later endpoint resolution too.
#
# Again, we're trusting that the input isn't overly bloated on that latter bit.
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
annotations = metadata.get('annotations', None) if metadata else None
if annotations:
annotations = annotations.get('getambassador.io/config', None)
skip = False
if not metadata:
self.logger.debug("ignoring K8s Service with no metadata")
skip = True
if not skip and not resource_name:
self.logger.debug("ignoring K8s Service with no name")
skip = True
if not skip and (Config.single_namespace and (resource_namespace != Config.ambassador_namespace)):
# This should never happen in actual usage, since we shouldn't be given things
# in the wrong namespace. However, in development, this can happen a lot.
self.logger.debug(f"ignoring K8s Service {resource_name}.{resource_namespace} in wrong namespace")
skip = True
if skip:
return None
# We use this resource identifier as a key into self.k8s_services, and of course for logging .
resource_identifier = f'{resource_name}.{resource_namespace}'
# Not skipping. First, if we have some actual ports, stash this in self.k8s_services
# for later resolution.
spec = k8s_object.get('spec', None)
ports = spec.get('ports', None) if spec else None
if spec and ports:
self.k8s_services[resource_identifier] = {
'name': resource_name,
'namespace': resource_namespace,
'ports': ports
}
else:
self.logger.debug(f"not saving K8s Service {resource_name}.{resource_namespace} with no ports")
objects: List[Any] = []
if annotations:
if (self.filename is not None) and (not self.filename.endswith(":annotation")):
self.filename += ":annotation"
try:
objects = parse_yaml(annotations)
except yaml.error.YAMLError as e:
self.logger.debug("could not parse YAML: %s" % e)
return resource_identifier, objects
# Handler for K8s Secret resources.
def handle_k8s_secret(self, k8s_object: AnyDict) -> HandlerResult:
# XXX Another one where we shouldn't be saving everything.
secret_type = k8s_object.get('type', None)
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
data = k8s_object.get('data', None)
skip = False
if (secret_type != 'kubernetes.io/tls') and (secret_type != 'Opaque'):
self.logger.debug("ignoring K8s Secret with unknown type %s" % secret_type)
skip = True
if not data:
self.logger.debug("ignoring K8s Secret with no data")
skip = True
if not metadata:
self.logger.debug("ignoring K8s Secret with no metadata")
skip = True
if not resource_name:
self.logger.debug("ignoring K8s Secret with no name")
skip = True
if not skip and (Config.single_namespace and (resource_namespace != Config.ambassador_namespace)):
# This should never happen in actual usage, since we shouldn't be given things
# in the wrong namespace. However, in development, this can happen a lot.
self.logger.debug("ignoring K8s Secret in wrong namespace")
skip = True
if skip:
return None
# This resource identifier is useful for log output since filenames can be duplicated (multiple subdirectories)
resource_identifier = f'{resource_name}.{resource_namespace}'
tls_crt = data.get('tls.crt', None)
tls_key = data.get('tls.key', None)
if not tls_crt and not tls_key:
# Uh. WTFO?
self.logger.debug(f'ignoring K8s Secret {resource_identifier} with no keys')
return None
# No need to muck about with resolution later, just immediately turn this
# into an Ambassador Secret resource.
secret_info = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Secret',
'name': resource_name,
'namespace': resource_namespace
}
if tls_crt:
secret_info['tls_crt'] = tls_crt
if tls_key:
secret_info['tls_key'] = tls_key
return resource_identifier, [ secret_info ]
# Handler for Consul services
def handle_consul_service(self,
consul_rkey: str, consul_object: AnyDict) -> HandlerResult:
# resource_identifier = f'consul-{consul_rkey}'
endpoints = consul_object.get('Endpoints', [])
name = consul_object.get('Service', consul_rkey)
if len(endpoints) < 1:
# Bzzt.
self.logger.debug(f"ignoring Consul service {name} with no Endpoints")
return None
# We can turn this directly into an Ambassador Service resource, since Consul keeps
# services and endpoints together (as it should!!).
#
# Note that we currently trust the association ID to contain the datacenter name.
# That's a function of the watch_hook putting it there.
svc = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Service',
'name': name,
'datacenter': consul_object.get('Id') or 'dc1',
'endpoints': {}
}
for ep in endpoints:
ep_addr = ep.get('Address')
ep_port = ep.get('Port')
if not ep_addr or not ep_port:
self.logger.debug(f"ignoring Consul service {name} endpoint {ep['ID']} missing address info")
continue
# Consul services don't have the weird indirections that Kube services do, so just
# lump all the endpoints together under the same source port of '*'.
svc_eps = svc['endpoints'].setdefault('*', [])
svc_eps.append({
'ip': ep_addr,
'port': ep_port,
'target_kind': 'Consul'
})
# Once again: don't return this. Instead, save it in self.services.
self.services[f"consul-{name}-{svc['datacenter']}"] = svc
return None
def finalize(self) -> None:
# The point here is to sort out self.k8s_services and self.k8s_endpoints and
# turn them into proper Ambassador Service resources. This is a bit annoying,
# because of the annoyances of Kubernetes, but we'll give it a go.
#
# Here are the rules:
#
# 1. By the time we get here, we have a _complete_ set of Ambassador resources that
# have passed muster by virtue of having the correct namespace, the correct
# ambassador_id, etc. (They may have duplicate names at this point, admittedly.)
# Any service not mentioned by name is out. Since the Ambassador resources in
# self.elements are in fact AResources, we can farm this out to code for each
# resource.
#
# 2. The check is, by design, permissive. If in doubt, write the check to leave
# the resource in.
#
# 3. For any service that stays in, we vet its listed ports against self.k8s_endpoints.
# Anything with no matching ports is _not_ dropped; it is assumed to use service
# routing rather than endpoint routing.
od = {
'elements': [ x.as_dict() for x in self.elements ],
'k8s_endpoints': self.k8s_endpoints,
'k8s_services': self.k8s_services,
'services': self.services
}
# self.logger.debug("==== FINALIZE START\n%s" % json.dumps(od, sort_keys=True, indent=4))
for key, k8s_svc in self.k8s_services.items():
# See if we can find endpoints for this service.
k8s_ep = self.k8s_endpoints.get(key, None)
k8s_ep_ports = k8s_ep.get('ports', None) if k8s_ep else None
k8s_name = k8s_svc['name']
k8s_namespace = k8s_svc['namespace']
# OK, Kube is weird. The way all this works goes like this:
#
# 1. When you create a Kube Service, Kube will allocate a clusterIP
# for it and update DNS to resolve the name of the service to
# that clusterIP.
# 2. Kube will look over the pods matched by the Service's selectors
# and stick those pods' IP addresses into Endpoints for the Service.
# 3. The Service will have ports listed. These service.port entries can
# contain:
# port -- a port number you can talk to at the clusterIP
# name -- a name for this port
# targetPort -- a port number you can talk to at the _endpoint_ IP
# We'll call the 'port' entry here the "service-port".
# 4. If you talk to clusterIP:service-port, you will get magically
# proxied by the Kube CNI to a target port at one of the endpoint IPs.
#
# The $64K question is: how does Kube decide which target port to use?
#
# First, if there's only one endpoint port, that's the one that gets used.
#
# If there's more than one, if the Service's port entry has a targetPort
# number, it uses that. Otherwise it tries to find an endpoint port with
# the same name as the service port. Otherwise, I dunno, it punts and uses
# the service-port.
#
# So that's how Ambassador is going to do it, for each Service port entry.
#
# If we have no endpoints at all, Ambassador will end up routing using
# just the service name and port per the Mapping's service spec.
target_ports = {}
target_addrs = []
svc_endpoints = {}
if not k8s_ep or not k8s_ep_ports:
# No endpoints at all, so we're done with this service.
self.logger.debug(f'{key}: no endpoints at all')
else:
idx = -1
for port in k8s_svc['ports']:
idx += 1
k8s_target: Optional[int] = None
src_port = port.get('port', None)
if not src_port:
# WTFO. This is impossible.
self.logger.error(f"Kubernetes service {key} has no port number at index {idx}?")
continue
if len(k8s_ep_ports) == 1:
# Just one endpoint port. Done.
k8s_target = list(k8s_ep_ports.values())[0]
target_ports[src_port] = k8s_target
self.logger.debug(f'{key} port {src_port}: single endpoint port {k8s_target}')
continue
# Hmmm, we need to try to actually map whatever ports are listed for
# this service. Oh well.
found_key = False
fallback: Optional[int] = None
for attr in [ 'targetPort', 'name', 'port' ]:
port_key = port.get(attr) # This could be a name or a number, in general.
if port_key:
found_key = True
if not fallback and (port_key != 'name') and str(port_key).isdigit():
# fallback can only be digits.
fallback = port_key
# Do we have a destination port for this?
k8s_target = k8s_ep_ports.get(str(port_key), None)
if k8s_target:
self.logger.debug(f'{key} port {src_port} #{idx}: {attr} {port_key} -> {k8s_target}')
break
else:
self.logger.debug(f'{key} port {src_port} #{idx}: {attr} {port_key} -> miss')
if not found_key:
# WTFO. This is impossible.
self.logger.error(f"Kubernetes service {key} port {src_port} has an empty port spec at index {idx}?")
continue
if not k8s_target:
# This is most likely because we don't have endpoint info at all, so we'll do service
# routing.
#
# It's actually impossible for fallback to be unset, but WTF.
k8s_target = fallback or src_port
self.logger.debug(f'{key} port {src_port} #{idx}: falling back to {k8s_target}')
target_ports[src_port] = k8s_target
if not target_ports:
# WTFO. This is impossible. I guess we'll fall back to service routing.
self.logger.error(f"Kubernetes service {key} has no routable ports at all?")
# OK. Once _that's_ done we have to take the endpoint addresses into
# account, or just use the service name if we don't have that.
k8s_ep_addrs = k8s_ep.get('addresses', None)
if k8s_ep_addrs:
for addr in k8s_ep_addrs:
ip = addr.get('ip', None)
if ip:
target_addrs.append(ip)
# OK! If we have no target addresses, just use service routing.
if not target_addrs:
self.logger.debug(f'{key} falling back to service routing')
target_addrs = [ key ]
for src_port, target_port in target_ports.items():
svc_endpoints[src_port] = [ {
'ip': target_addr,
'port': target_port
} for target_addr in target_addrs ]
# Nope. Set this up for service routing.
self.services[f'k8s-{k8s_name}-{k8s_namespace}'] = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Service',
'name': k8s_name,
'namespace': k8s_namespace,
'endpoints': svc_endpoints
}
# OK. After all that, go turn all of the things in self.services into Ambassador
# Service resources.
for key, svc in self.services.items():
serialization = dump_yaml(svc, default_flow_style=False)
r = ACResource.from_dict(key, key, serialization, svc)
self.elements.append(r)
od = {
'elements': [ x.as_dict() for x in self.elements ],
'k8s_endpoints': self.k8s_endpoints,
'k8s_services': self.k8s_services,
'services': self.services
}
# self.logger.debug("==== FINALIZE END\n%s" % json.dumps(od, sort_keys=True, indent=4))
| 41.332924 | 286 | 0.575895 | from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING
import json
import logging
import os
import yaml
from .config import Config
from .acresource import ACResource
from ..utils import parse_yaml, dump_yaml
AnyDict = Dict[str, Any]
HandlerResult = Optional[Tuple[str, List[AnyDict]]]
# resources, we'll get a full set. The whole 'secret loader' thing needs to have the
# recursive, I don't care) directory full of Ambassador YAML, including TLSSecrets
# send over K8s Service records, and anything annotated in there will end up in
# elements. This may include TLSSecrets or Endpoints. Any TLSSecret mentioned that
# isn't already in elements will need to be fetched.
# it. The ambassador_id is completely orthogonal to the namespace. No element with
# the wrong ambassador_id will end up in elements. It would be nice if they were
# never sent by kubewatch, but, well, y'know.
class ResourceFetcher:
def __init__(self, logger: logging.Logger, aconf: 'Config') -> None:
self.aconf = aconf
self.logger = logger
self.elements: List[ACResource] = []
self.filename: Optional[str] = None
self.ocount: int = 1
self.saved: List[Tuple[Optional[str], int]] = []
self.k8s_endpoints: Dict[str, AnyDict] = {}
self.k8s_services: Dict[str, AnyDict] = {}
self.services: Dict[str, AnyDict] = {}
@property
def location(self):
return "%s.%d" % (self.filename or "anonymous YAML", self.ocount)
def push_location(self, filename: Optional[str], ocount: int) -> None:
self.saved.append((self.filename, self.ocount))
self.filename = filename
self.ocount = ocount
def pop_location(self) -> None:
self.filename, self.ocount = self.saved.pop()
def load_from_filesystem(self, config_dir_path, recurse: bool=False, k8s: bool=False):
inputs: List[Tuple[str, str]] = []
if os.path.isdir(config_dir_path):
dirs = [ config_dir_path ]
while dirs:
dirpath = dirs.pop(0)
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
if recurse and os.path.isdir(filepath):
dirs.append(filepath)
continue
if not os.path.isfile(filepath):
continue
if not filename.lower().endswith('.yaml'):
continue
inputs.append((filepath, filename))
else:
inputs.append((config_dir_path, os.path.basename(config_dir_path)))
for filepath, filename in inputs:
self.logger.info("reading %s (%s)" % (filename, filepath))
try:
serialization = open(filepath, "r").read()
self.parse_yaml(serialization, k8s=k8s, filename=filename)
except IOError as e:
self.aconf.post_error("could not read YAML from %s: %s" % (filepath, e))
self.finalize()
def parse_yaml(self, serialization: str, k8s=False, rkey: Optional[str]=None,
filename: Optional[str]=None) -> None:
try:
objects = parse_yaml(serialization)
self.parse_object(objects=objects, k8s=k8s, rkey=rkey, filename=filename)
except yaml.error.YAMLError as e:
self.aconf.post_error("%s: could not parse YAML: %s" % (self.location, e))
self.finalize()
def parse_json(self, serialization: str, k8s=False, rkey: Optional[str]=None,
filename: Optional[str]=None) -> None:
try:
objects = json.loads(serialization)
self.parse_object(objects=objects, k8s=k8s, rkey=rkey, filename=filename)
except json.decoder.JSONDecodeError as e:
self.aconf.post_error("%s: could not parse YAML: %s" % (self.location, e))
self.finalize()
def parse_watt(self, serialization: str) -> None:
basedir = os.environ.get('AMBASSADOR_CONFIG_BASE_DIR', '/ambassador')
if os.path.isfile(os.path.join(basedir, '.ambassador_ignore_crds')):
self.aconf.post_error("Ambassador could not find core CRD definitions. Please visit https://www.getambassador.io/reference/core/crds/ for more information. You can continue using Ambassador via Kubernetes annotations, any configuration via CRDs will be ignored...")
if os.path.isfile(os.path.join(basedir, '.ambassador_ignore_crds_2')):
self.aconf.post_error("Ambassador could not find Resolver type CRD definitions. Please visit https://www.getambassador.io/reference/core/crds/ for more information. You can continue using Ambassador via Kubernetes annotations, any configuration via CRDs will be ignored...")
try:
watt_dict = json.loads(serialization)
watt_k8s = watt_dict.get('Kubernetes', {})
for key in [ 'service', 'endpoints', 'secret' ]:
for obj in watt_k8s.get(key) or []:
self.handle_k8s(obj)
for key in [ 'AuthService', 'ConsulResolver',
'KubernetesEndpointResolver', 'KubernetesServiceResolver',
'Mapping', 'Module', 'RateLimitService',
'TCPMapping', 'TLSContext', 'TracingService']:
for obj in watt_k8s.get(key) or []:
self.handle_k8s_crd(obj)
watt_consul = watt_dict.get('Consul', {})
consul_endpoints = watt_consul.get('Endpoints', {})
for consul_rkey, consul_object in consul_endpoints.items():
result = self.handle_consul_service(consul_rkey, consul_object)
if result:
rkey, parsed_objects = result
self.parse_object(parsed_objects, k8s=False,
filename=self.filename, rkey=rkey)
except json.decoder.JSONDecodeError as e:
self.aconf.post_error("%s: could not parse WATT: %s" % (self.location, e))
self.finalize()
def handle_k8s(self, obj: dict) -> None:
kind = obj.get('kind')
if not kind:
return
handler_name = f'handle_k8s_{kind.lower()}'
handler = getattr(self, handler_name, None)
if not handler:
return
result = handler(obj)
if result:
rkey, parsed_objects = result
self.parse_object(parsed_objects, k8s=False,
filename=self.filename, rkey=rkey)
def handle_k8s_crd(self, obj: dict) -> None:
kind = obj.get('kind')
if not kind:
self.logger.debug("%s: ignoring K8s CRD, no kind" % self.location)
return
apiVersion = obj.get('apiVersion')
metadata = obj.get('metadata') or {}
name = metadata.get('name')
namespace = metadata.get('namespace') or 'default'
spec = obj.get('spec') or {}
if not name:
self.logger.debug(f'{self.location}: ignoring K8s {kind} CRD, no name')
return
if not apiVersion:
self.logger.debug(f'{self.location}: ignoring K8s {kind} CRD {name}: no apiVersion')
return
resource_identifier = f'{name}.{namespace}'
amb_object = dict(spec)
amb_object['apiVersion'] = apiVersion
amb_object['name'] = name
amb_object['kind'] = kind
self.parse_object([ amb_object ], k8s=False, filename=self.filename, rkey=resource_identifier)
def parse_object(self, objects, k8s=False, rkey: Optional[str]=None, filename: Optional[str]=None):
self.push_location(filename, 1)
for obj in objects:
self.logger.debug("PARSE_OBJECT: checking %s" % obj)
if k8s:
self.handle_k8s(obj)
else:
self.process_object(obj, rkey=rkey)
self.ocount += 1
self.pop_location()
def process_object(self, obj: dict, rkey: Optional[str]=None) -> None:
if not isinstance(obj, dict):
if not obj:
self.aconf.post_error("%s is empty" % self.location)
else:
self.aconf.post_error("%s is not a dictionary? %s" %
(self.location, json.dumps(obj, indent=4, sort_keys=4)))
return
if not self.aconf.good_ambassador_id(obj):
return
if 'kind' not in obj:
self.aconf.post_error("%s is missing 'kind'?? %s" %
(self.location, json.dumps(obj, indent=4, sort_keys=True)))
return
if obj['kind'] == 'Pragma':
new_source = obj.get('source', None)
if new_source:
# the next input source (or the next Pragma).
self.filename = new_source
# Don't count Pragma objects, since the user generally doesn't write them.
self.ocount -= 1
return
if not rkey:
rkey = self.filename
rkey = "%s.%d" % (rkey, self.ocount)
# self.logger.debug("%s PROCESS %s updated rkey to %s" % (self.location, obj['kind'], rkey))
# Fine. Fine fine fine.
serialization = dump_yaml(obj, default_flow_style=False)
r = ACResource.from_dict(rkey, rkey, serialization, obj)
self.elements.append(r)
# self.logger.debug("%s PROCESS %s save %s: %s" % (self.location, obj['kind'], rkey, serialization))
def sorted(self, key=lambda x: x.rkey): # returns an iterator, probably
return sorted(self.elements, key=key)
def handle_k8s_endpoints(self, k8s_object: AnyDict) -> HandlerResult:
# Don't include Endpoints unless endpoint routing is enabled.
if not Config.enable_endpoints:
return None
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
resource_subsets = k8s_object.get('subsets', None)
skip = False
if not metadata:
self.logger.debug("ignoring K8s Endpoints with no metadata")
skip = True
if not resource_name:
self.logger.debug("ignoring K8s Endpoints with no name")
skip = True
if not resource_subsets:
self.logger.debug(f"ignoring K8s Endpoints {resource_name}.{resource_namespace} with no subsets")
skip = True
if skip:
return None
resource_identifier = '{name}.{namespace}'.format(namespace=resource_namespace, name=resource_name)
# as arrays of tuples and stash them for later.
#
# In Kubernetes-speak, the Endpoints resource has some metadata and a set
# of "subsets" (though I've personally never seen more than one subset in
for subset in resource_subsets:
addresses = []
for address in subset.get('addresses', []):
addr = {}
ip = address.get('ip', None)
if ip is not None:
addr['ip'] = ip
node = address.get('nodeName', None)
if node is not None:
addr['node'] = node
target_ref = address.get('targetRef', None)
if target_ref is not None:
target_kind = target_ref.get('kind', None)
if target_kind is not None:
addr['target_kind'] = target_kind
target_name = target_ref.get('name', None)
if target_name is not None:
addr['target_name'] = target_name
target_namespace = target_ref.get('namespace', None)
if target_namespace is not None:
addr['target_namespace'] = target_namespace
if len(addr) > 0:
addresses.append(addr)
if len(addresses) == 0:
continue
ports = subset.get('ports', [])
# A service can reference a port either by name or by port number.
port_dict = {}
for port in ports:
port_name = port.get('name', None)
port_number = port.get('port', None)
port_proto = port.get('protocol', 'TCP').upper()
if port_proto != 'TCP':
continue
if port_number is None:
# WTFO.
continue
port_dict[str(port_number)] = port_number
if port_name:
port_dict[port_name] = port_number
if port_dict:
# We're not going to actually return this: we'll just stash it for our
# later resolution pass.
self.k8s_endpoints[resource_identifier] = {
'name': resource_name,
'namespace': resource_namespace,
'addresses': addresses,
'ports': port_dict
}
else:
self.logger.debug(f"ignoring K8s Endpoints {resource_identifier} with no routable ports")
return None
def handle_k8s_service(self, k8s_object: AnyDict) -> HandlerResult:
# The annoying bit about K8s Service resources is that not only do we have to look
# inside them for Ambassador resources, but we also have to save their info for
# later endpoint resolution too.
#
# Again, we're trusting that the input isn't overly bloated on that latter bit.
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
annotations = metadata.get('annotations', None) if metadata else None
if annotations:
annotations = annotations.get('getambassador.io/config', None)
skip = False
if not metadata:
self.logger.debug("ignoring K8s Service with no metadata")
skip = True
if not skip and not resource_name:
self.logger.debug("ignoring K8s Service with no name")
skip = True
if not skip and (Config.single_namespace and (resource_namespace != Config.ambassador_namespace)):
# This should never happen in actual usage, since we shouldn't be given things
self.logger.debug(f"ignoring K8s Service {resource_name}.{resource_namespace} in wrong namespace")
skip = True
if skip:
return None
resource_identifier = f'{resource_name}.{resource_namespace}'
spec = k8s_object.get('spec', None)
ports = spec.get('ports', None) if spec else None
if spec and ports:
self.k8s_services[resource_identifier] = {
'name': resource_name,
'namespace': resource_namespace,
'ports': ports
}
else:
self.logger.debug(f"not saving K8s Service {resource_name}.{resource_namespace} with no ports")
objects: List[Any] = []
if annotations:
if (self.filename is not None) and (not self.filename.endswith(":annotation")):
self.filename += ":annotation"
try:
objects = parse_yaml(annotations)
except yaml.error.YAMLError as e:
self.logger.debug("could not parse YAML: %s" % e)
return resource_identifier, objects
def handle_k8s_secret(self, k8s_object: AnyDict) -> HandlerResult:
secret_type = k8s_object.get('type', None)
metadata = k8s_object.get('metadata', None)
resource_name = metadata.get('name') if metadata else None
resource_namespace = metadata.get('namespace', 'default') if metadata else None
data = k8s_object.get('data', None)
skip = False
if (secret_type != 'kubernetes.io/tls') and (secret_type != 'Opaque'):
self.logger.debug("ignoring K8s Secret with unknown type %s" % secret_type)
skip = True
if not data:
self.logger.debug("ignoring K8s Secret with no data")
skip = True
if not metadata:
self.logger.debug("ignoring K8s Secret with no metadata")
skip = True
if not resource_name:
self.logger.debug("ignoring K8s Secret with no name")
skip = True
if not skip and (Config.single_namespace and (resource_namespace != Config.ambassador_namespace)):
# This should never happen in actual usage, since we shouldn't be given things
self.logger.debug("ignoring K8s Secret in wrong namespace")
skip = True
if skip:
return None
resource_identifier = f'{resource_name}.{resource_namespace}'
tls_crt = data.get('tls.crt', None)
tls_key = data.get('tls.key', None)
if not tls_crt and not tls_key:
self.logger.debug(f'ignoring K8s Secret {resource_identifier} with no keys')
return None
secret_info = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Secret',
'name': resource_name,
'namespace': resource_namespace
}
if tls_crt:
secret_info['tls_crt'] = tls_crt
if tls_key:
secret_info['tls_key'] = tls_key
return resource_identifier, [ secret_info ]
def handle_consul_service(self,
consul_rkey: str, consul_object: AnyDict) -> HandlerResult:
endpoints = consul_object.get('Endpoints', [])
name = consul_object.get('Service', consul_rkey)
if len(endpoints) < 1:
self.logger.debug(f"ignoring Consul service {name} with no Endpoints")
return None
svc = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Service',
'name': name,
'datacenter': consul_object.get('Id') or 'dc1',
'endpoints': {}
}
for ep in endpoints:
ep_addr = ep.get('Address')
ep_port = ep.get('Port')
if not ep_addr or not ep_port:
self.logger.debug(f"ignoring Consul service {name} endpoint {ep['ID']} missing address info")
continue
# Consul services don't have the weird indirections that Kube services do, so just
svc_eps = svc['endpoints'].setdefault('*', [])
svc_eps.append({
'ip': ep_addr,
'port': ep_port,
'target_kind': 'Consul'
})
self.services[f"consul-{name}-{svc['datacenter']}"] = svc
return None
def finalize(self) -> None:
# The point here is to sort out self.k8s_services and self.k8s_endpoints and
# turn them into proper Ambassador Service resources. This is a bit annoying,
# because of the annoyances of Kubernetes, but we'll give it a go.
od = {
'elements': [ x.as_dict() for x in self.elements ],
'k8s_endpoints': self.k8s_endpoints,
'k8s_services': self.k8s_services,
'services': self.services
}
for key, k8s_svc in self.k8s_services.items():
k8s_ep = self.k8s_endpoints.get(key, None)
k8s_ep_ports = k8s_ep.get('ports', None) if k8s_ep else None
k8s_name = k8s_svc['name']
k8s_namespace = k8s_svc['namespace']
# and stick those pods' IP addresses into Endpoints for the Service.
# 4. If you talk to clusterIP:service-port, you will get magically
# proxied by the Kube CNI to a target port at one of the endpoint IPs.
#
# The $64K question is: how does Kube decide which target port to use?
#
# First, if there's only one endpoint port, that's the one that gets used.
#
# If there's more than one, if the Service's port entry has a targetPort
# number, it uses that. Otherwise it tries to find an endpoint port with
# the same name as the service port. Otherwise, I dunno, it punts and uses
# the service-port.
#
# So that's how Ambassador is going to do it, for each Service port entry.
target_ports = {}
target_addrs = []
svc_endpoints = {}
if not k8s_ep or not k8s_ep_ports:
# No endpoints at all, so we're done with this service.
self.logger.debug(f'{key}: no endpoints at all')
else:
idx = -1
for port in k8s_svc['ports']:
idx += 1
k8s_target: Optional[int] = None
src_port = port.get('port', None)
if not src_port:
self.logger.error(f"Kubernetes service {key} has no port number at index {idx}?")
continue
if len(k8s_ep_ports) == 1:
k8s_target = list(k8s_ep_ports.values())[0]
target_ports[src_port] = k8s_target
self.logger.debug(f'{key} port {src_port}: single endpoint port {k8s_target}')
continue
found_key = False
fallback: Optional[int] = None
for attr in [ 'targetPort', 'name', 'port' ]:
port_key = port.get(attr)
if port_key:
found_key = True
if not fallback and (port_key != 'name') and str(port_key).isdigit():
fallback = port_key
k8s_target = k8s_ep_ports.get(str(port_key), None)
if k8s_target:
self.logger.debug(f'{key} port {src_port} #{idx}: {attr} {port_key} -> {k8s_target}')
break
else:
self.logger.debug(f'{key} port {src_port} #{idx}: {attr} {port_key} -> miss')
if not found_key:
self.logger.error(f"Kubernetes service {key} port {src_port} has an empty port spec at index {idx}?")
continue
if not k8s_target:
k8s_target = fallback or src_port
self.logger.debug(f'{key} port {src_port}
target_ports[src_port] = k8s_target
if not target_ports:
# WTFO. This is impossible. I guess we'll fall back to service routing.
self.logger.error(f"Kubernetes service {key} has no routable ports at all?")
# account, or just use the service name if we don't have that.
k8s_ep_addrs = k8s_ep.get('addresses', None)
if k8s_ep_addrs:
for addr in k8s_ep_addrs:
ip = addr.get('ip', None)
if ip:
target_addrs.append(ip)
if not target_addrs:
self.logger.debug(f'{key} falling back to service routing')
target_addrs = [ key ]
for src_port, target_port in target_ports.items():
svc_endpoints[src_port] = [ {
'ip': target_addr,
'port': target_port
} for target_addr in target_addrs ]
self.services[f'k8s-{k8s_name}-{k8s_namespace}'] = {
'apiVersion': 'ambassador/v1',
'ambassador_id': Config.ambassador_id,
'kind': 'Service',
'name': k8s_name,
'namespace': k8s_namespace,
'endpoints': svc_endpoints
}
for key, svc in self.services.items():
serialization = dump_yaml(svc, default_flow_style=False)
r = ACResource.from_dict(key, key, serialization, svc)
self.elements.append(r)
od = {
'elements': [ x.as_dict() for x in self.elements ],
'k8s_endpoints': self.k8s_endpoints,
'k8s_services': self.k8s_services,
'services': self.services
}
| true | true |
f726c946b28663f6039c3f5e99cf5aef3b6ee900 | 302 | py | Python | pyexcel/sheets/__init__.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 5668b5785296b314ea1321057420bcd077dba9ea | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 1 | 2022-01-25T22:52:58.000Z | 2022-01-25T22:52:58.000Z | pyexcel/sheets/__init__.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | pyexcel/sheets/__init__.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | """
pyexcel.sheets
~~~~~~~~~~~~~~~~~~~
Core functionality of pyexcel, data model
:copyright: (c) 2014-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
"""
# flake8: noqa
from .sheet import Sheet
from .matrix import Matrix, transpose, Row, Column
| 23.230769 | 59 | 0.652318 |
from .sheet import Sheet
from .matrix import Matrix, transpose, Row, Column
| true | true |
f726caa23a352acc6478111d0682e07e79f4858c | 860 | py | Python | route/main_file.py | LiteHell/openNAMU | 72bd1ec1d4b63bd74876bf1c4bb3c4002ec9fdd1 | [
"BSD-3-Clause"
] | null | null | null | route/main_file.py | LiteHell/openNAMU | 72bd1ec1d4b63bd74876bf1c4bb3c4002ec9fdd1 | [
"BSD-3-Clause"
] | null | null | null | route/main_file.py | LiteHell/openNAMU | 72bd1ec1d4b63bd74876bf1c4bb3c4002ec9fdd1 | [
"BSD-3-Clause"
] | null | null | null | from .tool.func import *
from . import main_error_404
def main_file_2(conn, data):
curs = conn.cursor()
if data == 'easter_egg.html':
return easy_minify(flask.render_template(skin_check(),
imp = ['easter_egg.html', wiki_set(), custom(), other2([0, 0])],
data = open('./views/main_css/file/easter_egg.html', 'r').read(),
menu = 0
))
elif re.search('\.txt$', data) or data == 'sitemap.xml':
if data == 'robots.txt' and not os.path.exists('robots.txt'):
return flask.Response('User-agent: *\nDisallow: /\nAllow: /$\nAllow: /w/', mimetype='text/plain')
elif os.path.exists(data):
return flask.send_from_directory('./', data)
else:
return main_error_404.main_error_404_2(conn)
else:
return main_error_404.main_error_404_2(conn) | 40.952381 | 109 | 0.603488 | from .tool.func import *
from . import main_error_404
def main_file_2(conn, data):
curs = conn.cursor()
if data == 'easter_egg.html':
return easy_minify(flask.render_template(skin_check(),
imp = ['easter_egg.html', wiki_set(), custom(), other2([0, 0])],
data = open('./views/main_css/file/easter_egg.html', 'r').read(),
menu = 0
))
elif re.search('\.txt$', data) or data == 'sitemap.xml':
if data == 'robots.txt' and not os.path.exists('robots.txt'):
return flask.Response('User-agent: *\nDisallow: /\nAllow: /$\nAllow: /w/', mimetype='text/plain')
elif os.path.exists(data):
return flask.send_from_directory('./', data)
else:
return main_error_404.main_error_404_2(conn)
else:
return main_error_404.main_error_404_2(conn) | true | true |
f726cb978618b466b6e7a32b01c4590b62b5c7a6 | 3,077 | py | Python | commons/__init__.py | oeg-upm/ttla | ab1cc5a2777b3d4fb905f4452379f469153c904b | [
"Apache-2.0"
] | null | null | null | commons/__init__.py | oeg-upm/ttla | ab1cc5a2777b3d4fb905f4452379f469153c904b | [
"Apache-2.0"
] | 5 | 2019-04-03T12:58:29.000Z | 2021-06-02T00:18:34.000Z | commons/__init__.py | oeg-upm/bob | ab1cc5a2777b3d4fb905f4452379f469153c904b | [
"Apache-2.0"
] | null | null | null | import os
import pandas as pd
from easysparql import *
ENDPOINT = "https://dbpedia.org/sparql"
MIN_NUM_OF_ENT_PER_PROP = 30 # the minimum number of entities per property (get_properties)
QUERY_LIMIT = "" # At the moment, we do not put any limit on the number of results
MIN_NUM_NUMS = 30 # The minimum number of values that will be annotated, this is to ignore small size
proj_path = (os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
data_dir = os.path.join(proj_path, 'data')
meta_dir = os.path.join(proj_path, 'meta')
models_dir = os.path.join(proj_path, 'local_models')
log_dir = os.path.join(proj_path, 'local_logs')
# kinds
NOMINAL = "nominal"
ORDINAL = "ordinal"
RATIO_INTERVAL = "ratio-interval"
# sub kinds
CATEGORICAL = "categorical"
SEQUENTIAL = "sequential"
HIERARCHICAL = "hierarchical"
RANDOM = "random"
COUNTS = "count"
OTHER = "other"
YEAR = "year"
# I am not sure of the below is useful
# kinds and subkinds
KINDS = {
ORDINAL: [],
NOMINAL: [CATEGORICAL, SEQUENTIAL, HIERARCHICAL, RANDOM],
RATIO_INTERVAL: [COUNTS, OTHER],
YEAR: []
}
def get_column_from_meta(fname, column_id):
"""
:param fname:
:param column_id:
:return:
"""
fdir = os.path.join(data_dir, 'T2Dv2', fname+".csv")
df = pd.read_csv(fdir)
col_name = df.columns.values[column_id]
return list(df[col_name])
def t2dv2_columns_of_kind(num_kind, sub_kind=None):
"""
:param num_kind: nominal, ordinal, ratio-interval
:return: a dataframe of the specified kind
"""
meta_file_dir = os.path.join(meta_dir, 'T2Dv2_typology.csv')
df = pd.read_csv(meta_file_dir)
if sub_kind is None:
dfkind = df[df.kind == num_kind]
else:
dfkind = df[df.kind == num_kind and df.sub_kind == sub_kind]
print(dfkind)
return dfkind
def get_numerics_from_list(nums_str_list):
"""
:param nums_str_list: list of string or numbers or a mix
:return: list of numbers or None if less than 50% are numbers
"""
nums = []
for c in nums_str_list:
n = get_num(c)
if n is not None:
nums.append(n)
if len(nums) < len(nums_str_list)/2:
return None
return nums
def get_num(num_or_str):
"""
:param num_or_str:
:return: number or None if it is not a number
"""
if pd.isna(num_or_str):
return None
elif isinstance(num_or_str, (int, float)):
return num_or_str
elif isinstance(num_or_str, basestring):
if '.' in num_or_str or ',' in num_or_str or num_or_str.isdigit():
try:
return float(num_or_str.replace(',', ''))
except Exception as e:
return None
return None
def class_uri_to_fname(class_uri):
"""
:param class_uri:
:return:
"""
if class_uri[:7] == "http://":
class_dname = class_uri[7:]
elif class_uri[:8] == "https://":
class_dname = class_uri[8:]
class_fname = class_dname.replace('/', '__').replace(',', '').replace('#', '_')#.replace('-', '_')
return class_fname
| 26.756522 | 102 | 0.646409 | import os
import pandas as pd
from easysparql import *
ENDPOINT = "https://dbpedia.org/sparql"
MIN_NUM_OF_ENT_PER_PROP = 30
QUERY_LIMIT = ""
MIN_NUM_NUMS = 30
proj_path = (os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
data_dir = os.path.join(proj_path, 'data')
meta_dir = os.path.join(proj_path, 'meta')
models_dir = os.path.join(proj_path, 'local_models')
log_dir = os.path.join(proj_path, 'local_logs')
NOMINAL = "nominal"
ORDINAL = "ordinal"
RATIO_INTERVAL = "ratio-interval"
CATEGORICAL = "categorical"
SEQUENTIAL = "sequential"
HIERARCHICAL = "hierarchical"
RANDOM = "random"
COUNTS = "count"
OTHER = "other"
YEAR = "year"
KINDS = {
ORDINAL: [],
NOMINAL: [CATEGORICAL, SEQUENTIAL, HIERARCHICAL, RANDOM],
RATIO_INTERVAL: [COUNTS, OTHER],
YEAR: []
}
def get_column_from_meta(fname, column_id):
fdir = os.path.join(data_dir, 'T2Dv2', fname+".csv")
df = pd.read_csv(fdir)
col_name = df.columns.values[column_id]
return list(df[col_name])
def t2dv2_columns_of_kind(num_kind, sub_kind=None):
meta_file_dir = os.path.join(meta_dir, 'T2Dv2_typology.csv')
df = pd.read_csv(meta_file_dir)
if sub_kind is None:
dfkind = df[df.kind == num_kind]
else:
dfkind = df[df.kind == num_kind and df.sub_kind == sub_kind]
print(dfkind)
return dfkind
def get_numerics_from_list(nums_str_list):
nums = []
for c in nums_str_list:
n = get_num(c)
if n is not None:
nums.append(n)
if len(nums) < len(nums_str_list)/2:
return None
return nums
def get_num(num_or_str):
if pd.isna(num_or_str):
return None
elif isinstance(num_or_str, (int, float)):
return num_or_str
elif isinstance(num_or_str, basestring):
if '.' in num_or_str or ',' in num_or_str or num_or_str.isdigit():
try:
return float(num_or_str.replace(',', ''))
except Exception as e:
return None
return None
def class_uri_to_fname(class_uri):
if class_uri[:7] == "http://":
class_dname = class_uri[7:]
elif class_uri[:8] == "https://":
class_dname = class_uri[8:]
class_fname = class_dname.replace('/', '__').replace(',', '').replace('#', '_')
return class_fname
| true | true |
f726cc74ea48e6d84a1083f2a64bd4568a8f55c4 | 8,841 | py | Python | tools/pkg/tmpl.py | kristoffer-paulsson/angelos | 2ec236770d6530884a8ad88505aab01183f752b4 | [
"MIT"
] | 8 | 2020-06-07T23:26:34.000Z | 2022-03-28T00:20:34.000Z | tools/pkg/tmpl.py | kristoffer-paulsson/angelos | 2ec236770d6530884a8ad88505aab01183f752b4 | [
"MIT"
] | 1 | 2019-12-24T22:06:02.000Z | 2020-07-12T19:18:57.000Z | tools/pkg/tmpl.py | kristoffer-paulsson/angelos | 2ec236770d6530884a8ad88505aab01183f752b4 | [
"MIT"
] | null | null | null | #
# Copyright (c) 2018-2020 by Kristoffer Paulsson <kristoffer.paulsson@talenten.se>.
#
# This software is available under the terms of the MIT license. Parts are licensed under
# different terms if stated. The legal terms are attached to the LICENSE file and are
# made available on:
#
# https://opensource.org/licenses/MIT
#
# SPDX-License-Identifier: MIT
#
# Contributors:
# Kristoffer Paulsson - initial implementation
#
"""Install file templates."""
import datetime
import os
import re
import shutil
from pathlib import Path
from .data import NAME_NIX, VERSION, LICENSE, URL, PERMS_DIR, PERMS_EXEC, PERMS_FILE, EXEC_PREFIX, DIR_ANGELOS, \
FILE_ENV, FILE_CONF, FILE_EXE, USERNAME, GROUPNAME, NAME_SERVICE, DIR_VAR, DIR_LOG, DIR_ETC, FILE_ADMINS, LINK_EXE, \
FILTER, EXEC_SUFFIX, AUTHOR, AUTHOR_EMAIL
RPM_SPEC = """
Name: {namenix}
Version: {version}
Release: {release}
Summary: A safe messaging system.
License: {license}
URL: {url}
Source1: angelos.service
Source2: env.json
Source3: config.json
BuildArch: x86_64
BuildRequires: bzip2-devel, expat-devel, gdbm-devel, ncurses-devel, openssl-devel, readline-devel, sqlite-devel,
BuildRequires: tk-devel, xz-devel, zlib-devel, libffi-devel
BuildRequires: systemd-rpm-macros /usr/bin/pathfix.py
Requires: bzip2-libs, expat, gdbm-libs, ncurses-libs, openssl-libs, readline, sqlite-libs, tk, xz-libs, zlib, libffi
AutoReqProv: no
%description
Ἄγγελος is a safe messenger system. Angelos means "Carrier of a divine message."
%prep
%build
%check
%install
mkdir %{{buildroot}}/opt -p
sudo mv /opt/angelos/ %{{buildroot}}/opt
install --directory %{{buildroot}}{diretc}
install --directory %{{buildroot}}{dirvar}
install --directory %{{buildroot}}{dirlog}
install -D -m 0644 %{{SOURCE1}} %{{buildroot}}%{{_unitdir}}/{nameservice}
install -D -m 0644 %{{SOURCE2}} %{{buildroot}}{fileenv}
install -D -m 0644 %{{SOURCE3}} %{{buildroot}}{fileconf}
pathfix.py -pni "%{{__python3}} %{{py3_shbang_opts}}" %{{buildroot}}/*
%clean
%pre
grep -q {groupname} /etc/group >/dev/null 2>&1 || groupadd {groupname}
id {username} >/dev/null 2>&1 || useradd {username} --system -g {groupname}
%post
%systemd_post {nameservice}
touch {fileadmins}
chown 600 {fileadmins}
chmod {username}:{groupname} {fileadmins}
ln -sf {fileexe} {linkexe}
%preun
%systemd_preun {nameservice}
rm {linkexe}
%postun
%systemd_postun {nameservice}
%changelog
%files
%attr(700, {username}, {groupname}) {dirvar}
%attr(700, {username}, {groupname}) {dirlog}
%{{_unitdir}}/{nameservice}
%config {fileenv}
%config {fileconf}
%defattr({permsfile}, {username}, {groupname}, {permsdir})
{files}
"""
def walk_files(path: str) -> str:
"""Walk all files and directories at install path."""
path = str(Path(path))
output = ""
for root, dirs, files in os.walk(path):
output += "{path}\n".format(
perms=PERMS_DIR, path=root)
for file in files:
filepath = os.path.join(root, file)
output += "%attr({perms}, {username}, {groupname}) {path}\n".format(
perms=PERMS_EXEC, path=filepath,
username=USERNAME, groupname=GROUPNAME
) if root.startswith(EXEC_PREFIX) or file.endswith(EXEC_SUFFIX) else "{path}\n".format(
path=filepath
)
return output
def filter_files(path: str, subs: list = None):
"""Filter all files and directories."""
pattern = "|".join(subs if subs else FILTER)
for root, dirs, files in os.walk(path):
for file in files:
# Deal with file
filepath = os.path.join(root, file)
if re.search(pattern, filepath) and os.path.exists(filepath):
try:
os.remove(filepath)
print("Deleted file:", filepath)
except Exception as e:
print(filepath, e)
# Deal with directory
if re.search(pattern, root) and os.path.exists(root):
try:
shutil.rmtree(root)
print("Deleted directory:", root)
except Exception as e:
print(root, e)
def render_rpm_spec(release: int, full_path: bool=True) -> str:
"""Render the RPM spec file. (angelos.spec)"""
return RPM_SPEC.format(
dirangelos=DIR_ANGELOS, dirvar=DIR_VAR, diretc=DIR_ETC, dirlog=DIR_LOG,
fileenv=FILE_ENV, fileconf=FILE_CONF, fileexe=FILE_EXE, linkexe=LINK_EXE,
fileadmins=FILE_ADMINS, permsexec=PERMS_EXEC, permsfile=PERMS_FILE, permsdir=PERMS_DIR,
username=USERNAME, groupname=GROUPNAME, nameservice=NAME_SERVICE,
namenix=NAME_NIX, url=URL, version=VERSION, release=release, license=LICENSE,
files=walk_files(DIR_ANGELOS)
)
SYSTEMD_UNIT = """
[Unit]
Description = Run the Angelos server
After = network.target
[Service]
Type = forking
AmbientCapabilities = CAP_NET_BIND_SERVICE
ExecStart = {namenix} -d start
ExecStop = {namenix} -d stop
ExecReload = {namenix} -d restart
PIDFile = /tmp/angelos.pid
User = {username}
Group = {groupname}
StateDirectory = {service_dirvar}
LogsDirectory = {service_dirlog}
ConfigurationDirectory = {service_diretc}
KeyringMode = private
[Install]
WantedBy=default.target
"""
def render_systemd_unit(service_full_path: bool=True) -> str:
"""Render systemd unit file. (angelos.service)"""
return SYSTEMD_UNIT.format(
namenix=NAME_NIX, username=USERNAME, groupname=GROUPNAME,
service_dirvar=DIR_VAR if service_full_path else NAME_NIX,
service_dirlog=DIR_LOG if service_full_path else NAME_NIX,
service_diretc=DIR_ETC if service_full_path else NAME_NIX
)
def render_deb_name(release: int) -> str:
"""Render the debian package name."""
return "{namenix}_{version}-{release}_amd64".format(
namenix=NAME_NIX, version=VERSION, release=release)
DEB_CONTROL = """
Package: {namenix}
Version: {version}
Homepage: {url}
Depends: zlib1g, libncurses5, libgdbm6, libnss3, libssl1.1, libreadline7, libffi6, bzip2, libsqlite3-0
Architecture: amd64
Maintainer: {author} <{authoremail}>
Description: Ἄγγελος is a safe messenger system. Angelos means "Carrier of a divine message."
"""
def render_deb_control() -> str:
"""Render the control file. (debian/control)"""
return DEB_CONTROL.format(
namenix=NAME_NIX, version=VERSION, url=URL, author=AUTHOR, authoremail=AUTHOR_EMAIL
)
DEB_COPYRIGHT = """
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: {namenix}
Upstream-Contact: {author} <{authoremail}>
Source: {url}
Files: *
Copyright: 2018-2020, {author} <{authoremail}>
License: MIT
"""
def render_deb_copyright() -> str:
"""Render the copyright file. (debian/copyright)"""
return DEB_COPYRIGHT.format(
namenix=NAME_NIX, author=AUTHOR, authoremail=AUTHOR_EMAIL, url=URL,
)
DEB_CHANGELOG = """
{namenix} ({version}) testing; urgency=medium
* Initial release.
-- {author} <{authoremail}> {timestamp}
"""
def render_deb_changelog() -> str:
"""Render the changelog file. (debian/changelog)"""
return DEB_CHANGELOG.format(
namenix=NAME_NIX, version=VERSION, author=AUTHOR, authoremail=AUTHOR_EMAIL,
timestamp=datetime.datetime.strftime(
datetime.datetime.now(
datetime.datetime.now(
datetime.timezone.utc).astimezone().tzinfo), "%a, %d %b %Y %X %z"),
)
DEB_RULES = """
#!/usr/bin/make -f
#DH_VERBOSE = 1
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
%:
dh $@
"""
def render_deb_rules() -> str:
"""Render the compat file. (debian/rules)"""
return DEB_RULES.format()
DEB_COMPAT = """
10
"""
def render_deb_compat() -> str:
"""Render the compat file. (debian/compat)"""
return DEB_COMPAT.format()
DEB_CONFFILES = """
"""
def render_deb_conffiles() -> str:
"""Render the conffiles file. (debian/conffiles)"""
return DEB_CONFFILES.format()
DEB_DIRS = """
etc/angelos
var/lib/angelos
var/log/angelos
"""
def render_deb_dirs() -> str:
"""Render the dirs file. (debian/dirs)"""
return DEB_DIRS.format()
DEB_LINKS = """
{fileexe} {linkexe}
"""
def render_deb_links() -> str:
"""Render the dirs file. (debian/angelos.links)"""
return DEB_LINKS.format(fileexe=FILE_EXE, linkexe=LINK_EXE)
ENV_JSON = """{{}}"""
def render_env_json() -> str:
"""Render env configuration file. (env.json)"""
return ENV_JSON.format()
CONFIG_JSON = """{{}}"""
def render_config_json() -> str:
"""Render config configuration file. (config.json)"""
return CONFIG_JSON.format()
ADMINS_PUB = """"""
def render_admins_pub() -> str:
"""Render admins public key file. (admins.pub)"""
return ADMINS_PUB.format()
| 26.54955 | 121 | 0.679222 |
import datetime
import os
import re
import shutil
from pathlib import Path
from .data import NAME_NIX, VERSION, LICENSE, URL, PERMS_DIR, PERMS_EXEC, PERMS_FILE, EXEC_PREFIX, DIR_ANGELOS, \
FILE_ENV, FILE_CONF, FILE_EXE, USERNAME, GROUPNAME, NAME_SERVICE, DIR_VAR, DIR_LOG, DIR_ETC, FILE_ADMINS, LINK_EXE, \
FILTER, EXEC_SUFFIX, AUTHOR, AUTHOR_EMAIL
RPM_SPEC = """
Name: {namenix}
Version: {version}
Release: {release}
Summary: A safe messaging system.
License: {license}
URL: {url}
Source1: angelos.service
Source2: env.json
Source3: config.json
BuildArch: x86_64
BuildRequires: bzip2-devel, expat-devel, gdbm-devel, ncurses-devel, openssl-devel, readline-devel, sqlite-devel,
BuildRequires: tk-devel, xz-devel, zlib-devel, libffi-devel
BuildRequires: systemd-rpm-macros /usr/bin/pathfix.py
Requires: bzip2-libs, expat, gdbm-libs, ncurses-libs, openssl-libs, readline, sqlite-libs, tk, xz-libs, zlib, libffi
AutoReqProv: no
%description
Ἄγγελος is a safe messenger system. Angelos means "Carrier of a divine message."
%prep
%build
%check
%install
mkdir %{{buildroot}}/opt -p
sudo mv /opt/angelos/ %{{buildroot}}/opt
install --directory %{{buildroot}}{diretc}
install --directory %{{buildroot}}{dirvar}
install --directory %{{buildroot}}{dirlog}
install -D -m 0644 %{{SOURCE1}} %{{buildroot}}%{{_unitdir}}/{nameservice}
install -D -m 0644 %{{SOURCE2}} %{{buildroot}}{fileenv}
install -D -m 0644 %{{SOURCE3}} %{{buildroot}}{fileconf}
pathfix.py -pni "%{{__python3}} %{{py3_shbang_opts}}" %{{buildroot}}/*
%clean
%pre
grep -q {groupname} /etc/group >/dev/null 2>&1 || groupadd {groupname}
id {username} >/dev/null 2>&1 || useradd {username} --system -g {groupname}
%post
%systemd_post {nameservice}
touch {fileadmins}
chown 600 {fileadmins}
chmod {username}:{groupname} {fileadmins}
ln -sf {fileexe} {linkexe}
%preun
%systemd_preun {nameservice}
rm {linkexe}
%postun
%systemd_postun {nameservice}
%changelog
%files
%attr(700, {username}, {groupname}) {dirvar}
%attr(700, {username}, {groupname}) {dirlog}
%{{_unitdir}}/{nameservice}
%config {fileenv}
%config {fileconf}
%defattr({permsfile}, {username}, {groupname}, {permsdir})
{files}
"""
def walk_files(path: str) -> str:
path = str(Path(path))
output = ""
for root, dirs, files in os.walk(path):
output += "{path}\n".format(
perms=PERMS_DIR, path=root)
for file in files:
filepath = os.path.join(root, file)
output += "%attr({perms}, {username}, {groupname}) {path}\n".format(
perms=PERMS_EXEC, path=filepath,
username=USERNAME, groupname=GROUPNAME
) if root.startswith(EXEC_PREFIX) or file.endswith(EXEC_SUFFIX) else "{path}\n".format(
path=filepath
)
return output
def filter_files(path: str, subs: list = None):
pattern = "|".join(subs if subs else FILTER)
for root, dirs, files in os.walk(path):
for file in files:
filepath = os.path.join(root, file)
if re.search(pattern, filepath) and os.path.exists(filepath):
try:
os.remove(filepath)
print("Deleted file:", filepath)
except Exception as e:
print(filepath, e)
if re.search(pattern, root) and os.path.exists(root):
try:
shutil.rmtree(root)
print("Deleted directory:", root)
except Exception as e:
print(root, e)
def render_rpm_spec(release: int, full_path: bool=True) -> str:
return RPM_SPEC.format(
dirangelos=DIR_ANGELOS, dirvar=DIR_VAR, diretc=DIR_ETC, dirlog=DIR_LOG,
fileenv=FILE_ENV, fileconf=FILE_CONF, fileexe=FILE_EXE, linkexe=LINK_EXE,
fileadmins=FILE_ADMINS, permsexec=PERMS_EXEC, permsfile=PERMS_FILE, permsdir=PERMS_DIR,
username=USERNAME, groupname=GROUPNAME, nameservice=NAME_SERVICE,
namenix=NAME_NIX, url=URL, version=VERSION, release=release, license=LICENSE,
files=walk_files(DIR_ANGELOS)
)
SYSTEMD_UNIT = """
[Unit]
Description = Run the Angelos server
After = network.target
[Service]
Type = forking
AmbientCapabilities = CAP_NET_BIND_SERVICE
ExecStart = {namenix} -d start
ExecStop = {namenix} -d stop
ExecReload = {namenix} -d restart
PIDFile = /tmp/angelos.pid
User = {username}
Group = {groupname}
StateDirectory = {service_dirvar}
LogsDirectory = {service_dirlog}
ConfigurationDirectory = {service_diretc}
KeyringMode = private
[Install]
WantedBy=default.target
"""
def render_systemd_unit(service_full_path: bool=True) -> str:
return SYSTEMD_UNIT.format(
namenix=NAME_NIX, username=USERNAME, groupname=GROUPNAME,
service_dirvar=DIR_VAR if service_full_path else NAME_NIX,
service_dirlog=DIR_LOG if service_full_path else NAME_NIX,
service_diretc=DIR_ETC if service_full_path else NAME_NIX
)
def render_deb_name(release: int) -> str:
return "{namenix}_{version}-{release}_amd64".format(
namenix=NAME_NIX, version=VERSION, release=release)
DEB_CONTROL = """
Package: {namenix}
Version: {version}
Homepage: {url}
Depends: zlib1g, libncurses5, libgdbm6, libnss3, libssl1.1, libreadline7, libffi6, bzip2, libsqlite3-0
Architecture: amd64
Maintainer: {author} <{authoremail}>
Description: Ἄγγελος is a safe messenger system. Angelos means "Carrier of a divine message."
"""
def render_deb_control() -> str:
return DEB_CONTROL.format(
namenix=NAME_NIX, version=VERSION, url=URL, author=AUTHOR, authoremail=AUTHOR_EMAIL
)
DEB_COPYRIGHT = """
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: {namenix}
Upstream-Contact: {author} <{authoremail}>
Source: {url}
Files: *
Copyright: 2018-2020, {author} <{authoremail}>
License: MIT
"""
def render_deb_copyright() -> str:
return DEB_COPYRIGHT.format(
namenix=NAME_NIX, author=AUTHOR, authoremail=AUTHOR_EMAIL, url=URL,
)
DEB_CHANGELOG = """
{namenix} ({version}) testing; urgency=medium
* Initial release.
-- {author} <{authoremail}> {timestamp}
"""
def render_deb_changelog() -> str:
return DEB_CHANGELOG.format(
namenix=NAME_NIX, version=VERSION, author=AUTHOR, authoremail=AUTHOR_EMAIL,
timestamp=datetime.datetime.strftime(
datetime.datetime.now(
datetime.datetime.now(
datetime.timezone.utc).astimezone().tzinfo), "%a, %d %b %Y %X %z"),
)
DEB_RULES = """
#!/usr/bin/make -f
#DH_VERBOSE = 1
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all
#export DEB_CFLAGS_MAINT_APPEND = -Wall -pedantic
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
%:
dh $@
"""
def render_deb_rules() -> str:
return DEB_RULES.format()
DEB_COMPAT = """
10
"""
def render_deb_compat() -> str:
return DEB_COMPAT.format()
DEB_CONFFILES = """
"""
def render_deb_conffiles() -> str:
return DEB_CONFFILES.format()
DEB_DIRS = """
etc/angelos
var/lib/angelos
var/log/angelos
"""
def render_deb_dirs() -> str:
return DEB_DIRS.format()
DEB_LINKS = """
{fileexe} {linkexe}
"""
def render_deb_links() -> str:
return DEB_LINKS.format(fileexe=FILE_EXE, linkexe=LINK_EXE)
ENV_JSON = """{{}}"""
def render_env_json() -> str:
return ENV_JSON.format()
CONFIG_JSON = """{{}}"""
def render_config_json() -> str:
return CONFIG_JSON.format()
ADMINS_PUB = """"""
def render_admins_pub() -> str:
return ADMINS_PUB.format()
| true | true |
f726cc8a8a3084e57b5bf0e9e1bfcc87faa21241 | 6,494 | py | Python | dvc/stage/serialize.py | asford/dvc | 4ed55d00511ea3d9115b76c463e1a466408b11ef | [
"Apache-2.0"
] | 1 | 2021-06-18T19:36:13.000Z | 2021-06-18T19:36:13.000Z | dvc/stage/serialize.py | asford/dvc | 4ed55d00511ea3d9115b76c463e1a466408b11ef | [
"Apache-2.0"
] | 82 | 2021-05-04T02:40:05.000Z | 2022-03-31T03:14:04.000Z | dvc/stage/serialize.py | asford/dvc | 4ed55d00511ea3d9115b76c463e1a466408b11ef | [
"Apache-2.0"
] | 2 | 2021-06-14T19:12:25.000Z | 2021-06-14T19:12:29.000Z | from collections import OrderedDict
from functools import partial
from operator import attrgetter
from typing import TYPE_CHECKING, List, no_type_check
from funcy import post_processing
from dvc.dependency import ParamsDependency
from dvc.output import BaseOutput
from dvc.utils.collections import apply_diff
from dvc.utils.serialize import parse_yaml_for_update
from .params import StageParams
from .utils import resolve_wdir, split_params_deps
if TYPE_CHECKING:
from dvc.stage import PipelineStage, Stage
PARAM_PARAMS = ParamsDependency.PARAM_PARAMS
PARAM_PATH = ParamsDependency.PARAM_PATH
PARAM_DEPS = StageParams.PARAM_DEPS
PARAM_OUTS = StageParams.PARAM_OUTS
PARAM_CACHE = BaseOutput.PARAM_CACHE
PARAM_METRIC = BaseOutput.PARAM_METRIC
PARAM_PLOT = BaseOutput.PARAM_PLOT
PARAM_PERSIST = BaseOutput.PARAM_PERSIST
PARAM_CHECKPOINT = BaseOutput.PARAM_CHECKPOINT
PARAM_DESC = BaseOutput.PARAM_DESC
DEFAULT_PARAMS_FILE = ParamsDependency.DEFAULT_PARAMS_FILE
sort_by_path = partial(sorted, key=attrgetter("def_path"))
@post_processing(OrderedDict)
def _get_flags(out):
if out.desc:
yield PARAM_DESC, out.desc
if not out.use_cache:
yield PARAM_CACHE, False
if out.checkpoint:
yield PARAM_CHECKPOINT, True
if out.persist:
yield PARAM_PERSIST, True
if out.plot and isinstance(out.plot, dict):
# notice `out.plot` is not sorted
# `out.plot` is in the same order as is in the file when read
# and, should be dumped as-is without any sorting
yield from out.plot.items()
if out.live and isinstance(out.live, dict):
yield from out.live.items()
def _serialize_out(out):
flags = _get_flags(out)
return out.def_path if not flags else {out.def_path: flags}
@no_type_check
def _serialize_outs(outputs: List[BaseOutput]):
outs, metrics, plots, live = [], [], [], None
for out in sort_by_path(outputs):
bucket = outs
if out.plot:
bucket = plots
elif out.metric:
bucket = metrics
elif out.live:
assert live is None
live = _serialize_out(out)
continue
bucket.append(_serialize_out(out))
return outs, metrics, plots, live
def _serialize_params_keys(params):
"""
Returns the following format of data:
['lr', 'train', {'params2.yaml': ['lr']}]
The output is sorted, with keys of params from default params file being
at the first, and then followed by entry of other files in lexicographic
order. The keys of those custom files are also sorted in the same order.
"""
keys = []
for param_dep in sort_by_path(params):
dump = param_dep.dumpd()
path, params = dump[PARAM_PATH], dump[PARAM_PARAMS]
assert isinstance(params, (dict, list))
# when on no_exec, params are not filled and are saved as list
k = sorted(params.keys() if isinstance(params, dict) else params)
if not k:
continue
if path == DEFAULT_PARAMS_FILE:
keys = k + keys
else:
keys.append({path: k})
return keys
@no_type_check
def _serialize_params_values(params: List[ParamsDependency]):
"""Returns output of following format, used for lockfile:
{'params.yaml': {'lr': '1', 'train': 2}, {'params2.yaml': {'lr': '1'}}
Default params file are always kept at the start, followed by others in
alphabetical order. The param values are sorted too(not recursively though)
"""
key_vals = OrderedDict()
for param_dep in sort_by_path(params):
dump = param_dep.dumpd()
path, params = dump[PARAM_PATH], dump[PARAM_PARAMS]
if isinstance(params, dict):
kv = [(key, params[key]) for key in sorted(params.keys())]
key_vals[path] = OrderedDict(kv)
if path == DEFAULT_PARAMS_FILE:
key_vals.move_to_end(path, last=False)
return key_vals
def to_pipeline_file(stage: "PipelineStage"):
wdir = resolve_wdir(stage.wdir, stage.path)
params, deps = split_params_deps(stage)
deps = sorted(d.def_path for d in deps)
params = _serialize_params_keys(params)
outs, metrics, plots, live = _serialize_outs(stage.outs)
cmd = stage.cmd
assert cmd, (
f"'{stage.PARAM_CMD}' cannot be empty for stage '{stage.name}', "
f"got: '{cmd}'(type: '{type(cmd).__name__}')"
)
res = [
(stage.PARAM_DESC, stage.desc),
(stage.PARAM_CMD, stage.cmd),
(stage.PARAM_WDIR, wdir),
(stage.PARAM_DEPS, deps),
(stage.PARAM_PARAMS, params),
(stage.PARAM_OUTS, outs),
(stage.PARAM_METRICS, metrics),
(stage.PARAM_PLOTS, plots),
(stage.PARAM_LIVE, live),
(stage.PARAM_FROZEN, stage.frozen),
(stage.PARAM_ALWAYS_CHANGED, stage.always_changed),
(stage.PARAM_META, stage.meta),
]
return {
stage.name: OrderedDict([(key, value) for key, value in res if value])
}
def to_single_stage_lockfile(stage: "Stage") -> dict:
assert stage.cmd
def _dumpd(item):
ret = [
(item.PARAM_PATH, item.def_path),
*item.hash_info.to_dict().items(),
]
if item.isexec:
ret.append((item.PARAM_ISEXEC, True))
return OrderedDict(ret)
res = OrderedDict([("cmd", stage.cmd)])
params, deps = split_params_deps(stage)
deps, outs = [
[_dumpd(item) for item in sort_by_path(items)]
for items in [deps, stage.outs]
]
params = _serialize_params_values(params)
if deps:
res[PARAM_DEPS] = deps
if params:
res[PARAM_PARAMS] = params
if outs:
res[PARAM_OUTS] = outs
return res
def to_lockfile(stage: "PipelineStage") -> dict:
assert stage.name
return {stage.name: to_single_stage_lockfile(stage)}
def to_single_stage_file(stage: "Stage"):
state = stage.dumpd()
# When we load a stage we parse yaml with a fast parser, which strips
# off all the comments and formatting. To retain those on update we do
# a trick here:
# - reparse the same yaml text with a slow but smart ruamel yaml parser
# - apply changes to a returned structure
# - serialize it
text = stage._stage_text # noqa, pylint: disable=protected-access
if text is not None:
saved_state = parse_yaml_for_update(text, stage.path)
apply_diff(state, saved_state)
state = saved_state
return state
| 31.221154 | 79 | 0.665075 | from collections import OrderedDict
from functools import partial
from operator import attrgetter
from typing import TYPE_CHECKING, List, no_type_check
from funcy import post_processing
from dvc.dependency import ParamsDependency
from dvc.output import BaseOutput
from dvc.utils.collections import apply_diff
from dvc.utils.serialize import parse_yaml_for_update
from .params import StageParams
from .utils import resolve_wdir, split_params_deps
if TYPE_CHECKING:
from dvc.stage import PipelineStage, Stage
PARAM_PARAMS = ParamsDependency.PARAM_PARAMS
PARAM_PATH = ParamsDependency.PARAM_PATH
PARAM_DEPS = StageParams.PARAM_DEPS
PARAM_OUTS = StageParams.PARAM_OUTS
PARAM_CACHE = BaseOutput.PARAM_CACHE
PARAM_METRIC = BaseOutput.PARAM_METRIC
PARAM_PLOT = BaseOutput.PARAM_PLOT
PARAM_PERSIST = BaseOutput.PARAM_PERSIST
PARAM_CHECKPOINT = BaseOutput.PARAM_CHECKPOINT
PARAM_DESC = BaseOutput.PARAM_DESC
DEFAULT_PARAMS_FILE = ParamsDependency.DEFAULT_PARAMS_FILE
sort_by_path = partial(sorted, key=attrgetter("def_path"))
@post_processing(OrderedDict)
def _get_flags(out):
if out.desc:
yield PARAM_DESC, out.desc
if not out.use_cache:
yield PARAM_CACHE, False
if out.checkpoint:
yield PARAM_CHECKPOINT, True
if out.persist:
yield PARAM_PERSIST, True
if out.plot and isinstance(out.plot, dict):
yield from out.plot.items()
if out.live and isinstance(out.live, dict):
yield from out.live.items()
def _serialize_out(out):
flags = _get_flags(out)
return out.def_path if not flags else {out.def_path: flags}
@no_type_check
def _serialize_outs(outputs: List[BaseOutput]):
outs, metrics, plots, live = [], [], [], None
for out in sort_by_path(outputs):
bucket = outs
if out.plot:
bucket = plots
elif out.metric:
bucket = metrics
elif out.live:
assert live is None
live = _serialize_out(out)
continue
bucket.append(_serialize_out(out))
return outs, metrics, plots, live
def _serialize_params_keys(params):
keys = []
for param_dep in sort_by_path(params):
dump = param_dep.dumpd()
path, params = dump[PARAM_PATH], dump[PARAM_PARAMS]
assert isinstance(params, (dict, list))
k = sorted(params.keys() if isinstance(params, dict) else params)
if not k:
continue
if path == DEFAULT_PARAMS_FILE:
keys = k + keys
else:
keys.append({path: k})
return keys
@no_type_check
def _serialize_params_values(params: List[ParamsDependency]):
key_vals = OrderedDict()
for param_dep in sort_by_path(params):
dump = param_dep.dumpd()
path, params = dump[PARAM_PATH], dump[PARAM_PARAMS]
if isinstance(params, dict):
kv = [(key, params[key]) for key in sorted(params.keys())]
key_vals[path] = OrderedDict(kv)
if path == DEFAULT_PARAMS_FILE:
key_vals.move_to_end(path, last=False)
return key_vals
def to_pipeline_file(stage: "PipelineStage"):
wdir = resolve_wdir(stage.wdir, stage.path)
params, deps = split_params_deps(stage)
deps = sorted(d.def_path for d in deps)
params = _serialize_params_keys(params)
outs, metrics, plots, live = _serialize_outs(stage.outs)
cmd = stage.cmd
assert cmd, (
f"'{stage.PARAM_CMD}' cannot be empty for stage '{stage.name}', "
f"got: '{cmd}'(type: '{type(cmd).__name__}')"
)
res = [
(stage.PARAM_DESC, stage.desc),
(stage.PARAM_CMD, stage.cmd),
(stage.PARAM_WDIR, wdir),
(stage.PARAM_DEPS, deps),
(stage.PARAM_PARAMS, params),
(stage.PARAM_OUTS, outs),
(stage.PARAM_METRICS, metrics),
(stage.PARAM_PLOTS, plots),
(stage.PARAM_LIVE, live),
(stage.PARAM_FROZEN, stage.frozen),
(stage.PARAM_ALWAYS_CHANGED, stage.always_changed),
(stage.PARAM_META, stage.meta),
]
return {
stage.name: OrderedDict([(key, value) for key, value in res if value])
}
def to_single_stage_lockfile(stage: "Stage") -> dict:
assert stage.cmd
def _dumpd(item):
ret = [
(item.PARAM_PATH, item.def_path),
*item.hash_info.to_dict().items(),
]
if item.isexec:
ret.append((item.PARAM_ISEXEC, True))
return OrderedDict(ret)
res = OrderedDict([("cmd", stage.cmd)])
params, deps = split_params_deps(stage)
deps, outs = [
[_dumpd(item) for item in sort_by_path(items)]
for items in [deps, stage.outs]
]
params = _serialize_params_values(params)
if deps:
res[PARAM_DEPS] = deps
if params:
res[PARAM_PARAMS] = params
if outs:
res[PARAM_OUTS] = outs
return res
def to_lockfile(stage: "PipelineStage") -> dict:
assert stage.name
return {stage.name: to_single_stage_lockfile(stage)}
def to_single_stage_file(stage: "Stage"):
state = stage.dumpd()
text = stage._stage_text
if text is not None:
saved_state = parse_yaml_for_update(text, stage.path)
apply_diff(state, saved_state)
state = saved_state
return state
| true | true |
f726cca87b9b1703027d92c330e14876f773484c | 8,401 | py | Python | mmdet/models/losses/my_cross_entropy_loss.py | dyabel/wsod-mmdet | 60fc1993ea298f992b160b5599a6134702ac0d4f | [
"Apache-2.0"
] | 6 | 2021-10-09T05:34:04.000Z | 2022-03-31T00:36:55.000Z | mmdet/models/losses/my_cross_entropy_loss.py | dyabel/wsod-mmdet | 60fc1993ea298f992b160b5599a6134702ac0d4f | [
"Apache-2.0"
] | null | null | null | mmdet/models/losses/my_cross_entropy_loss.py | dyabel/wsod-mmdet | 60fc1993ea298f992b160b5599a6134702ac0d4f | [
"Apache-2.0"
] | null | null | null | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..builder import LOSSES
from .utils import weight_reduce_loss
eps = 0.000001
def cross_entropy_without_softmax(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
"""Calculate the CrossEntropy loss.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
label (torch.Tensor): The learning label of the prediction.
weight (torch.Tensor, optional): Sample-wise loss weight.
reduction (str, optional): The method used to reduce the loss.
avg_factor (int, optional): Average factor that is used to average
the loss. Defaults to None.
class_weight (list[float], optional): The weight for each class.
Returns:
torch.Tensor: The calculated loss
"""
# element-wise losses
#loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none')
loss = F.nll_loss(torch.log(pred), label, reduction = 'none')
# apply weights and do the reduction
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
"""Calculate the CrossEntropy loss.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
label (torch.Tensor): The learning label of the prediction.
weight (torch.Tensor, optional): Sample-wise loss weight.
reduction (str, optional): The method used to reduce the loss.
avg_factor (int, optional): Average factor that is used to average
the loss. Defaults to None.
class_weight (list[float], optional): The weight for each class.
Returns:
torch.Tensor: The calculated loss
"""
# element-wise losses
loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none')
# apply weights and do the reduction
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def _expand_onehot_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(
(labels >= 0) & (labels < label_channels), as_tuple=False).squeeze()
if inds.numel() > 0:
bin_labels[inds, labels[inds]] = 1
if label_weights is None:
bin_label_weights = None
else:
bin_label_weights = label_weights.view(-1, 1).expand(
label_weights.size(0), label_channels)
return bin_labels, bin_label_weights
def binary_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
"""Calculate the binary CrossEntropy loss.
Args:
pred (torch.Tensor): The prediction with shape (N, 1).
label (torch.Tensor): The learning label of the prediction.
weight (torch.Tensor, optional): Sample-wise loss weight.
reduction (str, optional): The method used to reduce the loss.
Options are "none", "mean" and "sum".
avg_factor (int, optional): Average factor that is used to average
the loss. Defaults to None.
class_weight (list[float], optional): The weight for each class.
Returns:
torch.Tensor: The calculated loss
"""
if pred.dim() != label.dim():
label, weight = _expand_onehot_labels(label, weight, pred.size(-1))
# weighted element-wise losses
if weight is not None:
weight = weight.float()
pred = pred.clamp(1e-6,1-1e-6)
label = label.clamp(0,1)
loss = F.binary_cross_entropy(pred,label)
return loss
def mask_cross_entropy(pred,
target,
label,
reduction='mean',
avg_factor=None,
class_weight=None):
"""Calculate the CrossEntropy loss for masks.
Args:
pred (torch.Tensor): The prediction with shape (N, C), C is the number
of classes.
target (torch.Tensor): The learning label of the prediction.
label (torch.Tensor): ``label`` indicates the class label of the mask'
corresponding object. This will be used to select the mask in the
of the class which the object belongs to when the mask prediction
if not class-agnostic.
reduction (str, optional): The method used to reduce the loss.
Options are "none", "mean" and "sum".
avg_factor (int, optional): Average factor that is used to average
the loss. Defaults to None.
class_weight (list[float], optional): The weight for each class.
Returns:
torch.Tensor: The calculated loss
"""
# TODO: handle these two reserved arguments
assert reduction == 'mean' and avg_factor is None
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[inds, label].squeeze(1)
return F.binary_cross_entropy_with_logits(
pred_slice, target, weight=class_weight, reduction='mean')[None]
@LOSSES.register_module()
class MyCrossEntropyLoss(nn.Module):
def __init__(self,
use_sigmoid=False,
use_mask=False,
reduction='mean',
class_weight=None,
loss_weight=1.0):
"""CrossEntropyLoss.
Args:
use_sigmoid (bool, optional): Whether the prediction uses sigmoid
of softmax. Defaults to False.
use_mask (bool, optional): Whether to use mask cross entropy loss.
Defaults to False.
reduction (str, optional): . Defaults to 'mean'.
Options are "none", "mean" and "sum".
class_weight (list[float], optional): Weight of each class.
Defaults to None.
loss_weight (float, optional): Weight of the loss. Defaults to 1.0.
"""
super(MyCrossEntropyLoss, self).__init__()
assert (use_sigmoid is False) or (use_mask is False)
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.cls_criterion = binary_cross_entropy
def forward(self,
cls_score,
label,
weight=None,
avg_factor=None,
reduction_override=None,
**kwargs):
"""Forward function.
Args:
cls_score (torch.Tensor): The prediction.
label (torch.Tensor): The learning label of the prediction.
weight (torch.Tensor, optional): Sample-wise loss weight.
avg_factor (int, optional): Average factor that is used to average
the loss. Defaults to None.
reduction (str, optional): The method used to reduce the loss.
Options are "none", "mean" and "sum".
Returns:
torch.Tensor: The calculated loss
"""
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (
reduction_override if reduction_override else self.reduction)
if self.class_weight is not None:
class_weight = cls_score.new_tensor(
self.class_weight, device=cls_score.device)
else:
class_weight = None
loss_cls = self.loss_weight * self.cls_criterion(
cls_score,
label,
weight,
class_weight=class_weight,
reduction=reduction,
avg_factor=avg_factor,
**kwargs)
return loss_cls
| 36.055794 | 79 | 0.59612 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..builder import LOSSES
from .utils import weight_reduce_loss
eps = 0.000001
def cross_entropy_without_softmax(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
loss = F.nll_loss(torch.log(pred), label, reduction = 'none')
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
loss = F.cross_entropy(pred, label, weight=class_weight, reduction='none')
if weight is not None:
weight = weight.float()
loss = weight_reduce_loss(
loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss
def _expand_onehot_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(
(labels >= 0) & (labels < label_channels), as_tuple=False).squeeze()
if inds.numel() > 0:
bin_labels[inds, labels[inds]] = 1
if label_weights is None:
bin_label_weights = None
else:
bin_label_weights = label_weights.view(-1, 1).expand(
label_weights.size(0), label_channels)
return bin_labels, bin_label_weights
def binary_cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None):
if pred.dim() != label.dim():
label, weight = _expand_onehot_labels(label, weight, pred.size(-1))
if weight is not None:
weight = weight.float()
pred = pred.clamp(1e-6,1-1e-6)
label = label.clamp(0,1)
loss = F.binary_cross_entropy(pred,label)
return loss
def mask_cross_entropy(pred,
target,
label,
reduction='mean',
avg_factor=None,
class_weight=None):
assert reduction == 'mean' and avg_factor is None
num_rois = pred.size()[0]
inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device)
pred_slice = pred[inds, label].squeeze(1)
return F.binary_cross_entropy_with_logits(
pred_slice, target, weight=class_weight, reduction='mean')[None]
@LOSSES.register_module()
class MyCrossEntropyLoss(nn.Module):
def __init__(self,
use_sigmoid=False,
use_mask=False,
reduction='mean',
class_weight=None,
loss_weight=1.0):
super(MyCrossEntropyLoss, self).__init__()
assert (use_sigmoid is False) or (use_mask is False)
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
self.cls_criterion = binary_cross_entropy
def forward(self,
cls_score,
label,
weight=None,
avg_factor=None,
reduction_override=None,
**kwargs):
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (
reduction_override if reduction_override else self.reduction)
if self.class_weight is not None:
class_weight = cls_score.new_tensor(
self.class_weight, device=cls_score.device)
else:
class_weight = None
loss_cls = self.loss_weight * self.cls_criterion(
cls_score,
label,
weight,
class_weight=class_weight,
reduction=reduction,
avg_factor=avg_factor,
**kwargs)
return loss_cls
| true | true |
f726ce223abc85e16691c9ec990fbe29a1aa1ef0 | 400 | py | Python | sys_monitor/wsgi.py | PeterXUYAOHAI/System_Monitor | 2b78107a7f87e13ebab38ea5a89c870ef5415fd2 | [
"MIT"
] | 2 | 2018-05-07T03:30:55.000Z | 2018-05-10T11:27:18.000Z | sys_monitor/wsgi.py | PeterXUYAOHAI/System_Monitor | 2b78107a7f87e13ebab38ea5a89c870ef5415fd2 | [
"MIT"
] | null | null | null | sys_monitor/wsgi.py | PeterXUYAOHAI/System_Monitor | 2b78107a7f87e13ebab38ea5a89c870ef5415fd2 | [
"MIT"
] | null | null | null | """
WSGI config for sys_monitor project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sys_monitor.settings")
application = get_wsgi_application()
| 23.529412 | 78 | 0.79 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sys_monitor.settings")
application = get_wsgi_application()
| true | true |
f726cee2a25f6da66c15f0d51afb12dd8579d0fe | 6,439 | py | Python | python/oneflow/nn/optimizer/sgd.py | grybd/oneflow | 82237ad096a10527591660c09b61444c42917e69 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | python/oneflow/nn/optimizer/sgd.py | grybd/oneflow | 82237ad096a10527591660c09b61444c42917e69 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | python/oneflow/nn/optimizer/sgd.py | grybd/oneflow | 82237ad096a10527591660c09b61444c42917e69 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | """
Copyright 2020 The OneFlow 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.
"""
import collections
from typing import Callable, Dict, Iterator, List, Union
import oneflow as flow
from oneflow.nn.parameter import Parameter
from .optimizer import Optimizer, ParamGroup
class SGD(Optimizer):
"""Implements SGD algorithm.
This algorithm takes a random sample’s gradient as an approximate estimate of
the overall gradient in small batch gradient descent.
When the momentum = 0, the equation of parameters updating is:
.. math::
param_{new} = param_{old} - learning\\_rate * grad
With momentum, the equation of parameters updating is:
.. math::
& V_t = \\beta * V_{t-1} - learning\\_rate * (g_t + param_{old} * weight\\_decay)
& param_{new} = param_{old} + V_t
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optional): learning rate (default: 1e-3)
momentum (float, optional): Momentum factor (default: 0.0)
weight_decay (float, optional): weight decay (L2 penalty) (default: 0.0)
For example:
Example 1:
.. code-block:: python
# Assume net is a custom model.
sgd = flow.optim.SGD(net.parameters(), lr=1e-3)
for epoch in range(epochs):
# Read data, Compute the loss and so on.
# ...
loss.backward()
sgd.step()
sgd.zero_grad()
Example 2:
.. code-block:: python
# Assume net is a custom model.
sgd = flow.optim.SGD(
[
{
"params": net.parameters(),
"lr": learning_rate,
"clip_grad_max_norm": 0.5,
"clip_grad_norm_type": 2.0,
}
],
)
for epoch in range(epochs):
# Read data, Compute the loss and so on.
# ...
loss.backward()
sgd.clip_grad()
sgd.step()
sgd.zero_grad()
If you want to use clip_grad, you can refer this example.
For more details of `clip_grad_max_norm` and `clip_grad_norm_type`, you can refer to :func:`oneflow.nn.utils.clip_grad_norm_`.
"""
def __init__(
self,
parameters: Union[Iterator[Parameter], List[Dict]],
lr: float = 0.001,
momentum: float = 0.0,
weight_decay: float = 0.0,
):
assert lr >= 0.0, f"Invalid learning rate: {lr}"
assert momentum >= 0.0, f"Invalid momentum: {momentum}"
assert weight_decay >= 0.0, f"Invalid weight_decay: {weight_decay}"
options = dict()
options["lr"] = lr
options["momentum"] = momentum
options["weight_decay"] = weight_decay
super().__init__(parameters, options)
for param_group in self.param_groups:
for param in param_group.parameters:
assert param.is_leaf, "parameters must be leaf tensor"
self._state[param] = dict()
self._momentum_sgd = (
flow.builtin_op("momentum_update")
.Input("model")
.Input("model_diff")
.Input("momentum")
.Attr("l1", 0.0)
.Attr("weight_decay", 0.0)
.Build()
)
self._sgd = (
flow.builtin_op("sgd_update")
.Input("model")
.Input("model_diff")
.Attr("weight_decay", 0.0)
.Attr("l1", 0.0)
.Build()
)
def step(self, closure: Callable = None):
with flow.no_grad():
loss = None
if closure is not None:
loss = closure()
for param_group in self.param_groups:
lr = param_group["lr"]
l2 = param_group["weight_decay"]
for param in param_group.parameters:
if param.grad is None:
continue
if param_group["momentum"] == 0.0:
self._sgd(param, param.grad, learning_rate_val=lr, l2=l2)
else:
if "momentum_buf" not in self._state[param]:
self._state[param]["momentum_buf"] = flow.zeros_like(param)
momentum_buf = self._state[param]["momentum_buf"]
beta = param_group["momentum"]
self._momentum_sgd(
param,
param.grad,
momentum_buf,
learning_rate_val=lr,
l2=l2,
beta=beta,
)
self._state["step"] = self._state["step"] + 1
return loss
def _generate_conf_for_graph(self, train_conf, vars_conf):
new_opt_confs = []
for param_group in self.param_groups:
optimizer_conf = train_conf.mutable_optimizer_conf().Add()
lr = (
param_group["initial_lr"]
if "initial_lr" in param_group
else param_group["lr"]
)
beta = param_group["momentum"]
l2 = param_group["weight_decay"]
optimizer_conf.set_base_learning_rate(lr)
if beta == 0:
optimizer_conf.mutable_naive_conf()
else:
optimizer_conf.mutable_momentum_conf().set_beta(beta)
self._generate_grad_clip_conf_for_optim_conf(param_group, optimizer_conf)
for param in param_group.parameters:
vars_conf[param].l2 = l2
if param.requires_grad:
optimizer_conf.add_variable_op_names(vars_conf[param].name)
new_opt_confs.append(optimizer_conf)
return new_opt_confs
| 33.362694 | 131 | 0.55226 | import collections
from typing import Callable, Dict, Iterator, List, Union
import oneflow as flow
from oneflow.nn.parameter import Parameter
from .optimizer import Optimizer, ParamGroup
class SGD(Optimizer):
def __init__(
self,
parameters: Union[Iterator[Parameter], List[Dict]],
lr: float = 0.001,
momentum: float = 0.0,
weight_decay: float = 0.0,
):
assert lr >= 0.0, f"Invalid learning rate: {lr}"
assert momentum >= 0.0, f"Invalid momentum: {momentum}"
assert weight_decay >= 0.0, f"Invalid weight_decay: {weight_decay}"
options = dict()
options["lr"] = lr
options["momentum"] = momentum
options["weight_decay"] = weight_decay
super().__init__(parameters, options)
for param_group in self.param_groups:
for param in param_group.parameters:
assert param.is_leaf, "parameters must be leaf tensor"
self._state[param] = dict()
self._momentum_sgd = (
flow.builtin_op("momentum_update")
.Input("model")
.Input("model_diff")
.Input("momentum")
.Attr("l1", 0.0)
.Attr("weight_decay", 0.0)
.Build()
)
self._sgd = (
flow.builtin_op("sgd_update")
.Input("model")
.Input("model_diff")
.Attr("weight_decay", 0.0)
.Attr("l1", 0.0)
.Build()
)
def step(self, closure: Callable = None):
with flow.no_grad():
loss = None
if closure is not None:
loss = closure()
for param_group in self.param_groups:
lr = param_group["lr"]
l2 = param_group["weight_decay"]
for param in param_group.parameters:
if param.grad is None:
continue
if param_group["momentum"] == 0.0:
self._sgd(param, param.grad, learning_rate_val=lr, l2=l2)
else:
if "momentum_buf" not in self._state[param]:
self._state[param]["momentum_buf"] = flow.zeros_like(param)
momentum_buf = self._state[param]["momentum_buf"]
beta = param_group["momentum"]
self._momentum_sgd(
param,
param.grad,
momentum_buf,
learning_rate_val=lr,
l2=l2,
beta=beta,
)
self._state["step"] = self._state["step"] + 1
return loss
def _generate_conf_for_graph(self, train_conf, vars_conf):
new_opt_confs = []
for param_group in self.param_groups:
optimizer_conf = train_conf.mutable_optimizer_conf().Add()
lr = (
param_group["initial_lr"]
if "initial_lr" in param_group
else param_group["lr"]
)
beta = param_group["momentum"]
l2 = param_group["weight_decay"]
optimizer_conf.set_base_learning_rate(lr)
if beta == 0:
optimizer_conf.mutable_naive_conf()
else:
optimizer_conf.mutable_momentum_conf().set_beta(beta)
self._generate_grad_clip_conf_for_optim_conf(param_group, optimizer_conf)
for param in param_group.parameters:
vars_conf[param].l2 = l2
if param.requires_grad:
optimizer_conf.add_variable_op_names(vars_conf[param].name)
new_opt_confs.append(optimizer_conf)
return new_opt_confs
| true | true |
f726cff10848dfee859add52644fda3f040aa102 | 966 | py | Python | nms/benchmark/nms_numba_cpu.py | ForrestPi/ObjectDetection | 54e0821e73f67be5360c36f01229a123c34ab3b3 | [
"MIT"
] | 12 | 2020-03-25T01:24:22.000Z | 2021-09-18T06:40:16.000Z | nms/benchmark/nms_numba_cpu.py | ForrestPi/ObjectDetection | 54e0821e73f67be5360c36f01229a123c34ab3b3 | [
"MIT"
] | 1 | 2020-04-22T07:52:36.000Z | 2020-04-22T07:52:36.000Z | nms/benchmark/nms_numba_cpu.py | ForrestPi/ObjectDetection | 54e0821e73f67be5360c36f01229a123c34ab3b3 | [
"MIT"
] | 4 | 2020-03-25T01:24:26.000Z | 2020-09-20T11:29:09.000Z | from __future__ import absolute_import
import numba
import numpy as np
@numba.jit(nopython=True)
def nms_cpu(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return keep
if __name__ == "__main__":
bbox=np.load("bbox.npy")
print(bbox.shape)
keep=nms_cpu(bbox,0.7)
print(len(keep))
| 25.421053 | 59 | 0.519669 | from __future__ import absolute_import
import numba
import numpy as np
@numba.jit(nopython=True)
def nms_cpu(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1)
h = np.maximum(0.0, yy2 - yy1 + 1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return keep
if __name__ == "__main__":
bbox=np.load("bbox.npy")
print(bbox.shape)
keep=nms_cpu(bbox,0.7)
print(len(keep))
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.