code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import types
import time
from pandac.PandaModules import *
from direct.distributed.ClockDelta import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import ivalMgr
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedSmoothNode
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from direct.task import Task
from direct.fsm import ClassicFSM
from direct.fsm import State
from direct.showbase.PythonUtil import Functor, ScratchPad
from direct.showbase.InputStateGlobal import inputState
from otp.avatar import Avatar
from otp.avatar import DistributedAvatar
from otp.friends import FriendManager
from otp.login import TTAccount
from otp.login import AccountServerConstants
from otp.login import LoginScreen
from otp.login import LoginGSAccount
from otp.login import LoginGoAccount
from otp.login import LoginWebPlayTokenAccount
from otp.login import LoginTTAccount
from otp.login import HTTPUtil
from otp.distributed import OTPClientRepository
from otp.distributed import PotentialAvatar
from otp.distributed import PotentialShard
from otp.distributed import DistributedDistrict
from otp.distributed.OtpDoGlobals import *
from otp.distributed import OtpDoGlobals
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
from otp.otpbase import OTPLauncherGlobals
from otp.avatar.Avatar import teleportNotify
from toontown.toonbase.ToonBaseGlobal import *
from toontown.toonbase.ToontownGlobals import *
from toontown.launcher.DownloadForceAcknowledge import *
from toontown.distributed import DelayDelete
from toontown.friends import FriendHandle
from toontown.friends import FriendsListPanel
from toontown.friends import ToontownFriendSecret
from toontown.uberdog import TTSpeedchatRelay
from toontown.login import DateObject
from toontown.login import AccountServerDate
from toontown.login import AvatarChooser
from toontown.makeatoon import MakeAToon
from toontown.pets import DistributedPet, PetDetail, PetHandle
from toontown.toonbase import TTLocalizer
from toontown.toontowngui import TTDialog
from toontown.toon import LocalToon
from toontown.toon import ToonDNA
from toontown.distributed import ToontownDistrictStats
from toontown.makeatoon import TTPickANamePattern
from toontown.parties import ToontownTimeManager
from toontown.toon import Toon, DistributedToon
from ToontownMsgTypes import *
import HoodMgr
import PlayGame
from toontown.toontowngui import ToontownLoadingBlocker
from toontown.hood import StreetSign
class ToontownClientRepository(OTPClientRepository.OTPClientRepository):
SupportTutorial = 1
GameGlobalsId = OTP_DO_ID_TOONTOWN
SetZoneDoneEvent = 'TCRSetZoneDone'
EmuSetZoneDoneEvent = 'TCREmuSetZoneDone'
SetInterest = 'Set'
ClearInterest = 'Clear'
ClearInterestDoneEvent = 'TCRClearInterestDone'
KeepSubShardObjects = False
def __init__(self, serverVersion, launcher = None):
OTPClientRepository.OTPClientRepository.__init__(self, serverVersion, launcher, playGame=PlayGame.PlayGame)
self._playerAvDclass = self.dclassesByName['DistributedToon']
setInterfaceFont(TTLocalizer.InterfaceFont)
setSignFont(TTLocalizer.SignFont)
setFancyFont(TTLocalizer.FancyFont)
nameTagFontIndex = 0
for font in TTLocalizer.NametagFonts:
setNametagFont(nameTagFontIndex, TTLocalizer.NametagFonts[nameTagFontIndex])
nameTagFontIndex += 1
self.toons = {}
if self.http.getVerifySsl() != HTTPClient.VSNoVerify:
self.http.setVerifySsl(HTTPClient.VSNoDateCheck)
#prepareAvatar(self.http)
self.__forbidCheesyEffects = 0
self.friendManager = None
self.speedchatRelay = None
self.trophyManager = None
self.bankManager = None
self.catalogManager = None
self.welcomeValleyManager = None
self.newsManager = None
self.streetSign = None
self.distributedDistrict = None
self.partyManager = None
self.inGameNewsMgr = None
self.whitelistMgr = None
self.toontownTimeManager = ToontownTimeManager.ToontownTimeManager()
self.avatarFriendsManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_AVATAR_FRIENDS_MANAGER, 'AvatarFriendsManager')
self.playerFriendsManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_PLAYER_FRIENDS_MANAGER, 'TTPlayerFriendsManager')
self.speedchatRelay = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_SPEEDCHAT_RELAY, 'TTSpeedchatRelay')
self.deliveryManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_DELIVERY_MANAGER, 'DistributedDeliveryManager')
if config.GetBool('want-code-redemption', 1):
self.codeRedemptionManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_CODE_REDEMPTION_MANAGER, 'TTCodeRedemptionMgr')
self.streetSign = None
self.furnitureManager = None
self.objectManager = None
self.friendsMap = {}
self.friendsOnline = {}
self.friendsMapPending = 0
self.friendsListError = 0
self.friendPendingChatSettings = {}
self.elderFriendsMap = {}
self.__queryAvatarMap = {}
self.dateObject = DateObject.DateObject()
self.accountServerDate = AccountServerDate.AccountServerDate()
self.hoodMgr = HoodMgr.HoodMgr(self)
self.setZonesEmulated = 0
self.old_setzone_interest_handle = None
self.setZoneQueue = Queue()
self.accept(ToontownClientRepository.SetZoneDoneEvent, self._handleEmuSetZoneDone)
self._deletedSubShardDoIds = set()
self.toonNameDict = {}
self.gameFSM.addState(State.State('skipTutorialRequest', self.enterSkipTutorialRequest, self.exitSkipTutorialRequest, ['playGame', 'gameOff', 'tutorialQuestion']))
state = self.gameFSM.getStateNamed('waitOnEnterResponses')
state.addTransition('skipTutorialRequest')
state = self.gameFSM.getStateNamed('playGame')
state.addTransition('skipTutorialRequest')
self.wantCogdominiums = base.config.GetBool('want-cogdominiums', 1)
self.wantEmblems = base.config.GetBool('want-emblems', 0)
if base.config.GetBool('tt-node-check', 0):
for species in ToonDNA.toonSpeciesTypes:
for head in ToonDNA.getHeadList(species):
for torso in ToonDNA.toonTorsoTypes:
for legs in ToonDNA.toonLegTypes:
for gender in ('m', 'f'):
print 'species: %s, head: %s, torso: %s, legs: %s, gender: %s' % (species,
head,
torso,
legs,
gender)
dna = ToonDNA.ToonDNA()
dna.newToon((head,
torso,
legs,
gender))
toon = Toon.Toon()
try:
toon.setDNA(dna)
except Exception, e:
print e
return
def congratulations(self, avatarChoice):
self.acceptedScreen = loader.loadModel('phase_3/models/gui/toon_council')
self.acceptedScreen.setScale(0.667)
self.acceptedScreen.reparentTo(aspect2d)
buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui')
self.acceptedBanner = DirectLabel(parent=self.acceptedScreen, relief=None, text=OTPLocalizer.CRNameCongratulations, text_scale=0.18, text_fg=Vec4(0.6, 0.1, 0.1, 1), text_pos=(0, 0.05), text_font=getMinnieFont())
newName = avatarChoice.approvedName
self.acceptedText = DirectLabel(parent=self.acceptedScreen, relief=None, text=OTPLocalizer.CRNameAccepted % newName, text_scale=0.125, text_fg=Vec4(0, 0, 0, 1), text_pos=(0, -0.15))
self.okButton = DirectButton(parent=self.acceptedScreen, image=(buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr')), relief=None, text='Ok', scale=1.5, text_scale=0.05, text_pos=(0.0, -0.1), pos=(0, 0, -1), command=self.__handleCongrats, extraArgs=[avatarChoice])
buttons.removeNode()
base.transitions.noFade()
return
def __handleCongrats(self, avatarChoice):
self.acceptedBanner.destroy()
self.acceptedText.destroy()
self.okButton.destroy()
self.acceptedScreen.removeNode()
del self.acceptedScreen
del self.okButton
del self.acceptedText
del self.acceptedBanner
if not self.astronSupport:
datagram = PyDatagram()
datagram.addUint16(CLIENT_SET_WISHNAME_CLEAR)
datagram.addUint32(avatarChoice.id)
datagram.addUint8(1)
self.send(datagram)
self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice])
else:
self.astronLoginManager.sendAcknowledgeAvatarName(avatarChoice.id,
lambda: self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice]))
def betterlucknexttime(self, avList, index):
self.rejectDoneEvent = 'rejectDone'
self.rejectDialog = TTDialog.TTGlobalDialog(doneEvent=self.rejectDoneEvent, message=TTLocalizer.NameShopNameRejected, style=TTDialog.Acknowledge)
self.rejectDialog.show()
self.acceptOnce(self.rejectDoneEvent, self.__handleReject, [avList, index])
base.transitions.noFade()
def __handleReject(self, avList, index):
self.rejectDialog.cleanup()
if not self.astronSupport:
datagram = PyDatagram()
datagram.addUint16(CLIENT_SET_WISHNAME_CLEAR)
avid = 0
for k in avList:
if k.position == index:
avid = k.id
if avid == 0:
self.notify.error('Avatar rejected not found in avList. Index is: ' + str(index))
if not self.astronSupport:
datagram.addUint32(avid)
datagram.addUint8(0)
self.send(datagram)
self.loginFSM.request('waitForAvatarList')
else:
self.astronLoginManager.sendAcknowledgeAvatarName(avId, lambda: self.loginFSM.request('waitForAvatarList'))
def enterChooseAvatar(self, avList):
ModelPool.garbageCollect()
TexturePool.garbageCollect()
self.sendSetAvatarIdMsg(0)
self.clearFriendState()
if self.music == None and base.musicManagerIsValid:
self.music = base.musicManager.getSound('phase_3/audio/bgm/tt_theme.mid')
if self.music:
self.music.setLoop(1)
self.music.setVolume(0.9)
self.music.play()
base.playMusic(self.music, looping=1, volume=0.9, interrupt=None)
self.handler = self.handleMessageType
self.avChoiceDoneEvent = 'avatarChooserDone'
self.avChoice = AvatarChooser.AvatarChooser(avList, self.loginFSM, self.avChoiceDoneEvent)
self.avChoice.load(self.isPaid())
self.avChoice.enter()
self.accept(self.avChoiceDoneEvent, self.__handleAvatarChooserDone, [avList])
if config.GetBool('want-gib-loader', 1):
self.loadingBlocker = ToontownLoadingBlocker.ToontownLoadingBlocker(avList)
return
def __handleAvatarChooserDone(self, avList, doneStatus):
done = doneStatus['mode']
if done == 'exit':
if not launcher.isDummy() and launcher.VISTA:
if not self.isPaid():
self.loginFSM.request('shutdown', [OTPLauncherGlobals.ExitUpsell])
else:
self.loginFSM.request('shutdown')
else:
self.loginFSM.request('shutdown')
return
index = self.avChoice.getChoice()
for av in avList:
if av.position == index:
avatarChoice = av
self.notify.info('================')
self.notify.info('Chose avatar id: %s' % av.id)
self.notify.info('Chose avatar name: %s' % av.name)
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(av.dna)
if base.logPrivateInfo:
self.notify.info('Chose avatar dna: %s' % (dna.asTuple(),))
self.notify.info('Chose avatar position: %s' % av.position)
self.notify.info('isPaid: %s' % self.isPaid())
self.notify.info('freeTimeLeft: %s' % self.freeTimeLeft())
self.notify.info('allowSecretChat: %s' % self.allowSecretChat())
self.notify.info('================')
if done == 'chose':
self.avChoice.exit()
if avatarChoice.approvedName != '':
self.congratulations(avatarChoice)
avatarChoice.approvedName = ''
elif avatarChoice.rejectedName != '':
avatarChoice.rejectedName = ''
self.betterlucknexttime(avList, index)
else:
self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice])
elif done == 'nameIt':
self.accept('downloadAck-response', self.__handleDownloadAck, [avList, index])
self.downloadAck = DownloadForceAcknowledge('downloadAck-response')
self.downloadAck.enter(4)
elif done == 'create':
self.loginFSM.request('createAvatar', [avList, index])
elif done == 'delete':
self.loginFSM.request('waitForDeleteAvatarResponse', [avatarChoice])
def __handleDownloadAck(self, avList, index, doneStatus):
if doneStatus['mode'] == 'complete':
self.goToPickAName(avList, index)
else:
self.loginFSM.request('chooseAvatar', [avList])
self.downloadAck.exit()
self.downloadAck = None
self.ignore('downloadAck-response')
return
def exitChooseAvatar(self):
self.handler = None
self.avChoice.exit()
self.avChoice.unload()
self.avChoice = None
self.ignore(self.avChoiceDoneEvent)
return
def goToPickAName(self, avList, index):
self.avChoice.exit()
self.loginFSM.request('createAvatar', [avList, index])
def enterCreateAvatar(self, avList, index, newDNA = None):
if self.music:
self.music.stop()
self.music = None
if newDNA != None:
self.newPotAv = PotentialAvatar.PotentialAvatar('deleteMe', ['',
'',
'',
''], newDNA.makeNetString(), index, 1)
avList.append(self.newPotAv)
base.transitions.noFade()
self.avCreate = MakeAToon.MakeAToon(self.loginFSM, avList, 'makeAToonComplete', index, self.isPaid())
self.avCreate.load()
self.avCreate.enter()
if not self.astronSupport:
self.handler = self.handleCreateAvatar
self.accept('makeAToonComplete', self.__handleMakeAToon, [avList, index])
self.accept('nameShopCreateAvatar', self.sendCreateAvatarMsg)
self.accept('nameShopPost', self.relayMessage)
return
def relayMessage(self, dg):
self.send(dg)
def handleCreateAvatar(self, msgType, di):
if msgType == CLIENT_CREATE_AVATAR_RESP or msgType == CLIENT_SET_NAME_PATTERN_ANSWER or msgType == CLIENT_SET_WISHNAME_RESP:
self.avCreate.ns.nameShopHandler(msgType, di)
else:
self.handleMessageType(msgType, di)
def __handleMakeAToon(self, avList, avPosition):
done = self.avCreate.getDoneStatus()
if done == 'cancel':
if hasattr(self, 'newPotAv'):
if self.newPotAv in avList:
avList.remove(self.newPotAv)
self.avCreate.exit()
self.loginFSM.request('chooseAvatar', [avList])
elif done == 'created':
self.avCreate.exit()
if not base.launcher or base.launcher.getPhaseComplete(3.5):
for i in avList:
if i.position == avPosition:
newPotAv = i
self.loginFSM.request('waitForSetAvatarResponse', [newPotAv])
else:
self.loginFSM.request('chooseAvatar', [avList])
else:
self.notify.error('Invalid doneStatus from MakeAToon: ' + str(done))
def exitCreateAvatar(self):
self.ignore('makeAToonComplete')
self.ignore('nameShopPost')
self.ignore('nameShopCreateAvatar')
self.avCreate.unload()
self.avCreate = None
self.handler = None
if hasattr(self, 'newPotAv'):
del self.newPotAv
return
if not config.GetBool('astron-support', True):
def handleAvatarResponseMsg(self, di):
self.cleanupWaitingForDatabase()
avatarId = di.getUint32()
returnCode = di.getUint8()
if returnCode == 0:
dclass = self.dclassesByName['DistributedToon']
NametagGlobals.setMasterArrowsOn(0)
loader.beginBulkLoad('localAvatarPlayGame', OTPLocalizer.CREnteringToontown, 400, 1, TTLocalizer.TIP_GENERAL)
localAvatar = LocalToon.LocalToon(self)
localAvatar.dclass = dclass
base.localAvatar = localAvatar
__builtins__['localAvatar'] = base.localAvatar
NametagGlobals.setToon(base.localAvatar)
localAvatar.doId = avatarId
self.localAvatarDoId = avatarId
parentId = None
zoneId = None
localAvatar.setLocation(parentId, zoneId)
localAvatar.generateInit()
localAvatar.generate()
localAvatar.updateAllRequiredFields(dclass, di)
self.doId2do[avatarId] = localAvatar
localAvatar.initInterface()
self.sendGetFriendsListRequest()
self.loginFSM.request('playingGame')
else:
self.notify.error('Bad avatar: return code %d' % returnCode)
return
else:
def handleAvatarResponseMsg(self, avatarId, di):
self.cleanupWaitingForDatabase()
dclass = self.dclassesByName['DistributedToon']
NametagGlobals.setMasterArrowsOn(0)
loader.beginBulkLoad('localAvatarPlayGame', OTPLocalizer.CREnteringToontown, 400, 1, TTLocalizer.TIP_GENERAL)
localAvatar = LocalToon.LocalToon(self)
localAvatar.dclass = dclass
base.localAvatar = localAvatar
__builtins__['localAvatar'] = base.localAvatar
NametagGlobals.setToon(base.localAvatar)
localAvatar.doId = avatarId
self.localAvatarDoId = avatarId
parentId = None
zoneId = None
localAvatar.setLocation(parentId, zoneId)
localAvatar.generateInit()
localAvatar.generate()
dclass.receiveUpdateBroadcastRequiredOwner(localAvatar, di)
localAvatar.announceGenerate()
localAvatar.postGenerateMessage()
self.doId2do[avatarId] = localAvatar
localAvatar.initInterface()
self.sendGetFriendsListRequest()
self.loginFSM.request('playingGame')
def getAvatarDetails(self, avatar, func, *args):
pad = ScratchPad()
pad.func = func
pad.args = args
pad.avatar = avatar
pad.delayDelete = DelayDelete.DelayDelete(avatar, 'getAvatarDetails')
avId = avatar.doId
self.__queryAvatarMap[avId] = pad
self.__sendGetAvatarDetails(avId)
def cancelAvatarDetailsRequest(self, avatar):
avId = avatar.doId
if self.__queryAvatarMap.has_key(avId):
pad = self.__queryAvatarMap.pop(avId)
pad.delayDelete.destroy()
def __sendGetAvatarDetails(self, avId):
datagram = PyDatagram()
avatar = self.__queryAvatarMap[avId].avatar
datagram.addUint16(avatar.getRequestID())
datagram.addUint32(avId)
self.send(datagram)
def handleGetAvatarDetailsResp(self, di):
avId = di.getUint32()
returnCode = di.getUint8()
self.notify.info('Got query response for avatar %d, code = %d.' % (avId, returnCode))
try:
pad = self.__queryAvatarMap[avId]
except:
self.notify.warning('Received unexpected or outdated details for avatar %d.' % avId)
return
del self.__queryAvatarMap[avId]
gotData = 0
if returnCode != 0:
self.notify.warning('No information available for avatar %d.' % avId)
else:
dclassName = pad.args[0]
dclass = self.dclassesByName[dclassName]
pad.avatar.updateAllRequiredFields(dclass, di)
gotData = 1
if isinstance(pad.func, types.StringType):
messenger.send(pad.func, list((gotData, pad.avatar) + pad.args))
else:
apply(pad.func, (gotData, pad.avatar) + pad.args)
pad.delayDelete.destroy()
def enterPlayingGame(self, *args, **kArgs):
OTPClientRepository.OTPClientRepository.enterPlayingGame(self, *args, **kArgs)
self.gameFSM.request('waitOnEnterResponses', [None,
base.localAvatar.defaultZone,
base.localAvatar.defaultZone,
-1])
self._userLoggingOut = False
if not self.streetSign:
self.streetSign = StreetSign.StreetSign()
return
def exitPlayingGame(self):
ivalMgr.interrupt()
if self.objectManager != None:
self.objectManager.destroy()
self.objectManager = None
ToontownFriendSecret.unloadFriendSecret()
FriendsListPanel.unloadFriendsList()
messenger.send('cancelFriendInvitation')
base.removeGlitchMessage()
taskMgr.remove('avatarRequestQueueTask')
OTPClientRepository.OTPClientRepository.exitPlayingGame(self)
if hasattr(base, 'localAvatar'):
camera.reparentTo(render)
camera.setPos(0, 0, 0)
camera.setHpr(0, 0, 0)
del self.doId2do[base.localAvatar.getDoId()]
if base.localAvatar.getDelayDeleteCount() != 0:
self.notify.error('could not delete localAvatar, delayDeletes=%s' % (base.localAvatar.getDelayDeleteNames(),))
base.localAvatar.deleteOrDelay()
base.localAvatar.detectLeaks()
NametagGlobals.setToon(base.cam)
del base.localAvatar
del __builtins__['localAvatar']
loader.abortBulkLoad()
base.transitions.noTransitions()
if self._userLoggingOut:
self.detectLeaks(okTasks=[], okEvents=['destroy-ToontownLoadingScreenTitle', 'destroy-ToontownLoadingScreenTip', 'destroy-ToontownLoadingScreenWaitBar'])
return
def enterGameOff(self):
OTPClientRepository.OTPClientRepository.enterGameOff(self)
def enterWaitOnEnterResponses(self, shardId, hoodId, zoneId, avId):
self.resetDeletedSubShardDoIds()
OTPClientRepository.OTPClientRepository.enterWaitOnEnterResponses(self, shardId, hoodId, zoneId, avId)
def enterSkipTutorialRequest(self, hoodId, zoneId, avId):
self.handlerArgs = {'hoodId': hoodId,
'zoneId': zoneId,
'avId': avId}
if not self.astronSupport:
self.handler = self.handleTutorialQuestion
self.__requestSkipTutorial(hoodId, zoneId, avId)
def __requestSkipTutorial(self, hoodId, zoneId, avId):
self.notify.debug('requesting skip tutorial')
self.acceptOnce('skipTutorialAnswered', self.__handleSkipTutorialAnswered, [hoodId, zoneId, avId])
messenger.send('requestSkipTutorial')
self.waitForDatabaseTimeout(requestName='RequestSkipTutorial')
def __handleSkipTutorialAnswered(self, hoodId, zoneId, avId, allOk):
if allOk:
hoodId = self.handlerArgs['hoodId']
zoneId = self.handlerArgs['zoneId']
avId = self.handlerArgs['avId']
self.gameFSM.request('playGame', [hoodId, zoneId, avId])
else:
self.notify.warning('allOk is false on skip tutorial, forcing the tutorial.')
self.gameFSM.request('tutorialQuestion', [hoodId, zoneId, avId])
def exitSkipTutorialRequest(self):
self.cleanupWaitingForDatabase()
self.handler = None
self.handlerArgs = None
self.ignore('skipTutorialAnswered')
return
def enterTutorialQuestion(self, hoodId, zoneId, avId):
if not self.astronSupport:
self.handler = self.handleTutorialQuestion
self.__requestTutorial(hoodId, zoneId, avId)
def handleTutorialQuestion(self, msgType, di):
if msgType == CLIENT_CREATE_OBJECT_REQUIRED:
self.handleGenerateWithRequired(di)
elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:
self.handleGenerateWithRequiredOther(di)
elif msgType == CLIENT_OBJECT_UPDATE_FIELD:
self.handleUpdateField(di)
elif msgType == CLIENT_OBJECT_DISABLE_RESP:
self.handleDisable(di)
elif msgType == CLIENT_OBJECT_DELETE_RESP:
self.handleDelete(di)
elif msgType == CLIENT_GET_FRIEND_LIST_RESP:
self.handleGetFriendsList(di)
elif msgType == CLIENT_GET_FRIEND_LIST_EXTENDED_RESP:
self.handleGetFriendsListExtended(di)
elif msgType == CLIENT_FRIEND_ONLINE:
self.handleFriendOnline(di)
elif msgType == CLIENT_FRIEND_OFFLINE:
self.handleFriendOffline(di)
elif msgType == CLIENT_GET_AVATAR_DETAILS_RESP:
self.handleGetAvatarDetailsResp(di)
else:
self.handleMessageType(msgType, di)
def __requestTutorial(self, hoodId, zoneId, avId):
self.notify.debug('requesting tutorial')
self.acceptOnce('startTutorial', self.__handleStartTutorial, [avId])
messenger.send('requestTutorial')
self.waitForDatabaseTimeout(requestName='RequestTutorial')
def __handleStartTutorial(self, avId, zoneId):
self.gameFSM.request('playGame', [Tutorial, zoneId, avId])
def exitTutorialQuestion(self):
self.cleanupWaitingForDatabase()
self.handler = None
self.handlerArgs = None
self.ignore('startTutorial')
taskMgr.remove('waitingForTutorial')
return
def enterSwitchShards(self, shardId, hoodId, zoneId, avId):
OTPClientRepository.OTPClientRepository.enterSwitchShards(self, shardId, hoodId, zoneId, avId)
self.handler = self.handleCloseShard
def exitSwitchShards(self):
OTPClientRepository.OTPClientRepository.exitSwitchShards(self)
self.ignore(ToontownClientRepository.ClearInterestDoneEvent)
self.handler = None
return
def enterCloseShard(self, loginState = None):
OTPClientRepository.OTPClientRepository.enterCloseShard(self, loginState)
self.handler = self.handleCloseShard
self._removeLocalAvFromStateServer()
if not config.GetBool('astron-support', True):
def handleCloseShard(self, msgType, di):
if msgType == CLIENT_CREATE_OBJECT_REQUIRED:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_OBJECT_UPDATE_FIELD:
di2 = PyDatagramIterator(di)
doId = di2.getUint32()
if self._doIdIsOnCurrentShard(doId):
return
self.handleMessageType(msgType, di)
else:
def handleCloseShard(self, msgType, di):
if msgType == CLIENT_ENTER_OBJECT_REQUIRED:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED_OTHER:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_OBJECT_SET_FIELD:
di2 = PyDatagramIterator(di)
doId = di2.getUint32()
if self._doIdIsOnCurrentShard(doId):
return
self.handleMessageType(msgType, di)
def _logFailedDisable(self, doId, ownerView):
if doId not in self.doId2do and doId in self._deletedSubShardDoIds:
return
OTPClientRepository.OTPClientRepository._logFailedDisable(self, doId, ownerView)
def exitCloseShard(self):
OTPClientRepository.OTPClientRepository.exitCloseShard(self)
self.ignore(ToontownClientRepository.ClearInterestDoneEvent)
self.handler = None
return
def isShardInterestOpen(self):
return self.old_setzone_interest_handle is not None or self.uberZoneInterest is not None
def resetDeletedSubShardDoIds(self):
self._deletedSubShardDoIds.clear()
def dumpAllSubShardObjects(self):
if self.KeepSubShardObjects:
return
isNotLive = not base.cr.isLive()
if isNotLive:
try:
localAvatar
except:
self.notify.info('dumpAllSubShardObjects')
else:
self.notify.info('dumpAllSubShardObjects: defaultShard is %s' % localAvatar.defaultShard)
ignoredClasses = ('MagicWordManager', 'TimeManager', 'DistributedDistrict', 'FriendManager', 'NewsManager', 'ToontownMagicWordManager', 'WelcomeValleyManager', 'DistributedTrophyMgr', 'CatalogManager', 'DistributedBankMgr', 'EstateManager', 'RaceManager', 'SafeZoneManager', 'DeleteManager', 'TutorialManager', 'ToontownDistrict', 'DistributedDeliveryManager', 'DistributedPartyManager', 'AvatarFriendsManager', 'InGameNewsMgr', 'WhitelistMgr', 'TTCodeRedemptionMgr')
messenger.send('clientCleanup')
for avId, pad in self.__queryAvatarMap.items():
pad.delayDelete.destroy()
self.__queryAvatarMap = {}
delayDeleted = []
doIds = self.doId2do.keys()
for doId in doIds:
obj = self.doId2do[doId]
if isNotLive:
ignoredClass = obj.__class__.__name__ in ignoredClasses
if not ignoredClass and obj.parentId != localAvatar.defaultShard:
self.notify.info('dumpAllSubShardObjects: %s %s parent %s is not defaultShard' % (obj.__class__.__name__, obj.doId, obj.parentId))
if obj.parentId == localAvatar.defaultShard and obj is not localAvatar:
if obj.neverDisable:
if isNotLive:
if not ignoredClass:
self.notify.warning('dumpAllSubShardObjects: neverDisable set for %s %s' % (obj.__class__.__name__, obj.doId))
else:
self.deleteObject(doId)
self._deletedSubShardDoIds.add(doId)
if obj.getDelayDeleteCount() != 0:
delayDeleted.append(obj)
delayDeleteLeaks = []
for obj in delayDeleted:
if obj.getDelayDeleteCount() != 0:
delayDeleteLeaks.append(obj)
if len(delayDeleteLeaks):
s = 'dumpAllSubShardObjects:'
for obj in delayDeleteLeaks:
s += '\n could not delete %s (%s), delayDeletes=%s' % (safeRepr(obj), itype(obj), obj.getDelayDeleteNames())
self.notify.error(s)
if isNotLive:
self.notify.info('dumpAllSubShardObjects: doIds left: %s' % self.doId2do.keys())
def _removeCurrentShardInterest(self, callback):
if self.old_setzone_interest_handle is None:
self.notify.warning('removeToontownShardInterest: no shard interest open')
callback()
return
self.acceptOnce(ToontownClientRepository.ClearInterestDoneEvent, Functor(self._tcrRemoveUberZoneInterest, callback))
self._removeEmulatedSetZone(ToontownClientRepository.ClearInterestDoneEvent)
return
def _tcrRemoveUberZoneInterest(self, callback):
self.acceptOnce(ToontownClientRepository.ClearInterestDoneEvent, Functor(self._tcrRemoveShardInterestDone, callback))
self.removeInterest(self.uberZoneInterest, ToontownClientRepository.ClearInterestDoneEvent)
def _tcrRemoveShardInterestDone(self, callback):
self.uberZoneInterest = None
callback()
return
def _doIdIsOnCurrentShard(self, doId):
if doId == base.localAvatar.defaultShard:
return True
do = self.getDo(doId)
if do:
if do.parentId == base.localAvatar.defaultShard:
return True
return False
def _wantShardListComplete(self):
print self.activeDistrictMap
if self._shardsAreReady():
self.acceptOnce(ToontownDistrictStats.EventName(), self.shardDetailStatsComplete)
ToontownDistrictStats.refresh()
else:
self.loginFSM.request('noShards')
def shardDetailStatsComplete(self):
self.loginFSM.request('waitForAvatarList')
def exitWaitForShardList(self):
self.ignore(ToontownDistrictStats.EventName())
OTPClientRepository.OTPClientRepository.exitWaitForShardList(self)
def fillUpFriendsMap(self):
if self.isFriendsMapComplete():
return 1
if not self.friendsMapPending and not self.friendsListError:
self.notify.warning('Friends list stale; fetching new list.')
self.sendGetFriendsListRequest()
return 0
def isFriend(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
self.identifyFriend(doId)
return 1
return 0
def isAvatarFriend(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
self.identifyFriend(doId)
return 1
return 0
def getFriendFlags(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
return flags
return 0
def isFriendOnline(self, doId):
return self.friendsOnline.has_key(doId)
def addAvatarToFriendsList(self, avatar):
self.friendsMap[avatar.doId] = avatar
def identifyFriend(self, doId, source = None):
if self.friendsMap.has_key(doId):
teleportNotify.debug('friend %s in friendsMap' % doId)
return self.friendsMap[doId]
avatar = None
if self.doId2do.has_key(doId):
teleportNotify.debug('found friend %s in doId2do' % doId)
avatar = self.doId2do[doId]
elif self.cache.contains(doId):
teleportNotify.debug('found friend %s in cache' % doId)
avatar = self.cache.dict[doId]
elif self.playerFriendsManager.getAvHandleFromId(doId):
teleportNotify.debug('found friend %s in playerFriendsManager' % doId)
avatar = base.cr.playerFriendsManager.getAvHandleFromId(doId)
else:
self.notify.warning("Don't know who friend %s is." % doId)
return
if not ((isinstance(avatar, DistributedToon.DistributedToon) and avatar.__class__ is DistributedToon.DistributedToon) or isinstance(avatar, DistributedPet.DistributedPet)):
self.notify.warning('friendsNotify%s: invalid friend object %s' % (choice(source, '(%s)' % source, ''), doId))
return
if base.wantPets:
if avatar.isPet():
if avatar.bFake:
handle = PetHandle.PetHandle(avatar)
else:
handle = avatar
else:
handle = FriendHandle.FriendHandle(doId, avatar.getName(), avatar.style, avatar.getPetId())
else:
handle = FriendHandle.FriendHandle(doId, avatar.getName(), avatar.style, '')
teleportNotify.debug('adding %s to friendsMap' % doId)
self.friendsMap[doId] = handle
return handle
def identifyPlayer(self, pId):
return base.cr.playerFriendsManager.getFriendInfo(pId)
def identifyAvatar(self, doId):
if self.doId2do.has_key(doId):
return self.doId2do[doId]
else:
return self.identifyFriend(doId)
def isFriendsMapComplete(self):
for friendId, flags in base.localAvatar.friendsList:
if self.identifyFriend(friendId) == None:
return 0
if base.wantPets and base.localAvatar.hasPet():
print str(self.friendsMap)
print str(self.friendsMap.has_key(base.localAvatar.getPetId()))
if self.friendsMap.has_key(base.localAvatar.getPetId()) == None:
return 0
return 1
def removeFriend(self, avatarId):
base.localAvatar.sendUpdate('friendsNotify', [base.localAvatar.doId, 1], sendToId=avatarId)
datagram = PyDatagram()
datagram.addUint16(CLIENT_REMOVE_FRIEND)
datagram.addUint32(avatarId)
self.send(datagram)
self.estateMgr.removeFriend(base.localAvatar.doId, avatarId)
for pair in base.localAvatar.friendsList:
friendId = pair[0]
if friendId == avatarId:
base.localAvatar.friendsList.remove(pair)
return
def clearFriendState(self):
self.friendsMap = {}
self.friendsOnline = {}
self.friendsMapPending = 0
self.friendsListError = 0
def sendGetFriendsListRequest(self):
if self.astronSupport:
print 'sendGetFriendsListRequest TODO'
else:
self.friendsMapPending = 1
self.friendsListError = 0
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST)
self.send(datagram)
def cleanPetsFromFriendsMap(self):
for objId, obj in self.friendsMap.items():
from toontown.pets import DistributedPet
if isinstance(obj, DistributedPet.DistributedPet):
print 'Removing %s reference from the friendsMap' % obj.getName()
del self.friendsMap[objId]
def removePetFromFriendsMap(self):
doId = base.localAvatar.getPetId()
if doId and self.friendsMap.has_key(doId):
del self.friendsMap[doId]
def addPetToFriendsMap(self, callback = None):
doId = base.localAvatar.getPetId()
if not doId or self.friendsMap.has_key(doId):
if callback:
callback()
return
def petDetailsCallback(petAvatar):
handle = PetHandle.PetHandle(petAvatar)
self.friendsMap[doId] = handle
petAvatar.disable()
petAvatar.delete()
if callback:
callback()
if self._proactiveLeakChecks:
petAvatar.detectLeaks()
PetDetail.PetDetail(doId, petDetailsCallback)
def handleGetFriendsList(self, di):
error = di.getUint8()
if error:
self.notify.warning('Got error return from friends list.')
self.friendsListError = 1
else:
count = di.getUint16()
for i in range(0, count):
doId = di.getUint32()
name = di.getString()
dnaString = di.getString()
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(dnaString)
petId = di.getUint32()
handle = FriendHandle.FriendHandle(doId, name, dna, petId)
self.friendsMap[doId] = handle
if self.friendsOnline.has_key(doId):
self.friendsOnline[doId] = handle
if self.friendPendingChatSettings.has_key(doId):
self.notify.debug('calling setCommonAndWL %s' % str(self.friendPendingChatSettings[doId]))
handle.setCommonAndWhitelistChatFlags(*self.friendPendingChatSettings[doId])
if base.wantPets and base.localAvatar.hasPet():
def handleAddedPet():
self.friendsMapPending = 0
messenger.send('friendsMapComplete')
self.addPetToFriendsMap(handleAddedPet)
return
self.friendsMapPending = 0
messenger.send('friendsMapComplete')
def handleGetFriendsListExtended(self, di):
avatarHandleList = []
error = di.getUint8()
if error:
self.notify.warning('Got error return from friends list extended.')
else:
count = di.getUint16()
for i in range(0, count):
abort = 0
doId = di.getUint32()
name = di.getString()
if name == '':
abort = 1
dnaString = di.getString()
if dnaString == '':
abort = 1
else:
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(dnaString)
petId = di.getUint32()
if not abort:
handle = FriendHandle.FriendHandle(doId, name, dna, petId)
avatarHandleList.append(handle)
if avatarHandleList:
messenger.send('gotExtraFriendHandles', [avatarHandleList])
def handleFriendOnline(self, di):
doId = di.getUint32()
commonChatFlags = 0
whitelistChatFlags = 0
if di.getRemainingSize() > 0:
commonChatFlags = di.getUint8()
if di.getRemainingSize() > 0:
whitelistChatFlags = di.getUint8()
self.notify.debug('Friend %d now online. common=%d whitelist=%d' % (doId, commonChatFlags, whitelistChatFlags))
if not self.friendsOnline.has_key(doId):
self.friendsOnline[doId] = self.identifyFriend(doId)
messenger.send('friendOnline', [doId, commonChatFlags, whitelistChatFlags])
if not self.friendsOnline[doId]:
self.friendPendingChatSettings[doId] = (commonChatFlags, whitelistChatFlags)
def handleFriendOffline(self, di):
doId = di.getUint32()
self.notify.debug('Friend %d now offline.' % doId)
try:
del self.friendsOnline[doId]
messenger.send('friendOffline', [doId])
except:
pass
def getFirstBattle(self):
from toontown.battle import DistributedBattleBase
for dobj in self.doId2do.values():
if isinstance(dobj, DistributedBattleBase.DistributedBattleBase):
return dobj
def forbidCheesyEffects(self, forbid):
wasAllowed = self.__forbidCheesyEffects != 0
if forbid:
self.__forbidCheesyEffects += 1
else:
self.__forbidCheesyEffects -= 1
isAllowed = self.__forbidCheesyEffects != 0
if wasAllowed != isAllowed:
for av in Avatar.Avatar.ActiveAvatars:
if hasattr(av, 'reconsiderCheesyEffect'):
av.reconsiderCheesyEffect()
base.localAvatar.reconsiderCheesyEffect()
def areCheesyEffectsAllowed(self):
return self.__forbidCheesyEffects == 0
def getNextSetZoneDoneEvent(self):
return '%s-%s' % (ToontownClientRepository.EmuSetZoneDoneEvent, self.setZonesEmulated + 1)
def getLastSetZoneDoneEvent(self):
return '%s-%s' % (ToontownClientRepository.EmuSetZoneDoneEvent, self.setZonesEmulated)
def getQuietZoneLeftEvent(self):
return 'leftQuietZone-%s' % (id(self),)
def sendSetZoneMsg(self, zoneId, visibleZoneList = None):
event = self.getNextSetZoneDoneEvent()
self.setZonesEmulated += 1
parentId = base.localAvatar.defaultShard
self.sendSetLocation(base.localAvatar.doId, parentId, zoneId)
localAvatar.setLocation(parentId, zoneId)
interestZones = zoneId
if visibleZoneList is not None:
interestZones = visibleZoneList
self._addInterestOpToQueue(ToontownClientRepository.SetInterest, [parentId, interestZones, 'OldSetZoneEmulator'], event)
return
def resetInterestStateForConnectionLoss(self):
OTPClientRepository.OTPClientRepository.resetInterestStateForConnectionLoss(self)
self.old_setzone_interest_handle = None
self.setZoneQueue.clear()
return
def _removeEmulatedSetZone(self, doneEvent):
self._addInterestOpToQueue(ToontownClientRepository.ClearInterest, None, doneEvent)
return
def _addInterestOpToQueue(self, op, args, event):
self.setZoneQueue.push([op, args, event])
if len(self.setZoneQueue) == 1:
self._sendNextSetZone()
def _sendNextSetZone(self):
op, args, event = self.setZoneQueue.top()
if op == ToontownClientRepository.SetInterest:
parentId, interestZones, name = args
if self.old_setzone_interest_handle == None:
self.old_setzone_interest_handle = self.addInterest(parentId, interestZones, name, ToontownClientRepository.SetZoneDoneEvent)
else:
self.alterInterest(self.old_setzone_interest_handle, parentId, interestZones, name, ToontownClientRepository.SetZoneDoneEvent)
elif op == ToontownClientRepository.ClearInterest:
self.removeInterest(self.old_setzone_interest_handle, ToontownClientRepository.SetZoneDoneEvent)
self.old_setzone_interest_handle = None
else:
self.notify.error('unknown setZone op: %s' % op)
return
def _handleEmuSetZoneDone(self):
op, args, event = self.setZoneQueue.pop()
queueIsEmpty = self.setZoneQueue.isEmpty()
if event is not None:
if not base.killInterestResponse:
messenger.send(event)
elif not hasattr(self, '_dontSendSetZoneDone'):
import random
if random.random() < 0.05:
self._dontSendSetZoneDone = True
else:
messenger.send(event)
if not queueIsEmpty:
self._sendNextSetZone()
return
def _isPlayerDclass(self, dclass):
return dclass == self._playerAvDclass
def _isValidPlayerLocation(self, parentId, zoneId):
if not self.distributedDistrict:
return False
if parentId != self.distributedDistrict.doId:
return False
if parentId == self.distributedDistrict.doId and zoneId == OTPGlobals.UberZone:
return False
return True
def sendQuietZoneRequest(self):
if self.astronSupport:
self.sendSetZoneMsg(OTPGlobals.QuietZone, [])
else:
self.sendSetZoneMsg(OTPGlobals.QuietZone)
if not config.GetBool('astron-support', True):
def handleQuietZoneGenerateWithRequired(self, di):
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
doId = di.getUint32()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleQuietZoneGenerateWithRequiredOther(self, di):
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
doId = di.getUint32()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
else:
def handleQuietZoneGenerateWithRequired(self, di):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleQuietZoneGenerateWithRequiredOther(self, di):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleGenerateWithRequiredOtherOwner(self, di):
# OwnerViews are only used for LocalToon in Toontown.
if self.loginFSM.getCurrentState().getName() == 'waitForSetAvatarResponse':
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
self.handleAvatarResponseMsg(doId, di)
def handleQuietZoneUpdateField(self, di):
di2 = DatagramIterator(di)
doId = di2.getUint32()
if doId in self.deferredDoIds:
args, deferrable, dg0, updates = self.deferredDoIds[doId]
dclass = args[2]
if not dclass.getClassDef().neverDisable:
return
else:
do = self.getDo(doId)
if do:
if not do.neverDisable:
return
OTPClientRepository.OTPClientRepository.handleUpdateField(self, di)
def handleDelete(self, di):
doId = di.getUint32()
self.deleteObject(doId)
def deleteObject(self, doId, ownerView = False):
if self.doId2do.has_key(doId):
obj = self.doId2do[doId]
del self.doId2do[doId]
obj.deleteOrDelay()
if obj.getDelayDeleteCount() <= 0:
obj.detectLeaks()
elif self.cache.contains(doId):
self.cache.delete(doId)
else:
ClientRepository.notify.warning('Asked to delete non-existent DistObj ' + str(doId))
def _abandonShard(self):
for doId, obj in self.doId2do.items():
if obj.parentId == localAvatar.defaultShard and obj is not localAvatar:
self.deleteObject(doId)
def askAvatarKnown(self, avId):
if not hasattr(base, 'localAvatar'):
return 0
for friendPair in base.localAvatar.friendsList:
if friendPair[0] == avId:
return 1
return 0
def requestAvatarInfo(self, avId):
if avId == 0:
return
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST_EXTENDED)
datagram.addUint16(1)
datagram.addUint32(avId)
base.cr.send(datagram)
def queueRequestAvatarInfo(self, avId):
removeTask = 0
if not hasattr(self, 'avatarInfoRequests'):
self.avatarInfoRequests = []
if self.avatarInfoRequests:
taskMgr.remove('avatarRequestQueueTask')
if avId not in self.avatarInfoRequests:
self.avatarInfoRequests.append(avId)
taskMgr.doMethodLater(0.1, self.sendAvatarInfoRequests, 'avatarRequestQueueTask')
def sendAvatarInfoRequests(self, task = None):
print 'Sending request Queue for AV Handles'
if not hasattr(self, 'avatarInfoRequests'):
return
if len(self.avatarInfoRequests) == 0:
return
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST_EXTENDED)
datagram.addUint16(len(self.avatarInfoRequests))
for avId in self.avatarInfoRequests:
datagram.addUint32(avId)
base.cr.send(datagram) | toontown/distributed/ToontownClientRepository.py | import types
import time
from pandac.PandaModules import *
from direct.distributed.ClockDelta import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import ivalMgr
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedSmoothNode
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from direct.task import Task
from direct.fsm import ClassicFSM
from direct.fsm import State
from direct.showbase.PythonUtil import Functor, ScratchPad
from direct.showbase.InputStateGlobal import inputState
from otp.avatar import Avatar
from otp.avatar import DistributedAvatar
from otp.friends import FriendManager
from otp.login import TTAccount
from otp.login import AccountServerConstants
from otp.login import LoginScreen
from otp.login import LoginGSAccount
from otp.login import LoginGoAccount
from otp.login import LoginWebPlayTokenAccount
from otp.login import LoginTTAccount
from otp.login import HTTPUtil
from otp.distributed import OTPClientRepository
from otp.distributed import PotentialAvatar
from otp.distributed import PotentialShard
from otp.distributed import DistributedDistrict
from otp.distributed.OtpDoGlobals import *
from otp.distributed import OtpDoGlobals
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
from otp.otpbase import OTPLauncherGlobals
from otp.avatar.Avatar import teleportNotify
from toontown.toonbase.ToonBaseGlobal import *
from toontown.toonbase.ToontownGlobals import *
from toontown.launcher.DownloadForceAcknowledge import *
from toontown.distributed import DelayDelete
from toontown.friends import FriendHandle
from toontown.friends import FriendsListPanel
from toontown.friends import ToontownFriendSecret
from toontown.uberdog import TTSpeedchatRelay
from toontown.login import DateObject
from toontown.login import AccountServerDate
from toontown.login import AvatarChooser
from toontown.makeatoon import MakeAToon
from toontown.pets import DistributedPet, PetDetail, PetHandle
from toontown.toonbase import TTLocalizer
from toontown.toontowngui import TTDialog
from toontown.toon import LocalToon
from toontown.toon import ToonDNA
from toontown.distributed import ToontownDistrictStats
from toontown.makeatoon import TTPickANamePattern
from toontown.parties import ToontownTimeManager
from toontown.toon import Toon, DistributedToon
from ToontownMsgTypes import *
import HoodMgr
import PlayGame
from toontown.toontowngui import ToontownLoadingBlocker
from toontown.hood import StreetSign
class ToontownClientRepository(OTPClientRepository.OTPClientRepository):
SupportTutorial = 1
GameGlobalsId = OTP_DO_ID_TOONTOWN
SetZoneDoneEvent = 'TCRSetZoneDone'
EmuSetZoneDoneEvent = 'TCREmuSetZoneDone'
SetInterest = 'Set'
ClearInterest = 'Clear'
ClearInterestDoneEvent = 'TCRClearInterestDone'
KeepSubShardObjects = False
def __init__(self, serverVersion, launcher = None):
OTPClientRepository.OTPClientRepository.__init__(self, serverVersion, launcher, playGame=PlayGame.PlayGame)
self._playerAvDclass = self.dclassesByName['DistributedToon']
setInterfaceFont(TTLocalizer.InterfaceFont)
setSignFont(TTLocalizer.SignFont)
setFancyFont(TTLocalizer.FancyFont)
nameTagFontIndex = 0
for font in TTLocalizer.NametagFonts:
setNametagFont(nameTagFontIndex, TTLocalizer.NametagFonts[nameTagFontIndex])
nameTagFontIndex += 1
self.toons = {}
if self.http.getVerifySsl() != HTTPClient.VSNoVerify:
self.http.setVerifySsl(HTTPClient.VSNoDateCheck)
#prepareAvatar(self.http)
self.__forbidCheesyEffects = 0
self.friendManager = None
self.speedchatRelay = None
self.trophyManager = None
self.bankManager = None
self.catalogManager = None
self.welcomeValleyManager = None
self.newsManager = None
self.streetSign = None
self.distributedDistrict = None
self.partyManager = None
self.inGameNewsMgr = None
self.whitelistMgr = None
self.toontownTimeManager = ToontownTimeManager.ToontownTimeManager()
self.avatarFriendsManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_AVATAR_FRIENDS_MANAGER, 'AvatarFriendsManager')
self.playerFriendsManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_PLAYER_FRIENDS_MANAGER, 'TTPlayerFriendsManager')
self.speedchatRelay = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_SPEEDCHAT_RELAY, 'TTSpeedchatRelay')
self.deliveryManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_DELIVERY_MANAGER, 'DistributedDeliveryManager')
if config.GetBool('want-code-redemption', 1):
self.codeRedemptionManager = self.generateGlobalObject(OtpDoGlobals.OTP_DO_ID_TOONTOWN_CODE_REDEMPTION_MANAGER, 'TTCodeRedemptionMgr')
self.streetSign = None
self.furnitureManager = None
self.objectManager = None
self.friendsMap = {}
self.friendsOnline = {}
self.friendsMapPending = 0
self.friendsListError = 0
self.friendPendingChatSettings = {}
self.elderFriendsMap = {}
self.__queryAvatarMap = {}
self.dateObject = DateObject.DateObject()
self.accountServerDate = AccountServerDate.AccountServerDate()
self.hoodMgr = HoodMgr.HoodMgr(self)
self.setZonesEmulated = 0
self.old_setzone_interest_handle = None
self.setZoneQueue = Queue()
self.accept(ToontownClientRepository.SetZoneDoneEvent, self._handleEmuSetZoneDone)
self._deletedSubShardDoIds = set()
self.toonNameDict = {}
self.gameFSM.addState(State.State('skipTutorialRequest', self.enterSkipTutorialRequest, self.exitSkipTutorialRequest, ['playGame', 'gameOff', 'tutorialQuestion']))
state = self.gameFSM.getStateNamed('waitOnEnterResponses')
state.addTransition('skipTutorialRequest')
state = self.gameFSM.getStateNamed('playGame')
state.addTransition('skipTutorialRequest')
self.wantCogdominiums = base.config.GetBool('want-cogdominiums', 1)
self.wantEmblems = base.config.GetBool('want-emblems', 0)
if base.config.GetBool('tt-node-check', 0):
for species in ToonDNA.toonSpeciesTypes:
for head in ToonDNA.getHeadList(species):
for torso in ToonDNA.toonTorsoTypes:
for legs in ToonDNA.toonLegTypes:
for gender in ('m', 'f'):
print 'species: %s, head: %s, torso: %s, legs: %s, gender: %s' % (species,
head,
torso,
legs,
gender)
dna = ToonDNA.ToonDNA()
dna.newToon((head,
torso,
legs,
gender))
toon = Toon.Toon()
try:
toon.setDNA(dna)
except Exception, e:
print e
return
def congratulations(self, avatarChoice):
self.acceptedScreen = loader.loadModel('phase_3/models/gui/toon_council')
self.acceptedScreen.setScale(0.667)
self.acceptedScreen.reparentTo(aspect2d)
buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui')
self.acceptedBanner = DirectLabel(parent=self.acceptedScreen, relief=None, text=OTPLocalizer.CRNameCongratulations, text_scale=0.18, text_fg=Vec4(0.6, 0.1, 0.1, 1), text_pos=(0, 0.05), text_font=getMinnieFont())
newName = avatarChoice.approvedName
self.acceptedText = DirectLabel(parent=self.acceptedScreen, relief=None, text=OTPLocalizer.CRNameAccepted % newName, text_scale=0.125, text_fg=Vec4(0, 0, 0, 1), text_pos=(0, -0.15))
self.okButton = DirectButton(parent=self.acceptedScreen, image=(buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr')), relief=None, text='Ok', scale=1.5, text_scale=0.05, text_pos=(0.0, -0.1), pos=(0, 0, -1), command=self.__handleCongrats, extraArgs=[avatarChoice])
buttons.removeNode()
base.transitions.noFade()
return
def __handleCongrats(self, avatarChoice):
self.acceptedBanner.destroy()
self.acceptedText.destroy()
self.okButton.destroy()
self.acceptedScreen.removeNode()
del self.acceptedScreen
del self.okButton
del self.acceptedText
del self.acceptedBanner
if not self.astronSupport:
datagram = PyDatagram()
datagram.addUint16(CLIENT_SET_WISHNAME_CLEAR)
datagram.addUint32(avatarChoice.id)
datagram.addUint8(1)
self.send(datagram)
self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice])
else:
self.astronLoginManager.sendAcknowledgeAvatarName(avatarChoice.id,
lambda: self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice]))
def betterlucknexttime(self, avList, index):
self.rejectDoneEvent = 'rejectDone'
self.rejectDialog = TTDialog.TTGlobalDialog(doneEvent=self.rejectDoneEvent, message=TTLocalizer.NameShopNameRejected, style=TTDialog.Acknowledge)
self.rejectDialog.show()
self.acceptOnce(self.rejectDoneEvent, self.__handleReject, [avList, index])
base.transitions.noFade()
def __handleReject(self, avList, index):
self.rejectDialog.cleanup()
if not self.astronSupport:
datagram = PyDatagram()
datagram.addUint16(CLIENT_SET_WISHNAME_CLEAR)
avid = 0
for k in avList:
if k.position == index:
avid = k.id
if avid == 0:
self.notify.error('Avatar rejected not found in avList. Index is: ' + str(index))
if not self.astronSupport:
datagram.addUint32(avid)
datagram.addUint8(0)
self.send(datagram)
self.loginFSM.request('waitForAvatarList')
else:
self.astronLoginManager.sendAcknowledgeAvatarName(avId, lambda: self.loginFSM.request('waitForAvatarList'))
def enterChooseAvatar(self, avList):
ModelPool.garbageCollect()
TexturePool.garbageCollect()
self.sendSetAvatarIdMsg(0)
self.clearFriendState()
if self.music == None and base.musicManagerIsValid:
self.music = base.musicManager.getSound('phase_3/audio/bgm/tt_theme.mid')
if self.music:
self.music.setLoop(1)
self.music.setVolume(0.9)
self.music.play()
base.playMusic(self.music, looping=1, volume=0.9, interrupt=None)
self.handler = self.handleMessageType
self.avChoiceDoneEvent = 'avatarChooserDone'
self.avChoice = AvatarChooser.AvatarChooser(avList, self.loginFSM, self.avChoiceDoneEvent)
self.avChoice.load(self.isPaid())
self.avChoice.enter()
self.accept(self.avChoiceDoneEvent, self.__handleAvatarChooserDone, [avList])
if config.GetBool('want-gib-loader', 1):
self.loadingBlocker = ToontownLoadingBlocker.ToontownLoadingBlocker(avList)
return
def __handleAvatarChooserDone(self, avList, doneStatus):
done = doneStatus['mode']
if done == 'exit':
if not launcher.isDummy() and launcher.VISTA:
if not self.isPaid():
self.loginFSM.request('shutdown', [OTPLauncherGlobals.ExitUpsell])
else:
self.loginFSM.request('shutdown')
else:
self.loginFSM.request('shutdown')
return
index = self.avChoice.getChoice()
for av in avList:
if av.position == index:
avatarChoice = av
self.notify.info('================')
self.notify.info('Chose avatar id: %s' % av.id)
self.notify.info('Chose avatar name: %s' % av.name)
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(av.dna)
if base.logPrivateInfo:
self.notify.info('Chose avatar dna: %s' % (dna.asTuple(),))
self.notify.info('Chose avatar position: %s' % av.position)
self.notify.info('isPaid: %s' % self.isPaid())
self.notify.info('freeTimeLeft: %s' % self.freeTimeLeft())
self.notify.info('allowSecretChat: %s' % self.allowSecretChat())
self.notify.info('================')
if done == 'chose':
self.avChoice.exit()
if avatarChoice.approvedName != '':
self.congratulations(avatarChoice)
avatarChoice.approvedName = ''
elif avatarChoice.rejectedName != '':
avatarChoice.rejectedName = ''
self.betterlucknexttime(avList, index)
else:
self.loginFSM.request('waitForSetAvatarResponse', [avatarChoice])
elif done == 'nameIt':
self.accept('downloadAck-response', self.__handleDownloadAck, [avList, index])
self.downloadAck = DownloadForceAcknowledge('downloadAck-response')
self.downloadAck.enter(4)
elif done == 'create':
self.loginFSM.request('createAvatar', [avList, index])
elif done == 'delete':
self.loginFSM.request('waitForDeleteAvatarResponse', [avatarChoice])
def __handleDownloadAck(self, avList, index, doneStatus):
if doneStatus['mode'] == 'complete':
self.goToPickAName(avList, index)
else:
self.loginFSM.request('chooseAvatar', [avList])
self.downloadAck.exit()
self.downloadAck = None
self.ignore('downloadAck-response')
return
def exitChooseAvatar(self):
self.handler = None
self.avChoice.exit()
self.avChoice.unload()
self.avChoice = None
self.ignore(self.avChoiceDoneEvent)
return
def goToPickAName(self, avList, index):
self.avChoice.exit()
self.loginFSM.request('createAvatar', [avList, index])
def enterCreateAvatar(self, avList, index, newDNA = None):
if self.music:
self.music.stop()
self.music = None
if newDNA != None:
self.newPotAv = PotentialAvatar.PotentialAvatar('deleteMe', ['',
'',
'',
''], newDNA.makeNetString(), index, 1)
avList.append(self.newPotAv)
base.transitions.noFade()
self.avCreate = MakeAToon.MakeAToon(self.loginFSM, avList, 'makeAToonComplete', index, self.isPaid())
self.avCreate.load()
self.avCreate.enter()
if not self.astronSupport:
self.handler = self.handleCreateAvatar
self.accept('makeAToonComplete', self.__handleMakeAToon, [avList, index])
self.accept('nameShopCreateAvatar', self.sendCreateAvatarMsg)
self.accept('nameShopPost', self.relayMessage)
return
def relayMessage(self, dg):
self.send(dg)
def handleCreateAvatar(self, msgType, di):
if msgType == CLIENT_CREATE_AVATAR_RESP or msgType == CLIENT_SET_NAME_PATTERN_ANSWER or msgType == CLIENT_SET_WISHNAME_RESP:
self.avCreate.ns.nameShopHandler(msgType, di)
else:
self.handleMessageType(msgType, di)
def __handleMakeAToon(self, avList, avPosition):
done = self.avCreate.getDoneStatus()
if done == 'cancel':
if hasattr(self, 'newPotAv'):
if self.newPotAv in avList:
avList.remove(self.newPotAv)
self.avCreate.exit()
self.loginFSM.request('chooseAvatar', [avList])
elif done == 'created':
self.avCreate.exit()
if not base.launcher or base.launcher.getPhaseComplete(3.5):
for i in avList:
if i.position == avPosition:
newPotAv = i
self.loginFSM.request('waitForSetAvatarResponse', [newPotAv])
else:
self.loginFSM.request('chooseAvatar', [avList])
else:
self.notify.error('Invalid doneStatus from MakeAToon: ' + str(done))
def exitCreateAvatar(self):
self.ignore('makeAToonComplete')
self.ignore('nameShopPost')
self.ignore('nameShopCreateAvatar')
self.avCreate.unload()
self.avCreate = None
self.handler = None
if hasattr(self, 'newPotAv'):
del self.newPotAv
return
if not config.GetBool('astron-support', True):
def handleAvatarResponseMsg(self, di):
self.cleanupWaitingForDatabase()
avatarId = di.getUint32()
returnCode = di.getUint8()
if returnCode == 0:
dclass = self.dclassesByName['DistributedToon']
NametagGlobals.setMasterArrowsOn(0)
loader.beginBulkLoad('localAvatarPlayGame', OTPLocalizer.CREnteringToontown, 400, 1, TTLocalizer.TIP_GENERAL)
localAvatar = LocalToon.LocalToon(self)
localAvatar.dclass = dclass
base.localAvatar = localAvatar
__builtins__['localAvatar'] = base.localAvatar
NametagGlobals.setToon(base.localAvatar)
localAvatar.doId = avatarId
self.localAvatarDoId = avatarId
parentId = None
zoneId = None
localAvatar.setLocation(parentId, zoneId)
localAvatar.generateInit()
localAvatar.generate()
localAvatar.updateAllRequiredFields(dclass, di)
self.doId2do[avatarId] = localAvatar
localAvatar.initInterface()
self.sendGetFriendsListRequest()
self.loginFSM.request('playingGame')
else:
self.notify.error('Bad avatar: return code %d' % returnCode)
return
else:
def handleAvatarResponseMsg(self, avatarId, di):
self.cleanupWaitingForDatabase()
dclass = self.dclassesByName['DistributedToon']
NametagGlobals.setMasterArrowsOn(0)
loader.beginBulkLoad('localAvatarPlayGame', OTPLocalizer.CREnteringToontown, 400, 1, TTLocalizer.TIP_GENERAL)
localAvatar = LocalToon.LocalToon(self)
localAvatar.dclass = dclass
base.localAvatar = localAvatar
__builtins__['localAvatar'] = base.localAvatar
NametagGlobals.setToon(base.localAvatar)
localAvatar.doId = avatarId
self.localAvatarDoId = avatarId
parentId = None
zoneId = None
localAvatar.setLocation(parentId, zoneId)
localAvatar.generateInit()
localAvatar.generate()
dclass.receiveUpdateBroadcastRequiredOwner(localAvatar, di)
localAvatar.announceGenerate()
localAvatar.postGenerateMessage()
self.doId2do[avatarId] = localAvatar
localAvatar.initInterface()
self.sendGetFriendsListRequest()
self.loginFSM.request('playingGame')
def getAvatarDetails(self, avatar, func, *args):
pad = ScratchPad()
pad.func = func
pad.args = args
pad.avatar = avatar
pad.delayDelete = DelayDelete.DelayDelete(avatar, 'getAvatarDetails')
avId = avatar.doId
self.__queryAvatarMap[avId] = pad
self.__sendGetAvatarDetails(avId)
def cancelAvatarDetailsRequest(self, avatar):
avId = avatar.doId
if self.__queryAvatarMap.has_key(avId):
pad = self.__queryAvatarMap.pop(avId)
pad.delayDelete.destroy()
def __sendGetAvatarDetails(self, avId):
datagram = PyDatagram()
avatar = self.__queryAvatarMap[avId].avatar
datagram.addUint16(avatar.getRequestID())
datagram.addUint32(avId)
self.send(datagram)
def handleGetAvatarDetailsResp(self, di):
avId = di.getUint32()
returnCode = di.getUint8()
self.notify.info('Got query response for avatar %d, code = %d.' % (avId, returnCode))
try:
pad = self.__queryAvatarMap[avId]
except:
self.notify.warning('Received unexpected or outdated details for avatar %d.' % avId)
return
del self.__queryAvatarMap[avId]
gotData = 0
if returnCode != 0:
self.notify.warning('No information available for avatar %d.' % avId)
else:
dclassName = pad.args[0]
dclass = self.dclassesByName[dclassName]
pad.avatar.updateAllRequiredFields(dclass, di)
gotData = 1
if isinstance(pad.func, types.StringType):
messenger.send(pad.func, list((gotData, pad.avatar) + pad.args))
else:
apply(pad.func, (gotData, pad.avatar) + pad.args)
pad.delayDelete.destroy()
def enterPlayingGame(self, *args, **kArgs):
OTPClientRepository.OTPClientRepository.enterPlayingGame(self, *args, **kArgs)
self.gameFSM.request('waitOnEnterResponses', [None,
base.localAvatar.defaultZone,
base.localAvatar.defaultZone,
-1])
self._userLoggingOut = False
if not self.streetSign:
self.streetSign = StreetSign.StreetSign()
return
def exitPlayingGame(self):
ivalMgr.interrupt()
if self.objectManager != None:
self.objectManager.destroy()
self.objectManager = None
ToontownFriendSecret.unloadFriendSecret()
FriendsListPanel.unloadFriendsList()
messenger.send('cancelFriendInvitation')
base.removeGlitchMessage()
taskMgr.remove('avatarRequestQueueTask')
OTPClientRepository.OTPClientRepository.exitPlayingGame(self)
if hasattr(base, 'localAvatar'):
camera.reparentTo(render)
camera.setPos(0, 0, 0)
camera.setHpr(0, 0, 0)
del self.doId2do[base.localAvatar.getDoId()]
if base.localAvatar.getDelayDeleteCount() != 0:
self.notify.error('could not delete localAvatar, delayDeletes=%s' % (base.localAvatar.getDelayDeleteNames(),))
base.localAvatar.deleteOrDelay()
base.localAvatar.detectLeaks()
NametagGlobals.setToon(base.cam)
del base.localAvatar
del __builtins__['localAvatar']
loader.abortBulkLoad()
base.transitions.noTransitions()
if self._userLoggingOut:
self.detectLeaks(okTasks=[], okEvents=['destroy-ToontownLoadingScreenTitle', 'destroy-ToontownLoadingScreenTip', 'destroy-ToontownLoadingScreenWaitBar'])
return
def enterGameOff(self):
OTPClientRepository.OTPClientRepository.enterGameOff(self)
def enterWaitOnEnterResponses(self, shardId, hoodId, zoneId, avId):
self.resetDeletedSubShardDoIds()
OTPClientRepository.OTPClientRepository.enterWaitOnEnterResponses(self, shardId, hoodId, zoneId, avId)
def enterSkipTutorialRequest(self, hoodId, zoneId, avId):
self.handlerArgs = {'hoodId': hoodId,
'zoneId': zoneId,
'avId': avId}
if not self.astronSupport:
self.handler = self.handleTutorialQuestion
self.__requestSkipTutorial(hoodId, zoneId, avId)
def __requestSkipTutorial(self, hoodId, zoneId, avId):
self.notify.debug('requesting skip tutorial')
self.acceptOnce('skipTutorialAnswered', self.__handleSkipTutorialAnswered, [hoodId, zoneId, avId])
messenger.send('requestSkipTutorial')
self.waitForDatabaseTimeout(requestName='RequestSkipTutorial')
def __handleSkipTutorialAnswered(self, hoodId, zoneId, avId, allOk):
if allOk:
hoodId = self.handlerArgs['hoodId']
zoneId = self.handlerArgs['zoneId']
avId = self.handlerArgs['avId']
self.gameFSM.request('playGame', [hoodId, zoneId, avId])
else:
self.notify.warning('allOk is false on skip tutorial, forcing the tutorial.')
self.gameFSM.request('tutorialQuestion', [hoodId, zoneId, avId])
def exitSkipTutorialRequest(self):
self.cleanupWaitingForDatabase()
self.handler = None
self.handlerArgs = None
self.ignore('skipTutorialAnswered')
return
def enterTutorialQuestion(self, hoodId, zoneId, avId):
if not self.astronSupport:
self.handler = self.handleTutorialQuestion
self.__requestTutorial(hoodId, zoneId, avId)
def handleTutorialQuestion(self, msgType, di):
if msgType == CLIENT_CREATE_OBJECT_REQUIRED:
self.handleGenerateWithRequired(di)
elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:
self.handleGenerateWithRequiredOther(di)
elif msgType == CLIENT_OBJECT_UPDATE_FIELD:
self.handleUpdateField(di)
elif msgType == CLIENT_OBJECT_DISABLE_RESP:
self.handleDisable(di)
elif msgType == CLIENT_OBJECT_DELETE_RESP:
self.handleDelete(di)
elif msgType == CLIENT_GET_FRIEND_LIST_RESP:
self.handleGetFriendsList(di)
elif msgType == CLIENT_GET_FRIEND_LIST_EXTENDED_RESP:
self.handleGetFriendsListExtended(di)
elif msgType == CLIENT_FRIEND_ONLINE:
self.handleFriendOnline(di)
elif msgType == CLIENT_FRIEND_OFFLINE:
self.handleFriendOffline(di)
elif msgType == CLIENT_GET_AVATAR_DETAILS_RESP:
self.handleGetAvatarDetailsResp(di)
else:
self.handleMessageType(msgType, di)
def __requestTutorial(self, hoodId, zoneId, avId):
self.notify.debug('requesting tutorial')
self.acceptOnce('startTutorial', self.__handleStartTutorial, [avId])
messenger.send('requestTutorial')
self.waitForDatabaseTimeout(requestName='RequestTutorial')
def __handleStartTutorial(self, avId, zoneId):
self.gameFSM.request('playGame', [Tutorial, zoneId, avId])
def exitTutorialQuestion(self):
self.cleanupWaitingForDatabase()
self.handler = None
self.handlerArgs = None
self.ignore('startTutorial')
taskMgr.remove('waitingForTutorial')
return
def enterSwitchShards(self, shardId, hoodId, zoneId, avId):
OTPClientRepository.OTPClientRepository.enterSwitchShards(self, shardId, hoodId, zoneId, avId)
self.handler = self.handleCloseShard
def exitSwitchShards(self):
OTPClientRepository.OTPClientRepository.exitSwitchShards(self)
self.ignore(ToontownClientRepository.ClearInterestDoneEvent)
self.handler = None
return
def enterCloseShard(self, loginState = None):
OTPClientRepository.OTPClientRepository.enterCloseShard(self, loginState)
self.handler = self.handleCloseShard
self._removeLocalAvFromStateServer()
if not config.GetBool('astron-support', True):
def handleCloseShard(self, msgType, di):
if msgType == CLIENT_CREATE_OBJECT_REQUIRED:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_OBJECT_UPDATE_FIELD:
di2 = PyDatagramIterator(di)
doId = di2.getUint32()
if self._doIdIsOnCurrentShard(doId):
return
self.handleMessageType(msgType, di)
else:
def handleCloseShard(self, msgType, di):
if msgType == CLIENT_ENTER_OBJECT_REQUIRED:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_ENTER_OBJECT_REQUIRED_OTHER:
di2 = PyDatagramIterator(di)
parentId = di2.getUint32()
if self._doIdIsOnCurrentShard(parentId):
return
elif msgType == CLIENT_OBJECT_SET_FIELD:
di2 = PyDatagramIterator(di)
doId = di2.getUint32()
if self._doIdIsOnCurrentShard(doId):
return
self.handleMessageType(msgType, di)
def _logFailedDisable(self, doId, ownerView):
if doId not in self.doId2do and doId in self._deletedSubShardDoIds:
return
OTPClientRepository.OTPClientRepository._logFailedDisable(self, doId, ownerView)
def exitCloseShard(self):
OTPClientRepository.OTPClientRepository.exitCloseShard(self)
self.ignore(ToontownClientRepository.ClearInterestDoneEvent)
self.handler = None
return
def isShardInterestOpen(self):
return self.old_setzone_interest_handle is not None or self.uberZoneInterest is not None
def resetDeletedSubShardDoIds(self):
self._deletedSubShardDoIds.clear()
def dumpAllSubShardObjects(self):
if self.KeepSubShardObjects:
return
isNotLive = not base.cr.isLive()
if isNotLive:
try:
localAvatar
except:
self.notify.info('dumpAllSubShardObjects')
else:
self.notify.info('dumpAllSubShardObjects: defaultShard is %s' % localAvatar.defaultShard)
ignoredClasses = ('MagicWordManager', 'TimeManager', 'DistributedDistrict', 'FriendManager', 'NewsManager', 'ToontownMagicWordManager', 'WelcomeValleyManager', 'DistributedTrophyMgr', 'CatalogManager', 'DistributedBankMgr', 'EstateManager', 'RaceManager', 'SafeZoneManager', 'DeleteManager', 'TutorialManager', 'ToontownDistrict', 'DistributedDeliveryManager', 'DistributedPartyManager', 'AvatarFriendsManager', 'InGameNewsMgr', 'WhitelistMgr', 'TTCodeRedemptionMgr')
messenger.send('clientCleanup')
for avId, pad in self.__queryAvatarMap.items():
pad.delayDelete.destroy()
self.__queryAvatarMap = {}
delayDeleted = []
doIds = self.doId2do.keys()
for doId in doIds:
obj = self.doId2do[doId]
if isNotLive:
ignoredClass = obj.__class__.__name__ in ignoredClasses
if not ignoredClass and obj.parentId != localAvatar.defaultShard:
self.notify.info('dumpAllSubShardObjects: %s %s parent %s is not defaultShard' % (obj.__class__.__name__, obj.doId, obj.parentId))
if obj.parentId == localAvatar.defaultShard and obj is not localAvatar:
if obj.neverDisable:
if isNotLive:
if not ignoredClass:
self.notify.warning('dumpAllSubShardObjects: neverDisable set for %s %s' % (obj.__class__.__name__, obj.doId))
else:
self.deleteObject(doId)
self._deletedSubShardDoIds.add(doId)
if obj.getDelayDeleteCount() != 0:
delayDeleted.append(obj)
delayDeleteLeaks = []
for obj in delayDeleted:
if obj.getDelayDeleteCount() != 0:
delayDeleteLeaks.append(obj)
if len(delayDeleteLeaks):
s = 'dumpAllSubShardObjects:'
for obj in delayDeleteLeaks:
s += '\n could not delete %s (%s), delayDeletes=%s' % (safeRepr(obj), itype(obj), obj.getDelayDeleteNames())
self.notify.error(s)
if isNotLive:
self.notify.info('dumpAllSubShardObjects: doIds left: %s' % self.doId2do.keys())
def _removeCurrentShardInterest(self, callback):
if self.old_setzone_interest_handle is None:
self.notify.warning('removeToontownShardInterest: no shard interest open')
callback()
return
self.acceptOnce(ToontownClientRepository.ClearInterestDoneEvent, Functor(self._tcrRemoveUberZoneInterest, callback))
self._removeEmulatedSetZone(ToontownClientRepository.ClearInterestDoneEvent)
return
def _tcrRemoveUberZoneInterest(self, callback):
self.acceptOnce(ToontownClientRepository.ClearInterestDoneEvent, Functor(self._tcrRemoveShardInterestDone, callback))
self.removeInterest(self.uberZoneInterest, ToontownClientRepository.ClearInterestDoneEvent)
def _tcrRemoveShardInterestDone(self, callback):
self.uberZoneInterest = None
callback()
return
def _doIdIsOnCurrentShard(self, doId):
if doId == base.localAvatar.defaultShard:
return True
do = self.getDo(doId)
if do:
if do.parentId == base.localAvatar.defaultShard:
return True
return False
def _wantShardListComplete(self):
print self.activeDistrictMap
if self._shardsAreReady():
self.acceptOnce(ToontownDistrictStats.EventName(), self.shardDetailStatsComplete)
ToontownDistrictStats.refresh()
else:
self.loginFSM.request('noShards')
def shardDetailStatsComplete(self):
self.loginFSM.request('waitForAvatarList')
def exitWaitForShardList(self):
self.ignore(ToontownDistrictStats.EventName())
OTPClientRepository.OTPClientRepository.exitWaitForShardList(self)
def fillUpFriendsMap(self):
if self.isFriendsMapComplete():
return 1
if not self.friendsMapPending and not self.friendsListError:
self.notify.warning('Friends list stale; fetching new list.')
self.sendGetFriendsListRequest()
return 0
def isFriend(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
self.identifyFriend(doId)
return 1
return 0
def isAvatarFriend(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
self.identifyFriend(doId)
return 1
return 0
def getFriendFlags(self, doId):
for friendId, flags in base.localAvatar.friendsList:
if friendId == doId:
return flags
return 0
def isFriendOnline(self, doId):
return self.friendsOnline.has_key(doId)
def addAvatarToFriendsList(self, avatar):
self.friendsMap[avatar.doId] = avatar
def identifyFriend(self, doId, source = None):
if self.friendsMap.has_key(doId):
teleportNotify.debug('friend %s in friendsMap' % doId)
return self.friendsMap[doId]
avatar = None
if self.doId2do.has_key(doId):
teleportNotify.debug('found friend %s in doId2do' % doId)
avatar = self.doId2do[doId]
elif self.cache.contains(doId):
teleportNotify.debug('found friend %s in cache' % doId)
avatar = self.cache.dict[doId]
elif self.playerFriendsManager.getAvHandleFromId(doId):
teleportNotify.debug('found friend %s in playerFriendsManager' % doId)
avatar = base.cr.playerFriendsManager.getAvHandleFromId(doId)
else:
self.notify.warning("Don't know who friend %s is." % doId)
return
if not ((isinstance(avatar, DistributedToon.DistributedToon) and avatar.__class__ is DistributedToon.DistributedToon) or isinstance(avatar, DistributedPet.DistributedPet)):
self.notify.warning('friendsNotify%s: invalid friend object %s' % (choice(source, '(%s)' % source, ''), doId))
return
if base.wantPets:
if avatar.isPet():
if avatar.bFake:
handle = PetHandle.PetHandle(avatar)
else:
handle = avatar
else:
handle = FriendHandle.FriendHandle(doId, avatar.getName(), avatar.style, avatar.getPetId())
else:
handle = FriendHandle.FriendHandle(doId, avatar.getName(), avatar.style, '')
teleportNotify.debug('adding %s to friendsMap' % doId)
self.friendsMap[doId] = handle
return handle
def identifyPlayer(self, pId):
return base.cr.playerFriendsManager.getFriendInfo(pId)
def identifyAvatar(self, doId):
if self.doId2do.has_key(doId):
return self.doId2do[doId]
else:
return self.identifyFriend(doId)
def isFriendsMapComplete(self):
for friendId, flags in base.localAvatar.friendsList:
if self.identifyFriend(friendId) == None:
return 0
if base.wantPets and base.localAvatar.hasPet():
print str(self.friendsMap)
print str(self.friendsMap.has_key(base.localAvatar.getPetId()))
if self.friendsMap.has_key(base.localAvatar.getPetId()) == None:
return 0
return 1
def removeFriend(self, avatarId):
base.localAvatar.sendUpdate('friendsNotify', [base.localAvatar.doId, 1], sendToId=avatarId)
datagram = PyDatagram()
datagram.addUint16(CLIENT_REMOVE_FRIEND)
datagram.addUint32(avatarId)
self.send(datagram)
self.estateMgr.removeFriend(base.localAvatar.doId, avatarId)
for pair in base.localAvatar.friendsList:
friendId = pair[0]
if friendId == avatarId:
base.localAvatar.friendsList.remove(pair)
return
def clearFriendState(self):
self.friendsMap = {}
self.friendsOnline = {}
self.friendsMapPending = 0
self.friendsListError = 0
def sendGetFriendsListRequest(self):
if self.astronSupport:
print 'sendGetFriendsListRequest TODO'
else:
self.friendsMapPending = 1
self.friendsListError = 0
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST)
self.send(datagram)
def cleanPetsFromFriendsMap(self):
for objId, obj in self.friendsMap.items():
from toontown.pets import DistributedPet
if isinstance(obj, DistributedPet.DistributedPet):
print 'Removing %s reference from the friendsMap' % obj.getName()
del self.friendsMap[objId]
def removePetFromFriendsMap(self):
doId = base.localAvatar.getPetId()
if doId and self.friendsMap.has_key(doId):
del self.friendsMap[doId]
def addPetToFriendsMap(self, callback = None):
doId = base.localAvatar.getPetId()
if not doId or self.friendsMap.has_key(doId):
if callback:
callback()
return
def petDetailsCallback(petAvatar):
handle = PetHandle.PetHandle(petAvatar)
self.friendsMap[doId] = handle
petAvatar.disable()
petAvatar.delete()
if callback:
callback()
if self._proactiveLeakChecks:
petAvatar.detectLeaks()
PetDetail.PetDetail(doId, petDetailsCallback)
def handleGetFriendsList(self, di):
error = di.getUint8()
if error:
self.notify.warning('Got error return from friends list.')
self.friendsListError = 1
else:
count = di.getUint16()
for i in range(0, count):
doId = di.getUint32()
name = di.getString()
dnaString = di.getString()
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(dnaString)
petId = di.getUint32()
handle = FriendHandle.FriendHandle(doId, name, dna, petId)
self.friendsMap[doId] = handle
if self.friendsOnline.has_key(doId):
self.friendsOnline[doId] = handle
if self.friendPendingChatSettings.has_key(doId):
self.notify.debug('calling setCommonAndWL %s' % str(self.friendPendingChatSettings[doId]))
handle.setCommonAndWhitelistChatFlags(*self.friendPendingChatSettings[doId])
if base.wantPets and base.localAvatar.hasPet():
def handleAddedPet():
self.friendsMapPending = 0
messenger.send('friendsMapComplete')
self.addPetToFriendsMap(handleAddedPet)
return
self.friendsMapPending = 0
messenger.send('friendsMapComplete')
def handleGetFriendsListExtended(self, di):
avatarHandleList = []
error = di.getUint8()
if error:
self.notify.warning('Got error return from friends list extended.')
else:
count = di.getUint16()
for i in range(0, count):
abort = 0
doId = di.getUint32()
name = di.getString()
if name == '':
abort = 1
dnaString = di.getString()
if dnaString == '':
abort = 1
else:
dna = ToonDNA.ToonDNA()
dna.makeFromNetString(dnaString)
petId = di.getUint32()
if not abort:
handle = FriendHandle.FriendHandle(doId, name, dna, petId)
avatarHandleList.append(handle)
if avatarHandleList:
messenger.send('gotExtraFriendHandles', [avatarHandleList])
def handleFriendOnline(self, di):
doId = di.getUint32()
commonChatFlags = 0
whitelistChatFlags = 0
if di.getRemainingSize() > 0:
commonChatFlags = di.getUint8()
if di.getRemainingSize() > 0:
whitelistChatFlags = di.getUint8()
self.notify.debug('Friend %d now online. common=%d whitelist=%d' % (doId, commonChatFlags, whitelistChatFlags))
if not self.friendsOnline.has_key(doId):
self.friendsOnline[doId] = self.identifyFriend(doId)
messenger.send('friendOnline', [doId, commonChatFlags, whitelistChatFlags])
if not self.friendsOnline[doId]:
self.friendPendingChatSettings[doId] = (commonChatFlags, whitelistChatFlags)
def handleFriendOffline(self, di):
doId = di.getUint32()
self.notify.debug('Friend %d now offline.' % doId)
try:
del self.friendsOnline[doId]
messenger.send('friendOffline', [doId])
except:
pass
def getFirstBattle(self):
from toontown.battle import DistributedBattleBase
for dobj in self.doId2do.values():
if isinstance(dobj, DistributedBattleBase.DistributedBattleBase):
return dobj
def forbidCheesyEffects(self, forbid):
wasAllowed = self.__forbidCheesyEffects != 0
if forbid:
self.__forbidCheesyEffects += 1
else:
self.__forbidCheesyEffects -= 1
isAllowed = self.__forbidCheesyEffects != 0
if wasAllowed != isAllowed:
for av in Avatar.Avatar.ActiveAvatars:
if hasattr(av, 'reconsiderCheesyEffect'):
av.reconsiderCheesyEffect()
base.localAvatar.reconsiderCheesyEffect()
def areCheesyEffectsAllowed(self):
return self.__forbidCheesyEffects == 0
def getNextSetZoneDoneEvent(self):
return '%s-%s' % (ToontownClientRepository.EmuSetZoneDoneEvent, self.setZonesEmulated + 1)
def getLastSetZoneDoneEvent(self):
return '%s-%s' % (ToontownClientRepository.EmuSetZoneDoneEvent, self.setZonesEmulated)
def getQuietZoneLeftEvent(self):
return 'leftQuietZone-%s' % (id(self),)
def sendSetZoneMsg(self, zoneId, visibleZoneList = None):
event = self.getNextSetZoneDoneEvent()
self.setZonesEmulated += 1
parentId = base.localAvatar.defaultShard
self.sendSetLocation(base.localAvatar.doId, parentId, zoneId)
localAvatar.setLocation(parentId, zoneId)
interestZones = zoneId
if visibleZoneList is not None:
interestZones = visibleZoneList
self._addInterestOpToQueue(ToontownClientRepository.SetInterest, [parentId, interestZones, 'OldSetZoneEmulator'], event)
return
def resetInterestStateForConnectionLoss(self):
OTPClientRepository.OTPClientRepository.resetInterestStateForConnectionLoss(self)
self.old_setzone_interest_handle = None
self.setZoneQueue.clear()
return
def _removeEmulatedSetZone(self, doneEvent):
self._addInterestOpToQueue(ToontownClientRepository.ClearInterest, None, doneEvent)
return
def _addInterestOpToQueue(self, op, args, event):
self.setZoneQueue.push([op, args, event])
if len(self.setZoneQueue) == 1:
self._sendNextSetZone()
def _sendNextSetZone(self):
op, args, event = self.setZoneQueue.top()
if op == ToontownClientRepository.SetInterest:
parentId, interestZones, name = args
if self.old_setzone_interest_handle == None:
self.old_setzone_interest_handle = self.addInterest(parentId, interestZones, name, ToontownClientRepository.SetZoneDoneEvent)
else:
self.alterInterest(self.old_setzone_interest_handle, parentId, interestZones, name, ToontownClientRepository.SetZoneDoneEvent)
elif op == ToontownClientRepository.ClearInterest:
self.removeInterest(self.old_setzone_interest_handle, ToontownClientRepository.SetZoneDoneEvent)
self.old_setzone_interest_handle = None
else:
self.notify.error('unknown setZone op: %s' % op)
return
def _handleEmuSetZoneDone(self):
op, args, event = self.setZoneQueue.pop()
queueIsEmpty = self.setZoneQueue.isEmpty()
if event is not None:
if not base.killInterestResponse:
messenger.send(event)
elif not hasattr(self, '_dontSendSetZoneDone'):
import random
if random.random() < 0.05:
self._dontSendSetZoneDone = True
else:
messenger.send(event)
if not queueIsEmpty:
self._sendNextSetZone()
return
def _isPlayerDclass(self, dclass):
return dclass == self._playerAvDclass
def _isValidPlayerLocation(self, parentId, zoneId):
if not self.distributedDistrict:
return False
if parentId != self.distributedDistrict.doId:
return False
if parentId == self.distributedDistrict.doId and zoneId == OTPGlobals.UberZone:
return False
return True
def sendQuietZoneRequest(self):
if self.astronSupport:
self.sendSetZoneMsg(OTPGlobals.QuietZone, [])
else:
self.sendSetZoneMsg(OTPGlobals.QuietZone)
if not config.GetBool('astron-support', True):
def handleQuietZoneGenerateWithRequired(self, di):
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
doId = di.getUint32()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleQuietZoneGenerateWithRequiredOther(self, di):
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
doId = di.getUint32()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
else:
def handleQuietZoneGenerateWithRequired(self, di):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleQuietZoneGenerateWithRequiredOther(self, di):
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
dclass = self.dclassesByNumber[classId]
if dclass.getClassDef().neverDisable:
dclass.startGenerate()
distObj = self.generateWithRequiredOtherFields(dclass, doId, di, parentId, zoneId)
dclass.stopGenerate()
def handleGenerateWithRequiredOtherOwner(self, di):
# OwnerViews are only used for LocalToon in Toontown.
if self.loginFSM.getCurrentState().getName() == 'waitForSetAvatarResponse':
doId = di.getUint32()
parentId = di.getUint32()
zoneId = di.getUint32()
classId = di.getUint16()
self.handleAvatarResponseMsg(doId, di)
def handleQuietZoneUpdateField(self, di):
di2 = DatagramIterator(di)
doId = di2.getUint32()
if doId in self.deferredDoIds:
args, deferrable, dg0, updates = self.deferredDoIds[doId]
dclass = args[2]
if not dclass.getClassDef().neverDisable:
return
else:
do = self.getDo(doId)
if do:
if not do.neverDisable:
return
OTPClientRepository.OTPClientRepository.handleUpdateField(self, di)
def handleDelete(self, di):
doId = di.getUint32()
self.deleteObject(doId)
def deleteObject(self, doId, ownerView = False):
if self.doId2do.has_key(doId):
obj = self.doId2do[doId]
del self.doId2do[doId]
obj.deleteOrDelay()
if obj.getDelayDeleteCount() <= 0:
obj.detectLeaks()
elif self.cache.contains(doId):
self.cache.delete(doId)
else:
ClientRepository.notify.warning('Asked to delete non-existent DistObj ' + str(doId))
def _abandonShard(self):
for doId, obj in self.doId2do.items():
if obj.parentId == localAvatar.defaultShard and obj is not localAvatar:
self.deleteObject(doId)
def askAvatarKnown(self, avId):
if not hasattr(base, 'localAvatar'):
return 0
for friendPair in base.localAvatar.friendsList:
if friendPair[0] == avId:
return 1
return 0
def requestAvatarInfo(self, avId):
if avId == 0:
return
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST_EXTENDED)
datagram.addUint16(1)
datagram.addUint32(avId)
base.cr.send(datagram)
def queueRequestAvatarInfo(self, avId):
removeTask = 0
if not hasattr(self, 'avatarInfoRequests'):
self.avatarInfoRequests = []
if self.avatarInfoRequests:
taskMgr.remove('avatarRequestQueueTask')
if avId not in self.avatarInfoRequests:
self.avatarInfoRequests.append(avId)
taskMgr.doMethodLater(0.1, self.sendAvatarInfoRequests, 'avatarRequestQueueTask')
def sendAvatarInfoRequests(self, task = None):
print 'Sending request Queue for AV Handles'
if not hasattr(self, 'avatarInfoRequests'):
return
if len(self.avatarInfoRequests) == 0:
return
datagram = PyDatagram()
datagram.addUint16(CLIENT_GET_FRIEND_LIST_EXTENDED)
datagram.addUint16(len(self.avatarInfoRequests))
for avId in self.avatarInfoRequests:
datagram.addUint32(avId)
base.cr.send(datagram) | 0.244634 | 0.059102 |
from __future__ import absolute_import
import json
from awkward._v2.types.type import Type
import awkward as ak
np = ak.nplike.NumpyMetadata.instance()
_primitive_to_dtype = {
"bool": np.dtype(np.bool_),
"int8": np.dtype(np.int8),
"uint8": np.dtype(np.uint8),
"int16": np.dtype(np.int16),
"uint16": np.dtype(np.uint16),
"int32": np.dtype(np.int32),
"uint32": np.dtype(np.uint32),
"int64": np.dtype(np.int64),
"uint64": np.dtype(np.uint64),
"float32": np.dtype(np.float32),
"float64": np.dtype(np.float64),
"complex64": np.dtype(np.complex64),
"complex128": np.dtype(np.complex128),
"datetime64": np.dtype(np.datetime64),
"timedelta64": np.dtype(np.timedelta64),
}
if hasattr(np, "float16"):
_primitive_to_dtype["float16"] = np.dtype(np.float16)
if hasattr(np, "float128"):
_primitive_to_dtype["float128"] = np.dtype(np.float128)
if hasattr(np, "complex256"):
_primitive_to_dtype["complex256"] = np.dtype(np.complex256)
_dtype_to_primitive = {}
for primitive, dtype in _primitive_to_dtype.items():
_dtype_to_primitive[dtype] = primitive
class NumpyType(Type):
def __init__(self, primitive, parameters=None, typestr=None):
if primitive not in _primitive_to_dtype:
raise TypeError(
"{0} 'primitive' must be one of {1}, not {2}".format(
type(self).__name__,
", ".join(repr(x) for x in _primitive_to_dtype),
repr(primitive),
)
)
if parameters is not None and not isinstance(parameters, dict):
raise TypeError(
"{0} 'parameters' must be of type dict or None, not {1}".format(
type(self).__name__, repr(parameters)
)
)
if typestr is not None and not ak._util.isstr(typestr):
raise TypeError(
"{0} 'typestr' must be of type string or None, not {1}".format(
type(self).__name__, repr(typestr)
)
)
self._primitive = primitive
self._parameters = parameters
self._typestr = typestr
@property
def primitive(self):
return self._primitive
_str_parameters_exclude = ("__categorical__", "__unit__")
def __str__(self):
if self._typestr is not None:
out = self._typestr
elif self.parameter("__array__") == "char":
out = "char"
elif self.parameter("__array__") == "byte":
out = "byte"
else:
if self.parameter("__unit__") is not None:
numpy_unit = str(np.dtype("M8[" + self._parameters["__unit__"] + "]"))
bracket_index = numpy_unit.index("[")
units = "unit=" + json.dumps(numpy_unit[bracket_index + 1 : -1])
else:
units = None
params = self._str_parameters()
if units is None and params is None:
out = self._primitive
else:
if units is not None and params is not None:
units = units + ", "
elif units is None:
units = ""
elif params is None:
params = ""
out = self._primitive + "[" + units + params + "]"
return self._str_categorical_begin() + out + self._str_categorical_end()
def __repr__(self):
args = [repr(self._primitive)] + self._repr_args()
return "{0}({1})".format(type(self).__name__, ", ".join(args)) | src/awkward/_v2/types/numpytype.py |
from __future__ import absolute_import
import json
from awkward._v2.types.type import Type
import awkward as ak
np = ak.nplike.NumpyMetadata.instance()
_primitive_to_dtype = {
"bool": np.dtype(np.bool_),
"int8": np.dtype(np.int8),
"uint8": np.dtype(np.uint8),
"int16": np.dtype(np.int16),
"uint16": np.dtype(np.uint16),
"int32": np.dtype(np.int32),
"uint32": np.dtype(np.uint32),
"int64": np.dtype(np.int64),
"uint64": np.dtype(np.uint64),
"float32": np.dtype(np.float32),
"float64": np.dtype(np.float64),
"complex64": np.dtype(np.complex64),
"complex128": np.dtype(np.complex128),
"datetime64": np.dtype(np.datetime64),
"timedelta64": np.dtype(np.timedelta64),
}
if hasattr(np, "float16"):
_primitive_to_dtype["float16"] = np.dtype(np.float16)
if hasattr(np, "float128"):
_primitive_to_dtype["float128"] = np.dtype(np.float128)
if hasattr(np, "complex256"):
_primitive_to_dtype["complex256"] = np.dtype(np.complex256)
_dtype_to_primitive = {}
for primitive, dtype in _primitive_to_dtype.items():
_dtype_to_primitive[dtype] = primitive
class NumpyType(Type):
def __init__(self, primitive, parameters=None, typestr=None):
if primitive not in _primitive_to_dtype:
raise TypeError(
"{0} 'primitive' must be one of {1}, not {2}".format(
type(self).__name__,
", ".join(repr(x) for x in _primitive_to_dtype),
repr(primitive),
)
)
if parameters is not None and not isinstance(parameters, dict):
raise TypeError(
"{0} 'parameters' must be of type dict or None, not {1}".format(
type(self).__name__, repr(parameters)
)
)
if typestr is not None and not ak._util.isstr(typestr):
raise TypeError(
"{0} 'typestr' must be of type string or None, not {1}".format(
type(self).__name__, repr(typestr)
)
)
self._primitive = primitive
self._parameters = parameters
self._typestr = typestr
@property
def primitive(self):
return self._primitive
_str_parameters_exclude = ("__categorical__", "__unit__")
def __str__(self):
if self._typestr is not None:
out = self._typestr
elif self.parameter("__array__") == "char":
out = "char"
elif self.parameter("__array__") == "byte":
out = "byte"
else:
if self.parameter("__unit__") is not None:
numpy_unit = str(np.dtype("M8[" + self._parameters["__unit__"] + "]"))
bracket_index = numpy_unit.index("[")
units = "unit=" + json.dumps(numpy_unit[bracket_index + 1 : -1])
else:
units = None
params = self._str_parameters()
if units is None and params is None:
out = self._primitive
else:
if units is not None and params is not None:
units = units + ", "
elif units is None:
units = ""
elif params is None:
params = ""
out = self._primitive + "[" + units + params + "]"
return self._str_categorical_begin() + out + self._str_categorical_end()
def __repr__(self):
args = [repr(self._primitive)] + self._repr_args()
return "{0}({1})".format(type(self).__name__, ", ".join(args)) | 0.73307 | 0.261357 |
import os
import sys
from RLTest import Env
from redisgraph import Graph, Node, Edge
from base import FlowTestsBase
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../demo/social/')
import social_utils
redis_graph = None
class testIndexScanFlow(FlowTestsBase):
def __init__(self):
self.env = Env()
def setUp(self):
global redis_graph
redis_con = self.env.getConnection()
redis_graph = Graph(social_utils.graph_name, redis_con)
social_utils.populate_graph(redis_con, redis_graph)
self.build_indices()
def tearDown(self):
self.env.cmd('flushall')
def build_indices(self):
global redis_graph
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(age)")
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :country(name)")
# Validate that Cartesian products using index and label scans succeed
def test01_cartesian_product_mixed_scans(self):
query = "MATCH (p:person), (c:country) WHERE p.age > 0 RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
indexed_result = redis_graph.query(query)
query = "MATCH (p:person), (c:country) RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
unindexed_result = redis_graph.query(query)
self.env.assertEquals(indexed_result.result_set, unindexed_result.result_set)
# Validate that Cartesian products using just index scans succeed
def test02_cartesian_product_index_scans_only(self):
query = "MATCH (p:person), (c:country) WHERE p.age > 0 AND c.name > '' RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
# The two streams should both use index scans
self.env.assertEquals(plan.count('Index Scan'), 2)
self.env.assertNotIn('Label Scan', plan)
indexed_result = redis_graph.query(query)
query = "MATCH (p:person), (c:country) RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
unindexed_result = redis_graph.query(query)
self.env.assertEquals(indexed_result.result_set, unindexed_result.result_set)
# Validate that the appropriate bounds are respected when a Cartesian product uses the same index in two streams
def test03_cartesian_product_reused_index(self):
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(name)")
query = "MATCH (a:person {name: '<NAME>'}), (b:person) WHERE b.age <= 30 RETURN a.name, b.name ORDER BY a.name, b.name"
plan = redis_graph.execution_plan(query)
# The two streams should both use index scans
self.env.assertEquals(plan.count('Index Scan'), 2)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>', '<NAME>'],
['<NAME>', '<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate index utilization when filtering on a numeric field with the `IN` keyword.
def test04_test_in_operator_numerics(self):
# Validate the transformation of IN to multiple OR expressions.
query = "MATCH (p:person) WHERE p.age IN [1,2,3] RETURN p"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
# Validate that nested arrays are not scanned in index.
query = "MATCH (p:person) WHERE p.age IN [[1,2],3] RETURN p"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
# Validate the transformation of IN to multiple OR, over a range.
query = "MATCH (p:person) WHERE p.age IN range(0,30) RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of IN to empty index iterator.
query = "MATCH (p:person) WHERE p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of IN OR IN to empty index iterators.
query = "MATCH (p:person) WHERE p.age IN [] OR p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of multiple IN filters.
query = "MATCH (p:person) WHERE p.age IN [26, 27, 30] OR p.age IN [33, 34, 35] RETURN p.name ORDER BY p.age"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>'], ['Noam Nativ']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of multiple IN filters.
query = "MATCH (p:person) WHERE p.age IN [26, 27, 30] OR p.age IN [33, 34, 35] OR p.age IN [] RETURN p.name ORDER BY p.age"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>'], ['Noam Nativ']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate index utilization when filtering on string fields with the `IN` keyword.
def test05_test_in_operator_string_props(self):
# Build an index on the name property.
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(name)")
# Validate the transformation of IN to multiple OR expressions over string properties.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Combine numeric and string filters specified by IN.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] AND p.age in [30] RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['Lucy Yanfital']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate an empty index on IN with multiple indexes
query = "MATCH (p:person) WHERE p.name IN [] OR p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Combine IN filters with other relational filters.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] AND p.name < 'H' RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] OR p.age = 33 RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# ',' is the default separator for tag indices
# we've updated our separator to '\0' this test verifies issue 696:
# https://github.com/RedisGraph/RedisGraph/issues/696
def test06_tag_separator(self):
redis_con = self.env.getConnection()
redis_graph = Graph("G", redis_con)
# Create a single node with a long string property, introduce a comma as part of the string.
query = """CREATE (:Node{value:"A ValuePartition is a pattern that describes a restricted set of classes from which a property can be associated. The parent class is used in restrictions, and the covering axiom means that only members of the subclasses may be used as values."})"""
redis_graph.query(query)
# Index property.
query = """CREATE INDEX ON :Node(value)"""
redis_graph.query(query)
# Make sure node is returned by index scan.
query = """MATCH (a:Node{value:"A ValuePartition is a pattern that describes a restricted set of classes from which a property can be associated. The parent class is used in restrictions, and the covering axiom means that only members of the subclasses may be used as values."}) RETURN a"""
plan = redis_graph.execution_plan(query)
result_set = redis_graph.query(query).result_set
self.env.assertIn('Index Scan', plan)
self.env.assertEqual(len(result_set), 1)
def test07_index_scan_and_id(self):
redis_con = self.env.getConnection()
redis_graph = Graph("G", redis_con)
nodes=[]
for i in range(10):
node = Node(node_id=i, label='person', properties={'age':i})
nodes.append(node)
redis_graph.add_node(node)
redis_graph.flush()
query = """CREATE INDEX ON :person(age)"""
query_result = redis_graph.query(query)
self.env.assertEqual(1, query_result.indices_created)
query = """MATCH (n:person) WHERE id(n)>=7 AND n.age<9 RETURN n ORDER BY n.age"""
plan = redis_graph.execution_plan(query)
query_result = redis_graph.query(query)
self.env.assertIn('Index Scan', plan)
self.env.assertIn('Filter', plan)
query_result = redis_graph.query(query)
self.env.assertEqual(2, len(query_result.result_set))
expected_result = [[nodes[7]], [nodes[8]]]
self.env.assertEquals(expected_result, query_result.result_set)
# Validate placement of index scans and filter ops when not all filters can be replaced.
def test08_index_scan_multiple_filters(self):
query = "MATCH (p:person) WHERE p.age = 30 AND NOT EXISTS(p.fakeprop) RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
self.env.assertIn('Filter', plan)
query_result = redis_graph.query(query)
expected_result = ["<NAME>"]
self.env.assertEquals(query_result.result_set[0], expected_result) | tests/flow/test_index_scans.py | import os
import sys
from RLTest import Env
from redisgraph import Graph, Node, Edge
from base import FlowTestsBase
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../demo/social/')
import social_utils
redis_graph = None
class testIndexScanFlow(FlowTestsBase):
def __init__(self):
self.env = Env()
def setUp(self):
global redis_graph
redis_con = self.env.getConnection()
redis_graph = Graph(social_utils.graph_name, redis_con)
social_utils.populate_graph(redis_con, redis_graph)
self.build_indices()
def tearDown(self):
self.env.cmd('flushall')
def build_indices(self):
global redis_graph
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(age)")
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :country(name)")
# Validate that Cartesian products using index and label scans succeed
def test01_cartesian_product_mixed_scans(self):
query = "MATCH (p:person), (c:country) WHERE p.age > 0 RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
indexed_result = redis_graph.query(query)
query = "MATCH (p:person), (c:country) RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
unindexed_result = redis_graph.query(query)
self.env.assertEquals(indexed_result.result_set, unindexed_result.result_set)
# Validate that Cartesian products using just index scans succeed
def test02_cartesian_product_index_scans_only(self):
query = "MATCH (p:person), (c:country) WHERE p.age > 0 AND c.name > '' RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
# The two streams should both use index scans
self.env.assertEquals(plan.count('Index Scan'), 2)
self.env.assertNotIn('Label Scan', plan)
indexed_result = redis_graph.query(query)
query = "MATCH (p:person), (c:country) RETURN p.age, c.name ORDER BY p.age, c.name"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
unindexed_result = redis_graph.query(query)
self.env.assertEquals(indexed_result.result_set, unindexed_result.result_set)
# Validate that the appropriate bounds are respected when a Cartesian product uses the same index in two streams
def test03_cartesian_product_reused_index(self):
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(name)")
query = "MATCH (a:person {name: '<NAME>'}), (b:person) WHERE b.age <= 30 RETURN a.name, b.name ORDER BY a.name, b.name"
plan = redis_graph.execution_plan(query)
# The two streams should both use index scans
self.env.assertEquals(plan.count('Index Scan'), 2)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>', '<NAME>'],
['<NAME>', '<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate index utilization when filtering on a numeric field with the `IN` keyword.
def test04_test_in_operator_numerics(self):
# Validate the transformation of IN to multiple OR expressions.
query = "MATCH (p:person) WHERE p.age IN [1,2,3] RETURN p"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
# Validate that nested arrays are not scanned in index.
query = "MATCH (p:person) WHERE p.age IN [[1,2],3] RETURN p"
plan = redis_graph.execution_plan(query)
self.env.assertNotIn('Index Scan', plan)
self.env.assertIn('Label Scan', plan)
# Validate the transformation of IN to multiple OR, over a range.
query = "MATCH (p:person) WHERE p.age IN range(0,30) RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of IN to empty index iterator.
query = "MATCH (p:person) WHERE p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of IN OR IN to empty index iterators.
query = "MATCH (p:person) WHERE p.age IN [] OR p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of multiple IN filters.
query = "MATCH (p:person) WHERE p.age IN [26, 27, 30] OR p.age IN [33, 34, 35] RETURN p.name ORDER BY p.age"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>'], ['Noam Nativ']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate the transformation of multiple IN filters.
query = "MATCH (p:person) WHERE p.age IN [26, 27, 30] OR p.age IN [33, 34, 35] OR p.age IN [] RETURN p.name ORDER BY p.age"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>'], ['Noam Nativ']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate index utilization when filtering on string fields with the `IN` keyword.
def test05_test_in_operator_string_props(self):
# Build an index on the name property.
redis_graph.redis_con.execute_command("GRAPH.QUERY", "social", "CREATE INDEX ON :person(name)")
# Validate the transformation of IN to multiple OR expressions over string properties.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Combine numeric and string filters specified by IN.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] AND p.age in [30] RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['Lucy Yanfital']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Validate an empty index on IN with multiple indexes
query = "MATCH (p:person) WHERE p.name IN [] OR p.age IN [] RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
expected_result = []
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# Combine IN filters with other relational filters.
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] AND p.name < 'H' RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>']]
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
query = "MATCH (p:person) WHERE p.name IN ['<NAME>', '<NAME>'] OR p.age = 33 RETURN p.name ORDER BY p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
expected_result = [['<NAME>'], ['<NAME>'], ['<NAME>']]
result = redis_graph.query(query)
result = redis_graph.query(query)
self.env.assertEquals(result.result_set, expected_result)
# ',' is the default separator for tag indices
# we've updated our separator to '\0' this test verifies issue 696:
# https://github.com/RedisGraph/RedisGraph/issues/696
def test06_tag_separator(self):
redis_con = self.env.getConnection()
redis_graph = Graph("G", redis_con)
# Create a single node with a long string property, introduce a comma as part of the string.
query = """CREATE (:Node{value:"A ValuePartition is a pattern that describes a restricted set of classes from which a property can be associated. The parent class is used in restrictions, and the covering axiom means that only members of the subclasses may be used as values."})"""
redis_graph.query(query)
# Index property.
query = """CREATE INDEX ON :Node(value)"""
redis_graph.query(query)
# Make sure node is returned by index scan.
query = """MATCH (a:Node{value:"A ValuePartition is a pattern that describes a restricted set of classes from which a property can be associated. The parent class is used in restrictions, and the covering axiom means that only members of the subclasses may be used as values."}) RETURN a"""
plan = redis_graph.execution_plan(query)
result_set = redis_graph.query(query).result_set
self.env.assertIn('Index Scan', plan)
self.env.assertEqual(len(result_set), 1)
def test07_index_scan_and_id(self):
redis_con = self.env.getConnection()
redis_graph = Graph("G", redis_con)
nodes=[]
for i in range(10):
node = Node(node_id=i, label='person', properties={'age':i})
nodes.append(node)
redis_graph.add_node(node)
redis_graph.flush()
query = """CREATE INDEX ON :person(age)"""
query_result = redis_graph.query(query)
self.env.assertEqual(1, query_result.indices_created)
query = """MATCH (n:person) WHERE id(n)>=7 AND n.age<9 RETURN n ORDER BY n.age"""
plan = redis_graph.execution_plan(query)
query_result = redis_graph.query(query)
self.env.assertIn('Index Scan', plan)
self.env.assertIn('Filter', plan)
query_result = redis_graph.query(query)
self.env.assertEqual(2, len(query_result.result_set))
expected_result = [[nodes[7]], [nodes[8]]]
self.env.assertEquals(expected_result, query_result.result_set)
# Validate placement of index scans and filter ops when not all filters can be replaced.
def test08_index_scan_multiple_filters(self):
query = "MATCH (p:person) WHERE p.age = 30 AND NOT EXISTS(p.fakeprop) RETURN p.name"
plan = redis_graph.execution_plan(query)
self.env.assertIn('Index Scan', plan)
self.env.assertNotIn('Label Scan', plan)
self.env.assertIn('Filter', plan)
query_result = redis_graph.query(query)
expected_result = ["<NAME>"]
self.env.assertEquals(query_result.result_set[0], expected_result) | 0.490968 | 0.424233 |
from rantlib.core_application.ui.window.window import Window
from rantlib.core_application.ui.theme import *
from rantlib.core_application.ui.runnables.load_themes import LoadThemesRunnable
from rantlib.core_application.ui.parts.pg_theme_sample import ThemeSamplePage
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QLabel, QComboBox, QPushButton, QScrollArea
from PyQt5.QtCore import Qt, QThreadPool
from PyQt5.QtGui import QColor
class ThemeTool(Window):
def __init__(self, qtpy):
super().__init__(qtpy)
self.setWindowTitle("qtpy-rant Theme Tool")
self.setMinimumSize(550, 450)
self.thread_pool = QThreadPool()
self.theme_list = None
widget = QWidget()
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
widget.setLayout(layout)
self.setCentralWidget(widget)
sidebar = QWidget(widget)
sidebar.setMaximumWidth(250)
sidebar.setFixedWidth(250)
sidebar.setLayout(QHBoxLayout())
sidebar.layout().setContentsMargins(0, 0, 0, 0)
layout.addWidget(sidebar, 1)
sidebar_scroller = QScrollArea()
sidebar.layout().addWidget(sidebar_scroller, 1)
sidebar_scroller.setWidgetResizable(True)
sidebar_scroller.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
sidebar_widget = QWidget()
sidebar_scroller.setWidget(sidebar_widget)
sidebar_widget_layout = QVBoxLayout()
sidebar_widget.setLayout(sidebar_widget_layout)
sidebar_widget.setObjectName("sidebar_widget")
sidebar_widget.setStyleSheet("QWidget#sidebar_widget { background-color: #ededed; color: black; }")
sidebar_label = QLabel()
sidebar_label.setWordWrap(True)
sidebar_label.setText("The Theme Tool is used to preview a theme and detect errors")
sidebar_label.adjustSize()
sidebar_widget_layout.addWidget(sidebar_label, alignment=Qt.AlignTop)
theme_area = QWidget()
theme_area_layout = QVBoxLayout()
theme_area_layout.setContentsMargins(0, 0, 0, 0)
theme_area.setLayout(theme_area_layout)
layout.addWidget(theme_area, 1)
select_theme_widget = QWidget()
select_theme_layout = QHBoxLayout()
select_theme_layout.setSpacing(0)
select_theme_layout.setContentsMargins(0, 25, 0, 0)
select_theme_widget.setLayout(select_theme_layout)
select_theme_label = QLabel()
select_theme_label.setText("Theme: ")
select_theme_label.adjustSize()
select_theme_layout.addWidget(select_theme_label)
select_theme_combo = QComboBox()
select_theme_combo.addItem("Loading...")
select_theme_combo.setEnabled(False)
select_theme_layout.addWidget(select_theme_combo, 1)
select_theme_combo.currentIndexChanged.connect(self.change_theme)
self.select_theme_combo = select_theme_combo
sidebar_widget_layout.addWidget(select_theme_widget, alignment=Qt.AlignTop)
reload_theme_list_button = QLabel("Reload")
reload_theme_list_button.setStyleSheet("QLabel {color: blue; margin-left: 5px; text-decoration: underline}")
reload_theme_list_button.setCursor(Qt.PointingHandCursor)
reload_theme_list_button.mousePressEvent = self.handle_list_reload_click
select_theme_layout.addWidget(reload_theme_list_button)
self.reload_theme_list_button = reload_theme_list_button
sidebar_widget_layout.addStretch()
theme_area_scroller = QScrollArea()
theme_area_layout.addWidget(theme_area_scroller, 1)
theme_area_scroller.setWidgetResizable(True)
theme_sample_page = ThemeSamplePage(qtpy)
theme_area_scroller.setWidget(theme_sample_page.root)
self.theme_sample_page = theme_sample_page
self.spawn_theme_loader()
def handle_list_reload_click(self, e):
self.reload_theme_list_button.setDisabled(True)
select_theme_combo = self.select_theme_combo
select_theme_combo.clear()
select_theme_combo.addItem("Loading...")
select_theme_combo.setEnabled(False)
self.spawn_theme_loader()
def spawn_theme_loader(self):
self.thread_pool.start(LoadThemesRunnable(self.accept_theme_list))
def accept_theme_list(self, theme_list):
self.theme_list = theme_list
select_theme_combo = self.select_theme_combo
select_theme_combo.clear()
for theme in theme_list:
select_theme_combo.addItem(theme.title)
select_theme_combo.setEnabled(True)
self.reload_theme_list_button.setDisabled(False)
self.change_theme()
def change_theme(self):
if(self.select_theme_combo.currentIndex() == -1):
self.select_theme_combo.setCurrentIndex(0)
return
self.theme_sample_page.apply_theme(self.theme_list[self.select_theme_combo.currentIndex()]) | rantlib/core_application/ui/window/theme_tool.py | from rantlib.core_application.ui.window.window import Window
from rantlib.core_application.ui.theme import *
from rantlib.core_application.ui.runnables.load_themes import LoadThemesRunnable
from rantlib.core_application.ui.parts.pg_theme_sample import ThemeSamplePage
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QLabel, QComboBox, QPushButton, QScrollArea
from PyQt5.QtCore import Qt, QThreadPool
from PyQt5.QtGui import QColor
class ThemeTool(Window):
def __init__(self, qtpy):
super().__init__(qtpy)
self.setWindowTitle("qtpy-rant Theme Tool")
self.setMinimumSize(550, 450)
self.thread_pool = QThreadPool()
self.theme_list = None
widget = QWidget()
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
widget.setLayout(layout)
self.setCentralWidget(widget)
sidebar = QWidget(widget)
sidebar.setMaximumWidth(250)
sidebar.setFixedWidth(250)
sidebar.setLayout(QHBoxLayout())
sidebar.layout().setContentsMargins(0, 0, 0, 0)
layout.addWidget(sidebar, 1)
sidebar_scroller = QScrollArea()
sidebar.layout().addWidget(sidebar_scroller, 1)
sidebar_scroller.setWidgetResizable(True)
sidebar_scroller.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
sidebar_widget = QWidget()
sidebar_scroller.setWidget(sidebar_widget)
sidebar_widget_layout = QVBoxLayout()
sidebar_widget.setLayout(sidebar_widget_layout)
sidebar_widget.setObjectName("sidebar_widget")
sidebar_widget.setStyleSheet("QWidget#sidebar_widget { background-color: #ededed; color: black; }")
sidebar_label = QLabel()
sidebar_label.setWordWrap(True)
sidebar_label.setText("The Theme Tool is used to preview a theme and detect errors")
sidebar_label.adjustSize()
sidebar_widget_layout.addWidget(sidebar_label, alignment=Qt.AlignTop)
theme_area = QWidget()
theme_area_layout = QVBoxLayout()
theme_area_layout.setContentsMargins(0, 0, 0, 0)
theme_area.setLayout(theme_area_layout)
layout.addWidget(theme_area, 1)
select_theme_widget = QWidget()
select_theme_layout = QHBoxLayout()
select_theme_layout.setSpacing(0)
select_theme_layout.setContentsMargins(0, 25, 0, 0)
select_theme_widget.setLayout(select_theme_layout)
select_theme_label = QLabel()
select_theme_label.setText("Theme: ")
select_theme_label.adjustSize()
select_theme_layout.addWidget(select_theme_label)
select_theme_combo = QComboBox()
select_theme_combo.addItem("Loading...")
select_theme_combo.setEnabled(False)
select_theme_layout.addWidget(select_theme_combo, 1)
select_theme_combo.currentIndexChanged.connect(self.change_theme)
self.select_theme_combo = select_theme_combo
sidebar_widget_layout.addWidget(select_theme_widget, alignment=Qt.AlignTop)
reload_theme_list_button = QLabel("Reload")
reload_theme_list_button.setStyleSheet("QLabel {color: blue; margin-left: 5px; text-decoration: underline}")
reload_theme_list_button.setCursor(Qt.PointingHandCursor)
reload_theme_list_button.mousePressEvent = self.handle_list_reload_click
select_theme_layout.addWidget(reload_theme_list_button)
self.reload_theme_list_button = reload_theme_list_button
sidebar_widget_layout.addStretch()
theme_area_scroller = QScrollArea()
theme_area_layout.addWidget(theme_area_scroller, 1)
theme_area_scroller.setWidgetResizable(True)
theme_sample_page = ThemeSamplePage(qtpy)
theme_area_scroller.setWidget(theme_sample_page.root)
self.theme_sample_page = theme_sample_page
self.spawn_theme_loader()
def handle_list_reload_click(self, e):
self.reload_theme_list_button.setDisabled(True)
select_theme_combo = self.select_theme_combo
select_theme_combo.clear()
select_theme_combo.addItem("Loading...")
select_theme_combo.setEnabled(False)
self.spawn_theme_loader()
def spawn_theme_loader(self):
self.thread_pool.start(LoadThemesRunnable(self.accept_theme_list))
def accept_theme_list(self, theme_list):
self.theme_list = theme_list
select_theme_combo = self.select_theme_combo
select_theme_combo.clear()
for theme in theme_list:
select_theme_combo.addItem(theme.title)
select_theme_combo.setEnabled(True)
self.reload_theme_list_button.setDisabled(False)
self.change_theme()
def change_theme(self):
if(self.select_theme_combo.currentIndex() == -1):
self.select_theme_combo.setCurrentIndex(0)
return
self.theme_sample_page.apply_theme(self.theme_list[self.select_theme_combo.currentIndex()]) | 0.528047 | 0.071949 |
import errno
import select
import socket
import struct
import threading
import time
from paramiko.common import *
from paramiko import util
from paramiko.ssh_exception import SSHException, ProxyCommandFailure
from paramiko.message import Message
try:
from r_hmac import HMAC
except ImportError:
from Crypto.Hash.HMAC import HMAC
def compute_hmac(key, message, digest_class):
return HMAC(key, message, digest_class).digest()
class NeedRekeyException (Exception):
pass
class Packetizer (object):
"""
Implementation of the base SSH packet protocol.
"""
# READ the secsh RFC's before raising these values. if anything,
# they should probably be lower.
REKEY_PACKETS = pow(2, 29)
REKEY_BYTES = pow(2, 29)
REKEY_PACKETS_OVERFLOW_MAX = pow(2,29) # Allow receiving this many packets after a re-key request before terminating
REKEY_BYTES_OVERFLOW_MAX = pow(2,29) # Allow receiving this many bytes after a re-key request before terminating
def __init__(self, socket):
self.__socket = socket
self.__logger = None
self.__closed = False
self.__dump_packets = False
self.__need_rekey = False
self.__init_count = 0
self.__remainder = ''
# used for noticing when to re-key:
self.__sent_bytes = 0
self.__sent_packets = 0
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# current inbound/outbound ciphering:
self.__block_size_out = 8
self.__block_size_in = 8
self.__mac_size_out = 0
self.__mac_size_in = 0
self.__block_engine_out = None
self.__block_engine_in = None
self.__sdctr_out = False
self.__mac_engine_out = None
self.__mac_engine_in = None
self.__mac_key_out = ''
self.__mac_key_in = ''
self.__compress_engine_out = None
self.__compress_engine_in = None
self.__sequence_number_out = 0L
self.__sequence_number_in = 0L
# lock around outbound writes (packet computation)
self.__write_lock = threading.RLock()
# keepalives:
self.__keepalive_interval = 0
self.__keepalive_last = time.time()
self.__keepalive_callback = None
def set_log(self, log):
"""
Set the python log object to use for logging.
"""
self.__logger = log
def set_outbound_cipher(self, block_engine, block_size, mac_engine, mac_size, mac_key, sdctr=False):
"""
Switch outbound data cipher.
"""
self.__block_engine_out = block_engine
self.__sdctr_out = sdctr
self.__block_size_out = block_size
self.__mac_engine_out = mac_engine
self.__mac_size_out = mac_size
self.__mac_key_out = mac_key
self.__sent_bytes = 0
self.__sent_packets = 0
# wait until the reset happens in both directions before clearing rekey flag
self.__init_count |= 1
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False
def set_inbound_cipher(self, block_engine, block_size, mac_engine, mac_size, mac_key):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# wait until the reset happens in both directions before clearing rekey flag
self.__init_count |= 2
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False
def set_outbound_compressor(self, compressor):
self.__compress_engine_out = compressor
def set_inbound_compressor(self, compressor):
self.__compress_engine_in = compressor
def close(self):
self.__closed = True
def set_hexdump(self, hexdump):
self.__dump_packets = hexdump
def get_hexdump(self):
return self.__dump_packets
def get_mac_size_in(self):
return self.__mac_size_in
def get_mac_size_out(self):
return self.__mac_size_out
def need_rekey(self):
"""
Returns C{True} if a new set of keys needs to be negotiated. This
will be triggered during a packet read or write, so it should be
checked after every read or write, or at least after every few.
@return: C{True} if a new set of keys needs to be negotiated
"""
return self.__need_rekey
def set_keepalive(self, interval, callback):
"""
Turn on/off the callback keepalive. If C{interval} seconds pass with
no data read from or written to the socket, the callback will be
executed and the timer will be reset.
"""
self.__keepalive_interval = interval
self.__keepalive_callback = callback
self.__keepalive_last = time.time()
def read_all(self, n, check_rekey=False):
"""
Read as close to N bytes as possible, blocking as long as necessary.
@param n: number of bytes to read
@type n: int
@return: the data read
@rtype: str
@raise EOFError: if the socket was closed before all the bytes could
be read
"""
out = ''
# handle over-reading from reading the banner line
if len(self.__remainder) > 0:
out = self.__remainder[:n]
self.__remainder = self.__remainder[n:]
n -= len(out)
if PY22:
return self._py22_read_all(n, out)
while n > 0:
got_timeout = False
try:
x = self.__socket.recv(n)
if len(x) == 0:
raise EOFError()
out += x
n -= len(x)
except socket.timeout:
got_timeout = True
except socket.error, e:
# on Linux, sometimes instead of socket.timeout, we get
# EAGAIN. this is a bug in recent (> 2.6.9) kernels but
# we need to work around it.
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
got_timeout = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
# syscall interrupted; try again
pass
elif self.__closed:
raise EOFError()
else:
raise
if got_timeout:
if self.__closed:
raise EOFError()
if check_rekey and (len(out) == 0) and self.__need_rekey:
raise NeedRekeyException()
self._check_keepalive()
return out
def write_all(self, out):
self.__keepalive_last = time.time()
while len(out) > 0:
retry_write = False
try:
n = self.__socket.send(out)
except socket.timeout:
retry_write = True
except socket.error, e:
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
retry_write = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
# syscall interrupted; try again
retry_write = True
else:
n = -1
except ProxyCommandFailure:
raise # so it doesn't get swallowed by the below catchall
except Exception:
# could be: (32, 'Broken pipe')
n = -1
if retry_write:
n = 0
if self.__closed:
n = -1
if n < 0:
raise EOFError()
if n == len(out):
break
out = out[n:]
return
def readline(self, timeout):
"""
Read a line from the socket. We assume no data is pending after the
line, so it's okay to attempt large reads.
"""
buf = self.__remainder
while not '\n' in buf:
buf += self._read_timeout(timeout)
n = buf.index('\n')
self.__remainder = buf[n+1:]
buf = buf[:n]
if (len(buf) > 0) and (buf[-1] == '\r'):
buf = buf[:-1]
return buf
def send_message(self, data):
"""
Write a block of data using the current cipher, as an SSH block.
"""
# encrypt this sucka
data = str(data)
cmd = ord(data[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
orig_len = len(data)
self.__write_lock.acquire()
try:
if self.__compress_engine_out is not None:
data = self.__compress_engine_out(data)
packet = self._build_packet(data)
if self.__dump_packets:
self._log(DEBUG, 'Write packet <%s>, length %d' % (cmd_name, orig_len))
self._log(DEBUG, util.format_binary(packet, 'OUT: '))
if self.__block_engine_out != None:
out = self.__block_engine_out.encrypt(packet)
else:
out = packet
# + mac
if self.__block_engine_out != None:
payload = struct.pack('>I', self.__sequence_number_out) + packet
out += compute_hmac(self.__mac_key_out, payload, self.__mac_engine_out)[:self.__mac_size_out]
self.__sequence_number_out = (self.__sequence_number_out + 1) & 0xffffffffL
self.write_all(out)
self.__sent_bytes += len(out)
self.__sent_packets += 1
if ((self.__sent_packets >= self.REKEY_PACKETS) or (self.__sent_bytes >= self.REKEY_BYTES)) \
and not self.__need_rekey:
# only ask once for rekeying
self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes sent)' %
(self.__sent_packets, self.__sent_bytes))
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
self._trigger_rekey()
finally:
self.__write_lock.release()
def read_message(self):
"""
Only one thread should ever be in this function (no other locking is
done).
@raise SSHException: if the packet is mangled
@raise NeedRekeyException: if the transport should rekey
"""
header = self.read_all(self.__block_size_in, check_rekey=True)
if self.__block_engine_in != None:
header = self.__block_engine_in.decrypt(header)
if self.__dump_packets:
self._log(DEBUG, util.format_binary(header, 'IN: '));
packet_size = struct.unpack('>I', header[:4])[0]
# leftover contains decrypted bytes from the first block (after the length field)
leftover = header[4:]
if (packet_size - len(leftover)) % self.__block_size_in != 0:
raise SSHException('Invalid packet blocking')
buf = self.read_all(packet_size + self.__mac_size_in - len(leftover))
packet = buf[:packet_size - len(leftover)]
post_packet = buf[packet_size - len(leftover):]
if self.__block_engine_in != None:
packet = self.__block_engine_in.decrypt(packet)
if self.__dump_packets:
self._log(DEBUG, util.format_binary(packet, 'IN: '));
packet = leftover + packet
if self.__mac_size_in > 0:
mac = post_packet[:self.__mac_size_in]
mac_payload = struct.pack('>II', self.__sequence_number_in, packet_size) + packet
my_mac = compute_hmac(self.__mac_key_in, mac_payload, self.__mac_engine_in)[:self.__mac_size_in]
if my_mac != mac:
raise SSHException('Mismatched MAC')
padding = ord(packet[0])
payload = packet[1:packet_size - padding]
if self.__dump_packets:
self._log(DEBUG, 'Got payload (%d bytes, %d padding)' % (packet_size, padding))
if self.__compress_engine_in is not None:
payload = self.__compress_engine_in(payload)
msg = Message(payload[1:])
msg.seqno = self.__sequence_number_in
self.__sequence_number_in = (self.__sequence_number_in + 1) & 0xffffffffL
# check for rekey
raw_packet_size = packet_size + self.__mac_size_in + 4
self.__received_bytes += raw_packet_size
self.__received_packets += 1
if self.__need_rekey:
# we've asked to rekey -- give them some packets to comply before
# dropping the connection
self.__received_bytes_overflow += raw_packet_size
self.__received_packets_overflow += 1
if (self.__received_packets_overflow >= self.REKEY_PACKETS_OVERFLOW_MAX) or \
(self.__received_bytes_overflow >= self.REKEY_BYTES_OVERFLOW_MAX):
raise SSHException('Remote transport is ignoring rekey requests')
elif (self.__received_packets >= self.REKEY_PACKETS) or \
(self.__received_bytes >= self.REKEY_BYTES):
# only ask once for rekeying
self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes received)' %
(self.__received_packets, self.__received_bytes))
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
self._trigger_rekey()
cmd = ord(payload[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
if self.__dump_packets:
self._log(DEBUG, 'Read packet <%s>, length %d' % (cmd_name, len(payload)))
return cmd, msg
########## protected
def _log(self, level, msg):
if self.__logger is None:
return
if issubclass(type(msg), list):
for m in msg:
self.__logger.log(level, m)
else:
self.__logger.log(level, msg)
def _check_keepalive(self):
if (not self.__keepalive_interval) or (not self.__block_engine_out) or \
self.__need_rekey:
# wait till we're encrypting, and not in the middle of rekeying
return
now = time.time()
if now > self.__keepalive_last + self.__keepalive_interval:
self.__keepalive_callback()
self.__keepalive_last = now
def _py22_read_all(self, n, out):
while n > 0:
r, w, e = select.select([self.__socket], [], [], 0.1)
if self.__socket not in r:
if self.__closed:
raise EOFError()
self._check_keepalive()
else:
x = self.__socket.recv(n)
if len(x) == 0:
raise EOFError()
out += x
n -= len(x)
return out
def _py22_read_timeout(self, timeout):
start = time.time()
while True:
r, w, e = select.select([self.__socket], [], [], 0.1)
if self.__socket in r:
x = self.__socket.recv(1)
if len(x) == 0:
raise EOFError()
break
if self.__closed:
raise EOFError()
now = time.time()
if now - start >= timeout:
raise socket.timeout()
return x
def _read_timeout(self, timeout):
if PY22:
return self._py22_read_timeout(timeout)
start = time.time()
while True:
try:
x = self.__socket.recv(128)
if len(x) == 0:
raise EOFError()
break
except socket.timeout:
pass
except EnvironmentError, e:
if ((type(e.args) is tuple) and (len(e.args) > 0) and
(e.args[0] == errno.EINTR)):
pass
else:
raise
if self.__closed:
raise EOFError()
now = time.time()
if now - start >= timeout:
raise socket.timeout()
return x
def _build_packet(self, payload):
# pad up at least 4 bytes, to nearest block-size (usually 8)
bsize = self.__block_size_out
padding = 3 + bsize - ((len(payload) + 8) % bsize)
packet = struct.pack('>IB', len(payload) + padding + 1, padding)
packet += payload
if self.__sdctr_out or self.__block_engine_out is None:
# cute trick i caught openssh doing: if we're not encrypting or SDCTR mode (RFC4344),
# don't waste random bytes for the padding
packet += (chr(0) * padding)
else:
packet += rng.read(padding)
return packet
def _trigger_rekey(self):
# outside code should check for this flag
self.__need_rekey = True | .venv/lib/python2.7/site-packages/paramiko/packet.py | import errno
import select
import socket
import struct
import threading
import time
from paramiko.common import *
from paramiko import util
from paramiko.ssh_exception import SSHException, ProxyCommandFailure
from paramiko.message import Message
try:
from r_hmac import HMAC
except ImportError:
from Crypto.Hash.HMAC import HMAC
def compute_hmac(key, message, digest_class):
return HMAC(key, message, digest_class).digest()
class NeedRekeyException (Exception):
pass
class Packetizer (object):
"""
Implementation of the base SSH packet protocol.
"""
# READ the secsh RFC's before raising these values. if anything,
# they should probably be lower.
REKEY_PACKETS = pow(2, 29)
REKEY_BYTES = pow(2, 29)
REKEY_PACKETS_OVERFLOW_MAX = pow(2,29) # Allow receiving this many packets after a re-key request before terminating
REKEY_BYTES_OVERFLOW_MAX = pow(2,29) # Allow receiving this many bytes after a re-key request before terminating
def __init__(self, socket):
self.__socket = socket
self.__logger = None
self.__closed = False
self.__dump_packets = False
self.__need_rekey = False
self.__init_count = 0
self.__remainder = ''
# used for noticing when to re-key:
self.__sent_bytes = 0
self.__sent_packets = 0
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# current inbound/outbound ciphering:
self.__block_size_out = 8
self.__block_size_in = 8
self.__mac_size_out = 0
self.__mac_size_in = 0
self.__block_engine_out = None
self.__block_engine_in = None
self.__sdctr_out = False
self.__mac_engine_out = None
self.__mac_engine_in = None
self.__mac_key_out = ''
self.__mac_key_in = ''
self.__compress_engine_out = None
self.__compress_engine_in = None
self.__sequence_number_out = 0L
self.__sequence_number_in = 0L
# lock around outbound writes (packet computation)
self.__write_lock = threading.RLock()
# keepalives:
self.__keepalive_interval = 0
self.__keepalive_last = time.time()
self.__keepalive_callback = None
def set_log(self, log):
"""
Set the python log object to use for logging.
"""
self.__logger = log
def set_outbound_cipher(self, block_engine, block_size, mac_engine, mac_size, mac_key, sdctr=False):
"""
Switch outbound data cipher.
"""
self.__block_engine_out = block_engine
self.__sdctr_out = sdctr
self.__block_size_out = block_size
self.__mac_engine_out = mac_engine
self.__mac_size_out = mac_size
self.__mac_key_out = mac_key
self.__sent_bytes = 0
self.__sent_packets = 0
# wait until the reset happens in both directions before clearing rekey flag
self.__init_count |= 1
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False
def set_inbound_cipher(self, block_engine, block_size, mac_engine, mac_size, mac_key):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# wait until the reset happens in both directions before clearing rekey flag
self.__init_count |= 2
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False
def set_outbound_compressor(self, compressor):
self.__compress_engine_out = compressor
def set_inbound_compressor(self, compressor):
self.__compress_engine_in = compressor
def close(self):
self.__closed = True
def set_hexdump(self, hexdump):
self.__dump_packets = hexdump
def get_hexdump(self):
return self.__dump_packets
def get_mac_size_in(self):
return self.__mac_size_in
def get_mac_size_out(self):
return self.__mac_size_out
def need_rekey(self):
"""
Returns C{True} if a new set of keys needs to be negotiated. This
will be triggered during a packet read or write, so it should be
checked after every read or write, or at least after every few.
@return: C{True} if a new set of keys needs to be negotiated
"""
return self.__need_rekey
def set_keepalive(self, interval, callback):
"""
Turn on/off the callback keepalive. If C{interval} seconds pass with
no data read from or written to the socket, the callback will be
executed and the timer will be reset.
"""
self.__keepalive_interval = interval
self.__keepalive_callback = callback
self.__keepalive_last = time.time()
def read_all(self, n, check_rekey=False):
"""
Read as close to N bytes as possible, blocking as long as necessary.
@param n: number of bytes to read
@type n: int
@return: the data read
@rtype: str
@raise EOFError: if the socket was closed before all the bytes could
be read
"""
out = ''
# handle over-reading from reading the banner line
if len(self.__remainder) > 0:
out = self.__remainder[:n]
self.__remainder = self.__remainder[n:]
n -= len(out)
if PY22:
return self._py22_read_all(n, out)
while n > 0:
got_timeout = False
try:
x = self.__socket.recv(n)
if len(x) == 0:
raise EOFError()
out += x
n -= len(x)
except socket.timeout:
got_timeout = True
except socket.error, e:
# on Linux, sometimes instead of socket.timeout, we get
# EAGAIN. this is a bug in recent (> 2.6.9) kernels but
# we need to work around it.
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
got_timeout = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
# syscall interrupted; try again
pass
elif self.__closed:
raise EOFError()
else:
raise
if got_timeout:
if self.__closed:
raise EOFError()
if check_rekey and (len(out) == 0) and self.__need_rekey:
raise NeedRekeyException()
self._check_keepalive()
return out
def write_all(self, out):
self.__keepalive_last = time.time()
while len(out) > 0:
retry_write = False
try:
n = self.__socket.send(out)
except socket.timeout:
retry_write = True
except socket.error, e:
if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN):
retry_write = True
elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR):
# syscall interrupted; try again
retry_write = True
else:
n = -1
except ProxyCommandFailure:
raise # so it doesn't get swallowed by the below catchall
except Exception:
# could be: (32, 'Broken pipe')
n = -1
if retry_write:
n = 0
if self.__closed:
n = -1
if n < 0:
raise EOFError()
if n == len(out):
break
out = out[n:]
return
def readline(self, timeout):
"""
Read a line from the socket. We assume no data is pending after the
line, so it's okay to attempt large reads.
"""
buf = self.__remainder
while not '\n' in buf:
buf += self._read_timeout(timeout)
n = buf.index('\n')
self.__remainder = buf[n+1:]
buf = buf[:n]
if (len(buf) > 0) and (buf[-1] == '\r'):
buf = buf[:-1]
return buf
def send_message(self, data):
"""
Write a block of data using the current cipher, as an SSH block.
"""
# encrypt this sucka
data = str(data)
cmd = ord(data[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
orig_len = len(data)
self.__write_lock.acquire()
try:
if self.__compress_engine_out is not None:
data = self.__compress_engine_out(data)
packet = self._build_packet(data)
if self.__dump_packets:
self._log(DEBUG, 'Write packet <%s>, length %d' % (cmd_name, orig_len))
self._log(DEBUG, util.format_binary(packet, 'OUT: '))
if self.__block_engine_out != None:
out = self.__block_engine_out.encrypt(packet)
else:
out = packet
# + mac
if self.__block_engine_out != None:
payload = struct.pack('>I', self.__sequence_number_out) + packet
out += compute_hmac(self.__mac_key_out, payload, self.__mac_engine_out)[:self.__mac_size_out]
self.__sequence_number_out = (self.__sequence_number_out + 1) & 0xffffffffL
self.write_all(out)
self.__sent_bytes += len(out)
self.__sent_packets += 1
if ((self.__sent_packets >= self.REKEY_PACKETS) or (self.__sent_bytes >= self.REKEY_BYTES)) \
and not self.__need_rekey:
# only ask once for rekeying
self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes sent)' %
(self.__sent_packets, self.__sent_bytes))
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
self._trigger_rekey()
finally:
self.__write_lock.release()
def read_message(self):
"""
Only one thread should ever be in this function (no other locking is
done).
@raise SSHException: if the packet is mangled
@raise NeedRekeyException: if the transport should rekey
"""
header = self.read_all(self.__block_size_in, check_rekey=True)
if self.__block_engine_in != None:
header = self.__block_engine_in.decrypt(header)
if self.__dump_packets:
self._log(DEBUG, util.format_binary(header, 'IN: '));
packet_size = struct.unpack('>I', header[:4])[0]
# leftover contains decrypted bytes from the first block (after the length field)
leftover = header[4:]
if (packet_size - len(leftover)) % self.__block_size_in != 0:
raise SSHException('Invalid packet blocking')
buf = self.read_all(packet_size + self.__mac_size_in - len(leftover))
packet = buf[:packet_size - len(leftover)]
post_packet = buf[packet_size - len(leftover):]
if self.__block_engine_in != None:
packet = self.__block_engine_in.decrypt(packet)
if self.__dump_packets:
self._log(DEBUG, util.format_binary(packet, 'IN: '));
packet = leftover + packet
if self.__mac_size_in > 0:
mac = post_packet[:self.__mac_size_in]
mac_payload = struct.pack('>II', self.__sequence_number_in, packet_size) + packet
my_mac = compute_hmac(self.__mac_key_in, mac_payload, self.__mac_engine_in)[:self.__mac_size_in]
if my_mac != mac:
raise SSHException('Mismatched MAC')
padding = ord(packet[0])
payload = packet[1:packet_size - padding]
if self.__dump_packets:
self._log(DEBUG, 'Got payload (%d bytes, %d padding)' % (packet_size, padding))
if self.__compress_engine_in is not None:
payload = self.__compress_engine_in(payload)
msg = Message(payload[1:])
msg.seqno = self.__sequence_number_in
self.__sequence_number_in = (self.__sequence_number_in + 1) & 0xffffffffL
# check for rekey
raw_packet_size = packet_size + self.__mac_size_in + 4
self.__received_bytes += raw_packet_size
self.__received_packets += 1
if self.__need_rekey:
# we've asked to rekey -- give them some packets to comply before
# dropping the connection
self.__received_bytes_overflow += raw_packet_size
self.__received_packets_overflow += 1
if (self.__received_packets_overflow >= self.REKEY_PACKETS_OVERFLOW_MAX) or \
(self.__received_bytes_overflow >= self.REKEY_BYTES_OVERFLOW_MAX):
raise SSHException('Remote transport is ignoring rekey requests')
elif (self.__received_packets >= self.REKEY_PACKETS) or \
(self.__received_bytes >= self.REKEY_BYTES):
# only ask once for rekeying
self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes received)' %
(self.__received_packets, self.__received_bytes))
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
self._trigger_rekey()
cmd = ord(payload[0])
if cmd in MSG_NAMES:
cmd_name = MSG_NAMES[cmd]
else:
cmd_name = '$%x' % cmd
if self.__dump_packets:
self._log(DEBUG, 'Read packet <%s>, length %d' % (cmd_name, len(payload)))
return cmd, msg
########## protected
def _log(self, level, msg):
if self.__logger is None:
return
if issubclass(type(msg), list):
for m in msg:
self.__logger.log(level, m)
else:
self.__logger.log(level, msg)
def _check_keepalive(self):
if (not self.__keepalive_interval) or (not self.__block_engine_out) or \
self.__need_rekey:
# wait till we're encrypting, and not in the middle of rekeying
return
now = time.time()
if now > self.__keepalive_last + self.__keepalive_interval:
self.__keepalive_callback()
self.__keepalive_last = now
def _py22_read_all(self, n, out):
while n > 0:
r, w, e = select.select([self.__socket], [], [], 0.1)
if self.__socket not in r:
if self.__closed:
raise EOFError()
self._check_keepalive()
else:
x = self.__socket.recv(n)
if len(x) == 0:
raise EOFError()
out += x
n -= len(x)
return out
def _py22_read_timeout(self, timeout):
start = time.time()
while True:
r, w, e = select.select([self.__socket], [], [], 0.1)
if self.__socket in r:
x = self.__socket.recv(1)
if len(x) == 0:
raise EOFError()
break
if self.__closed:
raise EOFError()
now = time.time()
if now - start >= timeout:
raise socket.timeout()
return x
def _read_timeout(self, timeout):
if PY22:
return self._py22_read_timeout(timeout)
start = time.time()
while True:
try:
x = self.__socket.recv(128)
if len(x) == 0:
raise EOFError()
break
except socket.timeout:
pass
except EnvironmentError, e:
if ((type(e.args) is tuple) and (len(e.args) > 0) and
(e.args[0] == errno.EINTR)):
pass
else:
raise
if self.__closed:
raise EOFError()
now = time.time()
if now - start >= timeout:
raise socket.timeout()
return x
def _build_packet(self, payload):
# pad up at least 4 bytes, to nearest block-size (usually 8)
bsize = self.__block_size_out
padding = 3 + bsize - ((len(payload) + 8) % bsize)
packet = struct.pack('>IB', len(payload) + padding + 1, padding)
packet += payload
if self.__sdctr_out or self.__block_engine_out is None:
# cute trick i caught openssh doing: if we're not encrypting or SDCTR mode (RFC4344),
# don't waste random bytes for the padding
packet += (chr(0) * padding)
else:
packet += rng.read(padding)
return packet
def _trigger_rekey(self):
# outside code should check for this flag
self.__need_rekey = True | 0.563498 | 0.094552 |
import argparse
import logging
from collections import defaultdict
from paasta_tools.config_utils import AutoConfigUpdater
from paasta_tools.contrib.paasta_update_soa_memcpu import get_report_from_splunk
from paasta_tools.utils import DEFAULT_SOA_CONFIGS_GIT_URL
from paasta_tools.utils import format_git_url
from paasta_tools.utils import load_system_paasta_config
NULL = "null"
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument(
"-s",
"--splunk-creds",
help="Service credentials for Splunk API, user:pass",
dest="splunk_creds",
required=True,
)
parser.add_argument(
"-f",
"--criteria-filter",
help="Filter Splunk search results criteria field. Default: *",
dest="criteria_filter",
required=False,
default="*",
)
parser.add_argument(
"-c",
"--csv-report",
help="Splunk csv file from which to pull data.",
required=True,
dest="csv_report",
)
parser.add_argument(
"--app",
help="Splunk app of the CSV file",
default="yelp_computeinfra",
required=False,
dest="splunk_app",
)
parser.add_argument(
"--git-remote",
help="Master git repo for soaconfigs",
default=None,
dest="git_remote",
)
parser.add_argument(
"--branch",
help="Branch name to push to. Defaults to master",
default="master",
required=False,
dest="branch",
)
parser.add_argument(
"--push-to-remote",
help="Actually push to remote. Otherwise files will only be modified and validated.",
action="store_true",
dest="push_to_remote",
)
parser.add_argument(
"--local-dir",
help="Act on configs in the local directory rather than cloning the git_remote",
required=False,
default=None,
dest="local_dir",
)
parser.add_argument(
"--source-id",
help="String to attribute the changes in the commit message. Defaults to csv report name",
required=False,
default=None,
dest="source_id",
)
parser.add_argument(
"-v",
"--verbose",
help="Logging verbosity",
action="store_true",
dest="verbose",
)
return parser.parse_args()
def get_default_git_remote():
system_paasta_config = load_system_paasta_config()
repo_config = system_paasta_config.get_git_repo_config("yelpsoa-configs")
default_git_remote = format_git_url(
system_paasta_config.get_git_config()["git_user"],
repo_config.get("git_server", DEFAULT_SOA_CONFIGS_GIT_URL),
repo_config["repo_name"],
)
return default_git_remote
def get_recommendation_from_result(result):
rec = {}
cpus = result.get("cpus")
if cpus and cpus != NULL:
rec["cpus"] = float(cpus)
mem = result.get("mem")
if mem and mem != NULL:
rec["mem"] = max(128, round(float(mem)))
disk = result.get("disk")
if disk and disk != NULL:
rec["disk"] = max(128, round(float(disk)))
hacheck_cpus = result.get("hacheck_cpus")
if hacheck_cpus and hacheck_cpus != NULL:
hacheck_cpus_value = max(0.1, min(float(hacheck_cpus), 1))
rec["sidecar_resource_requirements"] = {
"hacheck": {
"requests": {"cpu": hacheck_cpus_value,},
"limits": {"cpu": hacheck_cpus_value,},
},
}
return rec
def get_recommendations_by_service_file(results):
results_by_service_file = defaultdict(dict)
for result in results.values():
key = (
result["service"],
result["cluster"],
) # e.g. (foo, marathon-norcal-stagef)
rec = get_recommendation_from_result(result)
if not rec:
continue
results_by_service_file[key][result["instance"]] = rec
return results_by_service_file
def get_extra_message(splunk_search_string):
return f"""This review is based on results from the following Splunk search:\n
{splunk_search_string}
"""
def main(args):
report = get_report_from_splunk(
args.splunk_creds, args.splunk_app, args.csv_report, args.criteria_filter
)
extra_message = get_extra_message(report["search"])
config_source = args.source_id or args.csv_report
results = get_recommendations_by_service_file(report["results"])
updater = AutoConfigUpdater(
config_source=config_source,
git_remote=args.git_remote or get_default_git_remote(),
branch=args.branch,
working_dir=args.local_dir or "/nail/tmp",
do_clone=args.local_dir is None,
)
with updater:
for (service, extra_info), instance_recommendations in results.items():
existing_recommendations = updater.get_existing_configs(service, extra_info)
for instance_name, recommendation in instance_recommendations.items():
existing_recommendations.setdefault(instance_name, {})
existing_recommendations[instance_name].update(recommendation)
updater.write_configs(service, extra_info, existing_recommendations)
if args.push_to_remote:
updater.commit_to_remote(extra_message=extra_message)
else:
updater.validate()
if __name__ == "__main__":
args = parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
main(args) | paasta_tools/contrib/rightsizer_soaconfigs_update.py | import argparse
import logging
from collections import defaultdict
from paasta_tools.config_utils import AutoConfigUpdater
from paasta_tools.contrib.paasta_update_soa_memcpu import get_report_from_splunk
from paasta_tools.utils import DEFAULT_SOA_CONFIGS_GIT_URL
from paasta_tools.utils import format_git_url
from paasta_tools.utils import load_system_paasta_config
NULL = "null"
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument(
"-s",
"--splunk-creds",
help="Service credentials for Splunk API, user:pass",
dest="splunk_creds",
required=True,
)
parser.add_argument(
"-f",
"--criteria-filter",
help="Filter Splunk search results criteria field. Default: *",
dest="criteria_filter",
required=False,
default="*",
)
parser.add_argument(
"-c",
"--csv-report",
help="Splunk csv file from which to pull data.",
required=True,
dest="csv_report",
)
parser.add_argument(
"--app",
help="Splunk app of the CSV file",
default="yelp_computeinfra",
required=False,
dest="splunk_app",
)
parser.add_argument(
"--git-remote",
help="Master git repo for soaconfigs",
default=None,
dest="git_remote",
)
parser.add_argument(
"--branch",
help="Branch name to push to. Defaults to master",
default="master",
required=False,
dest="branch",
)
parser.add_argument(
"--push-to-remote",
help="Actually push to remote. Otherwise files will only be modified and validated.",
action="store_true",
dest="push_to_remote",
)
parser.add_argument(
"--local-dir",
help="Act on configs in the local directory rather than cloning the git_remote",
required=False,
default=None,
dest="local_dir",
)
parser.add_argument(
"--source-id",
help="String to attribute the changes in the commit message. Defaults to csv report name",
required=False,
default=None,
dest="source_id",
)
parser.add_argument(
"-v",
"--verbose",
help="Logging verbosity",
action="store_true",
dest="verbose",
)
return parser.parse_args()
def get_default_git_remote():
system_paasta_config = load_system_paasta_config()
repo_config = system_paasta_config.get_git_repo_config("yelpsoa-configs")
default_git_remote = format_git_url(
system_paasta_config.get_git_config()["git_user"],
repo_config.get("git_server", DEFAULT_SOA_CONFIGS_GIT_URL),
repo_config["repo_name"],
)
return default_git_remote
def get_recommendation_from_result(result):
rec = {}
cpus = result.get("cpus")
if cpus and cpus != NULL:
rec["cpus"] = float(cpus)
mem = result.get("mem")
if mem and mem != NULL:
rec["mem"] = max(128, round(float(mem)))
disk = result.get("disk")
if disk and disk != NULL:
rec["disk"] = max(128, round(float(disk)))
hacheck_cpus = result.get("hacheck_cpus")
if hacheck_cpus and hacheck_cpus != NULL:
hacheck_cpus_value = max(0.1, min(float(hacheck_cpus), 1))
rec["sidecar_resource_requirements"] = {
"hacheck": {
"requests": {"cpu": hacheck_cpus_value,},
"limits": {"cpu": hacheck_cpus_value,},
},
}
return rec
def get_recommendations_by_service_file(results):
results_by_service_file = defaultdict(dict)
for result in results.values():
key = (
result["service"],
result["cluster"],
) # e.g. (foo, marathon-norcal-stagef)
rec = get_recommendation_from_result(result)
if not rec:
continue
results_by_service_file[key][result["instance"]] = rec
return results_by_service_file
def get_extra_message(splunk_search_string):
return f"""This review is based on results from the following Splunk search:\n
{splunk_search_string}
"""
def main(args):
report = get_report_from_splunk(
args.splunk_creds, args.splunk_app, args.csv_report, args.criteria_filter
)
extra_message = get_extra_message(report["search"])
config_source = args.source_id or args.csv_report
results = get_recommendations_by_service_file(report["results"])
updater = AutoConfigUpdater(
config_source=config_source,
git_remote=args.git_remote or get_default_git_remote(),
branch=args.branch,
working_dir=args.local_dir or "/nail/tmp",
do_clone=args.local_dir is None,
)
with updater:
for (service, extra_info), instance_recommendations in results.items():
existing_recommendations = updater.get_existing_configs(service, extra_info)
for instance_name, recommendation in instance_recommendations.items():
existing_recommendations.setdefault(instance_name, {})
existing_recommendations[instance_name].update(recommendation)
updater.write_configs(service, extra_info, existing_recommendations)
if args.push_to_remote:
updater.commit_to_remote(extra_message=extra_message)
else:
updater.validate()
if __name__ == "__main__":
args = parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
main(args) | 0.462716 | 0.100879 |
import logging
import sys
from os.path import join
from subprocess import CalledProcessError
from pkgpanda.util import write_string
LOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s'
logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO)
log = logging.getLogger(__name__)
def integration_test(
tunnel, test_dir,
dcos_dns, master_list, agent_list, public_agent_list,
test_dns_search, provider,
aws_access_key_id='', aws_secret_access_key='', region='', add_env=None,
pytest_cmd='py.test -vv',
pytest_dir='/opt/mesosphere/active/dcos-integration-test'):
"""Runs integration test on host
Args:
test_dir: directory to leave test_wrapper.sh
dcos_dns: string representing IP of DCOS DNS host
master_list: string of comma separated master addresses
agent_list: string of comma separated agent addresses
test_dns_search: if set to True, test for deployed mesos DNS app
provider: (str) either onprem, aws, or azure
Optional args:
aws_access_key_id: needed for REXRAY tests
aws_secret_access_key: needed for REXRAY tests
region: string indicating AWS region in which cluster is running
add_env: a python dict with any number of key=value assignments to be passed to
the test environment
pytest_dir: directory of test package on test host
pytest_cmd: string representing command for py.test
Returns:
exit code corresponding to test_cmd run
"""
dns_search = 'true' if test_dns_search else 'false'
test_env = [
'DCOS_DNS_ADDRESS=http://'+dcos_dns,
'MASTER_HOSTS='+','.join(master_list),
'PUBLIC_MASTER_HOSTS='+','.join(master_list),
'SLAVE_HOSTS='+','.join(agent_list),
'PUBLIC_SLAVE_HOSTS='+','.join(public_agent_list),
'DCOS_PROVIDER='+provider,
'DNS_SEARCH='+dns_search,
'AWS_ACCESS_KEY_ID='+aws_access_key_id,
'AWS_SECRET_ACCESS_KEY='+aws_secret_access_key,
'AWS_REGION='+region]
if add_env:
for key, value in add_env.items():
extra_env = key + '=' + value
test_env.append(extra_env)
test_env_str = ''.join(['export '+e+'\n' for e in test_env])
test_boilerplate = """#!/bin/bash
source /opt/mesosphere/environment.export
{env}
cd {pytest_dir}
{cmd}
"""
write_string('test_preflight.sh', test_boilerplate.format(
env=test_env_str, pytest_dir=pytest_dir,
cmd='py.test -vv --collect-only'))
write_string('test_wrapper.sh', test_boilerplate.format(
env=test_env_str, pytest_dir=pytest_dir,
cmd=pytest_cmd))
pretest_path = join(test_dir, 'test_preflight.sh')
log.info('Running integration test setup check...')
tunnel.write_to_remote('test_preflight.sh', pretest_path)
tunnel.remote_cmd(['bash', pretest_path], stdout=sys.stdout.buffer)
wrapper_path = join(test_dir, 'test_wrapper.sh')
log.info('Running integration test...')
tunnel.write_to_remote('test_wrapper.sh', wrapper_path)
try:
tunnel.remote_cmd(['bash', wrapper_path], stdout=sys.stdout.buffer)
except CalledProcessError as e:
return e.returncode
return 0 | test_util/test_runner.py | import logging
import sys
from os.path import join
from subprocess import CalledProcessError
from pkgpanda.util import write_string
LOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s'
logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO)
log = logging.getLogger(__name__)
def integration_test(
tunnel, test_dir,
dcos_dns, master_list, agent_list, public_agent_list,
test_dns_search, provider,
aws_access_key_id='', aws_secret_access_key='', region='', add_env=None,
pytest_cmd='py.test -vv',
pytest_dir='/opt/mesosphere/active/dcos-integration-test'):
"""Runs integration test on host
Args:
test_dir: directory to leave test_wrapper.sh
dcos_dns: string representing IP of DCOS DNS host
master_list: string of comma separated master addresses
agent_list: string of comma separated agent addresses
test_dns_search: if set to True, test for deployed mesos DNS app
provider: (str) either onprem, aws, or azure
Optional args:
aws_access_key_id: needed for REXRAY tests
aws_secret_access_key: needed for REXRAY tests
region: string indicating AWS region in which cluster is running
add_env: a python dict with any number of key=value assignments to be passed to
the test environment
pytest_dir: directory of test package on test host
pytest_cmd: string representing command for py.test
Returns:
exit code corresponding to test_cmd run
"""
dns_search = 'true' if test_dns_search else 'false'
test_env = [
'DCOS_DNS_ADDRESS=http://'+dcos_dns,
'MASTER_HOSTS='+','.join(master_list),
'PUBLIC_MASTER_HOSTS='+','.join(master_list),
'SLAVE_HOSTS='+','.join(agent_list),
'PUBLIC_SLAVE_HOSTS='+','.join(public_agent_list),
'DCOS_PROVIDER='+provider,
'DNS_SEARCH='+dns_search,
'AWS_ACCESS_KEY_ID='+aws_access_key_id,
'AWS_SECRET_ACCESS_KEY='+aws_secret_access_key,
'AWS_REGION='+region]
if add_env:
for key, value in add_env.items():
extra_env = key + '=' + value
test_env.append(extra_env)
test_env_str = ''.join(['export '+e+'\n' for e in test_env])
test_boilerplate = """#!/bin/bash
source /opt/mesosphere/environment.export
{env}
cd {pytest_dir}
{cmd}
"""
write_string('test_preflight.sh', test_boilerplate.format(
env=test_env_str, pytest_dir=pytest_dir,
cmd='py.test -vv --collect-only'))
write_string('test_wrapper.sh', test_boilerplate.format(
env=test_env_str, pytest_dir=pytest_dir,
cmd=pytest_cmd))
pretest_path = join(test_dir, 'test_preflight.sh')
log.info('Running integration test setup check...')
tunnel.write_to_remote('test_preflight.sh', pretest_path)
tunnel.remote_cmd(['bash', pretest_path], stdout=sys.stdout.buffer)
wrapper_path = join(test_dir, 'test_wrapper.sh')
log.info('Running integration test...')
tunnel.write_to_remote('test_wrapper.sh', wrapper_path)
try:
tunnel.remote_cmd(['bash', wrapper_path], stdout=sys.stdout.buffer)
except CalledProcessError as e:
return e.returncode
return 0 | 0.404625 | 0.192046 |
import struct
from bxcommon import constants
from bxcommon.messages.abstract_internal_message import AbstractInternalMessage
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
from bxcommon.messages.bloxroute.abstract_broadcast_message import AbstractBroadcastMessage
from bxcommon.messages.bloxroute.bloxroute_message_type import BloxrouteMessageType
from bxcommon.messages.bloxroute.broadcast_message import BroadcastMessage
from bxcommon.messages.bloxroute.v8.broadcast_message_v8 import BroadcastMessageV8
from bxcommon.messages.versioning.abstract_message_converter import AbstractMessageConverter
from bxcommon.models.broadcast_message_type import BroadcastMessageType
class _BroadcastMessageConverterV8(AbstractMessageConverter):
_MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING = {
BloxrouteMessageType.BROADCAST: BroadcastMessageV8
}
_MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING = {
BloxrouteMessageType.BROADCAST: BroadcastMessage
}
_BASE_LENGTH = (
AbstractBroadcastMessage.HEADER_LENGTH
+ AbstractBroadcastMessage.PAYLOAD_LENGTH
- constants.CONTROL_FLAGS_LEN
)
_BREAKPOINT = (
_BASE_LENGTH + constants.BROADCAST_TYPE_LEN
)
def convert_to_older_version(
self, msg: AbstractInternalMessage
) -> AbstractInternalMessage:
msg_type = msg.MESSAGE_TYPE
if msg_type not in self._MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING:
raise ValueError(
f"Tried to convert unexpected new message type to v8: {msg_type}"
)
old_version_msg_class = self._MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING[
msg_type
]
old_version_payload_len = msg.payload_len() - constants.BROADCAST_TYPE_LEN
old_version_msg_bytes = bytearray(self._BASE_LENGTH + len(msg.rawbytes()[self._BREAKPOINT:]))
old_version_msg_bytes[:self._BASE_LENGTH] = msg.rawbytes()[:self._BASE_LENGTH]
old_version_msg_bytes[self._BASE_LENGTH:] = msg.rawbytes()[self._BREAKPOINT:]
return AbstractBloxrouteMessage.initialize_class(
old_version_msg_class,
old_version_msg_bytes,
(msg_type, old_version_payload_len),
)
def convert_from_older_version(
self, msg: AbstractInternalMessage
) -> AbstractInternalMessage:
msg_type = msg.MESSAGE_TYPE
if msg_type not in self._MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING:
raise ValueError(
f"Tried to convert unexpected old message type to v9: {msg_type}"
)
new_msg_class = self._MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING[msg_type]
new_payload_len = msg.payload_len() + constants.BROADCAST_TYPE_LEN
new_msg_bytes = bytearray(AbstractBloxrouteMessage.HEADER_LENGTH + new_payload_len)
new_msg_bytes[:self._BASE_LENGTH] = msg.rawbytes()[:self._BASE_LENGTH]
struct.pack_into(
"<4s",
new_msg_bytes,
self._BASE_LENGTH,
# pylint: disable=no-member
BroadcastMessageType.BLOCK.value.encode(constants.DEFAULT_TEXT_ENCODING)
)
new_msg_bytes[self._BREAKPOINT:] = msg.rawbytes()[self._BASE_LENGTH:]
return AbstractBloxrouteMessage.initialize_class(
new_msg_class,
new_msg_bytes,
(msg_type, new_payload_len)
)
def convert_first_bytes_to_older_version(
self, first_msg_bytes: memoryview
) -> memoryview:
if len(first_msg_bytes) < AbstractBloxrouteMessage.HEADER_LENGTH + AbstractBroadcastMessage.PAYLOAD_LENGTH - \
constants.CONTROL_FLAGS_LEN:
raise ValueError("Not enough bytes to convert.")
command, payload_len = BroadcastMessage.unpack(first_msg_bytes)
result_bytes = bytearray(len(first_msg_bytes) - constants.BROADCAST_TYPE_LEN)
result_bytes[:self._BASE_LENGTH] = first_msg_bytes[:self._BASE_LENGTH]
result_bytes[self._BASE_LENGTH:] = first_msg_bytes[self._BREAKPOINT:]
struct.pack_into("<12sL", result_bytes, constants.STARTING_SEQUENCE_BYTES_LEN, command,
payload_len - constants.BROADCAST_TYPE_LEN)
return memoryview(result_bytes)
def convert_first_bytes_from_older_version(
self, first_msg_bytes: memoryview
) -> memoryview:
if len(first_msg_bytes) < AbstractBloxrouteMessage.HEADER_LENGTH + AbstractBroadcastMessage.PAYLOAD_LENGTH - \
constants.CONTROL_FLAGS_LEN:
raise ValueError("Not enough bytes to convert.")
command, payload_len = BroadcastMessageV8.unpack(first_msg_bytes)
result_bytes = bytearray(len(first_msg_bytes) + constants.BROADCAST_TYPE_LEN)
result_bytes[:self._BASE_LENGTH] = first_msg_bytes[:self._BASE_LENGTH]
result_bytes[self._BREAKPOINT:] = first_msg_bytes[self._BASE_LENGTH:]
struct.pack_into(
"<4s",
result_bytes,
self._BASE_LENGTH,
# pylint: disable=no-member
BroadcastMessageType.BLOCK.value.encode(constants.DEFAULT_TEXT_ENCODING)
)
struct.pack_into("<12sL", result_bytes, constants.STARTING_SEQUENCE_BYTES_LEN, command,
payload_len + constants.BROADCAST_TYPE_LEN)
return memoryview(result_bytes)
def convert_last_bytes_to_older_version(
self, last_msg_bytes: memoryview
) -> memoryview:
return last_msg_bytes
def convert_last_bytes_from_older_version(
self, last_msg_bytes: memoryview
) -> memoryview:
return last_msg_bytes
def get_message_size_change_to_older_version(self) -> int:
return -constants.BROADCAST_TYPE_LEN
def get_message_size_change_from_older_version(self) -> int:
return constants.BROADCAST_TYPE_LEN
broadcast_message_converter_v8 = _BroadcastMessageConverterV8() | src/bxcommon/messages/bloxroute/v8/broadcast_message_converter_v8.py | import struct
from bxcommon import constants
from bxcommon.messages.abstract_internal_message import AbstractInternalMessage
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
from bxcommon.messages.bloxroute.abstract_broadcast_message import AbstractBroadcastMessage
from bxcommon.messages.bloxroute.bloxroute_message_type import BloxrouteMessageType
from bxcommon.messages.bloxroute.broadcast_message import BroadcastMessage
from bxcommon.messages.bloxroute.v8.broadcast_message_v8 import BroadcastMessageV8
from bxcommon.messages.versioning.abstract_message_converter import AbstractMessageConverter
from bxcommon.models.broadcast_message_type import BroadcastMessageType
class _BroadcastMessageConverterV8(AbstractMessageConverter):
_MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING = {
BloxrouteMessageType.BROADCAST: BroadcastMessageV8
}
_MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING = {
BloxrouteMessageType.BROADCAST: BroadcastMessage
}
_BASE_LENGTH = (
AbstractBroadcastMessage.HEADER_LENGTH
+ AbstractBroadcastMessage.PAYLOAD_LENGTH
- constants.CONTROL_FLAGS_LEN
)
_BREAKPOINT = (
_BASE_LENGTH + constants.BROADCAST_TYPE_LEN
)
def convert_to_older_version(
self, msg: AbstractInternalMessage
) -> AbstractInternalMessage:
msg_type = msg.MESSAGE_TYPE
if msg_type not in self._MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING:
raise ValueError(
f"Tried to convert unexpected new message type to v8: {msg_type}"
)
old_version_msg_class = self._MSG_TYPE_TO_OLD_MSG_CLASS_MAPPING[
msg_type
]
old_version_payload_len = msg.payload_len() - constants.BROADCAST_TYPE_LEN
old_version_msg_bytes = bytearray(self._BASE_LENGTH + len(msg.rawbytes()[self._BREAKPOINT:]))
old_version_msg_bytes[:self._BASE_LENGTH] = msg.rawbytes()[:self._BASE_LENGTH]
old_version_msg_bytes[self._BASE_LENGTH:] = msg.rawbytes()[self._BREAKPOINT:]
return AbstractBloxrouteMessage.initialize_class(
old_version_msg_class,
old_version_msg_bytes,
(msg_type, old_version_payload_len),
)
def convert_from_older_version(
self, msg: AbstractInternalMessage
) -> AbstractInternalMessage:
msg_type = msg.MESSAGE_TYPE
if msg_type not in self._MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING:
raise ValueError(
f"Tried to convert unexpected old message type to v9: {msg_type}"
)
new_msg_class = self._MSG_TYPE_TO_NEW_MSG_CLASS_MAPPING[msg_type]
new_payload_len = msg.payload_len() + constants.BROADCAST_TYPE_LEN
new_msg_bytes = bytearray(AbstractBloxrouteMessage.HEADER_LENGTH + new_payload_len)
new_msg_bytes[:self._BASE_LENGTH] = msg.rawbytes()[:self._BASE_LENGTH]
struct.pack_into(
"<4s",
new_msg_bytes,
self._BASE_LENGTH,
# pylint: disable=no-member
BroadcastMessageType.BLOCK.value.encode(constants.DEFAULT_TEXT_ENCODING)
)
new_msg_bytes[self._BREAKPOINT:] = msg.rawbytes()[self._BASE_LENGTH:]
return AbstractBloxrouteMessage.initialize_class(
new_msg_class,
new_msg_bytes,
(msg_type, new_payload_len)
)
def convert_first_bytes_to_older_version(
self, first_msg_bytes: memoryview
) -> memoryview:
if len(first_msg_bytes) < AbstractBloxrouteMessage.HEADER_LENGTH + AbstractBroadcastMessage.PAYLOAD_LENGTH - \
constants.CONTROL_FLAGS_LEN:
raise ValueError("Not enough bytes to convert.")
command, payload_len = BroadcastMessage.unpack(first_msg_bytes)
result_bytes = bytearray(len(first_msg_bytes) - constants.BROADCAST_TYPE_LEN)
result_bytes[:self._BASE_LENGTH] = first_msg_bytes[:self._BASE_LENGTH]
result_bytes[self._BASE_LENGTH:] = first_msg_bytes[self._BREAKPOINT:]
struct.pack_into("<12sL", result_bytes, constants.STARTING_SEQUENCE_BYTES_LEN, command,
payload_len - constants.BROADCAST_TYPE_LEN)
return memoryview(result_bytes)
def convert_first_bytes_from_older_version(
self, first_msg_bytes: memoryview
) -> memoryview:
if len(first_msg_bytes) < AbstractBloxrouteMessage.HEADER_LENGTH + AbstractBroadcastMessage.PAYLOAD_LENGTH - \
constants.CONTROL_FLAGS_LEN:
raise ValueError("Not enough bytes to convert.")
command, payload_len = BroadcastMessageV8.unpack(first_msg_bytes)
result_bytes = bytearray(len(first_msg_bytes) + constants.BROADCAST_TYPE_LEN)
result_bytes[:self._BASE_LENGTH] = first_msg_bytes[:self._BASE_LENGTH]
result_bytes[self._BREAKPOINT:] = first_msg_bytes[self._BASE_LENGTH:]
struct.pack_into(
"<4s",
result_bytes,
self._BASE_LENGTH,
# pylint: disable=no-member
BroadcastMessageType.BLOCK.value.encode(constants.DEFAULT_TEXT_ENCODING)
)
struct.pack_into("<12sL", result_bytes, constants.STARTING_SEQUENCE_BYTES_LEN, command,
payload_len + constants.BROADCAST_TYPE_LEN)
return memoryview(result_bytes)
def convert_last_bytes_to_older_version(
self, last_msg_bytes: memoryview
) -> memoryview:
return last_msg_bytes
def convert_last_bytes_from_older_version(
self, last_msg_bytes: memoryview
) -> memoryview:
return last_msg_bytes
def get_message_size_change_to_older_version(self) -> int:
return -constants.BROADCAST_TYPE_LEN
def get_message_size_change_from_older_version(self) -> int:
return constants.BROADCAST_TYPE_LEN
broadcast_message_converter_v8 = _BroadcastMessageConverterV8() | 0.5144 | 0.079531 |
from __future__ import absolute_import
import imp
import os
import mock
from collections import defaultdict
import unittest2
from oslo_config import cfg
from st2common import config
from st2common.util import loader
CURRENT_DIR = os.path.dirname(__file__)
ST2CONTENT_DIR = os.path.join(CURRENT_DIR, '../fixtures')
MOCK_RUNNER_NAME = 'mock_runner'
MOCK_RUNNER_PATH = '{0}/{1}/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_RUNNER_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_RUNNER_PATH)
MOCK_QUERIER_PATH = '{0}/{1}/query/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_QUERIER_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_QUERIER_PATH)
MOCK_CALLBACK_PATH = '{0}/{1}/callback/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_CALLBACK_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_CALLBACK_PATH)
class PluginLoaderTestCase(unittest2.TestCase):
@classmethod
def setUpClass(cls):
super(PluginLoaderTestCase, cls).setUpClass()
# Check to see if configs are already registered.
# The register_opts is needed when running tests individually.
if 'system' not in cfg.CONF:
config.register_opts()
def setUp(self):
super(PluginLoaderTestCase, self).setUp()
loader.RUNNER_MODULES_CACHE = defaultdict(dict)
loader.QUERIER_MODULES_CACHE = {}
loader.CALLBACK_MODULES_CACHE = {}
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_RUNNER_MODULE)
)
def test_register_runner(self):
runner = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertIsNotNone(runner)
self.assertEqual(MOCK_RUNNER_NAME, runner.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_RUNNER_MODULE)
)
def test_register_runner_again(self):
runner1 = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(runner1)
self.assertEqual(MOCK_RUNNER_NAME, runner1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner1, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
runner2 = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(runner1, runner2)
self.assertIsNotNone(runner2)
self.assertEqual(MOCK_RUNNER_NAME, runner2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner2, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_QUERIER_MODULE)
)
def test_register_query_module(self):
querier = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertIsNotNone(querier)
self.assertEqual(MOCK_RUNNER_NAME, querier.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_QUERIER_MODULE)
)
def test_register_query_module_again(self):
querier1 = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(querier1)
self.assertEqual(MOCK_RUNNER_NAME, querier1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier1, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
querier2 = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(querier1, querier2)
self.assertIsNotNone(querier2)
self.assertEqual(MOCK_RUNNER_NAME, querier2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier2, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_CALLBACK_MODULE)
)
def test_register_callback_module(self):
callback_module = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertIsNotNone(callback_module)
self.assertEqual(MOCK_RUNNER_NAME, callback_module.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_CALLBACK_MODULE)
)
def test_register_callback_module_again(self):
callback_module1 = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(callback_module1)
self.assertEqual(MOCK_RUNNER_NAME, callback_module1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module1, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME])
callback_module2 = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(callback_module1, callback_module2)
self.assertIsNotNone(callback_module2)
self.assertEqual(MOCK_RUNNER_NAME, callback_module2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module2, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME]) | st2common/tests/unit/test_util_loader.py |
from __future__ import absolute_import
import imp
import os
import mock
from collections import defaultdict
import unittest2
from oslo_config import cfg
from st2common import config
from st2common.util import loader
CURRENT_DIR = os.path.dirname(__file__)
ST2CONTENT_DIR = os.path.join(CURRENT_DIR, '../fixtures')
MOCK_RUNNER_NAME = 'mock_runner'
MOCK_RUNNER_PATH = '{0}/{1}/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_RUNNER_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_RUNNER_PATH)
MOCK_QUERIER_PATH = '{0}/{1}/query/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_QUERIER_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_QUERIER_PATH)
MOCK_CALLBACK_PATH = '{0}/{1}/callback/{1}.py'.format(ST2CONTENT_DIR, MOCK_RUNNER_NAME)
MOCK_CALLBACK_MODULE = imp.load_source(MOCK_RUNNER_NAME, MOCK_CALLBACK_PATH)
class PluginLoaderTestCase(unittest2.TestCase):
@classmethod
def setUpClass(cls):
super(PluginLoaderTestCase, cls).setUpClass()
# Check to see if configs are already registered.
# The register_opts is needed when running tests individually.
if 'system' not in cfg.CONF:
config.register_opts()
def setUp(self):
super(PluginLoaderTestCase, self).setUp()
loader.RUNNER_MODULES_CACHE = defaultdict(dict)
loader.QUERIER_MODULES_CACHE = {}
loader.CALLBACK_MODULES_CACHE = {}
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_RUNNER_MODULE)
)
def test_register_runner(self):
runner = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertIsNotNone(runner)
self.assertEqual(MOCK_RUNNER_NAME, runner.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_RUNNER_MODULE)
)
def test_register_runner_again(self):
runner1 = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(runner1)
self.assertEqual(MOCK_RUNNER_NAME, runner1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner1, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
runner2 = loader.register_runner(MOCK_RUNNER_NAME, MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(runner1, runner2)
self.assertIsNotNone(runner2)
self.assertEqual(MOCK_RUNNER_NAME, runner2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.RUNNER_MODULES_CACHE)
self.assertEqual(runner2, loader.RUNNER_MODULES_CACHE[MOCK_RUNNER_NAME][MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_QUERIER_MODULE)
)
def test_register_query_module(self):
querier = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertIsNotNone(querier)
self.assertEqual(MOCK_RUNNER_NAME, querier.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_QUERIER_MODULE)
)
def test_register_query_module_again(self):
querier1 = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(querier1)
self.assertEqual(MOCK_RUNNER_NAME, querier1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier1, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
querier2 = loader.register_query_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(querier1, querier2)
self.assertIsNotNone(querier2)
self.assertEqual(MOCK_RUNNER_NAME, querier2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.QUERIER_MODULES_CACHE)
self.assertEqual(querier2, loader.QUERIER_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_CALLBACK_MODULE)
)
def test_register_callback_module(self):
callback_module = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertIsNotNone(callback_module)
self.assertEqual(MOCK_RUNNER_NAME, callback_module.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME])
@mock.patch.object(
imp,
'load_source',
mock.MagicMock(return_value=MOCK_CALLBACK_MODULE)
)
def test_register_callback_module_again(self):
callback_module1 = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertIsNotNone(callback_module1)
self.assertEqual(MOCK_RUNNER_NAME, callback_module1.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module1, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME])
callback_module2 = loader.register_callback_module(MOCK_RUNNER_NAME)
self.assertEqual(1, imp.load_source.call_count)
self.assertEqual(callback_module1, callback_module2)
self.assertIsNotNone(callback_module2)
self.assertEqual(MOCK_RUNNER_NAME, callback_module2.__name__)
self.assertIn(MOCK_RUNNER_NAME, loader.CALLBACK_MODULES_CACHE)
self.assertEqual(callback_module2, loader.CALLBACK_MODULES_CACHE[MOCK_RUNNER_NAME]) | 0.52074 | 0.132486 |
import json
import os
import random
import bottle
from bottle import HTTPResponse
@bottle.route("/")
def index():
return "Your Battlesnake is alive!"
@bottle.post("/ping")
def ping():
"""
Used by the Battlesnake Engine to make sure your snake is still working.
"""
return HTTPResponse(status=200)
@bottle.post("/start")
def start():
"""
Called every time a new Battlesnake game starts and your snake is in it.
Your response will control how your snake is displayed on the board.
"""
data = bottle.request.json
print("START:", json.dumps(data))
response = {"color": "#00FF00", "headType": "regular", "tailType": "regular"}
return HTTPResponse(
status=200,
headers={"Content-Type": "application/json"},
body=json.dumps(response),
)
@bottle.post("/move")
def move():
"""
Called when the Battlesnake Engine needs to know your next move.
The data parameter will contain information about the board.
Your response must include your move of up, down, left, or right.
"""
data = bottle.request.json
print("MOVE:", json.dumps(data))
# Choose a random direction to move in
directions = ["up", "down", "left", "right"]
move = random.choice(directions)
# Shouts are messages sent to all the other snakes in the game.
# Shouts are not displayed on the game board.
shout = "I am a python snake!"
response = {"move": move, "shout": shout}
return HTTPResponse(
status=200,
headers={"Content-Type": "application/json"},
body=json.dumps(response),
)
@bottle.post("/end")
def end():
"""
Called every time a game with your snake in it ends.
"""
data = bottle.request.json
print("END:", json.dumps(data))
return HTTPResponse(status=200)
def main():
bottle.run(
application,
host=os.getenv("IP", "0.0.0.0"),
port=os.getenv("PORT", "8080"),
debug=os.getenv("DEBUG", True),
)
# Expose WSGI app (so gunicorn can find it)
application = bottle.default_app()
if __name__ == "__main__":
main() | app/server.py | import json
import os
import random
import bottle
from bottle import HTTPResponse
@bottle.route("/")
def index():
return "Your Battlesnake is alive!"
@bottle.post("/ping")
def ping():
"""
Used by the Battlesnake Engine to make sure your snake is still working.
"""
return HTTPResponse(status=200)
@bottle.post("/start")
def start():
"""
Called every time a new Battlesnake game starts and your snake is in it.
Your response will control how your snake is displayed on the board.
"""
data = bottle.request.json
print("START:", json.dumps(data))
response = {"color": "#00FF00", "headType": "regular", "tailType": "regular"}
return HTTPResponse(
status=200,
headers={"Content-Type": "application/json"},
body=json.dumps(response),
)
@bottle.post("/move")
def move():
"""
Called when the Battlesnake Engine needs to know your next move.
The data parameter will contain information about the board.
Your response must include your move of up, down, left, or right.
"""
data = bottle.request.json
print("MOVE:", json.dumps(data))
# Choose a random direction to move in
directions = ["up", "down", "left", "right"]
move = random.choice(directions)
# Shouts are messages sent to all the other snakes in the game.
# Shouts are not displayed on the game board.
shout = "I am a python snake!"
response = {"move": move, "shout": shout}
return HTTPResponse(
status=200,
headers={"Content-Type": "application/json"},
body=json.dumps(response),
)
@bottle.post("/end")
def end():
"""
Called every time a game with your snake in it ends.
"""
data = bottle.request.json
print("END:", json.dumps(data))
return HTTPResponse(status=200)
def main():
bottle.run(
application,
host=os.getenv("IP", "0.0.0.0"),
port=os.getenv("PORT", "8080"),
debug=os.getenv("DEBUG", True),
)
# Expose WSGI app (so gunicorn can find it)
application = bottle.default_app()
if __name__ == "__main__":
main() | 0.558809 | 0.161883 |
from unittest import mock
import pytest
from cumulusci.tasks.push.push_api import BasePushApiObject
from cumulusci.tasks.push.push_api import SalesforcePushApi
from cumulusci.tasks.push.push_api import memoize, batch_list, MetadataPackage
def test_memoize():
def test_func(number):
return number
memoized_func = memoize(test_func)
memoized_func(10)
memoized_func(20)
expected_cache = {"(10,){}": 10, "(20,){}": 20}
assert expected_cache == memoized_func.cache
memoized_func(10)
memoized_func(20)
# No new items introduced, cache should be same
assert expected_cache == memoized_func.cache
def test_batch_list():
data = ["zero", "one", "two", "three"]
actual_batch_list = batch_list(data, 1)
expected_batch_list = [["zero"], ["one"], ["two"], ["three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 2)
expected_batch_list = [["zero", "one"], ["two", "three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 3)
expected_batch_list = [["zero", "one", "two"], ["three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 4)
expected_batch_list = [["zero", "one", "two", "three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 5)
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list([], 2)
expected_batch_list = []
assert expected_batch_list == actual_batch_list
class TestBasePushApiObject:
@pytest.fixture
def base_obj(self):
return BasePushApiObject()
def test_format_where(self, base_obj):
field_name = "id_field"
sf_id = "006000000XXX000"
where_clause = "id=001000000XXX000"
base_obj.sf_id = sf_id
returned = base_obj.format_where(field_name, where_clause)
assert "{} = '{}' AND ({})".format(field_name, sf_id, where_clause)
returned = base_obj.format_where(field_name, None)
assert "{} = '{}'".format(field_name, sf_id) == returned
class TestMetadataPacakage:
"""Provides coverage for MetadataPackage"""
NAME = "Chewbacca"
SF_ID = "sf_id"
PUSH_API = "push_api"
NAMESPACE = "namespace"
@pytest.fixture
def package(self):
return MetadataPackage(self.PUSH_API, self.NAME, self.SF_ID, self.NAMESPACE)
def test_init(self):
package = MetadataPackage(self.PUSH_API, self.NAME)
assert package.push_api == self.PUSH_API
assert package.sf_id is None
assert package.name == self.NAME
assert package.namespace is None
package = MetadataPackage(self.PUSH_API, self.NAME, self.SF_ID, self.NAMESPACE)
assert package.push_api == self.PUSH_API
assert package.sf_id == self.SF_ID
assert package.name == self.NAME
assert package.namespace == self.NAMESPACE
class TestSalesforcePushApi:
"""Provides coverage for SalesforcePushApi"""
@pytest.fixture
def sf_push_api(self):
return SalesforcePushApi(mock.Mock(), mock.Mock()) # sf # logger
def test_return_query_records(self, sf_push_api):
query = "SELECT Id FROM Account"
records = ["record 1", "record 2", "record 3"]
results = {"totalSize": 10, "records": records}
sf_push_api.sf.query_all.return_value = results
returned = sf_push_api.return_query_records(query)
assert len(records) == len(returned)
results["totalSize"] = 0
sf_push_api.sf.query_all.return_value = results
returned = sf_push_api.return_query_records(query)
assert [] == returned
def test_format_where(self, sf_push_api):
returned = sf_push_api.format_where_clause(None)
assert "" == returned
default_where = "Id='001000000XXX000'"
sf_push_api.default_where = {"Account": default_where}
returned = sf_push_api.format_where_clause(None, "Object__c")
assert "" == returned
returned = sf_push_api.format_where_clause(None, "Account")
assert " WHERE ({})".format(default_where) == returned
where = "IsDeleted=False"
returned = sf_push_api.format_where_clause(where)
assert " WHERE {}".format(where) == returned
# No default where for Object__C
returned = sf_push_api.format_where_clause(where, "Object__c")
assert " WHERE {}".format(where) == returned
returned = sf_push_api.format_where_clause(where, "Account")
assert " WHERE ({}) AND ({})".format(default_where, where) == returned
def test_add_query_limit(self, sf_push_api):
query = "SELECT Id FROM Account"
limit = 100
returned = sf_push_api.add_query_limit(query, limit)
assert "{} LIMIT {}".format(query, limit) == returned | cumulusci/tasks/push/tests/test_push_api.py | from unittest import mock
import pytest
from cumulusci.tasks.push.push_api import BasePushApiObject
from cumulusci.tasks.push.push_api import SalesforcePushApi
from cumulusci.tasks.push.push_api import memoize, batch_list, MetadataPackage
def test_memoize():
def test_func(number):
return number
memoized_func = memoize(test_func)
memoized_func(10)
memoized_func(20)
expected_cache = {"(10,){}": 10, "(20,){}": 20}
assert expected_cache == memoized_func.cache
memoized_func(10)
memoized_func(20)
# No new items introduced, cache should be same
assert expected_cache == memoized_func.cache
def test_batch_list():
data = ["zero", "one", "two", "three"]
actual_batch_list = batch_list(data, 1)
expected_batch_list = [["zero"], ["one"], ["two"], ["three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 2)
expected_batch_list = [["zero", "one"], ["two", "three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 3)
expected_batch_list = [["zero", "one", "two"], ["three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 4)
expected_batch_list = [["zero", "one", "two", "three"]]
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list(data, 5)
assert expected_batch_list == actual_batch_list
actual_batch_list = batch_list([], 2)
expected_batch_list = []
assert expected_batch_list == actual_batch_list
class TestBasePushApiObject:
@pytest.fixture
def base_obj(self):
return BasePushApiObject()
def test_format_where(self, base_obj):
field_name = "id_field"
sf_id = "006000000XXX000"
where_clause = "id=001000000XXX000"
base_obj.sf_id = sf_id
returned = base_obj.format_where(field_name, where_clause)
assert "{} = '{}' AND ({})".format(field_name, sf_id, where_clause)
returned = base_obj.format_where(field_name, None)
assert "{} = '{}'".format(field_name, sf_id) == returned
class TestMetadataPacakage:
"""Provides coverage for MetadataPackage"""
NAME = "Chewbacca"
SF_ID = "sf_id"
PUSH_API = "push_api"
NAMESPACE = "namespace"
@pytest.fixture
def package(self):
return MetadataPackage(self.PUSH_API, self.NAME, self.SF_ID, self.NAMESPACE)
def test_init(self):
package = MetadataPackage(self.PUSH_API, self.NAME)
assert package.push_api == self.PUSH_API
assert package.sf_id is None
assert package.name == self.NAME
assert package.namespace is None
package = MetadataPackage(self.PUSH_API, self.NAME, self.SF_ID, self.NAMESPACE)
assert package.push_api == self.PUSH_API
assert package.sf_id == self.SF_ID
assert package.name == self.NAME
assert package.namespace == self.NAMESPACE
class TestSalesforcePushApi:
"""Provides coverage for SalesforcePushApi"""
@pytest.fixture
def sf_push_api(self):
return SalesforcePushApi(mock.Mock(), mock.Mock()) # sf # logger
def test_return_query_records(self, sf_push_api):
query = "SELECT Id FROM Account"
records = ["record 1", "record 2", "record 3"]
results = {"totalSize": 10, "records": records}
sf_push_api.sf.query_all.return_value = results
returned = sf_push_api.return_query_records(query)
assert len(records) == len(returned)
results["totalSize"] = 0
sf_push_api.sf.query_all.return_value = results
returned = sf_push_api.return_query_records(query)
assert [] == returned
def test_format_where(self, sf_push_api):
returned = sf_push_api.format_where_clause(None)
assert "" == returned
default_where = "Id='001000000XXX000'"
sf_push_api.default_where = {"Account": default_where}
returned = sf_push_api.format_where_clause(None, "Object__c")
assert "" == returned
returned = sf_push_api.format_where_clause(None, "Account")
assert " WHERE ({})".format(default_where) == returned
where = "IsDeleted=False"
returned = sf_push_api.format_where_clause(where)
assert " WHERE {}".format(where) == returned
# No default where for Object__C
returned = sf_push_api.format_where_clause(where, "Object__c")
assert " WHERE {}".format(where) == returned
returned = sf_push_api.format_where_clause(where, "Account")
assert " WHERE ({}) AND ({})".format(default_where, where) == returned
def test_add_query_limit(self, sf_push_api):
query = "SELECT Id FROM Account"
limit = 100
returned = sf_push_api.add_query_limit(query, limit)
assert "{} LIMIT {}".format(query, limit) == returned | 0.723114 | 0.580293 |
import numpy
from numpy.testing import assert_array_almost_equal
from keras import backend as K
from keras.layers import Input, Masking
from keras.models import Model
from scipy.stats import logistic
from deep_qa.layers.tuple_matchers import SlotSimilarityTupleMatcher
from deep_qa.tensors.similarity_functions.cosine_similarity import CosineSimilarity
from ...common.test_case import DeepQaTestCase
class TestSlotSimilarityTupleMatcher(DeepQaTestCase):
def setUp(self):
super(TestSlotSimilarityTupleMatcher, self).setUp()
num_slots = 3
embed_dimension = 4
self.tuple1_input = Input(shape=(num_slots, embed_dimension), dtype='float32', name="input_tuple1")
self.tuple2_input = Input(shape=(num_slots, embed_dimension), dtype='float32', name="input_tuple2")
self.num_hidden_layers = 1
self.hidden_layer_width = 2
self.hidden_layer_activation = 'linear'
# tuple1 shape: (batch size, num_slots, embed_dimension)
self.tuple1 = numpy.random.rand(1, num_slots, embed_dimension)
# tuple2 shape: (batch size, num_slots, embed_dimension)
self.tuple2 = numpy.random.rand(1, num_slots, embed_dimension)
def test_general_case(self):
match_layer = SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
output = match_layer([self.tuple1_input, self.tuple2_input])
model = Model([self.tuple1_input, self.tuple2_input], output)
# Get the initial weights for use in testing
dense_hidden_weights = K.eval(model.trainable_weights[0])
score_weights = K.eval(model.trainable_weights[1])
# Testing general unmasked case.
similarity_function = CosineSimilarity(name="cosine_similarity")
cosine_similarities = similarity_function.compute_similarity(K.variable(self.tuple1),
K.variable(self.tuple2))
# Desired_overlap gets fed into the inner NN.
dense1_activation = numpy.dot(K.eval(cosine_similarities), dense_hidden_weights)
final_score = numpy.dot(dense1_activation, score_weights)
# Apply the final sigmoid activation function.
desired_result = logistic.cdf(final_score)
result = model.predict([self.tuple1, self.tuple2])
assert_array_almost_equal(result, desired_result)
def test_returns_masks_correctly(self):
# Test when one tuple is all padding.
# Here, since tuple3 is all padding, we want to return a mask value of 0 for this pair
tuple1 = K.variable(self.tuple1)
mask1 = K.variable(numpy.asarray([[1, 1, 1]]))
tuple2 = K.variable(self.tuple2)
mask2 = K.variable(numpy.asarray([[0, 0, 0]]))
calculated_mask_exclude = K.eval(
SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
.compute_mask([tuple1, tuple2], [mask1, mask2]))
assert_array_almost_equal(calculated_mask_exclude, numpy.array([[0]], dtype='int32'))
assert calculated_mask_exclude.shape == (1, 1,)
# Test when tuple2 is valid.
# Here, since tuple2 is valid, we want to return a mask value of 1 for this pair
mask2 = K.variable(numpy.asarray([[0, 1, 0]]))
calculated_mask_include = K.eval(
SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
.compute_mask([tuple1, tuple2], [mask1, mask2]))
assert_array_almost_equal(calculated_mask_include, numpy.array([[1]], dtype='int32'))
assert calculated_mask_include.shape == (1, 1,)
def test_handles_input_masks_correctly(self):
mask_layer = Masking(mask_value=0.0)
masked_tuple1 = mask_layer(self.tuple1_input)
masked_tuple2 = mask_layer(self.tuple2_input)
# Add a set of paddings to slot 1 in tuple 2
self.tuple2[:, 1, :] = numpy.zeros(4)
match_layer = SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
output = match_layer([masked_tuple1, masked_tuple2])
mask_model = Model([self.tuple1_input, self.tuple2_input], output)
similarity_function = CosineSimilarity(name="cosine_similarity")
cosine_similarities = similarity_function.compute_similarity(K.variable(self.tuple1),
K.variable(self.tuple2))
mask2 = K.variable(numpy.asarray([[1, 0, 1]], dtype='float32'))
masked_cosine_similarities = cosine_similarities * mask2
# Get the initial weights for use in testing
dense_hidden_weights = K.eval(mask_model.trainable_weights[0])
score_weights = K.eval(mask_model.trainable_weights[1])
# Desired_overlap gets fed into the inner NN.
dense1_activation = numpy.dot(K.eval(masked_cosine_similarities), dense_hidden_weights)
final_score = numpy.dot(dense1_activation, score_weights)
# Apply the final sigmoid activation function.
desired_result = logistic.cdf(final_score)
result = mask_model.predict([self.tuple1, self.tuple2])
assert_array_almost_equal(result, desired_result) | tests/layers/tuple_matchers/slot_similarity_tuple_matcher_test.py | import numpy
from numpy.testing import assert_array_almost_equal
from keras import backend as K
from keras.layers import Input, Masking
from keras.models import Model
from scipy.stats import logistic
from deep_qa.layers.tuple_matchers import SlotSimilarityTupleMatcher
from deep_qa.tensors.similarity_functions.cosine_similarity import CosineSimilarity
from ...common.test_case import DeepQaTestCase
class TestSlotSimilarityTupleMatcher(DeepQaTestCase):
def setUp(self):
super(TestSlotSimilarityTupleMatcher, self).setUp()
num_slots = 3
embed_dimension = 4
self.tuple1_input = Input(shape=(num_slots, embed_dimension), dtype='float32', name="input_tuple1")
self.tuple2_input = Input(shape=(num_slots, embed_dimension), dtype='float32', name="input_tuple2")
self.num_hidden_layers = 1
self.hidden_layer_width = 2
self.hidden_layer_activation = 'linear'
# tuple1 shape: (batch size, num_slots, embed_dimension)
self.tuple1 = numpy.random.rand(1, num_slots, embed_dimension)
# tuple2 shape: (batch size, num_slots, embed_dimension)
self.tuple2 = numpy.random.rand(1, num_slots, embed_dimension)
def test_general_case(self):
match_layer = SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
output = match_layer([self.tuple1_input, self.tuple2_input])
model = Model([self.tuple1_input, self.tuple2_input], output)
# Get the initial weights for use in testing
dense_hidden_weights = K.eval(model.trainable_weights[0])
score_weights = K.eval(model.trainable_weights[1])
# Testing general unmasked case.
similarity_function = CosineSimilarity(name="cosine_similarity")
cosine_similarities = similarity_function.compute_similarity(K.variable(self.tuple1),
K.variable(self.tuple2))
# Desired_overlap gets fed into the inner NN.
dense1_activation = numpy.dot(K.eval(cosine_similarities), dense_hidden_weights)
final_score = numpy.dot(dense1_activation, score_weights)
# Apply the final sigmoid activation function.
desired_result = logistic.cdf(final_score)
result = model.predict([self.tuple1, self.tuple2])
assert_array_almost_equal(result, desired_result)
def test_returns_masks_correctly(self):
# Test when one tuple is all padding.
# Here, since tuple3 is all padding, we want to return a mask value of 0 for this pair
tuple1 = K.variable(self.tuple1)
mask1 = K.variable(numpy.asarray([[1, 1, 1]]))
tuple2 = K.variable(self.tuple2)
mask2 = K.variable(numpy.asarray([[0, 0, 0]]))
calculated_mask_exclude = K.eval(
SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
.compute_mask([tuple1, tuple2], [mask1, mask2]))
assert_array_almost_equal(calculated_mask_exclude, numpy.array([[0]], dtype='int32'))
assert calculated_mask_exclude.shape == (1, 1,)
# Test when tuple2 is valid.
# Here, since tuple2 is valid, we want to return a mask value of 1 for this pair
mask2 = K.variable(numpy.asarray([[0, 1, 0]]))
calculated_mask_include = K.eval(
SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
.compute_mask([tuple1, tuple2], [mask1, mask2]))
assert_array_almost_equal(calculated_mask_include, numpy.array([[1]], dtype='int32'))
assert calculated_mask_include.shape == (1, 1,)
def test_handles_input_masks_correctly(self):
mask_layer = Masking(mask_value=0.0)
masked_tuple1 = mask_layer(self.tuple1_input)
masked_tuple2 = mask_layer(self.tuple2_input)
# Add a set of paddings to slot 1 in tuple 2
self.tuple2[:, 1, :] = numpy.zeros(4)
match_layer = SlotSimilarityTupleMatcher({"type": "cosine_similarity"},
self.num_hidden_layers,
self.hidden_layer_width,
hidden_layer_activation=self.hidden_layer_activation)
output = match_layer([masked_tuple1, masked_tuple2])
mask_model = Model([self.tuple1_input, self.tuple2_input], output)
similarity_function = CosineSimilarity(name="cosine_similarity")
cosine_similarities = similarity_function.compute_similarity(K.variable(self.tuple1),
K.variable(self.tuple2))
mask2 = K.variable(numpy.asarray([[1, 0, 1]], dtype='float32'))
masked_cosine_similarities = cosine_similarities * mask2
# Get the initial weights for use in testing
dense_hidden_weights = K.eval(mask_model.trainable_weights[0])
score_weights = K.eval(mask_model.trainable_weights[1])
# Desired_overlap gets fed into the inner NN.
dense1_activation = numpy.dot(K.eval(masked_cosine_similarities), dense_hidden_weights)
final_score = numpy.dot(dense1_activation, score_weights)
# Apply the final sigmoid activation function.
desired_result = logistic.cdf(final_score)
result = mask_model.predict([self.tuple1, self.tuple2])
assert_array_almost_equal(result, desired_result) | 0.889721 | 0.565899 |
import struct
import threading
from pixiv_fetcher.utils.log import get_logger
from pixiv_fetcher.utils.path import make_direct_open
class BaseStrategy(object):
def __init__(self, maxsize=None, maxcount=None):
self.maxsize = maxsize
self.maxcount = maxcount
def reset(self, key):
raise NotImplemented()
def handle_set(self, key, value):
raise NotImplemented()
def handle_hit(self, key, value):
raise NotImplemented()
def handle_missing(self, key):
pass
def remove_keys(self, storage):
raise NotImplemented()
def is_excess(self, storage):
return storage.size > self.maxsize or storage.count > self.maxcount
class DoNothingStrategy(BaseStrategy):
def handle_set(self, *args, **kw):
pass
record_get = handle_set
reset = handle_set
remove_keys = handle_set
is_excess = handle_set
class FifoMemoryStrategy(BaseStrategy):
def __init__(self, maxsize=None, maxcount=None):
super(FifoMemoryStrategy, self).__init__(maxsize, maxcount)
self._keys = []
def reset(self, key):
while key in self._keys:
try:
self._keys.remove(key)
except ValueError:
pass
def handle_set(self, key, value):
if key not in self._keys:
self._keys.append(key)
def handle_hit(self, key, value):
# do nothing
pass
def remove_keys(self, storage):
while self.is_excess(storage) and self._keys:
storage.delete(self._keys.pop(0))
class LruMemoryStrategy(BaseStrategy):
"""
Least recently used strategy
"""
def __init__(self, maxsize=None, maxcount=None):
super(LruMemoryStrategy, self).__init__(maxsize, maxcount)
self._keys = []
self._lock = threading.RLock()
self._log = get_logger(self)
def reset(self, key):
raise NotImplemented()
def handle_set(self, key, value):
with self._lock:
while key in self._keys:
self._keys.remove(key)
self._keys.insert(0, key)
def handle_hit(self, key, value):
self.handle_set(key, value)
def remove_keys(self, storage):
while self.is_excess(storage) and self._keys:
with self._lock:
to_rm = self._keys.pop()
storage.delete(to_rm)
self._log.debug(u'清理缓存: %r', to_rm)
class DiskRecord(object):
_int_fmt = '<L'
_int_size = 4
def __init__(self, path, key_func=None, recover_func=None, key_len=16):
self._path = path
self._fp = make_direct_open(self._path, 'r+b', buffering=0)
self._key_len = key_len
self._key_func = key_func or (lambda _: _)
self._key_recover_func = recover_func or (lambda _: _)
self._lock = threading.RLock()
@property
def _row_length(self):
return self._key_len + self._int_size
def _pack_key(self, key):
k = self._key_func(key)
less = self._key_len - len(k)
k += chr(less) * less
return k
def _pack(self, key, c):
k = self._pack_key(key)
value = struct.pack(self._int_fmt, c)
return k + value
def _unpack(self, raw):
less = ord(raw[self._key_len-1])
value = struct.unpack(self._int_fmt, raw[self._key_len:])[0]
key = raw[:self._key_len]
if key <= less and key.endswith(chr(less) * less):
key = key[:-less]
return key, value
def insert(self, i, key, value):
curr_row = self._pack(key, value)
with self._lock:
num = self.length()
if i < 0:
i += num
elif i > num:
i = num
point = self._row_length * i + 5
self._fp.seek(point)
next_row = self._fp.read(self._row_length)
for i in xrange(num-i+1):
# 读到末尾空字符串位置不变
if next_row:
self._fp.seek(-self._row_length, 1)
self._fp.write(curr_row)
curr_row, next_row = next_row, self._fp.read(self._row_length)
self._write_length(num+1)
def set(self, key, value):
with self._lock:
idx, v = self.search(key)
if idx != -1:
p = self._row_length * idx + 5
self._fp.seek(p+self._key_len)
self._fp.write(struct.pack(self._int_fmt, value))
else:
idx = self.length()
end = self._row_length * idx + 5
self._fp.seek(end)
raw = self._pack(key, value)
self._fp.write(raw)
self._write_length(idx + 1)
return idx
def set_idx(self, i, key, value):
with self._lock:
p = 5 + i * self._row_length
self._fp.seek(p)
data = self._pack(key, value)
self._fp.write(data)
def swap(self, i1, i2):
with self._lock:
num = self.length()
if i1 >= num:
raise IndexError("%d (Length: %d)" % (i1, num))
if i2 >= num:
raise IndexError("%d (Length: %d)" % (i2, num))
p1 = 5 + self._row_length * i1
p2 = 5 + self._row_length * i2
self._fp.seek(p1)
data1 = self._fp.read(self._row_length)
self._fp.seek(p2)
data2 = self._fp.read(self._row_length)
self._fp.seek(p1)
self._fp.write(data2)
self._fp.seek(p2)
self._fp.write(data1)
def search(self, key):
num = self.length()
key = self._pack_key(key)
with self._lock:
self._fp.seek(5)
for i in xrange(num):
raw = self._fp.read(self._row_length)
k, value = self._unpack(raw)
if k == key:
return i, value
return -1, None
def get(self, key):
_, v = self.search(key)
return v
def get_idx(self, idx):
with self._lock:
p = 5 + self._row_length * idx
self._fp.seek(p)
raw = self._fp.read(self._row_length)
k, v = self._unpack(raw)
return self._key_recover_func(k), v
def has(self, key):
key = self._pack_key(key)
with self._lock:
num = self.length()
self._fp.seek(5)
for i in xrange(num):
k = self._fp.read(self._key_len)
if k == key:
return True
self._fp.seek(self._int_size, 1)
return False
def pop(self, key):
with self._lock:
idx, value = self.search(key)
self.pop_idx(idx)
return value
def pop_idx(self, idx=-1):
with self._lock:
num = self.length()
# FIXME: 索引越界
idx = num + idx if idx < 0 else idx
self._fp.seek(5 + self._row_length * idx)
raw_data = self._fp.read(self._row_length)
k, v = self._unpack(raw_data)
for i in xrange(num-idx):
next_row = self._fp.read(self._row_length)
self._fp.seek(-self._row_length*2, 1)
self._fp.write(next_row)
self._fp.seek(self._row_length, 1)
self._write_length(num-1)
return self._key_recover_func(k), v
def length(self):
with self._lock:
self._fp.seek(1)
bs = self._fp.read(4)
num = struct.unpack(self._int_fmt, bs)[0] if bs else 0
return num
def _write_length(self, l):
with self._lock:
self._fp.seek(1)
bs = struct.pack(self._int_fmt, l)
self._fp.write(bs)
def close(self):
if self._fp and not self._fp.closed:
self._fp.close()
def flush(self):
with self._lock:
self._fp.seek(0)
self._fp.flush()
class LfuDiskStrategy(BaseStrategy):
def __init__(self, path, maxsize=None, maxcount=None, key_func=None,
recover_func=None, key_len=16):
super(LfuDiskStrategy, self).__init__(maxsize, maxcount)
self._record = DiskRecord(path, key_func, recover_func, key_len)
self._lock = threading.RLock()
self._log = get_logger(self)
def remove_keys(self, storage):
with self._lock:
while self.is_excess(storage) and self._record.length():
to_remove = self._record.pop_idx()[0]
storage.delete(to_remove)
self._log.debug(u'清理缓存: %r', to_remove)
def handle_hit(self, key, value):
with self._lock:
idx, value = self._record.search(key)
value += 1
self._record.set_idx(idx, key, value)
pre_idx = idx - 1
while pre_idx >= 0 and self._record.get_idx(pre_idx)[1] <= value:
self._record.swap(pre_idx+1, pre_idx)
pre_idx -= 1
def handle_set(self, key, value):
with self._lock:
if not self._record.has(key):
i = self._record.length() - 1
while i >= 0 and self._record.get_idx(i)[1] <= 0:
i -= 1
self._record.insert(i+1, key, 0)
def reset(self, key):
self._record.pop(key) | pixiv_fetcher/cache/strategy.py | import struct
import threading
from pixiv_fetcher.utils.log import get_logger
from pixiv_fetcher.utils.path import make_direct_open
class BaseStrategy(object):
def __init__(self, maxsize=None, maxcount=None):
self.maxsize = maxsize
self.maxcount = maxcount
def reset(self, key):
raise NotImplemented()
def handle_set(self, key, value):
raise NotImplemented()
def handle_hit(self, key, value):
raise NotImplemented()
def handle_missing(self, key):
pass
def remove_keys(self, storage):
raise NotImplemented()
def is_excess(self, storage):
return storage.size > self.maxsize or storage.count > self.maxcount
class DoNothingStrategy(BaseStrategy):
def handle_set(self, *args, **kw):
pass
record_get = handle_set
reset = handle_set
remove_keys = handle_set
is_excess = handle_set
class FifoMemoryStrategy(BaseStrategy):
def __init__(self, maxsize=None, maxcount=None):
super(FifoMemoryStrategy, self).__init__(maxsize, maxcount)
self._keys = []
def reset(self, key):
while key in self._keys:
try:
self._keys.remove(key)
except ValueError:
pass
def handle_set(self, key, value):
if key not in self._keys:
self._keys.append(key)
def handle_hit(self, key, value):
# do nothing
pass
def remove_keys(self, storage):
while self.is_excess(storage) and self._keys:
storage.delete(self._keys.pop(0))
class LruMemoryStrategy(BaseStrategy):
"""
Least recently used strategy
"""
def __init__(self, maxsize=None, maxcount=None):
super(LruMemoryStrategy, self).__init__(maxsize, maxcount)
self._keys = []
self._lock = threading.RLock()
self._log = get_logger(self)
def reset(self, key):
raise NotImplemented()
def handle_set(self, key, value):
with self._lock:
while key in self._keys:
self._keys.remove(key)
self._keys.insert(0, key)
def handle_hit(self, key, value):
self.handle_set(key, value)
def remove_keys(self, storage):
while self.is_excess(storage) and self._keys:
with self._lock:
to_rm = self._keys.pop()
storage.delete(to_rm)
self._log.debug(u'清理缓存: %r', to_rm)
class DiskRecord(object):
_int_fmt = '<L'
_int_size = 4
def __init__(self, path, key_func=None, recover_func=None, key_len=16):
self._path = path
self._fp = make_direct_open(self._path, 'r+b', buffering=0)
self._key_len = key_len
self._key_func = key_func or (lambda _: _)
self._key_recover_func = recover_func or (lambda _: _)
self._lock = threading.RLock()
@property
def _row_length(self):
return self._key_len + self._int_size
def _pack_key(self, key):
k = self._key_func(key)
less = self._key_len - len(k)
k += chr(less) * less
return k
def _pack(self, key, c):
k = self._pack_key(key)
value = struct.pack(self._int_fmt, c)
return k + value
def _unpack(self, raw):
less = ord(raw[self._key_len-1])
value = struct.unpack(self._int_fmt, raw[self._key_len:])[0]
key = raw[:self._key_len]
if key <= less and key.endswith(chr(less) * less):
key = key[:-less]
return key, value
def insert(self, i, key, value):
curr_row = self._pack(key, value)
with self._lock:
num = self.length()
if i < 0:
i += num
elif i > num:
i = num
point = self._row_length * i + 5
self._fp.seek(point)
next_row = self._fp.read(self._row_length)
for i in xrange(num-i+1):
# 读到末尾空字符串位置不变
if next_row:
self._fp.seek(-self._row_length, 1)
self._fp.write(curr_row)
curr_row, next_row = next_row, self._fp.read(self._row_length)
self._write_length(num+1)
def set(self, key, value):
with self._lock:
idx, v = self.search(key)
if idx != -1:
p = self._row_length * idx + 5
self._fp.seek(p+self._key_len)
self._fp.write(struct.pack(self._int_fmt, value))
else:
idx = self.length()
end = self._row_length * idx + 5
self._fp.seek(end)
raw = self._pack(key, value)
self._fp.write(raw)
self._write_length(idx + 1)
return idx
def set_idx(self, i, key, value):
with self._lock:
p = 5 + i * self._row_length
self._fp.seek(p)
data = self._pack(key, value)
self._fp.write(data)
def swap(self, i1, i2):
with self._lock:
num = self.length()
if i1 >= num:
raise IndexError("%d (Length: %d)" % (i1, num))
if i2 >= num:
raise IndexError("%d (Length: %d)" % (i2, num))
p1 = 5 + self._row_length * i1
p2 = 5 + self._row_length * i2
self._fp.seek(p1)
data1 = self._fp.read(self._row_length)
self._fp.seek(p2)
data2 = self._fp.read(self._row_length)
self._fp.seek(p1)
self._fp.write(data2)
self._fp.seek(p2)
self._fp.write(data1)
def search(self, key):
num = self.length()
key = self._pack_key(key)
with self._lock:
self._fp.seek(5)
for i in xrange(num):
raw = self._fp.read(self._row_length)
k, value = self._unpack(raw)
if k == key:
return i, value
return -1, None
def get(self, key):
_, v = self.search(key)
return v
def get_idx(self, idx):
with self._lock:
p = 5 + self._row_length * idx
self._fp.seek(p)
raw = self._fp.read(self._row_length)
k, v = self._unpack(raw)
return self._key_recover_func(k), v
def has(self, key):
key = self._pack_key(key)
with self._lock:
num = self.length()
self._fp.seek(5)
for i in xrange(num):
k = self._fp.read(self._key_len)
if k == key:
return True
self._fp.seek(self._int_size, 1)
return False
def pop(self, key):
with self._lock:
idx, value = self.search(key)
self.pop_idx(idx)
return value
def pop_idx(self, idx=-1):
with self._lock:
num = self.length()
# FIXME: 索引越界
idx = num + idx if idx < 0 else idx
self._fp.seek(5 + self._row_length * idx)
raw_data = self._fp.read(self._row_length)
k, v = self._unpack(raw_data)
for i in xrange(num-idx):
next_row = self._fp.read(self._row_length)
self._fp.seek(-self._row_length*2, 1)
self._fp.write(next_row)
self._fp.seek(self._row_length, 1)
self._write_length(num-1)
return self._key_recover_func(k), v
def length(self):
with self._lock:
self._fp.seek(1)
bs = self._fp.read(4)
num = struct.unpack(self._int_fmt, bs)[0] if bs else 0
return num
def _write_length(self, l):
with self._lock:
self._fp.seek(1)
bs = struct.pack(self._int_fmt, l)
self._fp.write(bs)
def close(self):
if self._fp and not self._fp.closed:
self._fp.close()
def flush(self):
with self._lock:
self._fp.seek(0)
self._fp.flush()
class LfuDiskStrategy(BaseStrategy):
def __init__(self, path, maxsize=None, maxcount=None, key_func=None,
recover_func=None, key_len=16):
super(LfuDiskStrategy, self).__init__(maxsize, maxcount)
self._record = DiskRecord(path, key_func, recover_func, key_len)
self._lock = threading.RLock()
self._log = get_logger(self)
def remove_keys(self, storage):
with self._lock:
while self.is_excess(storage) and self._record.length():
to_remove = self._record.pop_idx()[0]
storage.delete(to_remove)
self._log.debug(u'清理缓存: %r', to_remove)
def handle_hit(self, key, value):
with self._lock:
idx, value = self._record.search(key)
value += 1
self._record.set_idx(idx, key, value)
pre_idx = idx - 1
while pre_idx >= 0 and self._record.get_idx(pre_idx)[1] <= value:
self._record.swap(pre_idx+1, pre_idx)
pre_idx -= 1
def handle_set(self, key, value):
with self._lock:
if not self._record.has(key):
i = self._record.length() - 1
while i >= 0 and self._record.get_idx(i)[1] <= 0:
i -= 1
self._record.insert(i+1, key, 0)
def reset(self, key):
self._record.pop(key) | 0.531209 | 0.114666 |
from .base_date_time import BaseDateTime
# pylint: disable=line-too-long
class EnglishDateTime:
LangMarker = 'Eng'
CheckBothBeforeAfter = False
TillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})'
RangeConnectorRegex = f'(?<and>\\b(and|through|to)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})'
LastNegPrefix = f'(?<!(w(ill|ould|on\\s*\'\\s*t)|m(ay|ight|ust)|sh(all|ould(n\\s*\'\\s*t)?)|c(an(\\s*\'\\s*t|not)?|ould(n\\s*\'\\s*t)?))(\\s+not)?\\s+)'
RelativeRegex = f'\\b(?<order>following|next|(up)?coming|this|{LastNegPrefix}last|past|previous|current|the)\\b'
StrictRelativeRegex = f'\\b(?<order>following|next|(up)?coming|this|{LastNegPrefix}last|past|previous|current)\\b'
UpcomingPrefixRegex = f'((this\\s+)?((up)?coming))'
NextPrefixRegex = f'\\b(following|next|{UpcomingPrefixRegex})\\b'
AfterNextSuffixRegex = f'\\b(after\\s+(the\\s+)?next)\\b'
PastPrefixRegex = f'((this\\s+)?past)\\b'
PreviousPrefixRegex = f'({LastNegPrefix}last|previous|{PastPrefixRegex})\\b'
ThisPrefixRegex = f'(this|current)\\b'
RangePrefixRegex = f'(from|between)'
CenturySuffixRegex = f'(^century)\\b'
ReferencePrefixRegex = f'(that|same)\\b'
FutureSuffixRegex = f'\\b(in\\s+the\\s+)?(future|hence)\\b'
DayRegex = f'(the\\s*)?(?<!(\\d+:?|\\$)\\s*)(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?)(?=\\b|t)'
ImplicitDayRegex = f'(the\\s*)?(?<day>(?:3[0-1]|[0-2]?\\d)(?:th|nd|rd|st))\\b'
MonthNumRegex = f'(?<month>1[0-2]|(0)?[1-9])\\b'
WrittenOneToNineRegex = f'(?:one|two|three|four|five|six|seven|eight|nine)'
WrittenElevenToNineteenRegex = f'(?:eleven|twelve|(?:thir|four|fif|six|seven|eigh|nine)teen)'
WrittenTensRegex = f'(?:ten|twenty|thirty|fou?rty|fifty|sixty|seventy|eighty|ninety)'
WrittenNumRegex = f'(?:{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}(\\s+{WrittenOneToNineRegex})?)'
WrittenCenturyFullYearRegex = f'(?:(one|two)\\s+thousand(\\s+and)?(\\s+{WrittenOneToNineRegex}\\s+hundred(\\s+and)?)?)'
WrittenCenturyOrdinalYearRegex = f'(?:twenty(\\s+(one|two))?|ten|eleven|twelve|thirteen|fifteen|eigthteen|(?:four|six|seven|nine)(teen)?|one|two|three|five|eight)'
CenturyRegex = f'\\b(?<century>{WrittenCenturyFullYearRegex}|{WrittenCenturyOrdinalYearRegex}(\\s+hundred)?(\\s+and)?)\\b'
LastTwoYearNumRegex = f'(?:zero\\s+{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}(\\s+{WrittenOneToNineRegex})?)'
FullTextYearRegex = f'\\b((?<firsttwoyearnum>{CenturyRegex})\\s+(?<lasttwoyearnum>{LastTwoYearNumRegex})\\b|\\b(?<firsttwoyearnum>{WrittenCenturyFullYearRegex}|{WrittenCenturyOrdinalYearRegex}\\s+hundred(\\s+and)?))\\b'
OclockRegex = f'(?<oclock>o\\s*((’|‘|\')\\s*)?clock|sharp)'
SpecialDescRegex = f'((?<ipm>)p\\b)'
AmDescRegex = f'(?:{BaseDateTime.BaseAmDescRegex})'
PmDescRegex = f'(:?{BaseDateTime.BasePmDescRegex})'
AmPmDescRegex = f'(:?{BaseDateTime.BaseAmPmDescRegex})'
DescRegex = f'(:?(:?({OclockRegex}\\s+)?(?<desc>({AmPmDescRegex}|{AmDescRegex}|{PmDescRegex}|{SpecialDescRegex})))|{OclockRegex})'
OfPrepositionRegex = f'(\\bof\\b)'
TwoDigitYearRegex = f'\\b(?<![$])(?<year>([0-9]\\d))(?!(\\s*((\\:\\d)|{AmDescRegex}|{PmDescRegex}|\\.\\d)))\\b'
YearRegex = f'(?:{BaseDateTime.FourDigitYearRegex}|{FullTextYearRegex})'
WeekDayRegex = f'\\b(?<weekday>(?:sun|mon|tues?|thurs?|fri)(day)?|thu|wedn(esday)?|weds?|sat(urday)?)s?\\b'
SingleWeekDayRegex = f'\\b(?<weekday>(?<!(easter|palm)\\s+)sunday|(?<!easter\\s+)saturday|(?<!(easter|cyber)\\s+)monday|mon|(?<!black\\s+)friday|fri|(?:tues?|thurs?)(day)?|thu|wedn(esday)?|weds?|((?<=on\\s+)(sat|sun)))\\b'
RelativeMonthRegex = f'(?<relmonth>((day\\s+)?of\\s+)?{RelativeRegex}\\s+month)\\b'
MonthRegex = f'\\b(?<month>apr(il)?|aug(ust)?|dec(ember)?|feb(ruary)?|jan(uary)?|july?|june?|mar(ch)?|may|nov(ember)?|oct(ober)?|sept(ember)?|sep)(?!\\p{{L}})'
WrittenMonthRegex = f'(((the\\s+)?month of\\s+)?{MonthRegex})'
MonthSuffixRegex = f'(?<msuf>(?:(in|of|on)\\s+)?({RelativeMonthRegex}|{WrittenMonthRegex}))'
DateUnitRegex = f'(?<unit>decades?|years?|months?|weeks?|(?<business>(business\\s+|week\\s*))?days?|fortnights?|weekends?|(?<=\\s+\\d{{1,4}})[ymwd])\\b'
DateTokenPrefix = 'on '
TimeTokenPrefix = 'at '
TokenBeforeDate = 'on '
TokenBeforeTime = 'at '
HalfTokenRegex = f'^(half)'
QuarterTokenRegex = f'^((a\\s+)?quarter)'
ThreeQuarterTokenRegex = f'^(three\\s+quarters?)'
ToTokenRegex = f'\\b(to)$'
FromRegex = f'\\b(from(\\s+the)?)$'
BetweenTokenRegex = f'\\b(between(\\s+the)?)$'
SimpleCasesRegex = f'\\b({RangePrefixRegex}\\s+)?({DayRegex})\\s*{TillRegex}\\s*({DayRegex}\\s+{MonthSuffixRegex}|{MonthSuffixRegex}\\s+{DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthFrontSimpleCasesRegex = f'\\b({RangePrefixRegex}\\s+)?{MonthSuffixRegex}\\s+((from)\\s+)?({DayRegex})\\s*{TillRegex}\\s*({DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthFrontBetweenRegex = f'\\b{MonthSuffixRegex}\\s+(between\\s+)({DayRegex})\\s*{RangeConnectorRegex}\\s*({DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
BetweenRegex = f'\\b(between\\s+)({DayRegex})\\s*{RangeConnectorRegex}\\s*({DayRegex})\\s+{MonthSuffixRegex}((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthWithYear = f'\\b(({WrittenMonthRegex}[\\.]?(\\s*)[/\\\\\\-\\.,]?(\\s+(of|in))?(\\s*)({YearRegex}|(?<order>following|next|last|this)\\s+year))|(({YearRegex}|(?<order>following|next|last|this)\\s+year)(\\s*),?(\\s*){WrittenMonthRegex}))\\b'
SpecialYearPrefixes = f'(calendar|(?<special>fiscal|school))'
OneWordPeriodRegex = f'\\b((((the\\s+)?month of\\s+)?({StrictRelativeRegex}\\s+)?{MonthRegex})|(month|year) to date|(?<toDate>((un)?till?|to)\\s+date)|({RelativeRegex}\\s+)?(my\\s+)?((?<business>working\\s+week|workweek)|week(end)?|month|fortnight|(({SpecialYearPrefixes}\\s+)?year))(?!((\\s+of)?\\s+\\d+(?!({BaseDateTime.BaseAmDescRegex}|{BaseDateTime.BasePmDescRegex}))|\\s+to\\s+date))(\\s+{AfterNextSuffixRegex})?)\\b'
MonthNumWithYear = f'\\b(({BaseDateTime.FourDigitYearRegex}(\\s*)[/\\-\\.](\\s*){MonthNumRegex})|({MonthNumRegex}(\\s*)[/\\-](\\s*){BaseDateTime.FourDigitYearRegex}))\\b'
WeekOfMonthRegex = f'\\b(?<wom>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+week\\s+{MonthSuffixRegex}(\\s+{BaseDateTime.FourDigitYearRegex}|{RelativeRegex}\\s+year)?)\\b'
WeekOfYearRegex = f'\\b(?<woy>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+week(\\s+of)?\\s+({YearRegex}|{RelativeRegex}\\s+year))\\b'
FollowedDateUnit = f'^\\s*{DateUnitRegex}'
NumberCombinedWithDateUnit = f'\\b(?<num>\\d+(\\.\\d*)?){DateUnitRegex}'
QuarterTermRegex = f'\\b(((?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th)[ -]+quarter)|(q(?<number>[1-4])))\\b'
RelativeQuarterTermRegex = f'\\b(?<orderQuarter>{StrictRelativeRegex})\\s+quarter\\b'
QuarterRegex = f'((the\\s+)?{QuarterTermRegex}(?:((\\s+of)?\\s+|\\s*[,-]\\s*)({YearRegex}|{RelativeRegex}\\s+year))?)|{RelativeQuarterTermRegex}'
QuarterRegexYearFront = f'(?:{YearRegex}|{RelativeRegex}\\s+year)(\'s)?(?:\\s*-\\s*|\\s+(the\\s+)?)?{QuarterTermRegex}'
HalfYearTermRegex = f'(?<cardinal>first|1st|second|2nd)\\s+half'
HalfYearFrontRegex = f'(?<year>((1[5-9]|20)\\d{{2}})|2100)(\\s*-\\s*|\\s+(the\\s+)?)?h(?<number>[1-2])'
HalfYearBackRegex = f'(the\\s+)?(h(?<number>[1-2])|({HalfYearTermRegex}))(\\s+of|\\s*,\\s*)?\\s+({YearRegex})'
HalfYearRelativeRegex = f'(the\\s+)?{HalfYearTermRegex}(\\s+of|\\s*,\\s*)?\\s+({RelativeRegex}\\s+year)'
AllHalfYearRegex = f'({HalfYearFrontRegex})|({HalfYearBackRegex})|({HalfYearRelativeRegex})'
EarlyPrefixRegex = f'\\b(?<EarlyPrefix>early|beginning of|start of|(?<RelEarly>earlier(\\s+in)?))\\b'
MidPrefixRegex = f'\\b(?<MidPrefix>mid-?|middle of)\\b'
LaterPrefixRegex = f'\\b(?<LatePrefix>late|end of|(?<RelLate>later(\\s+in)?))\\b'
PrefixPeriodRegex = f'({EarlyPrefixRegex}|{MidPrefixRegex}|{LaterPrefixRegex})'
PrefixDayRegex = f'\\b((?<EarlyPrefix>earl(y|ier))|(?<MidPrefix>mid(dle)?)|(?<LatePrefix>later?))(\\s+in)?(\\s+the\\s+day)?$'
SeasonDescRegex = f'(?<seas>spring|summer|fall|autumn|winter)'
SeasonRegex = f'\\b(?<season>({PrefixPeriodRegex}\\s+)?({RelativeRegex}\\s+)?{SeasonDescRegex}((\\s+of|\\s*,\\s*)?\\s+({YearRegex}|{RelativeRegex}\\s+year))?)\\b'
WhichWeekRegex = f'\\b(week)(\\s*)(?<number>5[0-3]|[1-4]\\d|0?[1-9])\\b'
WeekOfRegex = f'(the\\s+)?((week)(\\s+(of|(commencing|starting|beginning)(\\s+on)?))|w/c)(\\s+the)?'
MonthOfRegex = f'(month)(\\s*)(of)'
DateYearRegex = f'(?<year>{BaseDateTime.FourDigitYearRegex}|(?<!,\\s?){TwoDigitYearRegex}|{TwoDigitYearRegex}(?=(\\.(?!\\d)|[?!;]|$)))'
YearSuffix = f'((,|\\sof)?\\s*({DateYearRegex}|{FullTextYearRegex}))'
OnRegex = f'(?<=\\bon\\s+)({DayRegex}s?)\\b'
RelaxedOnRegex = f'(?<=\\b(on|at|in)\\s+)((?<day>(3[0-1]|[0-2]?\\d)(?:th|nd|rd|st))s?)\\b'
PrefixWeekDayRegex = f'(\\s*((,?\\s*on)|[-—–]))'
ThisRegex = f'\\b(this(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|({WeekDayRegex}((\\s+of)?\\s+this\\s*week))\\b'
LastDateRegex = f'\\b({PreviousPrefixRegex}(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|({WeekDayRegex}(\\s+(of\\s+)?last\\s*week))\\b'
NextDateRegex = f'\\b({NextPrefixRegex}(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|((on\\s+)?{WeekDayRegex}((\\s+of)?\\s+(the\\s+following|(the\\s+)?next)\\s*week))\\b'
SpecialDayRegex = f'\\b((the\\s+)?day before yesterday|(the\\s+)?day after (tomorrow|tmr)|the\\s+day\\s+(before|after)(?!=\\s+day)|((the\\s+)?({RelativeRegex}|my)\\s+day)|yesterday|tomorrow|tmr|today|otd)\\b'
SpecialDayWithNumRegex = f'\\b((?<number>{WrittenNumRegex})\\s+days?\\s+from\\s+(?<day>yesterday|tomorrow|tmr|today))\\b'
RelativeDayRegex = f'\\b(((the\\s+)?{RelativeRegex}\\s+day))\\b'
SetWeekDayRegex = f'\\b(?<prefix>on\\s+)?(?<weekday>morning|afternoon|evening|night|(sun|mon|tues|wednes|thurs|fri|satur)day)s\\b'
WeekDayOfMonthRegex = f'(?<wom>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+(week\\s+{MonthSuffixRegex}[\\.]?\\s+(on\\s+)?{WeekDayRegex}|{WeekDayRegex}\\s+{MonthSuffixRegex}))'
RelativeWeekDayRegex = f'\\b({WrittenNumRegex}\\s+{WeekDayRegex}\\s+(from\\s+now|later))\\b'
SpecialDate = f'(?=\\b(on|at)\\s+the\\s+){DayRegex}\\b'
DatePreposition = f'\\b(on|in)'
DateExtractorYearTermRegex = f'(\\s+|\\s*[/\\\\.,-]\\s*|\\s+of\\s+){DateYearRegex}'
DayPrefix = f'\\b({WeekDayRegex}|{SpecialDayRegex})\\b'
DateExtractor1 = f'\\b({DayPrefix}\\s*[,-]?\\s*)?(({MonthRegex}[\\.]?\\s*[/\\\\.,-]?\\s*{DayRegex})|(\\({MonthRegex}\\s*[-./]\\s*{DayRegex}\\)))(\\s*\\(\\s*{DayPrefix}\\s*\\))?({DateExtractorYearTermRegex}\\b)?'
DateExtractor3 = f'\\b({DayPrefix}(\\s+|\\s*,\\s*))?({DayRegex}[\\.]?(\\s+|\\s*[-,/]\\s*|\\s+of\\s+){MonthRegex}[\\.]?((\\s+in)?{DateExtractorYearTermRegex})?|{BaseDateTime.FourDigitYearRegex}\\s*[-./]?\\s*(the\\s+)?(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?)[\\.]?(\\s+|\\s*[-,/]\\s*|\\s+of\\s+){MonthRegex}[\\.]?)\\b'
DateExtractor4 = f'\\b{MonthNumRegex}\\s*[/\\\\\\-]\\s*{DayRegex}[\\.]?\\s*[/\\\\\\-]\\s*{DateYearRegex}'
DateExtractor5 = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*[/\\\\\\-\\.]\\s*({MonthNumRegex}|{MonthRegex})\\s*[/\\\\\\-\\.]\\s*{DateYearRegex}(?!\\s*[/\\\\\\-\\.]\\s*\\d+)'
DateExtractor6 = f'(?<={DatePreposition}\\s+)({StrictRelativeRegex}\\s+)?({DayPrefix}\\s+)?{MonthNumRegex}[\\-\\.]{DayRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor7L = f'\\b({DayPrefix}(\\s*,)?\\s+)?{MonthNumRegex}\\s*/\\s*{DayRegex}{DateExtractorYearTermRegex}(?![%])\\b'
DateExtractor7S = f'\\b({DayPrefix}(\\s*,)?\\s+)?{MonthNumRegex}\\s*/\\s*{DayRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor8 = f'(?<={DatePreposition}\\s+)({StrictRelativeRegex}\\s+)?({DayPrefix}\\s+)?{DayRegex}[\\\\\\-]{MonthNumRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor9L = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*/\\s*{MonthNumRegex}{DateExtractorYearTermRegex}(?![%])\\b'
DateExtractor9S = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*/\\s*{MonthNumRegex}{BaseDateTime.CheckDecimalRegex}(?![%])\\b'
DateExtractorA = f'\\b({DayPrefix}(\\s*,)?\\s+)?(({BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*({MonthNumRegex}|{MonthRegex})\\s*[/\\\\\\-\\.]\\s*{DayRegex})|({MonthRegex}\\s*[/\\\\\\-\\.]\\s*{BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*(the\\s+)?(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?))|({DayRegex}\\s*[/\\\\\\-\\.]\\s*{BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*{MonthRegex}))'
OfMonth = f'^\\s*(day\\s+)?of\\s*{MonthRegex}'
MonthEnd = f'{MonthRegex}\\s*(the)?\\s*$'
WeekDayEnd = f'(this\\s+)?{WeekDayRegex}\\s*,?\\s*$'
WeekDayStart = f'^[\\.]'
RangeUnitRegex = f'\\b(?<unit>years?|months?|weeks?|fortnights?)\\b'
HourNumRegex = f'\\b(?<hournum>zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\\b'
MinuteNumRegex = f'(((?<tens>twenty|thirty|fou?rty|fifty)(\\s*-?\\s*))?(?<minnum>one|two|three|four|five|six|seven|eight|nine)|(?<minnum>ten|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)|twenty|thirty|forty|fifty))'
DeltaMinuteNumRegex = f'(((?<tens>twenty|thirty|fou?rty|fifty)(\\s*-?\\s*))?(?<deltaminnum>one|two|three|four|five|six|seven|eight|nine)|(?<deltaminnum>ten|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)|twenty|thirty|forty|fifty))'
PmRegex = f'(?<pm>(((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(afternoon|evening|midnight|lunchtime))|((at|in|around|on|for)\\s+(the\\s+)?night))'
PmRegexFull = f'(?<pm>((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(afternoon|evening|(mid)?night|lunchtime))'
AmRegex = f'(?<am>((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(morning))'
LunchRegex = f'\\blunchtime\\b'
NightRegex = f'\\b(mid)?night\\b'
CommonDatePrefixRegex = f'^[\\.]'
LessThanOneHour = f'(?<lth>(a\\s+)?quarter|three quarter(s)?|half( an hour)?|{BaseDateTime.DeltaMinuteRegex}(\\s+(minutes?|mins?))|{DeltaMinuteNumRegex}(\\s+(minutes?|mins?)))'
WrittenTimeRegex = f'(?<writtentime>{HourNumRegex}\\s+{MinuteNumRegex}(\\s+(minutes?|mins?))?)'
TimePrefix = f'(?<prefix>{LessThanOneHour}\\s+(past|to))'
TimeSuffix = f'(?<suffix>{AmRegex}|{PmRegex}|{OclockRegex})'
TimeSuffixFull = f'(?<suffix>{AmRegex}|{PmRegexFull}|{OclockRegex})'
BasicTime = f'\\b(?<basictime>{WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}:{BaseDateTime.MinuteRegex}(:{BaseDateTime.SecondRegex})?|{BaseDateTime.HourRegex}(?![%\\d]))'
MidnightRegex = f'(?<midnight>mid\\s*(-\\s*)?night)'
MidmorningRegex = f'(?<midmorning>mid\\s*(-\\s*)?morning)'
MidafternoonRegex = f'(?<midafternoon>mid\\s*(-\\s*)?afternoon)'
MiddayRegex = f'(?<midday>mid\\s*(-\\s*)?day|((12\\s)?noon))'
MidTimeRegex = f'(?<mid>({MidnightRegex}|{MidmorningRegex}|{MidafternoonRegex}|{MiddayRegex}))'
AtRegex = f'\\b(?:(?:(?<=\\b(at|(at)?\\s*around|circa)\\s+)(?:{WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}(?!\\.\\d)(\\s*((?<iam>a)|(?<ipm>p)))?|{MidTimeRegex}))|{MidTimeRegex})\\b'
IshRegex = f'\\b({BaseDateTime.HourRegex}(-|——)?ish|noon(ish)?)\\b'
TimeUnitRegex = f'([^a-z]{{1,}}|\\b)(?<unit>h(ou)?rs?|h|min(ute)?s?|sec(ond)?s?)\\b'
RestrictedTimeUnitRegex = f'(?<unit>hour|minute)\\b'
FivesRegex = f'(?<tens>(?:fifteen|(?:twen|thir|fou?r|fif)ty(\\s*five)?|ten|five))\\b'
HourRegex = f'\\b{BaseDateTime.HourRegex}'
PeriodHourNumRegex = f'\\b(?<hour>twenty(\\s+(one|two|three|four))?|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)?|zero|one|two|three|five|eight|ten)\\b'
ConnectNumRegex = f'\\b{BaseDateTime.HourRegex}(?<min>[0-5][0-9])\\s*{DescRegex}'
TimeRegexWithDotConnector = f'({BaseDateTime.HourRegex}(\\s*\\.\\s*){BaseDateTime.MinuteRegex})'
TimeRegex1 = f'\\b({TimePrefix}\\s+)?({WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex})(\\s*|[.]){DescRegex}'
TimeRegex2 = f'(\\b{TimePrefix}\\s+)?(t)?{BaseDateTime.HourRegex}(\\s*)?:(\\s*)?{BaseDateTime.MinuteRegex}((\\s*)?:(\\s*)?{BaseDateTime.SecondRegex})?(?<iam>a)?((\\s*{DescRegex})|\\b)'
TimeRegex3 = f'(\\b{TimePrefix}\\s+)?{BaseDateTime.HourRegex}\\.{BaseDateTime.MinuteRegex}(\\s*{DescRegex})'
TimeRegex4 = f'\\b{TimePrefix}\\s+{BasicTime}(\\s*{DescRegex})?\\s+{TimeSuffix}\\b'
TimeRegex5 = f'\\b{TimePrefix}\\s+{BasicTime}((\\s*{DescRegex})|\\b)'
TimeRegex6 = f'({BasicTime})(\\s*{DescRegex})?\\s+{TimeSuffix}\\b'
TimeRegex7 = f'\\b{TimeSuffixFull}\\s+(at\\s+)?{BasicTime}((\\s*{DescRegex})|\\b)'
TimeRegex8 = f'.^'
TimeRegex9 = f'\\b{PeriodHourNumRegex}(\\s+|-){FivesRegex}((\\s*{DescRegex})|\\b)'
TimeRegex10 = f'\\b({TimePrefix}\\s+)?{BaseDateTime.HourRegex}(\\s*h\\s*){BaseDateTime.MinuteRegex}(\\s*{DescRegex})?'
TimeRegex11 = f'\\b((?:({TimeTokenPrefix})?{TimeRegexWithDotConnector}(\\s*{DescRegex}))|(?:(?:{TimeTokenPrefix}{TimeRegexWithDotConnector})(?!\\s*per\\s*cent|%)))'
FirstTimeRegexInTimeRange = f'\\b{TimeRegexWithDotConnector}(\\s*{DescRegex})?'
PureNumFromTo = f'({RangePrefixRegex}\\s+)?({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?\\s*{TillRegex}\\s*({HourRegex}|{PeriodHourNumRegex})(?<rightDesc>\\s*({PmRegex}|{AmRegex}|{DescRegex}))?'
PureNumBetweenAnd = f'(between\\s+)(({BaseDateTime.TwoDigitHourRegex}{BaseDateTime.TwoDigitMinuteRegex})|{HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?\\s*{RangeConnectorRegex}\\s*(({BaseDateTime.TwoDigitHourRegex}{BaseDateTime.TwoDigitMinuteRegex})|{HourRegex}|{PeriodHourNumRegex})(?<rightDesc>\\s*({PmRegex}|{AmRegex}|{DescRegex}))?'
SpecificTimeFromTo = f'({RangePrefixRegex}\\s+)?(?<time1>(({TimeRegex2}|{FirstTimeRegexInTimeRange})|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?))\\s*{TillRegex}\\s*(?<time2>(({TimeRegex2}|{TimeRegexWithDotConnector}(?<rightDesc>\\s*{DescRegex}))|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<rightDesc>{DescRegex}))?))'
SpecificTimeBetweenAnd = f'(between\\s+)(?<time1>(({TimeRegex2}|{FirstTimeRegexInTimeRange})|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?))\\s*{RangeConnectorRegex}\\s*(?<time2>(({TimeRegex2}|{TimeRegexWithDotConnector}(?<rightDesc>\\s*{DescRegex}))|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<rightDesc>{DescRegex}))?))'
SuffixAfterRegex = f'\\b(((at)\\s)?(or|and)\\s+(above|after|later|greater)(?!\\s+than))\\b'
PrepositionRegex = f'(?<prep>^(,\\s*)?(at|on|of)(\\s+the)?$)'
LaterEarlyRegex = f'((?<early>earl(y|ier)(\\s+|-))|(?<late>late(r?\\s+|-)))'
MealTimeRegex = f'\\b(at\\s+)?(?<mealTime>breakfast|brunch|lunch(\\s*time)?|dinner(\\s*time)?|supper)\\b'
UnspecificTimePeriodRegex = f'({MealTimeRegex})'
TimeOfDayRegex = f'\\b(?<timeOfDay>((((in\\s+the\\s+)?{LaterEarlyRegex}?(in(\\s+the)?\\s+)?(morning|afternoon|night|evening)))|{MealTimeRegex}|(((in\\s+(the)?\\s+)?)(daytime|business\\s+hour)))s?)\\b'
SpecificTimeOfDayRegex = f'\\b(({StrictRelativeRegex}\\s+{TimeOfDayRegex})\\b|\\btoni(ght|te))s?\\b'
TimeFollowedUnit = f'^\\s*{TimeUnitRegex}'
TimeNumberCombinedWithUnit = f'\\b(?<num>\\d+(\\.\\d*)?){TimeUnitRegex}'
BusinessHourSplitStrings = [r'business', r'hour']
NowRegex = f'\\b(?<now>(right\\s+)?now|as\\s+soon\\s+as\\s+possible|asap|recently|previously|at\\s+(present|this\\s+time|th(e|is)\\s+minute|the\\s+(moment|present\\s+time)))\\b'
NowParseRegex = f'\\b({NowRegex}|^(date)$)\\b'
SuffixRegex = f'^\\s*(in the\\s+)?(morning|afternoon|evening|night)\\b'
NonTimeContextTokens = f'(building)'
DateTimeTimeOfDayRegex = f'\\b(?<timeOfDay>morning|(?<pm>afternoon|night|evening))\\b'
DateTimeSpecificTimeOfDayRegex = f'\\b(({RelativeRegex}\\s+{DateTimeTimeOfDayRegex})\\b|\\btoni(ght|te))\\b'
TimeOfTodayAfterRegex = f'^\\s*(,\\s*)?(in\\s+)?{DateTimeSpecificTimeOfDayRegex}'
TimeOfTodayBeforeRegex = f'{DateTimeSpecificTimeOfDayRegex}(\\s*,)?(\\s+(at|around|circa|in|on))?\\s*$'
SimpleTimeOfTodayAfterRegex = f'(?<!{NonTimeContextTokens}\\s*)\\b({HourNumRegex}|{BaseDateTime.HourRegex})\\s*(,\\s*)?(in\\s+)?{DateTimeSpecificTimeOfDayRegex}\\b'
SimpleTimeOfTodayBeforeRegex = f'\\b{DateTimeSpecificTimeOfDayRegex}(\\s*,)?(\\s+(at|around|circa))?\\s*({HourNumRegex}|{BaseDateTime.HourRegex})\\b'
SpecificEndOfRegex = f'(the\\s+)?end of(\\s+the)?\\s*$'
UnspecificEndOfRegex = f'\\b(the\\s+)?(eod|(end\\s+of\\s+day))\\b'
UnspecificEndOfRangeRegex = f'\\b(eoy)\\b'
PeriodTimeOfDayRegex = f'\\b((in\\s+(the)?\\s+)?{LaterEarlyRegex}?(this\\s+)?{DateTimeTimeOfDayRegex})\\b'
PeriodSpecificTimeOfDayRegex = f'\\b({LaterEarlyRegex}?this\\s+{DateTimeTimeOfDayRegex}|({StrictRelativeRegex}\\s+{PeriodTimeOfDayRegex})\\b|\\btoni(ght|te))\\b'
PeriodTimeOfDayWithDateRegex = f'\\b(({PeriodTimeOfDayRegex}(\\s+(on|of))?))\\b'
LessThanRegex = f'\\b(less\\s+than)\\b'
MoreThanRegex = f'\\b(more\\s+than)\\b'
DurationUnitRegex = f'(?<unit>{DateUnitRegex}|h(ou)?rs?|h|min(ute)?s?|sec(ond)?s?|nights?)\\b'
SuffixAndRegex = f'(?<suffix>\\s*(and)\\s+(an?\\s+)?(?<suffix_num>half|quarter))'
PeriodicRegex = f'\\b(?<periodic>((?<multiplier>semi|bi|tri)(\\s*|-))?(daily|monthly|weekly|quarterly|yearly|annual(ly)?))\\b'
EachUnitRegex = f'\\b(?<each>(each|every|any|once an?)(?<other>\\s+other)?\\s+({DurationUnitRegex}|(?<specialUnit>quarters?|weekends?)|{WeekDayRegex})|(?<specialUnit>weekends))'
EachPrefixRegex = f'\\b(?<each>(each|every|once an?)\\s*$)'
SetEachRegex = f'\\b(?<each>(each|every)(?<other>\\s+other)?\\s*)(?!the|that)\\b'
SetLastRegex = f'(?<last>following|next|upcoming|this|{LastNegPrefix}last|past|previous|current)'
EachDayRegex = f'^\\s*(each|every)\\s*day\\b'
DurationFollowedUnit = f'(^\\s*{DurationUnitRegex}\\s+{SuffixAndRegex})|(^\\s*{SuffixAndRegex}?(\\s+|-)?{DurationUnitRegex})'
NumberCombinedWithDurationUnit = f'\\b(?<num>\\d+(\\.\\d*)?)(-)?{DurationUnitRegex}'
AnUnitRegex = f'(\\b((?<half>(half)\\s+)?an?|another)|(?<half>(1/2|½|half)))\\s+{DurationUnitRegex}'
DuringRegex = f'\\b(for|during)\\s+the\\s+(?<unit>year|month|week|day|fortnight)\\b'
AllRegex = f'\\b(?<all>(all|full|whole)(\\s+|-)(?<unit>year|month|week|day|fortnight))\\b'
HalfRegex = f'((an?\\s*)|\\b)(?<half>half\\s+(?<unit>year|month|week|fortnight|day|hour))\\b'
ConjunctionRegex = f'\\b((and(\\s+for)?)|with)\\b'
HolidayList1 = f'(?<holiday>mardi gras|(washington|mao)\'s birthday|juneteenth|(jubilee|freedom)(\\s+day)|chinese new year|(new\\s+(years\'|year\\s*\'s|years?)\\s+eve)|(new\\s+(years\'|year\\s*\'s|years?)(\\s+day)?)|may\\s*day|yuan dan|christmas eve|(christmas|xmas)(\\s+day)?|black friday|yuandan|easter(\\s+(sunday|saturday|monday))?|clean monday|ash wednesday|palm sunday|maundy thursday|good friday|white\\s+(sunday|monday)|trinity sunday|pentecost|corpus christi|cyber monday)'
HolidayList2 = f'(?<holiday>(thanks\\s*giving|all saint\'s|white lover|s(?:ain)?t?(\\.)?\\s+(?:patrick|george)(?:\')?(?:s)?|us independence|all hallow|all souls|guy fawkes|cinco de mayo|halloween|qingming|dragon boat|april fools|tomb\\s*sweeping)(\\s+day)?)'
HolidayList3 = f'(?<holiday>(?:independence|presidents(?:\')?|mlk|martin luther king( jr)?|canberra|ascension|columbus|tree( planting)?|arbor|labou?r|((international|int\'?l)\\s+)?workers\'?|mother\'?s?|father\'?s?|female|women(\'s)?|single|teacher\'?s|youth|children|girls|lovers?|earth|inauguration|groundhog|valentine\'?s|baptiste|bastille|veterans(?:\')?|memorial|mid[ \\-]autumn|moon|spring|lantern)\\s+day)'
HolidayRegex = f'\\b(({StrictRelativeRegex}\\s+({HolidayList1}|{HolidayList2}|{HolidayList3}))|(({HolidayList1}|{HolidayList2}|{HolidayList3})(\\s+(of\\s+)?({YearRegex}|{RelativeRegex}\\s+year))?))\\b'
AMTimeRegex = f'(?<am>morning)'
PMTimeRegex = f'\\b(?<pm>afternoon|evening|night)\\b'
NightTimeRegex = f'(night)'
NowTimeRegex = f'(now|at\\s+(present|this\\s+time|th(e|is)\\s+minute|the\\s+(moment|present\\s+time)))'
RecentlyTimeRegex = f'(recently|previously)'
AsapTimeRegex = f'(as soon as possible|asap)'
InclusiveModPrepositions = f'(?<include>((on|in|at)\\s+or\\s+)|(\\s+or\\s+(on|in|at)))'
AroundRegex = f'(?:\\b(?:around|circa)\\s*?\\b)(\\s+the)?'
BeforeRegex = f'((\\b{InclusiveModPrepositions}?(?:before|in\\s+advance\\s+of|prior\\s+to|(no\\s+later|earlier|sooner)\\s+than|ending\\s+(with|on)|by|(un)?till?|(?<include>as\\s+late\\s+as)){InclusiveModPrepositions}?\\b\\s*?)|(?<!\\w|>)((?<include><\\s*=)|<))(\\s+the)?'
AfterRegex = f'((\\b{InclusiveModPrepositions}?((after|(starting|beginning)(\\s+on)?(?!\\sfrom)|(?<!no\\s+)later than)|(year greater than))(?!\\s+or equal to){InclusiveModPrepositions}?\\b\\s*?)|(?<!\\w|<)((?<include>>\\s*=)|>))(\\s+the)?'
SinceRegex = f'(?:(?:\\b(?:since|after\\s+or\\s+equal\\s+to|starting\\s+(?:from|on|with)|as\\s+early\\s+as|(any\\s+time\\s+)from)\\b\\s*?)|(?<!\\w|<)(>=))(\\s+the)?'
SinceRegexExp = f'({SinceRegex}|\\bfrom(\\s+the)?\\b)'
AgoRegex = f'\\b(ago|before\\s+(?<day>yesterday|today))\\b'
LaterRegex = f'\\b(?:later(?!((\\s+in)?\\s*{OneWordPeriodRegex})|(\\s+{TimeOfDayRegex})|\\s+than\\b)|from now|(from|after)\\s+(?<day>tomorrow|tmr|today))\\b'
BeforeAfterRegex = f'\\b((?<before>before)|(?<after>from|after))\\b'
InConnectorRegex = f'\\b(in)\\b'
SinceYearSuffixRegex = f'(^\\s*{SinceRegex}(\\s*(the\\s+)?year\\s*)?{YearSuffix})'
WithinNextPrefixRegex = f'\\b(within(\\s+the)?(\\s+(?<next>{NextPrefixRegex}))?)\\b'
TodayNowRegex = f'\\b(today|now)\\b'
MorningStartEndRegex = f'(^(morning|{AmDescRegex}))|((morning|{AmDescRegex})$)'
AfternoonStartEndRegex = f'(^(afternoon|{PmDescRegex}))|((afternoon|{PmDescRegex})$)'
EveningStartEndRegex = f'(^(evening))|((evening)$)'
NightStartEndRegex = f'(^(over|to)?ni(ght|te))|((over|to)?ni(ght|te)$)'
InexactNumberRegex = f'\\b((a\\s+)?few|some|several|(?<NumTwoTerm>(a\\s+)?couple(\\s+of)?))\\b'
InexactNumberUnitRegex = f'({InexactNumberRegex})\\s+({DurationUnitRegex})'
RelativeTimeUnitRegex = f'(?:(?:(?:{NextPrefixRegex}|{PreviousPrefixRegex}|{ThisPrefixRegex})\\s+({TimeUnitRegex}))|((the|my))\\s+({RestrictedTimeUnitRegex}))'
RelativeDurationUnitRegex = f'(?:(?:(?<=({NextPrefixRegex}|{PreviousPrefixRegex}|{ThisPrefixRegex})\\s+)({DurationUnitRegex}))|((the|my))\\s+({RestrictedTimeUnitRegex}))'
ReferenceDatePeriodRegex = f'\\b{ReferencePrefixRegex}\\s+(?<duration>week(end)?|fortnight|month|year|decade)\\b'
ConnectorRegex = f'^(-|,|for|t|around|circa|@)$'
FromToRegex = f'(\\b(from).+(to|and|or)\\b.+)'
SingleAmbiguousMonthRegex = f'^(the\\s+)?(may|march)$'
SingleAmbiguousTermsRegex = f'^(the\\s+)?(day|week|month|year)$'
UnspecificDatePeriodRegex = f'^(week|fortnight|month|year)$'
PrepositionSuffixRegex = f'\\b(on|in|at|around|circa|from|to)$'
FlexibleDayRegex = f'(?<DayOfMonth>([A-Za-z]+\\s)?[A-Za-z\\d]+)'
ForTheRegex = f'\\b((((?<=for\\s+)the\\s+{FlexibleDayRegex})|((?<=on\\s+)(the\\s+)?{FlexibleDayRegex}(?<=(st|nd|rd|th))))(?<end>\\s*(,|\\.(?!\\d)|!|\\?|$)))'
WeekDayAndDayOfMonthRegex = f'\\b{WeekDayRegex}\\s+(the\\s+{FlexibleDayRegex})\\b'
WeekDayAndDayRegex = f'\\b{WeekDayRegex}\\s+(?!(the)){DayRegex}(?!([-:]|(\\s+({AmDescRegex}|{PmDescRegex}|{OclockRegex}))))\\b'
RestOfDateRegex = f'\\b(rest|remaining)\\s+(of\\s+)?((the|my|this|current)\\s+)?(?<duration>week|fortnight|month|year|decade)\\b'
RestOfDateTimeRegex = f'\\b(rest|remaining)\\s+(of\\s+)?((the|my|this|current)\\s+)?(?<unit>day)\\b'
AmbiguousRangeModifierPrefix = f'(from)'
NumberEndingPattern = f'^(?:\\s+(?<meeting>meeting|appointment|conference|((skype|teams|zoom|facetime)\\s+)?call)\\s+to\\s+(?<newTime>{PeriodHourNumRegex}|{HourRegex})([\\.]?$|(\\.,|,|!|\\?)))'
OneOnOneRegex = f'\\b(1\\s*:\\s*1(?!\\d))|(one (on )?one|one\\s*-\\s*one|one\\s*:\\s*one)\\b'
LaterEarlyPeriodRegex = f'\\b(({PrefixPeriodRegex})\\s*\\b\\s*(?<suffix>{OneWordPeriodRegex}|(?<FourDigitYear>{BaseDateTime.FourDigitYearRegex}))|({UnspecificEndOfRangeRegex}))\\b'
WeekWithWeekDayRangeRegex = f'\\b((?<week>({NextPrefixRegex}|{PreviousPrefixRegex}|this)\\s+week)((\\s+between\\s+{WeekDayRegex}\\s+and\\s+{WeekDayRegex})|(\\s+from\\s+{WeekDayRegex}\\s+to\\s+{WeekDayRegex})))\\b'
GeneralEndingRegex = f'^\\s*((\\.,)|\\.|,|!|\\?)?\\s*$'
MiddlePauseRegex = f'\\s*(,)\\s*'
DurationConnectorRegex = f'^\\s*(?<connector>\\s+|and|,)\\s*$'
PrefixArticleRegex = f'\\bthe\\s+'
OrRegex = f'\\s*((\\b|,\\s*)(or|and)\\b|,)\\s*'
SpecialYearTermsRegex = f'\\b((({SpecialYearPrefixes}\\s+)?year)|(cy|(?<special>fy|sy)))'
YearPlusNumberRegex = f'\\b({SpecialYearTermsRegex}\\s*((?<year>(\\d{{2,4}}))|{FullTextYearRegex}))\\b'
NumberAsTimeRegex = f'\\b({WrittenTimeRegex}|{PeriodHourNumRegex}|{BaseDateTime.HourRegex})\\b'
TimeBeforeAfterRegex = f'\\b(((?<=\\b(before|no later than|by|after)\\s+)({WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}|{MidTimeRegex}))|{MidTimeRegex})\\b'
DateNumberConnectorRegex = f'^\\s*(?<connector>\\s+at)\\s*$'
DecadeRegex = f'(?<decade>(?:nough|twen|thir|fou?r|fif|six|seven|eigh|nine)ties|two\\s+thousands)'
DecadeWithCenturyRegex = f'(the\\s+)?(((?<century>\\d|1\\d|2\\d)?(\')?(?<decade>\\d0)(\')?(\\s)?s\\b)|(({CenturyRegex}(\\s+|-)(and\\s+)?)?{DecadeRegex})|({CenturyRegex}(\\s+|-)(and\\s+)?(?<decade>tens|hundreds)))'
RelativeDecadeRegex = f'\\b((the\\s+)?{RelativeRegex}\\s+((?<number>[\\w,]+)\\s+)?decades?)\\b'
YearPeriodRegex = f'((((from|during|in)\\s+)?{YearRegex}\\s*({TillRegex})\\s*{YearRegex})|(((between)\\s+){YearRegex}\\s*({RangeConnectorRegex})\\s*{YearRegex}))'
StrictTillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b|{BaseDateTime.RangeConnectorSymbolRegex}(?!\\s*(h[1-2]|q[1-4])(?!(\\s+of|\\s*,\\s*))))'
StrictRangeConnectorRegex = f'(?<and>\\b(and|through|to)\\b|{BaseDateTime.RangeConnectorSymbolRegex}(?!\\s*(h[1-2]|q[1-4])(?!(\\s+of|\\s*,\\s*))))'
StartMiddleEndRegex = f'\\b((?<StartOf>((the\\s+)?(start|beginning)\\s+of\\s+)?)(?<MiddleOf>((the\\s+)?middle\\s+of\\s+)?)(?<EndOf>((the\\s+)?end\\s+of\\s+)?))'
ComplexDatePeriodRegex = f'(?:((from|during|in)\\s+)?{StartMiddleEndRegex}(?<start>.+)\\s*({StrictTillRegex})\\s*{StartMiddleEndRegex}(?<end>.+)|((between)\\s+){StartMiddleEndRegex}(?<start>.+)\\s*({StrictRangeConnectorRegex})\\s*{StartMiddleEndRegex}(?<end>.+))'
FailFastRegex = f'{BaseDateTime.DeltaMinuteRegex}|\\b(?:{BaseDateTime.BaseAmDescRegex}|{BaseDateTime.BasePmDescRegex})|{BaseDateTime.BaseAmPmDescRegex}|\\b(?:zero|{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}|{WrittenMonthRegex}|{SeasonDescRegex}|{DecadeRegex}|centur(y|ies)|weekends?|quarters?|hal(f|ves)|yesterday|to(morrow|day|night)|tmr|noonish|\\d(-|——)?ish|((the\\s+\\w*)|\\d)(th|rd|nd|st)|(mid\\s*(-\\s*)?)?(night|morning|afternoon|day)s?|evenings?|noon|lunch(time)?|dinner(time)?|(day|night)time|overnight|dawn|dusk|sunset|hours?|hrs?|h|minutes?|mins?|seconds?|secs?|eo[dmy]|mardi[ -]?gras|birthday|eve|christmas|xmas|thanksgiving|halloween|yuandan|easter|yuan dan|april fools|cinco de mayo|all (hallow|souls)|guy fawkes|(st )?patrick|hundreds?|noughties|aughts|thousands?)\\b|{WeekDayRegex}|{SetWeekDayRegex}|{NowRegex}|{PeriodicRegex}|\\b({DateUnitRegex}|{ImplicitDayRegex})'
UnitMap = dict([("decades", "10Y"),
("decade", "10Y"),
("years", "Y"),
("year", "Y"),
("months", "MON"),
("month", "MON"),
("quarters", "3MON"),
("quarter", "3MON"),
("semesters", "6MON"),
("semestres", "6MON"),
("semester", "6MON"),
("semestre", "6MON"),
("weeks", "W"),
("week", "W"),
("weekends", "WE"),
("weekend", "WE"),
("fortnights", "2W"),
("fortnight", "2W"),
("weekdays", "D"),
("weekday", "D"),
("days", "D"),
("day", "D"),
("nights", "D"),
("night", "D"),
("hours", "H"),
("hour", "H"),
("hrs", "H"),
("hr", "H"),
("h", "H"),
("minutes", "M"),
("minute", "M"),
("mins", "M"),
("min", "M"),
("seconds", "S"),
("second", "S"),
("secs", "S"),
("sec", "S")])
UnitValueMap = dict([("decades", 315360000),
("decade", 315360000),
("years", 31536000),
("year", 31536000),
("months", 2592000),
("month", 2592000),
("fortnights", 1209600),
("fortnight", 1209600),
("weekends", 172800),
("weekend", 172800),
("weeks", 604800),
("week", 604800),
("days", 86400),
("day", 86400),
("nights", 86400),
("night", 86400),
("hours", 3600),
("hour", 3600),
("hrs", 3600),
("hr", 3600),
("h", 3600),
("minutes", 60),
("minute", 60),
("mins", 60),
("min", 60),
("seconds", 1),
("second", 1),
("secs", 1),
("sec", 1)])
SpecialYearPrefixesMap = dict([("fiscal", "FY"),
("school", "SY"),
("fy", "FY"),
("sy", "SY")])
SeasonMap = dict([("spring", "SP"),
("summer", "SU"),
("fall", "FA"),
("autumn", "FA"),
("winter", "WI")])
SeasonValueMap = dict([("SP", 3),
("SU", 6),
("FA", 9),
("WI", 12)])
CardinalMap = dict([("first", 1),
("1st", 1),
("second", 2),
("2nd", 2),
("third", 3),
("3rd", 3),
("fourth", 4),
("4th", 4),
("fifth", 5),
("5th", 5)])
DayOfWeek = dict([("monday", 1),
("tuesday", 2),
("wednesday", 3),
("thursday", 4),
("friday", 5),
("saturday", 6),
("sunday", 0),
("mon", 1),
("tue", 2),
("tues", 2),
("wed", 3),
("wedn", 3),
("weds", 3),
("thu", 4),
("thur", 4),
("thurs", 4),
("fri", 5),
("sat", 6),
("sun", 0)])
MonthOfYear = dict([("january", 1),
("february", 2),
("march", 3),
("april", 4),
("may", 5),
("june", 6),
("july", 7),
("august", 8),
("september", 9),
("october", 10),
("november", 11),
("december", 12),
("jan", 1),
("feb", 2),
("mar", 3),
("apr", 4),
("jun", 6),
("jul", 7),
("aug", 8),
("sep", 9),
("sept", 9),
("oct", 10),
("nov", 11),
("dec", 12),
("1", 1),
("2", 2),
("3", 3),
("4", 4),
("5", 5),
("6", 6),
("7", 7),
("8", 8),
("9", 9),
("10", 10),
("11", 11),
("12", 12),
("01", 1),
("02", 2),
("03", 3),
("04", 4),
("05", 5),
("06", 6),
("07", 7),
("08", 8),
("09", 9)])
Numbers = dict([("zero", 0),
("one", 1),
("a", 1),
("an", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
("eleven", 11),
("twelve", 12),
("thirteen", 13),
("fourteen", 14),
("fifteen", 15),
("sixteen", 16),
("seventeen", 17),
("eighteen", 18),
("nineteen", 19),
("twenty", 20),
("twenty one", 21),
("twenty two", 22),
("twenty three", 23),
("twenty four", 24),
("twenty five", 25),
("twenty six", 26),
("twenty seven", 27),
("twenty eight", 28),
("twenty nine", 29),
("thirty", 30),
("thirty one", 31),
("thirty two", 32),
("thirty three", 33),
("thirty four", 34),
("thirty five", 35),
("thirty six", 36),
("thirty seven", 37),
("thirty eight", 38),
("thirty nine", 39),
("forty", 40),
("forty one", 41),
("forty two", 42),
("forty three", 43),
("forty four", 44),
("forty five", 45),
("forty six", 46),
("forty seven", 47),
("forty eight", 48),
("forty nine", 49),
("fifty", 50),
("fifty one", 51),
("fifty two", 52),
("fifty three", 53),
("fifty four", 54),
("fifty five", 55),
("fifty six", 56),
("fifty seven", 57),
("fifty eight", 58),
("fifty nine", 59),
("sixty", 60),
("sixty one", 61),
("sixty two", 62),
("sixty three", 63),
("sixty four", 64),
("sixty five", 65),
("sixty six", 66),
("sixty seven", 67),
("sixty eight", 68),
("sixty nine", 69),
("seventy", 70),
("seventy one", 71),
("seventy two", 72),
("seventy three", 73),
("seventy four", 74),
("seventy five", 75),
("seventy six", 76),
("seventy seven", 77),
("seventy eight", 78),
("seventy nine", 79),
("eighty", 80),
("eighty one", 81),
("eighty two", 82),
("eighty three", 83),
("eighty four", 84),
("eighty five", 85),
("eighty six", 86),
("eighty seven", 87),
("eighty eight", 88),
("eighty nine", 89),
("ninety", 90),
("ninety one", 91),
("ninety two", 92),
("ninety three", 93),
("ninety four", 94),
("ninety five", 95),
("ninety six", 96),
("ninety seven", 97),
("ninety eight", 98),
("ninety nine", 99),
("one hundred", 100)])
DayOfMonth = dict([("1st", 1),
("1th", 1),
("2nd", 2),
("2th", 2),
("3rd", 3),
("3th", 3),
("4th", 4),
("5th", 5),
("6th", 6),
("7th", 7),
("8th", 8),
("9th", 9),
("10th", 10),
("11th", 11),
("11st", 11),
("12th", 12),
("12nd", 12),
("13th", 13),
("13rd", 13),
("14th", 14),
("15th", 15),
("16th", 16),
("17th", 17),
("18th", 18),
("19th", 19),
("20th", 20),
("21st", 21),
("21th", 21),
("22nd", 22),
("22th", 22),
("23rd", 23),
("23th", 23),
("24th", 24),
("25th", 25),
("26th", 26),
("27th", 27),
("28th", 28),
("29th", 29),
("30th", 30),
("31st", 31),
("01st", 1),
("01th", 1),
("02nd", 2),
("02th", 2),
("03rd", 3),
("03th", 3),
("04th", 4),
("05th", 5),
("06th", 6),
("07th", 7),
("08th", 8),
("09th", 9)])
DoubleNumbers = dict([("half", 0.5),
("quarter", 0.25)])
HolidayNames = dict([("easterday", ["easterday", "easter", "eastersunday"]),
("ashwednesday", ["ashwednesday"]),
("palmsunday", ["palmsunday"]),
("maundythursday", ["maundythursday"]),
("goodfriday", ["goodfriday"]),
("eastersaturday", ["eastersaturday"]),
("eastermonday", ["eastermonday"]),
("ascensionday", ["ascensionday"]),
("whitesunday", ["whitesunday", "pentecost", "pentecostday"]),
("whitemonday", ["whitemonday"]),
("trinitysunday", ["trinitysunday"]),
("corpuschristi", ["corpuschristi"]),
("earthday", ["earthday"]),
("fathers", ["fatherday", "fathersday"]),
("mothers", ["motherday", "mothersday"]),
("thanksgiving", ["thanksgivingday", "thanksgiving"]),
("blackfriday", ["blackfriday"]),
("cybermonday", ["cybermonday"]),
("martinlutherking", ["mlkday", "martinlutherkingday", "martinlutherkingjrday"]),
("washingtonsbirthday", ["washingtonsbirthday", "washingtonbirthday", "presidentsday"]),
("canberra", ["canberraday"]),
("labour", ["labourday", "laborday"]),
("columbus", ["columbusday"]),
("memorial", ["memorialday"]),
("yuandan", ["yuandan"]),
("maosbirthday", ["maosbirthday"]),
("teachersday", ["teachersday", "teacherday"]),
("singleday", ["singleday"]),
("allsaintsday", ["allsaintsday"]),
("youthday", ["youthday"]),
("childrenday", ["childrenday", "childday"]),
("femaleday", ["femaleday"]),
("treeplantingday", ["treeplantingday"]),
("arborday", ["arborday"]),
("girlsday", ["girlsday"]),
("whiteloverday", ["whiteloverday"]),
("loverday", ["loverday", "loversday"]),
("christmas", ["christmasday", "christmas"]),
("xmas", ["xmasday", "xmas"]),
("newyear", ["newyear"]),
("newyearday", ["newyearday"]),
("newyearsday", ["newyearsday"]),
("inaugurationday", ["inaugurationday"]),
("groundhougday", ["groundhougday"]),
("valentinesday", ["valentinesday"]),
("stpatrickday", ["stpatrickday", "stpatricksday", "stpatrick"]),
("aprilfools", ["aprilfools"]),
("stgeorgeday", ["stgeorgeday"]),
("mayday", ["mayday", "intlworkersday", "internationalworkersday", "workersday"]),
("cincodemayoday", ["cincodemayoday"]),
("baptisteday", ["baptisteday"]),
("usindependenceday", ["usindependenceday"]),
("independenceday", ["independenceday"]),
("bastilleday", ["bastilleday"]),
("halloweenday", ["halloweenday", "halloween"]),
("allhallowday", ["allhallowday"]),
("allsoulsday", ["allsoulsday"]),
("guyfawkesday", ["guyfawkesday"]),
("veteransday", ["veteransday"]),
("christmaseve", ["christmaseve"]),
("newyeareve", ["newyearseve", "newyeareve"]),
("juneteenth", ["juneteenth", "freedomday", "jubileeday"])])
WrittenDecades = dict([("hundreds", 0),
("tens", 10),
("twenties", 20),
("thirties", 30),
("forties", 40),
("fifties", 50),
("sixties", 60),
("seventies", 70),
("eighties", 80),
("nineties", 90)])
SpecialDecadeCases = dict([("noughties", 2000),
("aughts", 2000),
("two thousands", 2000)])
DefaultLanguageFallback = 'MDY'
SuperfluousWordList = [r'preferably', r'how about', r'maybe', r'perhaps', r'say', r'like']
DurationDateRestrictions = [r'today', r'now']
AmbiguityFiltersDict = dict([("^\\d{4}$", "(\\d\\.\\d{4}|\\d{4}\\.\\d)"),
("^(morning|afternoon|evening|night|day)\\b", "\\b(good\\s+(morning|afternoon|evening|night|day))|(nighty\\s+night)\\b"),
("\\bnow\\b", "\\b(^now,)|\\b((is|are)\\s+now\\s+for|for\\s+now)\\b"),
("\\bmay\\b", "\\b((((!|\\.|\\?|,|;|)\\s+|^)may i)|(i|you|he|she|we|they)\\s+may|(may\\s+((((also|not|(also not)|well)\\s+)?(be|ask|contain|constitute|e-?mail|take|have|result|involve|get|work|reply|differ))|(or may not))))\\b"),
("\\b(a|one) second\\b", "\\b(?<!an?\\s+)(a|one) second (round|time)\\b"),
("\\b(breakfast|brunch|lunch(time)?|dinner(time)?|supper)$", "(?<!\\b(at|before|after|around|circa)\\b\\s)(breakfast|brunch|lunch|dinner|supper)(?!\\s*time)"),
("^\\d+m$", "^\\d+m$"),
("^(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)$", "([$%£&!?@#])(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)|(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)([$%£&@#])")])
MorningTermList = [r'morning']
AfternoonTermList = [r'afternoon']
EveningTermList = [r'evening']
MealtimeBreakfastTermList = [r'breakfast']
MealtimeBrunchTermList = [r'brunch']
MealtimeLunchTermList = [r'lunch', r'lunchtime']
MealtimeDinnerTermList = [r'dinner', r'dinnertime', r'supper']
DaytimeTermList = [r'daytime']
NightTermList = [r'night']
SameDayTerms = [r'today', r'otd']
PlusOneDayTerms = [r'tomorrow', r'tmr', r'day after']
MinusOneDayTerms = [r'yesterday', r'day before']
PlusTwoDayTerms = [r'day after tomorrow', r'day after tmr']
MinusTwoDayTerms = [r'day before yesterday']
FutureTerms = [r'this', r'next']
LastCardinalTerms = [r'last']
MonthTerms = [r'month']
MonthToDateTerms = [r'month to date']
WeekendTerms = [r'weekend']
WeekTerms = [r'week']
FortnightTerms = [r'fortnight', r'fourtenight']
YearTerms = [r'year']
GenericYearTerms = [r'y']
YearToDateTerms = [r'year to date']
DoubleMultiplierRegex = f'^(bi)(-|\\s)?'
HalfMultiplierRegex = f'^(semi)(-|\\s)?'
DayTypeRegex = f'((week)?da(il)?ys?)$'
WeekTypeRegex = f'(week(s|ly)?)$'
WeekendTypeRegex = f'(weekends?)$'
MonthTypeRegex = f'(month(s|ly)?)$'
QuarterTypeRegex = f'(quarter(s|ly)?)$'
YearTypeRegex = f'((years?|annual)(ly)?)$'
# pylint: enable=line-too-long | Python/libraries/recognizers-date-time/recognizers_date_time/resources/english_date_time.py |
from .base_date_time import BaseDateTime
# pylint: disable=line-too-long
class EnglishDateTime:
LangMarker = 'Eng'
CheckBothBeforeAfter = False
TillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})'
RangeConnectorRegex = f'(?<and>\\b(and|through|to)\\b(\\s+the\\b)?|{BaseDateTime.RangeConnectorSymbolRegex})'
LastNegPrefix = f'(?<!(w(ill|ould|on\\s*\'\\s*t)|m(ay|ight|ust)|sh(all|ould(n\\s*\'\\s*t)?)|c(an(\\s*\'\\s*t|not)?|ould(n\\s*\'\\s*t)?))(\\s+not)?\\s+)'
RelativeRegex = f'\\b(?<order>following|next|(up)?coming|this|{LastNegPrefix}last|past|previous|current|the)\\b'
StrictRelativeRegex = f'\\b(?<order>following|next|(up)?coming|this|{LastNegPrefix}last|past|previous|current)\\b'
UpcomingPrefixRegex = f'((this\\s+)?((up)?coming))'
NextPrefixRegex = f'\\b(following|next|{UpcomingPrefixRegex})\\b'
AfterNextSuffixRegex = f'\\b(after\\s+(the\\s+)?next)\\b'
PastPrefixRegex = f'((this\\s+)?past)\\b'
PreviousPrefixRegex = f'({LastNegPrefix}last|previous|{PastPrefixRegex})\\b'
ThisPrefixRegex = f'(this|current)\\b'
RangePrefixRegex = f'(from|between)'
CenturySuffixRegex = f'(^century)\\b'
ReferencePrefixRegex = f'(that|same)\\b'
FutureSuffixRegex = f'\\b(in\\s+the\\s+)?(future|hence)\\b'
DayRegex = f'(the\\s*)?(?<!(\\d+:?|\\$)\\s*)(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?)(?=\\b|t)'
ImplicitDayRegex = f'(the\\s*)?(?<day>(?:3[0-1]|[0-2]?\\d)(?:th|nd|rd|st))\\b'
MonthNumRegex = f'(?<month>1[0-2]|(0)?[1-9])\\b'
WrittenOneToNineRegex = f'(?:one|two|three|four|five|six|seven|eight|nine)'
WrittenElevenToNineteenRegex = f'(?:eleven|twelve|(?:thir|four|fif|six|seven|eigh|nine)teen)'
WrittenTensRegex = f'(?:ten|twenty|thirty|fou?rty|fifty|sixty|seventy|eighty|ninety)'
WrittenNumRegex = f'(?:{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}(\\s+{WrittenOneToNineRegex})?)'
WrittenCenturyFullYearRegex = f'(?:(one|two)\\s+thousand(\\s+and)?(\\s+{WrittenOneToNineRegex}\\s+hundred(\\s+and)?)?)'
WrittenCenturyOrdinalYearRegex = f'(?:twenty(\\s+(one|two))?|ten|eleven|twelve|thirteen|fifteen|eigthteen|(?:four|six|seven|nine)(teen)?|one|two|three|five|eight)'
CenturyRegex = f'\\b(?<century>{WrittenCenturyFullYearRegex}|{WrittenCenturyOrdinalYearRegex}(\\s+hundred)?(\\s+and)?)\\b'
LastTwoYearNumRegex = f'(?:zero\\s+{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}(\\s+{WrittenOneToNineRegex})?)'
FullTextYearRegex = f'\\b((?<firsttwoyearnum>{CenturyRegex})\\s+(?<lasttwoyearnum>{LastTwoYearNumRegex})\\b|\\b(?<firsttwoyearnum>{WrittenCenturyFullYearRegex}|{WrittenCenturyOrdinalYearRegex}\\s+hundred(\\s+and)?))\\b'
OclockRegex = f'(?<oclock>o\\s*((’|‘|\')\\s*)?clock|sharp)'
SpecialDescRegex = f'((?<ipm>)p\\b)'
AmDescRegex = f'(?:{BaseDateTime.BaseAmDescRegex})'
PmDescRegex = f'(:?{BaseDateTime.BasePmDescRegex})'
AmPmDescRegex = f'(:?{BaseDateTime.BaseAmPmDescRegex})'
DescRegex = f'(:?(:?({OclockRegex}\\s+)?(?<desc>({AmPmDescRegex}|{AmDescRegex}|{PmDescRegex}|{SpecialDescRegex})))|{OclockRegex})'
OfPrepositionRegex = f'(\\bof\\b)'
TwoDigitYearRegex = f'\\b(?<![$])(?<year>([0-9]\\d))(?!(\\s*((\\:\\d)|{AmDescRegex}|{PmDescRegex}|\\.\\d)))\\b'
YearRegex = f'(?:{BaseDateTime.FourDigitYearRegex}|{FullTextYearRegex})'
WeekDayRegex = f'\\b(?<weekday>(?:sun|mon|tues?|thurs?|fri)(day)?|thu|wedn(esday)?|weds?|sat(urday)?)s?\\b'
SingleWeekDayRegex = f'\\b(?<weekday>(?<!(easter|palm)\\s+)sunday|(?<!easter\\s+)saturday|(?<!(easter|cyber)\\s+)monday|mon|(?<!black\\s+)friday|fri|(?:tues?|thurs?)(day)?|thu|wedn(esday)?|weds?|((?<=on\\s+)(sat|sun)))\\b'
RelativeMonthRegex = f'(?<relmonth>((day\\s+)?of\\s+)?{RelativeRegex}\\s+month)\\b'
MonthRegex = f'\\b(?<month>apr(il)?|aug(ust)?|dec(ember)?|feb(ruary)?|jan(uary)?|july?|june?|mar(ch)?|may|nov(ember)?|oct(ober)?|sept(ember)?|sep)(?!\\p{{L}})'
WrittenMonthRegex = f'(((the\\s+)?month of\\s+)?{MonthRegex})'
MonthSuffixRegex = f'(?<msuf>(?:(in|of|on)\\s+)?({RelativeMonthRegex}|{WrittenMonthRegex}))'
DateUnitRegex = f'(?<unit>decades?|years?|months?|weeks?|(?<business>(business\\s+|week\\s*))?days?|fortnights?|weekends?|(?<=\\s+\\d{{1,4}})[ymwd])\\b'
DateTokenPrefix = 'on '
TimeTokenPrefix = 'at '
TokenBeforeDate = 'on '
TokenBeforeTime = 'at '
HalfTokenRegex = f'^(half)'
QuarterTokenRegex = f'^((a\\s+)?quarter)'
ThreeQuarterTokenRegex = f'^(three\\s+quarters?)'
ToTokenRegex = f'\\b(to)$'
FromRegex = f'\\b(from(\\s+the)?)$'
BetweenTokenRegex = f'\\b(between(\\s+the)?)$'
SimpleCasesRegex = f'\\b({RangePrefixRegex}\\s+)?({DayRegex})\\s*{TillRegex}\\s*({DayRegex}\\s+{MonthSuffixRegex}|{MonthSuffixRegex}\\s+{DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthFrontSimpleCasesRegex = f'\\b({RangePrefixRegex}\\s+)?{MonthSuffixRegex}\\s+((from)\\s+)?({DayRegex})\\s*{TillRegex}\\s*({DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthFrontBetweenRegex = f'\\b{MonthSuffixRegex}\\s+(between\\s+)({DayRegex})\\s*{RangeConnectorRegex}\\s*({DayRegex})((\\s+|\\s*,\\s*){YearRegex})?\\b'
BetweenRegex = f'\\b(between\\s+)({DayRegex})\\s*{RangeConnectorRegex}\\s*({DayRegex})\\s+{MonthSuffixRegex}((\\s+|\\s*,\\s*){YearRegex})?\\b'
MonthWithYear = f'\\b(({WrittenMonthRegex}[\\.]?(\\s*)[/\\\\\\-\\.,]?(\\s+(of|in))?(\\s*)({YearRegex}|(?<order>following|next|last|this)\\s+year))|(({YearRegex}|(?<order>following|next|last|this)\\s+year)(\\s*),?(\\s*){WrittenMonthRegex}))\\b'
SpecialYearPrefixes = f'(calendar|(?<special>fiscal|school))'
OneWordPeriodRegex = f'\\b((((the\\s+)?month of\\s+)?({StrictRelativeRegex}\\s+)?{MonthRegex})|(month|year) to date|(?<toDate>((un)?till?|to)\\s+date)|({RelativeRegex}\\s+)?(my\\s+)?((?<business>working\\s+week|workweek)|week(end)?|month|fortnight|(({SpecialYearPrefixes}\\s+)?year))(?!((\\s+of)?\\s+\\d+(?!({BaseDateTime.BaseAmDescRegex}|{BaseDateTime.BasePmDescRegex}))|\\s+to\\s+date))(\\s+{AfterNextSuffixRegex})?)\\b'
MonthNumWithYear = f'\\b(({BaseDateTime.FourDigitYearRegex}(\\s*)[/\\-\\.](\\s*){MonthNumRegex})|({MonthNumRegex}(\\s*)[/\\-](\\s*){BaseDateTime.FourDigitYearRegex}))\\b'
WeekOfMonthRegex = f'\\b(?<wom>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+week\\s+{MonthSuffixRegex}(\\s+{BaseDateTime.FourDigitYearRegex}|{RelativeRegex}\\s+year)?)\\b'
WeekOfYearRegex = f'\\b(?<woy>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+week(\\s+of)?\\s+({YearRegex}|{RelativeRegex}\\s+year))\\b'
FollowedDateUnit = f'^\\s*{DateUnitRegex}'
NumberCombinedWithDateUnit = f'\\b(?<num>\\d+(\\.\\d*)?){DateUnitRegex}'
QuarterTermRegex = f'\\b(((?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th)[ -]+quarter)|(q(?<number>[1-4])))\\b'
RelativeQuarterTermRegex = f'\\b(?<orderQuarter>{StrictRelativeRegex})\\s+quarter\\b'
QuarterRegex = f'((the\\s+)?{QuarterTermRegex}(?:((\\s+of)?\\s+|\\s*[,-]\\s*)({YearRegex}|{RelativeRegex}\\s+year))?)|{RelativeQuarterTermRegex}'
QuarterRegexYearFront = f'(?:{YearRegex}|{RelativeRegex}\\s+year)(\'s)?(?:\\s*-\\s*|\\s+(the\\s+)?)?{QuarterTermRegex}'
HalfYearTermRegex = f'(?<cardinal>first|1st|second|2nd)\\s+half'
HalfYearFrontRegex = f'(?<year>((1[5-9]|20)\\d{{2}})|2100)(\\s*-\\s*|\\s+(the\\s+)?)?h(?<number>[1-2])'
HalfYearBackRegex = f'(the\\s+)?(h(?<number>[1-2])|({HalfYearTermRegex}))(\\s+of|\\s*,\\s*)?\\s+({YearRegex})'
HalfYearRelativeRegex = f'(the\\s+)?{HalfYearTermRegex}(\\s+of|\\s*,\\s*)?\\s+({RelativeRegex}\\s+year)'
AllHalfYearRegex = f'({HalfYearFrontRegex})|({HalfYearBackRegex})|({HalfYearRelativeRegex})'
EarlyPrefixRegex = f'\\b(?<EarlyPrefix>early|beginning of|start of|(?<RelEarly>earlier(\\s+in)?))\\b'
MidPrefixRegex = f'\\b(?<MidPrefix>mid-?|middle of)\\b'
LaterPrefixRegex = f'\\b(?<LatePrefix>late|end of|(?<RelLate>later(\\s+in)?))\\b'
PrefixPeriodRegex = f'({EarlyPrefixRegex}|{MidPrefixRegex}|{LaterPrefixRegex})'
PrefixDayRegex = f'\\b((?<EarlyPrefix>earl(y|ier))|(?<MidPrefix>mid(dle)?)|(?<LatePrefix>later?))(\\s+in)?(\\s+the\\s+day)?$'
SeasonDescRegex = f'(?<seas>spring|summer|fall|autumn|winter)'
SeasonRegex = f'\\b(?<season>({PrefixPeriodRegex}\\s+)?({RelativeRegex}\\s+)?{SeasonDescRegex}((\\s+of|\\s*,\\s*)?\\s+({YearRegex}|{RelativeRegex}\\s+year))?)\\b'
WhichWeekRegex = f'\\b(week)(\\s*)(?<number>5[0-3]|[1-4]\\d|0?[1-9])\\b'
WeekOfRegex = f'(the\\s+)?((week)(\\s+(of|(commencing|starting|beginning)(\\s+on)?))|w/c)(\\s+the)?'
MonthOfRegex = f'(month)(\\s*)(of)'
DateYearRegex = f'(?<year>{BaseDateTime.FourDigitYearRegex}|(?<!,\\s?){TwoDigitYearRegex}|{TwoDigitYearRegex}(?=(\\.(?!\\d)|[?!;]|$)))'
YearSuffix = f'((,|\\sof)?\\s*({DateYearRegex}|{FullTextYearRegex}))'
OnRegex = f'(?<=\\bon\\s+)({DayRegex}s?)\\b'
RelaxedOnRegex = f'(?<=\\b(on|at|in)\\s+)((?<day>(3[0-1]|[0-2]?\\d)(?:th|nd|rd|st))s?)\\b'
PrefixWeekDayRegex = f'(\\s*((,?\\s*on)|[-—–]))'
ThisRegex = f'\\b(this(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|({WeekDayRegex}((\\s+of)?\\s+this\\s*week))\\b'
LastDateRegex = f'\\b({PreviousPrefixRegex}(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|({WeekDayRegex}(\\s+(of\\s+)?last\\s*week))\\b'
NextDateRegex = f'\\b({NextPrefixRegex}(\\s*week{PrefixWeekDayRegex}?)?\\s*{WeekDayRegex})|((on\\s+)?{WeekDayRegex}((\\s+of)?\\s+(the\\s+following|(the\\s+)?next)\\s*week))\\b'
SpecialDayRegex = f'\\b((the\\s+)?day before yesterday|(the\\s+)?day after (tomorrow|tmr)|the\\s+day\\s+(before|after)(?!=\\s+day)|((the\\s+)?({RelativeRegex}|my)\\s+day)|yesterday|tomorrow|tmr|today|otd)\\b'
SpecialDayWithNumRegex = f'\\b((?<number>{WrittenNumRegex})\\s+days?\\s+from\\s+(?<day>yesterday|tomorrow|tmr|today))\\b'
RelativeDayRegex = f'\\b(((the\\s+)?{RelativeRegex}\\s+day))\\b'
SetWeekDayRegex = f'\\b(?<prefix>on\\s+)?(?<weekday>morning|afternoon|evening|night|(sun|mon|tues|wednes|thurs|fri|satur)day)s\\b'
WeekDayOfMonthRegex = f'(?<wom>(the\\s+)?(?<cardinal>first|1st|second|2nd|third|3rd|fourth|4th|fifth|5th|last)\\s+(week\\s+{MonthSuffixRegex}[\\.]?\\s+(on\\s+)?{WeekDayRegex}|{WeekDayRegex}\\s+{MonthSuffixRegex}))'
RelativeWeekDayRegex = f'\\b({WrittenNumRegex}\\s+{WeekDayRegex}\\s+(from\\s+now|later))\\b'
SpecialDate = f'(?=\\b(on|at)\\s+the\\s+){DayRegex}\\b'
DatePreposition = f'\\b(on|in)'
DateExtractorYearTermRegex = f'(\\s+|\\s*[/\\\\.,-]\\s*|\\s+of\\s+){DateYearRegex}'
DayPrefix = f'\\b({WeekDayRegex}|{SpecialDayRegex})\\b'
DateExtractor1 = f'\\b({DayPrefix}\\s*[,-]?\\s*)?(({MonthRegex}[\\.]?\\s*[/\\\\.,-]?\\s*{DayRegex})|(\\({MonthRegex}\\s*[-./]\\s*{DayRegex}\\)))(\\s*\\(\\s*{DayPrefix}\\s*\\))?({DateExtractorYearTermRegex}\\b)?'
DateExtractor3 = f'\\b({DayPrefix}(\\s+|\\s*,\\s*))?({DayRegex}[\\.]?(\\s+|\\s*[-,/]\\s*|\\s+of\\s+){MonthRegex}[\\.]?((\\s+in)?{DateExtractorYearTermRegex})?|{BaseDateTime.FourDigitYearRegex}\\s*[-./]?\\s*(the\\s+)?(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?)[\\.]?(\\s+|\\s*[-,/]\\s*|\\s+of\\s+){MonthRegex}[\\.]?)\\b'
DateExtractor4 = f'\\b{MonthNumRegex}\\s*[/\\\\\\-]\\s*{DayRegex}[\\.]?\\s*[/\\\\\\-]\\s*{DateYearRegex}'
DateExtractor5 = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*[/\\\\\\-\\.]\\s*({MonthNumRegex}|{MonthRegex})\\s*[/\\\\\\-\\.]\\s*{DateYearRegex}(?!\\s*[/\\\\\\-\\.]\\s*\\d+)'
DateExtractor6 = f'(?<={DatePreposition}\\s+)({StrictRelativeRegex}\\s+)?({DayPrefix}\\s+)?{MonthNumRegex}[\\-\\.]{DayRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor7L = f'\\b({DayPrefix}(\\s*,)?\\s+)?{MonthNumRegex}\\s*/\\s*{DayRegex}{DateExtractorYearTermRegex}(?![%])\\b'
DateExtractor7S = f'\\b({DayPrefix}(\\s*,)?\\s+)?{MonthNumRegex}\\s*/\\s*{DayRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor8 = f'(?<={DatePreposition}\\s+)({StrictRelativeRegex}\\s+)?({DayPrefix}\\s+)?{DayRegex}[\\\\\\-]{MonthNumRegex}(?![%]){BaseDateTime.CheckDecimalRegex}\\b'
DateExtractor9L = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*/\\s*{MonthNumRegex}{DateExtractorYearTermRegex}(?![%])\\b'
DateExtractor9S = f'\\b({DayPrefix}(\\s*,)?\\s+)?{DayRegex}\\s*/\\s*{MonthNumRegex}{BaseDateTime.CheckDecimalRegex}(?![%])\\b'
DateExtractorA = f'\\b({DayPrefix}(\\s*,)?\\s+)?(({BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*({MonthNumRegex}|{MonthRegex})\\s*[/\\\\\\-\\.]\\s*{DayRegex})|({MonthRegex}\\s*[/\\\\\\-\\.]\\s*{BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*(the\\s+)?(?<day>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:th|nd|rd|st)?))|({DayRegex}\\s*[/\\\\\\-\\.]\\s*{BaseDateTime.FourDigitYearRegex}\\s*[/\\\\\\-\\.]\\s*{MonthRegex}))'
OfMonth = f'^\\s*(day\\s+)?of\\s*{MonthRegex}'
MonthEnd = f'{MonthRegex}\\s*(the)?\\s*$'
WeekDayEnd = f'(this\\s+)?{WeekDayRegex}\\s*,?\\s*$'
WeekDayStart = f'^[\\.]'
RangeUnitRegex = f'\\b(?<unit>years?|months?|weeks?|fortnights?)\\b'
HourNumRegex = f'\\b(?<hournum>zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\\b'
MinuteNumRegex = f'(((?<tens>twenty|thirty|fou?rty|fifty)(\\s*-?\\s*))?(?<minnum>one|two|three|four|five|six|seven|eight|nine)|(?<minnum>ten|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)|twenty|thirty|forty|fifty))'
DeltaMinuteNumRegex = f'(((?<tens>twenty|thirty|fou?rty|fifty)(\\s*-?\\s*))?(?<deltaminnum>one|two|three|four|five|six|seven|eight|nine)|(?<deltaminnum>ten|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)|twenty|thirty|forty|fifty))'
PmRegex = f'(?<pm>(((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(afternoon|evening|midnight|lunchtime))|((at|in|around|on|for)\\s+(the\\s+)?night))'
PmRegexFull = f'(?<pm>((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(afternoon|evening|(mid)?night|lunchtime))'
AmRegex = f'(?<am>((?:at|in|around|circa|on|for)\\s+(the\\s+)?)?(morning))'
LunchRegex = f'\\blunchtime\\b'
NightRegex = f'\\b(mid)?night\\b'
CommonDatePrefixRegex = f'^[\\.]'
LessThanOneHour = f'(?<lth>(a\\s+)?quarter|three quarter(s)?|half( an hour)?|{BaseDateTime.DeltaMinuteRegex}(\\s+(minutes?|mins?))|{DeltaMinuteNumRegex}(\\s+(minutes?|mins?)))'
WrittenTimeRegex = f'(?<writtentime>{HourNumRegex}\\s+{MinuteNumRegex}(\\s+(minutes?|mins?))?)'
TimePrefix = f'(?<prefix>{LessThanOneHour}\\s+(past|to))'
TimeSuffix = f'(?<suffix>{AmRegex}|{PmRegex}|{OclockRegex})'
TimeSuffixFull = f'(?<suffix>{AmRegex}|{PmRegexFull}|{OclockRegex})'
BasicTime = f'\\b(?<basictime>{WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}:{BaseDateTime.MinuteRegex}(:{BaseDateTime.SecondRegex})?|{BaseDateTime.HourRegex}(?![%\\d]))'
MidnightRegex = f'(?<midnight>mid\\s*(-\\s*)?night)'
MidmorningRegex = f'(?<midmorning>mid\\s*(-\\s*)?morning)'
MidafternoonRegex = f'(?<midafternoon>mid\\s*(-\\s*)?afternoon)'
MiddayRegex = f'(?<midday>mid\\s*(-\\s*)?day|((12\\s)?noon))'
MidTimeRegex = f'(?<mid>({MidnightRegex}|{MidmorningRegex}|{MidafternoonRegex}|{MiddayRegex}))'
AtRegex = f'\\b(?:(?:(?<=\\b(at|(at)?\\s*around|circa)\\s+)(?:{WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}(?!\\.\\d)(\\s*((?<iam>a)|(?<ipm>p)))?|{MidTimeRegex}))|{MidTimeRegex})\\b'
IshRegex = f'\\b({BaseDateTime.HourRegex}(-|——)?ish|noon(ish)?)\\b'
TimeUnitRegex = f'([^a-z]{{1,}}|\\b)(?<unit>h(ou)?rs?|h|min(ute)?s?|sec(ond)?s?)\\b'
RestrictedTimeUnitRegex = f'(?<unit>hour|minute)\\b'
FivesRegex = f'(?<tens>(?:fifteen|(?:twen|thir|fou?r|fif)ty(\\s*five)?|ten|five))\\b'
HourRegex = f'\\b{BaseDateTime.HourRegex}'
PeriodHourNumRegex = f'\\b(?<hour>twenty(\\s+(one|two|three|four))?|eleven|twelve|thirteen|fifteen|eighteen|(four|six|seven|nine)(teen)?|zero|one|two|three|five|eight|ten)\\b'
ConnectNumRegex = f'\\b{BaseDateTime.HourRegex}(?<min>[0-5][0-9])\\s*{DescRegex}'
TimeRegexWithDotConnector = f'({BaseDateTime.HourRegex}(\\s*\\.\\s*){BaseDateTime.MinuteRegex})'
TimeRegex1 = f'\\b({TimePrefix}\\s+)?({WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex})(\\s*|[.]){DescRegex}'
TimeRegex2 = f'(\\b{TimePrefix}\\s+)?(t)?{BaseDateTime.HourRegex}(\\s*)?:(\\s*)?{BaseDateTime.MinuteRegex}((\\s*)?:(\\s*)?{BaseDateTime.SecondRegex})?(?<iam>a)?((\\s*{DescRegex})|\\b)'
TimeRegex3 = f'(\\b{TimePrefix}\\s+)?{BaseDateTime.HourRegex}\\.{BaseDateTime.MinuteRegex}(\\s*{DescRegex})'
TimeRegex4 = f'\\b{TimePrefix}\\s+{BasicTime}(\\s*{DescRegex})?\\s+{TimeSuffix}\\b'
TimeRegex5 = f'\\b{TimePrefix}\\s+{BasicTime}((\\s*{DescRegex})|\\b)'
TimeRegex6 = f'({BasicTime})(\\s*{DescRegex})?\\s+{TimeSuffix}\\b'
TimeRegex7 = f'\\b{TimeSuffixFull}\\s+(at\\s+)?{BasicTime}((\\s*{DescRegex})|\\b)'
TimeRegex8 = f'.^'
TimeRegex9 = f'\\b{PeriodHourNumRegex}(\\s+|-){FivesRegex}((\\s*{DescRegex})|\\b)'
TimeRegex10 = f'\\b({TimePrefix}\\s+)?{BaseDateTime.HourRegex}(\\s*h\\s*){BaseDateTime.MinuteRegex}(\\s*{DescRegex})?'
TimeRegex11 = f'\\b((?:({TimeTokenPrefix})?{TimeRegexWithDotConnector}(\\s*{DescRegex}))|(?:(?:{TimeTokenPrefix}{TimeRegexWithDotConnector})(?!\\s*per\\s*cent|%)))'
FirstTimeRegexInTimeRange = f'\\b{TimeRegexWithDotConnector}(\\s*{DescRegex})?'
PureNumFromTo = f'({RangePrefixRegex}\\s+)?({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?\\s*{TillRegex}\\s*({HourRegex}|{PeriodHourNumRegex})(?<rightDesc>\\s*({PmRegex}|{AmRegex}|{DescRegex}))?'
PureNumBetweenAnd = f'(between\\s+)(({BaseDateTime.TwoDigitHourRegex}{BaseDateTime.TwoDigitMinuteRegex})|{HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?\\s*{RangeConnectorRegex}\\s*(({BaseDateTime.TwoDigitHourRegex}{BaseDateTime.TwoDigitMinuteRegex})|{HourRegex}|{PeriodHourNumRegex})(?<rightDesc>\\s*({PmRegex}|{AmRegex}|{DescRegex}))?'
SpecificTimeFromTo = f'({RangePrefixRegex}\\s+)?(?<time1>(({TimeRegex2}|{FirstTimeRegexInTimeRange})|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?))\\s*{TillRegex}\\s*(?<time2>(({TimeRegex2}|{TimeRegexWithDotConnector}(?<rightDesc>\\s*{DescRegex}))|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<rightDesc>{DescRegex}))?))'
SpecificTimeBetweenAnd = f'(between\\s+)(?<time1>(({TimeRegex2}|{FirstTimeRegexInTimeRange})|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<leftDesc>{DescRegex}))?))\\s*{RangeConnectorRegex}\\s*(?<time2>(({TimeRegex2}|{TimeRegexWithDotConnector}(?<rightDesc>\\s*{DescRegex}))|({HourRegex}|{PeriodHourNumRegex})(\\s*(?<rightDesc>{DescRegex}))?))'
SuffixAfterRegex = f'\\b(((at)\\s)?(or|and)\\s+(above|after|later|greater)(?!\\s+than))\\b'
PrepositionRegex = f'(?<prep>^(,\\s*)?(at|on|of)(\\s+the)?$)'
LaterEarlyRegex = f'((?<early>earl(y|ier)(\\s+|-))|(?<late>late(r?\\s+|-)))'
MealTimeRegex = f'\\b(at\\s+)?(?<mealTime>breakfast|brunch|lunch(\\s*time)?|dinner(\\s*time)?|supper)\\b'
UnspecificTimePeriodRegex = f'({MealTimeRegex})'
TimeOfDayRegex = f'\\b(?<timeOfDay>((((in\\s+the\\s+)?{LaterEarlyRegex}?(in(\\s+the)?\\s+)?(morning|afternoon|night|evening)))|{MealTimeRegex}|(((in\\s+(the)?\\s+)?)(daytime|business\\s+hour)))s?)\\b'
SpecificTimeOfDayRegex = f'\\b(({StrictRelativeRegex}\\s+{TimeOfDayRegex})\\b|\\btoni(ght|te))s?\\b'
TimeFollowedUnit = f'^\\s*{TimeUnitRegex}'
TimeNumberCombinedWithUnit = f'\\b(?<num>\\d+(\\.\\d*)?){TimeUnitRegex}'
BusinessHourSplitStrings = [r'business', r'hour']
NowRegex = f'\\b(?<now>(right\\s+)?now|as\\s+soon\\s+as\\s+possible|asap|recently|previously|at\\s+(present|this\\s+time|th(e|is)\\s+minute|the\\s+(moment|present\\s+time)))\\b'
NowParseRegex = f'\\b({NowRegex}|^(date)$)\\b'
SuffixRegex = f'^\\s*(in the\\s+)?(morning|afternoon|evening|night)\\b'
NonTimeContextTokens = f'(building)'
DateTimeTimeOfDayRegex = f'\\b(?<timeOfDay>morning|(?<pm>afternoon|night|evening))\\b'
DateTimeSpecificTimeOfDayRegex = f'\\b(({RelativeRegex}\\s+{DateTimeTimeOfDayRegex})\\b|\\btoni(ght|te))\\b'
TimeOfTodayAfterRegex = f'^\\s*(,\\s*)?(in\\s+)?{DateTimeSpecificTimeOfDayRegex}'
TimeOfTodayBeforeRegex = f'{DateTimeSpecificTimeOfDayRegex}(\\s*,)?(\\s+(at|around|circa|in|on))?\\s*$'
SimpleTimeOfTodayAfterRegex = f'(?<!{NonTimeContextTokens}\\s*)\\b({HourNumRegex}|{BaseDateTime.HourRegex})\\s*(,\\s*)?(in\\s+)?{DateTimeSpecificTimeOfDayRegex}\\b'
SimpleTimeOfTodayBeforeRegex = f'\\b{DateTimeSpecificTimeOfDayRegex}(\\s*,)?(\\s+(at|around|circa))?\\s*({HourNumRegex}|{BaseDateTime.HourRegex})\\b'
SpecificEndOfRegex = f'(the\\s+)?end of(\\s+the)?\\s*$'
UnspecificEndOfRegex = f'\\b(the\\s+)?(eod|(end\\s+of\\s+day))\\b'
UnspecificEndOfRangeRegex = f'\\b(eoy)\\b'
PeriodTimeOfDayRegex = f'\\b((in\\s+(the)?\\s+)?{LaterEarlyRegex}?(this\\s+)?{DateTimeTimeOfDayRegex})\\b'
PeriodSpecificTimeOfDayRegex = f'\\b({LaterEarlyRegex}?this\\s+{DateTimeTimeOfDayRegex}|({StrictRelativeRegex}\\s+{PeriodTimeOfDayRegex})\\b|\\btoni(ght|te))\\b'
PeriodTimeOfDayWithDateRegex = f'\\b(({PeriodTimeOfDayRegex}(\\s+(on|of))?))\\b'
LessThanRegex = f'\\b(less\\s+than)\\b'
MoreThanRegex = f'\\b(more\\s+than)\\b'
DurationUnitRegex = f'(?<unit>{DateUnitRegex}|h(ou)?rs?|h|min(ute)?s?|sec(ond)?s?|nights?)\\b'
SuffixAndRegex = f'(?<suffix>\\s*(and)\\s+(an?\\s+)?(?<suffix_num>half|quarter))'
PeriodicRegex = f'\\b(?<periodic>((?<multiplier>semi|bi|tri)(\\s*|-))?(daily|monthly|weekly|quarterly|yearly|annual(ly)?))\\b'
EachUnitRegex = f'\\b(?<each>(each|every|any|once an?)(?<other>\\s+other)?\\s+({DurationUnitRegex}|(?<specialUnit>quarters?|weekends?)|{WeekDayRegex})|(?<specialUnit>weekends))'
EachPrefixRegex = f'\\b(?<each>(each|every|once an?)\\s*$)'
SetEachRegex = f'\\b(?<each>(each|every)(?<other>\\s+other)?\\s*)(?!the|that)\\b'
SetLastRegex = f'(?<last>following|next|upcoming|this|{LastNegPrefix}last|past|previous|current)'
EachDayRegex = f'^\\s*(each|every)\\s*day\\b'
DurationFollowedUnit = f'(^\\s*{DurationUnitRegex}\\s+{SuffixAndRegex})|(^\\s*{SuffixAndRegex}?(\\s+|-)?{DurationUnitRegex})'
NumberCombinedWithDurationUnit = f'\\b(?<num>\\d+(\\.\\d*)?)(-)?{DurationUnitRegex}'
AnUnitRegex = f'(\\b((?<half>(half)\\s+)?an?|another)|(?<half>(1/2|½|half)))\\s+{DurationUnitRegex}'
DuringRegex = f'\\b(for|during)\\s+the\\s+(?<unit>year|month|week|day|fortnight)\\b'
AllRegex = f'\\b(?<all>(all|full|whole)(\\s+|-)(?<unit>year|month|week|day|fortnight))\\b'
HalfRegex = f'((an?\\s*)|\\b)(?<half>half\\s+(?<unit>year|month|week|fortnight|day|hour))\\b'
ConjunctionRegex = f'\\b((and(\\s+for)?)|with)\\b'
HolidayList1 = f'(?<holiday>mardi gras|(washington|mao)\'s birthday|juneteenth|(jubilee|freedom)(\\s+day)|chinese new year|(new\\s+(years\'|year\\s*\'s|years?)\\s+eve)|(new\\s+(years\'|year\\s*\'s|years?)(\\s+day)?)|may\\s*day|yuan dan|christmas eve|(christmas|xmas)(\\s+day)?|black friday|yuandan|easter(\\s+(sunday|saturday|monday))?|clean monday|ash wednesday|palm sunday|maundy thursday|good friday|white\\s+(sunday|monday)|trinity sunday|pentecost|corpus christi|cyber monday)'
HolidayList2 = f'(?<holiday>(thanks\\s*giving|all saint\'s|white lover|s(?:ain)?t?(\\.)?\\s+(?:patrick|george)(?:\')?(?:s)?|us independence|all hallow|all souls|guy fawkes|cinco de mayo|halloween|qingming|dragon boat|april fools|tomb\\s*sweeping)(\\s+day)?)'
HolidayList3 = f'(?<holiday>(?:independence|presidents(?:\')?|mlk|martin luther king( jr)?|canberra|ascension|columbus|tree( planting)?|arbor|labou?r|((international|int\'?l)\\s+)?workers\'?|mother\'?s?|father\'?s?|female|women(\'s)?|single|teacher\'?s|youth|children|girls|lovers?|earth|inauguration|groundhog|valentine\'?s|baptiste|bastille|veterans(?:\')?|memorial|mid[ \\-]autumn|moon|spring|lantern)\\s+day)'
HolidayRegex = f'\\b(({StrictRelativeRegex}\\s+({HolidayList1}|{HolidayList2}|{HolidayList3}))|(({HolidayList1}|{HolidayList2}|{HolidayList3})(\\s+(of\\s+)?({YearRegex}|{RelativeRegex}\\s+year))?))\\b'
AMTimeRegex = f'(?<am>morning)'
PMTimeRegex = f'\\b(?<pm>afternoon|evening|night)\\b'
NightTimeRegex = f'(night)'
NowTimeRegex = f'(now|at\\s+(present|this\\s+time|th(e|is)\\s+minute|the\\s+(moment|present\\s+time)))'
RecentlyTimeRegex = f'(recently|previously)'
AsapTimeRegex = f'(as soon as possible|asap)'
InclusiveModPrepositions = f'(?<include>((on|in|at)\\s+or\\s+)|(\\s+or\\s+(on|in|at)))'
AroundRegex = f'(?:\\b(?:around|circa)\\s*?\\b)(\\s+the)?'
BeforeRegex = f'((\\b{InclusiveModPrepositions}?(?:before|in\\s+advance\\s+of|prior\\s+to|(no\\s+later|earlier|sooner)\\s+than|ending\\s+(with|on)|by|(un)?till?|(?<include>as\\s+late\\s+as)){InclusiveModPrepositions}?\\b\\s*?)|(?<!\\w|>)((?<include><\\s*=)|<))(\\s+the)?'
AfterRegex = f'((\\b{InclusiveModPrepositions}?((after|(starting|beginning)(\\s+on)?(?!\\sfrom)|(?<!no\\s+)later than)|(year greater than))(?!\\s+or equal to){InclusiveModPrepositions}?\\b\\s*?)|(?<!\\w|<)((?<include>>\\s*=)|>))(\\s+the)?'
SinceRegex = f'(?:(?:\\b(?:since|after\\s+or\\s+equal\\s+to|starting\\s+(?:from|on|with)|as\\s+early\\s+as|(any\\s+time\\s+)from)\\b\\s*?)|(?<!\\w|<)(>=))(\\s+the)?'
SinceRegexExp = f'({SinceRegex}|\\bfrom(\\s+the)?\\b)'
AgoRegex = f'\\b(ago|before\\s+(?<day>yesterday|today))\\b'
LaterRegex = f'\\b(?:later(?!((\\s+in)?\\s*{OneWordPeriodRegex})|(\\s+{TimeOfDayRegex})|\\s+than\\b)|from now|(from|after)\\s+(?<day>tomorrow|tmr|today))\\b'
BeforeAfterRegex = f'\\b((?<before>before)|(?<after>from|after))\\b'
InConnectorRegex = f'\\b(in)\\b'
SinceYearSuffixRegex = f'(^\\s*{SinceRegex}(\\s*(the\\s+)?year\\s*)?{YearSuffix})'
WithinNextPrefixRegex = f'\\b(within(\\s+the)?(\\s+(?<next>{NextPrefixRegex}))?)\\b'
TodayNowRegex = f'\\b(today|now)\\b'
MorningStartEndRegex = f'(^(morning|{AmDescRegex}))|((morning|{AmDescRegex})$)'
AfternoonStartEndRegex = f'(^(afternoon|{PmDescRegex}))|((afternoon|{PmDescRegex})$)'
EveningStartEndRegex = f'(^(evening))|((evening)$)'
NightStartEndRegex = f'(^(over|to)?ni(ght|te))|((over|to)?ni(ght|te)$)'
InexactNumberRegex = f'\\b((a\\s+)?few|some|several|(?<NumTwoTerm>(a\\s+)?couple(\\s+of)?))\\b'
InexactNumberUnitRegex = f'({InexactNumberRegex})\\s+({DurationUnitRegex})'
RelativeTimeUnitRegex = f'(?:(?:(?:{NextPrefixRegex}|{PreviousPrefixRegex}|{ThisPrefixRegex})\\s+({TimeUnitRegex}))|((the|my))\\s+({RestrictedTimeUnitRegex}))'
RelativeDurationUnitRegex = f'(?:(?:(?<=({NextPrefixRegex}|{PreviousPrefixRegex}|{ThisPrefixRegex})\\s+)({DurationUnitRegex}))|((the|my))\\s+({RestrictedTimeUnitRegex}))'
ReferenceDatePeriodRegex = f'\\b{ReferencePrefixRegex}\\s+(?<duration>week(end)?|fortnight|month|year|decade)\\b'
ConnectorRegex = f'^(-|,|for|t|around|circa|@)$'
FromToRegex = f'(\\b(from).+(to|and|or)\\b.+)'
SingleAmbiguousMonthRegex = f'^(the\\s+)?(may|march)$'
SingleAmbiguousTermsRegex = f'^(the\\s+)?(day|week|month|year)$'
UnspecificDatePeriodRegex = f'^(week|fortnight|month|year)$'
PrepositionSuffixRegex = f'\\b(on|in|at|around|circa|from|to)$'
FlexibleDayRegex = f'(?<DayOfMonth>([A-Za-z]+\\s)?[A-Za-z\\d]+)'
ForTheRegex = f'\\b((((?<=for\\s+)the\\s+{FlexibleDayRegex})|((?<=on\\s+)(the\\s+)?{FlexibleDayRegex}(?<=(st|nd|rd|th))))(?<end>\\s*(,|\\.(?!\\d)|!|\\?|$)))'
WeekDayAndDayOfMonthRegex = f'\\b{WeekDayRegex}\\s+(the\\s+{FlexibleDayRegex})\\b'
WeekDayAndDayRegex = f'\\b{WeekDayRegex}\\s+(?!(the)){DayRegex}(?!([-:]|(\\s+({AmDescRegex}|{PmDescRegex}|{OclockRegex}))))\\b'
RestOfDateRegex = f'\\b(rest|remaining)\\s+(of\\s+)?((the|my|this|current)\\s+)?(?<duration>week|fortnight|month|year|decade)\\b'
RestOfDateTimeRegex = f'\\b(rest|remaining)\\s+(of\\s+)?((the|my|this|current)\\s+)?(?<unit>day)\\b'
AmbiguousRangeModifierPrefix = f'(from)'
NumberEndingPattern = f'^(?:\\s+(?<meeting>meeting|appointment|conference|((skype|teams|zoom|facetime)\\s+)?call)\\s+to\\s+(?<newTime>{PeriodHourNumRegex}|{HourRegex})([\\.]?$|(\\.,|,|!|\\?)))'
OneOnOneRegex = f'\\b(1\\s*:\\s*1(?!\\d))|(one (on )?one|one\\s*-\\s*one|one\\s*:\\s*one)\\b'
LaterEarlyPeriodRegex = f'\\b(({PrefixPeriodRegex})\\s*\\b\\s*(?<suffix>{OneWordPeriodRegex}|(?<FourDigitYear>{BaseDateTime.FourDigitYearRegex}))|({UnspecificEndOfRangeRegex}))\\b'
WeekWithWeekDayRangeRegex = f'\\b((?<week>({NextPrefixRegex}|{PreviousPrefixRegex}|this)\\s+week)((\\s+between\\s+{WeekDayRegex}\\s+and\\s+{WeekDayRegex})|(\\s+from\\s+{WeekDayRegex}\\s+to\\s+{WeekDayRegex})))\\b'
GeneralEndingRegex = f'^\\s*((\\.,)|\\.|,|!|\\?)?\\s*$'
MiddlePauseRegex = f'\\s*(,)\\s*'
DurationConnectorRegex = f'^\\s*(?<connector>\\s+|and|,)\\s*$'
PrefixArticleRegex = f'\\bthe\\s+'
OrRegex = f'\\s*((\\b|,\\s*)(or|and)\\b|,)\\s*'
SpecialYearTermsRegex = f'\\b((({SpecialYearPrefixes}\\s+)?year)|(cy|(?<special>fy|sy)))'
YearPlusNumberRegex = f'\\b({SpecialYearTermsRegex}\\s*((?<year>(\\d{{2,4}}))|{FullTextYearRegex}))\\b'
NumberAsTimeRegex = f'\\b({WrittenTimeRegex}|{PeriodHourNumRegex}|{BaseDateTime.HourRegex})\\b'
TimeBeforeAfterRegex = f'\\b(((?<=\\b(before|no later than|by|after)\\s+)({WrittenTimeRegex}|{HourNumRegex}|{BaseDateTime.HourRegex}|{MidTimeRegex}))|{MidTimeRegex})\\b'
DateNumberConnectorRegex = f'^\\s*(?<connector>\\s+at)\\s*$'
DecadeRegex = f'(?<decade>(?:nough|twen|thir|fou?r|fif|six|seven|eigh|nine)ties|two\\s+thousands)'
DecadeWithCenturyRegex = f'(the\\s+)?(((?<century>\\d|1\\d|2\\d)?(\')?(?<decade>\\d0)(\')?(\\s)?s\\b)|(({CenturyRegex}(\\s+|-)(and\\s+)?)?{DecadeRegex})|({CenturyRegex}(\\s+|-)(and\\s+)?(?<decade>tens|hundreds)))'
RelativeDecadeRegex = f'\\b((the\\s+)?{RelativeRegex}\\s+((?<number>[\\w,]+)\\s+)?decades?)\\b'
YearPeriodRegex = f'((((from|during|in)\\s+)?{YearRegex}\\s*({TillRegex})\\s*{YearRegex})|(((between)\\s+){YearRegex}\\s*({RangeConnectorRegex})\\s*{YearRegex}))'
StrictTillRegex = f'(?<till>\\b(to|(un)?till?|thru|through)\\b|{BaseDateTime.RangeConnectorSymbolRegex}(?!\\s*(h[1-2]|q[1-4])(?!(\\s+of|\\s*,\\s*))))'
StrictRangeConnectorRegex = f'(?<and>\\b(and|through|to)\\b|{BaseDateTime.RangeConnectorSymbolRegex}(?!\\s*(h[1-2]|q[1-4])(?!(\\s+of|\\s*,\\s*))))'
StartMiddleEndRegex = f'\\b((?<StartOf>((the\\s+)?(start|beginning)\\s+of\\s+)?)(?<MiddleOf>((the\\s+)?middle\\s+of\\s+)?)(?<EndOf>((the\\s+)?end\\s+of\\s+)?))'
ComplexDatePeriodRegex = f'(?:((from|during|in)\\s+)?{StartMiddleEndRegex}(?<start>.+)\\s*({StrictTillRegex})\\s*{StartMiddleEndRegex}(?<end>.+)|((between)\\s+){StartMiddleEndRegex}(?<start>.+)\\s*({StrictRangeConnectorRegex})\\s*{StartMiddleEndRegex}(?<end>.+))'
FailFastRegex = f'{BaseDateTime.DeltaMinuteRegex}|\\b(?:{BaseDateTime.BaseAmDescRegex}|{BaseDateTime.BasePmDescRegex})|{BaseDateTime.BaseAmPmDescRegex}|\\b(?:zero|{WrittenOneToNineRegex}|{WrittenElevenToNineteenRegex}|{WrittenTensRegex}|{WrittenMonthRegex}|{SeasonDescRegex}|{DecadeRegex}|centur(y|ies)|weekends?|quarters?|hal(f|ves)|yesterday|to(morrow|day|night)|tmr|noonish|\\d(-|——)?ish|((the\\s+\\w*)|\\d)(th|rd|nd|st)|(mid\\s*(-\\s*)?)?(night|morning|afternoon|day)s?|evenings?|noon|lunch(time)?|dinner(time)?|(day|night)time|overnight|dawn|dusk|sunset|hours?|hrs?|h|minutes?|mins?|seconds?|secs?|eo[dmy]|mardi[ -]?gras|birthday|eve|christmas|xmas|thanksgiving|halloween|yuandan|easter|yuan dan|april fools|cinco de mayo|all (hallow|souls)|guy fawkes|(st )?patrick|hundreds?|noughties|aughts|thousands?)\\b|{WeekDayRegex}|{SetWeekDayRegex}|{NowRegex}|{PeriodicRegex}|\\b({DateUnitRegex}|{ImplicitDayRegex})'
UnitMap = dict([("decades", "10Y"),
("decade", "10Y"),
("years", "Y"),
("year", "Y"),
("months", "MON"),
("month", "MON"),
("quarters", "3MON"),
("quarter", "3MON"),
("semesters", "6MON"),
("semestres", "6MON"),
("semester", "6MON"),
("semestre", "6MON"),
("weeks", "W"),
("week", "W"),
("weekends", "WE"),
("weekend", "WE"),
("fortnights", "2W"),
("fortnight", "2W"),
("weekdays", "D"),
("weekday", "D"),
("days", "D"),
("day", "D"),
("nights", "D"),
("night", "D"),
("hours", "H"),
("hour", "H"),
("hrs", "H"),
("hr", "H"),
("h", "H"),
("minutes", "M"),
("minute", "M"),
("mins", "M"),
("min", "M"),
("seconds", "S"),
("second", "S"),
("secs", "S"),
("sec", "S")])
UnitValueMap = dict([("decades", 315360000),
("decade", 315360000),
("years", 31536000),
("year", 31536000),
("months", 2592000),
("month", 2592000),
("fortnights", 1209600),
("fortnight", 1209600),
("weekends", 172800),
("weekend", 172800),
("weeks", 604800),
("week", 604800),
("days", 86400),
("day", 86400),
("nights", 86400),
("night", 86400),
("hours", 3600),
("hour", 3600),
("hrs", 3600),
("hr", 3600),
("h", 3600),
("minutes", 60),
("minute", 60),
("mins", 60),
("min", 60),
("seconds", 1),
("second", 1),
("secs", 1),
("sec", 1)])
SpecialYearPrefixesMap = dict([("fiscal", "FY"),
("school", "SY"),
("fy", "FY"),
("sy", "SY")])
SeasonMap = dict([("spring", "SP"),
("summer", "SU"),
("fall", "FA"),
("autumn", "FA"),
("winter", "WI")])
SeasonValueMap = dict([("SP", 3),
("SU", 6),
("FA", 9),
("WI", 12)])
CardinalMap = dict([("first", 1),
("1st", 1),
("second", 2),
("2nd", 2),
("third", 3),
("3rd", 3),
("fourth", 4),
("4th", 4),
("fifth", 5),
("5th", 5)])
DayOfWeek = dict([("monday", 1),
("tuesday", 2),
("wednesday", 3),
("thursday", 4),
("friday", 5),
("saturday", 6),
("sunday", 0),
("mon", 1),
("tue", 2),
("tues", 2),
("wed", 3),
("wedn", 3),
("weds", 3),
("thu", 4),
("thur", 4),
("thurs", 4),
("fri", 5),
("sat", 6),
("sun", 0)])
MonthOfYear = dict([("january", 1),
("february", 2),
("march", 3),
("april", 4),
("may", 5),
("june", 6),
("july", 7),
("august", 8),
("september", 9),
("october", 10),
("november", 11),
("december", 12),
("jan", 1),
("feb", 2),
("mar", 3),
("apr", 4),
("jun", 6),
("jul", 7),
("aug", 8),
("sep", 9),
("sept", 9),
("oct", 10),
("nov", 11),
("dec", 12),
("1", 1),
("2", 2),
("3", 3),
("4", 4),
("5", 5),
("6", 6),
("7", 7),
("8", 8),
("9", 9),
("10", 10),
("11", 11),
("12", 12),
("01", 1),
("02", 2),
("03", 3),
("04", 4),
("05", 5),
("06", 6),
("07", 7),
("08", 8),
("09", 9)])
Numbers = dict([("zero", 0),
("one", 1),
("a", 1),
("an", 1),
("two", 2),
("three", 3),
("four", 4),
("five", 5),
("six", 6),
("seven", 7),
("eight", 8),
("nine", 9),
("ten", 10),
("eleven", 11),
("twelve", 12),
("thirteen", 13),
("fourteen", 14),
("fifteen", 15),
("sixteen", 16),
("seventeen", 17),
("eighteen", 18),
("nineteen", 19),
("twenty", 20),
("twenty one", 21),
("twenty two", 22),
("twenty three", 23),
("twenty four", 24),
("twenty five", 25),
("twenty six", 26),
("twenty seven", 27),
("twenty eight", 28),
("twenty nine", 29),
("thirty", 30),
("thirty one", 31),
("thirty two", 32),
("thirty three", 33),
("thirty four", 34),
("thirty five", 35),
("thirty six", 36),
("thirty seven", 37),
("thirty eight", 38),
("thirty nine", 39),
("forty", 40),
("forty one", 41),
("forty two", 42),
("forty three", 43),
("forty four", 44),
("forty five", 45),
("forty six", 46),
("forty seven", 47),
("forty eight", 48),
("forty nine", 49),
("fifty", 50),
("fifty one", 51),
("fifty two", 52),
("fifty three", 53),
("fifty four", 54),
("fifty five", 55),
("fifty six", 56),
("fifty seven", 57),
("fifty eight", 58),
("fifty nine", 59),
("sixty", 60),
("sixty one", 61),
("sixty two", 62),
("sixty three", 63),
("sixty four", 64),
("sixty five", 65),
("sixty six", 66),
("sixty seven", 67),
("sixty eight", 68),
("sixty nine", 69),
("seventy", 70),
("seventy one", 71),
("seventy two", 72),
("seventy three", 73),
("seventy four", 74),
("seventy five", 75),
("seventy six", 76),
("seventy seven", 77),
("seventy eight", 78),
("seventy nine", 79),
("eighty", 80),
("eighty one", 81),
("eighty two", 82),
("eighty three", 83),
("eighty four", 84),
("eighty five", 85),
("eighty six", 86),
("eighty seven", 87),
("eighty eight", 88),
("eighty nine", 89),
("ninety", 90),
("ninety one", 91),
("ninety two", 92),
("ninety three", 93),
("ninety four", 94),
("ninety five", 95),
("ninety six", 96),
("ninety seven", 97),
("ninety eight", 98),
("ninety nine", 99),
("one hundred", 100)])
DayOfMonth = dict([("1st", 1),
("1th", 1),
("2nd", 2),
("2th", 2),
("3rd", 3),
("3th", 3),
("4th", 4),
("5th", 5),
("6th", 6),
("7th", 7),
("8th", 8),
("9th", 9),
("10th", 10),
("11th", 11),
("11st", 11),
("12th", 12),
("12nd", 12),
("13th", 13),
("13rd", 13),
("14th", 14),
("15th", 15),
("16th", 16),
("17th", 17),
("18th", 18),
("19th", 19),
("20th", 20),
("21st", 21),
("21th", 21),
("22nd", 22),
("22th", 22),
("23rd", 23),
("23th", 23),
("24th", 24),
("25th", 25),
("26th", 26),
("27th", 27),
("28th", 28),
("29th", 29),
("30th", 30),
("31st", 31),
("01st", 1),
("01th", 1),
("02nd", 2),
("02th", 2),
("03rd", 3),
("03th", 3),
("04th", 4),
("05th", 5),
("06th", 6),
("07th", 7),
("08th", 8),
("09th", 9)])
DoubleNumbers = dict([("half", 0.5),
("quarter", 0.25)])
HolidayNames = dict([("easterday", ["easterday", "easter", "eastersunday"]),
("ashwednesday", ["ashwednesday"]),
("palmsunday", ["palmsunday"]),
("maundythursday", ["maundythursday"]),
("goodfriday", ["goodfriday"]),
("eastersaturday", ["eastersaturday"]),
("eastermonday", ["eastermonday"]),
("ascensionday", ["ascensionday"]),
("whitesunday", ["whitesunday", "pentecost", "pentecostday"]),
("whitemonday", ["whitemonday"]),
("trinitysunday", ["trinitysunday"]),
("corpuschristi", ["corpuschristi"]),
("earthday", ["earthday"]),
("fathers", ["fatherday", "fathersday"]),
("mothers", ["motherday", "mothersday"]),
("thanksgiving", ["thanksgivingday", "thanksgiving"]),
("blackfriday", ["blackfriday"]),
("cybermonday", ["cybermonday"]),
("martinlutherking", ["mlkday", "martinlutherkingday", "martinlutherkingjrday"]),
("washingtonsbirthday", ["washingtonsbirthday", "washingtonbirthday", "presidentsday"]),
("canberra", ["canberraday"]),
("labour", ["labourday", "laborday"]),
("columbus", ["columbusday"]),
("memorial", ["memorialday"]),
("yuandan", ["yuandan"]),
("maosbirthday", ["maosbirthday"]),
("teachersday", ["teachersday", "teacherday"]),
("singleday", ["singleday"]),
("allsaintsday", ["allsaintsday"]),
("youthday", ["youthday"]),
("childrenday", ["childrenday", "childday"]),
("femaleday", ["femaleday"]),
("treeplantingday", ["treeplantingday"]),
("arborday", ["arborday"]),
("girlsday", ["girlsday"]),
("whiteloverday", ["whiteloverday"]),
("loverday", ["loverday", "loversday"]),
("christmas", ["christmasday", "christmas"]),
("xmas", ["xmasday", "xmas"]),
("newyear", ["newyear"]),
("newyearday", ["newyearday"]),
("newyearsday", ["newyearsday"]),
("inaugurationday", ["inaugurationday"]),
("groundhougday", ["groundhougday"]),
("valentinesday", ["valentinesday"]),
("stpatrickday", ["stpatrickday", "stpatricksday", "stpatrick"]),
("aprilfools", ["aprilfools"]),
("stgeorgeday", ["stgeorgeday"]),
("mayday", ["mayday", "intlworkersday", "internationalworkersday", "workersday"]),
("cincodemayoday", ["cincodemayoday"]),
("baptisteday", ["baptisteday"]),
("usindependenceday", ["usindependenceday"]),
("independenceday", ["independenceday"]),
("bastilleday", ["bastilleday"]),
("halloweenday", ["halloweenday", "halloween"]),
("allhallowday", ["allhallowday"]),
("allsoulsday", ["allsoulsday"]),
("guyfawkesday", ["guyfawkesday"]),
("veteransday", ["veteransday"]),
("christmaseve", ["christmaseve"]),
("newyeareve", ["newyearseve", "newyeareve"]),
("juneteenth", ["juneteenth", "freedomday", "jubileeday"])])
WrittenDecades = dict([("hundreds", 0),
("tens", 10),
("twenties", 20),
("thirties", 30),
("forties", 40),
("fifties", 50),
("sixties", 60),
("seventies", 70),
("eighties", 80),
("nineties", 90)])
SpecialDecadeCases = dict([("noughties", 2000),
("aughts", 2000),
("two thousands", 2000)])
DefaultLanguageFallback = 'MDY'
SuperfluousWordList = [r'preferably', r'how about', r'maybe', r'perhaps', r'say', r'like']
DurationDateRestrictions = [r'today', r'now']
AmbiguityFiltersDict = dict([("^\\d{4}$", "(\\d\\.\\d{4}|\\d{4}\\.\\d)"),
("^(morning|afternoon|evening|night|day)\\b", "\\b(good\\s+(morning|afternoon|evening|night|day))|(nighty\\s+night)\\b"),
("\\bnow\\b", "\\b(^now,)|\\b((is|are)\\s+now\\s+for|for\\s+now)\\b"),
("\\bmay\\b", "\\b((((!|\\.|\\?|,|;|)\\s+|^)may i)|(i|you|he|she|we|they)\\s+may|(may\\s+((((also|not|(also not)|well)\\s+)?(be|ask|contain|constitute|e-?mail|take|have|result|involve|get|work|reply|differ))|(or may not))))\\b"),
("\\b(a|one) second\\b", "\\b(?<!an?\\s+)(a|one) second (round|time)\\b"),
("\\b(breakfast|brunch|lunch(time)?|dinner(time)?|supper)$", "(?<!\\b(at|before|after|around|circa)\\b\\s)(breakfast|brunch|lunch|dinner|supper)(?!\\s*time)"),
("^\\d+m$", "^\\d+m$"),
("^(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)$", "([$%£&!?@#])(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)|(apr|aug|dec|feb|jan|jul|jun|mar|may|nov|oct|sept?)([$%£&@#])")])
MorningTermList = [r'morning']
AfternoonTermList = [r'afternoon']
EveningTermList = [r'evening']
MealtimeBreakfastTermList = [r'breakfast']
MealtimeBrunchTermList = [r'brunch']
MealtimeLunchTermList = [r'lunch', r'lunchtime']
MealtimeDinnerTermList = [r'dinner', r'dinnertime', r'supper']
DaytimeTermList = [r'daytime']
NightTermList = [r'night']
SameDayTerms = [r'today', r'otd']
PlusOneDayTerms = [r'tomorrow', r'tmr', r'day after']
MinusOneDayTerms = [r'yesterday', r'day before']
PlusTwoDayTerms = [r'day after tomorrow', r'day after tmr']
MinusTwoDayTerms = [r'day before yesterday']
FutureTerms = [r'this', r'next']
LastCardinalTerms = [r'last']
MonthTerms = [r'month']
MonthToDateTerms = [r'month to date']
WeekendTerms = [r'weekend']
WeekTerms = [r'week']
FortnightTerms = [r'fortnight', r'fourtenight']
YearTerms = [r'year']
GenericYearTerms = [r'y']
YearToDateTerms = [r'year to date']
DoubleMultiplierRegex = f'^(bi)(-|\\s)?'
HalfMultiplierRegex = f'^(semi)(-|\\s)?'
DayTypeRegex = f'((week)?da(il)?ys?)$'
WeekTypeRegex = f'(week(s|ly)?)$'
WeekendTypeRegex = f'(weekends?)$'
MonthTypeRegex = f'(month(s|ly)?)$'
QuarterTypeRegex = f'(quarter(s|ly)?)$'
YearTypeRegex = f'((years?|annual)(ly)?)$'
# pylint: enable=line-too-long | 0.327453 | 0.370966 |
import json
from alipay.aop.api.constant.ParamConstants import *
class MergePayOrder(object):
def __init__(self):
self._amount = None
self._fail_reason = None
self._fee = None
self._order_id = None
self._out_biz_no = None
self._payee_display_account = None
self._payee_display_name = None
self._payee_inst_id = None
self._payee_inst_name = None
self._payee_portrait_id = None
self._payee_type = None
self._remark = None
self._status = None
self._withdraw_delay = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
@property
def fail_reason(self):
return self._fail_reason
@fail_reason.setter
def fail_reason(self, value):
self._fail_reason = value
@property
def fee(self):
return self._fee
@fee.setter
def fee(self, value):
self._fee = value
@property
def order_id(self):
return self._order_id
@order_id.setter
def order_id(self, value):
self._order_id = value
@property
def out_biz_no(self):
return self._out_biz_no
@out_biz_no.setter
def out_biz_no(self, value):
self._out_biz_no = value
@property
def payee_display_account(self):
return self._payee_display_account
@payee_display_account.setter
def payee_display_account(self, value):
self._payee_display_account = value
@property
def payee_display_name(self):
return self._payee_display_name
@payee_display_name.setter
def payee_display_name(self, value):
self._payee_display_name = value
@property
def payee_inst_id(self):
return self._payee_inst_id
@payee_inst_id.setter
def payee_inst_id(self, value):
self._payee_inst_id = value
@property
def payee_inst_name(self):
return self._payee_inst_name
@payee_inst_name.setter
def payee_inst_name(self, value):
self._payee_inst_name = value
@property
def payee_portrait_id(self):
return self._payee_portrait_id
@payee_portrait_id.setter
def payee_portrait_id(self, value):
self._payee_portrait_id = value
@property
def payee_type(self):
return self._payee_type
@payee_type.setter
def payee_type(self, value):
self._payee_type = value
@property
def remark(self):
return self._remark
@remark.setter
def remark(self, value):
self._remark = value
@property
def status(self):
return self._status
@status.setter
def status(self, value):
self._status = value
@property
def withdraw_delay(self):
return self._withdraw_delay
@withdraw_delay.setter
def withdraw_delay(self, value):
self._withdraw_delay = value
def to_alipay_dict(self):
params = dict()
if self.amount:
if hasattr(self.amount, 'to_alipay_dict'):
params['amount'] = self.amount.to_alipay_dict()
else:
params['amount'] = self.amount
if self.fail_reason:
if hasattr(self.fail_reason, 'to_alipay_dict'):
params['fail_reason'] = self.fail_reason.to_alipay_dict()
else:
params['fail_reason'] = self.fail_reason
if self.fee:
if hasattr(self.fee, 'to_alipay_dict'):
params['fee'] = self.fee.to_alipay_dict()
else:
params['fee'] = self.fee
if self.order_id:
if hasattr(self.order_id, 'to_alipay_dict'):
params['order_id'] = self.order_id.to_alipay_dict()
else:
params['order_id'] = self.order_id
if self.out_biz_no:
if hasattr(self.out_biz_no, 'to_alipay_dict'):
params['out_biz_no'] = self.out_biz_no.to_alipay_dict()
else:
params['out_biz_no'] = self.out_biz_no
if self.payee_display_account:
if hasattr(self.payee_display_account, 'to_alipay_dict'):
params['payee_display_account'] = self.payee_display_account.to_alipay_dict()
else:
params['payee_display_account'] = self.payee_display_account
if self.payee_display_name:
if hasattr(self.payee_display_name, 'to_alipay_dict'):
params['payee_display_name'] = self.payee_display_name.to_alipay_dict()
else:
params['payee_display_name'] = self.payee_display_name
if self.payee_inst_id:
if hasattr(self.payee_inst_id, 'to_alipay_dict'):
params['payee_inst_id'] = self.payee_inst_id.to_alipay_dict()
else:
params['payee_inst_id'] = self.payee_inst_id
if self.payee_inst_name:
if hasattr(self.payee_inst_name, 'to_alipay_dict'):
params['payee_inst_name'] = self.payee_inst_name.to_alipay_dict()
else:
params['payee_inst_name'] = self.payee_inst_name
if self.payee_portrait_id:
if hasattr(self.payee_portrait_id, 'to_alipay_dict'):
params['payee_portrait_id'] = self.payee_portrait_id.to_alipay_dict()
else:
params['payee_portrait_id'] = self.payee_portrait_id
if self.payee_type:
if hasattr(self.payee_type, 'to_alipay_dict'):
params['payee_type'] = self.payee_type.to_alipay_dict()
else:
params['payee_type'] = self.payee_type
if self.remark:
if hasattr(self.remark, 'to_alipay_dict'):
params['remark'] = self.remark.to_alipay_dict()
else:
params['remark'] = self.remark
if self.status:
if hasattr(self.status, 'to_alipay_dict'):
params['status'] = self.status.to_alipay_dict()
else:
params['status'] = self.status
if self.withdraw_delay:
if hasattr(self.withdraw_delay, 'to_alipay_dict'):
params['withdraw_delay'] = self.withdraw_delay.to_alipay_dict()
else:
params['withdraw_delay'] = self.withdraw_delay
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = MergePayOrder()
if 'amount' in d:
o.amount = d['amount']
if 'fail_reason' in d:
o.fail_reason = d['fail_reason']
if 'fee' in d:
o.fee = d['fee']
if 'order_id' in d:
o.order_id = d['order_id']
if 'out_biz_no' in d:
o.out_biz_no = d['out_biz_no']
if 'payee_display_account' in d:
o.payee_display_account = d['payee_display_account']
if 'payee_display_name' in d:
o.payee_display_name = d['payee_display_name']
if 'payee_inst_id' in d:
o.payee_inst_id = d['payee_inst_id']
if 'payee_inst_name' in d:
o.payee_inst_name = d['payee_inst_name']
if 'payee_portrait_id' in d:
o.payee_portrait_id = d['payee_portrait_id']
if 'payee_type' in d:
o.payee_type = d['payee_type']
if 'remark' in d:
o.remark = d['remark']
if 'status' in d:
o.status = d['status']
if 'withdraw_delay' in d:
o.withdraw_delay = d['withdraw_delay']
return o | alipay/aop/api/domain/MergePayOrder.py | import json
from alipay.aop.api.constant.ParamConstants import *
class MergePayOrder(object):
def __init__(self):
self._amount = None
self._fail_reason = None
self._fee = None
self._order_id = None
self._out_biz_no = None
self._payee_display_account = None
self._payee_display_name = None
self._payee_inst_id = None
self._payee_inst_name = None
self._payee_portrait_id = None
self._payee_type = None
self._remark = None
self._status = None
self._withdraw_delay = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
@property
def fail_reason(self):
return self._fail_reason
@fail_reason.setter
def fail_reason(self, value):
self._fail_reason = value
@property
def fee(self):
return self._fee
@fee.setter
def fee(self, value):
self._fee = value
@property
def order_id(self):
return self._order_id
@order_id.setter
def order_id(self, value):
self._order_id = value
@property
def out_biz_no(self):
return self._out_biz_no
@out_biz_no.setter
def out_biz_no(self, value):
self._out_biz_no = value
@property
def payee_display_account(self):
return self._payee_display_account
@payee_display_account.setter
def payee_display_account(self, value):
self._payee_display_account = value
@property
def payee_display_name(self):
return self._payee_display_name
@payee_display_name.setter
def payee_display_name(self, value):
self._payee_display_name = value
@property
def payee_inst_id(self):
return self._payee_inst_id
@payee_inst_id.setter
def payee_inst_id(self, value):
self._payee_inst_id = value
@property
def payee_inst_name(self):
return self._payee_inst_name
@payee_inst_name.setter
def payee_inst_name(self, value):
self._payee_inst_name = value
@property
def payee_portrait_id(self):
return self._payee_portrait_id
@payee_portrait_id.setter
def payee_portrait_id(self, value):
self._payee_portrait_id = value
@property
def payee_type(self):
return self._payee_type
@payee_type.setter
def payee_type(self, value):
self._payee_type = value
@property
def remark(self):
return self._remark
@remark.setter
def remark(self, value):
self._remark = value
@property
def status(self):
return self._status
@status.setter
def status(self, value):
self._status = value
@property
def withdraw_delay(self):
return self._withdraw_delay
@withdraw_delay.setter
def withdraw_delay(self, value):
self._withdraw_delay = value
def to_alipay_dict(self):
params = dict()
if self.amount:
if hasattr(self.amount, 'to_alipay_dict'):
params['amount'] = self.amount.to_alipay_dict()
else:
params['amount'] = self.amount
if self.fail_reason:
if hasattr(self.fail_reason, 'to_alipay_dict'):
params['fail_reason'] = self.fail_reason.to_alipay_dict()
else:
params['fail_reason'] = self.fail_reason
if self.fee:
if hasattr(self.fee, 'to_alipay_dict'):
params['fee'] = self.fee.to_alipay_dict()
else:
params['fee'] = self.fee
if self.order_id:
if hasattr(self.order_id, 'to_alipay_dict'):
params['order_id'] = self.order_id.to_alipay_dict()
else:
params['order_id'] = self.order_id
if self.out_biz_no:
if hasattr(self.out_biz_no, 'to_alipay_dict'):
params['out_biz_no'] = self.out_biz_no.to_alipay_dict()
else:
params['out_biz_no'] = self.out_biz_no
if self.payee_display_account:
if hasattr(self.payee_display_account, 'to_alipay_dict'):
params['payee_display_account'] = self.payee_display_account.to_alipay_dict()
else:
params['payee_display_account'] = self.payee_display_account
if self.payee_display_name:
if hasattr(self.payee_display_name, 'to_alipay_dict'):
params['payee_display_name'] = self.payee_display_name.to_alipay_dict()
else:
params['payee_display_name'] = self.payee_display_name
if self.payee_inst_id:
if hasattr(self.payee_inst_id, 'to_alipay_dict'):
params['payee_inst_id'] = self.payee_inst_id.to_alipay_dict()
else:
params['payee_inst_id'] = self.payee_inst_id
if self.payee_inst_name:
if hasattr(self.payee_inst_name, 'to_alipay_dict'):
params['payee_inst_name'] = self.payee_inst_name.to_alipay_dict()
else:
params['payee_inst_name'] = self.payee_inst_name
if self.payee_portrait_id:
if hasattr(self.payee_portrait_id, 'to_alipay_dict'):
params['payee_portrait_id'] = self.payee_portrait_id.to_alipay_dict()
else:
params['payee_portrait_id'] = self.payee_portrait_id
if self.payee_type:
if hasattr(self.payee_type, 'to_alipay_dict'):
params['payee_type'] = self.payee_type.to_alipay_dict()
else:
params['payee_type'] = self.payee_type
if self.remark:
if hasattr(self.remark, 'to_alipay_dict'):
params['remark'] = self.remark.to_alipay_dict()
else:
params['remark'] = self.remark
if self.status:
if hasattr(self.status, 'to_alipay_dict'):
params['status'] = self.status.to_alipay_dict()
else:
params['status'] = self.status
if self.withdraw_delay:
if hasattr(self.withdraw_delay, 'to_alipay_dict'):
params['withdraw_delay'] = self.withdraw_delay.to_alipay_dict()
else:
params['withdraw_delay'] = self.withdraw_delay
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = MergePayOrder()
if 'amount' in d:
o.amount = d['amount']
if 'fail_reason' in d:
o.fail_reason = d['fail_reason']
if 'fee' in d:
o.fee = d['fee']
if 'order_id' in d:
o.order_id = d['order_id']
if 'out_biz_no' in d:
o.out_biz_no = d['out_biz_no']
if 'payee_display_account' in d:
o.payee_display_account = d['payee_display_account']
if 'payee_display_name' in d:
o.payee_display_name = d['payee_display_name']
if 'payee_inst_id' in d:
o.payee_inst_id = d['payee_inst_id']
if 'payee_inst_name' in d:
o.payee_inst_name = d['payee_inst_name']
if 'payee_portrait_id' in d:
o.payee_portrait_id = d['payee_portrait_id']
if 'payee_type' in d:
o.payee_type = d['payee_type']
if 'remark' in d:
o.remark = d['remark']
if 'status' in d:
o.status = d['status']
if 'withdraw_delay' in d:
o.withdraw_delay = d['withdraw_delay']
return o | 0.495361 | 0.061706 |
import hydra
from omegaconf import DictConfig
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimizer (Optimizer): Wrapped optimizer.
multiplier: target learning rate = base lr * multiplier if multiplier > 1.0. if multiplier = 1.0, lr starts from 0 and ends up with the base_lr.
warmup_epoch: target learning rate is reached at warmup_epoch, gradually
after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau)
"""
def __init__(self, optimizer, multiplier: float=0.9, warmup_epoch: int=10, after_scheduler=None):
self.multiplier = multiplier
if self.multiplier < 1.:
raise ValueError('multiplier should be greater thant or equal to 1.')
self.warmup_epoch = warmup_epoch
if isinstance(after_scheduler, (dict, DictConfig)):
after_scheduler_cfg = after_scheduler
after_scheduler = hydra.utils.instantiate(after_scheduler_cfg, optimizer=optimizer)
self.after_scheduler = after_scheduler
self.finished = False
super(GradualWarmupScheduler, self).__init__(optimizer)
def get_lr(self):
if self.last_epoch >= self.warmup_epoch:
if self.after_scheduler:
if not self.finished:
self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs]
self.finished = True
return self.after_scheduler.get_last_lr()
return [base_lr * self.multiplier for base_lr in self.base_lrs]
if self.multiplier == 1.0:
return [base_lr * (float(self.last_epoch+1) / self.warmup_epoch) for base_lr in self.base_lrs]
else:
return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.warmup_epoch + 1.) for base_lr in self.base_lrs]
def step_ReduceLROnPlateau(self, metrics, epoch=None):
if epoch is None:
epoch = self.last_epoch + 1
self.last_epoch = epoch if epoch != 0 else 1 # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning
if self.last_epoch <= self.warmup_epoch:
warmup_lr = [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.warmup_epoch + 1.) for base_lr in self.base_lrs]
for param_group, lr in zip(self.optimizer.param_groups, warmup_lr):
param_group['lr'] = lr
else:
if epoch is None:
self.after_scheduler.step(metrics, None)
else:
self.after_scheduler.step(metrics, epoch - self.warmup_epoch)
def step(self, epoch=None, metrics=None):
if type(self.after_scheduler) != ReduceLROnPlateau:
if self.finished and self.after_scheduler:
if epoch is None:
self.after_scheduler.step(None)
else:
self.after_scheduler.step(epoch - self.warmup_epoch)
self._last_lr = self.after_scheduler.get_last_lr()
else:
return super(GradualWarmupScheduler, self).step(epoch)
else:
self.step_ReduceLROnPlateau(metrics, epoch)
if __name__ == '__main__':
import torch
from torch.optim.lr_scheduler import StepLR, ExponentialLR, MultiStepLR, CosineAnnealingLR
from torch.optim.sgd import SGD
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
optim = SGD(model, 0.1)
# scheduler_warmup is chained with schduler_steplr
total_epoch = 30
warmup_epoch = 10
scheduler_steplr = StepLR(optim, step_size=2, gamma=0.9)
scheduler_steplr = CosineAnnealingLR(optim, T_max=total_epoch-warmup_epoch, eta_min=1e-6)
# scheduler_steplr = None
scheduler_warmup = GradualWarmupScheduler(optim, multiplier=1, warmup_epoch=warmup_epoch, after_scheduler=scheduler_steplr)
# this zero gradient update is needed to avoid a warning message, issue #8.
optim.zero_grad()
optim.step()
for epoch in range(1, total_epoch):
scheduler_warmup.step(epoch)
print(epoch, optim.param_groups[0]['lr'])
optim.step() # backward pass (update network) | hyperbox/schedulers/warmup_scheduler.py | import hydra
from omegaconf import DictConfig
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimizer (Optimizer): Wrapped optimizer.
multiplier: target learning rate = base lr * multiplier if multiplier > 1.0. if multiplier = 1.0, lr starts from 0 and ends up with the base_lr.
warmup_epoch: target learning rate is reached at warmup_epoch, gradually
after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau)
"""
def __init__(self, optimizer, multiplier: float=0.9, warmup_epoch: int=10, after_scheduler=None):
self.multiplier = multiplier
if self.multiplier < 1.:
raise ValueError('multiplier should be greater thant or equal to 1.')
self.warmup_epoch = warmup_epoch
if isinstance(after_scheduler, (dict, DictConfig)):
after_scheduler_cfg = after_scheduler
after_scheduler = hydra.utils.instantiate(after_scheduler_cfg, optimizer=optimizer)
self.after_scheduler = after_scheduler
self.finished = False
super(GradualWarmupScheduler, self).__init__(optimizer)
def get_lr(self):
if self.last_epoch >= self.warmup_epoch:
if self.after_scheduler:
if not self.finished:
self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs]
self.finished = True
return self.after_scheduler.get_last_lr()
return [base_lr * self.multiplier for base_lr in self.base_lrs]
if self.multiplier == 1.0:
return [base_lr * (float(self.last_epoch+1) / self.warmup_epoch) for base_lr in self.base_lrs]
else:
return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.warmup_epoch + 1.) for base_lr in self.base_lrs]
def step_ReduceLROnPlateau(self, metrics, epoch=None):
if epoch is None:
epoch = self.last_epoch + 1
self.last_epoch = epoch if epoch != 0 else 1 # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning
if self.last_epoch <= self.warmup_epoch:
warmup_lr = [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.warmup_epoch + 1.) for base_lr in self.base_lrs]
for param_group, lr in zip(self.optimizer.param_groups, warmup_lr):
param_group['lr'] = lr
else:
if epoch is None:
self.after_scheduler.step(metrics, None)
else:
self.after_scheduler.step(metrics, epoch - self.warmup_epoch)
def step(self, epoch=None, metrics=None):
if type(self.after_scheduler) != ReduceLROnPlateau:
if self.finished and self.after_scheduler:
if epoch is None:
self.after_scheduler.step(None)
else:
self.after_scheduler.step(epoch - self.warmup_epoch)
self._last_lr = self.after_scheduler.get_last_lr()
else:
return super(GradualWarmupScheduler, self).step(epoch)
else:
self.step_ReduceLROnPlateau(metrics, epoch)
if __name__ == '__main__':
import torch
from torch.optim.lr_scheduler import StepLR, ExponentialLR, MultiStepLR, CosineAnnealingLR
from torch.optim.sgd import SGD
model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
optim = SGD(model, 0.1)
# scheduler_warmup is chained with schduler_steplr
total_epoch = 30
warmup_epoch = 10
scheduler_steplr = StepLR(optim, step_size=2, gamma=0.9)
scheduler_steplr = CosineAnnealingLR(optim, T_max=total_epoch-warmup_epoch, eta_min=1e-6)
# scheduler_steplr = None
scheduler_warmup = GradualWarmupScheduler(optim, multiplier=1, warmup_epoch=warmup_epoch, after_scheduler=scheduler_steplr)
# this zero gradient update is needed to avoid a warning message, issue #8.
optim.zero_grad()
optim.step()
for epoch in range(1, total_epoch):
scheduler_warmup.step(epoch)
print(epoch, optim.param_groups[0]['lr'])
optim.step() # backward pass (update network) | 0.840815 | 0.276275 |
__version__ = '0.0.8' # Time-stamp: <2021-09-14T10:47:01Z>
## Language: Japanese/UTF-8
"""Simulation Buddhism Prototype No.3 - Death
死亡関連
"""
##
## Author:
##
## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese))
##
## License:
##
## The author is a Japanese.
##
## I intended this program to be public-domain, but you can treat
## this program under the (new) BSD-License or under the Artistic
## License, if it is convenient for you.
##
## Within three months after the release of this program, I
## especially admit responsibility of efforts for rational requests
## of correction to this program.
##
## I often have bouts of schizophrenia, but I believe that my
## intention is legitimately fulfilled.
##
import math
import random
import simbdp3.base as base
from simbdp3.base import ARGS, Person0, Economy0
from simbdp3.common import Death, Tomb, np_clip
from simbdp3.inherit import calc_inheritance_share
class PersonDT (Person0):
def is_dead (self):
return self.death is not None
def die_relation (self, relation):
p = self
rel = relation
economy = self.economy
if p.age > 60:
p.a60_spouse_death = True
rel.end = economy.term
if rel.spouse != '' and economy.is_living(rel.spouse):
s = economy.people[rel.spouse]
if s.marriage is not None and s.marriage.spouse == p.id:
s.marriage.end = economy.term
s.trash.append(s.marriage)
s.marriage = None
for a in s.adulteries:
if a.spouse == p.id:
a.end = economy.term
s.trash.append(a)
s.adulteries.remove(a)
def die_child (self, child_id):
p = self
economy = self.economy
ch = None
for x in p.children:
if x.id == child_id:
ch = x
if ch is None:
return
ch.death_term = economy.term
p.children.remove(ch)
p.trash.append(ch)
def die_supporting (self, new_supporter):
p = self
economy = self.economy
ns = None
if new_supporter is not None \
and new_supporter != '':
assert economy.is_living(new_supporter)
ns = economy.people[new_supporter]
assert new_supporter is None or new_supporter == ''\
or (ns is not None and ns.supported is None)
if new_supporter is None or new_supporter == '':
for x in [x for x in p.supporting]:
if x != '' and x in economy.people:
s = economy.people[x]
assert s.supported == p.id
if new_supporter is None:
s.remove_supported()
else:
s.supported = ''
else:
ns.add_supporting(p.supporting_non_nil())
p.supporting = []
def do_inheritance (self):
p = self
economy = self.economy
assert p.is_dead()
q = p.death.inheritance_share
a = p.prop + p.land * ARGS.prop_value_of_land
if q is None or a <= 0:
economy.cur_forfeit_prop += p.prop
economy.cur_forfeit_land += p.land
p.prop = 0
p.land = 0
return
land = p.land
prop = p.prop
for x, y in sorted(q.items(), key=lambda x: x[1], reverse=True):
a1 = a * y
l = math.floor(a1 / ARGS.prop_value_of_land)
if l > land:
l = land
land = 0
else:
land -= l
if x == '':
economy.cur_forfeit_land += l
economy.cur_forfeit_prop += a1 - l * ARGS.prop_value_of_land
prop -= a1 - l * ARGS.prop_value_of_land
else:
assert economy.is_living(x)
p1 = economy.people[x]
if l > 0:
p1.tmp_land_damage = \
(p1.tmp_land_damage * p1.land
+ p.tmp_land_damage * l) / (p1.land + l)
p1.land += l
p1.prop += a1 - l * ARGS.prop_value_of_land
prop -= a1 - l * ARGS.prop_value_of_land
p.land = 0
p.prop = 0
class EconomyDT (Economy0):
def is_living (self, id_or_person):
s = id_or_person
if type(id_or_person) is not str:
s = id_or_person.id
return s in self.people and self.people[s].death is None
def get_person (self, id1):
economy = self
if id1 in economy.people:
return economy.people[id1]
elif id1 in economy.tombs:
return economy.tombs[id1].person
return None
def die (self, persons):
economy = self
if isinstance(persons, base.Person):
persons = [persons]
for p in persons:
assert not p.is_dead()
dt = Death()
dt.term = economy.term
p.death = dt
tomb = Tomb()
tomb.death_term = economy.term
tomb.person = p
tomb.death_hating = p.hating.copy()
tomb.death_hating_unknown = p.hating_unknown
tomb.death_political_hating = p.political_hating
tomb.death_merchant_hating = p.merchant_hating
tomb.death_merchant_hated = p.merchant_hated
economy.tombs[p.id] = tomb
prs = [[] for dist in economy.nation.districts]
for p in economy.people.values():
if not p.is_dead() and p.in_priesthood():
prs[p.district].append(p.id)
for p in persons:
tomb = economy.tombs[p.id]
if prs[p.district]:
tomb.priest = random.choice(prs[p.district])
a = (p.prop + p.land * ARGS.prop_value_of_land) \
* ARGS.priest_share
if a > 0:
p.prop -= a
economy.nation.districts[p.district].priests_share += a
for p in persons:
if p.in_jail():
p.release_from_jail()
for p in persons:
if p.dominator_position is None:
continue
p.get_dominator().resign()
for p in persons:
if p.id in economy.dominator_parameters:
economy.dominator_parameters[p.id].economy = None
del economy.dominator_parameters[p.id]
for p in persons:
p.death.inheritance_share = calc_inheritance_share(economy, p.id)
for p in persons:
spouse = None
if p.marriage is not None \
and (p.marriage.spouse == ''
or economy.is_living(p.marriage.spouse)):
spouse = p.marriage.spouse
if p.marriage is not None:
p.die_relation(p.marriage)
for a in p.adulteries:
p.die_relation(a)
# father mother は死んでも情報の更新はないが、child は欲し
# い子供の数に影響するため、更新が必要。
if p.father != '' and economy.is_living(p.father):
economy.people[p.father].die_child(p.id)
if p.mother != '' and economy.is_living(p.mother):
economy.people[p.mother].die_child(p.id)
fst_heir = None
if p.death.inheritance_share is not None:
l1 = [(x, y) for x, y
in p.death.inheritance_share.items()
if x != '' and economy.is_living(x)
and x != spouse
and (economy.people[x].supported is None or
economy.people[x].supported == p.id)
and economy.people[x].age >= 18]
if l1:
u = max(l1, key=lambda x: x[1])[1]
l2 = [x for x, y in l1 if y == u]
fst_heir = max(l2, key=lambda x:
economy.people[x].asset_value())
if (fst_heir is None
or fst_heir not in [ch.id for ch in p.children]) \
and spouse is not None and spouse in p.supporting:
if spouse == '':
fst_heir = ''
p.remove_supporting_nil()
else:
s = economy.people[spouse]
if s.age >= 18 and s.age < 70:
fst_heir = spouse
s.remove_supported()
if fst_heir is not None and fst_heir != '' \
and fst_heir in p.supporting:
fh = economy.people[fst_heir]
fh.remove_supported()
if p.supporting:
if p.supported is not None \
and economy.is_living(p.supported):
p.die_supporting(p.supported)
elif fst_heir is None or p.death.inheritance_share is None:
p.die_supporting(None)
else:
p.die_supporting(fst_heir)
if p.supported is not None:
p.remove_supported()
if fst_heir is not None and fst_heir != '':
fh = economy.people[fst_heir]
fh.add_supporting(p)
for p in persons:
p.do_inheritance()
def update_death (economy):
print("\nDeath:...", flush=True)
l = []
for p in economy.people.values():
if not p.is_dead():
if random.random() < ARGS.general_death_rate:
l.append(p)
else:
threshold = 0
if p.age > 110:
threshold = 1
elif p.age > 80 and p.age <= 100:
threshold = ARGS.a80_death_rate
elif p.age > 60 and p.age <= 80:
threshold = ARGS.a60_death_rate
elif p.age >= 0 and p.age <= 3:
threshold = ARGS.infant_death_rate
ij = np_clip(p.injured + p.tmp_injured, 0, 1)
threshold2 = ARGS.injured_death_rate * ij
if random.random() < max([threshold, threshold2]):
l.append(p)
economy.die(l) | simbdp3/death.py | __version__ = '0.0.8' # Time-stamp: <2021-09-14T10:47:01Z>
## Language: Japanese/UTF-8
"""Simulation Buddhism Prototype No.3 - Death
死亡関連
"""
##
## Author:
##
## JRF ( http://jrf.cocolog-nifty.com/statuses/ (in Japanese))
##
## License:
##
## The author is a Japanese.
##
## I intended this program to be public-domain, but you can treat
## this program under the (new) BSD-License or under the Artistic
## License, if it is convenient for you.
##
## Within three months after the release of this program, I
## especially admit responsibility of efforts for rational requests
## of correction to this program.
##
## I often have bouts of schizophrenia, but I believe that my
## intention is legitimately fulfilled.
##
import math
import random
import simbdp3.base as base
from simbdp3.base import ARGS, Person0, Economy0
from simbdp3.common import Death, Tomb, np_clip
from simbdp3.inherit import calc_inheritance_share
class PersonDT (Person0):
def is_dead (self):
return self.death is not None
def die_relation (self, relation):
p = self
rel = relation
economy = self.economy
if p.age > 60:
p.a60_spouse_death = True
rel.end = economy.term
if rel.spouse != '' and economy.is_living(rel.spouse):
s = economy.people[rel.spouse]
if s.marriage is not None and s.marriage.spouse == p.id:
s.marriage.end = economy.term
s.trash.append(s.marriage)
s.marriage = None
for a in s.adulteries:
if a.spouse == p.id:
a.end = economy.term
s.trash.append(a)
s.adulteries.remove(a)
def die_child (self, child_id):
p = self
economy = self.economy
ch = None
for x in p.children:
if x.id == child_id:
ch = x
if ch is None:
return
ch.death_term = economy.term
p.children.remove(ch)
p.trash.append(ch)
def die_supporting (self, new_supporter):
p = self
economy = self.economy
ns = None
if new_supporter is not None \
and new_supporter != '':
assert economy.is_living(new_supporter)
ns = economy.people[new_supporter]
assert new_supporter is None or new_supporter == ''\
or (ns is not None and ns.supported is None)
if new_supporter is None or new_supporter == '':
for x in [x for x in p.supporting]:
if x != '' and x in economy.people:
s = economy.people[x]
assert s.supported == p.id
if new_supporter is None:
s.remove_supported()
else:
s.supported = ''
else:
ns.add_supporting(p.supporting_non_nil())
p.supporting = []
def do_inheritance (self):
p = self
economy = self.economy
assert p.is_dead()
q = p.death.inheritance_share
a = p.prop + p.land * ARGS.prop_value_of_land
if q is None or a <= 0:
economy.cur_forfeit_prop += p.prop
economy.cur_forfeit_land += p.land
p.prop = 0
p.land = 0
return
land = p.land
prop = p.prop
for x, y in sorted(q.items(), key=lambda x: x[1], reverse=True):
a1 = a * y
l = math.floor(a1 / ARGS.prop_value_of_land)
if l > land:
l = land
land = 0
else:
land -= l
if x == '':
economy.cur_forfeit_land += l
economy.cur_forfeit_prop += a1 - l * ARGS.prop_value_of_land
prop -= a1 - l * ARGS.prop_value_of_land
else:
assert economy.is_living(x)
p1 = economy.people[x]
if l > 0:
p1.tmp_land_damage = \
(p1.tmp_land_damage * p1.land
+ p.tmp_land_damage * l) / (p1.land + l)
p1.land += l
p1.prop += a1 - l * ARGS.prop_value_of_land
prop -= a1 - l * ARGS.prop_value_of_land
p.land = 0
p.prop = 0
class EconomyDT (Economy0):
def is_living (self, id_or_person):
s = id_or_person
if type(id_or_person) is not str:
s = id_or_person.id
return s in self.people and self.people[s].death is None
def get_person (self, id1):
economy = self
if id1 in economy.people:
return economy.people[id1]
elif id1 in economy.tombs:
return economy.tombs[id1].person
return None
def die (self, persons):
economy = self
if isinstance(persons, base.Person):
persons = [persons]
for p in persons:
assert not p.is_dead()
dt = Death()
dt.term = economy.term
p.death = dt
tomb = Tomb()
tomb.death_term = economy.term
tomb.person = p
tomb.death_hating = p.hating.copy()
tomb.death_hating_unknown = p.hating_unknown
tomb.death_political_hating = p.political_hating
tomb.death_merchant_hating = p.merchant_hating
tomb.death_merchant_hated = p.merchant_hated
economy.tombs[p.id] = tomb
prs = [[] for dist in economy.nation.districts]
for p in economy.people.values():
if not p.is_dead() and p.in_priesthood():
prs[p.district].append(p.id)
for p in persons:
tomb = economy.tombs[p.id]
if prs[p.district]:
tomb.priest = random.choice(prs[p.district])
a = (p.prop + p.land * ARGS.prop_value_of_land) \
* ARGS.priest_share
if a > 0:
p.prop -= a
economy.nation.districts[p.district].priests_share += a
for p in persons:
if p.in_jail():
p.release_from_jail()
for p in persons:
if p.dominator_position is None:
continue
p.get_dominator().resign()
for p in persons:
if p.id in economy.dominator_parameters:
economy.dominator_parameters[p.id].economy = None
del economy.dominator_parameters[p.id]
for p in persons:
p.death.inheritance_share = calc_inheritance_share(economy, p.id)
for p in persons:
spouse = None
if p.marriage is not None \
and (p.marriage.spouse == ''
or economy.is_living(p.marriage.spouse)):
spouse = p.marriage.spouse
if p.marriage is not None:
p.die_relation(p.marriage)
for a in p.adulteries:
p.die_relation(a)
# father mother は死んでも情報の更新はないが、child は欲し
# い子供の数に影響するため、更新が必要。
if p.father != '' and economy.is_living(p.father):
economy.people[p.father].die_child(p.id)
if p.mother != '' and economy.is_living(p.mother):
economy.people[p.mother].die_child(p.id)
fst_heir = None
if p.death.inheritance_share is not None:
l1 = [(x, y) for x, y
in p.death.inheritance_share.items()
if x != '' and economy.is_living(x)
and x != spouse
and (economy.people[x].supported is None or
economy.people[x].supported == p.id)
and economy.people[x].age >= 18]
if l1:
u = max(l1, key=lambda x: x[1])[1]
l2 = [x for x, y in l1 if y == u]
fst_heir = max(l2, key=lambda x:
economy.people[x].asset_value())
if (fst_heir is None
or fst_heir not in [ch.id for ch in p.children]) \
and spouse is not None and spouse in p.supporting:
if spouse == '':
fst_heir = ''
p.remove_supporting_nil()
else:
s = economy.people[spouse]
if s.age >= 18 and s.age < 70:
fst_heir = spouse
s.remove_supported()
if fst_heir is not None and fst_heir != '' \
and fst_heir in p.supporting:
fh = economy.people[fst_heir]
fh.remove_supported()
if p.supporting:
if p.supported is not None \
and economy.is_living(p.supported):
p.die_supporting(p.supported)
elif fst_heir is None or p.death.inheritance_share is None:
p.die_supporting(None)
else:
p.die_supporting(fst_heir)
if p.supported is not None:
p.remove_supported()
if fst_heir is not None and fst_heir != '':
fh = economy.people[fst_heir]
fh.add_supporting(p)
for p in persons:
p.do_inheritance()
def update_death (economy):
print("\nDeath:...", flush=True)
l = []
for p in economy.people.values():
if not p.is_dead():
if random.random() < ARGS.general_death_rate:
l.append(p)
else:
threshold = 0
if p.age > 110:
threshold = 1
elif p.age > 80 and p.age <= 100:
threshold = ARGS.a80_death_rate
elif p.age > 60 and p.age <= 80:
threshold = ARGS.a60_death_rate
elif p.age >= 0 and p.age <= 3:
threshold = ARGS.infant_death_rate
ij = np_clip(p.injured + p.tmp_injured, 0, 1)
threshold2 = ARGS.injured_death_rate * ij
if random.random() < max([threshold, threshold2]):
l.append(p)
economy.die(l) | 0.33764 | 0.208803 |
import unittest
from configparser import ConfigParser
from os import environ
import logging
import json
import mock
from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil, SDKConfig
from GenomeFileUtil.GenomeFileUtilServer import MethodContext
from GenomeFileUtil.core.GenomeInterface import GenomeInterface
from GenomeFileUtil.core import GenomeUtils
from installed_clients.WorkspaceClient import Workspace as workspaceService
class GenomeFileUtilTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# logging.basicConfig(level=logging.info)
token = environ.get('KB_AUTH_TOKEN', None)
# WARNING: don't call any logging methods on the context object,
# it'll result in a NoneType error
cls.ctx = MethodContext(None)
cls.ctx.update({'token': token,
'provenance': [
{'service': 'GenomeFileUtil',
'method': 'please_never_use_it_in_production',
'method_params': []
}],
'authenticated': 1})
config_file = environ.get('KB_DEPLOYMENT_CONFIG', None)
cls.cfg = {}
config = ConfigParser()
config.read(config_file)
for nameval in config.items('GenomeFileUtil'):
cls.cfg[nameval[0]] = nameval[1]
cls.wsURL = cls.cfg['workspace-url']
cls.ws = workspaceService(cls.wsURL, token=token)
cls.serviceImpl = GenomeFileUtil(cls.cfg)
gi_config = SDKConfig(cls.cfg)
cls.genome_interface = GenomeInterface(gi_config)
@classmethod
def tearDownClass(cls):
pass
def test_non_unique_ids(self):
# Non unique ids
with open('data/non_unique_ids.json') as json_file:
non_unique_ids_genome = json.load(json_file)
uniqueness_results = GenomeUtils.check_feature_ids_uniqueness(non_unique_ids_genome)
self.assertTrue(len(uniqueness_results) > 0)
self.assertTrue(uniqueness_results == {'RL742_CDS_1': 2, 'RL4742_mRNA_2': 2, 'RL4742': 3})
def test_unique_ids(self):
# Unique ids.
with open('data/unique_ids.json') as json_file:
non_unique_ids_genome = json.load(json_file)
uniqueness_results = GenomeUtils.check_feature_ids_uniqueness(non_unique_ids_genome)
self.assertTrue(len(uniqueness_results) == 0)
def test_single_feature_relationships_good(self):
# Tests confirm_feature_relationships called separately for valid relationships.
test_count = 0
with open('data/good_relationships.json') as json_file:
good_relationships_genome = json.load(json_file)
feature_id_sets_dict = dict()
feature_lists = ["features","cdss","mrnas","non_coding_features"]
for feature_list in feature_lists:
if feature_list in good_relationships_genome:
feature_id_sets_dict[feature_list] = GenomeUtils.make_id_set(good_relationships_genome[feature_list])
else:
feature_id_sets_dict[feature_list] = set()
for feature in good_relationships_genome["features"]:
if feature["id"] == "RL4742":
gene_results = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
self.assertTrue(len(gene_results)==0)
test_count += 1
for feature in good_relationships_genome["cdss"]:
if feature["id"] == "RL742_CDS_1":
cds_results = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
self.assertTrue(len(cds_results)==0)
test_count += 1
for feature in good_relationships_genome["mrnas"]:
if feature["id"] == "RL742_mRNA_1":
mrna_results = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
self.assertTrue(len(mrna_results)==0)
test_count += 1
for feature in good_relationships_genome["non_coding_features"]:
if feature["id"] == "test_gene_1":
non_coding_parent_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_parent_results)==0)
test_count += 1
elif feature["id"] == "test_gene_1_tRNA_2":
non_coding_nc_child_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_nc_child_results)==0)
test_count += 1
elif feature["id"] == "RL4742_promoter":
non_coding_gene_child_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_gene_child_results)==0)
test_count += 1
self.assertTrue(test_count == 6,"Not all good inividual feature relationships tested. " + str(test_count))
def test_single_feature_relationships_bad(self):
# Tests confirm_feature_relationships called separately for missing relationship targets.
with open('data/bad_relationships.json') as json_file:
bad_relationships_genome = json.load(json_file)
feature_id_sets_dict = dict()
feature_lists = ["features","cdss","mrnas","non_coding_features"]
for feature_list in feature_lists:
if feature_list in bad_relationships_genome:
feature_id_sets_dict[feature_list] = GenomeUtils.make_id_set(bad_relationships_genome[feature_list])
else:
feature_id_sets_dict[feature_list] = set()
test_count = 0
for feature in bad_relationships_genome["features"]:
if feature["id"] == "no_real_cds":
gene_results1 = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
print("Bad Gene Results 1:" + str(gene_results1))
self.assertTrue(len(gene_results1)>0)
test_count += 1
elif feature["id"] == "no_real_mrna":
gene_results2 = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
print("Bad Gene Results 2:" + str(gene_results2))
self.assertTrue(len(gene_results2)>0)
test_count += 1
for feature in bad_relationships_genome["cdss"]:
if feature["id"] == "no_real_parent_gene_cds":
cds_results1 = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
print("Bad CDS Results 1:" + str(cds_results1))
self.assertTrue(len(cds_results1)>0)
test_count += 1
elif feature["id"] == "no_real_parent_mrna_cds":
cds_results2 = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
print("Bad CDS Results 2:" + str(cds_results2))
self.assertTrue(len(cds_results2)>0)
test_count += 1
for feature in bad_relationships_genome["mrnas"]:
if feature["id"] == "no_real_parent_gene_mrna":
mrna_results1 = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
print("Bad mRNA Results 1:" + str(mrna_results1))
self.assertTrue(len(mrna_results1)>0)
test_count += 1
elif feature["id"] == "no_child_cds_mrna":
mrna_results2 = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
print("Bad mRNA Results 2:" + str(mrna_results2))
self.assertTrue(len(mrna_results2)>0)
test_count += 1
for feature in bad_relationships_genome["non_coding_features"]:
if feature["id"] == "no_real_parent_gene_nc":
NC_results1 = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
print("Bad NC Results 1:" + str(NC_results1))
self.assertTrue(len(NC_results1)>0)
test_count += 1
elif feature["id"] == "no_real_nc_child":
NC_results2 = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
print("Bad NC Results 2:" + str(NC_results2))
self.assertTrue(len(NC_results2)>0)
test_count += 1
self.assertTrue(test_count == 8,"Not all bad inividual feature relationships tested." + str(test_count))
def test_genome_relationships_good(self):
# Tests confirm_feature_relationships for Genome with only valid relationships.
with open('data/good_relationships.json') as json_file:
good_relationships_genome = json.load(json_file)
genome_results = GenomeUtils.confirm_genomes_feature_relationships(good_relationships_genome)
#print("Good Genome_results: " + str(genome_results))
self.assertTrue(len(genome_results) == 0)
def test_genome_relationships_bad(self):
# Tests confirm_feature_relationships for Genome with only valid relationships.
with open('data/bad_relationships.json') as json_file:
bad_relationships_genome = json.load(json_file)
genome_results = GenomeUtils.confirm_genomes_feature_relationships(bad_relationships_genome)
print("Bad Genome_results: " + str(genome_results))
self.assertTrue(len(genome_results) > 0) | test/utility/utils_data_integrity_test.py | import unittest
from configparser import ConfigParser
from os import environ
import logging
import json
import mock
from GenomeFileUtil.GenomeFileUtilImpl import GenomeFileUtil, SDKConfig
from GenomeFileUtil.GenomeFileUtilServer import MethodContext
from GenomeFileUtil.core.GenomeInterface import GenomeInterface
from GenomeFileUtil.core import GenomeUtils
from installed_clients.WorkspaceClient import Workspace as workspaceService
class GenomeFileUtilTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# logging.basicConfig(level=logging.info)
token = environ.get('KB_AUTH_TOKEN', None)
# WARNING: don't call any logging methods on the context object,
# it'll result in a NoneType error
cls.ctx = MethodContext(None)
cls.ctx.update({'token': token,
'provenance': [
{'service': 'GenomeFileUtil',
'method': 'please_never_use_it_in_production',
'method_params': []
}],
'authenticated': 1})
config_file = environ.get('KB_DEPLOYMENT_CONFIG', None)
cls.cfg = {}
config = ConfigParser()
config.read(config_file)
for nameval in config.items('GenomeFileUtil'):
cls.cfg[nameval[0]] = nameval[1]
cls.wsURL = cls.cfg['workspace-url']
cls.ws = workspaceService(cls.wsURL, token=token)
cls.serviceImpl = GenomeFileUtil(cls.cfg)
gi_config = SDKConfig(cls.cfg)
cls.genome_interface = GenomeInterface(gi_config)
@classmethod
def tearDownClass(cls):
pass
def test_non_unique_ids(self):
# Non unique ids
with open('data/non_unique_ids.json') as json_file:
non_unique_ids_genome = json.load(json_file)
uniqueness_results = GenomeUtils.check_feature_ids_uniqueness(non_unique_ids_genome)
self.assertTrue(len(uniqueness_results) > 0)
self.assertTrue(uniqueness_results == {'RL742_CDS_1': 2, 'RL4742_mRNA_2': 2, 'RL4742': 3})
def test_unique_ids(self):
# Unique ids.
with open('data/unique_ids.json') as json_file:
non_unique_ids_genome = json.load(json_file)
uniqueness_results = GenomeUtils.check_feature_ids_uniqueness(non_unique_ids_genome)
self.assertTrue(len(uniqueness_results) == 0)
def test_single_feature_relationships_good(self):
# Tests confirm_feature_relationships called separately for valid relationships.
test_count = 0
with open('data/good_relationships.json') as json_file:
good_relationships_genome = json.load(json_file)
feature_id_sets_dict = dict()
feature_lists = ["features","cdss","mrnas","non_coding_features"]
for feature_list in feature_lists:
if feature_list in good_relationships_genome:
feature_id_sets_dict[feature_list] = GenomeUtils.make_id_set(good_relationships_genome[feature_list])
else:
feature_id_sets_dict[feature_list] = set()
for feature in good_relationships_genome["features"]:
if feature["id"] == "RL4742":
gene_results = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
self.assertTrue(len(gene_results)==0)
test_count += 1
for feature in good_relationships_genome["cdss"]:
if feature["id"] == "RL742_CDS_1":
cds_results = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
self.assertTrue(len(cds_results)==0)
test_count += 1
for feature in good_relationships_genome["mrnas"]:
if feature["id"] == "RL742_mRNA_1":
mrna_results = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
self.assertTrue(len(mrna_results)==0)
test_count += 1
for feature in good_relationships_genome["non_coding_features"]:
if feature["id"] == "test_gene_1":
non_coding_parent_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_parent_results)==0)
test_count += 1
elif feature["id"] == "test_gene_1_tRNA_2":
non_coding_nc_child_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_nc_child_results)==0)
test_count += 1
elif feature["id"] == "RL4742_promoter":
non_coding_gene_child_results = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
self.assertTrue(len(non_coding_gene_child_results)==0)
test_count += 1
self.assertTrue(test_count == 6,"Not all good inividual feature relationships tested. " + str(test_count))
def test_single_feature_relationships_bad(self):
# Tests confirm_feature_relationships called separately for missing relationship targets.
with open('data/bad_relationships.json') as json_file:
bad_relationships_genome = json.load(json_file)
feature_id_sets_dict = dict()
feature_lists = ["features","cdss","mrnas","non_coding_features"]
for feature_list in feature_lists:
if feature_list in bad_relationships_genome:
feature_id_sets_dict[feature_list] = GenomeUtils.make_id_set(bad_relationships_genome[feature_list])
else:
feature_id_sets_dict[feature_list] = set()
test_count = 0
for feature in bad_relationships_genome["features"]:
if feature["id"] == "no_real_cds":
gene_results1 = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
print("Bad Gene Results 1:" + str(gene_results1))
self.assertTrue(len(gene_results1)>0)
test_count += 1
elif feature["id"] == "no_real_mrna":
gene_results2 = GenomeUtils.confirm_feature_relationships(feature,"features",feature_id_sets_dict)
print("Bad Gene Results 2:" + str(gene_results2))
self.assertTrue(len(gene_results2)>0)
test_count += 1
for feature in bad_relationships_genome["cdss"]:
if feature["id"] == "no_real_parent_gene_cds":
cds_results1 = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
print("Bad CDS Results 1:" + str(cds_results1))
self.assertTrue(len(cds_results1)>0)
test_count += 1
elif feature["id"] == "no_real_parent_mrna_cds":
cds_results2 = GenomeUtils.confirm_feature_relationships(feature,"cdss",feature_id_sets_dict)
print("Bad CDS Results 2:" + str(cds_results2))
self.assertTrue(len(cds_results2)>0)
test_count += 1
for feature in bad_relationships_genome["mrnas"]:
if feature["id"] == "no_real_parent_gene_mrna":
mrna_results1 = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
print("Bad mRNA Results 1:" + str(mrna_results1))
self.assertTrue(len(mrna_results1)>0)
test_count += 1
elif feature["id"] == "no_child_cds_mrna":
mrna_results2 = GenomeUtils.confirm_feature_relationships(feature,"mrnas",feature_id_sets_dict)
print("Bad mRNA Results 2:" + str(mrna_results2))
self.assertTrue(len(mrna_results2)>0)
test_count += 1
for feature in bad_relationships_genome["non_coding_features"]:
if feature["id"] == "no_real_parent_gene_nc":
NC_results1 = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
print("Bad NC Results 1:" + str(NC_results1))
self.assertTrue(len(NC_results1)>0)
test_count += 1
elif feature["id"] == "no_real_nc_child":
NC_results2 = GenomeUtils.confirm_feature_relationships(feature,"non_coding_features",feature_id_sets_dict)
print("Bad NC Results 2:" + str(NC_results2))
self.assertTrue(len(NC_results2)>0)
test_count += 1
self.assertTrue(test_count == 8,"Not all bad inividual feature relationships tested." + str(test_count))
def test_genome_relationships_good(self):
# Tests confirm_feature_relationships for Genome with only valid relationships.
with open('data/good_relationships.json') as json_file:
good_relationships_genome = json.load(json_file)
genome_results = GenomeUtils.confirm_genomes_feature_relationships(good_relationships_genome)
#print("Good Genome_results: " + str(genome_results))
self.assertTrue(len(genome_results) == 0)
def test_genome_relationships_bad(self):
# Tests confirm_feature_relationships for Genome with only valid relationships.
with open('data/bad_relationships.json') as json_file:
bad_relationships_genome = json.load(json_file)
genome_results = GenomeUtils.confirm_genomes_feature_relationships(bad_relationships_genome)
print("Bad Genome_results: " + str(genome_results))
self.assertTrue(len(genome_results) > 0) | 0.193033 | 0.187114 |
__author__ = 'stephen'
# ===============================================================================
# GLOBAL IMPORTS:
import os,sys
import numpy as np
import argparse
import time
# ===============================================================================
# LOCAL IMPORTS:
#HK_DataMiner_Path = os.path.relpath(os.pardir)
HK_DataMiner_Path = os.path.abspath("/Users/stephen/Dropbox/projects/work-2018.12/HK_DataMiner/")
#print HK_DataMiner_Path
sys.path.append(HK_DataMiner_Path)
from cluster import Faiss_DBSCAN
from utils import XTCReader, plot_cluster
# ===============================================================================
cli = argparse.ArgumentParser()
cli.add_argument('-t', '--trajListFns', default = 'trajlist',
help='List of trajectory files to read in, separated by spaces.')
cli.add_argument('-a', '--atomListFns', default='atom_indices',
help='List of atom index files to read in, separated by spaces.')
cli.add_argument('-g', '--topology', default='native.pdb', help='topology file.')
cli.add_argument('-o', '--homedir', help='Home dir.', default=".", type=str)
cli.add_argument('-e', '--iext', help='''The file extension of input trajectory
files. Must be a filetype that mdtraj.load() can recognize.''',
default="xtc", type=str)
cli.add_argument('-n', '--n_clusters', help='''n_clusters.''',
default=100, type=int)
cli.add_argument('-m', '--n_macro_states', help='''n_macro_states.''',
default=6, type=int)
cli.add_argument('-s', '--stride', help='stride.',
default=None, type=int)
args = cli.parse_args()
trajlistname = args.trajListFns
atom_indicesname = args.atomListFns
trajext = args.iext
File_TOP = args.topology
homedir = args.homedir
n_clusters = args.n_clusters
n_macro_states = args.n_macro_states
stride = args.stride
# ===========================================================================
# Reading Trajs from XTC files
#print "stride:", stride
#trajreader = XTCReader(trajlistname, atom_indicesname, homedir, trajext, File_TOP, nSubSample=stride)
#trajs = trajreader.trajs
#print(trajs)
#traj_len = trajreader.traj_len
#np.savetxt("./traj_len.txt", traj_len, fmt="%d")
if os.path.isfile("./phi_angles.txt") and os.path.isfile("./psi_angles.txt") is True:
phi_angles = np.loadtxt("./phi_angles.txt", dtype=np.float32)
psi_angles = np.loadtxt("./psi_angles.txt", dtype=np.float32)
else:
phi_angles, psi_angles = trajreader.get_phipsi(trajs, psi=[6, 8, 14, 16], phi=[4, 6, 8, 14])
#phi_angles, psi_angles = trajreader.get_phipsi(trajs, psi=[5, 7, 13, 15], phi=[3, 5, 7, 13])
np.savetxt("./phi_angles.txt", phi_angles, fmt="%f")
np.savetxt("./psi_angles.txt", psi_angles, fmt="%f")
phi_psi=np.column_stack((phi_angles, psi_angles))
print(phi_psi.shape)
# ===========================================================================
eps = 30.0
min_samples = 5
# ===========================================================================
# do Clustering using Faiss GPU DBSCAN method
'''
GPU_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples, metric="l2", GPU=False)
print(GPU_cluster)
GPU_cluster.fit(phi_psi)
#cluster.fit(trajs)
GPU_labels = GPU_cluster.labels_
print(GPU_labels)
n_microstates = len(set(GPU_labels)) - (1 if -1 in GPU_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "GPU_Faiss_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", GPU_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=GPU_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
'''
# ===========================================================================
# do Clustering using Faiss CPU DBSCAN method
CPU_IVFFlat_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples,nlist=100, nprobe=5, metric="l2", GPU=False, IVFFlat=True)
print(CPU_IVFFlat_cluster)
CPU_IVFFlat_cluster.fit(phi_psi)
#cluster.fit(trajs)
CPU_IVFFlat_labels = CPU_IVFFlat_cluster.labels_
print(CPU_IVFFlat_labels)
n_microstates = len(set(CPU_IVFFlat_labels)) - (1 if -1 in CPU_IVFFlat_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "CPU_Faiss_IVFFlat_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", CPU_IVFFlat_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=CPU_IVFFlat_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
# ===========================================================================
# do Clustering using Faiss CPU DBSCAN method
CPU_FlatL2_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples,nlist=100, nprobe=5, metric="l2", GPU=False, IVFFlat=False)
print(CPU_FlatL2_cluster)
CPU_FlatL2_cluster.fit(phi_psi)
#cluster.fit(trajs)
CPU_FlatL2_labels = CPU_FlatL2_cluster.labels_
print(CPU_FlatL2_labels)
n_microstates = len(set(CPU_FlatL2_labels)) - (1 if -1 in CPU_FlatL2_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "CPU_Faiss_FlatL2_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", CPU_FlatL2_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=CPU_FlatL2_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
# ===========================================================================
# do Clustering using Scikit-Learn DBSCAN method
from sklearn.cluster import DBSCAN
sk_cluster = DBSCAN(eps=eps, min_samples=min_samples, metric="l2")
t0 = time.time()
sk_cluster.fit(phi_psi)
t1 = time.time()
print("Scikit-Learn DBSCAN clustering Time Cost:", t1 - t0)
sk_labels = sk_cluster.labels_
print(sk_labels)
n_microstates = len(set(sk_labels)) - (1 if -1 in sk_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "Sklearn_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", sk_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=sk_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name) | hkdataminer/scripts/test_faiss_dbscan_old.py | __author__ = 'stephen'
# ===============================================================================
# GLOBAL IMPORTS:
import os,sys
import numpy as np
import argparse
import time
# ===============================================================================
# LOCAL IMPORTS:
#HK_DataMiner_Path = os.path.relpath(os.pardir)
HK_DataMiner_Path = os.path.abspath("/Users/stephen/Dropbox/projects/work-2018.12/HK_DataMiner/")
#print HK_DataMiner_Path
sys.path.append(HK_DataMiner_Path)
from cluster import Faiss_DBSCAN
from utils import XTCReader, plot_cluster
# ===============================================================================
cli = argparse.ArgumentParser()
cli.add_argument('-t', '--trajListFns', default = 'trajlist',
help='List of trajectory files to read in, separated by spaces.')
cli.add_argument('-a', '--atomListFns', default='atom_indices',
help='List of atom index files to read in, separated by spaces.')
cli.add_argument('-g', '--topology', default='native.pdb', help='topology file.')
cli.add_argument('-o', '--homedir', help='Home dir.', default=".", type=str)
cli.add_argument('-e', '--iext', help='''The file extension of input trajectory
files. Must be a filetype that mdtraj.load() can recognize.''',
default="xtc", type=str)
cli.add_argument('-n', '--n_clusters', help='''n_clusters.''',
default=100, type=int)
cli.add_argument('-m', '--n_macro_states', help='''n_macro_states.''',
default=6, type=int)
cli.add_argument('-s', '--stride', help='stride.',
default=None, type=int)
args = cli.parse_args()
trajlistname = args.trajListFns
atom_indicesname = args.atomListFns
trajext = args.iext
File_TOP = args.topology
homedir = args.homedir
n_clusters = args.n_clusters
n_macro_states = args.n_macro_states
stride = args.stride
# ===========================================================================
# Reading Trajs from XTC files
#print "stride:", stride
#trajreader = XTCReader(trajlistname, atom_indicesname, homedir, trajext, File_TOP, nSubSample=stride)
#trajs = trajreader.trajs
#print(trajs)
#traj_len = trajreader.traj_len
#np.savetxt("./traj_len.txt", traj_len, fmt="%d")
if os.path.isfile("./phi_angles.txt") and os.path.isfile("./psi_angles.txt") is True:
phi_angles = np.loadtxt("./phi_angles.txt", dtype=np.float32)
psi_angles = np.loadtxt("./psi_angles.txt", dtype=np.float32)
else:
phi_angles, psi_angles = trajreader.get_phipsi(trajs, psi=[6, 8, 14, 16], phi=[4, 6, 8, 14])
#phi_angles, psi_angles = trajreader.get_phipsi(trajs, psi=[5, 7, 13, 15], phi=[3, 5, 7, 13])
np.savetxt("./phi_angles.txt", phi_angles, fmt="%f")
np.savetxt("./psi_angles.txt", psi_angles, fmt="%f")
phi_psi=np.column_stack((phi_angles, psi_angles))
print(phi_psi.shape)
# ===========================================================================
eps = 30.0
min_samples = 5
# ===========================================================================
# do Clustering using Faiss GPU DBSCAN method
'''
GPU_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples, metric="l2", GPU=False)
print(GPU_cluster)
GPU_cluster.fit(phi_psi)
#cluster.fit(trajs)
GPU_labels = GPU_cluster.labels_
print(GPU_labels)
n_microstates = len(set(GPU_labels)) - (1 if -1 in GPU_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "GPU_Faiss_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", GPU_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=GPU_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
'''
# ===========================================================================
# do Clustering using Faiss CPU DBSCAN method
CPU_IVFFlat_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples,nlist=100, nprobe=5, metric="l2", GPU=False, IVFFlat=True)
print(CPU_IVFFlat_cluster)
CPU_IVFFlat_cluster.fit(phi_psi)
#cluster.fit(trajs)
CPU_IVFFlat_labels = CPU_IVFFlat_cluster.labels_
print(CPU_IVFFlat_labels)
n_microstates = len(set(CPU_IVFFlat_labels)) - (1 if -1 in CPU_IVFFlat_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "CPU_Faiss_IVFFlat_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", CPU_IVFFlat_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=CPU_IVFFlat_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
# ===========================================================================
# do Clustering using Faiss CPU DBSCAN method
CPU_FlatL2_cluster = Faiss_DBSCAN(eps=eps, min_samples=min_samples,nlist=100, nprobe=5, metric="l2", GPU=False, IVFFlat=False)
print(CPU_FlatL2_cluster)
CPU_FlatL2_cluster.fit(phi_psi)
#cluster.fit(trajs)
CPU_FlatL2_labels = CPU_FlatL2_cluster.labels_
print(CPU_FlatL2_labels)
n_microstates = len(set(CPU_FlatL2_labels)) - (1 if -1 in CPU_FlatL2_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "CPU_Faiss_FlatL2_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", CPU_FlatL2_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=CPU_FlatL2_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name)
# ===========================================================================
# do Clustering using Scikit-Learn DBSCAN method
from sklearn.cluster import DBSCAN
sk_cluster = DBSCAN(eps=eps, min_samples=min_samples, metric="l2")
t0 = time.time()
sk_cluster.fit(phi_psi)
t1 = time.time()
print("Scikit-Learn DBSCAN clustering Time Cost:", t1 - t0)
sk_labels = sk_cluster.labels_
print(sk_labels)
n_microstates = len(set(sk_labels)) - (1 if -1 in sk_labels else 0)
print('Estimated number of clusters: %d' % n_microstates)
#cluster_centers_ = cluster.cluster_centers_
# plot micro states
clustering_name = "Sklearn_dbscan_n_" + str(n_microstates)
np.savetxt("assignments_"+clustering_name+".txt", sk_labels, fmt="%d")
#np.savetxt("cluster_centers_"+clustering_name+".txt", cluster_centers_, fmt="%d")
plot_cluster(labels=sk_labels, phi_angles=phi_angles, psi_angles=psi_angles, name=clustering_name) | 0.418222 | 0.121217 |
import numpy as np
import warnings
import copy
import numpy as np
import numpy.random as ra
from astropy import log
from astropy.logger import AstropyUserWarning
from .utils import njit
__all__ = ['Window1D', 'Optimal1D']
class Window1D(object):
"""
Make a top hat filter (window function) for power spectrum or cross
spectrum. It assumes that the first model is the QPO component
Lorentzian model.
Parameters
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
Attributes
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
x_o: Parameter class instance
Centroid of Lorentzian model.
fwhm: Parameter class instance
Full width at half maximum of Lorentzian model.
"""
def __init__(self, model):
self.model = model
self.x_0 = model[0].x_0
self.fwhm = model[0].fwhm
def __call__(self, x):
y = np.zeros((len(x),), dtype=np.float64)
for i in range(len(x)):
if np.abs(x[i] - self.x_0[0]) <= self.fwhm[0] / 2:
y[i] = 1.
return y
class Optimal1D(object):
"""
Make a optimal filter for power spectrum or cross spectrum.
It assumes that the first model is the QPO component.
Parameters
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
Attributes
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
filter: astropy.modeling.models class instance
It s the ratio of QPO component to the model fit to the spectrum.
"""
def __init__(self, model):
self.model = model
qpo_component_model = self.model[0]
all_components_model = self.model
self.filter = qpo_component_model / all_components_model
def __call__(self, x):
return self.filter(x)
def _paralyzable_dead_time(event_list, dead_time):
"""Apply paralyzable dead time to an event list.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time: float
Dead time (single value)
Returns
-------
output_event_list : array of floats
Filtered event times
mask : array of bools
Final mask, showing all good events in the original event list.
"""
mask = np.ones(len(event_list), dtype=bool)
dead_time_end = event_list + dead_time
bad = dead_time_end[:-1] > event_list[1:]
# Easy: paralyzable case. Here, events coming during dead time produce
# more dead time. So...
mask[1:][bad] = False
return event_list[mask], mask
@njit()
def _nonpar_core(event_list, dead_time_end, mask):
"""Numba-compiled core of the non-paralyzable dead time calculation.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time_end : array of floats
End of the dead time of each event
mask : array of bools
Final mask of good events. Initially, all entries must be ``True``
Return
------
mask : array of bools
Final mask of good events
"""
for i in range(1, len(event_list)):
if (event_list[i] < dead_time_end[i - 1]):
dead_time_end[i] = dead_time_end[i - 1]
mask[i] = False
return mask
def _non_paralyzable_dead_time(event_list, dead_time):
"""Apply non-paralyzable dead time to an event list.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time: float
Dead time (single value)
Returns
-------
output_event_list : array of floats
Filtered event times
mask : array of bools
Final mask, showing all good events in the original event list.
"""
event_list_dbl = (event_list - event_list[0]).astype(np.double)
dead_time_end = event_list_dbl + np.double(dead_time)
mask = np.ones(event_list_dbl.size, dtype=bool)
mask = _nonpar_core(event_list_dbl, dead_time_end, mask)
return event_list[mask], mask
class DeadtimeFilterOutput(object):
uf_events = None
is_event = None
deadtime = None
mask = None
bkg = None
def get_deadtime_mask(ev_list, deadtime, bkg_ev_list=None,
dt_sigma=None, paralyzable=False,
return_all=False, verbose=False):
"""Filter an event list for a given dead time.
Parameters
----------
ev_list : array-like
The event list
deadtime: float
The (mean, if not constant) value of deadtime
Other Parameters
----------------
bkg_ev_list : array-like
A background event list that affects dead time
dt_sigma : float
If specified, dead time will not have a single value but it will have
a normal distribution with mean ``deadtime`` and standard deviation
``dt_sigma``.
Returns
-------
mask : array-like, optional
The mask that filters the input event list and produces the output
event list.
additional_output : object
Object with all the following attributes. Only returned if
`return_all` is True
uf_events : array-like
Unfiltered event list (events + background)
is_event : array-like
Boolean values; True if event, False if background
deadtime : array-like
Dead time values
bkg : array-like
The filtered background event list
"""
additional_output = DeadtimeFilterOutput()
# Create the total lightcurve, and a "kind" array that keeps track
# of the events classified as "signal" (True) and "background" (False)
if bkg_ev_list is not None:
tot_ev_list = np.append(ev_list, bkg_ev_list)
ev_kind = np.append(np.ones(len(ev_list), dtype=bool),
np.zeros(len(bkg_ev_list), dtype=bool))
order = np.argsort(tot_ev_list)
tot_ev_list = tot_ev_list[order]
ev_kind = ev_kind[order]
del order
else:
tot_ev_list = ev_list
ev_kind = np.ones(len(ev_list), dtype=bool)
additional_output.uf_events = tot_ev_list
additional_output.is_event = ev_kind
additional_output.deadtime = deadtime
additional_output.uf_mask = np.ones(tot_ev_list.size, dtype=bool)
additional_output.bkg = tot_ev_list[np.logical_not(ev_kind)]
if deadtime <= 0.:
if deadtime < 0:
raise ValueError("Dead time is less than 0. Please check.")
retval = [np.ones(ev_list.size, dtype=bool), additional_output]
return retval
nevents = len(tot_ev_list)
all_ev_kind = ev_kind.copy()
if dt_sigma is not None:
deadtime_values = ra.normal(deadtime, dt_sigma, nevents)
deadtime_values[deadtime_values < 0] = 0.
else:
deadtime_values = np.zeros(nevents) + deadtime
initial_len = len(tot_ev_list)
# Note: saved_mask gives the mask that produces tot_ev_list_filt from
# tot_ev_list. The same mask can be used to also filter all other arrays.
if paralyzable:
tot_ev_list_filt, saved_mask = \
_paralyzable_dead_time(tot_ev_list, deadtime_values)
else:
tot_ev_list_filt, saved_mask = \
_non_paralyzable_dead_time(tot_ev_list, deadtime_values)
del tot_ev_list
ev_kind = ev_kind[saved_mask]
deadtime_values = deadtime_values[saved_mask]
final_len = tot_ev_list_filt.size
if verbose:
log.info(
'filter_for_deadtime: '
'{0}/{1} events rejected'.format(initial_len - final_len,
initial_len))
retval = saved_mask[all_ev_kind]
if return_all:
# uf_events: source and background events together
# ev_kind : kind of each event in uf_events.
# bkg : Background events
additional_output.uf_events = tot_ev_list_filt
additional_output.is_event = ev_kind
additional_output.deadtime = deadtime_values
additional_output.bkg = tot_ev_list_filt[np.logical_not(ev_kind)]
retval = [retval, additional_output]
return retval
def filter_for_deadtime(event_list, deadtime, **kwargs):
"""Filter an event list for a given dead time.
This function accepts either a list of times or a
`stingray.events.EventList` object.
For the complete optional parameter list, see `get_deadtime_mask`
Parameters
----------
ev_list : array-like or class:`stingray.events.EventList`
The event list
deadtime: float
The (mean, if not constant) value of deadtime
Returns
-------
new_ev_list : class:`stingray.events.EventList` object
The filtered event list
additional_output : dict
See `get_deadtime_mask`
"""
# Need to import here to avoid circular imports in the top module.
from stingray.events import EventList
local_retall = kwargs.pop('return_all', False)
if isinstance(event_list, EventList):
retval = event_list.apply_deadtime(deadtime, return_all=local_retall,
**kwargs)
else:
mask, retall = get_deadtime_mask(event_list, deadtime, return_all=True,
**kwargs)
retval = event_list[mask]
if local_retall:
retval = [retval, retall]
return retval | stingray/filters.py | import numpy as np
import warnings
import copy
import numpy as np
import numpy.random as ra
from astropy import log
from astropy.logger import AstropyUserWarning
from .utils import njit
__all__ = ['Window1D', 'Optimal1D']
class Window1D(object):
"""
Make a top hat filter (window function) for power spectrum or cross
spectrum. It assumes that the first model is the QPO component
Lorentzian model.
Parameters
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
Attributes
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
x_o: Parameter class instance
Centroid of Lorentzian model.
fwhm: Parameter class instance
Full width at half maximum of Lorentzian model.
"""
def __init__(self, model):
self.model = model
self.x_0 = model[0].x_0
self.fwhm = model[0].fwhm
def __call__(self, x):
y = np.zeros((len(x),), dtype=np.float64)
for i in range(len(x)):
if np.abs(x[i] - self.x_0[0]) <= self.fwhm[0] / 2:
y[i] = 1.
return y
class Optimal1D(object):
"""
Make a optimal filter for power spectrum or cross spectrum.
It assumes that the first model is the QPO component.
Parameters
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
Attributes
----------
model: astropy.modeling.models class instance
The compound model fit to the spectrum.
filter: astropy.modeling.models class instance
It s the ratio of QPO component to the model fit to the spectrum.
"""
def __init__(self, model):
self.model = model
qpo_component_model = self.model[0]
all_components_model = self.model
self.filter = qpo_component_model / all_components_model
def __call__(self, x):
return self.filter(x)
def _paralyzable_dead_time(event_list, dead_time):
"""Apply paralyzable dead time to an event list.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time: float
Dead time (single value)
Returns
-------
output_event_list : array of floats
Filtered event times
mask : array of bools
Final mask, showing all good events in the original event list.
"""
mask = np.ones(len(event_list), dtype=bool)
dead_time_end = event_list + dead_time
bad = dead_time_end[:-1] > event_list[1:]
# Easy: paralyzable case. Here, events coming during dead time produce
# more dead time. So...
mask[1:][bad] = False
return event_list[mask], mask
@njit()
def _nonpar_core(event_list, dead_time_end, mask):
"""Numba-compiled core of the non-paralyzable dead time calculation.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time_end : array of floats
End of the dead time of each event
mask : array of bools
Final mask of good events. Initially, all entries must be ``True``
Return
------
mask : array of bools
Final mask of good events
"""
for i in range(1, len(event_list)):
if (event_list[i] < dead_time_end[i - 1]):
dead_time_end[i] = dead_time_end[i - 1]
mask[i] = False
return mask
def _non_paralyzable_dead_time(event_list, dead_time):
"""Apply non-paralyzable dead time to an event list.
Parameters
----------
event_list : array of floats
Event times of arrival
dead_time: float
Dead time (single value)
Returns
-------
output_event_list : array of floats
Filtered event times
mask : array of bools
Final mask, showing all good events in the original event list.
"""
event_list_dbl = (event_list - event_list[0]).astype(np.double)
dead_time_end = event_list_dbl + np.double(dead_time)
mask = np.ones(event_list_dbl.size, dtype=bool)
mask = _nonpar_core(event_list_dbl, dead_time_end, mask)
return event_list[mask], mask
class DeadtimeFilterOutput(object):
uf_events = None
is_event = None
deadtime = None
mask = None
bkg = None
def get_deadtime_mask(ev_list, deadtime, bkg_ev_list=None,
dt_sigma=None, paralyzable=False,
return_all=False, verbose=False):
"""Filter an event list for a given dead time.
Parameters
----------
ev_list : array-like
The event list
deadtime: float
The (mean, if not constant) value of deadtime
Other Parameters
----------------
bkg_ev_list : array-like
A background event list that affects dead time
dt_sigma : float
If specified, dead time will not have a single value but it will have
a normal distribution with mean ``deadtime`` and standard deviation
``dt_sigma``.
Returns
-------
mask : array-like, optional
The mask that filters the input event list and produces the output
event list.
additional_output : object
Object with all the following attributes. Only returned if
`return_all` is True
uf_events : array-like
Unfiltered event list (events + background)
is_event : array-like
Boolean values; True if event, False if background
deadtime : array-like
Dead time values
bkg : array-like
The filtered background event list
"""
additional_output = DeadtimeFilterOutput()
# Create the total lightcurve, and a "kind" array that keeps track
# of the events classified as "signal" (True) and "background" (False)
if bkg_ev_list is not None:
tot_ev_list = np.append(ev_list, bkg_ev_list)
ev_kind = np.append(np.ones(len(ev_list), dtype=bool),
np.zeros(len(bkg_ev_list), dtype=bool))
order = np.argsort(tot_ev_list)
tot_ev_list = tot_ev_list[order]
ev_kind = ev_kind[order]
del order
else:
tot_ev_list = ev_list
ev_kind = np.ones(len(ev_list), dtype=bool)
additional_output.uf_events = tot_ev_list
additional_output.is_event = ev_kind
additional_output.deadtime = deadtime
additional_output.uf_mask = np.ones(tot_ev_list.size, dtype=bool)
additional_output.bkg = tot_ev_list[np.logical_not(ev_kind)]
if deadtime <= 0.:
if deadtime < 0:
raise ValueError("Dead time is less than 0. Please check.")
retval = [np.ones(ev_list.size, dtype=bool), additional_output]
return retval
nevents = len(tot_ev_list)
all_ev_kind = ev_kind.copy()
if dt_sigma is not None:
deadtime_values = ra.normal(deadtime, dt_sigma, nevents)
deadtime_values[deadtime_values < 0] = 0.
else:
deadtime_values = np.zeros(nevents) + deadtime
initial_len = len(tot_ev_list)
# Note: saved_mask gives the mask that produces tot_ev_list_filt from
# tot_ev_list. The same mask can be used to also filter all other arrays.
if paralyzable:
tot_ev_list_filt, saved_mask = \
_paralyzable_dead_time(tot_ev_list, deadtime_values)
else:
tot_ev_list_filt, saved_mask = \
_non_paralyzable_dead_time(tot_ev_list, deadtime_values)
del tot_ev_list
ev_kind = ev_kind[saved_mask]
deadtime_values = deadtime_values[saved_mask]
final_len = tot_ev_list_filt.size
if verbose:
log.info(
'filter_for_deadtime: '
'{0}/{1} events rejected'.format(initial_len - final_len,
initial_len))
retval = saved_mask[all_ev_kind]
if return_all:
# uf_events: source and background events together
# ev_kind : kind of each event in uf_events.
# bkg : Background events
additional_output.uf_events = tot_ev_list_filt
additional_output.is_event = ev_kind
additional_output.deadtime = deadtime_values
additional_output.bkg = tot_ev_list_filt[np.logical_not(ev_kind)]
retval = [retval, additional_output]
return retval
def filter_for_deadtime(event_list, deadtime, **kwargs):
"""Filter an event list for a given dead time.
This function accepts either a list of times or a
`stingray.events.EventList` object.
For the complete optional parameter list, see `get_deadtime_mask`
Parameters
----------
ev_list : array-like or class:`stingray.events.EventList`
The event list
deadtime: float
The (mean, if not constant) value of deadtime
Returns
-------
new_ev_list : class:`stingray.events.EventList` object
The filtered event list
additional_output : dict
See `get_deadtime_mask`
"""
# Need to import here to avoid circular imports in the top module.
from stingray.events import EventList
local_retall = kwargs.pop('return_all', False)
if isinstance(event_list, EventList):
retval = event_list.apply_deadtime(deadtime, return_all=local_retall,
**kwargs)
else:
mask, retall = get_deadtime_mask(event_list, deadtime, return_all=True,
**kwargs)
retval = event_list[mask]
if local_retall:
retval = [retval, retall]
return retval | 0.84039 | 0.449634 |
from __future__ import unicode_literals
import io
from os import path
try:
from pip.req import parse_requirements
except ImportError:
# pip >= 10
from pip._internal.req import parse_requirements
from setuptools import find_packages, setup
def get_requirements(requirements_file):
"""Use pip to parse requirements file."""
requirements = []
if path.isfile(requirements_file):
for req in parse_requirements(requirements_file, session="hack"):
if req.markers:
requirements.append("%s;%s" % (req.req, req.markers))
else:
requirements.append("%s" % req.req)
return requirements
if __name__ == "__main__":
HERE = path.abspath(path.dirname(__file__))
INSTALL_REQUIRES = get_requirements(path.join(HERE, "requirements.txt"))
MYSQL_REQUIRES = get_requirements(path.join(HERE, "mysql-requirements.txt"))
POSTGRESQL_REQUIRES = get_requirements(
path.join(HERE, "postgresql-requirements.txt"))
LDAP_REQUIRES = get_requirements(path.join(HERE, "ldap-requirements.txt"))
with io.open(path.join(HERE, "README.rst"), encoding="utf-8") as readme:
LONG_DESCRIPTION = readme.read()
setup(
name="modoboa",
description="Mail hosting made simple",
long_description=LONG_DESCRIPTION,
license="ISC",
url="http://modoboa.org/",
author="<NAME>",
author_email="<EMAIL>",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django :: 1.11",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Communications :: Email",
"Topic :: Internet :: WWW/HTTP",
],
keywords="email",
packages=find_packages(exclude=["doc", "test_data", "test_project"]),
include_package_data=True,
zip_safe=False,
scripts=["bin/modoboa-admin.py"],
install_requires=INSTALL_REQUIRES,
use_scm_version=True,
setup_requires=["setuptools_scm"],
extras_require={
"ldap": LDAP_REQUIRES,
"mysql": MYSQL_REQUIRES,
"postgresql": POSTGRESQL_REQUIRES,
"argon2": ["argon2-cffi >= 16.1.0"],
},
) | setup.py | from __future__ import unicode_literals
import io
from os import path
try:
from pip.req import parse_requirements
except ImportError:
# pip >= 10
from pip._internal.req import parse_requirements
from setuptools import find_packages, setup
def get_requirements(requirements_file):
"""Use pip to parse requirements file."""
requirements = []
if path.isfile(requirements_file):
for req in parse_requirements(requirements_file, session="hack"):
if req.markers:
requirements.append("%s;%s" % (req.req, req.markers))
else:
requirements.append("%s" % req.req)
return requirements
if __name__ == "__main__":
HERE = path.abspath(path.dirname(__file__))
INSTALL_REQUIRES = get_requirements(path.join(HERE, "requirements.txt"))
MYSQL_REQUIRES = get_requirements(path.join(HERE, "mysql-requirements.txt"))
POSTGRESQL_REQUIRES = get_requirements(
path.join(HERE, "postgresql-requirements.txt"))
LDAP_REQUIRES = get_requirements(path.join(HERE, "ldap-requirements.txt"))
with io.open(path.join(HERE, "README.rst"), encoding="utf-8") as readme:
LONG_DESCRIPTION = readme.read()
setup(
name="modoboa",
description="Mail hosting made simple",
long_description=LONG_DESCRIPTION,
license="ISC",
url="http://modoboa.org/",
author="<NAME>",
author_email="<EMAIL>",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django :: 1.11",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: ISC License (ISCL)",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Communications :: Email",
"Topic :: Internet :: WWW/HTTP",
],
keywords="email",
packages=find_packages(exclude=["doc", "test_data", "test_project"]),
include_package_data=True,
zip_safe=False,
scripts=["bin/modoboa-admin.py"],
install_requires=INSTALL_REQUIRES,
use_scm_version=True,
setup_requires=["setuptools_scm"],
extras_require={
"ldap": LDAP_REQUIRES,
"mysql": MYSQL_REQUIRES,
"postgresql": POSTGRESQL_REQUIRES,
"argon2": ["argon2-cffi >= 16.1.0"],
},
) | 0.437824 | 0.104569 |
import json
import logging
import ckan.plugins as p
try:
# CKAN 2.7 and later
from ckan.common import config
except ImportError:
# CKAN 2.6 and earlier
from pylons import config
log = logging.getLogger(__name__)
ignore_empty = p.toolkit.get_validator('ignore_empty')
DEFAULT_AGS_FORMATS = ['ags', 'esri rest']
def ags_view_default_basemap_url():
return config.get('ckanext.ags_view_default_basemap_url', '')
def ags_view_proxy():
return config.get('ckanext.ags_view_proxy', '')
def with_proxy(url):
text = url
proxies = json.loads(ags_view_proxy())
for p in proxies:
text = text.replace(p, proxies[p])
return text
class AGSFSView(p.SingletonPlugin):
'''This plugin makes views of arcgis FeatureServer services'''
p.implements(p.IConfigurer, inherit=True)
p.implements(p.IResourceView, inherit=True)
p.implements(p.ITemplateHelpers, inherit=True)
# IConfigurer
def update_config(self, config):
p.toolkit.add_public_directory(config, 'public')
p.toolkit.add_template_directory(config, 'templates')
p.toolkit.add_resource('public', 'ckanext-agsview')
# IResourceView
def can_view(self, data_dict):
return (data_dict['resource'].get('format', '').lower()
in DEFAULT_AGS_FORMATS)
def view_template(self, context, data_dict):
return 'ags_fs_view.html'
def form_template(self, context, data_dict):
return 'ags_fs_form.html'
def info(self):
return {'name': 'ags_fs_view',
'title': p.toolkit._('ArcGIS FeatureServer Service'),
'icon': 'compass',
'schema': {
'ags_url': [ignore_empty, unicode],
'basemap_url': [ignore_empty, unicode]
},
'iframed': False,
'default_title': p.toolkit._('ArcGIS FeatureServer Service'),
}
# ITemplateHelpers
def get_helpers(self):
h = {'ags_view_default_basemap_url': ags_view_default_basemap_url,
'ags_view_proxy': ags_view_proxy,
'with_proxy': with_proxy}
return h
class AGSMSView(p.SingletonPlugin):
'''This plugin makes views of arcgis MapServer services'''
p.implements(p.IConfigurer, inherit=True)
p.implements(p.IResourceView, inherit=True)
def update_config(self, config):
p.toolkit.add_public_directory(config, 'public')
p.toolkit.add_template_directory(config, 'templates')
p.toolkit.add_resource('public', 'ckanext-agsview')
def info(self):
return {'name': 'ags_ms_view',
'title': p.toolkit._('ArcGIS MapServer Service'),
'icon': 'compass',
'schema': {
'ags_url': [ignore_empty, unicode],
'basemap_url': [ignore_empty, unicode],
'layer_ids': [ignore_empty, unicode]
},
'iframed': False,
'default_title': p.toolkit._('ArcGIS MapServer Service'),
}
def can_view(self, data_dict):
return (data_dict['resource'].get('format', '').lower()
in DEFAULT_AGS_FORMATS)
def view_template(self, context, data_dict):
return 'ags_ms_view.html'
def form_template(self, context, data_dict):
return 'ags_ms_form.html' | ckanext/agsview/plugin.py | import json
import logging
import ckan.plugins as p
try:
# CKAN 2.7 and later
from ckan.common import config
except ImportError:
# CKAN 2.6 and earlier
from pylons import config
log = logging.getLogger(__name__)
ignore_empty = p.toolkit.get_validator('ignore_empty')
DEFAULT_AGS_FORMATS = ['ags', 'esri rest']
def ags_view_default_basemap_url():
return config.get('ckanext.ags_view_default_basemap_url', '')
def ags_view_proxy():
return config.get('ckanext.ags_view_proxy', '')
def with_proxy(url):
text = url
proxies = json.loads(ags_view_proxy())
for p in proxies:
text = text.replace(p, proxies[p])
return text
class AGSFSView(p.SingletonPlugin):
'''This plugin makes views of arcgis FeatureServer services'''
p.implements(p.IConfigurer, inherit=True)
p.implements(p.IResourceView, inherit=True)
p.implements(p.ITemplateHelpers, inherit=True)
# IConfigurer
def update_config(self, config):
p.toolkit.add_public_directory(config, 'public')
p.toolkit.add_template_directory(config, 'templates')
p.toolkit.add_resource('public', 'ckanext-agsview')
# IResourceView
def can_view(self, data_dict):
return (data_dict['resource'].get('format', '').lower()
in DEFAULT_AGS_FORMATS)
def view_template(self, context, data_dict):
return 'ags_fs_view.html'
def form_template(self, context, data_dict):
return 'ags_fs_form.html'
def info(self):
return {'name': 'ags_fs_view',
'title': p.toolkit._('ArcGIS FeatureServer Service'),
'icon': 'compass',
'schema': {
'ags_url': [ignore_empty, unicode],
'basemap_url': [ignore_empty, unicode]
},
'iframed': False,
'default_title': p.toolkit._('ArcGIS FeatureServer Service'),
}
# ITemplateHelpers
def get_helpers(self):
h = {'ags_view_default_basemap_url': ags_view_default_basemap_url,
'ags_view_proxy': ags_view_proxy,
'with_proxy': with_proxy}
return h
class AGSMSView(p.SingletonPlugin):
'''This plugin makes views of arcgis MapServer services'''
p.implements(p.IConfigurer, inherit=True)
p.implements(p.IResourceView, inherit=True)
def update_config(self, config):
p.toolkit.add_public_directory(config, 'public')
p.toolkit.add_template_directory(config, 'templates')
p.toolkit.add_resource('public', 'ckanext-agsview')
def info(self):
return {'name': 'ags_ms_view',
'title': p.toolkit._('ArcGIS MapServer Service'),
'icon': 'compass',
'schema': {
'ags_url': [ignore_empty, unicode],
'basemap_url': [ignore_empty, unicode],
'layer_ids': [ignore_empty, unicode]
},
'iframed': False,
'default_title': p.toolkit._('ArcGIS MapServer Service'),
}
def can_view(self, data_dict):
return (data_dict['resource'].get('format', '').lower()
in DEFAULT_AGS_FORMATS)
def view_template(self, context, data_dict):
return 'ags_ms_view.html'
def form_template(self, context, data_dict):
return 'ags_ms_form.html' | 0.435902 | 0.162081 |
# This file provides some classes for setting up (partially-populated)
# homeservers; either as a full homeserver as a real application, or a small
# partial one for unit test mocking.
# Imports required for the default HomeServer() implementation
import abc
import logging
import os
from twisted.mail.smtp import sendmail
from synapse.api.auth import Auth
from synapse.api.filtering import Filtering
from synapse.api.ratelimiting import Ratelimiter
from synapse.appservice.api import ApplicationServiceApi
from synapse.appservice.scheduler import ApplicationServiceScheduler
from synapse.config.homeserver import HomeServerConfig
from synapse.crypto import context_factory
from synapse.crypto.context_factory import RegularPolicyForHTTPS
from synapse.crypto.keyring import Keyring
from synapse.events.builder import EventBuilderFactory
from synapse.events.spamcheck import SpamChecker
from synapse.events.third_party_rules import ThirdPartyEventRules
from synapse.events.utils import EventClientSerializer
from synapse.federation.federation_client import FederationClient
from synapse.federation.federation_server import (
FederationHandlerRegistry,
FederationServer,
ReplicationFederationHandlerRegistry,
)
from synapse.federation.send_queue import FederationRemoteSendQueue
from synapse.federation.sender import FederationSender
from synapse.federation.transport.client import TransportLayerClient
from synapse.groups.attestations import GroupAttestationSigning, GroupAttestionRenewer
from synapse.groups.groups_server import GroupsServerHandler, GroupsServerWorkerHandler
from synapse.handlers import Handlers
from synapse.handlers.account_validity import AccountValidityHandler
from synapse.handlers.acme import AcmeHandler
from synapse.handlers.appservice import ApplicationServicesHandler
from synapse.handlers.auth import AuthHandler, MacaroonGenerator
from synapse.handlers.cas_handler import CasHandler
from synapse.handlers.deactivate_account import DeactivateAccountHandler
from synapse.handlers.device import DeviceHandler, DeviceWorkerHandler
from synapse.handlers.devicemessage import DeviceMessageHandler
from synapse.handlers.e2e_keys import E2eKeysHandler
from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
from synapse.handlers.events import EventHandler, EventStreamHandler
from synapse.handlers.groups_local import GroupsLocalHandler, GroupsLocalWorkerHandler
from synapse.handlers.initial_sync import InitialSyncHandler
from synapse.handlers.message import EventCreationHandler, MessageHandler
from synapse.handlers.pagination import PaginationHandler
from synapse.handlers.password_policy import PasswordPolicyHandler
from synapse.handlers.presence import PresenceHandler
from synapse.handlers.profile import BaseProfileHandler, MasterProfileHandler
from synapse.handlers.read_marker import ReadMarkerHandler
from synapse.handlers.receipts import ReceiptsHandler
from synapse.handlers.register import RegistrationHandler
from synapse.handlers.room import RoomContextHandler, RoomCreationHandler
from synapse.handlers.room_list import RoomListHandler
from synapse.handlers.room_member import RoomMemberMasterHandler
from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
from synapse.handlers.set_password import SetPasswordHandler
from synapse.handlers.stats import StatsHandler
from synapse.handlers.sync import SyncHandler
from synapse.handlers.typing import TypingHandler
from synapse.handlers.user_directory import UserDirectoryHandler
from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
from synapse.http.matrixfederationclient import MatrixFederationHttpClient
from synapse.notifier import Notifier
from synapse.push.action_generator import ActionGenerator
from synapse.push.pusherpool import PusherPool
from synapse.replication.tcp.client import ReplicationDataHandler
from synapse.replication.tcp.handler import ReplicationCommandHandler
from synapse.replication.tcp.resource import ReplicationStreamer
from synapse.replication.tcp.streams import STREAMS_MAP
from synapse.rest.media.v1.media_repository import (
MediaRepository,
MediaRepositoryResource,
)
from synapse.secrets import Secrets
from synapse.server_notices.server_notices_manager import ServerNoticesManager
from synapse.server_notices.server_notices_sender import ServerNoticesSender
from synapse.server_notices.worker_server_notices_sender import (
WorkerServerNoticesSender,
)
from synapse.state import StateHandler, StateResolutionHandler
from synapse.storage import DataStores, Storage
from synapse.streams.events import EventSources
from synapse.util import Clock
from synapse.util.distributor import Distributor
from synapse.util.stringutils import random_string
logger = logging.getLogger(__name__)
class HomeServer(object):
"""A basic homeserver object without lazy component builders.
This will need all of the components it requires to either be passed as
constructor arguments, or the relevant methods overriding to create them.
Typically this would only be used for unit tests.
For every dependency in the DEPENDENCIES list below, this class creates one
method,
def get_DEPENDENCY(self)
which returns the value of that dependency. If no value has yet been set
nor was provided to the constructor, it will attempt to call a lazy builder
method called
def build_DEPENDENCY(self)
which must be implemented by the subclass. This code may call any of the
required "get" methods on the instance to obtain the sub-dependencies that
one requires.
Attributes:
config (synapse.config.homeserver.HomeserverConfig):
_listening_services (list[twisted.internet.tcp.Port]): TCP ports that
we are listening on to provide HTTP services.
"""
__metaclass__ = abc.ABCMeta
DEPENDENCIES = [
"http_client",
"federation_client",
"federation_server",
"handlers",
"auth",
"room_creation_handler",
"state_handler",
"state_resolution_handler",
"presence_handler",
"sync_handler",
"typing_handler",
"room_list_handler",
"acme_handler",
"auth_handler",
"device_handler",
"stats_handler",
"e2e_keys_handler",
"e2e_room_keys_handler",
"event_handler",
"event_stream_handler",
"initial_sync_handler",
"application_service_api",
"application_service_scheduler",
"application_service_handler",
"device_message_handler",
"profile_handler",
"event_creation_handler",
"deactivate_account_handler",
"set_password_handler",
"notifier",
"event_sources",
"keyring",
"pusherpool",
"event_builder_factory",
"filtering",
"http_client_context_factory",
"simple_http_client",
"proxied_http_client",
"media_repository",
"media_repository_resource",
"federation_transport_client",
"federation_sender",
"receipts_handler",
"macaroon_generator",
"tcp_replication",
"read_marker_handler",
"action_generator",
"user_directory_handler",
"groups_local_handler",
"groups_server_handler",
"groups_attestation_signing",
"groups_attestation_renewer",
"secrets",
"spam_checker",
"third_party_event_rules",
"room_member_handler",
"federation_registry",
"server_notices_manager",
"server_notices_sender",
"message_handler",
"pagination_handler",
"room_context_handler",
"sendmail",
"registration_handler",
"account_validity_handler",
"cas_handler",
"saml_handler",
"oidc_handler",
"event_client_serializer",
"password_policy_handler",
"storage",
"replication_streamer",
"replication_data_handler",
"replication_streams",
]
REQUIRED_ON_MASTER_STARTUP = ["user_directory_handler", "stats_handler"]
# This is overridden in derived application classes
# (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
# instantiated during setup() for future return by get_datastore()
DATASTORE_CLASS = abc.abstractproperty()
def __init__(self, hostname: str, config: HomeServerConfig, reactor=None, **kwargs):
"""
Args:
hostname : The hostname for the server.
config: The full config for the homeserver.
"""
if not reactor:
from twisted.internet import reactor
self._reactor = reactor
self.hostname = hostname
# the key we use to sign events and requests
self.signing_key = config.key.signing_key[0]
self.config = config
self._building = {}
self._listening_services = []
self.start_time = None
self._instance_id = random_string(5)
self._instance_name = config.worker_name or "master"
self.clock = Clock(reactor)
self.distributor = Distributor()
self.registration_ratelimiter = Ratelimiter(
clock=self.clock,
rate_hz=config.rc_registration.per_second,
burst_count=config.rc_registration.burst_count,
)
self.datastores = None
# Other kwargs are explicit dependencies
for depname in kwargs:
setattr(self, depname, kwargs[depname])
def get_instance_id(self):
"""A unique ID for this synapse process instance.
This is used to distinguish running instances in worker-based
deployments.
"""
return self._instance_id
def get_instance_name(self) -> str:
"""A unique name for this synapse process.
Used to identify the process over replication and in config. Does not
change over restarts.
"""
return self._instance_name
def setup(self):
logger.info("Setting up.")
self.start_time = int(self.get_clock().time())
self.datastores = DataStores(self.DATASTORE_CLASS, self)
logger.info("Finished setting up.")
def setup_master(self):
"""
Some handlers have side effects on instantiation (like registering
background updates). This function causes them to be fetched, and
therefore instantiated, to run those side effects.
"""
for i in self.REQUIRED_ON_MASTER_STARTUP:
getattr(self, "get_" + i)()
def get_reactor(self):
"""
Fetch the Twisted reactor in use by this HomeServer.
"""
return self._reactor
def get_ip_from_request(self, request):
# X-Forwarded-For is handled by our custom request type.
return request.getClientIP()
def is_mine(self, domain_specific_string):
return domain_specific_string.domain == self.hostname
def is_mine_id(self, string):
return string.split(":", 1)[1] == self.hostname
def get_clock(self):
return self.clock
def get_datastore(self):
return self.datastores.main
def get_datastores(self):
return self.datastores
def get_config(self):
return self.config
def get_distributor(self):
return self.distributor
def get_registration_ratelimiter(self) -> Ratelimiter:
return self.registration_ratelimiter
def build_federation_client(self):
return FederationClient(self)
def build_federation_server(self):
return FederationServer(self)
def build_handlers(self):
return Handlers(self)
def build_notifier(self):
return Notifier(self)
def build_auth(self):
return Auth(self)
def build_http_client_context_factory(self):
return (
InsecureInterceptableContextFactory()
if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
else RegularPolicyForHTTPS()
)
def build_simple_http_client(self):
return SimpleHttpClient(self)
def build_proxied_http_client(self):
return SimpleHttpClient(
self,
http_proxy=os.getenvb(b"http_proxy"),
https_proxy=os.getenvb(b"HTTPS_PROXY"),
)
def build_room_creation_handler(self):
return RoomCreationHandler(self)
def build_sendmail(self):
return sendmail
def build_state_handler(self):
return StateHandler(self)
def build_state_resolution_handler(self):
return StateResolutionHandler(self)
def build_presence_handler(self):
return PresenceHandler(self)
def build_typing_handler(self):
return TypingHandler(self)
def build_sync_handler(self):
return SyncHandler(self)
def build_room_list_handler(self):
return RoomListHandler(self)
def build_auth_handler(self):
return AuthHandler(self)
def build_macaroon_generator(self):
return MacaroonGenerator(self)
def build_device_handler(self):
if self.config.worker_app:
return DeviceWorkerHandler(self)
else:
return DeviceHandler(self)
def build_device_message_handler(self):
return DeviceMessageHandler(self)
def build_e2e_keys_handler(self):
return E2eKeysHandler(self)
def build_e2e_room_keys_handler(self):
return E2eRoomKeysHandler(self)
def build_acme_handler(self):
return AcmeHandler(self)
def build_application_service_api(self):
return ApplicationServiceApi(self)
def build_application_service_scheduler(self):
return ApplicationServiceScheduler(self)
def build_application_service_handler(self):
return ApplicationServicesHandler(self)
def build_event_handler(self):
return EventHandler(self)
def build_event_stream_handler(self):
return EventStreamHandler(self)
def build_initial_sync_handler(self):
return InitialSyncHandler(self)
def build_profile_handler(self):
if self.config.worker_app:
return BaseProfileHandler(self)
else:
return MasterProfileHandler(self)
def build_event_creation_handler(self):
return EventCreationHandler(self)
def build_deactivate_account_handler(self):
return DeactivateAccountHandler(self)
def build_set_password_handler(self):
return SetPasswordHandler(self)
def build_event_sources(self):
return EventSources(self)
def build_keyring(self):
return Keyring(self)
def build_event_builder_factory(self):
return EventBuilderFactory(self)
def build_filtering(self):
return Filtering(self)
def build_pusherpool(self):
return PusherPool(self)
def build_http_client(self):
tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory)
def build_media_repository_resource(self):
# build the media repo resource. This indirects through the HomeServer
# to ensure that we only have a single instance of
return MediaRepositoryResource(self)
def build_media_repository(self):
return MediaRepository(self)
def build_federation_transport_client(self):
return TransportLayerClient(self)
def build_federation_sender(self):
if self.should_send_federation():
return FederationSender(self)
elif not self.config.worker_app:
return FederationRemoteSendQueue(self)
else:
raise Exception("Workers cannot send federation traffic")
def build_receipts_handler(self):
return ReceiptsHandler(self)
def build_read_marker_handler(self):
return ReadMarkerHandler(self)
def build_tcp_replication(self):
return ReplicationCommandHandler(self)
def build_action_generator(self):
return ActionGenerator(self)
def build_user_directory_handler(self):
return UserDirectoryHandler(self)
def build_groups_local_handler(self):
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
else:
return GroupsLocalHandler(self)
def build_groups_server_handler(self):
if self.config.worker_app:
return GroupsServerWorkerHandler(self)
else:
return GroupsServerHandler(self)
def build_groups_attestation_signing(self):
return GroupAttestationSigning(self)
def build_groups_attestation_renewer(self):
return GroupAttestionRenewer(self)
def build_secrets(self):
return Secrets()
def build_stats_handler(self):
return StatsHandler(self)
def build_spam_checker(self):
return SpamChecker(self)
def build_third_party_event_rules(self):
return ThirdPartyEventRules(self)
def build_room_member_handler(self):
if self.config.worker_app:
return RoomMemberWorkerHandler(self)
return RoomMemberMasterHandler(self)
def build_federation_registry(self):
if self.config.worker_app:
return ReplicationFederationHandlerRegistry(self)
else:
return FederationHandlerRegistry()
def build_server_notices_manager(self):
if self.config.worker_app:
raise Exception("Workers cannot send server notices")
return ServerNoticesManager(self)
def build_server_notices_sender(self):
if self.config.worker_app:
return WorkerServerNoticesSender(self)
return ServerNoticesSender(self)
def build_message_handler(self):
return MessageHandler(self)
def build_pagination_handler(self):
return PaginationHandler(self)
def build_room_context_handler(self):
return RoomContextHandler(self)
def build_registration_handler(self):
return RegistrationHandler(self)
def build_account_validity_handler(self):
return AccountValidityHandler(self)
def build_cas_handler(self):
return CasHandler(self)
def build_saml_handler(self):
from synapse.handlers.saml_handler import SamlHandler
return SamlHandler(self)
def build_oidc_handler(self):
from synapse.handlers.oidc_handler import OidcHandler
return OidcHandler(self)
def build_event_client_serializer(self):
return EventClientSerializer(self)
def build_password_policy_handler(self):
return PasswordPolicyHandler(self)
def build_storage(self) -> Storage:
return Storage(self, self.datastores)
def build_replication_streamer(self) -> ReplicationStreamer:
return ReplicationStreamer(self)
def build_replication_data_handler(self):
return ReplicationDataHandler(self)
def build_replication_streams(self):
return {stream.NAME: stream(self) for stream in STREAMS_MAP.values()}
def remove_pusher(self, app_id, push_key, user_id):
return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
def should_send_federation(self):
"Should this server be sending federation traffic directly?"
return self.config.send_federation and (
not self.config.worker_app
or self.config.worker_app == "synapse.app.federation_sender"
)
def _make_dependency_method(depname):
def _get(hs):
try:
return getattr(hs, depname)
except AttributeError:
pass
try:
builder = getattr(hs, "build_%s" % (depname))
except AttributeError:
raise NotImplementedError(
"%s has no %s nor a builder for it" % (type(hs).__name__, depname)
)
# Prevent cyclic dependencies from deadlocking
if depname in hs._building:
raise ValueError("Cyclic dependency while building %s" % (depname,))
hs._building[depname] = 1
try:
dep = builder()
setattr(hs, depname, dep)
finally:
del hs._building[depname]
return dep
setattr(HomeServer, "get_%s" % (depname), _get)
# Build magic accessors for every dependency
for depname in HomeServer.DEPENDENCIES:
_make_dependency_method(depname) | synapse/server.py |
# This file provides some classes for setting up (partially-populated)
# homeservers; either as a full homeserver as a real application, or a small
# partial one for unit test mocking.
# Imports required for the default HomeServer() implementation
import abc
import logging
import os
from twisted.mail.smtp import sendmail
from synapse.api.auth import Auth
from synapse.api.filtering import Filtering
from synapse.api.ratelimiting import Ratelimiter
from synapse.appservice.api import ApplicationServiceApi
from synapse.appservice.scheduler import ApplicationServiceScheduler
from synapse.config.homeserver import HomeServerConfig
from synapse.crypto import context_factory
from synapse.crypto.context_factory import RegularPolicyForHTTPS
from synapse.crypto.keyring import Keyring
from synapse.events.builder import EventBuilderFactory
from synapse.events.spamcheck import SpamChecker
from synapse.events.third_party_rules import ThirdPartyEventRules
from synapse.events.utils import EventClientSerializer
from synapse.federation.federation_client import FederationClient
from synapse.federation.federation_server import (
FederationHandlerRegistry,
FederationServer,
ReplicationFederationHandlerRegistry,
)
from synapse.federation.send_queue import FederationRemoteSendQueue
from synapse.federation.sender import FederationSender
from synapse.federation.transport.client import TransportLayerClient
from synapse.groups.attestations import GroupAttestationSigning, GroupAttestionRenewer
from synapse.groups.groups_server import GroupsServerHandler, GroupsServerWorkerHandler
from synapse.handlers import Handlers
from synapse.handlers.account_validity import AccountValidityHandler
from synapse.handlers.acme import AcmeHandler
from synapse.handlers.appservice import ApplicationServicesHandler
from synapse.handlers.auth import AuthHandler, MacaroonGenerator
from synapse.handlers.cas_handler import CasHandler
from synapse.handlers.deactivate_account import DeactivateAccountHandler
from synapse.handlers.device import DeviceHandler, DeviceWorkerHandler
from synapse.handlers.devicemessage import DeviceMessageHandler
from synapse.handlers.e2e_keys import E2eKeysHandler
from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
from synapse.handlers.events import EventHandler, EventStreamHandler
from synapse.handlers.groups_local import GroupsLocalHandler, GroupsLocalWorkerHandler
from synapse.handlers.initial_sync import InitialSyncHandler
from synapse.handlers.message import EventCreationHandler, MessageHandler
from synapse.handlers.pagination import PaginationHandler
from synapse.handlers.password_policy import PasswordPolicyHandler
from synapse.handlers.presence import PresenceHandler
from synapse.handlers.profile import BaseProfileHandler, MasterProfileHandler
from synapse.handlers.read_marker import ReadMarkerHandler
from synapse.handlers.receipts import ReceiptsHandler
from synapse.handlers.register import RegistrationHandler
from synapse.handlers.room import RoomContextHandler, RoomCreationHandler
from synapse.handlers.room_list import RoomListHandler
from synapse.handlers.room_member import RoomMemberMasterHandler
from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
from synapse.handlers.set_password import SetPasswordHandler
from synapse.handlers.stats import StatsHandler
from synapse.handlers.sync import SyncHandler
from synapse.handlers.typing import TypingHandler
from synapse.handlers.user_directory import UserDirectoryHandler
from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
from synapse.http.matrixfederationclient import MatrixFederationHttpClient
from synapse.notifier import Notifier
from synapse.push.action_generator import ActionGenerator
from synapse.push.pusherpool import PusherPool
from synapse.replication.tcp.client import ReplicationDataHandler
from synapse.replication.tcp.handler import ReplicationCommandHandler
from synapse.replication.tcp.resource import ReplicationStreamer
from synapse.replication.tcp.streams import STREAMS_MAP
from synapse.rest.media.v1.media_repository import (
MediaRepository,
MediaRepositoryResource,
)
from synapse.secrets import Secrets
from synapse.server_notices.server_notices_manager import ServerNoticesManager
from synapse.server_notices.server_notices_sender import ServerNoticesSender
from synapse.server_notices.worker_server_notices_sender import (
WorkerServerNoticesSender,
)
from synapse.state import StateHandler, StateResolutionHandler
from synapse.storage import DataStores, Storage
from synapse.streams.events import EventSources
from synapse.util import Clock
from synapse.util.distributor import Distributor
from synapse.util.stringutils import random_string
logger = logging.getLogger(__name__)
class HomeServer(object):
"""A basic homeserver object without lazy component builders.
This will need all of the components it requires to either be passed as
constructor arguments, or the relevant methods overriding to create them.
Typically this would only be used for unit tests.
For every dependency in the DEPENDENCIES list below, this class creates one
method,
def get_DEPENDENCY(self)
which returns the value of that dependency. If no value has yet been set
nor was provided to the constructor, it will attempt to call a lazy builder
method called
def build_DEPENDENCY(self)
which must be implemented by the subclass. This code may call any of the
required "get" methods on the instance to obtain the sub-dependencies that
one requires.
Attributes:
config (synapse.config.homeserver.HomeserverConfig):
_listening_services (list[twisted.internet.tcp.Port]): TCP ports that
we are listening on to provide HTTP services.
"""
__metaclass__ = abc.ABCMeta
DEPENDENCIES = [
"http_client",
"federation_client",
"federation_server",
"handlers",
"auth",
"room_creation_handler",
"state_handler",
"state_resolution_handler",
"presence_handler",
"sync_handler",
"typing_handler",
"room_list_handler",
"acme_handler",
"auth_handler",
"device_handler",
"stats_handler",
"e2e_keys_handler",
"e2e_room_keys_handler",
"event_handler",
"event_stream_handler",
"initial_sync_handler",
"application_service_api",
"application_service_scheduler",
"application_service_handler",
"device_message_handler",
"profile_handler",
"event_creation_handler",
"deactivate_account_handler",
"set_password_handler",
"notifier",
"event_sources",
"keyring",
"pusherpool",
"event_builder_factory",
"filtering",
"http_client_context_factory",
"simple_http_client",
"proxied_http_client",
"media_repository",
"media_repository_resource",
"federation_transport_client",
"federation_sender",
"receipts_handler",
"macaroon_generator",
"tcp_replication",
"read_marker_handler",
"action_generator",
"user_directory_handler",
"groups_local_handler",
"groups_server_handler",
"groups_attestation_signing",
"groups_attestation_renewer",
"secrets",
"spam_checker",
"third_party_event_rules",
"room_member_handler",
"federation_registry",
"server_notices_manager",
"server_notices_sender",
"message_handler",
"pagination_handler",
"room_context_handler",
"sendmail",
"registration_handler",
"account_validity_handler",
"cas_handler",
"saml_handler",
"oidc_handler",
"event_client_serializer",
"password_policy_handler",
"storage",
"replication_streamer",
"replication_data_handler",
"replication_streams",
]
REQUIRED_ON_MASTER_STARTUP = ["user_directory_handler", "stats_handler"]
# This is overridden in derived application classes
# (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
# instantiated during setup() for future return by get_datastore()
DATASTORE_CLASS = abc.abstractproperty()
def __init__(self, hostname: str, config: HomeServerConfig, reactor=None, **kwargs):
"""
Args:
hostname : The hostname for the server.
config: The full config for the homeserver.
"""
if not reactor:
from twisted.internet import reactor
self._reactor = reactor
self.hostname = hostname
# the key we use to sign events and requests
self.signing_key = config.key.signing_key[0]
self.config = config
self._building = {}
self._listening_services = []
self.start_time = None
self._instance_id = random_string(5)
self._instance_name = config.worker_name or "master"
self.clock = Clock(reactor)
self.distributor = Distributor()
self.registration_ratelimiter = Ratelimiter(
clock=self.clock,
rate_hz=config.rc_registration.per_second,
burst_count=config.rc_registration.burst_count,
)
self.datastores = None
# Other kwargs are explicit dependencies
for depname in kwargs:
setattr(self, depname, kwargs[depname])
def get_instance_id(self):
"""A unique ID for this synapse process instance.
This is used to distinguish running instances in worker-based
deployments.
"""
return self._instance_id
def get_instance_name(self) -> str:
"""A unique name for this synapse process.
Used to identify the process over replication and in config. Does not
change over restarts.
"""
return self._instance_name
def setup(self):
logger.info("Setting up.")
self.start_time = int(self.get_clock().time())
self.datastores = DataStores(self.DATASTORE_CLASS, self)
logger.info("Finished setting up.")
def setup_master(self):
"""
Some handlers have side effects on instantiation (like registering
background updates). This function causes them to be fetched, and
therefore instantiated, to run those side effects.
"""
for i in self.REQUIRED_ON_MASTER_STARTUP:
getattr(self, "get_" + i)()
def get_reactor(self):
"""
Fetch the Twisted reactor in use by this HomeServer.
"""
return self._reactor
def get_ip_from_request(self, request):
# X-Forwarded-For is handled by our custom request type.
return request.getClientIP()
def is_mine(self, domain_specific_string):
return domain_specific_string.domain == self.hostname
def is_mine_id(self, string):
return string.split(":", 1)[1] == self.hostname
def get_clock(self):
return self.clock
def get_datastore(self):
return self.datastores.main
def get_datastores(self):
return self.datastores
def get_config(self):
return self.config
def get_distributor(self):
return self.distributor
def get_registration_ratelimiter(self) -> Ratelimiter:
return self.registration_ratelimiter
def build_federation_client(self):
return FederationClient(self)
def build_federation_server(self):
return FederationServer(self)
def build_handlers(self):
return Handlers(self)
def build_notifier(self):
return Notifier(self)
def build_auth(self):
return Auth(self)
def build_http_client_context_factory(self):
return (
InsecureInterceptableContextFactory()
if self.config.use_insecure_ssl_client_just_for_testing_do_not_use
else RegularPolicyForHTTPS()
)
def build_simple_http_client(self):
return SimpleHttpClient(self)
def build_proxied_http_client(self):
return SimpleHttpClient(
self,
http_proxy=os.getenvb(b"http_proxy"),
https_proxy=os.getenvb(b"HTTPS_PROXY"),
)
def build_room_creation_handler(self):
return RoomCreationHandler(self)
def build_sendmail(self):
return sendmail
def build_state_handler(self):
return StateHandler(self)
def build_state_resolution_handler(self):
return StateResolutionHandler(self)
def build_presence_handler(self):
return PresenceHandler(self)
def build_typing_handler(self):
return TypingHandler(self)
def build_sync_handler(self):
return SyncHandler(self)
def build_room_list_handler(self):
return RoomListHandler(self)
def build_auth_handler(self):
return AuthHandler(self)
def build_macaroon_generator(self):
return MacaroonGenerator(self)
def build_device_handler(self):
if self.config.worker_app:
return DeviceWorkerHandler(self)
else:
return DeviceHandler(self)
def build_device_message_handler(self):
return DeviceMessageHandler(self)
def build_e2e_keys_handler(self):
return E2eKeysHandler(self)
def build_e2e_room_keys_handler(self):
return E2eRoomKeysHandler(self)
def build_acme_handler(self):
return AcmeHandler(self)
def build_application_service_api(self):
return ApplicationServiceApi(self)
def build_application_service_scheduler(self):
return ApplicationServiceScheduler(self)
def build_application_service_handler(self):
return ApplicationServicesHandler(self)
def build_event_handler(self):
return EventHandler(self)
def build_event_stream_handler(self):
return EventStreamHandler(self)
def build_initial_sync_handler(self):
return InitialSyncHandler(self)
def build_profile_handler(self):
if self.config.worker_app:
return BaseProfileHandler(self)
else:
return MasterProfileHandler(self)
def build_event_creation_handler(self):
return EventCreationHandler(self)
def build_deactivate_account_handler(self):
return DeactivateAccountHandler(self)
def build_set_password_handler(self):
return SetPasswordHandler(self)
def build_event_sources(self):
return EventSources(self)
def build_keyring(self):
return Keyring(self)
def build_event_builder_factory(self):
return EventBuilderFactory(self)
def build_filtering(self):
return Filtering(self)
def build_pusherpool(self):
return PusherPool(self)
def build_http_client(self):
tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
self.config
)
return MatrixFederationHttpClient(self, tls_client_options_factory)
def build_media_repository_resource(self):
# build the media repo resource. This indirects through the HomeServer
# to ensure that we only have a single instance of
return MediaRepositoryResource(self)
def build_media_repository(self):
return MediaRepository(self)
def build_federation_transport_client(self):
return TransportLayerClient(self)
def build_federation_sender(self):
if self.should_send_federation():
return FederationSender(self)
elif not self.config.worker_app:
return FederationRemoteSendQueue(self)
else:
raise Exception("Workers cannot send federation traffic")
def build_receipts_handler(self):
return ReceiptsHandler(self)
def build_read_marker_handler(self):
return ReadMarkerHandler(self)
def build_tcp_replication(self):
return ReplicationCommandHandler(self)
def build_action_generator(self):
return ActionGenerator(self)
def build_user_directory_handler(self):
return UserDirectoryHandler(self)
def build_groups_local_handler(self):
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
else:
return GroupsLocalHandler(self)
def build_groups_server_handler(self):
if self.config.worker_app:
return GroupsServerWorkerHandler(self)
else:
return GroupsServerHandler(self)
def build_groups_attestation_signing(self):
return GroupAttestationSigning(self)
def build_groups_attestation_renewer(self):
return GroupAttestionRenewer(self)
def build_secrets(self):
return Secrets()
def build_stats_handler(self):
return StatsHandler(self)
def build_spam_checker(self):
return SpamChecker(self)
def build_third_party_event_rules(self):
return ThirdPartyEventRules(self)
def build_room_member_handler(self):
if self.config.worker_app:
return RoomMemberWorkerHandler(self)
return RoomMemberMasterHandler(self)
def build_federation_registry(self):
if self.config.worker_app:
return ReplicationFederationHandlerRegistry(self)
else:
return FederationHandlerRegistry()
def build_server_notices_manager(self):
if self.config.worker_app:
raise Exception("Workers cannot send server notices")
return ServerNoticesManager(self)
def build_server_notices_sender(self):
if self.config.worker_app:
return WorkerServerNoticesSender(self)
return ServerNoticesSender(self)
def build_message_handler(self):
return MessageHandler(self)
def build_pagination_handler(self):
return PaginationHandler(self)
def build_room_context_handler(self):
return RoomContextHandler(self)
def build_registration_handler(self):
return RegistrationHandler(self)
def build_account_validity_handler(self):
return AccountValidityHandler(self)
def build_cas_handler(self):
return CasHandler(self)
def build_saml_handler(self):
from synapse.handlers.saml_handler import SamlHandler
return SamlHandler(self)
def build_oidc_handler(self):
from synapse.handlers.oidc_handler import OidcHandler
return OidcHandler(self)
def build_event_client_serializer(self):
return EventClientSerializer(self)
def build_password_policy_handler(self):
return PasswordPolicyHandler(self)
def build_storage(self) -> Storage:
return Storage(self, self.datastores)
def build_replication_streamer(self) -> ReplicationStreamer:
return ReplicationStreamer(self)
def build_replication_data_handler(self):
return ReplicationDataHandler(self)
def build_replication_streams(self):
return {stream.NAME: stream(self) for stream in STREAMS_MAP.values()}
def remove_pusher(self, app_id, push_key, user_id):
return self.get_pusherpool().remove_pusher(app_id, push_key, user_id)
def should_send_federation(self):
"Should this server be sending federation traffic directly?"
return self.config.send_federation and (
not self.config.worker_app
or self.config.worker_app == "synapse.app.federation_sender"
)
def _make_dependency_method(depname):
def _get(hs):
try:
return getattr(hs, depname)
except AttributeError:
pass
try:
builder = getattr(hs, "build_%s" % (depname))
except AttributeError:
raise NotImplementedError(
"%s has no %s nor a builder for it" % (type(hs).__name__, depname)
)
# Prevent cyclic dependencies from deadlocking
if depname in hs._building:
raise ValueError("Cyclic dependency while building %s" % (depname,))
hs._building[depname] = 1
try:
dep = builder()
setattr(hs, depname, dep)
finally:
del hs._building[depname]
return dep
setattr(HomeServer, "get_%s" % (depname), _get)
# Build magic accessors for every dependency
for depname in HomeServer.DEPENDENCIES:
_make_dependency_method(depname) | 0.547948 | 0.095349 |
import logging
from plugwise.exceptions import InvalidAuthentication, PlugwiseException
from plugwise.smile import Smile
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
CONF_BASE,
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import DiscoveryInfoType
from .const import DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN, ZEROCONF_MAP
_LOGGER = logging.getLogger(__name__)
def _base_gw_schema(discovery_info):
"""Generate base schema for gateways."""
base_gw_schema = {}
if not discovery_info:
base_gw_schema[vol.Required(CONF_HOST)] = str
base_gw_schema[vol.Optional(CONF_PORT, default=DEFAULT_PORT)] = int
base_gw_schema.update(
{
vol.Required(
CONF_USERNAME, default="smile", description={"suggested_value": "smile"}
): str,
vol.Required(CONF_PASSWORD): str,
}
)
return vol.Schema(base_gw_schema)
async def validate_gw_input(hass: core.HomeAssistant, data):
"""
Validate whether the user input allows us to connect to the gateray.
Data has the keys from _base_gw_schema() with values provided by the user.
"""
websession = async_get_clientsession(hass, verify_ssl=False)
api = Smile(
host=data[CONF_HOST],
password=data[CONF_PASSWORD],
port=data[CONF_PORT],
username=data[CONF_USERNAME],
timeout=30,
websession=websession,
)
try:
await api.connect()
except InvalidAuthentication as err:
raise InvalidAuth from err
except PlugwiseException as err:
raise CannotConnect from err
return api
# PLACEHOLDER USB connection validation
class PlugwiseConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Plugwise Smile."""
VERSION = 1
def __init__(self):
"""Initialize the Plugwise config flow."""
self.discovery_info = {}
async def async_step_zeroconf(self, discovery_info: DiscoveryInfoType):
"""Prepare configuration for a discovered Plugwise Smile."""
self.discovery_info = discovery_info
_properties = self.discovery_info.get("properties")
unique_id = self.discovery_info.get("hostname").split(".")[0]
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
_product = _properties.get("product", None)
_version = _properties.get("version", "n/a")
_name = f"{ZEROCONF_MAP.get(_product, _product)} v{_version}"
self.context["title_placeholders"] = {
CONF_HOST: discovery_info[CONF_HOST],
CONF_PORT: discovery_info.get(CONF_PORT, DEFAULT_PORT),
CONF_NAME: _name,
}
return await self.async_step_user()
async def async_step_user_gateway(self, user_input=None):
"""Handle the initial step for gateways."""
errors = {}
if user_input is not None:
if self.discovery_info:
user_input[CONF_HOST] = self.discovery_info[CONF_HOST]
user_input[CONF_PORT] = self.discovery_info.get(CONF_PORT, DEFAULT_PORT)
for entry in self._async_current_entries():
if entry.data.get(CONF_HOST) == user_input[CONF_HOST]:
return self.async_abort(reason="already_configured")
try:
api = await validate_gw_input(self.hass, user_input)
except CannotConnect:
errors[CONF_BASE] = "cannot_connect"
except InvalidAuth:
errors[CONF_BASE] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors[CONF_BASE] = "unknown"
if not errors:
await self.async_set_unique_id(
api.smile_hostname or api.gateway_id, raise_on_progress=False
)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=api.smile_name, data=user_input)
return self.async_show_form(
step_id="user_gateway",
data_schema=_base_gw_schema(self.discovery_info),
errors=errors or {},
)
# PLACEHOLDER USB async_step_user_usb and async_step_user_usb_manual_paht
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
# PLACEHOLDER USB vs Gateway Logic
return await self.async_step_user_gateway()
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return PlugwiseOptionsFlowHandler(config_entry)
class PlugwiseOptionsFlowHandler(config_entries.OptionsFlow):
"""Plugwise option flow."""
def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None):
"""Manage the Plugwise options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
api = self.hass.data[DOMAIN][self.config_entry.entry_id]["api"]
interval = DEFAULT_SCAN_INTERVAL[api.smile_type]
data = {
vol.Optional(
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(CONF_SCAN_INTERVAL, interval),
): int
}
return self.async_show_form(step_id="init", data_schema=vol.Schema(data))
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth.""" | homeassistant/components/plugwise/config_flow.py | import logging
from plugwise.exceptions import InvalidAuthentication, PlugwiseException
from plugwise.smile import Smile
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import (
CONF_BASE,
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_SCAN_INTERVAL,
CONF_USERNAME,
)
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import DiscoveryInfoType
from .const import DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN, ZEROCONF_MAP
_LOGGER = logging.getLogger(__name__)
def _base_gw_schema(discovery_info):
"""Generate base schema for gateways."""
base_gw_schema = {}
if not discovery_info:
base_gw_schema[vol.Required(CONF_HOST)] = str
base_gw_schema[vol.Optional(CONF_PORT, default=DEFAULT_PORT)] = int
base_gw_schema.update(
{
vol.Required(
CONF_USERNAME, default="smile", description={"suggested_value": "smile"}
): str,
vol.Required(CONF_PASSWORD): str,
}
)
return vol.Schema(base_gw_schema)
async def validate_gw_input(hass: core.HomeAssistant, data):
"""
Validate whether the user input allows us to connect to the gateray.
Data has the keys from _base_gw_schema() with values provided by the user.
"""
websession = async_get_clientsession(hass, verify_ssl=False)
api = Smile(
host=data[CONF_HOST],
password=data[CONF_PASSWORD],
port=data[CONF_PORT],
username=data[CONF_USERNAME],
timeout=30,
websession=websession,
)
try:
await api.connect()
except InvalidAuthentication as err:
raise InvalidAuth from err
except PlugwiseException as err:
raise CannotConnect from err
return api
# PLACEHOLDER USB connection validation
class PlugwiseConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Plugwise Smile."""
VERSION = 1
def __init__(self):
"""Initialize the Plugwise config flow."""
self.discovery_info = {}
async def async_step_zeroconf(self, discovery_info: DiscoveryInfoType):
"""Prepare configuration for a discovered Plugwise Smile."""
self.discovery_info = discovery_info
_properties = self.discovery_info.get("properties")
unique_id = self.discovery_info.get("hostname").split(".")[0]
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
_product = _properties.get("product", None)
_version = _properties.get("version", "n/a")
_name = f"{ZEROCONF_MAP.get(_product, _product)} v{_version}"
self.context["title_placeholders"] = {
CONF_HOST: discovery_info[CONF_HOST],
CONF_PORT: discovery_info.get(CONF_PORT, DEFAULT_PORT),
CONF_NAME: _name,
}
return await self.async_step_user()
async def async_step_user_gateway(self, user_input=None):
"""Handle the initial step for gateways."""
errors = {}
if user_input is not None:
if self.discovery_info:
user_input[CONF_HOST] = self.discovery_info[CONF_HOST]
user_input[CONF_PORT] = self.discovery_info.get(CONF_PORT, DEFAULT_PORT)
for entry in self._async_current_entries():
if entry.data.get(CONF_HOST) == user_input[CONF_HOST]:
return self.async_abort(reason="already_configured")
try:
api = await validate_gw_input(self.hass, user_input)
except CannotConnect:
errors[CONF_BASE] = "cannot_connect"
except InvalidAuth:
errors[CONF_BASE] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors[CONF_BASE] = "unknown"
if not errors:
await self.async_set_unique_id(
api.smile_hostname or api.gateway_id, raise_on_progress=False
)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=api.smile_name, data=user_input)
return self.async_show_form(
step_id="user_gateway",
data_schema=_base_gw_schema(self.discovery_info),
errors=errors or {},
)
# PLACEHOLDER USB async_step_user_usb and async_step_user_usb_manual_paht
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
# PLACEHOLDER USB vs Gateway Logic
return await self.async_step_user_gateway()
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return PlugwiseOptionsFlowHandler(config_entry)
class PlugwiseOptionsFlowHandler(config_entries.OptionsFlow):
"""Plugwise option flow."""
def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry
async def async_step_init(self, user_input=None):
"""Manage the Plugwise options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
api = self.hass.data[DOMAIN][self.config_entry.entry_id]["api"]
interval = DEFAULT_SCAN_INTERVAL[api.smile_type]
data = {
vol.Optional(
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(CONF_SCAN_INTERVAL, interval),
): int
}
return self.async_show_form(step_id="init", data_schema=vol.Schema(data))
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth.""" | 0.68616 | 0.074332 |
# Copyright (c) 2016, <NAME> <<EMAIL>>
# All rights reserved.
import json
import interfaces.ckan
import datetime
license_id_to_name = {
"Apache": "Apache License",
"Apache-1.0": "Apache License 1.0",
"Apache-2.0": "Apache License 2.0",
"Artistic": "Artistic License",
"Artistic-1.0": "Artistic License 1.0",
"Artistic-2.0": "Artistic License 2.0",
"BSD-2-clause": "BSD 2-clause \"Simplified\" License",
"BSD-3-clause": "BSD 3-clause \"New\" or \"Revised\" License",
"BSD-4-clause": "BSD 4-clause \"Original\" or \"Old\" License",
"CC-BY": "Creative Commons Attribution",
"CC-BY-1.0": "Creative Commons Attribution 1.0",
"CC-BY-2.0": "Creative Commons Attribution 2.0",
"CC-BY-2.5": "Creative Commons Attribution 2.5",
"CC-BY-3.0": "Creative Commons Attribution 3.0",
"CC-BY-4.0": "Creative Commons Attribution 4.0",
"CC-BY-NC": "Creative Commons Attribution Non Commercial",
"CC-BY-NC-1.0": "Creative Commons Attribution Non Commercial 1.0",
"CC-BY-NC-2.0": "Creative Commons Attribution Non Commercial 2.0",
"CC-BY-NC-2.5": "Creative Commons Attribution Non Commercial 2.5",
"CC-BY-NC-3.0": "Creative Commons Attribution Non Commercial 3.0",
"CC-BY-NC-4.0": "Creative Commons Attribution Non Commercial 4.0",
"CC-BY-NC-ND": "Creative Commons Attribution Non Commercial No Derivatives",
"CC-BY-NC-ND-1.0": "Creative Commons Attribution Non Commercial No Derivatives 1.0",
"CC-BY-NC-ND-2.0": "Creative Commons Attribution Non Commercial No Derivatives 2.0",
"CC-BY-NC-ND-2.5": "Creative Commons Attribution Non Commercial No Derivatives 2.5",
"CC-BY-NC-ND-3.0": "Creative Commons Attribution Non Commercial No Derivatives 3.0",
"CC-BY-NC-ND-4.0": "Creative Commons Attribution Non Commercial No Derivatives 4.0",
"CC-BY-NC-SA": "Creative Commons Attribution Non Commercial Share Alike",
"CC-BY-NC-SA-1.0": "Creative Commons Attribution Non Commercial Share Alike 1.0",
"CC-BY-NC-SA-2.0": "Creative Commons Attribution Non Commercial Share Alike 2.0",
"CC-BY-NC-SA-2.5": "Creative Commons Attribution Non Commercial Share Alike 2.5",
"CC-BY-NC-SA-3.0": "Creative Commons Attribution Non Commercial Share Alike 3.0",
"CC-BY-NC-SA-4.0": "Creative Commons Attribution Non Commercial Share Alike 4.0",
"CC-BY-SA": "Creative Commons Attribution Share Alike",
"CC-BY-SA-1.0": "Creative Commons Attribution Share Alike 1.0",
"CC-BY-SA-2.0": "Creative Commons Attribution Share Alike 2.0",
"CC-BY-SA-2.5": "Creative Commons Attribution Share Alike 2.5",
"CC-BY-SA-3.0": "Creative Commons Attribution Share Alike 3.0",
"CC-BY-SA-4.0": "Creative Commons Attribution Share Alike 4.0",
"CC0": "Creative Commons Zero v1.0 Universal",
"CDDL": "Common Development and Distribution License",
"CPL": "Common Public License",
"EFL-1.0": "Eiffel Forum License v1.0",
"EFL-2.0": "Eiffel Forum License v2.0",
"Expat": "MIT License (Expat)",
"GFDL-1.0": "GNU Free Documentation License v1.0",
"GFDL-1.1": "GNU Free Documentation License v1.1",
"GFDL-1.2": "GNU Free Documentation License v1.2",
"GFDL-1.3": "GNU Free Documentation License v1.3",
"GFDL-NIV-1.0": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.0",
"GFDL-NIV-1.1": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.1",
"GFDL-NIV-1.2": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.2",
"GFDL-NIV-1.3": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.3",
"GPL-1.0": "GNU General Public License v1.0 only",
"GPL-2.0": "GNU General Public License v2.0 only",
"GPL-3.0": "GNU General Public License v3.0 only",
"ISC": "ISC License",
"LGPL-2.0": "GNU Library General Public License v2 only",
"LGPL-2.1": "GNU Library General Public License v2.1 only",
"LGPL-3.0": "GNU Library General Public License v3 only",
"LPPL-1.0": "LaTeX Project Public License v1.0",
"LPPL-1.1": "LaTeX Project Public License v1.1",
"LPPL-1.2": "LaTeX Project Public License v1.2",
"LPPL-1.3c": "LaTeX Project Public License v1.3c",
"MIT": "MIT License (Expat)",
"MPL-1.1": "Mozilla Public License 1.1",
"Perl": "Artistic License 1.0 (Perl)",
"Python-2.0": "Python License 2.0",
"QPL-1.0": "Q Public License 1.0",
# Waiting for v1.18 "Unlicense": "The Unlicense",
"W3C": "W3C Software Notice and License (2002-12-31)",
"WTFPL": "Do What The F*ck You Want To Public License",
"Zlib": "zlib License",
"Zope": "Zope Public License",
"open-source": "Other Open Source Initiative (OSI) approved license",
"public-domain": "public domain",
"restricted": "All rights reserved",
"unknown": "License not provided",
"unrestricted": "Not an OSI approved license, but not restricted"
}
mandatory_fields = [
"spec_version",
"identifier",
"name",
"abstract",
"author",
"version",
"ksp_version",
"license",
"download"
]
modes_autofill = {
"github": [
"name",
"abstract",
"author",
"download",
"download_hash",
"download_size",
"resources.repository",
"resources.bugtracker",
"version",
"license"
],
"http": [
"download",
"download_content_type",
"download_hash",
"download_size"
],
"other": [],
"spacedock": [
"abstract",
"author",
"download",
"download_hash",
"download_size",
"ksp_version",
"license",
"name",
"resources.homepage",
"resources.repository",
"resources.spacedock",
"resources.x_screenshot",
"version"
]
}
js = """
var license_name_to_id = {};
for (var k in license_id_to_name) {
license_name_to_id[license_id_to_name[k]] = k;
}
var license_ids = Object.keys(license_id_to_name);
license_ids.sort();
var license_names = Object.keys(license_name_to_id);
license_names.sort();
var ckan_ids = [];
var ckan_name_to_id = {};
for (var i in ckan_names_ids) {
var id = ckan_names_ids[i][1];
var name = ckan_names_ids[i][0];
if (!ckan_ids.includes(id)) {
ckan_ids.push(id);
}
ckan_name_to_id[name] = id;
}
ckan_ids.sort();
var ckan_names = Object.keys(ckan_name_to_id);
ckan_names.sort();
"""
def main():
ckan = interfaces.ckan.full()
ckan_ids = sorted(set(e["identifier"] for e in ckan))
ckan_names_ids = sorted(
set((e["name"].strip(), e["identifier"]) for e in ckan))
ckan_schema = interfaces.ckan.json_schema()
now = datetime.datetime.utcnow()
now_str = now.strftime("%Y-%m-%dT%H:%M:%S")
with open("static/data.js", "w", encoding="utf-8") as f:
f.write("// auto-generated on %s UTC - see refresh_datajs.py\n\"use strict\";\n\nvar data_updated = \"%s\";\n\n" % (now_str, now_str))
f.write("var mandatory_fields = ")
json.dump(mandatory_fields, f, sort_keys=True)
f.write(";\n\n")
f.write("var license_id_to_name = ")
json.dump(license_id_to_name, f, sort_keys=True)
f.write(";\n\n")
f.write("var modes_autofill = ")
json.dump(modes_autofill, f, sort_keys=True)
f.write(";\n\n")
f.write("var ckan_schema = ")
json.dump(ckan_schema, f, sort_keys=True)
f.write(";\n\n")
f.write("var ckan_names_ids = ")
json.dump(ckan_names_ids, f, sort_keys=True)
f.write(";\n\n")
f.write(js)
if __name__ == "__main__":
main() | refresh_datajs.py |
# Copyright (c) 2016, <NAME> <<EMAIL>>
# All rights reserved.
import json
import interfaces.ckan
import datetime
license_id_to_name = {
"Apache": "Apache License",
"Apache-1.0": "Apache License 1.0",
"Apache-2.0": "Apache License 2.0",
"Artistic": "Artistic License",
"Artistic-1.0": "Artistic License 1.0",
"Artistic-2.0": "Artistic License 2.0",
"BSD-2-clause": "BSD 2-clause \"Simplified\" License",
"BSD-3-clause": "BSD 3-clause \"New\" or \"Revised\" License",
"BSD-4-clause": "BSD 4-clause \"Original\" or \"Old\" License",
"CC-BY": "Creative Commons Attribution",
"CC-BY-1.0": "Creative Commons Attribution 1.0",
"CC-BY-2.0": "Creative Commons Attribution 2.0",
"CC-BY-2.5": "Creative Commons Attribution 2.5",
"CC-BY-3.0": "Creative Commons Attribution 3.0",
"CC-BY-4.0": "Creative Commons Attribution 4.0",
"CC-BY-NC": "Creative Commons Attribution Non Commercial",
"CC-BY-NC-1.0": "Creative Commons Attribution Non Commercial 1.0",
"CC-BY-NC-2.0": "Creative Commons Attribution Non Commercial 2.0",
"CC-BY-NC-2.5": "Creative Commons Attribution Non Commercial 2.5",
"CC-BY-NC-3.0": "Creative Commons Attribution Non Commercial 3.0",
"CC-BY-NC-4.0": "Creative Commons Attribution Non Commercial 4.0",
"CC-BY-NC-ND": "Creative Commons Attribution Non Commercial No Derivatives",
"CC-BY-NC-ND-1.0": "Creative Commons Attribution Non Commercial No Derivatives 1.0",
"CC-BY-NC-ND-2.0": "Creative Commons Attribution Non Commercial No Derivatives 2.0",
"CC-BY-NC-ND-2.5": "Creative Commons Attribution Non Commercial No Derivatives 2.5",
"CC-BY-NC-ND-3.0": "Creative Commons Attribution Non Commercial No Derivatives 3.0",
"CC-BY-NC-ND-4.0": "Creative Commons Attribution Non Commercial No Derivatives 4.0",
"CC-BY-NC-SA": "Creative Commons Attribution Non Commercial Share Alike",
"CC-BY-NC-SA-1.0": "Creative Commons Attribution Non Commercial Share Alike 1.0",
"CC-BY-NC-SA-2.0": "Creative Commons Attribution Non Commercial Share Alike 2.0",
"CC-BY-NC-SA-2.5": "Creative Commons Attribution Non Commercial Share Alike 2.5",
"CC-BY-NC-SA-3.0": "Creative Commons Attribution Non Commercial Share Alike 3.0",
"CC-BY-NC-SA-4.0": "Creative Commons Attribution Non Commercial Share Alike 4.0",
"CC-BY-SA": "Creative Commons Attribution Share Alike",
"CC-BY-SA-1.0": "Creative Commons Attribution Share Alike 1.0",
"CC-BY-SA-2.0": "Creative Commons Attribution Share Alike 2.0",
"CC-BY-SA-2.5": "Creative Commons Attribution Share Alike 2.5",
"CC-BY-SA-3.0": "Creative Commons Attribution Share Alike 3.0",
"CC-BY-SA-4.0": "Creative Commons Attribution Share Alike 4.0",
"CC0": "Creative Commons Zero v1.0 Universal",
"CDDL": "Common Development and Distribution License",
"CPL": "Common Public License",
"EFL-1.0": "Eiffel Forum License v1.0",
"EFL-2.0": "Eiffel Forum License v2.0",
"Expat": "MIT License (Expat)",
"GFDL-1.0": "GNU Free Documentation License v1.0",
"GFDL-1.1": "GNU Free Documentation License v1.1",
"GFDL-1.2": "GNU Free Documentation License v1.2",
"GFDL-1.3": "GNU Free Documentation License v1.3",
"GFDL-NIV-1.0": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.0",
"GFDL-NIV-1.1": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.1",
"GFDL-NIV-1.2": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.2",
"GFDL-NIV-1.3": "GNU Free Documentation License, with no Front-Cover or Back-Cover Texts or Invariant Sections v1.3",
"GPL-1.0": "GNU General Public License v1.0 only",
"GPL-2.0": "GNU General Public License v2.0 only",
"GPL-3.0": "GNU General Public License v3.0 only",
"ISC": "ISC License",
"LGPL-2.0": "GNU Library General Public License v2 only",
"LGPL-2.1": "GNU Library General Public License v2.1 only",
"LGPL-3.0": "GNU Library General Public License v3 only",
"LPPL-1.0": "LaTeX Project Public License v1.0",
"LPPL-1.1": "LaTeX Project Public License v1.1",
"LPPL-1.2": "LaTeX Project Public License v1.2",
"LPPL-1.3c": "LaTeX Project Public License v1.3c",
"MIT": "MIT License (Expat)",
"MPL-1.1": "Mozilla Public License 1.1",
"Perl": "Artistic License 1.0 (Perl)",
"Python-2.0": "Python License 2.0",
"QPL-1.0": "Q Public License 1.0",
# Waiting for v1.18 "Unlicense": "The Unlicense",
"W3C": "W3C Software Notice and License (2002-12-31)",
"WTFPL": "Do What The F*ck You Want To Public License",
"Zlib": "zlib License",
"Zope": "Zope Public License",
"open-source": "Other Open Source Initiative (OSI) approved license",
"public-domain": "public domain",
"restricted": "All rights reserved",
"unknown": "License not provided",
"unrestricted": "Not an OSI approved license, but not restricted"
}
mandatory_fields = [
"spec_version",
"identifier",
"name",
"abstract",
"author",
"version",
"ksp_version",
"license",
"download"
]
modes_autofill = {
"github": [
"name",
"abstract",
"author",
"download",
"download_hash",
"download_size",
"resources.repository",
"resources.bugtracker",
"version",
"license"
],
"http": [
"download",
"download_content_type",
"download_hash",
"download_size"
],
"other": [],
"spacedock": [
"abstract",
"author",
"download",
"download_hash",
"download_size",
"ksp_version",
"license",
"name",
"resources.homepage",
"resources.repository",
"resources.spacedock",
"resources.x_screenshot",
"version"
]
}
js = """
var license_name_to_id = {};
for (var k in license_id_to_name) {
license_name_to_id[license_id_to_name[k]] = k;
}
var license_ids = Object.keys(license_id_to_name);
license_ids.sort();
var license_names = Object.keys(license_name_to_id);
license_names.sort();
var ckan_ids = [];
var ckan_name_to_id = {};
for (var i in ckan_names_ids) {
var id = ckan_names_ids[i][1];
var name = ckan_names_ids[i][0];
if (!ckan_ids.includes(id)) {
ckan_ids.push(id);
}
ckan_name_to_id[name] = id;
}
ckan_ids.sort();
var ckan_names = Object.keys(ckan_name_to_id);
ckan_names.sort();
"""
def main():
ckan = interfaces.ckan.full()
ckan_ids = sorted(set(e["identifier"] for e in ckan))
ckan_names_ids = sorted(
set((e["name"].strip(), e["identifier"]) for e in ckan))
ckan_schema = interfaces.ckan.json_schema()
now = datetime.datetime.utcnow()
now_str = now.strftime("%Y-%m-%dT%H:%M:%S")
with open("static/data.js", "w", encoding="utf-8") as f:
f.write("// auto-generated on %s UTC - see refresh_datajs.py\n\"use strict\";\n\nvar data_updated = \"%s\";\n\n" % (now_str, now_str))
f.write("var mandatory_fields = ")
json.dump(mandatory_fields, f, sort_keys=True)
f.write(";\n\n")
f.write("var license_id_to_name = ")
json.dump(license_id_to_name, f, sort_keys=True)
f.write(";\n\n")
f.write("var modes_autofill = ")
json.dump(modes_autofill, f, sort_keys=True)
f.write(";\n\n")
f.write("var ckan_schema = ")
json.dump(ckan_schema, f, sort_keys=True)
f.write(";\n\n")
f.write("var ckan_names_ids = ")
json.dump(ckan_names_ids, f, sort_keys=True)
f.write(";\n\n")
f.write(js)
if __name__ == "__main__":
main() | 0.516108 | 0.351728 |
import rospy
import numpy as np
from geometry_msgs.msg import Twist, Vector3
from sensor_msgs.msg import LaserScan
def converte(valor):
return valor*44.4/0.501
def scaneou(dado):
#print("Faixa valida: ", dado.range_min , " - ", dado.range_max )
#print("Leituras:")
distancias = np.array(dado.ranges)
#print(distancias)
desviando = False
menor_frente_esquerda = 4
menor_frente_direita = 4
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, 0)) #Comentar isso dps
for i in range(len(distancias)):
if i <= 40:
if converte(distancias[i]) < 50 and converte(distancias[i]) >= 30:
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, -0.7))
desviando = True
print("frente e")
elif converte(distancias[i]) < 30 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(-0.1, 0, 0), Vector3(0, 0, -0.9))
desviando = True
print("mt frente e")
if menor_frente_esquerda > converte(distancias[i]):
menor_frente_esquerda = converte(distancias[i])
if i >= 320:
if converte(distancias[i]) < 50 and converte(distancias[i]) >= 30:
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, 0.7))
desviando = True
print("frente d")
elif converte(distancias[i]) < 30 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(-0.1, 0, 0), Vector3(0, 0, 0.9))
desviando = True
print("mt frente d")
if menor_frente_direita > converte(distancias[i]):
menor_frente_direita = converte(distancias[i])
if i <= 70 and i > 40:
if converte(distancias[i]) < 25 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(0.1, 0, 0), Vector3(0, 0, -0.5))
desviando = True
print("mt esq")
if i < 320 and i >= 290:
if converte(distancias[i]) < 25 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(0.1, 0, 0), Vector3(0, 0, 0.5))
desviando = True
print("mt dir")
velocidade_saida.publish(velocidade)
#print(np.array(dado.ranges).round(decimals=2))
#print("Intensities")
#print(np.array(dado.intensities).round(decimals=2))
if desviando:
return 'desviando'
else:
return 'desviado'
if __name__=="__main__":
global velocidade_saida
rospy.init_node("desviar")
velocidade_saida = rospy.Publisher("/cmd_vel", Twist, queue_size = 2 )
recebe_scan = rospy.Subscriber("/scan", LaserScan, scaneou)
while not rospy.is_shutdown():
print("Oeee")
rospy.sleep(0.5) | Scripts/desviar.py |
import rospy
import numpy as np
from geometry_msgs.msg import Twist, Vector3
from sensor_msgs.msg import LaserScan
def converte(valor):
return valor*44.4/0.501
def scaneou(dado):
#print("Faixa valida: ", dado.range_min , " - ", dado.range_max )
#print("Leituras:")
distancias = np.array(dado.ranges)
#print(distancias)
desviando = False
menor_frente_esquerda = 4
menor_frente_direita = 4
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, 0)) #Comentar isso dps
for i in range(len(distancias)):
if i <= 40:
if converte(distancias[i]) < 50 and converte(distancias[i]) >= 30:
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, -0.7))
desviando = True
print("frente e")
elif converte(distancias[i]) < 30 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(-0.1, 0, 0), Vector3(0, 0, -0.9))
desviando = True
print("mt frente e")
if menor_frente_esquerda > converte(distancias[i]):
menor_frente_esquerda = converte(distancias[i])
if i >= 320:
if converte(distancias[i]) < 50 and converte(distancias[i]) >= 30:
velocidade = Twist(Vector3(0.2, 0, 0), Vector3(0, 0, 0.7))
desviando = True
print("frente d")
elif converte(distancias[i]) < 30 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(-0.1, 0, 0), Vector3(0, 0, 0.9))
desviando = True
print("mt frente d")
if menor_frente_direita > converte(distancias[i]):
menor_frente_direita = converte(distancias[i])
if i <= 70 and i > 40:
if converte(distancias[i]) < 25 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(0.1, 0, 0), Vector3(0, 0, -0.5))
desviando = True
print("mt esq")
if i < 320 and i >= 290:
if converte(distancias[i]) < 25 and converte(distancias[i]) != 0:
velocidade = Twist(Vector3(0.1, 0, 0), Vector3(0, 0, 0.5))
desviando = True
print("mt dir")
velocidade_saida.publish(velocidade)
#print(np.array(dado.ranges).round(decimals=2))
#print("Intensities")
#print(np.array(dado.intensities).round(decimals=2))
if desviando:
return 'desviando'
else:
return 'desviado'
if __name__=="__main__":
global velocidade_saida
rospy.init_node("desviar")
velocidade_saida = rospy.Publisher("/cmd_vel", Twist, queue_size = 2 )
recebe_scan = rospy.Subscriber("/scan", LaserScan, scaneou)
while not rospy.is_shutdown():
print("Oeee")
rospy.sleep(0.5) | 0.071892 | 0.39257 |
import base64
from asyncio import sleep
from os import sep, remove, listdir
from os.path import isfile, exists
from time import strftime, localtime
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import alias_command, execute, pip_install
pip_install("pyncm")
from mutagen.mp3 import EasyMP3
from mutagen.id3 import ID3, APIC
from mutagen.flac import FLAC, Picture
from mutagen.oggvorbis import OggVorbis
from pyncm import GetCurrentSession, apis, DumpSessionAsString, SetCurrentSession, LoadSessionFromString
from pyncm.utils.helper import TrackHelper
from pyncm.apis import LoginFailedException
from pyncm.apis.cloudsearch import CloudSearchType
from pyncm.apis.login import LoginLogout
from telethon.tl.types import DocumentAttributeAudio
def download_by_url(url, dest):
# Downloads generic content
response = GetCurrentSession().get(url, stream=True)
with open(dest, 'wb') as f:
for chunk in response.iter_content(1024 * 2 ** 10):
f.write(chunk) # write every 1MB read
return dest
def gen_author(song_info: dict) -> str:
data = []
for i in song_info["songs"][0]["ar"]:
data.append(i["name"])
return " ".join(data)
def get_duration(song_info: dict, track_info: dict) -> int:
if track_info["data"][0]["freeTrialInfo"]:
return track_info["data"][0]["freeTrialInfo"]["end"] - track_info["data"][0]["freeTrialInfo"]["start"]
else:
return int(song_info["songs"][0]["dt"] / 1000)
def tag_audio(track, file: str, cover_img: str = ''):
def write_keys(song):
# Write trackdatas
song['title'] = track.TrackName
song['artist'] = track.Artists
song['album'] = track.AlbumName
song['tracknumber'] = str(track.TrackNumber)
song['date'] = str(track.TrackPublishTime)
song.save()
def mp3():
song = EasyMP3(file)
write_keys(song)
if exists(cover_img):
song = ID3(file)
song.update_to_v23() # better compatibility over v2.4
song.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='',
data=open(cover_img, 'rb').read()))
song.save(v2_version=3)
def flac():
song = FLAC(file)
write_keys(song)
if exists(cover_img):
pic = Picture()
pic.data = open(cover_img, 'rb').read()
pic.mime = 'image/jpeg'
song.add_picture(pic)
song.save()
def ogg():
song = OggVorbis(file)
write_keys(song)
if exists(cover_img):
pic = Picture()
pic.data = open(cover_img, 'rb').read()
pic.mime = 'image/jpeg'
song["metadata_block_picture"] = [base64.b64encode(pic.write()).decode('ascii')]
song.save()
format_ = file.split('.')[-1].upper()
for ext, method in [({'MP3'}, mp3), ({'FLAC'}, flac), ({'OGG', 'OGV'}, ogg)]:
if format_ in ext:
return method() or True
return False
async def netease_down(track_info: dict, song_info: dict, song) -> str:
if not isfile(f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}'):
# Downloding source audio
download_by_url(track_info["data"][0]["url"],
f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}')
# Downloading cover
if not isfile(f'data{sep}{song_info["songs"][0]["name"]}.jpg'):
download_by_url(song.AlbumCover,
f'data{sep}{song_info["songs"][0]["name"]}.jpg')
# 设置标签
tag_audio(song, f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}',
f'data{sep}{song_info["songs"][0]["name"]}.jpg')
# 返回
return f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}'
ned_help_msg = f"""
网易云搜/点歌。
i.e.
`-{alias_command('ned')} 失眠飞行 兔籽鲸 / 雨客Yoker` # 通过歌曲名称+歌手(可选)点歌
`-{alias_command('ned')} see you again -f` # 通过 -f 参数点播 flac 最高音质
`-{alias_command('ned')} 1430702717` # 通过歌曲 ID 点歌
`-{alias_command('ned')} login` # 显示登录信息
`-{alias_command('ned')} login 手机号码 密码` # 登录账号
`-{alias_command('ned')} logout` # 登出
`-{alias_command('ned')} clear` # 手动清除缓存
"""
@listener(is_plugin=True, outgoing=True, command=alias_command("ned"),
description=ned_help_msg,
parameters="{关键词/id}/{login <账号> <密码>}/{clear}")
async def ned(context):
if len(context.parameter) < 1:
# 使用方法
await context.edit(ned_help_msg)
return
# 加载登录信息
if isfile(f"data{sep}session.ncm"):
with open(f"data{sep}session.ncm") as f:
SetCurrentSession(LoadSessionFromString(f.read()))
# 海外用户
GetCurrentSession().headers['X-Real-IP'] = '172.16.58.3'
# 处理账号登录
if context.parameter[0] == "login":
# 显示登录信息
if len(context.parameter) == 1:
login_info = GetCurrentSession().login_info
if login_info["success"]:
# 获取VIP类型
if login_info['content']['account']['vipType'] != 0:
vip_type = "**VIP**"
else:
vip_type = "**普通**"
# 获取账号创建时间
time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
if context.is_group:
await context.edit(f"[ned] 已登录{vip_type}账号,账号创建时间:`{time}`")
else:
await context.edit(f"[ned] 已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
f"账号创建时间:`{time}`")
else:
await context.edit(f"[ned] **未登录/登录失败**,额外信息:`{login_info['content']}`")
return
# 过滤空参数
if len(context.parameter) == 2:
# 登录命令格式错误
await context.edit(f"**使用方法:** `-{alias_command('ned')} <账号> <密码>`")
return
# 开始登录
try:
apis.login.LoginViaCellphone(context.parameter[1], context.parameter[2])
except LoginFailedException:
await context.edit("**登录失败**,请检查账号密码是否正确。")
return
# 获取登录信息
login_info = GetCurrentSession().login_info
# 获取VIP类型
if login_info['content']['account']['vipType'] != 0:
vip_type = "**VIP**"
else:
vip_type = "**普通**"
# 获取账号创建时间
time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
if context.is_group:
await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号,账号创建时间:`{time}`")
else:
await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
f"账号创建时间:`{time}`")
# 保存登录信息
with open(f"data{sep}session.ncm", 'w+') as f:
f.write(DumpSessionAsString(GetCurrentSession()))
return
elif context.parameter[0] == "logout":
# 登出
LoginLogout()
if isfile(f"data{sep}session.ncm"):
remove(f"data{sep}session.ncm")
return await context.edit("[ned] 账号登出成功。")
elif context.parameter[0] == "clear":
# 清除歌曲缓存
for i in listdir("data"):
if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
remove(f"data{sep}{i}")
await context.edit("[ned] **已清除缓存**")
return
# 搜索歌曲
# 判断是否使用最高比特率解析
flac_mode = True if context.arguments.find("-f") != -1 else False
song_id = context.arguments.replace("-f", "").replace("\u200b", "").strip()
# id
if song_id.isdigit():
song_id = int(song_id)
else:
search_data = apis.cloudsearch.GetSearchResult(song_id, CloudSearchType(1), 1)
if search_data.get("result", {}).get("songCount", 0) >= 1:
song_id = search_data["result"]["songs"][0]["id"]
else:
await context.edit(f"**没有找到歌曲**,请检查歌曲名称是否正确。")
return
# 获取歌曲质量是否大于 320k HQ
track_info = apis.track.GetTrackAudio([song_id], bitrate=3200 * 1000 if flac_mode else 320000)
# 获取歌曲详情
song_info = apis.track.GetTrackDetail([song_id])
if track_info["data"][0]["code"] == 404:
await context.edit(f"**没有找到歌曲**,请检查歌曲id是否正确。")
return
await context.edit(f"正在下载歌曲:**{song_info['songs'][0]['name']} - {gen_author(song_info)}** "
f"{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB")
# 下载歌曲并且设置歌曲标签
song = TrackHelper(song_info['songs'][0])
# 转义
for char in song_info["songs"][0]["name"]:
if char in ['/', '\\', ':', '*', '?', '"', '<', '>', '|']:
song_info["songs"][0]["name"] = song_info["songs"][0]["name"].replace(char, '')
path = await netease_down(track_info, song_info, song)
await context.edit("正在上传歌曲。。。")
# 上传歌曲
cap_ = ""
# 提醒登录VIP账号
if track_info["data"][0]["freeTrialInfo"]:
cap_ = f"**非VIP,正在试听 {track_info['data'][0]['freeTrialInfo']['start']}s ~ \n" \
f"{track_info['data'][0]['freeTrialInfo']['end']}s**\n"
cap = f"「**{song_info['songs'][0]['name']}**」\n" \
f"{gen_author(song_info)}\n" \
f"文件大小:{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB\n" \
f"\n{cap_}" \
f"#netease #{int(track_info['data'][0]['br'] / 1000)}kbps #{track_info['data'][0]['type']}"
await context.client.send_file(
context.chat_id,
path,
reply_to=context.message.reply_to_msg_id,
caption=cap,
link_preview=False,
force_document=False,
thumb=f'data{sep}{song_info["songs"][0]["name"]}.jpg',
attributes=(DocumentAttributeAudio(
get_duration(song_info, track_info), False, song_info['songs'][0]['name'], gen_author(song_info)),)
)
await context.delete()
# 过多文件自动清理
if len(listdir("data")) > 100:
for i in listdir("data"):
if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
remove(f"data{sep}{i}")
msg = await context.respond("[ned] **已自动清除缓存**")
await sleep(3)
await msg.delete() | neteasedown.py |
import base64
from asyncio import sleep
from os import sep, remove, listdir
from os.path import isfile, exists
from time import strftime, localtime
from pagermaid import version
from pagermaid.listener import listener
from pagermaid.utils import alias_command, execute, pip_install
pip_install("pyncm")
from mutagen.mp3 import EasyMP3
from mutagen.id3 import ID3, APIC
from mutagen.flac import FLAC, Picture
from mutagen.oggvorbis import OggVorbis
from pyncm import GetCurrentSession, apis, DumpSessionAsString, SetCurrentSession, LoadSessionFromString
from pyncm.utils.helper import TrackHelper
from pyncm.apis import LoginFailedException
from pyncm.apis.cloudsearch import CloudSearchType
from pyncm.apis.login import LoginLogout
from telethon.tl.types import DocumentAttributeAudio
def download_by_url(url, dest):
# Downloads generic content
response = GetCurrentSession().get(url, stream=True)
with open(dest, 'wb') as f:
for chunk in response.iter_content(1024 * 2 ** 10):
f.write(chunk) # write every 1MB read
return dest
def gen_author(song_info: dict) -> str:
data = []
for i in song_info["songs"][0]["ar"]:
data.append(i["name"])
return " ".join(data)
def get_duration(song_info: dict, track_info: dict) -> int:
if track_info["data"][0]["freeTrialInfo"]:
return track_info["data"][0]["freeTrialInfo"]["end"] - track_info["data"][0]["freeTrialInfo"]["start"]
else:
return int(song_info["songs"][0]["dt"] / 1000)
def tag_audio(track, file: str, cover_img: str = ''):
def write_keys(song):
# Write trackdatas
song['title'] = track.TrackName
song['artist'] = track.Artists
song['album'] = track.AlbumName
song['tracknumber'] = str(track.TrackNumber)
song['date'] = str(track.TrackPublishTime)
song.save()
def mp3():
song = EasyMP3(file)
write_keys(song)
if exists(cover_img):
song = ID3(file)
song.update_to_v23() # better compatibility over v2.4
song.add(APIC(encoding=3, mime='image/jpeg', type=3, desc='',
data=open(cover_img, 'rb').read()))
song.save(v2_version=3)
def flac():
song = FLAC(file)
write_keys(song)
if exists(cover_img):
pic = Picture()
pic.data = open(cover_img, 'rb').read()
pic.mime = 'image/jpeg'
song.add_picture(pic)
song.save()
def ogg():
song = OggVorbis(file)
write_keys(song)
if exists(cover_img):
pic = Picture()
pic.data = open(cover_img, 'rb').read()
pic.mime = 'image/jpeg'
song["metadata_block_picture"] = [base64.b64encode(pic.write()).decode('ascii')]
song.save()
format_ = file.split('.')[-1].upper()
for ext, method in [({'MP3'}, mp3), ({'FLAC'}, flac), ({'OGG', 'OGV'}, ogg)]:
if format_ in ext:
return method() or True
return False
async def netease_down(track_info: dict, song_info: dict, song) -> str:
if not isfile(f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}'):
# Downloding source audio
download_by_url(track_info["data"][0]["url"],
f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}')
# Downloading cover
if not isfile(f'data{sep}{song_info["songs"][0]["name"]}.jpg'):
download_by_url(song.AlbumCover,
f'data{sep}{song_info["songs"][0]["name"]}.jpg')
# 设置标签
tag_audio(song, f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}',
f'data{sep}{song_info["songs"][0]["name"]}.jpg')
# 返回
return f'data{sep}{song_info["songs"][0]["name"]}.{track_info["data"][0]["type"]}'
ned_help_msg = f"""
网易云搜/点歌。
i.e.
`-{alias_command('ned')} 失眠飞行 兔籽鲸 / 雨客Yoker` # 通过歌曲名称+歌手(可选)点歌
`-{alias_command('ned')} see you again -f` # 通过 -f 参数点播 flac 最高音质
`-{alias_command('ned')} 1430702717` # 通过歌曲 ID 点歌
`-{alias_command('ned')} login` # 显示登录信息
`-{alias_command('ned')} login 手机号码 密码` # 登录账号
`-{alias_command('ned')} logout` # 登出
`-{alias_command('ned')} clear` # 手动清除缓存
"""
@listener(is_plugin=True, outgoing=True, command=alias_command("ned"),
description=ned_help_msg,
parameters="{关键词/id}/{login <账号> <密码>}/{clear}")
async def ned(context):
if len(context.parameter) < 1:
# 使用方法
await context.edit(ned_help_msg)
return
# 加载登录信息
if isfile(f"data{sep}session.ncm"):
with open(f"data{sep}session.ncm") as f:
SetCurrentSession(LoadSessionFromString(f.read()))
# 海外用户
GetCurrentSession().headers['X-Real-IP'] = '172.16.58.3'
# 处理账号登录
if context.parameter[0] == "login":
# 显示登录信息
if len(context.parameter) == 1:
login_info = GetCurrentSession().login_info
if login_info["success"]:
# 获取VIP类型
if login_info['content']['account']['vipType'] != 0:
vip_type = "**VIP**"
else:
vip_type = "**普通**"
# 获取账号创建时间
time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
if context.is_group:
await context.edit(f"[ned] 已登录{vip_type}账号,账号创建时间:`{time}`")
else:
await context.edit(f"[ned] 已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
f"账号创建时间:`{time}`")
else:
await context.edit(f"[ned] **未登录/登录失败**,额外信息:`{login_info['content']}`")
return
# 过滤空参数
if len(context.parameter) == 2:
# 登录命令格式错误
await context.edit(f"**使用方法:** `-{alias_command('ned')} <账号> <密码>`")
return
# 开始登录
try:
apis.login.LoginViaCellphone(context.parameter[1], context.parameter[2])
except LoginFailedException:
await context.edit("**登录失败**,请检查账号密码是否正确。")
return
# 获取登录信息
login_info = GetCurrentSession().login_info
# 获取VIP类型
if login_info['content']['account']['vipType'] != 0:
vip_type = "**VIP**"
else:
vip_type = "**普通**"
# 获取账号创建时间
time = strftime("%Y-%m-%d %H:%M:%S", localtime(login_info['content']['account']['createTime'] / 1000))
if context.is_group:
await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号,账号创建时间:`{time}`")
else:
await context.edit(f"[ned] **登录成功**,已登录{vip_type}账号:`{login_info['content']['profile']['nickname']}`,"
f"账号创建时间:`{time}`")
# 保存登录信息
with open(f"data{sep}session.ncm", 'w+') as f:
f.write(DumpSessionAsString(GetCurrentSession()))
return
elif context.parameter[0] == "logout":
# 登出
LoginLogout()
if isfile(f"data{sep}session.ncm"):
remove(f"data{sep}session.ncm")
return await context.edit("[ned] 账号登出成功。")
elif context.parameter[0] == "clear":
# 清除歌曲缓存
for i in listdir("data"):
if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
remove(f"data{sep}{i}")
await context.edit("[ned] **已清除缓存**")
return
# 搜索歌曲
# 判断是否使用最高比特率解析
flac_mode = True if context.arguments.find("-f") != -1 else False
song_id = context.arguments.replace("-f", "").replace("\u200b", "").strip()
# id
if song_id.isdigit():
song_id = int(song_id)
else:
search_data = apis.cloudsearch.GetSearchResult(song_id, CloudSearchType(1), 1)
if search_data.get("result", {}).get("songCount", 0) >= 1:
song_id = search_data["result"]["songs"][0]["id"]
else:
await context.edit(f"**没有找到歌曲**,请检查歌曲名称是否正确。")
return
# 获取歌曲质量是否大于 320k HQ
track_info = apis.track.GetTrackAudio([song_id], bitrate=3200 * 1000 if flac_mode else 320000)
# 获取歌曲详情
song_info = apis.track.GetTrackDetail([song_id])
if track_info["data"][0]["code"] == 404:
await context.edit(f"**没有找到歌曲**,请检查歌曲id是否正确。")
return
await context.edit(f"正在下载歌曲:**{song_info['songs'][0]['name']} - {gen_author(song_info)}** "
f"{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB")
# 下载歌曲并且设置歌曲标签
song = TrackHelper(song_info['songs'][0])
# 转义
for char in song_info["songs"][0]["name"]:
if char in ['/', '\\', ':', '*', '?', '"', '<', '>', '|']:
song_info["songs"][0]["name"] = song_info["songs"][0]["name"].replace(char, '')
path = await netease_down(track_info, song_info, song)
await context.edit("正在上传歌曲。。。")
# 上传歌曲
cap_ = ""
# 提醒登录VIP账号
if track_info["data"][0]["freeTrialInfo"]:
cap_ = f"**非VIP,正在试听 {track_info['data'][0]['freeTrialInfo']['start']}s ~ \n" \
f"{track_info['data'][0]['freeTrialInfo']['end']}s**\n"
cap = f"「**{song_info['songs'][0]['name']}**」\n" \
f"{gen_author(song_info)}\n" \
f"文件大小:{round(track_info['data'][0]['size'] / 1000 / 1000, 2)} MB\n" \
f"\n{cap_}" \
f"#netease #{int(track_info['data'][0]['br'] / 1000)}kbps #{track_info['data'][0]['type']}"
await context.client.send_file(
context.chat_id,
path,
reply_to=context.message.reply_to_msg_id,
caption=cap,
link_preview=False,
force_document=False,
thumb=f'data{sep}{song_info["songs"][0]["name"]}.jpg',
attributes=(DocumentAttributeAudio(
get_duration(song_info, track_info), False, song_info['songs'][0]['name'], gen_author(song_info)),)
)
await context.delete()
# 过多文件自动清理
if len(listdir("data")) > 100:
for i in listdir("data"):
if i.find(".mp3") != -1 or i.find(".jpg") != -1 or i.find(".flac") != -1 or i.find(".ogg") != -1:
remove(f"data{sep}{i}")
msg = await context.respond("[ned] **已自动清除缓存**")
await sleep(3)
await msg.delete() | 0.298594 | 0.077622 |
### I. Initialisation
# Fundamental libraries
import os
import re
import sys
import time
import glob
import random
import datetime
import warnings
import itertools
import numpy as np
import pandas as pd
import pickle as cp
import seaborn as sns
import multiprocessing
from scipy import stats
from pathlib import Path
from ast import literal_eval
import matplotlib.pyplot as plt
from collections import Counter
from argparse import ArgumentParser
from pandas.api.types import CategoricalDtype
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
warnings.filterwarnings(action="ignore")
# TQDM for progress tracking
from tqdm import tqdm
# Custom analysis functions
from functions.analysis import collect_metrics
# Define directories in which CPM performance metrics are saved
performance_dir = '../model_performance/CPM'
# Define number of cores for parallel processing
NUM_CORES = multiprocessing.cpu_count()
### II. Compile all CPM_deep performance metrics
# Search for all performance metric files in the CPM_DeepMN directory
deepMN_metric_files = []
for path in Path(os.path.join(performance_dir,'deepMN')).rglob('*.csv'):
deepMN_metric_files.append(str(path.resolve()))
# Search for all performance metric files in the CPM_DeepOR directory
deepOR_metric_files = []
for path in Path(os.path.join(performance_dir,'deepOR')).rglob('*.csv'):
deepOR_metric_files.append(str(path.resolve()))
# Concatenate lists of performance metric files
metric_files = deepMN_metric_files+deepOR_metric_files
# Characterise list of discovered performance metric files
metric_info_df = pd.DataFrame({'file':metric_files,
'MODEL':['CPM_D'+re.search('CPM/d(.*)/resample', curr_file).group(1) for curr_file in metric_files],
'RESAMPLE_IDX':[int(re.search('/resample(.*)/deep', curr_file).group(1)) for curr_file in metric_files],
'METRIC':[re.search('/deep_(.*).csv', curr_file).group(1) for curr_file in metric_files]
}).sort_values(by=['MODEL','RESAMPLE_IDX','METRIC']).reset_index(drop=True)
# Iterate through unique metric types and compile CPM_deep results into a single dataframe
for curr_metric in metric_info_df.METRIC.unique():
# Filter files of current metric
curr_metric_info_df = metric_info_df[metric_info_df.METRIC == curr_metric].reset_index(drop=True)
# Partition current metric files among cores
s = [curr_metric_info_df.shape[0] // NUM_CORES for _ in range(NUM_CORES)]
s[:(curr_metric_info_df.shape[0] - sum(s))] = [over+1 for over in s[:(curr_metric_info_df.shape[0] - sum(s))]]
end_idx = np.cumsum(s)
start_idx = np.insert(end_idx[:-1],0,0)
# Collect current metric performance files in parallel
curr_files_per_core = [(curr_metric_info_df.iloc[start_idx[idx]:end_idx[idx],:].reset_index(drop=True),True,'CPM_deep metric extraction: '+curr_metric) for idx in range(len(start_idx))]
with multiprocessing.Pool(NUM_CORES) as pool:
compiled_curr_metric_values = pd.concat(pool.starmap(collect_metrics, curr_files_per_core),ignore_index=True)
# Save compiled values of current metric type into model performance directory
compiled_curr_metric_values.to_csv(os.path.join(performance_dir,'deep_'+curr_metric+'.csv'),index=False)
### III. Calculate confidence intervals on all CPM performance metrics
## Threshold-level ROCs
# Load and compile ROCs
CPM_compiled_ROCs = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_ROCs.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_ROCs.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_ROCs = CPM_compiled_ROCs.groupby(['MODEL','Threshold','FPR'],as_index=False)['TPR'].aggregate({'TPR_mean':np.mean,'TPR_std':np.std,'TPR_median':np.median,'TPR_lo':lambda x: np.quantile(x,.025),'TPR_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_ROCs[['FPR','TPR_mean','TPR_std','TPR_median','TPR_lo','TPR_hi']] = CI_CPM_compiled_ROCs[['FPR','TPR_mean','TPR_std','TPR_median','TPR_lo','TPR_hi']].clip(0,1)
# Save 95% confidence intervals for ROC
CI_CPM_compiled_ROCs.to_csv(os.path.join(performance_dir,'CI_ROCs.csv'))
## Threshold-level calibration curves
# Load and compile calibration curves
CPM_compiled_calibration = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_calibration.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_calibration.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_calibration = CPM_compiled_calibration.groupby(['MODEL','Threshold','PredProb'],as_index=False)['TrueProb'].aggregate({'TrueProb_mean':np.mean,'TrueProb_std':np.std,'TrueProb_median':np.median,'TrueProb_lo':lambda x: np.quantile(x,.025),'TrueProb_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_calibration[['PredProb','TrueProb_mean','TrueProb_std','TrueProb_median','TrueProb_lo','TrueProb_hi']] = CI_CPM_compiled_calibration[['PredProb','TrueProb_mean','TrueProb_std','TrueProb_median','TrueProb_lo','TrueProb_hi']].clip(0,1)
# Save 95% confidence intervals for calibration curves
CI_CPM_compiled_calibration.to_csv(os.path.join(performance_dir,'CI_calibration.csv'))
## Classification confusion matrices
# Load and compile normalised confusion matrices
CPM_compiled_cm = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_confusion_matrices.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_confusion_matrices.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_cm = CPM_compiled_cm.groupby(['MODEL','TrueLabel','PredLabel'],as_index=False)['cm_prob'].aggregate({'cm_prob_mean':np.mean,'cm_prob_std':np.std,'cm_prob_median':np.median,'cm_prob_lo':lambda x: np.quantile(x,.025),'cm_prob_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_cm[['cm_prob_mean','cm_prob_std','cm_prob_median','cm_prob_lo','cm_prob_hi']] = CI_CPM_compiled_cm[['cm_prob_mean','cm_prob_std','cm_prob_median','cm_prob_lo','cm_prob_hi']].clip(0,1)
# Save 95% confidence intervals for normalised confusion matrices
CI_CPM_compiled_cm.to_csv(os.path.join(performance_dir,'CI_confusion_matrices.csv'))
## Overall performance metrics
# Load and compile overall performance metrics
CPM_compiled_overall = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_overall_metrics.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_overall_metrics.csv'))],ignore_index=True)
# Melt overall performance metric dataframe into long format
CPM_compiled_overall = pd.melt(CPM_compiled_overall,id_vars=['MODEL','RESAMPLE_IDX'],var_name='METRIC', value_name='VALUE')
# Calculate 95% confidence intervals for each metric
CI_CPM_overall = CPM_compiled_overall.groupby(['MODEL','METRIC'],as_index=False)['VALUE'].aggregate({'mean':np.mean,'std':np.std,'median':np.median,'lo':lambda x: np.quantile(x,.025),'hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_overall.to_csv(os.path.join(performance_dir,'CI_overall_metrics.csv'),index=False)
## Threshold-level performance metrics
# Load and compile threshold-level performance metrics
CPM_compiled_threshold = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_threshold_metrics.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_threshold_metrics.csv'))],ignore_index=True)
# Melt threshold-level performance metric dataframe into long format
CPM_compiled_threshold = pd.melt(CPM_compiled_threshold,id_vars=['MODEL','Threshold','RESAMPLE_IDX'],var_name='METRIC', value_name='VALUE')
# Calculate macro-averages for each threshold-level metric
macro_CPM_compiled_threshold = CPM_compiled_threshold.groupby(['MODEL','RESAMPLE_IDX','METRIC'],as_index=False)['VALUE'].mean()
macro_CPM_compiled_threshold['Threshold'] = 'Average'
# Concatenate macr-averaged metrics to compiled threshold-level metric dataframe
CPM_compiled_threshold = pd.concat([CPM_compiled_threshold,macro_CPM_compiled_threshold],ignore_index=True)
# Calculate 95% confidence intervals for each metric
CI_CPM_threshold = CPM_compiled_threshold.groupby(['MODEL','Threshold','METRIC'],as_index=False)['VALUE'].aggregate({'mean':np.mean,'std':np.std,'median':np.median,'lo':lambda x: np.quantile(x,.025),'hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_threshold.to_csv(os.path.join(performance_dir,'CI_threshold_metrics.csv'),index=False) | scripts/07b_CPM_compile_metrics.py |
### I. Initialisation
# Fundamental libraries
import os
import re
import sys
import time
import glob
import random
import datetime
import warnings
import itertools
import numpy as np
import pandas as pd
import pickle as cp
import seaborn as sns
import multiprocessing
from scipy import stats
from pathlib import Path
from ast import literal_eval
import matplotlib.pyplot as plt
from collections import Counter
from argparse import ArgumentParser
from pandas.api.types import CategoricalDtype
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
warnings.filterwarnings(action="ignore")
# TQDM for progress tracking
from tqdm import tqdm
# Custom analysis functions
from functions.analysis import collect_metrics
# Define directories in which CPM performance metrics are saved
performance_dir = '../model_performance/CPM'
# Define number of cores for parallel processing
NUM_CORES = multiprocessing.cpu_count()
### II. Compile all CPM_deep performance metrics
# Search for all performance metric files in the CPM_DeepMN directory
deepMN_metric_files = []
for path in Path(os.path.join(performance_dir,'deepMN')).rglob('*.csv'):
deepMN_metric_files.append(str(path.resolve()))
# Search for all performance metric files in the CPM_DeepOR directory
deepOR_metric_files = []
for path in Path(os.path.join(performance_dir,'deepOR')).rglob('*.csv'):
deepOR_metric_files.append(str(path.resolve()))
# Concatenate lists of performance metric files
metric_files = deepMN_metric_files+deepOR_metric_files
# Characterise list of discovered performance metric files
metric_info_df = pd.DataFrame({'file':metric_files,
'MODEL':['CPM_D'+re.search('CPM/d(.*)/resample', curr_file).group(1) for curr_file in metric_files],
'RESAMPLE_IDX':[int(re.search('/resample(.*)/deep', curr_file).group(1)) for curr_file in metric_files],
'METRIC':[re.search('/deep_(.*).csv', curr_file).group(1) for curr_file in metric_files]
}).sort_values(by=['MODEL','RESAMPLE_IDX','METRIC']).reset_index(drop=True)
# Iterate through unique metric types and compile CPM_deep results into a single dataframe
for curr_metric in metric_info_df.METRIC.unique():
# Filter files of current metric
curr_metric_info_df = metric_info_df[metric_info_df.METRIC == curr_metric].reset_index(drop=True)
# Partition current metric files among cores
s = [curr_metric_info_df.shape[0] // NUM_CORES for _ in range(NUM_CORES)]
s[:(curr_metric_info_df.shape[0] - sum(s))] = [over+1 for over in s[:(curr_metric_info_df.shape[0] - sum(s))]]
end_idx = np.cumsum(s)
start_idx = np.insert(end_idx[:-1],0,0)
# Collect current metric performance files in parallel
curr_files_per_core = [(curr_metric_info_df.iloc[start_idx[idx]:end_idx[idx],:].reset_index(drop=True),True,'CPM_deep metric extraction: '+curr_metric) for idx in range(len(start_idx))]
with multiprocessing.Pool(NUM_CORES) as pool:
compiled_curr_metric_values = pd.concat(pool.starmap(collect_metrics, curr_files_per_core),ignore_index=True)
# Save compiled values of current metric type into model performance directory
compiled_curr_metric_values.to_csv(os.path.join(performance_dir,'deep_'+curr_metric+'.csv'),index=False)
### III. Calculate confidence intervals on all CPM performance metrics
## Threshold-level ROCs
# Load and compile ROCs
CPM_compiled_ROCs = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_ROCs.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_ROCs.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_ROCs = CPM_compiled_ROCs.groupby(['MODEL','Threshold','FPR'],as_index=False)['TPR'].aggregate({'TPR_mean':np.mean,'TPR_std':np.std,'TPR_median':np.median,'TPR_lo':lambda x: np.quantile(x,.025),'TPR_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_ROCs[['FPR','TPR_mean','TPR_std','TPR_median','TPR_lo','TPR_hi']] = CI_CPM_compiled_ROCs[['FPR','TPR_mean','TPR_std','TPR_median','TPR_lo','TPR_hi']].clip(0,1)
# Save 95% confidence intervals for ROC
CI_CPM_compiled_ROCs.to_csv(os.path.join(performance_dir,'CI_ROCs.csv'))
## Threshold-level calibration curves
# Load and compile calibration curves
CPM_compiled_calibration = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_calibration.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_calibration.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_calibration = CPM_compiled_calibration.groupby(['MODEL','Threshold','PredProb'],as_index=False)['TrueProb'].aggregate({'TrueProb_mean':np.mean,'TrueProb_std':np.std,'TrueProb_median':np.median,'TrueProb_lo':lambda x: np.quantile(x,.025),'TrueProb_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_calibration[['PredProb','TrueProb_mean','TrueProb_std','TrueProb_median','TrueProb_lo','TrueProb_hi']] = CI_CPM_compiled_calibration[['PredProb','TrueProb_mean','TrueProb_std','TrueProb_median','TrueProb_lo','TrueProb_hi']].clip(0,1)
# Save 95% confidence intervals for calibration curves
CI_CPM_compiled_calibration.to_csv(os.path.join(performance_dir,'CI_calibration.csv'))
## Classification confusion matrices
# Load and compile normalised confusion matrices
CPM_compiled_cm = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_confusion_matrices.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_confusion_matrices.csv'))],ignore_index=True)
# Calculate 95% confidence intervals
CI_CPM_compiled_cm = CPM_compiled_cm.groupby(['MODEL','TrueLabel','PredLabel'],as_index=False)['cm_prob'].aggregate({'cm_prob_mean':np.mean,'cm_prob_std':np.std,'cm_prob_median':np.median,'cm_prob_lo':lambda x: np.quantile(x,.025),'cm_prob_hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_compiled_cm[['cm_prob_mean','cm_prob_std','cm_prob_median','cm_prob_lo','cm_prob_hi']] = CI_CPM_compiled_cm[['cm_prob_mean','cm_prob_std','cm_prob_median','cm_prob_lo','cm_prob_hi']].clip(0,1)
# Save 95% confidence intervals for normalised confusion matrices
CI_CPM_compiled_cm.to_csv(os.path.join(performance_dir,'CI_confusion_matrices.csv'))
## Overall performance metrics
# Load and compile overall performance metrics
CPM_compiled_overall = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_overall_metrics.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_overall_metrics.csv'))],ignore_index=True)
# Melt overall performance metric dataframe into long format
CPM_compiled_overall = pd.melt(CPM_compiled_overall,id_vars=['MODEL','RESAMPLE_IDX'],var_name='METRIC', value_name='VALUE')
# Calculate 95% confidence intervals for each metric
CI_CPM_overall = CPM_compiled_overall.groupby(['MODEL','METRIC'],as_index=False)['VALUE'].aggregate({'mean':np.mean,'std':np.std,'median':np.median,'lo':lambda x: np.quantile(x,.025),'hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_overall.to_csv(os.path.join(performance_dir,'CI_overall_metrics.csv'),index=False)
## Threshold-level performance metrics
# Load and compile threshold-level performance metrics
CPM_compiled_threshold = pd.concat([pd.read_csv(os.path.join(performance_dir,'deep_threshold_metrics.csv')),pd.read_csv(os.path.join(performance_dir,'logreg_threshold_metrics.csv'))],ignore_index=True)
# Melt threshold-level performance metric dataframe into long format
CPM_compiled_threshold = pd.melt(CPM_compiled_threshold,id_vars=['MODEL','Threshold','RESAMPLE_IDX'],var_name='METRIC', value_name='VALUE')
# Calculate macro-averages for each threshold-level metric
macro_CPM_compiled_threshold = CPM_compiled_threshold.groupby(['MODEL','RESAMPLE_IDX','METRIC'],as_index=False)['VALUE'].mean()
macro_CPM_compiled_threshold['Threshold'] = 'Average'
# Concatenate macr-averaged metrics to compiled threshold-level metric dataframe
CPM_compiled_threshold = pd.concat([CPM_compiled_threshold,macro_CPM_compiled_threshold],ignore_index=True)
# Calculate 95% confidence intervals for each metric
CI_CPM_threshold = CPM_compiled_threshold.groupby(['MODEL','Threshold','METRIC'],as_index=False)['VALUE'].aggregate({'mean':np.mean,'std':np.std,'median':np.median,'lo':lambda x: np.quantile(x,.025),'hi':lambda x: np.quantile(x,.975),'resamples':'count'}).reset_index(drop=True)
CI_CPM_threshold.to_csv(os.path.join(performance_dir,'CI_threshold_metrics.csv'),index=False) | 0.564819 | 0.24262 |
import os
__ALL__ = ["colored", "cprint"]
VERSION = (1, 1, 0)
ATTRIBUTES = dict(
list(
zip(
[
"bold",
"dark",
"",
"underline",
"blink",
"",
"reverse",
"concealed",
],
list(range(1, 9)),
)
)
)
del ATTRIBUTES[""]
HIGHLIGHTS = dict(
list(
zip(
[
"on_grey",
"on_red",
"on_green",
"on_yellow",
"on_blue",
"on_magenta",
"on_cyan",
"on_white",
],
list(range(40, 48)),
)
)
)
COLORS = dict(
list(
zip(
[
"grey",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
],
list(range(30, 38)),
)
)
)
RESET = "\033[0m"
def colored(text, color=None, on_color=None, attrs=None):
"""Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv("ANSI_COLORS_DISABLED") is None:
fmt_str = "\033[%dm%s"
if color is not None:
text = fmt_str % (COLORS[color], text)
if on_color is not None:
text = fmt_str % (HIGHLIGHTS[on_color], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
def cprint(text, color=None, on_color=None, attrs=None, **kwargs):
"""Print colorize text.
It accepts arguments of print function.
"""
print((colored(text, color, on_color, attrs)), **kwargs)
if __name__ == "__main__":
print("Current terminal type: %s" % os.getenv("TERM"))
print("Test basic colors:")
cprint("Grey color", "grey")
cprint("Red color", "red")
cprint("Green color", "green")
cprint("Yellow color", "yellow")
cprint("Blue color", "blue")
cprint("Magenta color", "magenta")
cprint("Cyan color", "cyan")
cprint("White color", "white")
print("-" * 78)
print("Test highlights:")
cprint("On grey color", on_color="on_grey")
cprint("On red color", on_color="on_red")
cprint("On green color", on_color="on_green")
cprint("On yellow color", on_color="on_yellow")
cprint("On blue color", on_color="on_blue")
cprint("On magenta color", on_color="on_magenta")
cprint("On cyan color", on_color="on_cyan")
cprint("On white color", color="grey", on_color="on_white")
print("-" * 78)
print("Test attributes:")
cprint("Bold grey color", "grey", attrs=["bold"])
cprint("Dark red color", "red", attrs=["dark"])
cprint("Underline green color", "green", attrs=["underline"])
cprint("Blink yellow color", "yellow", attrs=["blink"])
cprint("Reversed blue color", "blue", attrs=["reverse"])
cprint("Concealed Magenta color", "magenta", attrs=["concealed"])
cprint(
"Bold underline reverse cyan color",
"cyan",
attrs=["bold", "underline", "reverse"],
)
cprint(
"Dark blink concealed white color",
"white",
attrs=["dark", "blink", "concealed"],
)
print("-" * 78)
print("Test mixing:")
cprint("Underline red on grey color", "red", "on_grey", ["underline"])
cprint("Reversed green on red color", "green", "on_red", ["reverse"]) | src/termcolor/termcolor.py | import os
__ALL__ = ["colored", "cprint"]
VERSION = (1, 1, 0)
ATTRIBUTES = dict(
list(
zip(
[
"bold",
"dark",
"",
"underline",
"blink",
"",
"reverse",
"concealed",
],
list(range(1, 9)),
)
)
)
del ATTRIBUTES[""]
HIGHLIGHTS = dict(
list(
zip(
[
"on_grey",
"on_red",
"on_green",
"on_yellow",
"on_blue",
"on_magenta",
"on_cyan",
"on_white",
],
list(range(40, 48)),
)
)
)
COLORS = dict(
list(
zip(
[
"grey",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
],
list(range(30, 38)),
)
)
)
RESET = "\033[0m"
def colored(text, color=None, on_color=None, attrs=None):
"""Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv("ANSI_COLORS_DISABLED") is None:
fmt_str = "\033[%dm%s"
if color is not None:
text = fmt_str % (COLORS[color], text)
if on_color is not None:
text = fmt_str % (HIGHLIGHTS[on_color], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
def cprint(text, color=None, on_color=None, attrs=None, **kwargs):
"""Print colorize text.
It accepts arguments of print function.
"""
print((colored(text, color, on_color, attrs)), **kwargs)
if __name__ == "__main__":
print("Current terminal type: %s" % os.getenv("TERM"))
print("Test basic colors:")
cprint("Grey color", "grey")
cprint("Red color", "red")
cprint("Green color", "green")
cprint("Yellow color", "yellow")
cprint("Blue color", "blue")
cprint("Magenta color", "magenta")
cprint("Cyan color", "cyan")
cprint("White color", "white")
print("-" * 78)
print("Test highlights:")
cprint("On grey color", on_color="on_grey")
cprint("On red color", on_color="on_red")
cprint("On green color", on_color="on_green")
cprint("On yellow color", on_color="on_yellow")
cprint("On blue color", on_color="on_blue")
cprint("On magenta color", on_color="on_magenta")
cprint("On cyan color", on_color="on_cyan")
cprint("On white color", color="grey", on_color="on_white")
print("-" * 78)
print("Test attributes:")
cprint("Bold grey color", "grey", attrs=["bold"])
cprint("Dark red color", "red", attrs=["dark"])
cprint("Underline green color", "green", attrs=["underline"])
cprint("Blink yellow color", "yellow", attrs=["blink"])
cprint("Reversed blue color", "blue", attrs=["reverse"])
cprint("Concealed Magenta color", "magenta", attrs=["concealed"])
cprint(
"Bold underline reverse cyan color",
"cyan",
attrs=["bold", "underline", "reverse"],
)
cprint(
"Dark blink concealed white color",
"white",
attrs=["dark", "blink", "concealed"],
)
print("-" * 78)
print("Test mixing:")
cprint("Underline red on grey color", "red", "on_grey", ["underline"])
cprint("Reversed green on red color", "green", "on_red", ["reverse"]) | 0.459561 | 0.161287 |
{
'target_defaults': {
'defines': [
'OPJ_STATIC',
'_CRT_SECURE_NO_WARNINGS',
],
'msvs_disabled_warnings': [
4005, 4018, 4146, 4333, 4345, 4267
],
},
'targets': [
{
'target_name': 'bigint',
'type': 'static_library',
'sources': [
'bigint/BigInteger.hh',
'bigint/BigIntegerLibrary.hh',
'bigint/BigIntegerUtils.hh',
'bigint/BigUnsigned.hh',
'bigint/NumberlikeArray.hh',
'bigint/BigUnsignedInABase.hh',
'bigint/BigInteger.cc',
'bigint/BigIntegerUtils.cc',
'bigint/BigUnsigned.cc',
'bigint/BigUnsignedInABase.cc',
],
},
{
'target_name': 'fx_freetype',
'type': 'static_library',
'defines': [
'FT2_BUILD_LIBRARY',
],
'include_dirs': [
'freetype/include',
],
'sources': [
'freetype/include/freetype.h',
'freetype/include/ft2build.h',
'freetype/include/ftmm.h',
'freetype/include/ftotval.h',
'freetype/include/ftoutln.h',
'freetype/include/tttables.h',
'freetype/include/internal/ftobjs.h',
'freetype/include/internal/ftstream.h',
'freetype/include/internal/tttypes.h',
'freetype/src/cff/cffobjs.h',
'freetype/src/cff/cfftypes.h',
'freetype/src/cff/cff.c',
'freetype/src/base/ftbase.c',
'freetype/src/base/ftbase.h',
'freetype/src/base/ftbitmap.c',
'freetype/src/base/ftglyph.c',
'freetype/src/base/ftinit.c',
'freetype/src/base/ftlcdfil.c',
'freetype/src/base/ftmm.c',
'freetype/src/base/ftsystem.c',
'freetype/src/psaux/psaux.c',
'freetype/src/pshinter/pshinter.c',
'freetype/src/psnames/psmodule.c',
'freetype/src/raster/raster.c',
'freetype/src/sfnt/sfnt.c',
'freetype/src/smooth/smooth.c',
'freetype/src/truetype/truetype.c',
'freetype/src/type1/type1.c',
'freetype/src/cid/type1cid.c',
],
'variables': {
'clang_warning_flags': [
# open_face_PS_from_sfnt_stream() and open_face_from_buffer() in
# ftbase.h are unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_agg',
'type': 'static_library',
'sources': [
'agg23/agg_basics.h',
'agg23/agg_clip_liang_barsky.h',
'agg23/agg_conv_dash.h',
'agg23/agg_conv_stroke.h',
'agg23/agg_curves.cpp',
'agg23/agg_curves.h',
'agg23/agg_path_storage.cpp',
'agg23/agg_path_storage.h',
'agg23/agg_rasterizer_scanline_aa.cpp',
'agg23/agg_rasterizer_scanline_aa.h',
'agg23/agg_renderer_scanline.h',
'agg23/agg_rendering_buffer.h',
'agg23/agg_scanline_u.h',
'agg23/agg_vcgen_dash.cpp',
'agg23/agg_vcgen_stroke.cpp',
],
'conditions': [
['os_posix==1', {
# library contains several enum vs non-enum conditionals.
'cflags': [ '-Wno-extra', ],
}],
],
'variables': {
'clang_warning_flags': [
# calc_butt_cap() in agg_vcgen_stroke.cpp is unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_lcms2',
'type': 'static_library',
'sources': [
'lcms2-2.6/include/lcms2.h',
'lcms2-2.6/include/lcms2_plugin.h',
'lcms2-2.6/src/cmscam02.c',
'lcms2-2.6/src/cmscgats.c',
'lcms2-2.6/src/cmscnvrt.c',
'lcms2-2.6/src/cmserr.c',
'lcms2-2.6/src/cmsgamma.c',
'lcms2-2.6/src/cmsgmt.c',
'lcms2-2.6/src/cmshalf.c',
'lcms2-2.6/src/cmsintrp.c',
'lcms2-2.6/src/cmsio0.c',
'lcms2-2.6/src/cmsio1.c',
'lcms2-2.6/src/cmslut.c',
'lcms2-2.6/src/cmsmd5.c',
'lcms2-2.6/src/cmsmtrx.c',
'lcms2-2.6/src/cmsnamed.c',
'lcms2-2.6/src/cmsopt.c',
'lcms2-2.6/src/cmspack.c',
'lcms2-2.6/src/cmspcs.c',
'lcms2-2.6/src/cmsplugin.c',
'lcms2-2.6/src/cmsps2.c',
'lcms2-2.6/src/cmssamp.c',
'lcms2-2.6/src/cmssm.c',
'lcms2-2.6/src/cmstypes.c',
'lcms2-2.6/src/cmsvirt.c',
'lcms2-2.6/src/cmswtpnt.c',
'lcms2-2.6/src/cmsxform.c',
],
'conditions': [
['os_posix==1', {
'cflags': [
'-Wno-main',
'-Wno-missing-braces',
'-Wno-unused',
],
}],
],
'variables': {
'clang_warning_flags': [
'-Wno-missing-braces',
# FindPrev() in cmsplugin.c is unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_libjpeg',
'type': 'static_library',
'sources': [
'libjpeg/cderror.h',
'libjpeg/cdjpeg.h',
'libjpeg/fpdfapi_jcapimin.c',
'libjpeg/fpdfapi_jcapistd.c',
'libjpeg/fpdfapi_jccoefct.c',
'libjpeg/fpdfapi_jccolor.c',
'libjpeg/fpdfapi_jcdctmgr.c',
'libjpeg/fpdfapi_jchuff.c',
'libjpeg/fpdfapi_jcinit.c',
'libjpeg/fpdfapi_jcmainct.c',
'libjpeg/fpdfapi_jcmarker.c',
'libjpeg/fpdfapi_jcmaster.c',
'libjpeg/fpdfapi_jcomapi.c',
'libjpeg/fpdfapi_jcparam.c',
'libjpeg/fpdfapi_jcphuff.c',
'libjpeg/fpdfapi_jcprepct.c',
'libjpeg/fpdfapi_jcsample.c',
'libjpeg/fpdfapi_jctrans.c',
'libjpeg/fpdfapi_jdapimin.c',
'libjpeg/fpdfapi_jdapistd.c',
'libjpeg/fpdfapi_jdcoefct.c',
'libjpeg/fpdfapi_jdcolor.c',
'libjpeg/fpdfapi_jddctmgr.c',
'libjpeg/fpdfapi_jdhuff.c',
'libjpeg/fpdfapi_jdinput.c',
'libjpeg/fpdfapi_jdmainct.c',
'libjpeg/fpdfapi_jdmarker.c',
'libjpeg/fpdfapi_jdmaster.c',
'libjpeg/fpdfapi_jdmerge.c',
'libjpeg/fpdfapi_jdphuff.c',
'libjpeg/fpdfapi_jdpostct.c',
'libjpeg/fpdfapi_jdsample.c',
'libjpeg/fpdfapi_jdtrans.c',
'libjpeg/fpdfapi_jerror.c',
'libjpeg/fpdfapi_jfdctfst.c',
'libjpeg/fpdfapi_jfdctint.c',
'libjpeg/fpdfapi_jidctfst.c',
'libjpeg/fpdfapi_jidctint.c',
'libjpeg/fpdfapi_jidctred.c',
'libjpeg/fpdfapi_jmemmgr.c',
'libjpeg/fpdfapi_jmemnobs.c',
'libjpeg/fpdfapi_jutils.c',
'libjpeg/jchuff.h',
'libjpeg/jconfig.h',
'libjpeg/jdct.h',
'libjpeg/jdhuff.h',
'libjpeg/jerror.h',
'libjpeg/jinclude.h',
'libjpeg/jmemsys.h',
'libjpeg/jmorecfg.h',
'libjpeg/jpegint.h',
'libjpeg/jpeglib.h',
'libjpeg/jversion.h',
'libjpeg/transupp.h',
],
'conditions': [
['os_posix==1', {
'cflags': [
'-Wno-main',
'-Wno-missing-braces',
'-Wno-unused',
],
}],
],
},
{
'target_name': 'fx_libopenjpeg',
'type': 'static_library',
'sources': [
'libopenjpeg20/bio.c',
'libopenjpeg20/cio.c',
'libopenjpeg20/dwt.c',
'libopenjpeg20/event.c',
'libopenjpeg20/function_list.c',
'libopenjpeg20/image.c',
'libopenjpeg20/invert.c',
'libopenjpeg20/j2k.c',
'libopenjpeg20/jp2.c',
'libopenjpeg20/mct.c',
'libopenjpeg20/mqc.c',
'libopenjpeg20/openjpeg.c',
'libopenjpeg20/opj_clock.c',
'libopenjpeg20/pi.c',
'libopenjpeg20/raw.c',
'libopenjpeg20/t1.c',
'libopenjpeg20/t2.c',
'libopenjpeg20/tcd.c',
'libopenjpeg20/tgt.c',
],
},
{
'target_name': 'fx_zlib',
'type': 'static_library',
'sources': [
'zlib_v128/adler32.c',
'zlib_v128/compress.c',
'zlib_v128/crc32.c',
'zlib_v128/deflate.c',
'zlib_v128/gzclose.c',
'zlib_v128/gzlib.c',
'zlib_v128/gzread.c',
'zlib_v128/gzwrite.c',
'zlib_v128/infback.c',
'zlib_v128/inffast.c',
'zlib_v128/inflate.c',
'zlib_v128/inftrees.c',
'zlib_v128/trees.c',
'zlib_v128/uncompr.c',
'zlib_v128/zutil.c',
],
},
{
'target_name': 'pdfium_base',
'type': 'none',
'sources': [
'base/logging.h',
'base/macros.h',
'base/nonstd_unique_ptr.h',
'base/template_util.h',
'base/numerics/safe_conversions.h',
'base/numerics/safe_conversions_impl.h',
'base/numerics/safe_math.h',
'base/numerics/safe_math_impl.h',
],
},
],
} | third_party/third_party.gyp |
{
'target_defaults': {
'defines': [
'OPJ_STATIC',
'_CRT_SECURE_NO_WARNINGS',
],
'msvs_disabled_warnings': [
4005, 4018, 4146, 4333, 4345, 4267
],
},
'targets': [
{
'target_name': 'bigint',
'type': 'static_library',
'sources': [
'bigint/BigInteger.hh',
'bigint/BigIntegerLibrary.hh',
'bigint/BigIntegerUtils.hh',
'bigint/BigUnsigned.hh',
'bigint/NumberlikeArray.hh',
'bigint/BigUnsignedInABase.hh',
'bigint/BigInteger.cc',
'bigint/BigIntegerUtils.cc',
'bigint/BigUnsigned.cc',
'bigint/BigUnsignedInABase.cc',
],
},
{
'target_name': 'fx_freetype',
'type': 'static_library',
'defines': [
'FT2_BUILD_LIBRARY',
],
'include_dirs': [
'freetype/include',
],
'sources': [
'freetype/include/freetype.h',
'freetype/include/ft2build.h',
'freetype/include/ftmm.h',
'freetype/include/ftotval.h',
'freetype/include/ftoutln.h',
'freetype/include/tttables.h',
'freetype/include/internal/ftobjs.h',
'freetype/include/internal/ftstream.h',
'freetype/include/internal/tttypes.h',
'freetype/src/cff/cffobjs.h',
'freetype/src/cff/cfftypes.h',
'freetype/src/cff/cff.c',
'freetype/src/base/ftbase.c',
'freetype/src/base/ftbase.h',
'freetype/src/base/ftbitmap.c',
'freetype/src/base/ftglyph.c',
'freetype/src/base/ftinit.c',
'freetype/src/base/ftlcdfil.c',
'freetype/src/base/ftmm.c',
'freetype/src/base/ftsystem.c',
'freetype/src/psaux/psaux.c',
'freetype/src/pshinter/pshinter.c',
'freetype/src/psnames/psmodule.c',
'freetype/src/raster/raster.c',
'freetype/src/sfnt/sfnt.c',
'freetype/src/smooth/smooth.c',
'freetype/src/truetype/truetype.c',
'freetype/src/type1/type1.c',
'freetype/src/cid/type1cid.c',
],
'variables': {
'clang_warning_flags': [
# open_face_PS_from_sfnt_stream() and open_face_from_buffer() in
# ftbase.h are unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_agg',
'type': 'static_library',
'sources': [
'agg23/agg_basics.h',
'agg23/agg_clip_liang_barsky.h',
'agg23/agg_conv_dash.h',
'agg23/agg_conv_stroke.h',
'agg23/agg_curves.cpp',
'agg23/agg_curves.h',
'agg23/agg_path_storage.cpp',
'agg23/agg_path_storage.h',
'agg23/agg_rasterizer_scanline_aa.cpp',
'agg23/agg_rasterizer_scanline_aa.h',
'agg23/agg_renderer_scanline.h',
'agg23/agg_rendering_buffer.h',
'agg23/agg_scanline_u.h',
'agg23/agg_vcgen_dash.cpp',
'agg23/agg_vcgen_stroke.cpp',
],
'conditions': [
['os_posix==1', {
# library contains several enum vs non-enum conditionals.
'cflags': [ '-Wno-extra', ],
}],
],
'variables': {
'clang_warning_flags': [
# calc_butt_cap() in agg_vcgen_stroke.cpp is unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_lcms2',
'type': 'static_library',
'sources': [
'lcms2-2.6/include/lcms2.h',
'lcms2-2.6/include/lcms2_plugin.h',
'lcms2-2.6/src/cmscam02.c',
'lcms2-2.6/src/cmscgats.c',
'lcms2-2.6/src/cmscnvrt.c',
'lcms2-2.6/src/cmserr.c',
'lcms2-2.6/src/cmsgamma.c',
'lcms2-2.6/src/cmsgmt.c',
'lcms2-2.6/src/cmshalf.c',
'lcms2-2.6/src/cmsintrp.c',
'lcms2-2.6/src/cmsio0.c',
'lcms2-2.6/src/cmsio1.c',
'lcms2-2.6/src/cmslut.c',
'lcms2-2.6/src/cmsmd5.c',
'lcms2-2.6/src/cmsmtrx.c',
'lcms2-2.6/src/cmsnamed.c',
'lcms2-2.6/src/cmsopt.c',
'lcms2-2.6/src/cmspack.c',
'lcms2-2.6/src/cmspcs.c',
'lcms2-2.6/src/cmsplugin.c',
'lcms2-2.6/src/cmsps2.c',
'lcms2-2.6/src/cmssamp.c',
'lcms2-2.6/src/cmssm.c',
'lcms2-2.6/src/cmstypes.c',
'lcms2-2.6/src/cmsvirt.c',
'lcms2-2.6/src/cmswtpnt.c',
'lcms2-2.6/src/cmsxform.c',
],
'conditions': [
['os_posix==1', {
'cflags': [
'-Wno-main',
'-Wno-missing-braces',
'-Wno-unused',
],
}],
],
'variables': {
'clang_warning_flags': [
'-Wno-missing-braces',
# FindPrev() in cmsplugin.c is unused.
'-Wno-unused-function',
],
},
},
{
'target_name': 'fx_libjpeg',
'type': 'static_library',
'sources': [
'libjpeg/cderror.h',
'libjpeg/cdjpeg.h',
'libjpeg/fpdfapi_jcapimin.c',
'libjpeg/fpdfapi_jcapistd.c',
'libjpeg/fpdfapi_jccoefct.c',
'libjpeg/fpdfapi_jccolor.c',
'libjpeg/fpdfapi_jcdctmgr.c',
'libjpeg/fpdfapi_jchuff.c',
'libjpeg/fpdfapi_jcinit.c',
'libjpeg/fpdfapi_jcmainct.c',
'libjpeg/fpdfapi_jcmarker.c',
'libjpeg/fpdfapi_jcmaster.c',
'libjpeg/fpdfapi_jcomapi.c',
'libjpeg/fpdfapi_jcparam.c',
'libjpeg/fpdfapi_jcphuff.c',
'libjpeg/fpdfapi_jcprepct.c',
'libjpeg/fpdfapi_jcsample.c',
'libjpeg/fpdfapi_jctrans.c',
'libjpeg/fpdfapi_jdapimin.c',
'libjpeg/fpdfapi_jdapistd.c',
'libjpeg/fpdfapi_jdcoefct.c',
'libjpeg/fpdfapi_jdcolor.c',
'libjpeg/fpdfapi_jddctmgr.c',
'libjpeg/fpdfapi_jdhuff.c',
'libjpeg/fpdfapi_jdinput.c',
'libjpeg/fpdfapi_jdmainct.c',
'libjpeg/fpdfapi_jdmarker.c',
'libjpeg/fpdfapi_jdmaster.c',
'libjpeg/fpdfapi_jdmerge.c',
'libjpeg/fpdfapi_jdphuff.c',
'libjpeg/fpdfapi_jdpostct.c',
'libjpeg/fpdfapi_jdsample.c',
'libjpeg/fpdfapi_jdtrans.c',
'libjpeg/fpdfapi_jerror.c',
'libjpeg/fpdfapi_jfdctfst.c',
'libjpeg/fpdfapi_jfdctint.c',
'libjpeg/fpdfapi_jidctfst.c',
'libjpeg/fpdfapi_jidctint.c',
'libjpeg/fpdfapi_jidctred.c',
'libjpeg/fpdfapi_jmemmgr.c',
'libjpeg/fpdfapi_jmemnobs.c',
'libjpeg/fpdfapi_jutils.c',
'libjpeg/jchuff.h',
'libjpeg/jconfig.h',
'libjpeg/jdct.h',
'libjpeg/jdhuff.h',
'libjpeg/jerror.h',
'libjpeg/jinclude.h',
'libjpeg/jmemsys.h',
'libjpeg/jmorecfg.h',
'libjpeg/jpegint.h',
'libjpeg/jpeglib.h',
'libjpeg/jversion.h',
'libjpeg/transupp.h',
],
'conditions': [
['os_posix==1', {
'cflags': [
'-Wno-main',
'-Wno-missing-braces',
'-Wno-unused',
],
}],
],
},
{
'target_name': 'fx_libopenjpeg',
'type': 'static_library',
'sources': [
'libopenjpeg20/bio.c',
'libopenjpeg20/cio.c',
'libopenjpeg20/dwt.c',
'libopenjpeg20/event.c',
'libopenjpeg20/function_list.c',
'libopenjpeg20/image.c',
'libopenjpeg20/invert.c',
'libopenjpeg20/j2k.c',
'libopenjpeg20/jp2.c',
'libopenjpeg20/mct.c',
'libopenjpeg20/mqc.c',
'libopenjpeg20/openjpeg.c',
'libopenjpeg20/opj_clock.c',
'libopenjpeg20/pi.c',
'libopenjpeg20/raw.c',
'libopenjpeg20/t1.c',
'libopenjpeg20/t2.c',
'libopenjpeg20/tcd.c',
'libopenjpeg20/tgt.c',
],
},
{
'target_name': 'fx_zlib',
'type': 'static_library',
'sources': [
'zlib_v128/adler32.c',
'zlib_v128/compress.c',
'zlib_v128/crc32.c',
'zlib_v128/deflate.c',
'zlib_v128/gzclose.c',
'zlib_v128/gzlib.c',
'zlib_v128/gzread.c',
'zlib_v128/gzwrite.c',
'zlib_v128/infback.c',
'zlib_v128/inffast.c',
'zlib_v128/inflate.c',
'zlib_v128/inftrees.c',
'zlib_v128/trees.c',
'zlib_v128/uncompr.c',
'zlib_v128/zutil.c',
],
},
{
'target_name': 'pdfium_base',
'type': 'none',
'sources': [
'base/logging.h',
'base/macros.h',
'base/nonstd_unique_ptr.h',
'base/template_util.h',
'base/numerics/safe_conversions.h',
'base/numerics/safe_conversions_impl.h',
'base/numerics/safe_math.h',
'base/numerics/safe_math_impl.h',
],
},
],
} | 0.314366 | 0.098555 |
import _plotly_utils.basevalidators
class IndicatorValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="indicator", parent_name="", **kwargs):
super(IndicatorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Indicator"),
data_docs=kwargs.pop(
"data_docs",
"""
align
Sets the horizontal alignment of the `text`
within the box. Note that this attribute has no
effect if an angular gauge is displayed: in
this case, it is always centered
customdata
Assigns extra data each datum. This may be
useful when listening to hover, click and
selection events. Note that, "scatter" traces
also appends customdata items in the markers
DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud
for customdata .
delta
:class:`new_plotly.graph_objects.indicator.Delta`
instance or dict with compatible properties
domain
:class:`new_plotly.graph_objects.indicator.Domain`
instance or dict with compatible properties
gauge
The gauge of the Indicator plot.
ids
Assigns id labels to each datum. These ids for
object constancy of data points during
animation. Should be an array of strings, not
numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud
for ids .
meta
Assigns extra meta information associated with
this trace that can be used in various text
attributes. Attributes such as trace `name`,
graph, axis and colorbar `title.text`,
annotation `text` `rangeselector`,
`updatemenues` and `sliders` `label` text all
support `meta`. To access the trace `meta`
values in an attribute in the same trace,
simply use `%{meta[i]}` where `i` is the index
or key of the `meta` item in question. To
access trace `meta` in layout attributes, use
`%{data[n[.meta[i]}` where `i` is the index or
key of the `meta` and `n` is the trace index.
metasrc
Sets the source reference on Chart Studio Cloud
for meta .
mode
Determines how the value is displayed on the
graph. `number` displays the value numerically
in text. `delta` displays the difference to a
reference value in text. Finally, `gauge`
displays the value graphically on an axis.
name
Sets the trace name. The trace name appear as
the legend item and on hover.
number
:class:`new_plotly.graph_objects.indicator.Number`
instance or dict with compatible properties
stream
:class:`new_plotly.graph_objects.indicator.Stream`
instance or dict with compatible properties
title
:class:`new_plotly.graph_objects.indicator.Title`
instance or dict with compatible properties
uid
Assign an id to this trace, Use this to provide
object constancy between traces during
animations and transitions.
uirevision
Controls persistence of some user-driven
changes to the trace: `constraintrange` in
`parcoords` traces, as well as some `editable:
true` modifications such as `name` and
`colorbar.title`. Defaults to
`layout.uirevision`. Note that other user-
driven trace attribute changes are controlled
by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and
`colorbar.(x|y)` (accessible with `config:
{editable: true}`) is controlled by
`layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on
trace index if no `uid` is provided. So if your
app can add/remove traces before the end of the
`data` array, such that the same trace has a
different index, you can still preserve user-
driven changes if you give each trace a `uid`
that stays with it as it moves.
value
Sets the number to be displayed.
visible
Determines whether or not this trace is
visible. If "legendonly", the trace is not
drawn, but can appear as a legend item
(provided that the legend itself is visible).
""",
),
**kwargs
) | validators/_indicator.py | import _plotly_utils.basevalidators
class IndicatorValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="indicator", parent_name="", **kwargs):
super(IndicatorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Indicator"),
data_docs=kwargs.pop(
"data_docs",
"""
align
Sets the horizontal alignment of the `text`
within the box. Note that this attribute has no
effect if an angular gauge is displayed: in
this case, it is always centered
customdata
Assigns extra data each datum. This may be
useful when listening to hover, click and
selection events. Note that, "scatter" traces
also appends customdata items in the markers
DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud
for customdata .
delta
:class:`new_plotly.graph_objects.indicator.Delta`
instance or dict with compatible properties
domain
:class:`new_plotly.graph_objects.indicator.Domain`
instance or dict with compatible properties
gauge
The gauge of the Indicator plot.
ids
Assigns id labels to each datum. These ids for
object constancy of data points during
animation. Should be an array of strings, not
numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud
for ids .
meta
Assigns extra meta information associated with
this trace that can be used in various text
attributes. Attributes such as trace `name`,
graph, axis and colorbar `title.text`,
annotation `text` `rangeselector`,
`updatemenues` and `sliders` `label` text all
support `meta`. To access the trace `meta`
values in an attribute in the same trace,
simply use `%{meta[i]}` where `i` is the index
or key of the `meta` item in question. To
access trace `meta` in layout attributes, use
`%{data[n[.meta[i]}` where `i` is the index or
key of the `meta` and `n` is the trace index.
metasrc
Sets the source reference on Chart Studio Cloud
for meta .
mode
Determines how the value is displayed on the
graph. `number` displays the value numerically
in text. `delta` displays the difference to a
reference value in text. Finally, `gauge`
displays the value graphically on an axis.
name
Sets the trace name. The trace name appear as
the legend item and on hover.
number
:class:`new_plotly.graph_objects.indicator.Number`
instance or dict with compatible properties
stream
:class:`new_plotly.graph_objects.indicator.Stream`
instance or dict with compatible properties
title
:class:`new_plotly.graph_objects.indicator.Title`
instance or dict with compatible properties
uid
Assign an id to this trace, Use this to provide
object constancy between traces during
animations and transitions.
uirevision
Controls persistence of some user-driven
changes to the trace: `constraintrange` in
`parcoords` traces, as well as some `editable:
true` modifications such as `name` and
`colorbar.title`. Defaults to
`layout.uirevision`. Note that other user-
driven trace attribute changes are controlled
by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and
`colorbar.(x|y)` (accessible with `config:
{editable: true}`) is controlled by
`layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on
trace index if no `uid` is provided. So if your
app can add/remove traces before the end of the
`data` array, such that the same trace has a
different index, you can still preserve user-
driven changes if you give each trace a `uid`
that stays with it as it moves.
value
Sets the number to be displayed.
visible
Determines whether or not this trace is
visible. If "legendonly", the trace is not
drawn, but can appear as a legend item
(provided that the legend itself is visible).
""",
),
**kwargs
) | 0.868213 | 0.352313 |
import math
import numpy as np
from utils.env_objects import Cylinder, Cube
import os
class EnvDefs:
epuck = ('EPUCK', os.path.abspath('webots_objects/E-puck.wbo'))
cylinders = [
# node DEF, node file definition, radius
('Cylinder1', os.path.abspath('webots_objects/Cylinder1.wbo'), 0.05),
('Cylinder2', os.path.abspath('webots_objects/Cylinder2.wbo'), 0.05)
]
boxes = [
# node DEF, node file definition, side length
('Box1', os.path.abspath('webots_objects/Box1.wbo'), 0.1),
('Box2', os.path.abspath('webots_objects/Box2.wbo'), 0.1)
]
wall = ('Wall', os.path.abspath('webots_objects/Wall.wbo'))
class SimpleArena:
def __init__(self, supervisor):
self.supervisor = supervisor
# initialization helper variables
self.robot_initial_position = []
self.children_field = self.supervisor.getRoot().getField('children') # Get list of all the objects of the scene
self.robot = None
self.environment_objects = []
def reset(self):
self._remove_objects()
# Respawn robot in starting position and state
epuck_def, epuck_file = EnvDefs.epuck
self.children_field.importMFNode(-2, epuck_file) # Load robot from file and add to second-to-last position
self.robot = self.supervisor.getFromDef(epuck_def)
self._insert_robot_in_random_position()
self.environment_objects = self._populate_environment_objects()
def _remove_objects(self):
if self.robot is not None:
self.robot.remove()
for environment_object in self.environment_objects:
if environment_object.webot_object:
environment_object.webot_object.remove()
def get_robot(self):
return self.robot
def _populate_environment_objects(self):
environment_objects = []
for node_def, node_file, radius in EnvDefs.cylinders:
wrapped_object = Cylinder(node_def, node_file, radius=radius)
self._place_object_in_random_position(environment_objects, wrapped_object)
environment_objects.append(wrapped_object)
for node_def, node_file, side_length in EnvDefs.boxes:
wrapped_object = Cube(node_def, node_file, side_length=side_length)
self._place_object_in_random_position(environment_objects, wrapped_object)
environment_objects.append(wrapped_object)
return environment_objects
def _place_object_in_random_position(self, placed_objects, wrapped_object):
"""
Sets the shape passed by parameter to a random valid position
within the parent's node environment.
:param wrapped_object: the wrapped object with utility functions that is to be placed
:param placed_objects: the objects that have already been placed
:return: the node corresponding to the shape
"""
self.children_field.importMFNode(-1, wrapped_object.node_file)
shape = self.supervisor.getFromDef(wrapped_object.node_def)
wrapped_object.webot_object = shape
x, z = self._generate_random_valid_position(placed_objects, wrapped_object)
trans_field = shape.getField('translation')
initial_position = [x, 0.05, z]
wrapped_object.initial_position = initial_position
trans_field.setSFVec3f(initial_position)
shape.resetPhysics()
return wrapped_object
def _generate_random_valid_position(self, placed_objects, wrapped_object):
valid_position_found = False
min_distance_from_wall = wrapped_object.get_min_distance_from_wall()
position_x = None
position_z = None
while not valid_position_found:
position_x, position_z = self._get_random_coords_in_arena(min_distance_from_wall)
if self._intersects_with_robot(position_x, position_z):
continue
valid_position_found = True
for placed_object in placed_objects:
if placed_object.is_inside_object(position_x, position_z, wrapped_object.get_min_distance_from_wall()):
valid_position_found = False
continue
return position_x, position_z
@staticmethod
def _get_random_coords_in_arena(min_distance_from_wall):
floor_x = 1 / 2
floor_z = 1 / 2
position_x = np.random.uniform(-floor_x + min_distance_from_wall, floor_x - min_distance_from_wall)
position_z = np.random.uniform(-floor_z + min_distance_from_wall, floor_z - min_distance_from_wall)
return position_x, position_z
def _intersects_with_robot(self, position_x, position_z):
position_vec = self.robot_initial_position
return np.sqrt(((position_vec[0] - position_x) ** 2) + ((position_vec[2] - position_z) ** 2)) < 0.1
def _insert_robot_in_random_position(self):
trans_field = self.robot.getField('translation')
x, z = self._get_random_coords_in_arena(0.045)
self.robot_initial_position = [x, 0.01, z]
trans_field.setSFVec3f(self.robot_initial_position)
class Maze:
def __init__(self, supervisor):
self.supervisor = supervisor
# initialization helper variables
self.children_field = self.supervisor.getRoot().getField('children') # Get list of all the objects of the scene
self.robot = None
self.arena_size = np.array(self.supervisor.getFromDef('arena').getField('floorSize').getSFVec2f())
self.tile_size = np.array([0.25, 0.25])
self.walls = self._create_walls()
def reset(self):
self._respawn_robot()
self._create_maze()
def _respawn_robot(self):
if self.robot is not None:
self.robot.remove()
epuck_def, epuck_file = EnvDefs.epuck
self.children_field.importMFNode(-2, epuck_file) # Load robot from file and add to second-to-last position
self.robot = self.supervisor.getFromDef(epuck_def)
self._insert_robot_in_initial_position()
def _create_walls(self):
wall_def, wall_file = EnvDefs.wall
walls = []
for i in range(int((self.arena_size[0] / 0.25 + 1) * (self.arena_size[1] / 0.25 + 1))):
self.children_field.importMFNode(0, wall_file)
wb_object = self.supervisor.getFromDef(wall_def)
self._set_object_position(wb_object, 10 + i*0.1, 0)
walls.append(wb_object)
return walls
def _create_maze(self):
shape = np.ceil(self.arena_size / self.tile_size).astype(int)
h_walls = np.ones(shape - np.array([1, 0]), dtype=bool)
v_walls = np.ones(shape - np.array([0, 1]), dtype=bool)
visited = np.zeros(shape, dtype=bool)
directions = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])
start = np.array([0, 0])
visited[tuple(start)] = True
stack = [start]
while len(stack) > 0:
cur = stack.pop()
neighbors = directions + cur
ns_x = neighbors[:, 0]
ns_y = neighbors[:, 1]
valid_ns = neighbors[(ns_x >= 0) & (ns_x < shape[0]) & (ns_y >= 0) & (ns_y < shape[1])]
unvisited_ns = valid_ns[~visited[valid_ns[:, 0], valid_ns[:, 1]]]
if len(unvisited_ns) > 0:
stack.append(cur)
idx = np.random.choice(unvisited_ns.shape[0])
neighbor = unvisited_ns[idx, :]
direction = neighbor - cur
wall = np.minimum(cur, neighbor)
if direction[0] == 0:
v_walls[tuple(wall)] = False
else:
h_walls[tuple(wall)] = False
t_neigh = tuple(neighbor)
visited[t_neigh] = True
stack.append(t_neigh)
zs, xs = np.nonzero(h_walls)
wall_id = 0
for i in range(len(xs)):
x = 0.125 + xs[i] * 0.25 - self.arena_size[0] / 2
z = 0.25 + zs[i] * 0.25 - self.arena_size[1] / 2
self._set_object_rotation(self.walls[wall_id], math.pi/2)
self._set_object_position(self.walls[wall_id], x, z)
wall_id += 1
zs, xs = np.nonzero(v_walls)
for i in range(len(xs)):
x = 0.25 + xs[i] * 0.25 - self.arena_size[0] / 2
z = 0.125 + zs[i] * 0.25 - self.arena_size[1] / 2
self._set_object_rotation(self.walls[wall_id], 0)
self._set_object_position(self.walls[wall_id], x, z)
wall_id += 1
def get_robot(self):
return self.robot
def _set_object_position(self, wb_object, x, z):
trans_field = wb_object.getField('translation')
position = [x, 0.05, z]
trans_field.setSFVec3f(position)
def _set_object_rotation(self, wb_object, angle):
rot_field = wb_object.getField('rotation')
rotation = [0.0, 1.0, 0.0, angle]
rot_field.setSFRotation(rotation)
def _insert_robot_in_initial_position(self):
trans_field = self.robot.getField('translation')
x, z = [-0.375, -0.375]
self.robot_initial_position = [x, 0.01, z]
trans_field.setSFVec3f(self.robot_initial_position)
def _get_random_coords_in_arena(self, min_distance_from_wall):
floor_x = self.arena_size[0] / 2
floor_z = self.arena_size[1] / 2
position_x = np.random.uniform(-floor_x + min_distance_from_wall, floor_x - min_distance_from_wall)
position_z = np.random.uniform(-floor_z + min_distance_from_wall, floor_z - min_distance_from_wall)
return position_x, position_z | epuck-nav/controllers/supervisor_controller/environment/__init__.py | import math
import numpy as np
from utils.env_objects import Cylinder, Cube
import os
class EnvDefs:
epuck = ('EPUCK', os.path.abspath('webots_objects/E-puck.wbo'))
cylinders = [
# node DEF, node file definition, radius
('Cylinder1', os.path.abspath('webots_objects/Cylinder1.wbo'), 0.05),
('Cylinder2', os.path.abspath('webots_objects/Cylinder2.wbo'), 0.05)
]
boxes = [
# node DEF, node file definition, side length
('Box1', os.path.abspath('webots_objects/Box1.wbo'), 0.1),
('Box2', os.path.abspath('webots_objects/Box2.wbo'), 0.1)
]
wall = ('Wall', os.path.abspath('webots_objects/Wall.wbo'))
class SimpleArena:
def __init__(self, supervisor):
self.supervisor = supervisor
# initialization helper variables
self.robot_initial_position = []
self.children_field = self.supervisor.getRoot().getField('children') # Get list of all the objects of the scene
self.robot = None
self.environment_objects = []
def reset(self):
self._remove_objects()
# Respawn robot in starting position and state
epuck_def, epuck_file = EnvDefs.epuck
self.children_field.importMFNode(-2, epuck_file) # Load robot from file and add to second-to-last position
self.robot = self.supervisor.getFromDef(epuck_def)
self._insert_robot_in_random_position()
self.environment_objects = self._populate_environment_objects()
def _remove_objects(self):
if self.robot is not None:
self.robot.remove()
for environment_object in self.environment_objects:
if environment_object.webot_object:
environment_object.webot_object.remove()
def get_robot(self):
return self.robot
def _populate_environment_objects(self):
environment_objects = []
for node_def, node_file, radius in EnvDefs.cylinders:
wrapped_object = Cylinder(node_def, node_file, radius=radius)
self._place_object_in_random_position(environment_objects, wrapped_object)
environment_objects.append(wrapped_object)
for node_def, node_file, side_length in EnvDefs.boxes:
wrapped_object = Cube(node_def, node_file, side_length=side_length)
self._place_object_in_random_position(environment_objects, wrapped_object)
environment_objects.append(wrapped_object)
return environment_objects
def _place_object_in_random_position(self, placed_objects, wrapped_object):
"""
Sets the shape passed by parameter to a random valid position
within the parent's node environment.
:param wrapped_object: the wrapped object with utility functions that is to be placed
:param placed_objects: the objects that have already been placed
:return: the node corresponding to the shape
"""
self.children_field.importMFNode(-1, wrapped_object.node_file)
shape = self.supervisor.getFromDef(wrapped_object.node_def)
wrapped_object.webot_object = shape
x, z = self._generate_random_valid_position(placed_objects, wrapped_object)
trans_field = shape.getField('translation')
initial_position = [x, 0.05, z]
wrapped_object.initial_position = initial_position
trans_field.setSFVec3f(initial_position)
shape.resetPhysics()
return wrapped_object
def _generate_random_valid_position(self, placed_objects, wrapped_object):
valid_position_found = False
min_distance_from_wall = wrapped_object.get_min_distance_from_wall()
position_x = None
position_z = None
while not valid_position_found:
position_x, position_z = self._get_random_coords_in_arena(min_distance_from_wall)
if self._intersects_with_robot(position_x, position_z):
continue
valid_position_found = True
for placed_object in placed_objects:
if placed_object.is_inside_object(position_x, position_z, wrapped_object.get_min_distance_from_wall()):
valid_position_found = False
continue
return position_x, position_z
@staticmethod
def _get_random_coords_in_arena(min_distance_from_wall):
floor_x = 1 / 2
floor_z = 1 / 2
position_x = np.random.uniform(-floor_x + min_distance_from_wall, floor_x - min_distance_from_wall)
position_z = np.random.uniform(-floor_z + min_distance_from_wall, floor_z - min_distance_from_wall)
return position_x, position_z
def _intersects_with_robot(self, position_x, position_z):
position_vec = self.robot_initial_position
return np.sqrt(((position_vec[0] - position_x) ** 2) + ((position_vec[2] - position_z) ** 2)) < 0.1
def _insert_robot_in_random_position(self):
trans_field = self.robot.getField('translation')
x, z = self._get_random_coords_in_arena(0.045)
self.robot_initial_position = [x, 0.01, z]
trans_field.setSFVec3f(self.robot_initial_position)
class Maze:
def __init__(self, supervisor):
self.supervisor = supervisor
# initialization helper variables
self.children_field = self.supervisor.getRoot().getField('children') # Get list of all the objects of the scene
self.robot = None
self.arena_size = np.array(self.supervisor.getFromDef('arena').getField('floorSize').getSFVec2f())
self.tile_size = np.array([0.25, 0.25])
self.walls = self._create_walls()
def reset(self):
self._respawn_robot()
self._create_maze()
def _respawn_robot(self):
if self.robot is not None:
self.robot.remove()
epuck_def, epuck_file = EnvDefs.epuck
self.children_field.importMFNode(-2, epuck_file) # Load robot from file and add to second-to-last position
self.robot = self.supervisor.getFromDef(epuck_def)
self._insert_robot_in_initial_position()
def _create_walls(self):
wall_def, wall_file = EnvDefs.wall
walls = []
for i in range(int((self.arena_size[0] / 0.25 + 1) * (self.arena_size[1] / 0.25 + 1))):
self.children_field.importMFNode(0, wall_file)
wb_object = self.supervisor.getFromDef(wall_def)
self._set_object_position(wb_object, 10 + i*0.1, 0)
walls.append(wb_object)
return walls
def _create_maze(self):
shape = np.ceil(self.arena_size / self.tile_size).astype(int)
h_walls = np.ones(shape - np.array([1, 0]), dtype=bool)
v_walls = np.ones(shape - np.array([0, 1]), dtype=bool)
visited = np.zeros(shape, dtype=bool)
directions = np.array([[0, 1], [0, -1], [1, 0], [-1, 0]])
start = np.array([0, 0])
visited[tuple(start)] = True
stack = [start]
while len(stack) > 0:
cur = stack.pop()
neighbors = directions + cur
ns_x = neighbors[:, 0]
ns_y = neighbors[:, 1]
valid_ns = neighbors[(ns_x >= 0) & (ns_x < shape[0]) & (ns_y >= 0) & (ns_y < shape[1])]
unvisited_ns = valid_ns[~visited[valid_ns[:, 0], valid_ns[:, 1]]]
if len(unvisited_ns) > 0:
stack.append(cur)
idx = np.random.choice(unvisited_ns.shape[0])
neighbor = unvisited_ns[idx, :]
direction = neighbor - cur
wall = np.minimum(cur, neighbor)
if direction[0] == 0:
v_walls[tuple(wall)] = False
else:
h_walls[tuple(wall)] = False
t_neigh = tuple(neighbor)
visited[t_neigh] = True
stack.append(t_neigh)
zs, xs = np.nonzero(h_walls)
wall_id = 0
for i in range(len(xs)):
x = 0.125 + xs[i] * 0.25 - self.arena_size[0] / 2
z = 0.25 + zs[i] * 0.25 - self.arena_size[1] / 2
self._set_object_rotation(self.walls[wall_id], math.pi/2)
self._set_object_position(self.walls[wall_id], x, z)
wall_id += 1
zs, xs = np.nonzero(v_walls)
for i in range(len(xs)):
x = 0.25 + xs[i] * 0.25 - self.arena_size[0] / 2
z = 0.125 + zs[i] * 0.25 - self.arena_size[1] / 2
self._set_object_rotation(self.walls[wall_id], 0)
self._set_object_position(self.walls[wall_id], x, z)
wall_id += 1
def get_robot(self):
return self.robot
def _set_object_position(self, wb_object, x, z):
trans_field = wb_object.getField('translation')
position = [x, 0.05, z]
trans_field.setSFVec3f(position)
def _set_object_rotation(self, wb_object, angle):
rot_field = wb_object.getField('rotation')
rotation = [0.0, 1.0, 0.0, angle]
rot_field.setSFRotation(rotation)
def _insert_robot_in_initial_position(self):
trans_field = self.robot.getField('translation')
x, z = [-0.375, -0.375]
self.robot_initial_position = [x, 0.01, z]
trans_field.setSFVec3f(self.robot_initial_position)
def _get_random_coords_in_arena(self, min_distance_from_wall):
floor_x = self.arena_size[0] / 2
floor_z = self.arena_size[1] / 2
position_x = np.random.uniform(-floor_x + min_distance_from_wall, floor_x - min_distance_from_wall)
position_z = np.random.uniform(-floor_z + min_distance_from_wall, floor_z - min_distance_from_wall)
return position_x, position_z | 0.622459 | 0.163579 |
from django.db import models
# Staff Detail
class StaffDetail(models.Model):
Employee_ID = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length=50)
GENDER_MALE = 'Male'
GENDER_FEMALE = 'Female'
GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')]
gender = models.CharField(choices=GENDER_CHOICES,
max_length=30, blank=True)
date_of_birth = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
CID = models.CharField(max_length=11, unique=True, blank=True)
Administration = 'Administration'
TeachingStaff = 'Teaching Staff'
NonTeachingStaff = 'Non Teaching Staff'
SupportingStaff = 'Supporting Staff'
Category_choices = [(Administration, 'Administration'),
(TeachingStaff, 'Teaching Staff'),
(NonTeachingStaff, 'Non Teaching Staff'),
(SupportingStaff, 'Supporting Staff'), ]
category = models.CharField(
choices=Category_choices, max_length=30, blank=True)
position_title = models.CharField(max_length=50, blank=True)
position_level = models.CharField(max_length=50, blank=True)
grade = models.CharField(max_length=5, blank=True)
appointment_date = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
joining_date_of_present_school = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
transfered_from = models.CharField(max_length=50, blank=True)
Regular = 'Regular'
Contract = 'Contract'
Employment_choices = [(Regular, 'Regular'), (Contract, 'Contract')]
Employment_type = models.CharField(
choices=Employment_choices, max_length=30, blank=True)
nationality = models.CharField(max_length=50, blank=True)
subject = models.CharField(max_length=50, blank=True)
qualification = models.TextField(blank=True)
contact_number = models.CharField(
max_length=8, blank=True)
email = models.EmailField(blank=True, unique=True)
permanent_address = models.TextField(blank=True)
profile_pic = models.ImageField(
upload_to="images/staff", default='/static/images/user.jpg', null=True, blank=True)
def __str__(self):
return '%s %s' % (self.name, self.position_title)
# Add Course
class Course(models.Model):
course = models.CharField(max_length=100)
def __str__(self):
return self.course
# Class teacher
class ClassTeacher(models.Model):
name = models.ForeignKey(StaffDetail, on_delete=models.CASCADE)
seven = '7'
eight = '8'
nine = '9'
ten = '10'
eleven = '11'
twelve = '12'
class_choices = [(seven, '7'), (eight, '8'), (nine, '9'),
(ten, '10'), (eleven, '11'), (twelve, '12')]
standard = models.CharField(choices=class_choices, max_length=30)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
A = 'A'
B = 'B'
C = 'C'
D = 'D'
E = 'E'
section_choices = [(A, 'A'), (B, 'B'), (C, 'C'), (D, 'D'), (E, 'E')]
section = models.CharField(choices=section_choices, max_length=30)
def __str__(self):
return '%s' % (self.name)
# Student details
class StudentDetail(models.Model):
student_code = models.CharField(max_length=50, primary_key=True)
name = models.CharField(max_length=50)
GENDER_MALE = 'Male'
GENDER_FEMALE = 'Female'
GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')]
gender = models.CharField(choices=GENDER_CHOICES, max_length=30)
seven = '7'
eight = '8'
nine = '9'
ten = '10'
eleven = '11'
twelve = '12'
class_choices = [(seven, '7'), (eight, '8'), (nine, '9'),
(ten, '10'), (eleven, '11'), (twelve, '12')]
standard = models.CharField(choices=class_choices, max_length=30)
A = 'A'
B = 'B'
C = 'C'
D = 'D'
E = 'E'
section_choices = [(A, 'A'), (B, 'B'), (C, 'C'), (D, 'D'), (E, 'E')]
section = models.CharField(choices=section_choices, max_length=30)
course = models.ForeignKey(Course, null=True, on_delete=models.SET_NULL)
date_of_birth = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
admission_no = models.BigIntegerField(blank=True)
date_of_admission = models.DateField(
blank=True, auto_now=False, auto_now_add=False)
email = models.EmailField(blank=True, unique=True)
CID = models.CharField(max_length=11, unique=True, blank=True)
class_teacher = models.ForeignKey(
ClassTeacher, null=True, on_delete=models.SET_NULL)
previous_school = models.CharField(max_length=50, blank=True)
mobile_number = models.CharField(max_length=8, blank=True)
permanent_address = models.TextField(blank=True)
proctor_master = models.ForeignKey(
StaffDetail, null=True, on_delete=models.SET_NULL)
Boarder = 'Boarder'
Dayscholar = 'Dayscholar'
BoarderOrDayscholar = [(Boarder, 'Boarder'), (Dayscholar, 'Dayscholar')]
BoarderOrDayscholar = models.CharField(
choices=BoarderOrDayscholar, blank=True, max_length=30)
Regular = 'Regular'
Repeater = 'Repeater'
RegularOrRepeater = [(Regular, 'Regular'), (Repeater, 'Repeater')]
RegularOrRepeater = models.CharField(
choices=RegularOrRepeater, blank=True, max_length=30)
profile_pic = models.ImageField(
upload_to="images/students", default='/static/images/user.jpg', null=True, blank=True)
father_name = models.CharField(max_length=50, blank=True)
mother_name = models.CharField(max_length=50, blank=True)
fathers_occupation = models.CharField(max_length=50, blank=True)
mothers_occupation = models.CharField(max_length=50, blank=True)
parents_mobile_number = models.CharField(max_length=8, blank=True)
def __str__(self):
return '%s %s %s' % (self.name, self.standard, self.section)
# Student Disciplinary Isuue
class DisciplinaryIssue(models.Model):
Student = models.ForeignKey(
StudentDetail, null=True, on_delete=models.CASCADE)
Violation_detail = models.TextField()
Violation_date = models.DateField(auto_now=False, auto_now_add=False)
Warning_decision = models.TextField()
Approved_by = models.CharField(max_length=50)
def __str__(self):
return '%s' % (self.Student)
# Student Character Certificate
class CharacterCertificate(models.Model):
Student = models.ForeignKey(
StudentDetail, null=True, on_delete=models.CASCADE)
Special_Recognization = 'Special_Recognition'
Volunteerism = 'Volunteerism'
Academic = 'Academic'
Games_Sports = 'Games and Sports'
Literary = 'Literary'
Cultural = 'Cultural'
Category_choices = [
(Special_Recognization, 'Special_Recognition'),
(Volunteerism, 'Volunteerism'),
(Academic, 'Academic'),
(Games_Sports, 'Games and Sports'),
(Literary, 'Literary'),
(Cultural, 'Cultural')
]
Category = models.CharField(choices=Category_choices, max_length=30)
Description = models.TextField()
Awarded_on = models.DateField(auto_now=False, auto_now_add=False)
Awarded_by = models.CharField(max_length=100)
def __str__(self):
return '%s' % (self.Student) | school_management_system_app/models.py | from django.db import models
# Staff Detail
class StaffDetail(models.Model):
Employee_ID = models.BigIntegerField(primary_key=True)
name = models.CharField(max_length=50)
GENDER_MALE = 'Male'
GENDER_FEMALE = 'Female'
GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')]
gender = models.CharField(choices=GENDER_CHOICES,
max_length=30, blank=True)
date_of_birth = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
CID = models.CharField(max_length=11, unique=True, blank=True)
Administration = 'Administration'
TeachingStaff = 'Teaching Staff'
NonTeachingStaff = 'Non Teaching Staff'
SupportingStaff = 'Supporting Staff'
Category_choices = [(Administration, 'Administration'),
(TeachingStaff, 'Teaching Staff'),
(NonTeachingStaff, 'Non Teaching Staff'),
(SupportingStaff, 'Supporting Staff'), ]
category = models.CharField(
choices=Category_choices, max_length=30, blank=True)
position_title = models.CharField(max_length=50, blank=True)
position_level = models.CharField(max_length=50, blank=True)
grade = models.CharField(max_length=5, blank=True)
appointment_date = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
joining_date_of_present_school = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
transfered_from = models.CharField(max_length=50, blank=True)
Regular = 'Regular'
Contract = 'Contract'
Employment_choices = [(Regular, 'Regular'), (Contract, 'Contract')]
Employment_type = models.CharField(
choices=Employment_choices, max_length=30, blank=True)
nationality = models.CharField(max_length=50, blank=True)
subject = models.CharField(max_length=50, blank=True)
qualification = models.TextField(blank=True)
contact_number = models.CharField(
max_length=8, blank=True)
email = models.EmailField(blank=True, unique=True)
permanent_address = models.TextField(blank=True)
profile_pic = models.ImageField(
upload_to="images/staff", default='/static/images/user.jpg', null=True, blank=True)
def __str__(self):
return '%s %s' % (self.name, self.position_title)
# Add Course
class Course(models.Model):
course = models.CharField(max_length=100)
def __str__(self):
return self.course
# Class teacher
class ClassTeacher(models.Model):
name = models.ForeignKey(StaffDetail, on_delete=models.CASCADE)
seven = '7'
eight = '8'
nine = '9'
ten = '10'
eleven = '11'
twelve = '12'
class_choices = [(seven, '7'), (eight, '8'), (nine, '9'),
(ten, '10'), (eleven, '11'), (twelve, '12')]
standard = models.CharField(choices=class_choices, max_length=30)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
A = 'A'
B = 'B'
C = 'C'
D = 'D'
E = 'E'
section_choices = [(A, 'A'), (B, 'B'), (C, 'C'), (D, 'D'), (E, 'E')]
section = models.CharField(choices=section_choices, max_length=30)
def __str__(self):
return '%s' % (self.name)
# Student details
class StudentDetail(models.Model):
student_code = models.CharField(max_length=50, primary_key=True)
name = models.CharField(max_length=50)
GENDER_MALE = 'Male'
GENDER_FEMALE = 'Female'
GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')]
gender = models.CharField(choices=GENDER_CHOICES, max_length=30)
seven = '7'
eight = '8'
nine = '9'
ten = '10'
eleven = '11'
twelve = '12'
class_choices = [(seven, '7'), (eight, '8'), (nine, '9'),
(ten, '10'), (eleven, '11'), (twelve, '12')]
standard = models.CharField(choices=class_choices, max_length=30)
A = 'A'
B = 'B'
C = 'C'
D = 'D'
E = 'E'
section_choices = [(A, 'A'), (B, 'B'), (C, 'C'), (D, 'D'), (E, 'E')]
section = models.CharField(choices=section_choices, max_length=30)
course = models.ForeignKey(Course, null=True, on_delete=models.SET_NULL)
date_of_birth = models.DateField(
auto_now=False, auto_now_add=False, blank=True)
admission_no = models.BigIntegerField(blank=True)
date_of_admission = models.DateField(
blank=True, auto_now=False, auto_now_add=False)
email = models.EmailField(blank=True, unique=True)
CID = models.CharField(max_length=11, unique=True, blank=True)
class_teacher = models.ForeignKey(
ClassTeacher, null=True, on_delete=models.SET_NULL)
previous_school = models.CharField(max_length=50, blank=True)
mobile_number = models.CharField(max_length=8, blank=True)
permanent_address = models.TextField(blank=True)
proctor_master = models.ForeignKey(
StaffDetail, null=True, on_delete=models.SET_NULL)
Boarder = 'Boarder'
Dayscholar = 'Dayscholar'
BoarderOrDayscholar = [(Boarder, 'Boarder'), (Dayscholar, 'Dayscholar')]
BoarderOrDayscholar = models.CharField(
choices=BoarderOrDayscholar, blank=True, max_length=30)
Regular = 'Regular'
Repeater = 'Repeater'
RegularOrRepeater = [(Regular, 'Regular'), (Repeater, 'Repeater')]
RegularOrRepeater = models.CharField(
choices=RegularOrRepeater, blank=True, max_length=30)
profile_pic = models.ImageField(
upload_to="images/students", default='/static/images/user.jpg', null=True, blank=True)
father_name = models.CharField(max_length=50, blank=True)
mother_name = models.CharField(max_length=50, blank=True)
fathers_occupation = models.CharField(max_length=50, blank=True)
mothers_occupation = models.CharField(max_length=50, blank=True)
parents_mobile_number = models.CharField(max_length=8, blank=True)
def __str__(self):
return '%s %s %s' % (self.name, self.standard, self.section)
# Student Disciplinary Isuue
class DisciplinaryIssue(models.Model):
Student = models.ForeignKey(
StudentDetail, null=True, on_delete=models.CASCADE)
Violation_detail = models.TextField()
Violation_date = models.DateField(auto_now=False, auto_now_add=False)
Warning_decision = models.TextField()
Approved_by = models.CharField(max_length=50)
def __str__(self):
return '%s' % (self.Student)
# Student Character Certificate
class CharacterCertificate(models.Model):
Student = models.ForeignKey(
StudentDetail, null=True, on_delete=models.CASCADE)
Special_Recognization = 'Special_Recognition'
Volunteerism = 'Volunteerism'
Academic = 'Academic'
Games_Sports = 'Games and Sports'
Literary = 'Literary'
Cultural = 'Cultural'
Category_choices = [
(Special_Recognization, 'Special_Recognition'),
(Volunteerism, 'Volunteerism'),
(Academic, 'Academic'),
(Games_Sports, 'Games and Sports'),
(Literary, 'Literary'),
(Cultural, 'Cultural')
]
Category = models.CharField(choices=Category_choices, max_length=30)
Description = models.TextField()
Awarded_on = models.DateField(auto_now=False, auto_now_add=False)
Awarded_by = models.CharField(max_length=100)
def __str__(self):
return '%s' % (self.Student) | 0.486088 | 0.184859 |
import numpy as np
from numba import jit
import cv2
import os
@jit(cache=True, nopython=True)
def compute_errors(image_gt, image_pred):
""" Compute Errors from two floating point image.
init errors
1. mae
2. rmse
3. inverse mae
4. inverse rmse
5. log mae
6. log rmse
7. scale invariant log
8. abs relative
9. squared relative
"""
errors = np.zeros(9)
num_pixels = 0.0
# log sum for scale invariant metric
logSum = 0.0
w, h = image_gt.shape
for i in range(w):
for j in range(h):
if image_gt[i, j] > 0.01:
depth_pred = image_pred[i, j]
depth_gt = image_gt[i, j]
d_err = abs(depth_pred - depth_gt)
d_err_squared = d_err ** 2
d_err_inv = abs(1.0 / depth_gt - 1.0 / depth_pred)
d_err_inv_squared = d_err_inv ** 2
d_err_log = abs(np.log(depth_pred) - np.log(depth_gt))
d_err_log_squared = d_err_log ** 2
# MAE
errors[0] += d_err
# rmse
errors[1] += d_err_squared
# inv_mae
errors[2] += d_err_inv
# inv_rmse
errors[3] += d_err_inv_squared
# log
errors[4] += d_err_log
errors[5] += d_err_log_squared
# log diff for scale invariancet metric
logSum += np.log(depth_gt) - np.log(depth_pred)
# abs relative
errors[7] += d_err / depth_gt
# squared relative
errors[8] += d_err_squared / (depth_gt ** 2 )
num_pixels += 1
# normalize mae
errors[0] = errors[0] / num_pixels
# normalize and take sqrt for rmse
errors[1] = errors[1] / num_pixels
errors[1] = np.sqrt(errors[1])
# normalize inverse absoulte error
errors[2] = errors[2] / num_pixels
# normalize and take sqrt for inverse rmse
errors[3] = errors[3] / num_pixels
errors[3] = np.sqrt(errors[3])
# normalize log mae
errors[4] = errors[4] / num_pixels
# first normalize log rmse -> we need this result later
normalizedSquaredLog = errors[5] / num_pixels
errors[5] = np.sqrt(normalizedSquaredLog)
# calculate scale invariant metric
errors[6] = np.sqrt(normalizedSquaredLog - (logSum**2 / (num_pixels**2)))
# normalize abs relative
errors[7] = errors[7] / num_pixels
# normalize squared relative
errors[8] = errors[8] / num_pixels
return errors
def evaluate_depth(label_path,
result_path,
scale=256.0):
gt_list = os.listdir(label_path)
gt_list.sort()
gt_list = [os.path.join(label_path, gt) for gt in gt_list if gt.endswith(".png")]
result_list = os.listdir(result_path)
result_list.sort()
result_list = [os.path.join(result_path, result) for result in result_list if result.endswith(".png")]
if not len(gt_list) == len(result_list):
print("Notice: the lenght of gt_list {} is not the same as the result_list {}".format(len(gt_list), len(result_list)))
print("totally found {} images in {} and {}".format(len(gt_list), label_path, result_path))
error_vectors = []
for i in range(len(gt_list)):
image_gt = cv2.imread(gt_list[i], -1) / scale
image_pred = cv2.imread(result_list[i], -1) / scale
error_vectors.append(compute_errors(image_gt, image_pred))
error_vectors = np.array(error_vectors)
metric_names = [
"mae",
"rmse",
"inverse mae",
"inverse rmse",
"log mae",
"log rmse",
"scale invariant log",
"abs relative",
"squared relative"
]
result_texts = []
for i in range(len(error_vectors[0])):
text = "mean {} : {}\n".format(metric_names[i], np.mean(error_vectors[:, i]))
result_texts.append(text)
return result_texts
if __name__ == "__main__":
from fire import Fire
def main(label_path,
result_path):
texts = evaluate(label_path, result_path)
for text in texts:
print(text, end="")
Fire(main) | visualDet3D/evaluator/kitti_depth_prediction/evaluate_depth.py | import numpy as np
from numba import jit
import cv2
import os
@jit(cache=True, nopython=True)
def compute_errors(image_gt, image_pred):
""" Compute Errors from two floating point image.
init errors
1. mae
2. rmse
3. inverse mae
4. inverse rmse
5. log mae
6. log rmse
7. scale invariant log
8. abs relative
9. squared relative
"""
errors = np.zeros(9)
num_pixels = 0.0
# log sum for scale invariant metric
logSum = 0.0
w, h = image_gt.shape
for i in range(w):
for j in range(h):
if image_gt[i, j] > 0.01:
depth_pred = image_pred[i, j]
depth_gt = image_gt[i, j]
d_err = abs(depth_pred - depth_gt)
d_err_squared = d_err ** 2
d_err_inv = abs(1.0 / depth_gt - 1.0 / depth_pred)
d_err_inv_squared = d_err_inv ** 2
d_err_log = abs(np.log(depth_pred) - np.log(depth_gt))
d_err_log_squared = d_err_log ** 2
# MAE
errors[0] += d_err
# rmse
errors[1] += d_err_squared
# inv_mae
errors[2] += d_err_inv
# inv_rmse
errors[3] += d_err_inv_squared
# log
errors[4] += d_err_log
errors[5] += d_err_log_squared
# log diff for scale invariancet metric
logSum += np.log(depth_gt) - np.log(depth_pred)
# abs relative
errors[7] += d_err / depth_gt
# squared relative
errors[8] += d_err_squared / (depth_gt ** 2 )
num_pixels += 1
# normalize mae
errors[0] = errors[0] / num_pixels
# normalize and take sqrt for rmse
errors[1] = errors[1] / num_pixels
errors[1] = np.sqrt(errors[1])
# normalize inverse absoulte error
errors[2] = errors[2] / num_pixels
# normalize and take sqrt for inverse rmse
errors[3] = errors[3] / num_pixels
errors[3] = np.sqrt(errors[3])
# normalize log mae
errors[4] = errors[4] / num_pixels
# first normalize log rmse -> we need this result later
normalizedSquaredLog = errors[5] / num_pixels
errors[5] = np.sqrt(normalizedSquaredLog)
# calculate scale invariant metric
errors[6] = np.sqrt(normalizedSquaredLog - (logSum**2 / (num_pixels**2)))
# normalize abs relative
errors[7] = errors[7] / num_pixels
# normalize squared relative
errors[8] = errors[8] / num_pixels
return errors
def evaluate_depth(label_path,
result_path,
scale=256.0):
gt_list = os.listdir(label_path)
gt_list.sort()
gt_list = [os.path.join(label_path, gt) for gt in gt_list if gt.endswith(".png")]
result_list = os.listdir(result_path)
result_list.sort()
result_list = [os.path.join(result_path, result) for result in result_list if result.endswith(".png")]
if not len(gt_list) == len(result_list):
print("Notice: the lenght of gt_list {} is not the same as the result_list {}".format(len(gt_list), len(result_list)))
print("totally found {} images in {} and {}".format(len(gt_list), label_path, result_path))
error_vectors = []
for i in range(len(gt_list)):
image_gt = cv2.imread(gt_list[i], -1) / scale
image_pred = cv2.imread(result_list[i], -1) / scale
error_vectors.append(compute_errors(image_gt, image_pred))
error_vectors = np.array(error_vectors)
metric_names = [
"mae",
"rmse",
"inverse mae",
"inverse rmse",
"log mae",
"log rmse",
"scale invariant log",
"abs relative",
"squared relative"
]
result_texts = []
for i in range(len(error_vectors[0])):
text = "mean {} : {}\n".format(metric_names[i], np.mean(error_vectors[:, i]))
result_texts.append(text)
return result_texts
if __name__ == "__main__":
from fire import Fire
def main(label_path,
result_path):
texts = evaluate(label_path, result_path)
for text in texts:
print(text, end="")
Fire(main) | 0.482429 | 0.430447 |
import ctypes as ct
import math
import pdb
_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv_gemm.so')
def DivUp(a, b):
return (a + b - 1) / b
def AddAtAllLocs(h, b):
batch_size, size_x, size_y, num_channels = h.shape4d
b_shape = b.shape
h.reshape((-1, num_channels))
b.reshape((1, -1))
assert b.shape[1] == num_channels
h.add_row_vec(b)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddAtAllLocs3D(h, b):
batch_size, size_x, size_y, num_channels_mult_size_t = h.shape4d
num_channels = b.shape[1]
size_t = num_channels_mult_size_t / num_channels
assert size_t * num_channels == num_channels_mult_size_t
b_shape = b.shape
h.reshape((-1, num_channels_mult_size_t))
b.reshape((1, -1))
for i in xrange(size_t):
h.slice(i*num_channels, (i+1)*num_channels).add_row_vec(b)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddUpAllLocs(h, b, scaleTargets=0):
batch_size, size_x, size_y, num_channels = h.shape4d
b_shape = b.shape
h.reshape((-1, num_channels))
b.reshape((1, -1))
assert b.shape[1] == num_channels
if scaleTargets == 0:
h.sum(axis=0, target=b)
else:
b.mult(scaleTargets)
b.add_sums(h, axis=0)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddUpAllLocs3D(h, b, scaleTargets=0):
batch_size, size_x, size_y, num_channels_mult_size_t = h.shape4d
num_channels = b.shape[1]
size_t = num_channels_mult_size_t / num_channels
assert size_t * num_channels == num_channels_mult_size_t
b_shape = b.shape
h.reshape((-1, num_channels_mult_size_t))
b.reshape((1, -1))
b.mult(scaleTargets)
for i in xrange(size_t):
b.add_sums(h.slice(i*num_channels, (i+1)*num_channels), axis=0)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def convUp(images, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convUpGemm(images.p_mat, filters.p_mat, targets.p_mat,
images.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convDown(hidSums, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convDownGemm(hidSums.p_mat, filters.p_mat, targets.p_mat,
hidSums.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convOutp(images, hidSums, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convOutpGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convCovariance(images, y1_targets, y2_targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convCovarianceGemm(
images.p_mat, y1_targets.p_mat, y2_targets.p_mat, images.p_shape4d, y2_targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convCovariance2(images, images2, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convCovariance2Gemm(
images.p_mat, images2.p_mat, targets.p_mat, images.p_shape4d, images2.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convInnerp(images, hidSums, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convInnerpGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def MaxPool(images, targets, conv_desc):
_ConvNet.MaxPoolGemm(images.p_mat, targets.p_mat, images.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(0.0),
ct.c_float(1.0))
def MaxPoolUndo(images, grad, maxes, targets, conv_desc, scaleTargets=0):
_ConvNet.MaxPoolUndoGemm(images.p_mat, grad.p_mat, maxes.p_mat, targets.p_mat,
images.p_shape4d, grad.p_shape4d, conv_desc,
ct.c_float(scaleTargets))
def MaxPoolRprop(images, R_images, maxes, targets, conv_desc, scaleTargets=0):
_ConvNet.MaxPoolRpropGemm(images.p_mat, R_images.p_mat, maxes.p_mat, targets.p_mat,
images.p_shape4d, maxes.p_shape4d, conv_desc,
ct.c_float(scaleTargets))
def AvgPool(images, targets, conv_desc):
_ConvNet.AvgPoolGemm(images.p_mat, targets.p_mat, images.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(0.0),
ct.c_float(1.0))
def AvgPoolUndo(avgGrads, targets, conv_desc, scaleTargets=0):
_ConvNet.AvgPoolUndoGemm(avgGrads.p_mat, targets.p_mat, avgGrads.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(scaleTargets))
def ResponseNormCrossMap(images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapGemm(
images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def ResponseNormCrossMapUndo(derivs, images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapUndoGemm(
derivs.p_mat, images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def ResponseNormCrossMapRprop(images, R_images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapRpropGemm(
images.p_mat, R_images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def convUp3D(images, filters, targets, conv_desc, scaleTargets=0, bias=None):
_ConvNet.convUp3DGemm(images.p_mat, filters.p_mat, targets.p_mat,
images.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
if bias is not None:
AddAtAllLocs3D(targets, bias)
def convDown3D(hidSums, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convDown3DGemm(hidSums.p_mat, filters.p_mat, targets.p_mat,
hidSums.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convOutp3D(images, hidSums, targets, conv_desc, scaleTargets=0, dbias=None):
_ConvNet.convOutp3DGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(1))
if dbias is not None:
AddUpAllLocs3D(hidSums, dbias)
def MaxPool3D(images, targets, conv_desc):
MaxPool(images, targets, conv_desc)
def MaxPool3DUndo(images, grad, maxes, targets, conv_desc, scaleTargets=0):
MaxPoolUndo(images, grad, maxes, targets, conv_desc, scaleTargets=scaleTargets)
def AvgPool3D(images, targets, conv_desc):
AvgPool(images, targets, conv_desc)
def AvgPool3DUndo(avgGrads, targets, conv_desc, scaleTargets=0):
AvgPoolUndo(avgGrads, targets, conv_desc, scaleTargets=scaleTargets) | cudamat/cudamat_conv_gemm.py | import ctypes as ct
import math
import pdb
_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv_gemm.so')
def DivUp(a, b):
return (a + b - 1) / b
def AddAtAllLocs(h, b):
batch_size, size_x, size_y, num_channels = h.shape4d
b_shape = b.shape
h.reshape((-1, num_channels))
b.reshape((1, -1))
assert b.shape[1] == num_channels
h.add_row_vec(b)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddAtAllLocs3D(h, b):
batch_size, size_x, size_y, num_channels_mult_size_t = h.shape4d
num_channels = b.shape[1]
size_t = num_channels_mult_size_t / num_channels
assert size_t * num_channels == num_channels_mult_size_t
b_shape = b.shape
h.reshape((-1, num_channels_mult_size_t))
b.reshape((1, -1))
for i in xrange(size_t):
h.slice(i*num_channels, (i+1)*num_channels).add_row_vec(b)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddUpAllLocs(h, b, scaleTargets=0):
batch_size, size_x, size_y, num_channels = h.shape4d
b_shape = b.shape
h.reshape((-1, num_channels))
b.reshape((1, -1))
assert b.shape[1] == num_channels
if scaleTargets == 0:
h.sum(axis=0, target=b)
else:
b.mult(scaleTargets)
b.add_sums(h, axis=0)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def AddUpAllLocs3D(h, b, scaleTargets=0):
batch_size, size_x, size_y, num_channels_mult_size_t = h.shape4d
num_channels = b.shape[1]
size_t = num_channels_mult_size_t / num_channels
assert size_t * num_channels == num_channels_mult_size_t
b_shape = b.shape
h.reshape((-1, num_channels_mult_size_t))
b.reshape((1, -1))
b.mult(scaleTargets)
for i in xrange(size_t):
b.add_sums(h.slice(i*num_channels, (i+1)*num_channels), axis=0)
h.reshape((batch_size, -1))
b.reshape(b_shape)
def convUp(images, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convUpGemm(images.p_mat, filters.p_mat, targets.p_mat,
images.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convDown(hidSums, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convDownGemm(hidSums.p_mat, filters.p_mat, targets.p_mat,
hidSums.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convOutp(images, hidSums, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convOutpGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convCovariance(images, y1_targets, y2_targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convCovarianceGemm(
images.p_mat, y1_targets.p_mat, y2_targets.p_mat, images.p_shape4d, y2_targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convCovariance2(images, images2, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convCovariance2Gemm(
images.p_mat, images2.p_mat, targets.p_mat, images.p_shape4d, images2.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def convInnerp(images, hidSums, targets, conv_desc, scaleTargets=0, scaleGradients=1):
_ConvNet.convInnerpGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(scaleGradients))
def MaxPool(images, targets, conv_desc):
_ConvNet.MaxPoolGemm(images.p_mat, targets.p_mat, images.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(0.0),
ct.c_float(1.0))
def MaxPoolUndo(images, grad, maxes, targets, conv_desc, scaleTargets=0):
_ConvNet.MaxPoolUndoGemm(images.p_mat, grad.p_mat, maxes.p_mat, targets.p_mat,
images.p_shape4d, grad.p_shape4d, conv_desc,
ct.c_float(scaleTargets))
def MaxPoolRprop(images, R_images, maxes, targets, conv_desc, scaleTargets=0):
_ConvNet.MaxPoolRpropGemm(images.p_mat, R_images.p_mat, maxes.p_mat, targets.p_mat,
images.p_shape4d, maxes.p_shape4d, conv_desc,
ct.c_float(scaleTargets))
def AvgPool(images, targets, conv_desc):
_ConvNet.AvgPoolGemm(images.p_mat, targets.p_mat, images.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(0.0),
ct.c_float(1.0))
def AvgPoolUndo(avgGrads, targets, conv_desc, scaleTargets=0):
_ConvNet.AvgPoolUndoGemm(avgGrads.p_mat, targets.p_mat, avgGrads.p_shape4d,
targets.p_shape4d, conv_desc, ct.c_float(scaleTargets))
def ResponseNormCrossMap(images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapGemm(
images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def ResponseNormCrossMapUndo(derivs, images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapUndoGemm(
derivs.p_mat, images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def ResponseNormCrossMapRprop(images, R_images, targets, sizeF, addScale, powScale, blocked):
_, _, _, num_filters = images.shape4d
_ConvNet.ResponseNormCrossMapRpropGemm(
images.p_mat, R_images.p_mat, targets.p_mat, ct.c_int(num_filters), ct.c_int(sizeF),
ct.c_float(addScale), ct.c_float(powScale), ct.c_int(blocked))
def convUp3D(images, filters, targets, conv_desc, scaleTargets=0, bias=None):
_ConvNet.convUp3DGemm(images.p_mat, filters.p_mat, targets.p_mat,
images.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
if bias is not None:
AddAtAllLocs3D(targets, bias)
def convDown3D(hidSums, filters, targets, conv_desc, scaleTargets=0):
_ConvNet.convDown3DGemm(hidSums.p_mat, filters.p_mat, targets.p_mat,
hidSums.p_shape4d, filters.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets))
def convOutp3D(images, hidSums, targets, conv_desc, scaleTargets=0, dbias=None):
_ConvNet.convOutp3DGemm(
images.p_mat, hidSums.p_mat, targets.p_mat,
images.p_shape4d, hidSums.p_shape4d, targets.p_shape4d,
conv_desc, ct.c_float(scaleTargets), ct.c_float(1))
if dbias is not None:
AddUpAllLocs3D(hidSums, dbias)
def MaxPool3D(images, targets, conv_desc):
MaxPool(images, targets, conv_desc)
def MaxPool3DUndo(images, grad, maxes, targets, conv_desc, scaleTargets=0):
MaxPoolUndo(images, grad, maxes, targets, conv_desc, scaleTargets=scaleTargets)
def AvgPool3D(images, targets, conv_desc):
AvgPool(images, targets, conv_desc)
def AvgPool3DUndo(avgGrads, targets, conv_desc, scaleTargets=0):
AvgPoolUndo(avgGrads, targets, conv_desc, scaleTargets=scaleTargets) | 0.51879 | 0.601535 |
from decimal import Decimal
from pathlib import Path
from typing import Callable, Dict, Tuple, List, Any
from srctools import FileSystem, VMF, Output, Entity, FGD
from srctools.bsp import BSP
from srctools.logger import get_logger
from srctools.packlist import PackList
from srctools.game import Game
LOGGER = get_logger(__name__, 'bsp_trans')
__all__ = ['Context', 'trans', 'run_transformations']
class Context:
"""Bundles information useful for each transformation.
This allows them to ignore data they don't use.
"""
def __init__(
self,
filesys: FileSystem,
vmf: VMF,
pack: PackList,
bsp: BSP,
game: Game,
*,
fgd: FGD = None,
studiomdl_loc: Path=None,
) -> None:
self.sys = filesys
self.vmf = vmf
self.bsp = bsp
self.pack = pack
self.bsp_path = Path(bsp.filename)
self.fgd = fgd or FGD.engine_dbase()
self.game = game
self.studiomdl = studiomdl_loc
self._io_remaps = {} # type: Dict[Tuple[str, str], Tuple[List[Output], bool]]
self._ent_code = {} # type: Dict[Entity, str]
def add_io_remap(self, name: str, *outputs: Output, remove: bool=True) -> None:
"""Register an output to be replaced.
This is used to convert inputs to comp_ entities into their real
forms. The output name in the output is the input that will be replaced.
If remove is set to False, the original output will be kept.
If the name is blank, this does nothing.
"""
if not name:
return
name = name.casefold()
for out in outputs:
inp_name = out.output.casefold()
out.output = ''
key = (name, inp_name)
try:
out_list, old_remove = self._io_remaps[key]
except KeyError:
self._io_remaps[key] = ([out], remove)
else:
out_list.append(out)
# Only allow removing if all remaps have requested it.
if old_remove and not remove:
self._io_remaps[key] = (out_list, False)
def add_io_remap_removal(self, name: str, inp_name: str) -> None:
"""Special case of add_io_remap, request that this output should be removed."""
key = (name.casefold(), inp_name.casefold())
if key not in self._io_remaps:
self._io_remaps[key] = ([], True)
def add_code(self, ent: Entity, code: str) -> None:
"""Register VScript code to be run on spawn for this entity.
This way multiple such options can be merged together.
"""
try:
existing = self._ent_code[ent]
except KeyError:
self._ent_code[ent] = code
else:
self._ent_code[ent] = '{}\n{}'.format(existing, code)
TransFunc = Callable[[Context], None]
TRANSFORMS = {} # type: Dict[str, TransFunc]
def trans(name: str, *, priority: int=0) -> Callable[[TransFunc], TransFunc]:
"""Add a transformation procedure to the list."""
def deco(func: TransFunc) -> TransFunc:
"""Stores the transformation."""
TRANSFORMS[name] = func
func.priority = priority
return func
return deco
# noinspection PyProtectedMember
def run_transformations(
vmf: VMF,
filesys: FileSystem,
pack: PackList,
bsp: BSP,
game: Game,
studiomdl_loc: Path=None,
) -> None:
"""Run all transformations."""
context = Context(filesys, vmf, pack, bsp, game, studiomdl_loc=studiomdl_loc)
for func_name, func in sorted(
TRANSFORMS.items(),
key=lambda tup: tup[1].priority,
):
LOGGER.info('Running "{}"...', func_name)
func(context)
if context._ent_code:
LOGGER.info('Injecting VScript code...')
for ent, code in context._ent_code.items():
init_scripts = ent['vscripts'].split()
init_scripts.append(pack.inject_vscript(code.replace('`', '"')))
ent['vscripts'] = ' '.join(init_scripts)
if context._io_remaps:
LOGGER.info('Remapping outputs...')
for ent in vmf.entities:
todo = ent.outputs[:]
# Recursively convert only up to 500 times.
# Arbitrary limit, should be sufficient.
for _ in range(500):
if not todo:
break
deferred = []
for out in todo:
try:
remaps, should_remove = context._io_remaps[
out.target.casefold(),
out.input.casefold(),
]
except KeyError:
continue
if should_remove:
ent.outputs.remove(out)
for rep_out in remaps:
new_out = Output(
out.output,
rep_out.target,
rep_out.input,
rep_out.params or out.params,
out.delay + rep_out.delay,
only_once=rep_out.only_once and out.only_once,
)
ent.outputs.append(new_out)
deferred.append(new_out)
todo = deferred
else:
LOGGER.error(
'Entity "{}" ({}) has infinite loop when expanding '
' compiler outputs to real ones! Final output list: \n{}',
ent['targetname'], ent['classname'],
'\n'.join(['* {}\n'.format(out) for out in ent.outputs])
)
def _load() -> None:
"""Import all submodules.
This loads the transformations. We do it in a function to allow discarding
the output.
"""
from srctools.bsp_transform import (
globals,
instancing,
packing,
tweaks,
)
_load() | srctools/bsp_transform/__init__.py | from decimal import Decimal
from pathlib import Path
from typing import Callable, Dict, Tuple, List, Any
from srctools import FileSystem, VMF, Output, Entity, FGD
from srctools.bsp import BSP
from srctools.logger import get_logger
from srctools.packlist import PackList
from srctools.game import Game
LOGGER = get_logger(__name__, 'bsp_trans')
__all__ = ['Context', 'trans', 'run_transformations']
class Context:
"""Bundles information useful for each transformation.
This allows them to ignore data they don't use.
"""
def __init__(
self,
filesys: FileSystem,
vmf: VMF,
pack: PackList,
bsp: BSP,
game: Game,
*,
fgd: FGD = None,
studiomdl_loc: Path=None,
) -> None:
self.sys = filesys
self.vmf = vmf
self.bsp = bsp
self.pack = pack
self.bsp_path = Path(bsp.filename)
self.fgd = fgd or FGD.engine_dbase()
self.game = game
self.studiomdl = studiomdl_loc
self._io_remaps = {} # type: Dict[Tuple[str, str], Tuple[List[Output], bool]]
self._ent_code = {} # type: Dict[Entity, str]
def add_io_remap(self, name: str, *outputs: Output, remove: bool=True) -> None:
"""Register an output to be replaced.
This is used to convert inputs to comp_ entities into their real
forms. The output name in the output is the input that will be replaced.
If remove is set to False, the original output will be kept.
If the name is blank, this does nothing.
"""
if not name:
return
name = name.casefold()
for out in outputs:
inp_name = out.output.casefold()
out.output = ''
key = (name, inp_name)
try:
out_list, old_remove = self._io_remaps[key]
except KeyError:
self._io_remaps[key] = ([out], remove)
else:
out_list.append(out)
# Only allow removing if all remaps have requested it.
if old_remove and not remove:
self._io_remaps[key] = (out_list, False)
def add_io_remap_removal(self, name: str, inp_name: str) -> None:
"""Special case of add_io_remap, request that this output should be removed."""
key = (name.casefold(), inp_name.casefold())
if key not in self._io_remaps:
self._io_remaps[key] = ([], True)
def add_code(self, ent: Entity, code: str) -> None:
"""Register VScript code to be run on spawn for this entity.
This way multiple such options can be merged together.
"""
try:
existing = self._ent_code[ent]
except KeyError:
self._ent_code[ent] = code
else:
self._ent_code[ent] = '{}\n{}'.format(existing, code)
TransFunc = Callable[[Context], None]
TRANSFORMS = {} # type: Dict[str, TransFunc]
def trans(name: str, *, priority: int=0) -> Callable[[TransFunc], TransFunc]:
"""Add a transformation procedure to the list."""
def deco(func: TransFunc) -> TransFunc:
"""Stores the transformation."""
TRANSFORMS[name] = func
func.priority = priority
return func
return deco
# noinspection PyProtectedMember
def run_transformations(
vmf: VMF,
filesys: FileSystem,
pack: PackList,
bsp: BSP,
game: Game,
studiomdl_loc: Path=None,
) -> None:
"""Run all transformations."""
context = Context(filesys, vmf, pack, bsp, game, studiomdl_loc=studiomdl_loc)
for func_name, func in sorted(
TRANSFORMS.items(),
key=lambda tup: tup[1].priority,
):
LOGGER.info('Running "{}"...', func_name)
func(context)
if context._ent_code:
LOGGER.info('Injecting VScript code...')
for ent, code in context._ent_code.items():
init_scripts = ent['vscripts'].split()
init_scripts.append(pack.inject_vscript(code.replace('`', '"')))
ent['vscripts'] = ' '.join(init_scripts)
if context._io_remaps:
LOGGER.info('Remapping outputs...')
for ent in vmf.entities:
todo = ent.outputs[:]
# Recursively convert only up to 500 times.
# Arbitrary limit, should be sufficient.
for _ in range(500):
if not todo:
break
deferred = []
for out in todo:
try:
remaps, should_remove = context._io_remaps[
out.target.casefold(),
out.input.casefold(),
]
except KeyError:
continue
if should_remove:
ent.outputs.remove(out)
for rep_out in remaps:
new_out = Output(
out.output,
rep_out.target,
rep_out.input,
rep_out.params or out.params,
out.delay + rep_out.delay,
only_once=rep_out.only_once and out.only_once,
)
ent.outputs.append(new_out)
deferred.append(new_out)
todo = deferred
else:
LOGGER.error(
'Entity "{}" ({}) has infinite loop when expanding '
' compiler outputs to real ones! Final output list: \n{}',
ent['targetname'], ent['classname'],
'\n'.join(['* {}\n'.format(out) for out in ent.outputs])
)
def _load() -> None:
"""Import all submodules.
This loads the transformations. We do it in a function to allow discarding
the output.
"""
from srctools.bsp_transform import (
globals,
instancing,
packing,
tweaks,
)
_load() | 0.771672 | 0.187877 |
Case Type : 服务端工具
Case Name : set 方式设置认证参数:HOSTTYPE DATABASE USERNAME IPADDR IPMASK
Description :
1.设置认证参数
2.设置认证参数
3.重启数据库
4.查看是否设置成功
5.注释已经设置的客户端认证策略
6.重启数据库
Expect :
1.设置失败
2.设置完成
3.重启成功
4.设置成功
5.注释成功
6.重启成功
History :
"""
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
LOG = Logger()
class Tools(unittest.TestCase):
def setUp(self):
LOG.info('-----Opengauss_Function_Tools_gs_guc_Case0026开始执行-----')
self.dbuser_node = Node('dbuser')
self.constant = Constant()
self.commonsh = CommonSH()
def test_server_tools(self):
LOG.info('---------设置认证参数合理报错---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostl all all reject";
'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('ERROR: Invalid argument as \
invalid connection type "hostl"', msg)
LOG.info('---------设置认证参数---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostssl all all \
127.0.0.1 255.255.255.255 cert";'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('Success to perform gs_guc!', msg)
LOG.info('-------重启数据库------')
check_cmd = f'source {macro.DB_ENV_PATH};' \
f'gs_om -t status --detail;' \
f'gs_om -t restart;'
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertTrue("Normal" in msg or 'Degraded' in msg)
LOG.info('---------查看是否设置成功---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
cat {macro.DB_INSTANCE_PATH}/pg_hba.conf | grep 'hostssl'| \
grep '255.255.255.255';'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('hostssl all all 127.0.0.1 255.255.255.255 cert', msg)
LOG.info('---------删除已经设置的客户端认证策略---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
sed -i 's/\hostssl all all 127.0.0.1 255.255.255.255 cert/\ /g' \
{macro.DB_INSTANCE_PATH}/pg_hba.conf;
'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
def tearDown(self):
LOG.info('---------注释已经设置的客户端认证策略---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostnossl all all 127.0.0.1\
255.255.255.255 ";'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
LOG.info('-------重启数据库------')
check_cmd = f'source {macro.DB_ENV_PATH};' \
f'gs_om -t status --detail;' \
f'gs_om -t restart;'
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
LOG.info('----Opengauss_Function_Tools_gs_guc_Case0026执行结束----') | openGaussBase/testcase/TOOLS/SERVER_TOOLS/gs_guc/Opengauss_Function_Tools_gs_guc_Case0026.py | Case Type : 服务端工具
Case Name : set 方式设置认证参数:HOSTTYPE DATABASE USERNAME IPADDR IPMASK
Description :
1.设置认证参数
2.设置认证参数
3.重启数据库
4.查看是否设置成功
5.注释已经设置的客户端认证策略
6.重启数据库
Expect :
1.设置失败
2.设置完成
3.重启成功
4.设置成功
5.注释成功
6.重启成功
History :
"""
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
LOG = Logger()
class Tools(unittest.TestCase):
def setUp(self):
LOG.info('-----Opengauss_Function_Tools_gs_guc_Case0026开始执行-----')
self.dbuser_node = Node('dbuser')
self.constant = Constant()
self.commonsh = CommonSH()
def test_server_tools(self):
LOG.info('---------设置认证参数合理报错---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostl all all reject";
'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('ERROR: Invalid argument as \
invalid connection type "hostl"', msg)
LOG.info('---------设置认证参数---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostssl all all \
127.0.0.1 255.255.255.255 cert";'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('Success to perform gs_guc!', msg)
LOG.info('-------重启数据库------')
check_cmd = f'source {macro.DB_ENV_PATH};' \
f'gs_om -t status --detail;' \
f'gs_om -t restart;'
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertTrue("Normal" in msg or 'Degraded' in msg)
LOG.info('---------查看是否设置成功---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
cat {macro.DB_INSTANCE_PATH}/pg_hba.conf | grep 'hostssl'| \
grep '255.255.255.255';'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
self.assertIn('hostssl all all 127.0.0.1 255.255.255.255 cert', msg)
LOG.info('---------删除已经设置的客户端认证策略---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
sed -i 's/\hostssl all all 127.0.0.1 255.255.255.255 cert/\ /g' \
{macro.DB_INSTANCE_PATH}/pg_hba.conf;
'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
def tearDown(self):
LOG.info('---------注释已经设置的客户端认证策略---------')
check_cmd = f'''source {macro.DB_ENV_PATH};
gs_guc set -N all -I all -h "hostnossl all all 127.0.0.1\
255.255.255.255 ";'''
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
LOG.info('-------重启数据库------')
check_cmd = f'source {macro.DB_ENV_PATH};' \
f'gs_om -t status --detail;' \
f'gs_om -t restart;'
LOG.info(check_cmd)
msg = self.dbuser_node.sh(check_cmd).result()
LOG.info(msg)
LOG.info('----Opengauss_Function_Tools_gs_guc_Case0026执行结束----') | 0.204421 | 0.358746 |
import argparse
import os
from decouple import config
from rasa.core.nlg import TemplatedNaturalLanguageGenerator, NaturalLanguageGenerator
from rasa.utils.endpoints import EndpointConfig
from sanic import Sanic, response
from rasa.constants import ENV_SANIC_BACKLOG, DEFAULT_SANIC_WORKERS
import logging
from rasa.shared.core.domain import Domain
from rasa.shared.core.trackers import DialogueStateTracker
import file_watcher
logger = logging.getLogger(__name__)
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
DEFAULT_SERVER_PORT = 5065
RASA_ENVIRONMENT = config("RASA_ENVIRONMENT", default="DEV")
class NlgServer:
def __init__(
self,
domain_path="./data",
port=DEFAULT_SERVER_PORT,
workers=1,
nlg_class=TemplatedNaturalLanguageGenerator
):
self.domain_path = domain_path
self.domain = self._get_domain()
if isinstance(nlg_class, str):
self.nlg_class = NaturalLanguageGenerator.create(EndpointConfig(type=nlg_class), self.domain)
else:
self.nlg_class = nlg_class(self.domain.responses)
self.port = port
self.workers = workers
if RASA_ENVIRONMENT == "DEV":
file_watcher.start(self)
def _get_domain(self):
logger.info("Starting to load domain")
try:
domain = Domain.load(self.domain_path)
logger.info(f"Successfully loaded domain with {len(domain.responses)} responses")
except Exception as e:
domain = Domain.empty()
logger.error(e)
return domain
def load_domain(self, debug_mode=None):
try:
self.domain = self._get_domain()
self.nlg_class.responses = self.domain.responses
except Exception as e:
logger.error(e)
debug_dict = {
"text": f"Loaded {len(self.nlg_class.responses)} responses",
"domain_path": self.domain_path
}
if debug_mode == "title":
debug_dict["responses"] = list(self.domain.responses.keys())
elif debug_mode == "full":
debug_dict["responses"] = self.domain.responses
return debug_dict
async def generate_response(self, nlg_call):
kwargs = nlg_call.get("arguments", {})
response_arg = nlg_call.get("response")
sender_id = nlg_call.get("tracker", {}).get("sender_id")
events = nlg_call.get("tracker", {}).get("events")
tracker = DialogueStateTracker.from_dict(sender_id, events, self.domain.slots)
channel_name = nlg_call.get("channel").get("name")
return await self.nlg_class.generate(response_arg, tracker, channel_name, **kwargs)
def run_server(self):
app = Sanic(__name__)
@app.route("/nlg", methods=["POST"])
async def nlg(request):
nlg_call = request.json
bot_response = await self.generate_response(nlg_call)
return response.json(bot_response)
if RASA_ENVIRONMENT == "DEV":
@app.route("/reload", methods=["GET"])
async def reload(request):
debug_response = self.load_domain(request.args.get("show_responses"))
return response.json(debug_response)
app.run(
host="0.0.0.0",
port=self.port,
workers=self.workers,
backlog=int(os.environ.get(ENV_SANIC_BACKLOG, "100")),
)
def create_argument_parser():
parser = argparse.ArgumentParser(description="starts the nlg endpoint")
parser.add_argument(
"-p",
"--port",
default=DEFAULT_SERVER_PORT,
type=int,
help="port to run the server at",
)
parser.add_argument(
"-w",
"--workers",
default=DEFAULT_SANIC_WORKERS,
type=int,
help="Number of processes to spin up",
)
parser.add_argument(
"-d",
"--domain",
type=str,
default="./data",
help="path of the domain file to load utterances from",
)
parser.add_argument(
"--nlg",
type=str,
default=TemplatedNaturalLanguageGenerator,
help="custom nlg class path",
)
return parser
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
arg_parser = create_argument_parser()
cmdline_args = arg_parser.parse_args()
NlgServer(
cmdline_args.domain,
cmdline_args.port,
cmdline_args.workers,
cmdline_args.nlg
).run_server() | server.py | import argparse
import os
from decouple import config
from rasa.core.nlg import TemplatedNaturalLanguageGenerator, NaturalLanguageGenerator
from rasa.utils.endpoints import EndpointConfig
from sanic import Sanic, response
from rasa.constants import ENV_SANIC_BACKLOG, DEFAULT_SANIC_WORKERS
import logging
from rasa.shared.core.domain import Domain
from rasa.shared.core.trackers import DialogueStateTracker
import file_watcher
logger = logging.getLogger(__name__)
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S'
)
DEFAULT_SERVER_PORT = 5065
RASA_ENVIRONMENT = config("RASA_ENVIRONMENT", default="DEV")
class NlgServer:
def __init__(
self,
domain_path="./data",
port=DEFAULT_SERVER_PORT,
workers=1,
nlg_class=TemplatedNaturalLanguageGenerator
):
self.domain_path = domain_path
self.domain = self._get_domain()
if isinstance(nlg_class, str):
self.nlg_class = NaturalLanguageGenerator.create(EndpointConfig(type=nlg_class), self.domain)
else:
self.nlg_class = nlg_class(self.domain.responses)
self.port = port
self.workers = workers
if RASA_ENVIRONMENT == "DEV":
file_watcher.start(self)
def _get_domain(self):
logger.info("Starting to load domain")
try:
domain = Domain.load(self.domain_path)
logger.info(f"Successfully loaded domain with {len(domain.responses)} responses")
except Exception as e:
domain = Domain.empty()
logger.error(e)
return domain
def load_domain(self, debug_mode=None):
try:
self.domain = self._get_domain()
self.nlg_class.responses = self.domain.responses
except Exception as e:
logger.error(e)
debug_dict = {
"text": f"Loaded {len(self.nlg_class.responses)} responses",
"domain_path": self.domain_path
}
if debug_mode == "title":
debug_dict["responses"] = list(self.domain.responses.keys())
elif debug_mode == "full":
debug_dict["responses"] = self.domain.responses
return debug_dict
async def generate_response(self, nlg_call):
kwargs = nlg_call.get("arguments", {})
response_arg = nlg_call.get("response")
sender_id = nlg_call.get("tracker", {}).get("sender_id")
events = nlg_call.get("tracker", {}).get("events")
tracker = DialogueStateTracker.from_dict(sender_id, events, self.domain.slots)
channel_name = nlg_call.get("channel").get("name")
return await self.nlg_class.generate(response_arg, tracker, channel_name, **kwargs)
def run_server(self):
app = Sanic(__name__)
@app.route("/nlg", methods=["POST"])
async def nlg(request):
nlg_call = request.json
bot_response = await self.generate_response(nlg_call)
return response.json(bot_response)
if RASA_ENVIRONMENT == "DEV":
@app.route("/reload", methods=["GET"])
async def reload(request):
debug_response = self.load_domain(request.args.get("show_responses"))
return response.json(debug_response)
app.run(
host="0.0.0.0",
port=self.port,
workers=self.workers,
backlog=int(os.environ.get(ENV_SANIC_BACKLOG, "100")),
)
def create_argument_parser():
parser = argparse.ArgumentParser(description="starts the nlg endpoint")
parser.add_argument(
"-p",
"--port",
default=DEFAULT_SERVER_PORT,
type=int,
help="port to run the server at",
)
parser.add_argument(
"-w",
"--workers",
default=DEFAULT_SANIC_WORKERS,
type=int,
help="Number of processes to spin up",
)
parser.add_argument(
"-d",
"--domain",
type=str,
default="./data",
help="path of the domain file to load utterances from",
)
parser.add_argument(
"--nlg",
type=str,
default=TemplatedNaturalLanguageGenerator,
help="custom nlg class path",
)
return parser
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
arg_parser = create_argument_parser()
cmdline_args = arg_parser.parse_args()
NlgServer(
cmdline_args.domain,
cmdline_args.port,
cmdline_args.workers,
cmdline_args.nlg
).run_server() | 0.356447 | 0.078325 |
from collections import defaultdict
from rqalpha.utils.i18n import gettext as _
from rqalpha.const import ORDER_TYPE, SIDE, BAR_STATUS
from rqalpha.model.trade import Trade
from rqalpha.environment import Environment
from rqalpha.events import EVENT
class Matcher(object):
def __init__(self,
deal_price_decider,
bar_limit=True,
volume_percent=0.25):
self._board = None
self._turnover = defaultdict(int)
self._calendar_dt = None
self._trading_dt = None
self._deal_price_decider = deal_price_decider
self._volume_percent = volume_percent
self._bar_limit = bar_limit
def update(self, calendar_dt, trading_dt, bar_dict):
self._board = bar_dict
self._turnover.clear()
self._calendar_dt = calendar_dt
self._trading_dt = trading_dt
def match(self, open_orders):
for account, order in open_orders:
slippage_decider = account.slippage_decider
commission_decider = account.commission_decider
tax_decider = account.tax_decider
bar = self._board[order.order_book_id]
bar_status = bar._bar_status
if bar_status == BAR_STATUS.ERROR:
listed_date = bar.instrument.listed_date.date()
if listed_date == self._trading_dt.date():
reason = _("Order Cancelled: current security [{order_book_id}] can not be traded in listed date [{listed_date}]").format(
order_book_id=order.order_book_id,
listed_date=listed_date,
)
else:
reason = _("Order Cancelled: current bar [{order_book_id}] miss market data.").format(
order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
deal_price = self._deal_price_decider(bar)
if order.type == ORDER_TYPE.LIMIT:
if order.price > bar.limit_up:
reason = _(
"Order Rejected: limit order price {limit_price} is higher than limit up {limit_up}."
).format(
limit_price=order.price,
limit_up=bar.limit_up
)
order._mark_rejected(reason)
continue
if order.price < bar.limit_down:
reason = _(
"Order Rejected: limit order price {limit_price} is lower than limit down {limit_down}."
).format(
limit_price=order.price,
limit_down=bar.limit_down
)
order._mark_rejected(reason)
continue
if order.side == SIDE.BUY and order.price < deal_price:
continue
if order.side == SIDE.SELL and order.price > deal_price:
continue
else:
if self._bar_limit and order.side == SIDE.BUY and bar_status == BAR_STATUS.LIMIT_UP:
reason = _(
"Order Cancelled: current bar [{order_book_id}] reach the limit_up price."
).format(order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
elif self._bar_limit and order.side == SIDE.SELL and bar_status == BAR_STATUS.LIMIT_DOWN:
reason = _(
"Order Cancelled: current bar [{order_book_id}] reach the limit_down price."
).format(order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
if self._bar_limit:
if order.side == SIDE.BUY and bar_status == BAR_STATUS.LIMIT_UP:
continue
if order.side == SIDE.SELL and bar_status == BAR_STATUS.LIMIT_DOWN:
continue
volume_limit = round(bar.volume * self._volume_percent) - self._turnover[order.order_book_id]
round_lot = bar.instrument.round_lot
volume_limit = (volume_limit // round_lot) * round_lot
if volume_limit <= 0:
if order.type == ORDER_TYPE.MARKET:
reason = _('Order Cancelled: market order {order_book_id} volume {order_volume}'
' due to volume limit').format(
order_book_id=order.order_book_id,
order_volume=order.quantity
)
order._mark_cancelled(reason)
continue
unfilled = order.unfilled_quantity
fill = min(unfilled, volume_limit)
ct_amount = account.portfolio.positions[order.order_book_id]._cal_close_today_amount(fill, order.side)
price = slippage_decider.get_trade_price(order, deal_price)
trade = Trade.__from_create__(order=order, calendar_dt=self._calendar_dt, trading_dt=self._trading_dt,
price=price, amount=fill, close_today_amount=ct_amount)
trade._commission = commission_decider.get_commission(trade)
trade._tax = tax_decider.get_tax(trade)
order._fill(trade)
self._turnover[order.order_book_id] += fill
Environment.get_instance().event_bus.publish_event(EVENT.TRADE, account, trade)
if order.type == ORDER_TYPE.MARKET and order.unfilled_quantity != 0:
reason = _(
"Order Cancelled: market order {order_book_id} volume {order_volume} is"
" larger than 25 percent of current bar volume, fill {filled_volume} actually"
).format(
order_book_id=order.order_book_id,
order_volume=order.quantity,
filled_volume=order.filled_quantity
)
order._mark_cancelled(reason) | engine/matcher.py |
from collections import defaultdict
from rqalpha.utils.i18n import gettext as _
from rqalpha.const import ORDER_TYPE, SIDE, BAR_STATUS
from rqalpha.model.trade import Trade
from rqalpha.environment import Environment
from rqalpha.events import EVENT
class Matcher(object):
def __init__(self,
deal_price_decider,
bar_limit=True,
volume_percent=0.25):
self._board = None
self._turnover = defaultdict(int)
self._calendar_dt = None
self._trading_dt = None
self._deal_price_decider = deal_price_decider
self._volume_percent = volume_percent
self._bar_limit = bar_limit
def update(self, calendar_dt, trading_dt, bar_dict):
self._board = bar_dict
self._turnover.clear()
self._calendar_dt = calendar_dt
self._trading_dt = trading_dt
def match(self, open_orders):
for account, order in open_orders:
slippage_decider = account.slippage_decider
commission_decider = account.commission_decider
tax_decider = account.tax_decider
bar = self._board[order.order_book_id]
bar_status = bar._bar_status
if bar_status == BAR_STATUS.ERROR:
listed_date = bar.instrument.listed_date.date()
if listed_date == self._trading_dt.date():
reason = _("Order Cancelled: current security [{order_book_id}] can not be traded in listed date [{listed_date}]").format(
order_book_id=order.order_book_id,
listed_date=listed_date,
)
else:
reason = _("Order Cancelled: current bar [{order_book_id}] miss market data.").format(
order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
deal_price = self._deal_price_decider(bar)
if order.type == ORDER_TYPE.LIMIT:
if order.price > bar.limit_up:
reason = _(
"Order Rejected: limit order price {limit_price} is higher than limit up {limit_up}."
).format(
limit_price=order.price,
limit_up=bar.limit_up
)
order._mark_rejected(reason)
continue
if order.price < bar.limit_down:
reason = _(
"Order Rejected: limit order price {limit_price} is lower than limit down {limit_down}."
).format(
limit_price=order.price,
limit_down=bar.limit_down
)
order._mark_rejected(reason)
continue
if order.side == SIDE.BUY and order.price < deal_price:
continue
if order.side == SIDE.SELL and order.price > deal_price:
continue
else:
if self._bar_limit and order.side == SIDE.BUY and bar_status == BAR_STATUS.LIMIT_UP:
reason = _(
"Order Cancelled: current bar [{order_book_id}] reach the limit_up price."
).format(order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
elif self._bar_limit and order.side == SIDE.SELL and bar_status == BAR_STATUS.LIMIT_DOWN:
reason = _(
"Order Cancelled: current bar [{order_book_id}] reach the limit_down price."
).format(order_book_id=order.order_book_id)
order._mark_rejected(reason)
continue
if self._bar_limit:
if order.side == SIDE.BUY and bar_status == BAR_STATUS.LIMIT_UP:
continue
if order.side == SIDE.SELL and bar_status == BAR_STATUS.LIMIT_DOWN:
continue
volume_limit = round(bar.volume * self._volume_percent) - self._turnover[order.order_book_id]
round_lot = bar.instrument.round_lot
volume_limit = (volume_limit // round_lot) * round_lot
if volume_limit <= 0:
if order.type == ORDER_TYPE.MARKET:
reason = _('Order Cancelled: market order {order_book_id} volume {order_volume}'
' due to volume limit').format(
order_book_id=order.order_book_id,
order_volume=order.quantity
)
order._mark_cancelled(reason)
continue
unfilled = order.unfilled_quantity
fill = min(unfilled, volume_limit)
ct_amount = account.portfolio.positions[order.order_book_id]._cal_close_today_amount(fill, order.side)
price = slippage_decider.get_trade_price(order, deal_price)
trade = Trade.__from_create__(order=order, calendar_dt=self._calendar_dt, trading_dt=self._trading_dt,
price=price, amount=fill, close_today_amount=ct_amount)
trade._commission = commission_decider.get_commission(trade)
trade._tax = tax_decider.get_tax(trade)
order._fill(trade)
self._turnover[order.order_book_id] += fill
Environment.get_instance().event_bus.publish_event(EVENT.TRADE, account, trade)
if order.type == ORDER_TYPE.MARKET and order.unfilled_quantity != 0:
reason = _(
"Order Cancelled: market order {order_book_id} volume {order_volume} is"
" larger than 25 percent of current bar volume, fill {filled_volume} actually"
).format(
order_book_id=order.order_book_id,
order_volume=order.quantity,
filled_volume=order.filled_quantity
)
order._mark_cancelled(reason) | 0.628521 | 0.188641 |
import sys
import json
from subprocess import Popen, PIPE
try:
import yaml
except ImportError:
print('Unable to import YAML module: please install PyYAML', file=sys.stderr)
sys.exit(1)
class Reporter(object):
"""Collect and report errors."""
def __init__(self):
"""Constructor."""
super(Reporter, self).__init__()
self.messages = []
def check_field(self, filename, name, values, key, expected):
"""Check that a dictionary has an expected value."""
if key not in values:
self.add(filename, '{0} does not contain {1}', name, key)
elif values[key] != expected:
self.add(filename, '{0} {1} is {2} not {3}', name, key, values[key], expected)
def check(self, condition, location, fmt, *args):
"""Append error if condition not met."""
if not condition:
self.add(location, fmt, *args)
def add(self, location, fmt, *args):
"""Append error unilaterally."""
if isinstance(location, type(None)):
coords = ''
elif isinstance(location, str):
coords = '{0}: '.format(location)
elif isinstance(location, tuple):
filename, line_number = location
coords = '{0}:{1}: '.format(*location)
else:
assert False, 'Unknown location "{0}"/{1}'.format(location, type(location))
self.messages.append(coords + fmt.format(*args))
def report(self, stream=sys.stdout):
"""Report all messages."""
if not self.messages:
return
for m in sorted(self.messages):
print(m, file=stream)
def read_markdown(parser, path):
"""
Get YAML and AST for Markdown file, returning
{'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
"""
# Split and extract YAML (if present).
with open(path, 'r') as reader:
body = reader.read()
metadata_raw, metadata_yaml, body = split_metadata(path, body)
# Split into lines.
metadata_len = 0 if metadata_raw is None else metadata_raw.count('\n')
lines = [(metadata_len+i+1, line, len(line)) for (i, line) in enumerate(body.split('\n'))]
# Parse Markdown.
cmd = 'ruby {0}'.format(parser)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, universal_newlines=True)
stdout_data, stderr_data = p.communicate(body)
doc = json.loads(stdout_data)
return {
'metadata': metadata_yaml,
'metadata_len': metadata_len,
'text': body,
'lines': lines,
'doc': doc
}
def split_metadata(path, text):
"""
Get raw (text) metadata, metadata as YAML, and rest of body.
If no metadata, return (None, None, body).
"""
metadata_raw = None
metadata_yaml = None
metadata_len = None
pieces = text.split('---', 2)
if len(pieces) == 3:
metadata_raw = pieces[1]
text = pieces[2]
try:
metadata_yaml = yaml.load(metadata_raw)
except yaml.YAMLError as e:
print('Unable to parse YAML header in {0}:\n{1}'.format(path, e), file=sys.stderr)
sys.exit(1)
return metadata_raw, metadata_yaml, text
def load_yaml(filename):
"""
Wrapper around YAML loading so that 'import yaml' and error
handling is only needed in one place.
"""
with open(filename, 'r') as reader:
return yaml.load(reader) | bin/util.py | import sys
import json
from subprocess import Popen, PIPE
try:
import yaml
except ImportError:
print('Unable to import YAML module: please install PyYAML', file=sys.stderr)
sys.exit(1)
class Reporter(object):
"""Collect and report errors."""
def __init__(self):
"""Constructor."""
super(Reporter, self).__init__()
self.messages = []
def check_field(self, filename, name, values, key, expected):
"""Check that a dictionary has an expected value."""
if key not in values:
self.add(filename, '{0} does not contain {1}', name, key)
elif values[key] != expected:
self.add(filename, '{0} {1} is {2} not {3}', name, key, values[key], expected)
def check(self, condition, location, fmt, *args):
"""Append error if condition not met."""
if not condition:
self.add(location, fmt, *args)
def add(self, location, fmt, *args):
"""Append error unilaterally."""
if isinstance(location, type(None)):
coords = ''
elif isinstance(location, str):
coords = '{0}: '.format(location)
elif isinstance(location, tuple):
filename, line_number = location
coords = '{0}:{1}: '.format(*location)
else:
assert False, 'Unknown location "{0}"/{1}'.format(location, type(location))
self.messages.append(coords + fmt.format(*args))
def report(self, stream=sys.stdout):
"""Report all messages."""
if not self.messages:
return
for m in sorted(self.messages):
print(m, file=stream)
def read_markdown(parser, path):
"""
Get YAML and AST for Markdown file, returning
{'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
"""
# Split and extract YAML (if present).
with open(path, 'r') as reader:
body = reader.read()
metadata_raw, metadata_yaml, body = split_metadata(path, body)
# Split into lines.
metadata_len = 0 if metadata_raw is None else metadata_raw.count('\n')
lines = [(metadata_len+i+1, line, len(line)) for (i, line) in enumerate(body.split('\n'))]
# Parse Markdown.
cmd = 'ruby {0}'.format(parser)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, universal_newlines=True)
stdout_data, stderr_data = p.communicate(body)
doc = json.loads(stdout_data)
return {
'metadata': metadata_yaml,
'metadata_len': metadata_len,
'text': body,
'lines': lines,
'doc': doc
}
def split_metadata(path, text):
"""
Get raw (text) metadata, metadata as YAML, and rest of body.
If no metadata, return (None, None, body).
"""
metadata_raw = None
metadata_yaml = None
metadata_len = None
pieces = text.split('---', 2)
if len(pieces) == 3:
metadata_raw = pieces[1]
text = pieces[2]
try:
metadata_yaml = yaml.load(metadata_raw)
except yaml.YAMLError as e:
print('Unable to parse YAML header in {0}:\n{1}'.format(path, e), file=sys.stderr)
sys.exit(1)
return metadata_raw, metadata_yaml, text
def load_yaml(filename):
"""
Wrapper around YAML loading so that 'import yaml' and error
handling is only needed in one place.
"""
with open(filename, 'r') as reader:
return yaml.load(reader) | 0.325413 | 0.279901 |
import os.path
import qprompt
from cosmic_ray.config import ConfigDict
from cosmic_ray.plugins import execution_engine_names
MODULE_PATH_HELP = """The path to the module that will be mutated.
If this is a package (as opposed to a single file module),
then all modules in the package and its subpackages will be
mutated.
This path can be absolute or relative to the location of the
config file.
"""
PYTHON_VERSION_HELP = """The version of Python to use for mutation.
If provided, this should be of the form MAJOR.MINOR. If
your mutation test runs will take place on python 3.6.4,
for example, you should specify 3.6.
If blank, then the python version to us will be detected
from the system on which the init command is run.
Generally this can be blank. You need to set it if the
Python version you're using for exec is different from
that of the workers.
"""
TEST_COMMAND_HELP = """The command to execute to run the tests on mutated code.
The string "{python-executable}" will be replaced with the
correct Python executable when tests are run. It's often
best to use this variable rather than use test program names
directly. For example, use "{python-executable} -m pytest
tests" rather than "pytest tests".
"""
def _validate_python_version(s):
"Return True if a string is of the form <int>.<int>, False otherwise."
if not s:
return True
toks = s.split('.')
if len(toks) != 2:
return False
try:
int(toks[0])
int(toks[1])
except ValueError:
return False
return True
def new_config():
"""Prompt user for config variables and generate new config.
Returns: A new ConfigDict.
"""
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_version = qprompt.ask_str(
'Python version (blank for auto detection)',
vld=_validate_python_version,
hlp=PYTHON_VERSION_HELP)
config['python-version'] = python_version
timeout = qprompt.ask_str(
'Test execution timeout (seconds)',
vld=float,
blk=False,
hlp="The number of seconds to let a test run before terminating it.")
config['timeout'] = float(timeout)
config['excluded-modules'] = []
config["test-command"] = qprompt.ask_str(
"Test command",
blk=False,
hlp=TEST_COMMAND_HELP)
menu = qprompt.Menu()
for at_pos, engine_name in enumerate(execution_engine_names()):
menu.add(str(at_pos), engine_name)
config["execution-engine"] = ConfigDict()
config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")
config["cloning"] = ConfigDict()
config['cloning']['method'] = 'copy'
config['cloning']['commands'] = []
return config | src/cosmic_ray/commands/new_config.py | import os.path
import qprompt
from cosmic_ray.config import ConfigDict
from cosmic_ray.plugins import execution_engine_names
MODULE_PATH_HELP = """The path to the module that will be mutated.
If this is a package (as opposed to a single file module),
then all modules in the package and its subpackages will be
mutated.
This path can be absolute or relative to the location of the
config file.
"""
PYTHON_VERSION_HELP = """The version of Python to use for mutation.
If provided, this should be of the form MAJOR.MINOR. If
your mutation test runs will take place on python 3.6.4,
for example, you should specify 3.6.
If blank, then the python version to us will be detected
from the system on which the init command is run.
Generally this can be blank. You need to set it if the
Python version you're using for exec is different from
that of the workers.
"""
TEST_COMMAND_HELP = """The command to execute to run the tests on mutated code.
The string "{python-executable}" will be replaced with the
correct Python executable when tests are run. It's often
best to use this variable rather than use test program names
directly. For example, use "{python-executable} -m pytest
tests" rather than "pytest tests".
"""
def _validate_python_version(s):
"Return True if a string is of the form <int>.<int>, False otherwise."
if not s:
return True
toks = s.split('.')
if len(toks) != 2:
return False
try:
int(toks[0])
int(toks[1])
except ValueError:
return False
return True
def new_config():
"""Prompt user for config variables and generate new config.
Returns: A new ConfigDict.
"""
config = ConfigDict()
config["module-path"] = qprompt.ask_str(
"Top-level module path",
blk=False,
vld=os.path.exists,
hlp=MODULE_PATH_HELP)
python_version = qprompt.ask_str(
'Python version (blank for auto detection)',
vld=_validate_python_version,
hlp=PYTHON_VERSION_HELP)
config['python-version'] = python_version
timeout = qprompt.ask_str(
'Test execution timeout (seconds)',
vld=float,
blk=False,
hlp="The number of seconds to let a test run before terminating it.")
config['timeout'] = float(timeout)
config['excluded-modules'] = []
config["test-command"] = qprompt.ask_str(
"Test command",
blk=False,
hlp=TEST_COMMAND_HELP)
menu = qprompt.Menu()
for at_pos, engine_name in enumerate(execution_engine_names()):
menu.add(str(at_pos), engine_name)
config["execution-engine"] = ConfigDict()
config['execution-engine']['name'] = menu.show(header="Execution engine", returns="desc")
config["cloning"] = ConfigDict()
config['cloning']['method'] = 'copy'
config['cloning']['commands'] = []
return config | 0.529263 | 0.318803 |
import os
import json
from functools import partial
from http.server import SimpleHTTPRequestHandler , test
from http import HTTPStatus
ENCODING = "utf-8"
UPLOAD_DIR = "upload"
CONTENT_TYPE_FORM = "multipart/form-data"
CONTENT_TYPE_RAW_JSON = "application/json"
class CustomRequestHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, directory=None, **kwargs):
if directory is None:
directory = os.getcwd()
self.directory = directory
# 上传文件夹初始化
dir_path = os.path.join(directory, UPLOAD_DIR)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
self.upload_dir = dir_path
super().__init__(*args, directory=directory, **kwargs)
def do_POST(self):
self.parse_body()
file_info = self.req_params["stream"]
f = open(os.path.join(self.upload_dir, file_info['file_name']), 'wb')
f.write(file_info['value'])
f.close()
self.send_result({"code": 200})
def send_result(self, result):
self.send_response(HTTPStatus.OK)
body = json.dumps(result).encode(ENCODING, 'replace')
self.send_header("Content-Type", CONTENT_TYPE_RAW_JSON)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def parse_body(self):
"""解析 HTTP 请求体中的参数
multipart/form-data 按照标准解析,文件请求二进制值并不解析,由用户自行处理
application/x-www-form-urlencoded application/json 按照标准解析
text/plain application/xml 按照字符串解析 不验证格式
其他格式皆返回二进制值
Parse the parameters in the HTTP request body
-Multipart / form-data is parsed according to the standard,
the binary value of the file request is not parsed, and is
handled by the user
-application / x-www-form-urlencoded application / json is
parsed according to the standard
- text / plain application / xml parsing according to the
string without verifying the format
- All other formats return binary values
"""
encoding = ENCODING
content_length = self.headers.get("Content-Length")
if content_length and content_length != 0:
body = self.rfile.read(int(content_length))
content_type = self.headers.get('Content-Type')
content_type_up = content_type.upper()
params = None
if CONTENT_TYPE_FORM.upper() in content_type_up:
"""
...
Content-Type: multipart/form-data; boundary=${boundary}
--${boundary}
...
...
--${boundary}--
"""
boundary = content_type.split("boundary=")[1]
tag = b'--'
bin_boundary = tag + boundary.encode() + b'\r\n'
bin_boundary_end = tag + boundary.encode() + tag + b'\r\n'
if not body.startswith(bin_boundary):
self.send_error(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "multipart/form-data format error")
return False
if not body.endswith(bin_boundary_end):
self.send_error(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "multipart/form-data format error")
return False
body = body[len(bin_boundary):]
body = body[:-len(bin_boundary_end)]
content_list = body.split(bin_boundary)
params = {}
key = ""
for line in content_list:
meta_key, meta_value = line.split(b'\r\n\r\n')
meta_key = meta_key.decode(encoding)
name_begin = meta_key.find("name=\"") + 6
name_end = meta_key.find("\"", name_begin)
name = meta_key[name_begin:name_end]
if not name.strip():
continue
file_name_begin = meta_key.find("filename=\"")
if file_name_begin == -1:
meta_value = meta_value.decode(encoding)
value = meta_value.rstrip('\r\n')
params[name] = value
else:
file_name_begin += 10
file_name_end = meta_key.find("\"", file_name_begin)
file_name = meta_key[file_name_begin:file_name_end]
file_type = meta_key[meta_key.find("Content-Type:") + 13:]
value = meta_value[:-len(b'\r\n')]
# record file info
params[name] = {"file_name": file_name,
"file_type": file_type,
"value": value}
self.req_params = params
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cgi', action='store_true',
help='Run as CGI Server')
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
handler_class = partial(CustomRequestHandler,
directory=args.directory)
test(HandlerClass=handler_class, port=args.port, bind=args.bind) | simpleFtp.py | import os
import json
from functools import partial
from http.server import SimpleHTTPRequestHandler , test
from http import HTTPStatus
ENCODING = "utf-8"
UPLOAD_DIR = "upload"
CONTENT_TYPE_FORM = "multipart/form-data"
CONTENT_TYPE_RAW_JSON = "application/json"
class CustomRequestHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, directory=None, **kwargs):
if directory is None:
directory = os.getcwd()
self.directory = directory
# 上传文件夹初始化
dir_path = os.path.join(directory, UPLOAD_DIR)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
self.upload_dir = dir_path
super().__init__(*args, directory=directory, **kwargs)
def do_POST(self):
self.parse_body()
file_info = self.req_params["stream"]
f = open(os.path.join(self.upload_dir, file_info['file_name']), 'wb')
f.write(file_info['value'])
f.close()
self.send_result({"code": 200})
def send_result(self, result):
self.send_response(HTTPStatus.OK)
body = json.dumps(result).encode(ENCODING, 'replace')
self.send_header("Content-Type", CONTENT_TYPE_RAW_JSON)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def parse_body(self):
"""解析 HTTP 请求体中的参数
multipart/form-data 按照标准解析,文件请求二进制值并不解析,由用户自行处理
application/x-www-form-urlencoded application/json 按照标准解析
text/plain application/xml 按照字符串解析 不验证格式
其他格式皆返回二进制值
Parse the parameters in the HTTP request body
-Multipart / form-data is parsed according to the standard,
the binary value of the file request is not parsed, and is
handled by the user
-application / x-www-form-urlencoded application / json is
parsed according to the standard
- text / plain application / xml parsing according to the
string without verifying the format
- All other formats return binary values
"""
encoding = ENCODING
content_length = self.headers.get("Content-Length")
if content_length and content_length != 0:
body = self.rfile.read(int(content_length))
content_type = self.headers.get('Content-Type')
content_type_up = content_type.upper()
params = None
if CONTENT_TYPE_FORM.upper() in content_type_up:
"""
...
Content-Type: multipart/form-data; boundary=${boundary}
--${boundary}
...
...
--${boundary}--
"""
boundary = content_type.split("boundary=")[1]
tag = b'--'
bin_boundary = tag + boundary.encode() + b'\r\n'
bin_boundary_end = tag + boundary.encode() + tag + b'\r\n'
if not body.startswith(bin_boundary):
self.send_error(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "multipart/form-data format error")
return False
if not body.endswith(bin_boundary_end):
self.send_error(HTTPStatus.UNSUPPORTED_MEDIA_TYPE, "multipart/form-data format error")
return False
body = body[len(bin_boundary):]
body = body[:-len(bin_boundary_end)]
content_list = body.split(bin_boundary)
params = {}
key = ""
for line in content_list:
meta_key, meta_value = line.split(b'\r\n\r\n')
meta_key = meta_key.decode(encoding)
name_begin = meta_key.find("name=\"") + 6
name_end = meta_key.find("\"", name_begin)
name = meta_key[name_begin:name_end]
if not name.strip():
continue
file_name_begin = meta_key.find("filename=\"")
if file_name_begin == -1:
meta_value = meta_value.decode(encoding)
value = meta_value.rstrip('\r\n')
params[name] = value
else:
file_name_begin += 10
file_name_end = meta_key.find("\"", file_name_begin)
file_name = meta_key[file_name_begin:file_name_end]
file_type = meta_key[meta_key.find("Content-Type:") + 13:]
value = meta_value[:-len(b'\r\n')]
# record file info
params[name] = {"file_name": file_name,
"file_type": file_type,
"value": value}
self.req_params = params
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cgi', action='store_true',
help='Run as CGI Server')
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('--directory', '-d', default=os.getcwd(),
help='Specify alternative directory '
'[default:current directory]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
handler_class = partial(CustomRequestHandler,
directory=args.directory)
test(HandlerClass=handler_class, port=args.port, bind=args.bind) | 0.328529 | 0.055823 |
import json
import re
from wtforms import StringField
from wtforms.validators import DataRequired, ValidationError
from app.validators.base import NotRequiredDateTimeForm
class CreateProblemSetForm(NotRequiredDateTimeForm):
name = StringField(validators=[DataRequired(message='Problem set name cannot be empty')])
problem_list = StringField(validators=[DataRequired(message='Problem list cannot be empty')])
user_list = StringField(validators=[DataRequired(message='User list cannot be empty')])
def validate_problem_list(self, value):
try:
self.problem_list.data = json.loads(self.problem_list.data)
if not isinstance(self.problem_list.data, list):
raise Exception()
except Exception:
raise ValidationError('Problem list must be list')
for i in self.problem_list.data:
if re.match('[a-z_]+-.+', i['problem']) is None:
raise ValidationError('Problem format error')
def validate_user_list(self, value):
try:
self.user_list.data = json.loads(self.user_list.data)
if not isinstance(self.user_list.data, list):
raise Exception()
except Exception:
raise ValidationError('User list must be list')
for i in self.user_list.data:
if type(i) != str:
raise ValidationError('Username must be string')
class ModifyProblemSetForm(NotRequiredDateTimeForm):
name = StringField()
problem_list = StringField()
def validate_problem_list(self, value):
if self.problem_list.data:
try:
self.problem_list.data = json.loads(self.problem_list.data)
if not isinstance(self.problem_list.data, list):
raise Exception()
except Exception:
raise ValidationError('Problem list must be list')
for i in self.problem_list.data:
if re.match('[a-z_]+-.+', i['problem']) is None:
raise ValidationError('Problem format error') | app/validators/problem_set.py | import json
import re
from wtforms import StringField
from wtforms.validators import DataRequired, ValidationError
from app.validators.base import NotRequiredDateTimeForm
class CreateProblemSetForm(NotRequiredDateTimeForm):
name = StringField(validators=[DataRequired(message='Problem set name cannot be empty')])
problem_list = StringField(validators=[DataRequired(message='Problem list cannot be empty')])
user_list = StringField(validators=[DataRequired(message='User list cannot be empty')])
def validate_problem_list(self, value):
try:
self.problem_list.data = json.loads(self.problem_list.data)
if not isinstance(self.problem_list.data, list):
raise Exception()
except Exception:
raise ValidationError('Problem list must be list')
for i in self.problem_list.data:
if re.match('[a-z_]+-.+', i['problem']) is None:
raise ValidationError('Problem format error')
def validate_user_list(self, value):
try:
self.user_list.data = json.loads(self.user_list.data)
if not isinstance(self.user_list.data, list):
raise Exception()
except Exception:
raise ValidationError('User list must be list')
for i in self.user_list.data:
if type(i) != str:
raise ValidationError('Username must be string')
class ModifyProblemSetForm(NotRequiredDateTimeForm):
name = StringField()
problem_list = StringField()
def validate_problem_list(self, value):
if self.problem_list.data:
try:
self.problem_list.data = json.loads(self.problem_list.data)
if not isinstance(self.problem_list.data, list):
raise Exception()
except Exception:
raise ValidationError('Problem list must be list')
for i in self.problem_list.data:
if re.match('[a-z_]+-.+', i['problem']) is None:
raise ValidationError('Problem format error') | 0.298491 | 0.073132 |
import os
import pytest
import yaml
import re
import requests
from kiali import KialiClient
from utils.command_exec import command_exec
from pkg_resources import resource_string
from urllib.request import urlopen
CONFIG_PATH = '../config'
ENV_FILE = CONFIG_PATH + '/env.yaml'
ASSETS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets')
CIRCUIT_BREAKER_FILE = ASSETS_PATH + '/bookinfo-reviews-all-cb.yaml'
VIRTUAL_SERVICE_FILE = ASSETS_PATH + '/bookinfo-ratings-delay.yaml'
WORKLOADS_FILE = ASSETS_PATH + '/bookinfo-workloads.yaml'
CURRENT_CONFIGMAP_FILE = './current_kiali_configmap.yaml'
NEW_CONFIG_MAP_FILE = './new_kiali_configmap.yaml'
@pytest.fixture(scope='session')
def kiali_client():
config = __get_environment_config__(ENV_FILE)
__remove_assets()
yield __get_kiali_client__(config)
def get_bookinfo_namespace():
return __get_environment_config__(ENV_FILE).get('mesh_bookinfo_namespace')
def __get_kiali_client__(config):
if(config.get('kiali_scheme') == 'https'):
return KialiClient(hostname=config.get('kiali_hostname'), auth_type=config.get(
'kiali_auth_method'), token=config.get('kiali_token'),
username=config.get('kiali_username'), password=config.<PASSWORD>('<PASSWORD>'), verify=config.get(
'kiali_verify_ssl_certificate'), swagger_address=config.get('kiali_swagger_address'), custom_base_path=config.get('kiali_custom_base_context'))
else:
return KialiClient(hostname=config.get('kiali_hostname'), username=config.get('kiali_username'), password=config.get('kiali_password'),
auth_type=config.get('kiali_auth_method'), swagger_address=config.get('kiali_swagger_address'), custom_base_path=config.get('kiali_custom_base_context'))
def __get_environment_config__(env_file):
yamlfile = resource_string(__name__, env_file)
config = yaml.safe_load(yamlfile)
return config
def __remove_assets():
print('Cleanning up (Note: ignore messages: "Error from server (NotFound))": ')
namespace = get_bookinfo_namespace()
file_count = 0
for root, dirs, files in os.walk(ASSETS_PATH):
file_count = len(files)
for name in files:
command_exec.oc_delete(ASSETS_PATH + "/" + name, namespace)
print('Assets deleted: {}'.format(file_count))
def get_istio_clusterrole_file():
file = __get_environment_config__(ENV_FILE).get('istio_clusterrole')
yaml_content = urlopen(file).read().decode("utf-8")
yaml_content = re.sub("app: {{.+}}", "app: kiali", yaml_content)
yaml_content = re.sub("chart: {{.+}}", "version: 0.10 ", yaml_content)
yaml_content = re.sub("heritage: {{.+}}\n", "", yaml_content)
yaml_content = re.sub("release: {{.+}}", "", yaml_content)
return next(yaml.safe_load_all(yaml_content))
def get_kiali_clusterrole_file(file_type):
if(file_type == "Openshift"):
file = __get_environment_config__(ENV_FILE).get('kiali_openshift_clusterrole')
elif(file_type == "Kubernetes"):
file = __get_environment_config__(ENV_FILE).get('kiali_kubernetes_clusterrole')
yaml_content = urlopen(file).read()
return next(yaml.safe_load_all(yaml_content))
def get_kiali_swagger_address():
return __get_environment_config__(ENV_FILE).get('kiali_swagger_address')
def get_kiali_auth_method():
return __get_environment_config__(ENV_FILE).get('kiali_auth_method')
def get_control_plane_namespace():
return __get_environment_config__(ENV_FILE).get('control_plane_namespace')
def get_kiali_hostname():
return __get_environment_config__(ENV_FILE).get('kiali_hostname')
def get_new_kiali_client():
return __get_kiali_client__(__get_environment_config__(ENV_FILE)) | tests/e2e/tests/conftest.py | import os
import pytest
import yaml
import re
import requests
from kiali import KialiClient
from utils.command_exec import command_exec
from pkg_resources import resource_string
from urllib.request import urlopen
CONFIG_PATH = '../config'
ENV_FILE = CONFIG_PATH + '/env.yaml'
ASSETS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../assets')
CIRCUIT_BREAKER_FILE = ASSETS_PATH + '/bookinfo-reviews-all-cb.yaml'
VIRTUAL_SERVICE_FILE = ASSETS_PATH + '/bookinfo-ratings-delay.yaml'
WORKLOADS_FILE = ASSETS_PATH + '/bookinfo-workloads.yaml'
CURRENT_CONFIGMAP_FILE = './current_kiali_configmap.yaml'
NEW_CONFIG_MAP_FILE = './new_kiali_configmap.yaml'
@pytest.fixture(scope='session')
def kiali_client():
config = __get_environment_config__(ENV_FILE)
__remove_assets()
yield __get_kiali_client__(config)
def get_bookinfo_namespace():
return __get_environment_config__(ENV_FILE).get('mesh_bookinfo_namespace')
def __get_kiali_client__(config):
if(config.get('kiali_scheme') == 'https'):
return KialiClient(hostname=config.get('kiali_hostname'), auth_type=config.get(
'kiali_auth_method'), token=config.get('kiali_token'),
username=config.get('kiali_username'), password=config.<PASSWORD>('<PASSWORD>'), verify=config.get(
'kiali_verify_ssl_certificate'), swagger_address=config.get('kiali_swagger_address'), custom_base_path=config.get('kiali_custom_base_context'))
else:
return KialiClient(hostname=config.get('kiali_hostname'), username=config.get('kiali_username'), password=config.get('kiali_password'),
auth_type=config.get('kiali_auth_method'), swagger_address=config.get('kiali_swagger_address'), custom_base_path=config.get('kiali_custom_base_context'))
def __get_environment_config__(env_file):
yamlfile = resource_string(__name__, env_file)
config = yaml.safe_load(yamlfile)
return config
def __remove_assets():
print('Cleanning up (Note: ignore messages: "Error from server (NotFound))": ')
namespace = get_bookinfo_namespace()
file_count = 0
for root, dirs, files in os.walk(ASSETS_PATH):
file_count = len(files)
for name in files:
command_exec.oc_delete(ASSETS_PATH + "/" + name, namespace)
print('Assets deleted: {}'.format(file_count))
def get_istio_clusterrole_file():
file = __get_environment_config__(ENV_FILE).get('istio_clusterrole')
yaml_content = urlopen(file).read().decode("utf-8")
yaml_content = re.sub("app: {{.+}}", "app: kiali", yaml_content)
yaml_content = re.sub("chart: {{.+}}", "version: 0.10 ", yaml_content)
yaml_content = re.sub("heritage: {{.+}}\n", "", yaml_content)
yaml_content = re.sub("release: {{.+}}", "", yaml_content)
return next(yaml.safe_load_all(yaml_content))
def get_kiali_clusterrole_file(file_type):
if(file_type == "Openshift"):
file = __get_environment_config__(ENV_FILE).get('kiali_openshift_clusterrole')
elif(file_type == "Kubernetes"):
file = __get_environment_config__(ENV_FILE).get('kiali_kubernetes_clusterrole')
yaml_content = urlopen(file).read()
return next(yaml.safe_load_all(yaml_content))
def get_kiali_swagger_address():
return __get_environment_config__(ENV_FILE).get('kiali_swagger_address')
def get_kiali_auth_method():
return __get_environment_config__(ENV_FILE).get('kiali_auth_method')
def get_control_plane_namespace():
return __get_environment_config__(ENV_FILE).get('control_plane_namespace')
def get_kiali_hostname():
return __get_environment_config__(ENV_FILE).get('kiali_hostname')
def get_new_kiali_client():
return __get_kiali_client__(__get_environment_config__(ENV_FILE)) | 0.237399 | 0.040846 |
from msrest.serialization import Model
class AccountSasParameters(Model):
"""The parameters to list SAS credentials of a storage account.
:param services: The signed services accessible with the account SAS.
Possible values include: Blob (b), Queue (q), Table (t), File (f).
Possible values include: 'b', 'q', 't', 'f'
:type services: str or ~azure.mgmt.storage.v2017_10_01.models.Services
:param resource_types: The signed resource types that are accessible with
the account SAS. Service (s): Access to service-level APIs; Container (c):
Access to container-level APIs; Object (o): Access to object-level APIs
for blobs, queue messages, table entities, and files. Possible values
include: 's', 'c', 'o'
:type resource_types: str or
~azure.mgmt.storage.v2017_10_01.models.SignedResourceTypes
:param permissions: The signed permissions for the account SAS. Possible
values include: Read (r), Write (w), Delete (d), List (l), Add (a), Create
(c), Update (u) and Process (p). Possible values include: 'r', 'd', 'w',
'l', 'a', 'c', 'u', 'p'
:type permissions: str or
~azure.mgmt.storage.v2017_10_01.models.Permissions
:param ip_address_or_range: An IP address or a range of IP addresses from
which to accept requests.
:type ip_address_or_range: str
:param protocols: The protocol permitted for a request made with the
account SAS. Possible values include: 'https,http', 'https'
:type protocols: str or
~azure.mgmt.storage.v2017_10_01.models.HttpProtocol
:param shared_access_start_time: The time at which the SAS becomes valid.
:type shared_access_start_time: datetime
:param shared_access_expiry_time: The time at which the shared access
signature becomes invalid.
:type shared_access_expiry_time: datetime
:param key_to_sign: The key to sign the account SAS token with.
:type key_to_sign: str
"""
_validation = {
'services': {'required': True},
'resource_types': {'required': True},
'permissions': {'required': True},
'shared_access_expiry_time': {'required': True},
}
_attribute_map = {
'services': {'key': 'signedServices', 'type': 'str'},
'resource_types': {'key': 'signedResourceTypes', 'type': 'str'},
'permissions': {'key': 'signedPermission', 'type': 'str'},
'ip_address_or_range': {'key': 'signedIp', 'type': 'str'},
'protocols': {'key': 'signedProtocol', 'type': 'HttpProtocol'},
'shared_access_start_time': {'key': 'signedStart', 'type': 'iso-8601'},
'shared_access_expiry_time': {'key': 'signedExpiry', 'type': 'iso-8601'},
'key_to_sign': {'key': 'keyToSign', 'type': 'str'},
}
def __init__(self, services, resource_types, permissions, shared_access_expiry_time, ip_address_or_range=None, protocols=None, shared_access_start_time=None, key_to_sign=None):
super(AccountSasParameters, self).__init__()
self.services = services
self.resource_types = resource_types
self.permissions = permissions
self.ip_address_or_range = ip_address_or_range
self.protocols = protocols
self.shared_access_start_time = shared_access_start_time
self.shared_access_expiry_time = shared_access_expiry_time
self.key_to_sign = key_to_sign | azure-mgmt-storage/azure/mgmt/storage/v2017_10_01/models/account_sas_parameters.py |
from msrest.serialization import Model
class AccountSasParameters(Model):
"""The parameters to list SAS credentials of a storage account.
:param services: The signed services accessible with the account SAS.
Possible values include: Blob (b), Queue (q), Table (t), File (f).
Possible values include: 'b', 'q', 't', 'f'
:type services: str or ~azure.mgmt.storage.v2017_10_01.models.Services
:param resource_types: The signed resource types that are accessible with
the account SAS. Service (s): Access to service-level APIs; Container (c):
Access to container-level APIs; Object (o): Access to object-level APIs
for blobs, queue messages, table entities, and files. Possible values
include: 's', 'c', 'o'
:type resource_types: str or
~azure.mgmt.storage.v2017_10_01.models.SignedResourceTypes
:param permissions: The signed permissions for the account SAS. Possible
values include: Read (r), Write (w), Delete (d), List (l), Add (a), Create
(c), Update (u) and Process (p). Possible values include: 'r', 'd', 'w',
'l', 'a', 'c', 'u', 'p'
:type permissions: str or
~azure.mgmt.storage.v2017_10_01.models.Permissions
:param ip_address_or_range: An IP address or a range of IP addresses from
which to accept requests.
:type ip_address_or_range: str
:param protocols: The protocol permitted for a request made with the
account SAS. Possible values include: 'https,http', 'https'
:type protocols: str or
~azure.mgmt.storage.v2017_10_01.models.HttpProtocol
:param shared_access_start_time: The time at which the SAS becomes valid.
:type shared_access_start_time: datetime
:param shared_access_expiry_time: The time at which the shared access
signature becomes invalid.
:type shared_access_expiry_time: datetime
:param key_to_sign: The key to sign the account SAS token with.
:type key_to_sign: str
"""
_validation = {
'services': {'required': True},
'resource_types': {'required': True},
'permissions': {'required': True},
'shared_access_expiry_time': {'required': True},
}
_attribute_map = {
'services': {'key': 'signedServices', 'type': 'str'},
'resource_types': {'key': 'signedResourceTypes', 'type': 'str'},
'permissions': {'key': 'signedPermission', 'type': 'str'},
'ip_address_or_range': {'key': 'signedIp', 'type': 'str'},
'protocols': {'key': 'signedProtocol', 'type': 'HttpProtocol'},
'shared_access_start_time': {'key': 'signedStart', 'type': 'iso-8601'},
'shared_access_expiry_time': {'key': 'signedExpiry', 'type': 'iso-8601'},
'key_to_sign': {'key': 'keyToSign', 'type': 'str'},
}
def __init__(self, services, resource_types, permissions, shared_access_expiry_time, ip_address_or_range=None, protocols=None, shared_access_start_time=None, key_to_sign=None):
super(AccountSasParameters, self).__init__()
self.services = services
self.resource_types = resource_types
self.permissions = permissions
self.ip_address_or_range = ip_address_or_range
self.protocols = protocols
self.shared_access_start_time = shared_access_start_time
self.shared_access_expiry_time = shared_access_expiry_time
self.key_to_sign = key_to_sign | 0.878939 | 0.400192 |
from copy import deepcopy
from typing import Any, Dict, List, Tuple, Union
from torch import nn
from torchmetrics.metric import Metric
class MetricCollection(nn.ModuleDict):
"""
MetricCollection class can be used to chain metrics that have the same
call pattern into one single class.
Args:
metrics: One of the following
* list or tuple: if metrics are passed in as a list, will use the
metrics class name as key for output dict. Therefore, two metrics
of the same class cannot be chained this way.
* dict: if metrics are passed in as a dict, will use each key in the
dict as key for output dict. Use this format if you want to chain
together multiple of the same metric with different parameters.
Example (input as list):
>>> import torch
>>> from torchmetrics import MetricCollection, Accuracy, Precision, Recall
>>> target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
>>> preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
>>> metrics = MetricCollection([Accuracy(),
... Precision(num_classes=3, average='macro'),
... Recall(num_classes=3, average='macro')])
>>> metrics(preds, target)
{'Accuracy': tensor(0.1250), 'Precision': tensor(0.0667), 'Recall': tensor(0.1111)}
Example (input as dict):
>>> metrics = MetricCollection({'micro_recall': Recall(num_classes=3, average='micro'),
... 'macro_recall': Recall(num_classes=3, average='macro')})
>>> same_metric = metrics.clone()
>>> metrics(preds, target)
{'micro_recall': tensor(0.1250), 'macro_recall': tensor(0.1111)}
>>> same_metric(preds, target)
{'micro_recall': tensor(0.1250), 'macro_recall': tensor(0.1111)}
>>> metrics.persistent()
"""
def __init__(self, metrics: Union[List[Metric], Tuple[Metric], Dict[str, Metric]]):
super().__init__()
if isinstance(metrics, dict):
# Check all values are metrics
for name, metric in metrics.items():
if not isinstance(metric, Metric):
raise ValueError(
f"Value {metric} belonging to key {name}"
" is not an instance of `pl.metrics.Metric`"
)
self[name] = metric
elif isinstance(metrics, (tuple, list)):
for metric in metrics:
if not isinstance(metric, Metric):
raise ValueError(
f"Input {metric} to `MetricCollection` is not a instance"
" of `pl.metrics.Metric`"
)
name = metric.__class__.__name__
if name in self:
raise ValueError(f"Encountered two metrics both named {name}")
self[name] = metric
else:
raise ValueError("Unknown input to MetricCollection.")
def forward(self, *args, **kwargs) -> Dict[str, Any]: # pylint: disable=E0202
"""
Iteratively call forward for each metric. Positional arguments (args) will
be passed to every metric in the collection, while keyword arguments (kwargs)
will be filtered based on the signature of the individual metric.
"""
return {k: m(*args, **m._filter_kwargs(**kwargs)) for k, m in self.items()}
def update(self, *args, **kwargs): # pylint: disable=E0202
"""
Iteratively call update for each metric. Positional arguments (args) will
be passed to every metric in the collection, while keyword arguments (kwargs)
will be filtered based on the signature of the individual metric.
"""
for _, m in self.items():
m_kwargs = m._filter_kwargs(**kwargs)
m.update(*args, **m_kwargs)
def compute(self) -> Dict[str, Any]:
return {k: m.compute() for k, m in self.items()}
def reset(self):
""" Iteratively call reset for each metric """
for _, m in self.items():
m.reset()
def clone(self):
""" Make a copy of the metric collection """
return deepcopy(self)
def persistent(self, mode: bool = True):
"""Method for post-init to change if metric states should be saved to
its state_dict
"""
for _, m in self.items():
m.persistent(mode) | torchmetrics/collections.py |
from copy import deepcopy
from typing import Any, Dict, List, Tuple, Union
from torch import nn
from torchmetrics.metric import Metric
class MetricCollection(nn.ModuleDict):
"""
MetricCollection class can be used to chain metrics that have the same
call pattern into one single class.
Args:
metrics: One of the following
* list or tuple: if metrics are passed in as a list, will use the
metrics class name as key for output dict. Therefore, two metrics
of the same class cannot be chained this way.
* dict: if metrics are passed in as a dict, will use each key in the
dict as key for output dict. Use this format if you want to chain
together multiple of the same metric with different parameters.
Example (input as list):
>>> import torch
>>> from torchmetrics import MetricCollection, Accuracy, Precision, Recall
>>> target = torch.tensor([0, 2, 0, 2, 0, 1, 0, 2])
>>> preds = torch.tensor([2, 1, 2, 0, 1, 2, 2, 2])
>>> metrics = MetricCollection([Accuracy(),
... Precision(num_classes=3, average='macro'),
... Recall(num_classes=3, average='macro')])
>>> metrics(preds, target)
{'Accuracy': tensor(0.1250), 'Precision': tensor(0.0667), 'Recall': tensor(0.1111)}
Example (input as dict):
>>> metrics = MetricCollection({'micro_recall': Recall(num_classes=3, average='micro'),
... 'macro_recall': Recall(num_classes=3, average='macro')})
>>> same_metric = metrics.clone()
>>> metrics(preds, target)
{'micro_recall': tensor(0.1250), 'macro_recall': tensor(0.1111)}
>>> same_metric(preds, target)
{'micro_recall': tensor(0.1250), 'macro_recall': tensor(0.1111)}
>>> metrics.persistent()
"""
def __init__(self, metrics: Union[List[Metric], Tuple[Metric], Dict[str, Metric]]):
super().__init__()
if isinstance(metrics, dict):
# Check all values are metrics
for name, metric in metrics.items():
if not isinstance(metric, Metric):
raise ValueError(
f"Value {metric} belonging to key {name}"
" is not an instance of `pl.metrics.Metric`"
)
self[name] = metric
elif isinstance(metrics, (tuple, list)):
for metric in metrics:
if not isinstance(metric, Metric):
raise ValueError(
f"Input {metric} to `MetricCollection` is not a instance"
" of `pl.metrics.Metric`"
)
name = metric.__class__.__name__
if name in self:
raise ValueError(f"Encountered two metrics both named {name}")
self[name] = metric
else:
raise ValueError("Unknown input to MetricCollection.")
def forward(self, *args, **kwargs) -> Dict[str, Any]: # pylint: disable=E0202
"""
Iteratively call forward for each metric. Positional arguments (args) will
be passed to every metric in the collection, while keyword arguments (kwargs)
will be filtered based on the signature of the individual metric.
"""
return {k: m(*args, **m._filter_kwargs(**kwargs)) for k, m in self.items()}
def update(self, *args, **kwargs): # pylint: disable=E0202
"""
Iteratively call update for each metric. Positional arguments (args) will
be passed to every metric in the collection, while keyword arguments (kwargs)
will be filtered based on the signature of the individual metric.
"""
for _, m in self.items():
m_kwargs = m._filter_kwargs(**kwargs)
m.update(*args, **m_kwargs)
def compute(self) -> Dict[str, Any]:
return {k: m.compute() for k, m in self.items()}
def reset(self):
""" Iteratively call reset for each metric """
for _, m in self.items():
m.reset()
def clone(self):
""" Make a copy of the metric collection """
return deepcopy(self)
def persistent(self, mode: bool = True):
"""Method for post-init to change if metric states should be saved to
its state_dict
"""
for _, m in self.items():
m.persistent(mode) | 0.960398 | 0.510985 |
import tensorflow.compat.v2 as tf
from keras import backend
from keras.layers.pooling.base_global_pooling1d import GlobalPooling1D
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export(
"keras.layers.GlobalAveragePooling1D", "keras.layers.GlobalAvgPool1D"
)
class GlobalAveragePooling1D(GlobalPooling1D):
"""Global average pooling operation for temporal data.
Examples:
>>> input_shape = (2, 3, 4)
>>> x = tf.random.normal(input_shape)
>>> y = tf.keras.layers.GlobalAveragePooling1D()(x)
>>> print(y.shape)
(2, 4)
Args:
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, steps, features)` while `channels_first`
corresponds to inputs with shape
`(batch, features, steps)`.
keepdims: A boolean, whether to keep the temporal dimension or not.
If `keepdims` is `False` (default), the rank of the tensor is reduced
for spatial dimensions.
If `keepdims` is `True`, the temporal dimension are retained with
length 1.
The behavior is the same as for `tf.reduce_mean` or `np.mean`.
Call arguments:
inputs: A 3D tensor.
mask: Binary tensor of shape `(batch_size, steps)` indicating whether
a given step should be masked (excluded from the average).
Input shape:
- If `data_format='channels_last'`:
3D tensor with shape:
`(batch_size, steps, features)`
- If `data_format='channels_first'`:
3D tensor with shape:
`(batch_size, features, steps)`
Output shape:
- If `keepdims`=False:
2D tensor with shape `(batch_size, features)`.
- If `keepdims`=True:
- If `data_format='channels_last'`:
3D tensor with shape `(batch_size, 1, features)`
- If `data_format='channels_first'`:
3D tensor with shape `(batch_size, features, 1)`
"""
def __init__(self, data_format="channels_last", **kwargs):
super().__init__(data_format=data_format, **kwargs)
self.supports_masking = True
def call(self, inputs, mask=None):
steps_axis = 1 if self.data_format == "channels_last" else 2
if mask is not None:
mask = tf.cast(mask, inputs[0].dtype)
mask = tf.expand_dims(
mask, 2 if self.data_format == "channels_last" else 1
)
inputs *= mask
return backend.sum(
inputs, axis=steps_axis, keepdims=self.keepdims
) / tf.reduce_sum(mask, axis=steps_axis, keepdims=self.keepdims)
else:
return backend.mean(inputs, axis=steps_axis, keepdims=self.keepdims)
def compute_mask(self, inputs, mask=None):
return None
# Alias
GlobalAvgPool1D = GlobalAveragePooling1D | keras/layers/pooling/global_average_pooling1d.py | import tensorflow.compat.v2 as tf
from keras import backend
from keras.layers.pooling.base_global_pooling1d import GlobalPooling1D
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export(
"keras.layers.GlobalAveragePooling1D", "keras.layers.GlobalAvgPool1D"
)
class GlobalAveragePooling1D(GlobalPooling1D):
"""Global average pooling operation for temporal data.
Examples:
>>> input_shape = (2, 3, 4)
>>> x = tf.random.normal(input_shape)
>>> y = tf.keras.layers.GlobalAveragePooling1D()(x)
>>> print(y.shape)
(2, 4)
Args:
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, steps, features)` while `channels_first`
corresponds to inputs with shape
`(batch, features, steps)`.
keepdims: A boolean, whether to keep the temporal dimension or not.
If `keepdims` is `False` (default), the rank of the tensor is reduced
for spatial dimensions.
If `keepdims` is `True`, the temporal dimension are retained with
length 1.
The behavior is the same as for `tf.reduce_mean` or `np.mean`.
Call arguments:
inputs: A 3D tensor.
mask: Binary tensor of shape `(batch_size, steps)` indicating whether
a given step should be masked (excluded from the average).
Input shape:
- If `data_format='channels_last'`:
3D tensor with shape:
`(batch_size, steps, features)`
- If `data_format='channels_first'`:
3D tensor with shape:
`(batch_size, features, steps)`
Output shape:
- If `keepdims`=False:
2D tensor with shape `(batch_size, features)`.
- If `keepdims`=True:
- If `data_format='channels_last'`:
3D tensor with shape `(batch_size, 1, features)`
- If `data_format='channels_first'`:
3D tensor with shape `(batch_size, features, 1)`
"""
def __init__(self, data_format="channels_last", **kwargs):
super().__init__(data_format=data_format, **kwargs)
self.supports_masking = True
def call(self, inputs, mask=None):
steps_axis = 1 if self.data_format == "channels_last" else 2
if mask is not None:
mask = tf.cast(mask, inputs[0].dtype)
mask = tf.expand_dims(
mask, 2 if self.data_format == "channels_last" else 1
)
inputs *= mask
return backend.sum(
inputs, axis=steps_axis, keepdims=self.keepdims
) / tf.reduce_sum(mask, axis=steps_axis, keepdims=self.keepdims)
else:
return backend.mean(inputs, axis=steps_axis, keepdims=self.keepdims)
def compute_mask(self, inputs, mask=None):
return None
# Alias
GlobalAvgPool1D = GlobalAveragePooling1D | 0.962497 | 0.622431 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='flyteidl/plugins/spark.proto',
package='flyteidl.plugins',
syntax='proto3',
serialized_options=_b('Z7github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/plugins'),
serialized_pb=_b('\n\x1c\x66lyteidl/plugins/spark.proto\x12\x10\x66lyteidl.plugins\"B\n\x10SparkApplication\".\n\x04Type\x12\n\n\x06PYTHON\x10\x00\x12\x08\n\x04JAVA\x10\x01\x12\t\n\x05SCALA\x10\x02\x12\x05\n\x01R\x10\x03\"\xf5\x02\n\x08SparkJob\x12@\n\x0f\x61pplicationType\x18\x01 \x01(\x0e\x32\'.flyteidl.plugins.SparkApplication.Type\x12\x1b\n\x13mainApplicationFile\x18\x02 \x01(\t\x12\x11\n\tmainClass\x18\x03 \x01(\t\x12<\n\tsparkConf\x18\x04 \x03(\x0b\x32).flyteidl.plugins.SparkJob.SparkConfEntry\x12>\n\nhadoopConf\x18\x05 \x03(\x0b\x32*.flyteidl.plugins.SparkJob.HadoopConfEntry\x12\x14\n\x0c\x65xecutorPath\x18\x06 \x01(\t\x1a\x30\n\x0eSparkConfEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x31\n\x0fHadoopConfEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x39Z7github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/pluginsb\x06proto3')
)
_SPARKAPPLICATION_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='flyteidl.plugins.SparkApplication.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='PYTHON', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='JAVA', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SCALA', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='R', index=3, number=3,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=70,
serialized_end=116,
)
_sym_db.RegisterEnumDescriptor(_SPARKAPPLICATION_TYPE)
_SPARKAPPLICATION = _descriptor.Descriptor(
name='SparkApplication',
full_name='flyteidl.plugins.SparkApplication',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_SPARKAPPLICATION_TYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=50,
serialized_end=116,
)
_SPARKJOB_SPARKCONFENTRY = _descriptor.Descriptor(
name='SparkConfEntry',
full_name='flyteidl.plugins.SparkJob.SparkConfEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='flyteidl.plugins.SparkJob.SparkConfEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='flyteidl.plugins.SparkJob.SparkConfEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=393,
serialized_end=441,
)
_SPARKJOB_HADOOPCONFENTRY = _descriptor.Descriptor(
name='HadoopConfEntry',
full_name='flyteidl.plugins.SparkJob.HadoopConfEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='flyteidl.plugins.SparkJob.HadoopConfEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='flyteidl.plugins.SparkJob.HadoopConfEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=443,
serialized_end=492,
)
_SPARKJOB = _descriptor.Descriptor(
name='SparkJob',
full_name='flyteidl.plugins.SparkJob',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='applicationType', full_name='flyteidl.plugins.SparkJob.applicationType', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mainApplicationFile', full_name='flyteidl.plugins.SparkJob.mainApplicationFile', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mainClass', full_name='flyteidl.plugins.SparkJob.mainClass', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sparkConf', full_name='flyteidl.plugins.SparkJob.sparkConf', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hadoopConf', full_name='flyteidl.plugins.SparkJob.hadoopConf', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='executorPath', full_name='flyteidl.plugins.SparkJob.executorPath', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_SPARKJOB_SPARKCONFENTRY, _SPARKJOB_HADOOPCONFENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=119,
serialized_end=492,
)
_SPARKAPPLICATION_TYPE.containing_type = _SPARKAPPLICATION
_SPARKJOB_SPARKCONFENTRY.containing_type = _SPARKJOB
_SPARKJOB_HADOOPCONFENTRY.containing_type = _SPARKJOB
_SPARKJOB.fields_by_name['applicationType'].enum_type = _SPARKAPPLICATION_TYPE
_SPARKJOB.fields_by_name['sparkConf'].message_type = _SPARKJOB_SPARKCONFENTRY
_SPARKJOB.fields_by_name['hadoopConf'].message_type = _SPARKJOB_HADOOPCONFENTRY
DESCRIPTOR.message_types_by_name['SparkApplication'] = _SPARKAPPLICATION
DESCRIPTOR.message_types_by_name['SparkJob'] = _SPARKJOB
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SparkApplication = _reflection.GeneratedProtocolMessageType('SparkApplication', (_message.Message,), dict(
DESCRIPTOR = _SPARKAPPLICATION,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkApplication)
))
_sym_db.RegisterMessage(SparkApplication)
SparkJob = _reflection.GeneratedProtocolMessageType('SparkJob', (_message.Message,), dict(
SparkConfEntry = _reflection.GeneratedProtocolMessageType('SparkConfEntry', (_message.Message,), dict(
DESCRIPTOR = _SPARKJOB_SPARKCONFENTRY,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob.SparkConfEntry)
))
,
HadoopConfEntry = _reflection.GeneratedProtocolMessageType('HadoopConfEntry', (_message.Message,), dict(
DESCRIPTOR = _SPARKJOB_HADOOPCONFENTRY,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob.HadoopConfEntry)
))
,
DESCRIPTOR = _SPARKJOB,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob)
))
_sym_db.RegisterMessage(SparkJob)
_sym_db.RegisterMessage(SparkJob.SparkConfEntry)
_sym_db.RegisterMessage(SparkJob.HadoopConfEntry)
DESCRIPTOR._options = None
_SPARKJOB_SPARKCONFENTRY._options = None
_SPARKJOB_HADOOPCONFENTRY._options = None
# @@protoc_insertion_point(module_scope) | gen/pb_python/flyteidl/plugins/spark_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='flyteidl/plugins/spark.proto',
package='flyteidl.plugins',
syntax='proto3',
serialized_options=_b('Z7github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/plugins'),
serialized_pb=_b('\n\x1c\x66lyteidl/plugins/spark.proto\x12\x10\x66lyteidl.plugins\"B\n\x10SparkApplication\".\n\x04Type\x12\n\n\x06PYTHON\x10\x00\x12\x08\n\x04JAVA\x10\x01\x12\t\n\x05SCALA\x10\x02\x12\x05\n\x01R\x10\x03\"\xf5\x02\n\x08SparkJob\x12@\n\x0f\x61pplicationType\x18\x01 \x01(\x0e\x32\'.flyteidl.plugins.SparkApplication.Type\x12\x1b\n\x13mainApplicationFile\x18\x02 \x01(\t\x12\x11\n\tmainClass\x18\x03 \x01(\t\x12<\n\tsparkConf\x18\x04 \x03(\x0b\x32).flyteidl.plugins.SparkJob.SparkConfEntry\x12>\n\nhadoopConf\x18\x05 \x03(\x0b\x32*.flyteidl.plugins.SparkJob.HadoopConfEntry\x12\x14\n\x0c\x65xecutorPath\x18\x06 \x01(\t\x1a\x30\n\x0eSparkConfEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x31\n\x0fHadoopConfEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x39Z7github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/pluginsb\x06proto3')
)
_SPARKAPPLICATION_TYPE = _descriptor.EnumDescriptor(
name='Type',
full_name='flyteidl.plugins.SparkApplication.Type',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='PYTHON', index=0, number=0,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='JAVA', index=1, number=1,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SCALA', index=2, number=2,
serialized_options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='R', index=3, number=3,
serialized_options=None,
type=None),
],
containing_type=None,
serialized_options=None,
serialized_start=70,
serialized_end=116,
)
_sym_db.RegisterEnumDescriptor(_SPARKAPPLICATION_TYPE)
_SPARKAPPLICATION = _descriptor.Descriptor(
name='SparkApplication',
full_name='flyteidl.plugins.SparkApplication',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_SPARKAPPLICATION_TYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=50,
serialized_end=116,
)
_SPARKJOB_SPARKCONFENTRY = _descriptor.Descriptor(
name='SparkConfEntry',
full_name='flyteidl.plugins.SparkJob.SparkConfEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='flyteidl.plugins.SparkJob.SparkConfEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='flyteidl.plugins.SparkJob.SparkConfEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=393,
serialized_end=441,
)
_SPARKJOB_HADOOPCONFENTRY = _descriptor.Descriptor(
name='HadoopConfEntry',
full_name='flyteidl.plugins.SparkJob.HadoopConfEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='flyteidl.plugins.SparkJob.HadoopConfEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='flyteidl.plugins.SparkJob.HadoopConfEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=_b('8\001'),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=443,
serialized_end=492,
)
_SPARKJOB = _descriptor.Descriptor(
name='SparkJob',
full_name='flyteidl.plugins.SparkJob',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='applicationType', full_name='flyteidl.plugins.SparkJob.applicationType', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mainApplicationFile', full_name='flyteidl.plugins.SparkJob.mainApplicationFile', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='mainClass', full_name='flyteidl.plugins.SparkJob.mainClass', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sparkConf', full_name='flyteidl.plugins.SparkJob.sparkConf', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='hadoopConf', full_name='flyteidl.plugins.SparkJob.hadoopConf', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='executorPath', full_name='flyteidl.plugins.SparkJob.executorPath', index=5,
number=6, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[_SPARKJOB_SPARKCONFENTRY, _SPARKJOB_HADOOPCONFENTRY, ],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=119,
serialized_end=492,
)
_SPARKAPPLICATION_TYPE.containing_type = _SPARKAPPLICATION
_SPARKJOB_SPARKCONFENTRY.containing_type = _SPARKJOB
_SPARKJOB_HADOOPCONFENTRY.containing_type = _SPARKJOB
_SPARKJOB.fields_by_name['applicationType'].enum_type = _SPARKAPPLICATION_TYPE
_SPARKJOB.fields_by_name['sparkConf'].message_type = _SPARKJOB_SPARKCONFENTRY
_SPARKJOB.fields_by_name['hadoopConf'].message_type = _SPARKJOB_HADOOPCONFENTRY
DESCRIPTOR.message_types_by_name['SparkApplication'] = _SPARKAPPLICATION
DESCRIPTOR.message_types_by_name['SparkJob'] = _SPARKJOB
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SparkApplication = _reflection.GeneratedProtocolMessageType('SparkApplication', (_message.Message,), dict(
DESCRIPTOR = _SPARKAPPLICATION,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkApplication)
))
_sym_db.RegisterMessage(SparkApplication)
SparkJob = _reflection.GeneratedProtocolMessageType('SparkJob', (_message.Message,), dict(
SparkConfEntry = _reflection.GeneratedProtocolMessageType('SparkConfEntry', (_message.Message,), dict(
DESCRIPTOR = _SPARKJOB_SPARKCONFENTRY,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob.SparkConfEntry)
))
,
HadoopConfEntry = _reflection.GeneratedProtocolMessageType('HadoopConfEntry', (_message.Message,), dict(
DESCRIPTOR = _SPARKJOB_HADOOPCONFENTRY,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob.HadoopConfEntry)
))
,
DESCRIPTOR = _SPARKJOB,
__module__ = 'flyteidl.plugins.spark_pb2'
# @@protoc_insertion_point(class_scope:flyteidl.plugins.SparkJob)
))
_sym_db.RegisterMessage(SparkJob)
_sym_db.RegisterMessage(SparkJob.SparkConfEntry)
_sym_db.RegisterMessage(SparkJob.HadoopConfEntry)
DESCRIPTOR._options = None
_SPARKJOB_SPARKCONFENTRY._options = None
_SPARKJOB_HADOOPCONFENTRY._options = None
# @@protoc_insertion_point(module_scope) | 0.229018 | 0.136493 |
import numpy as np
from scipy import linalg
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array
from utils_wpca import check_array_with_weights, weighted_mean
class WPCA(BaseEstimator, TransformerMixin):
"""Weighted Principal Component Analysis
Parameters
----------
n_components : int (optional)
Number of components to keep. If not specified, all components are kept
xi : float (optional)
Degree of weight enhancement.
regularization : float (optional)
Control the strength of ridge regularization used to compute the
transform.
copy_data : boolean, optional, default True
If True, X and weights will be copied; else, they may be overwritten.
Attributes
----------
components_ : array, [n_components, n_features]
Principal axes in feature space, representing the directions of
maximum variance in the data.
explained_variance_ : array, [n_components]
The amount of variance explained by each of the selected components.
explained_variance_ratio_ : array, [n_components]
Percentage of variance explained by each of the selected components.
mean_ : array, [n_features]
Per-feature empirical mean, estimated from the training set.
See Also
--------
- PCA
- sklearn.decomposition.PCA
"""
def __init__(self, n_components=None, xi=0, regularization=None,
copy_data=True, mean_centering=True):
self.n_components = n_components
self.xi = xi
self.regularization = regularization
self.copy_data = copy_data
self.mean_centering = mean_centering
def _center_and_weight(self, X, weights, fit_mean=False):
"""Compute centered and weighted version of X.
If fit_mean is True, then also save the mean to self.mean_
"""
X, weights = check_array_with_weights(X, weights, dtype=float,
copy=self.copy_data)
if fit_mean:
self.mean_ = weighted_mean(X, weights, axis=0)
# now let X <- (X - mean) * weights
if self.mean_centering:
X -= self.mean_
if weights is not None:
X *= weights
else:
weights = np.ones_like(X)
return X.astype(np.float64), weights.astype(np.float64)
def fit(self, X, y=None, weights=None):
"""Compute principal components for X
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
self : object
Returns the instance itself.
"""
# let X <- (X - mean) * weights
X, weights = self._center_and_weight(X, weights, fit_mean=True)
self._fit_precentered(X, weights)
return self
def _fit_precentered(self, X, weights):
"""fit pre-centered data"""
if self.n_components is None:
n_components = X.shape[1]
else:
n_components = self.n_components
# TODO: filter NaN warnings
covar = np.dot(X.T, X)
wscale = np.dot(weights.T, weights)
covar /= np.dot(weights.T, weights)
covar[np.isnan(covar)] = 0
# enhance weights if desired
if self.xi != 0:
Ws = weights.sum(0)
covar *= np.outer(Ws, Ws) ** self.xi
eigvals = (X.shape[1] - n_components, X.shape[1] - 1)
evals, evecs = linalg.eigh(covar, eigvals=eigvals)
'''
evals, evecs = np.linalg.eigh(covar)
evals = evals[(X.shape[1] - n_components):X.shape[1]]; evecs = evecs[(X.shape[1] - n_components):X.shape[1]]
'''
self.components_ = evecs[:, ::-1].T
self.explained_variance_ = evals[::-1]
if covar.trace() == 0:
self.explained_variance_ratio_ = evals[::-1]
raise ZeroDivisionError('It is likely that the covar matrix is all 0s thus the trace is {} because after mean-centering everything is 0'.format(covar.trace))
else:
self.explained_variance_ratio_ = evals[::-1] / covar.trace()
def transform(self, X, weights=None):
"""Apply dimensionality reduction on X.
X is projected on the first principal components previous extracted
from a training set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
New data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
X, weights = self._center_and_weight(X, weights, fit_mean=False)
return self._transform_precentered(X, weights)
def _transform_precentered(self, X, weights):
"""transform pre-centered data"""
# TODO: parallelize this?
Y = np.zeros((X.shape[0], self.components_.shape[0]))
for i in range(X.shape[0]):
cW = self.components_ * weights[i]
cWX = np.dot(cW, X[i])
cWc = np.dot(cW, cW.T)
if self.regularization is not None:
cWc += np.diag(self.regularization / self.explained_variance_)
Y[i] = np.linalg.solve(cWc, cWX)
return Y
def fit_transform(self, X, y=None, weights=None):
"""Fit the model with X and apply the dimensionality reduction on X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
New data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
X, weights = self._center_and_weight(X, weights, fit_mean=True)
self._fit_precentered(X, weights)
return self._transform_precentered(X, weights)
def inverse_transform(self, X):
"""Transform data back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
Returns
-------
X_original : array-like, shape (n_samples, n_features)
"""
X = check_array(X)
return self.mean_ + np.dot(X, self.components_)
def reconstruct(self, X, weights=None):
"""Reconstruct the data using the PCA model
This is equivalent to calling transform followed by inverse_transform.
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_reconstructed : ndarray, shape (n_samples, n_components)
Reconstructed version of X
"""
return self.inverse_transform(self.transform(X, weights=weights))
def fit_reconstruct(self, X, weights=None):
"""Fit the model and reconstruct the data using the PCA model
This is equivalent to calling fit_transform()
followed by inverse_transform().
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_reconstructed : ndarray, shape (n_samples, n_components)
Reconstructed version of X
"""
return self.inverse_transform(self.fit_transform(X, weights=weights)) | wpca.py | import numpy as np
from scipy import linalg
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_array
from utils_wpca import check_array_with_weights, weighted_mean
class WPCA(BaseEstimator, TransformerMixin):
"""Weighted Principal Component Analysis
Parameters
----------
n_components : int (optional)
Number of components to keep. If not specified, all components are kept
xi : float (optional)
Degree of weight enhancement.
regularization : float (optional)
Control the strength of ridge regularization used to compute the
transform.
copy_data : boolean, optional, default True
If True, X and weights will be copied; else, they may be overwritten.
Attributes
----------
components_ : array, [n_components, n_features]
Principal axes in feature space, representing the directions of
maximum variance in the data.
explained_variance_ : array, [n_components]
The amount of variance explained by each of the selected components.
explained_variance_ratio_ : array, [n_components]
Percentage of variance explained by each of the selected components.
mean_ : array, [n_features]
Per-feature empirical mean, estimated from the training set.
See Also
--------
- PCA
- sklearn.decomposition.PCA
"""
def __init__(self, n_components=None, xi=0, regularization=None,
copy_data=True, mean_centering=True):
self.n_components = n_components
self.xi = xi
self.regularization = regularization
self.copy_data = copy_data
self.mean_centering = mean_centering
def _center_and_weight(self, X, weights, fit_mean=False):
"""Compute centered and weighted version of X.
If fit_mean is True, then also save the mean to self.mean_
"""
X, weights = check_array_with_weights(X, weights, dtype=float,
copy=self.copy_data)
if fit_mean:
self.mean_ = weighted_mean(X, weights, axis=0)
# now let X <- (X - mean) * weights
if self.mean_centering:
X -= self.mean_
if weights is not None:
X *= weights
else:
weights = np.ones_like(X)
return X.astype(np.float64), weights.astype(np.float64)
def fit(self, X, y=None, weights=None):
"""Compute principal components for X
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
self : object
Returns the instance itself.
"""
# let X <- (X - mean) * weights
X, weights = self._center_and_weight(X, weights, fit_mean=True)
self._fit_precentered(X, weights)
return self
def _fit_precentered(self, X, weights):
"""fit pre-centered data"""
if self.n_components is None:
n_components = X.shape[1]
else:
n_components = self.n_components
# TODO: filter NaN warnings
covar = np.dot(X.T, X)
wscale = np.dot(weights.T, weights)
covar /= np.dot(weights.T, weights)
covar[np.isnan(covar)] = 0
# enhance weights if desired
if self.xi != 0:
Ws = weights.sum(0)
covar *= np.outer(Ws, Ws) ** self.xi
eigvals = (X.shape[1] - n_components, X.shape[1] - 1)
evals, evecs = linalg.eigh(covar, eigvals=eigvals)
'''
evals, evecs = np.linalg.eigh(covar)
evals = evals[(X.shape[1] - n_components):X.shape[1]]; evecs = evecs[(X.shape[1] - n_components):X.shape[1]]
'''
self.components_ = evecs[:, ::-1].T
self.explained_variance_ = evals[::-1]
if covar.trace() == 0:
self.explained_variance_ratio_ = evals[::-1]
raise ZeroDivisionError('It is likely that the covar matrix is all 0s thus the trace is {} because after mean-centering everything is 0'.format(covar.trace))
else:
self.explained_variance_ratio_ = evals[::-1] / covar.trace()
def transform(self, X, weights=None):
"""Apply dimensionality reduction on X.
X is projected on the first principal components previous extracted
from a training set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
New data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
X, weights = self._center_and_weight(X, weights, fit_mean=False)
return self._transform_precentered(X, weights)
def _transform_precentered(self, X, weights):
"""transform pre-centered data"""
# TODO: parallelize this?
Y = np.zeros((X.shape[0], self.components_.shape[0]))
for i in range(X.shape[0]):
cW = self.components_ * weights[i]
cWX = np.dot(cW, X[i])
cWc = np.dot(cW, cW.T)
if self.regularization is not None:
cWc += np.diag(self.regularization / self.explained_variance_)
Y[i] = np.linalg.solve(cWc, cWX)
return Y
def fit_transform(self, X, y=None, weights=None):
"""Fit the model with X and apply the dimensionality reduction on X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
New data, where n_samples in the number of samples
and n_features is the number of features.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
X, weights = self._center_and_weight(X, weights, fit_mean=True)
self._fit_precentered(X, weights)
return self._transform_precentered(X, weights)
def inverse_transform(self, X):
"""Transform data back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
Returns
-------
X_original : array-like, shape (n_samples, n_features)
"""
X = check_array(X)
return self.mean_ + np.dot(X, self.components_)
def reconstruct(self, X, weights=None):
"""Reconstruct the data using the PCA model
This is equivalent to calling transform followed by inverse_transform.
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_reconstructed : ndarray, shape (n_samples, n_components)
Reconstructed version of X
"""
return self.inverse_transform(self.transform(X, weights=weights))
def fit_reconstruct(self, X, weights=None):
"""Fit the model and reconstruct the data using the PCA model
This is equivalent to calling fit_transform()
followed by inverse_transform().
Parameters
----------
X : array-like, shape (n_samples, n_components)
Data in transformed representation.
weights: array-like, shape (n_samples, n_features)
Non-negative weights encoding the reliability of each measurement.
Equivalent to the inverse of the Gaussian errorbar.
Returns
-------
X_reconstructed : ndarray, shape (n_samples, n_components)
Reconstructed version of X
"""
return self.inverse_transform(self.fit_transform(X, weights=weights)) | 0.878295 | 0.646711 |
import abc
from collections import defaultdict
import networkx as nx
from aizynthfinder.chem import (
Molecule,
UniqueMolecule,
FixedRetroReaction,
hash_reactions,
)
from aizynthfinder.utils.image import make_visjs_page
class _ReactionTreeLoader(abc.ABC):
""" Base class for classes that creates a reaction tree object
"""
def __init__(self, *args, **kwargs):
# To avoid circular imports
from aizynthfinder.analysis import ReactionTree # noqa
self.tree = ReactionTree()
self._load(*args, **kwargs)
self.tree.is_solved = all(
self.tree.in_stock(node) for node in self.tree.leafs()
)
_RepeatingPatternIdentifier.find(self.tree)
def _add_node(self, node, depth=0, transform=0, in_stock=False, hide=False):
attributes = {
"hide": hide,
"depth": depth,
}
if isinstance(node, Molecule):
attributes.update({"transform": transform, "in_stock": in_stock})
self.tree.graph.add_node(node, **attributes)
if not self.tree.root:
self.tree.root = node
@abc.abstractmethod
def _load(self, *args, **kwargs):
pass
class ReactionTreeFromDict(_ReactionTreeLoader):
"""
Creates a reaction tree object from a dictionary
:param tree_dict: the dictionary representation
:type tree_dict: dict
"""
def _load(self, tree_dict):
self._parse_tree_dict(tree_dict)
def _parse_tree_dict(self, tree_dict, ncalls=0):
product_node = UniqueMolecule(smiles=tree_dict["smiles"])
self._add_node(
product_node,
depth=2 * ncalls,
transform=ncalls,
hide=tree_dict.get("hide", False),
in_stock=tree_dict["in_stock"],
)
rxn_tree_dict = tree_dict.get("children", [])
if not rxn_tree_dict:
return product_node
rxn_tree_dict = rxn_tree_dict[0]
reaction_node = FixedRetroReaction(
product_node,
smiles=rxn_tree_dict["smiles"],
metadata=rxn_tree_dict.get("metadata", {}),
)
self._add_node(
reaction_node, depth=2 * ncalls + 1, hide=rxn_tree_dict.get("hide", False)
)
self.tree.graph.add_edge(product_node, reaction_node)
reactant_nodes = []
for reactant_tree in rxn_tree_dict.get("children", []):
reactant_node = self._parse_tree_dict(reactant_tree, ncalls + 1)
self.tree.graph.add_edge(reaction_node, reactant_node)
reactant_nodes.append(reactant_node)
reaction_node.reactants = reactant_nodes
return product_node
class ReactionTreeFromMcts(_ReactionTreeLoader):
"""
Creates a reaction tree object from MCTS nodes and reaction objects
:param actions: the reactions forming the route
:type actions: list of RetroReaction
:param nodes: the MCTS nodes forming the route
:type nodes: list of Node
"""
def _load(self, actions, nodes):
self._unique_mols = {}
root_mol = nodes[0].state.mols[0]
self._unique_mols[id(root_mol)] = root_mol.make_unique()
self._add_node(
self._unique_mols[id(root_mol)], in_stock=nodes[0].state.is_solved,
)
for child, action in zip(nodes[1:], actions):
self._add_bipartite(child, action)
def _add_bipartite(self, child, action):
reaction_obj = FixedRetroReaction(
self._unique_mol(action.mol), smiles=action.smiles, metadata=action.metadata
)
self._add_node(reaction_obj, depth=action.mol.transform + 1)
self.tree.graph.add_edge(self._unique_mol(action.mol), reaction_obj)
reactant_nodes = []
for mol in child.state.mols:
if mol.parent is action.mol:
self._add_node(
self._unique_mol(mol),
depth=2 * mol.transform,
transform=mol.transform,
in_stock=mol in child.state.stock,
)
self.tree.graph.add_edge(reaction_obj, self._unique_mol(mol))
reactant_nodes.append(self._unique_mol(mol))
reaction_obj.reactants = reactant_nodes
def _unique_mol(self, molecule):
id_ = id(molecule)
if id_ not in self._unique_mols:
self._unique_mols[id_] = molecule.make_unique()
return self._unique_mols[id_]
class _RepeatingPatternIdentifier:
"""
Encapsulation of algorithm to identify repeating patterns of reactions and mark them as hidden.
A unit of the repetition is the hash of two consecutive reactions,
where the first unit should be the first two reactions of the route.
This is for hiding repeating patterns of e.g. protection followed by deprotection,
which is a common behaviour for the tree search when it fails to solve a route.
"""
@staticmethod
def find(reaction_tree):
"""
Find the repeating patterns and mark the nodes
:param reaction_tree: the reaction tree to process
:type reaction_tree: ReactionTree
"""
for node in reaction_tree.reactions():
# We are only interesting of starting at the very first reaction
if any(reaction_tree.graph[mol] for mol in node.reactants[0]):
continue
actions = _RepeatingPatternIdentifier._list_reactions(reaction_tree, node)
if len(actions) < 5:
continue
hashes = [
hash_reactions([rxn1, rxn2], sort=False)
for rxn1, rxn2 in zip(actions[:-1:2], actions[1::2])
]
for idx, (hash1, hash2) in enumerate(zip(hashes[:-1], hashes[1:])):
if hash1 == hash2:
_RepeatingPatternIdentifier._hide_reaction(
reaction_tree, actions[idx * 2]
)
_RepeatingPatternIdentifier._hide_reaction(
reaction_tree, actions[idx * 2 + 1]
)
reaction_tree.has_repeating_patterns = True
# The else-clause prevents removing repeating patterns in the middle of a route
else:
break
@staticmethod
def _hide_reaction(reaction_tree, reaction_node):
reaction_tree.graph.nodes[reaction_node]["hide"] = True
for reactants in reaction_node.reactants[0]:
reaction_tree.graph.nodes[reactants]["hide"] = True
@staticmethod
def _list_reactions(reaction_tree, reaction_node):
""" List all reaction nodes from the given one to the last
"""
reactions = [reaction_node]
curr_rxn = reaction_node
product = reaction_node.mol
while product is not reaction_tree.root:
curr_rxn = next(reaction_tree.graph.predecessors(product))
product = curr_rxn.mol
reactions.append(curr_rxn)
return reactions
class CombinedReactionTrees:
"""
Encapsulation of an algorithm that combines several reaction trees into a
larger bipartite graph with all reactions and molecules.
The reactions at a specific level of the reaction trees are grouped based
on the reaction smiles.
:params reactions_trees: the list of reaction trees to combine
:type reaction_trees: list of ReactionTree
"""
def __init__(self, reaction_trees):
self.graph = nx.DiGraph()
first_rt = reaction_trees[0]
# This is to avoid circular imports
self._reaction_tree_class = first_rt.__class__
self.root = first_rt.root
self.graph.add_node(self.root, in_stock=first_rt.in_stock(self.root))
rt_node_spec = [(rt.root, rt.graph) for rt in reaction_trees]
self._add_reaction_trees_to_node(self.root, rt_node_spec)
def to_dict(self):
"""
Returns the graph as a dictionary in a pre-defined format.
:return: the combined reaction trees
:rtype: dict
"""
rt = self._reaction_tree_class()
rt.root = self.root
rt.graph = self.graph
return rt.to_dict()
def to_visjs_page(
self, filename, in_stock_colors={True: "green", False: "orange"},
):
"""
Create a visualization of the combined reaction tree using the vis.js network library.
The HTML page and all the images will be put into a tar-ball.
:param filename: the name of the tarball
:type filename: str
:param in_stock_colors: the colors around molecules, defaults to {True: "green", False: "orange"}
:type in_stock_colors: dict, optional
"""
molecules = [node for node in self.graph if isinstance(node, Molecule)]
reactions = [node for node in self.graph if not isinstance(node, Molecule)]
frame_colors = [
in_stock_colors[self.graph.nodes[node].get("in_stock", False)]
for node in molecules
]
make_visjs_page(filename, molecules, reactions, self.graph.edges, frame_colors)
def _add_reaction_trees_to_node(self, base_node, rt_node_spec):
reaction_groups = defaultdict(list)
# Group the reactions from the nodes at this level based on the reaction smiles
for node, graph in rt_node_spec:
for reaction in graph[node]:
reaction_groups[reaction.reaction_smiles()].append((graph, reaction))
for group in reaction_groups.values():
# Use the first RT in each group as the base
first_graph, first_reaction = group[0]
reaction_node = first_reaction.copy()
self.graph.add_edge(base_node, reaction_node)
for child in first_graph[first_reaction]:
mol_node = child.make_unique()
self.graph.add_node(
mol_node, in_stock=first_graph.nodes[child].get("in_stock", False)
)
self.graph.add_edge(reaction_node, mol_node)
self._add_reaction_trees_to_node(
mol_node, self._find_other_children(child, group)
)
@staticmethod
def _find_other_children(child, group):
children_spec = []
for other_graph, other_reaction in group:
found = False
for other_child in other_graph[other_reaction]:
if other_child.inchi_key == child.inchi_key:
children_spec.append((other_child, other_graph))
found = True
break
if not found:
raise ValueError("Could not find other child")
return children_spec | aizynthfinder/utils/analysis_helpers.py | import abc
from collections import defaultdict
import networkx as nx
from aizynthfinder.chem import (
Molecule,
UniqueMolecule,
FixedRetroReaction,
hash_reactions,
)
from aizynthfinder.utils.image import make_visjs_page
class _ReactionTreeLoader(abc.ABC):
""" Base class for classes that creates a reaction tree object
"""
def __init__(self, *args, **kwargs):
# To avoid circular imports
from aizynthfinder.analysis import ReactionTree # noqa
self.tree = ReactionTree()
self._load(*args, **kwargs)
self.tree.is_solved = all(
self.tree.in_stock(node) for node in self.tree.leafs()
)
_RepeatingPatternIdentifier.find(self.tree)
def _add_node(self, node, depth=0, transform=0, in_stock=False, hide=False):
attributes = {
"hide": hide,
"depth": depth,
}
if isinstance(node, Molecule):
attributes.update({"transform": transform, "in_stock": in_stock})
self.tree.graph.add_node(node, **attributes)
if not self.tree.root:
self.tree.root = node
@abc.abstractmethod
def _load(self, *args, **kwargs):
pass
class ReactionTreeFromDict(_ReactionTreeLoader):
"""
Creates a reaction tree object from a dictionary
:param tree_dict: the dictionary representation
:type tree_dict: dict
"""
def _load(self, tree_dict):
self._parse_tree_dict(tree_dict)
def _parse_tree_dict(self, tree_dict, ncalls=0):
product_node = UniqueMolecule(smiles=tree_dict["smiles"])
self._add_node(
product_node,
depth=2 * ncalls,
transform=ncalls,
hide=tree_dict.get("hide", False),
in_stock=tree_dict["in_stock"],
)
rxn_tree_dict = tree_dict.get("children", [])
if not rxn_tree_dict:
return product_node
rxn_tree_dict = rxn_tree_dict[0]
reaction_node = FixedRetroReaction(
product_node,
smiles=rxn_tree_dict["smiles"],
metadata=rxn_tree_dict.get("metadata", {}),
)
self._add_node(
reaction_node, depth=2 * ncalls + 1, hide=rxn_tree_dict.get("hide", False)
)
self.tree.graph.add_edge(product_node, reaction_node)
reactant_nodes = []
for reactant_tree in rxn_tree_dict.get("children", []):
reactant_node = self._parse_tree_dict(reactant_tree, ncalls + 1)
self.tree.graph.add_edge(reaction_node, reactant_node)
reactant_nodes.append(reactant_node)
reaction_node.reactants = reactant_nodes
return product_node
class ReactionTreeFromMcts(_ReactionTreeLoader):
"""
Creates a reaction tree object from MCTS nodes and reaction objects
:param actions: the reactions forming the route
:type actions: list of RetroReaction
:param nodes: the MCTS nodes forming the route
:type nodes: list of Node
"""
def _load(self, actions, nodes):
self._unique_mols = {}
root_mol = nodes[0].state.mols[0]
self._unique_mols[id(root_mol)] = root_mol.make_unique()
self._add_node(
self._unique_mols[id(root_mol)], in_stock=nodes[0].state.is_solved,
)
for child, action in zip(nodes[1:], actions):
self._add_bipartite(child, action)
def _add_bipartite(self, child, action):
reaction_obj = FixedRetroReaction(
self._unique_mol(action.mol), smiles=action.smiles, metadata=action.metadata
)
self._add_node(reaction_obj, depth=action.mol.transform + 1)
self.tree.graph.add_edge(self._unique_mol(action.mol), reaction_obj)
reactant_nodes = []
for mol in child.state.mols:
if mol.parent is action.mol:
self._add_node(
self._unique_mol(mol),
depth=2 * mol.transform,
transform=mol.transform,
in_stock=mol in child.state.stock,
)
self.tree.graph.add_edge(reaction_obj, self._unique_mol(mol))
reactant_nodes.append(self._unique_mol(mol))
reaction_obj.reactants = reactant_nodes
def _unique_mol(self, molecule):
id_ = id(molecule)
if id_ not in self._unique_mols:
self._unique_mols[id_] = molecule.make_unique()
return self._unique_mols[id_]
class _RepeatingPatternIdentifier:
"""
Encapsulation of algorithm to identify repeating patterns of reactions and mark them as hidden.
A unit of the repetition is the hash of two consecutive reactions,
where the first unit should be the first two reactions of the route.
This is for hiding repeating patterns of e.g. protection followed by deprotection,
which is a common behaviour for the tree search when it fails to solve a route.
"""
@staticmethod
def find(reaction_tree):
"""
Find the repeating patterns and mark the nodes
:param reaction_tree: the reaction tree to process
:type reaction_tree: ReactionTree
"""
for node in reaction_tree.reactions():
# We are only interesting of starting at the very first reaction
if any(reaction_tree.graph[mol] for mol in node.reactants[0]):
continue
actions = _RepeatingPatternIdentifier._list_reactions(reaction_tree, node)
if len(actions) < 5:
continue
hashes = [
hash_reactions([rxn1, rxn2], sort=False)
for rxn1, rxn2 in zip(actions[:-1:2], actions[1::2])
]
for idx, (hash1, hash2) in enumerate(zip(hashes[:-1], hashes[1:])):
if hash1 == hash2:
_RepeatingPatternIdentifier._hide_reaction(
reaction_tree, actions[idx * 2]
)
_RepeatingPatternIdentifier._hide_reaction(
reaction_tree, actions[idx * 2 + 1]
)
reaction_tree.has_repeating_patterns = True
# The else-clause prevents removing repeating patterns in the middle of a route
else:
break
@staticmethod
def _hide_reaction(reaction_tree, reaction_node):
reaction_tree.graph.nodes[reaction_node]["hide"] = True
for reactants in reaction_node.reactants[0]:
reaction_tree.graph.nodes[reactants]["hide"] = True
@staticmethod
def _list_reactions(reaction_tree, reaction_node):
""" List all reaction nodes from the given one to the last
"""
reactions = [reaction_node]
curr_rxn = reaction_node
product = reaction_node.mol
while product is not reaction_tree.root:
curr_rxn = next(reaction_tree.graph.predecessors(product))
product = curr_rxn.mol
reactions.append(curr_rxn)
return reactions
class CombinedReactionTrees:
"""
Encapsulation of an algorithm that combines several reaction trees into a
larger bipartite graph with all reactions and molecules.
The reactions at a specific level of the reaction trees are grouped based
on the reaction smiles.
:params reactions_trees: the list of reaction trees to combine
:type reaction_trees: list of ReactionTree
"""
def __init__(self, reaction_trees):
self.graph = nx.DiGraph()
first_rt = reaction_trees[0]
# This is to avoid circular imports
self._reaction_tree_class = first_rt.__class__
self.root = first_rt.root
self.graph.add_node(self.root, in_stock=first_rt.in_stock(self.root))
rt_node_spec = [(rt.root, rt.graph) for rt in reaction_trees]
self._add_reaction_trees_to_node(self.root, rt_node_spec)
def to_dict(self):
"""
Returns the graph as a dictionary in a pre-defined format.
:return: the combined reaction trees
:rtype: dict
"""
rt = self._reaction_tree_class()
rt.root = self.root
rt.graph = self.graph
return rt.to_dict()
def to_visjs_page(
self, filename, in_stock_colors={True: "green", False: "orange"},
):
"""
Create a visualization of the combined reaction tree using the vis.js network library.
The HTML page and all the images will be put into a tar-ball.
:param filename: the name of the tarball
:type filename: str
:param in_stock_colors: the colors around molecules, defaults to {True: "green", False: "orange"}
:type in_stock_colors: dict, optional
"""
molecules = [node for node in self.graph if isinstance(node, Molecule)]
reactions = [node for node in self.graph if not isinstance(node, Molecule)]
frame_colors = [
in_stock_colors[self.graph.nodes[node].get("in_stock", False)]
for node in molecules
]
make_visjs_page(filename, molecules, reactions, self.graph.edges, frame_colors)
def _add_reaction_trees_to_node(self, base_node, rt_node_spec):
reaction_groups = defaultdict(list)
# Group the reactions from the nodes at this level based on the reaction smiles
for node, graph in rt_node_spec:
for reaction in graph[node]:
reaction_groups[reaction.reaction_smiles()].append((graph, reaction))
for group in reaction_groups.values():
# Use the first RT in each group as the base
first_graph, first_reaction = group[0]
reaction_node = first_reaction.copy()
self.graph.add_edge(base_node, reaction_node)
for child in first_graph[first_reaction]:
mol_node = child.make_unique()
self.graph.add_node(
mol_node, in_stock=first_graph.nodes[child].get("in_stock", False)
)
self.graph.add_edge(reaction_node, mol_node)
self._add_reaction_trees_to_node(
mol_node, self._find_other_children(child, group)
)
@staticmethod
def _find_other_children(child, group):
children_spec = []
for other_graph, other_reaction in group:
found = False
for other_child in other_graph[other_reaction]:
if other_child.inchi_key == child.inchi_key:
children_spec.append((other_child, other_graph))
found = True
break
if not found:
raise ValueError("Could not find other child")
return children_spec | 0.779616 | 0.362913 |
import sys
import time
import os
import re
import requests
import json
import numpy as np
import matplotlib.pyplot as plt
domain = "https://qiita.com"
username = ""
token = ""
def check_domain_valid(domain: str):
regex = "^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$"
return True if re.match(regex, domain) else False
def check_url_valid(url: str):
regex = "^(http|https)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"
return True if re.match(regex, domain) else False
def exec_http_requrest(url: str, headers={}):
headers = {'Authorization': "Bearer " + token}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response
else:
return response.status_code
def get_user_ingo(username: str):
if exec_http_requrest(gen_url(domain, "agwagopkewpogkew", 0)) == 404:
pass
def get_itmes(url: str, js: list, pages: int):
response = exec_http_requrest(url)
tmp = json.loads(response.text)
js.extend(tmp)
if len(js) % 20 == 0:
get_itmes(gen_url(domain, username, pages+1), js, pages+1)
return js
def gen_url(domain: str, username: str, pages: int):
if pages:
return f'{domain}/api/v2/users/{username}/items?page={pages}'
else:
return f'{domain}/api/v2/users/{username}'
def get_titles(items: list, kind: str):
if kind is "title":
return [items[i]['title'] for i in range(len(items))]
elif kind is "id":
return [items[i]['id'] for i in range(len(items))]
elif kind is "views":
return []
def get_views_count(id_list: list):
view_list = []
for i in range(len(id_list)):
url = "https://qiita.com/api/v2/items/" + id_list[i]
tmp = json.loads(exec_http_requrest(url).text)
view_list.append(tmp['page_views_count'])
time.sleep(3)
return view_list
def load_config(conf_path: str):
pass
def data_prot(data: list):
x_width = 0.5
x_loc = np.array(range(len(data))) + x_width
labels = [i for i in range(len(data))]
plt.figure(figsize=(30, 15), dpi=50, facecolor="azure", edgecolor="coral")
plt.title(f'view count / Total : [{sum(data)}]', fontsize=30)
plt.ylabel("count", fontsize=20)
plt.bar(x_loc, data, color="green", width=x_width)
plt.xticks(x_loc, labels)
plt.show()
def main():
pages = 1
print(check_domain_valid(domain))
get_user_ingo(username)
url = gen_url(domain, username, pages)
response = get_itmes(url, [], pages)
id_list = get_titles(response, "id")
view_list = get_views_count(id_list)
data_prot(view_list)
if __name__ == "__main__":
main() | getqiitainfo.py | import sys
import time
import os
import re
import requests
import json
import numpy as np
import matplotlib.pyplot as plt
domain = "https://qiita.com"
username = ""
token = ""
def check_domain_valid(domain: str):
regex = "^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$"
return True if re.match(regex, domain) else False
def check_url_valid(url: str):
regex = "^(http|https)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"
return True if re.match(regex, domain) else False
def exec_http_requrest(url: str, headers={}):
headers = {'Authorization': "Bearer " + token}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response
else:
return response.status_code
def get_user_ingo(username: str):
if exec_http_requrest(gen_url(domain, "agwagopkewpogkew", 0)) == 404:
pass
def get_itmes(url: str, js: list, pages: int):
response = exec_http_requrest(url)
tmp = json.loads(response.text)
js.extend(tmp)
if len(js) % 20 == 0:
get_itmes(gen_url(domain, username, pages+1), js, pages+1)
return js
def gen_url(domain: str, username: str, pages: int):
if pages:
return f'{domain}/api/v2/users/{username}/items?page={pages}'
else:
return f'{domain}/api/v2/users/{username}'
def get_titles(items: list, kind: str):
if kind is "title":
return [items[i]['title'] for i in range(len(items))]
elif kind is "id":
return [items[i]['id'] for i in range(len(items))]
elif kind is "views":
return []
def get_views_count(id_list: list):
view_list = []
for i in range(len(id_list)):
url = "https://qiita.com/api/v2/items/" + id_list[i]
tmp = json.loads(exec_http_requrest(url).text)
view_list.append(tmp['page_views_count'])
time.sleep(3)
return view_list
def load_config(conf_path: str):
pass
def data_prot(data: list):
x_width = 0.5
x_loc = np.array(range(len(data))) + x_width
labels = [i for i in range(len(data))]
plt.figure(figsize=(30, 15), dpi=50, facecolor="azure", edgecolor="coral")
plt.title(f'view count / Total : [{sum(data)}]', fontsize=30)
plt.ylabel("count", fontsize=20)
plt.bar(x_loc, data, color="green", width=x_width)
plt.xticks(x_loc, labels)
plt.show()
def main():
pages = 1
print(check_domain_valid(domain))
get_user_ingo(username)
url = gen_url(domain, username, pages)
response = get_itmes(url, [], pages)
id_list = get_titles(response, "id")
view_list = get_views_count(id_list)
data_prot(view_list)
if __name__ == "__main__":
main() | 0.196749 | 0.217753 |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
"""
Base class defining the interface for a printer.
"""
from abc import ABC, abstractmethod
from enum import Enum
from typing import List, NamedTuple, Optional
from astroid import nodes
from pylint.pyreverse.utils import get_annotation_label
class NodeType(Enum):
CLASS = "class"
INTERFACE = "interface"
PACKAGE = "package"
class EdgeType(Enum):
INHERITS = "inherits"
IMPLEMENTS = "implements"
ASSOCIATION = "association"
USES = "uses"
class Layout(Enum):
LEFT_TO_RIGHT = "LR"
RIGHT_TO_LEFT = "RL"
TOP_TO_BOTTOM = "TB"
BOTTOM_TO_TOP = "BT"
class NodeProperties(NamedTuple):
label: str
attrs: Optional[List[str]] = None
methods: Optional[List[nodes.FunctionDef]] = None
color: Optional[str] = None
fontcolor: Optional[str] = None
class Printer(ABC):
"""Base class defining the interface for a printer"""
def __init__(
self,
title: str,
layout: Optional[Layout] = None,
use_automatic_namespace: Optional[bool] = None,
) -> None:
self.title: str = title
self.layout = layout
self.use_automatic_namespace = use_automatic_namespace
self.lines: List[str] = []
self._indent = ""
self._open_graph()
def _inc_indent(self) -> None:
"""increment indentation"""
self._indent += " "
def _dec_indent(self) -> None:
"""decrement indentation"""
self._indent = self._indent[:-2]
@abstractmethod
def _open_graph(self) -> None:
"""Emit the header lines, i.e. all boilerplate code that defines things like layout etc."""
def emit(self, line: str, force_newline: Optional[bool] = True) -> None:
if force_newline and not line.endswith("\n"):
line += "\n"
self.lines.append(self._indent + line)
@abstractmethod
def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
) -> None:
"""Create a new node. Nodes can be classes, packages, participants etc."""
@abstractmethod
def emit_edge(
self,
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
@staticmethod
def _get_method_arguments(method: nodes.FunctionDef) -> List[str]:
if method.args.args:
arguments: List[nodes.AssignName] = [
arg for arg in method.args.args if arg.name != "self"
]
else:
arguments = []
annotations = dict(zip(arguments, method.args.annotations[1:]))
for arg in arguments:
annotation_label = ""
ann = annotations.get(arg)
if ann:
annotation_label = get_annotation_label(ann)
annotations[arg] = annotation_label
return [
f"{arg.name}: {ann}" if ann else f"{arg.name}"
for arg, ann in annotations.items()
]
def generate(self, outputfile: str) -> None:
"""Generate and save the final outputfile."""
self._close_graph()
with open(outputfile, "w", encoding="utf-8") as outfile:
outfile.writelines(self.lines)
@abstractmethod
def _close_graph(self) -> None:
"""Emit the lines needed to properly close the graph.""" | Lib/site-packages/pylint/pyreverse/printer.py |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
"""
Base class defining the interface for a printer.
"""
from abc import ABC, abstractmethod
from enum import Enum
from typing import List, NamedTuple, Optional
from astroid import nodes
from pylint.pyreverse.utils import get_annotation_label
class NodeType(Enum):
CLASS = "class"
INTERFACE = "interface"
PACKAGE = "package"
class EdgeType(Enum):
INHERITS = "inherits"
IMPLEMENTS = "implements"
ASSOCIATION = "association"
USES = "uses"
class Layout(Enum):
LEFT_TO_RIGHT = "LR"
RIGHT_TO_LEFT = "RL"
TOP_TO_BOTTOM = "TB"
BOTTOM_TO_TOP = "BT"
class NodeProperties(NamedTuple):
label: str
attrs: Optional[List[str]] = None
methods: Optional[List[nodes.FunctionDef]] = None
color: Optional[str] = None
fontcolor: Optional[str] = None
class Printer(ABC):
"""Base class defining the interface for a printer"""
def __init__(
self,
title: str,
layout: Optional[Layout] = None,
use_automatic_namespace: Optional[bool] = None,
) -> None:
self.title: str = title
self.layout = layout
self.use_automatic_namespace = use_automatic_namespace
self.lines: List[str] = []
self._indent = ""
self._open_graph()
def _inc_indent(self) -> None:
"""increment indentation"""
self._indent += " "
def _dec_indent(self) -> None:
"""decrement indentation"""
self._indent = self._indent[:-2]
@abstractmethod
def _open_graph(self) -> None:
"""Emit the header lines, i.e. all boilerplate code that defines things like layout etc."""
def emit(self, line: str, force_newline: Optional[bool] = True) -> None:
if force_newline and not line.endswith("\n"):
line += "\n"
self.lines.append(self._indent + line)
@abstractmethod
def emit_node(
self,
name: str,
type_: NodeType,
properties: Optional[NodeProperties] = None,
) -> None:
"""Create a new node. Nodes can be classes, packages, participants etc."""
@abstractmethod
def emit_edge(
self,
from_node: str,
to_node: str,
type_: EdgeType,
label: Optional[str] = None,
) -> None:
"""Create an edge from one node to another to display relationships."""
@staticmethod
def _get_method_arguments(method: nodes.FunctionDef) -> List[str]:
if method.args.args:
arguments: List[nodes.AssignName] = [
arg for arg in method.args.args if arg.name != "self"
]
else:
arguments = []
annotations = dict(zip(arguments, method.args.annotations[1:]))
for arg in arguments:
annotation_label = ""
ann = annotations.get(arg)
if ann:
annotation_label = get_annotation_label(ann)
annotations[arg] = annotation_label
return [
f"{arg.name}: {ann}" if ann else f"{arg.name}"
for arg, ann in annotations.items()
]
def generate(self, outputfile: str) -> None:
"""Generate and save the final outputfile."""
self._close_graph()
with open(outputfile, "w", encoding="utf-8") as outfile:
outfile.writelines(self.lines)
@abstractmethod
def _close_graph(self) -> None:
"""Emit the lines needed to properly close the graph.""" | 0.969368 | 0.272572 |
import os
import csv
from pylab import *
from numpy import *
from loadData import loadData
from mymath import statistic, revcumsum
from random import sample as spl
#sim
N = 200000 # number of users
t0 = 500 # initial time for observation
T = t0 +320
P = [0.52] # probability of joining a banned group
mxP = 2 # maximum cumulative position for banning
#randomize initial time for each user
T0 = random.randint(0,t0,N)
POS = []
LSP = []
POS0 = []
for p in P:
Pos = zeros([N,T]) # position vs time for each user
Lsp = [] # life span
#do simulation
Pos[:,1:] = (random.random([N,T-1]) < p) * 2.0 - 1.0
for u in range(N):
Pos[u,:T0[u]+1] = 0.0
Pos = Pos.cumsum(1)
Pos0 = Pos[t0,:].tolist()
for u in range(N):
L = where(Pos[u,:]>=mxP)[0]
if len(L)>0:
L=L[0]
if L>t0:
Lsp.append(L-max(T0[u],t0))
POS.append(Pos)
LSP.append(Lsp)
POS0.append(Pos0)
#data
US=loadData('userStates')
N=len(US)
Dir='sav/Edgelists-all/'
fnames=os.listdir(Dir)
fileNames=[]
for f in fnames:
if f.startswith('Edges'):
fileNames.append(f)
fileNames=sorted(fileNames)
T=len(fileNames)
Ms={}
t=0
for f in fileNames:
fpath=Dir+f
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=' ')
U=set()
for row in data:
if US[row[0]] == 0:
U.add(row[0])
csvfile.close()
del data
for u in U:
if not u in Ms:
Ms[u] = [t,T]
else:
Ms[u][1] = t
t+=1
Ls=[]
for u in Ms:
if Ms[u][1] != T:
Ls.append(Ms[u][1]-Ms[u][0]+1)
f1=figure(1,figsize=(6,4))
x,y=statistic(Ls,norm=True)
_=loglog(x,y,'ro',label='empirical',alpha=0.5)
Lsp=LSP[0]
x,y=statistic(Lsp,norm=True)
_=loglog(x,y,'g-',label='$p$='+str(P[0]),alpha=0.5)
xlim([1,330])
xlabel(r'Lifespan [day]')
ylabel(r'Fraction')
legend(loc='best')
f1.set_tight_layout(True)
savefig('figs/Lifespan-bannedUsers-data-vs-sim.pdf', format='pdf')
close(1)
f=figure(1,figsize=(6,4))
for i in range(len(P)):
f.clf()
Pos=POS[i]
for u in range(500):
_=plot(Pos[u,:],alpha=0.2)
_=plot([t0,t0],[100,-100],'w--',linewidth=2.0)
_=plot([t0,t0+T],[mxP,mxP],'w--',linewidth=2.0)
xlabel(r'$Time$')
ylabel(r'$Position$')
savefig('figs/Time-Position-sim-p'+str(P[i])+'.png',bbox_inches='tight')
f.clf()
for i in range(len(P)):
Pos0=POS0[i]
x,y=statistic(Pos0,norm=True)
_=plot(x,y,label='$p$='+str(P[i]))
xlabel(r'$Position$')
ylabel(r'$Fraction$')
legend(loc='best')
savefig('figs/InitialPosition-sim.pdf',bbox_inches='tight')
close(1) | survival/lifespan-bannedsimVsdata.py | import os
import csv
from pylab import *
from numpy import *
from loadData import loadData
from mymath import statistic, revcumsum
from random import sample as spl
#sim
N = 200000 # number of users
t0 = 500 # initial time for observation
T = t0 +320
P = [0.52] # probability of joining a banned group
mxP = 2 # maximum cumulative position for banning
#randomize initial time for each user
T0 = random.randint(0,t0,N)
POS = []
LSP = []
POS0 = []
for p in P:
Pos = zeros([N,T]) # position vs time for each user
Lsp = [] # life span
#do simulation
Pos[:,1:] = (random.random([N,T-1]) < p) * 2.0 - 1.0
for u in range(N):
Pos[u,:T0[u]+1] = 0.0
Pos = Pos.cumsum(1)
Pos0 = Pos[t0,:].tolist()
for u in range(N):
L = where(Pos[u,:]>=mxP)[0]
if len(L)>0:
L=L[0]
if L>t0:
Lsp.append(L-max(T0[u],t0))
POS.append(Pos)
LSP.append(Lsp)
POS0.append(Pos0)
#data
US=loadData('userStates')
N=len(US)
Dir='sav/Edgelists-all/'
fnames=os.listdir(Dir)
fileNames=[]
for f in fnames:
if f.startswith('Edges'):
fileNames.append(f)
fileNames=sorted(fileNames)
T=len(fileNames)
Ms={}
t=0
for f in fileNames:
fpath=Dir+f
csvfile=open(fpath, 'rb')
data = csv.reader(csvfile, delimiter=' ')
U=set()
for row in data:
if US[row[0]] == 0:
U.add(row[0])
csvfile.close()
del data
for u in U:
if not u in Ms:
Ms[u] = [t,T]
else:
Ms[u][1] = t
t+=1
Ls=[]
for u in Ms:
if Ms[u][1] != T:
Ls.append(Ms[u][1]-Ms[u][0]+1)
f1=figure(1,figsize=(6,4))
x,y=statistic(Ls,norm=True)
_=loglog(x,y,'ro',label='empirical',alpha=0.5)
Lsp=LSP[0]
x,y=statistic(Lsp,norm=True)
_=loglog(x,y,'g-',label='$p$='+str(P[0]),alpha=0.5)
xlim([1,330])
xlabel(r'Lifespan [day]')
ylabel(r'Fraction')
legend(loc='best')
f1.set_tight_layout(True)
savefig('figs/Lifespan-bannedUsers-data-vs-sim.pdf', format='pdf')
close(1)
f=figure(1,figsize=(6,4))
for i in range(len(P)):
f.clf()
Pos=POS[i]
for u in range(500):
_=plot(Pos[u,:],alpha=0.2)
_=plot([t0,t0],[100,-100],'w--',linewidth=2.0)
_=plot([t0,t0+T],[mxP,mxP],'w--',linewidth=2.0)
xlabel(r'$Time$')
ylabel(r'$Position$')
savefig('figs/Time-Position-sim-p'+str(P[i])+'.png',bbox_inches='tight')
f.clf()
for i in range(len(P)):
Pos0=POS0[i]
x,y=statistic(Pos0,norm=True)
_=plot(x,y,label='$p$='+str(P[i]))
xlabel(r'$Position$')
ylabel(r'$Fraction$')
legend(loc='best')
savefig('figs/InitialPosition-sim.pdf',bbox_inches='tight')
close(1) | 0.154089 | 0.279203 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import logging
import random
from pajbot.models.command import Command, CommandExample
from pajbot.modules import BaseModule, ModuleSetting
from pajbot.modules.basic import BasicCommandsModule
if TYPE_CHECKING:
from pajbot.bot import Bot
from pajbot.models.user import User
log = logging.getLogger(__name__)
class SelfTimeoutModule(BaseModule):
ID = __name__.rsplit(".", maxsplit=1)[-1]
NAME = "Self timeout"
DESCRIPTION = "Allows users to timeout themselves based on a random duration."
CATEGORY = "Feature"
PARENT_MODULE = BasicCommandsModule
SETTINGS = [
ModuleSetting(
key="subscribers_only",
label="Only allow subscribers to use the !selftimeout command.",
type="boolean",
required=True,
default=False,
),
ModuleSetting(
key="vip_only",
label="Only allow VIPs to use the !selftimeout command.",
type="boolean",
required=True,
default=False,
),
ModuleSetting(
key="global_cd",
label="Global cooldown (seconds)",
type="number",
required=True,
placeholder="",
default=5,
constraints={"min_value": 0, "max_value": 120},
),
ModuleSetting(
key="user_cd",
label="Per-user cooldown (seconds)",
type="number",
required=True,
placeholder="",
default=15,
constraints={"min_value": 0, "max_value": 240},
),
ModuleSetting(
key="level",
label="Level required to use the command",
type="number",
required=True,
placeholder="",
default=100,
constraints={"min_value": 100, "max_value": 2000},
),
ModuleSetting(
key="command_name",
label="Command name (e.g. selftimeout)",
type="text",
required=True,
placeholder="Command name (no !)",
default="selftimeout",
constraints={"min_str_len": 2, "max_str_len": 15},
),
ModuleSetting(
key="low_value",
label="Lowest number to select from",
type="number",
required=True,
placeholder="0",
default=0,
constraints={"min_value": 0},
),
ModuleSetting(
key="high_value",
label="Highest number to select to",
type="number",
required=True,
placeholder="100",
default=100,
constraints={"min_value": 1},
),
ModuleSetting(
key="timeout_unit",
label="Choose the timeout format to use. Maximum Twitch timeout limits are enforced.",
type="options",
required=False,
default="Minutes",
options=["Seconds", "Minutes", "Hours", "Days", "Weeks"],
),
ModuleSetting(
key="zero_response",
label="Additional text to say when the user gets a 0. Text is disabled for moderator rolls.",
type="text",
required=False,
placeholder="You're safe! For now... PRChase",
default="You're safe! For now... PRChase",
constraints={"max_str_len": 100},
),
]
def load_commands(self, **options) -> None:
self.commands[self.settings["command_name"].lower().replace("!", "").replace(" ", "")] = Command.raw_command(
self.selftimeout,
sub_only=self.settings["subscribers_only"],
delay_all=self.settings["global_cd"],
delay_user=self.settings["user_cd"],
level=self.settings["level"],
examples=[
CommandExample(
None,
"Get timed out for a random duration",
chat="user:!selftimeout",
description="You don't get confirmation, only a timeout.",
).parse(),
],
)
# We're converting timeout times to seconds in order to avoid having to specify the unit to Twitch
def seconds_conversion(self, random_value: int) -> int:
if self.settings["timeout_unit"] == "Seconds":
return random_value
if self.settings["timeout_unit"] == "Minutes":
return random_value * 60
if self.settings["timeout_unit"] == "Hours":
return random_value * 3600
if self.settings["timeout_unit"] == "Days":
return random_value * 86400
if self.settings["timeout_unit"] == "Weeks":
return random_value * 604800
# Could raise an exception here instead too
return 0
def selftimeout(self, bot: Bot, source: User, event: Any, **rest) -> bool:
if self.settings["subscribers_only"] and not source.subscriber:
return True
if self.settings["vip_only"] and not source.vip:
return True
if source.moderator is True:
return True
random_value = random.randint(self.settings["low_value"], self.settings["high_value"])
standard_response = f"You got a {random_value}"
if random_value == 0 and self.settings["zero_response"] != "":
bot.send_message_to_user(
source, f"{standard_response}. {self.settings['zero_response']}", event, method="reply"
)
else:
timeout_length = self.seconds_conversion(random_value)
# Check if timeout value is over Twitch's maximum
timeout_length = min(timeout_length, 1209600)
bot.timeout(source, timeout_length, f"{standard_response}!", once=True)
return True | pajbot/modules/basic/selftimeout.py | from __future__ import annotations
from typing import TYPE_CHECKING, Any
import logging
import random
from pajbot.models.command import Command, CommandExample
from pajbot.modules import BaseModule, ModuleSetting
from pajbot.modules.basic import BasicCommandsModule
if TYPE_CHECKING:
from pajbot.bot import Bot
from pajbot.models.user import User
log = logging.getLogger(__name__)
class SelfTimeoutModule(BaseModule):
ID = __name__.rsplit(".", maxsplit=1)[-1]
NAME = "Self timeout"
DESCRIPTION = "Allows users to timeout themselves based on a random duration."
CATEGORY = "Feature"
PARENT_MODULE = BasicCommandsModule
SETTINGS = [
ModuleSetting(
key="subscribers_only",
label="Only allow subscribers to use the !selftimeout command.",
type="boolean",
required=True,
default=False,
),
ModuleSetting(
key="vip_only",
label="Only allow VIPs to use the !selftimeout command.",
type="boolean",
required=True,
default=False,
),
ModuleSetting(
key="global_cd",
label="Global cooldown (seconds)",
type="number",
required=True,
placeholder="",
default=5,
constraints={"min_value": 0, "max_value": 120},
),
ModuleSetting(
key="user_cd",
label="Per-user cooldown (seconds)",
type="number",
required=True,
placeholder="",
default=15,
constraints={"min_value": 0, "max_value": 240},
),
ModuleSetting(
key="level",
label="Level required to use the command",
type="number",
required=True,
placeholder="",
default=100,
constraints={"min_value": 100, "max_value": 2000},
),
ModuleSetting(
key="command_name",
label="Command name (e.g. selftimeout)",
type="text",
required=True,
placeholder="Command name (no !)",
default="selftimeout",
constraints={"min_str_len": 2, "max_str_len": 15},
),
ModuleSetting(
key="low_value",
label="Lowest number to select from",
type="number",
required=True,
placeholder="0",
default=0,
constraints={"min_value": 0},
),
ModuleSetting(
key="high_value",
label="Highest number to select to",
type="number",
required=True,
placeholder="100",
default=100,
constraints={"min_value": 1},
),
ModuleSetting(
key="timeout_unit",
label="Choose the timeout format to use. Maximum Twitch timeout limits are enforced.",
type="options",
required=False,
default="Minutes",
options=["Seconds", "Minutes", "Hours", "Days", "Weeks"],
),
ModuleSetting(
key="zero_response",
label="Additional text to say when the user gets a 0. Text is disabled for moderator rolls.",
type="text",
required=False,
placeholder="You're safe! For now... PRChase",
default="You're safe! For now... PRChase",
constraints={"max_str_len": 100},
),
]
def load_commands(self, **options) -> None:
self.commands[self.settings["command_name"].lower().replace("!", "").replace(" ", "")] = Command.raw_command(
self.selftimeout,
sub_only=self.settings["subscribers_only"],
delay_all=self.settings["global_cd"],
delay_user=self.settings["user_cd"],
level=self.settings["level"],
examples=[
CommandExample(
None,
"Get timed out for a random duration",
chat="user:!selftimeout",
description="You don't get confirmation, only a timeout.",
).parse(),
],
)
# We're converting timeout times to seconds in order to avoid having to specify the unit to Twitch
def seconds_conversion(self, random_value: int) -> int:
if self.settings["timeout_unit"] == "Seconds":
return random_value
if self.settings["timeout_unit"] == "Minutes":
return random_value * 60
if self.settings["timeout_unit"] == "Hours":
return random_value * 3600
if self.settings["timeout_unit"] == "Days":
return random_value * 86400
if self.settings["timeout_unit"] == "Weeks":
return random_value * 604800
# Could raise an exception here instead too
return 0
def selftimeout(self, bot: Bot, source: User, event: Any, **rest) -> bool:
if self.settings["subscribers_only"] and not source.subscriber:
return True
if self.settings["vip_only"] and not source.vip:
return True
if source.moderator is True:
return True
random_value = random.randint(self.settings["low_value"], self.settings["high_value"])
standard_response = f"You got a {random_value}"
if random_value == 0 and self.settings["zero_response"] != "":
bot.send_message_to_user(
source, f"{standard_response}. {self.settings['zero_response']}", event, method="reply"
)
else:
timeout_length = self.seconds_conversion(random_value)
# Check if timeout value is over Twitch's maximum
timeout_length = min(timeout_length, 1209600)
bot.timeout(source, timeout_length, f"{standard_response}!", once=True)
return True | 0.826467 | 0.131006 |
import contextlib
import enum
import socket
import uuid
import weakref
from typing import Any, Mapping, Optional, Sequence
try:
from pymongocrypt.auto_encrypter import AutoEncrypter
from pymongocrypt.errors import MongoCryptError # noqa: F401
from pymongocrypt.explicit_encrypter import ExplicitEncrypter
from pymongocrypt.mongocrypt import MongoCryptOptions
from pymongocrypt.state_machine import MongoCryptCallback
_HAVE_PYMONGOCRYPT = True
except ImportError:
_HAVE_PYMONGOCRYPT = False
MongoCryptCallback = object
from bson import _dict_to_bson, decode, encode
from bson.binary import STANDARD, UUID_SUBTYPE, Binary
from bson.codec_options import CodecOptions
from bson.errors import BSONError
from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson
from bson.son import SON
from pymongo import _csot
from pymongo.daemon import _spawn_daemon
from pymongo.encryption_options import AutoEncryptionOpts
from pymongo.errors import (
ConfigurationError,
EncryptionError,
InvalidOperation,
ServerSelectionTimeoutError,
)
from pymongo.mongo_client import MongoClient
from pymongo.network import BLOCKING_IO_ERRORS
from pymongo.pool import PoolOptions, _configured_socket
from pymongo.read_concern import ReadConcern
from pymongo.ssl_support import get_ssl_context
from pymongo.uri_parser import parse_host
from pymongo.write_concern import WriteConcern
_HTTPS_PORT = 443
_KMS_CONNECT_TIMEOUT = 10 # TODO: CDRIVER-3262 will define this value.
_MONGOCRYPTD_TIMEOUT_MS = 10000
_DATA_KEY_OPTS: CodecOptions = CodecOptions(document_class=SON, uuid_representation=STANDARD)
# Use RawBSONDocument codec options to avoid needlessly decoding
# documents from the key vault.
_KEY_VAULT_OPTS = CodecOptions(document_class=RawBSONDocument, uuid_representation=STANDARD)
@contextlib.contextmanager
def _wrap_encryption_errors():
"""Context manager to wrap encryption related errors."""
try:
yield
except BSONError:
# BSON encoding/decoding errors are unrelated to encryption so
# we should propagate them unchanged.
raise
except Exception as exc:
raise EncryptionError(exc)
class _EncryptionIO(MongoCryptCallback): # type: ignore
def __init__(self, client, key_vault_coll, mongocryptd_client, opts):
"""Internal class to perform I/O on behalf of pymongocrypt."""
self.client_ref: Any
# Use a weak ref to break reference cycle.
if client is not None:
self.client_ref = weakref.ref(client)
else:
self.client_ref = None
self.key_vault_coll = key_vault_coll.with_options(
codec_options=_KEY_VAULT_OPTS,
read_concern=ReadConcern(level="majority"),
write_concern=WriteConcern(w="majority"),
)
self.mongocryptd_client = mongocryptd_client
self.opts = opts
self._spawned = False
def kms_request(self, kms_context):
"""Complete a KMS request.
:Parameters:
- `kms_context`: A :class:`MongoCryptKmsContext`.
:Returns:
None
"""
endpoint = kms_context.endpoint
message = kms_context.message
provider = kms_context.kms_provider
ctx = self.opts._kms_ssl_contexts.get(provider)
if ctx is None:
# Enable strict certificate verification, OCSP, match hostname, and
# SNI using the system default CA certificates.
ctx = get_ssl_context(
None, # certfile
None, # passphrase
None, # ca_certs
None, # crlfile
False, # allow_invalid_certificates
False, # allow_invalid_hostnames
False,
) # disable_ocsp_endpoint_check
# CSOT: set timeout for socket creation.
connect_timeout = max(_csot.clamp_remaining(_KMS_CONNECT_TIMEOUT), 0.001)
opts = PoolOptions(
connect_timeout=connect_timeout,
socket_timeout=connect_timeout,
ssl_context=ctx,
)
host, port = parse_host(endpoint, _HTTPS_PORT)
conn = _configured_socket((host, port), opts)
try:
conn.sendall(message)
while kms_context.bytes_needed > 0:
# CSOT: update timeout.
conn.settimeout(max(_csot.clamp_remaining(_KMS_CONNECT_TIMEOUT), 0))
data = conn.recv(kms_context.bytes_needed)
if not data:
raise OSError("KMS connection closed")
kms_context.feed(data)
except BLOCKING_IO_ERRORS:
raise socket.timeout("timed out")
finally:
conn.close()
def collection_info(self, database, filter):
"""Get the collection info for a namespace.
The returned collection info is passed to libmongocrypt which reads
the JSON schema.
:Parameters:
- `database`: The database on which to run listCollections.
- `filter`: The filter to pass to listCollections.
:Returns:
The first document from the listCollections command response as BSON.
"""
with self.client_ref()[database].list_collections(filter=RawBSONDocument(filter)) as cursor:
for doc in cursor:
return _dict_to_bson(doc, False, _DATA_KEY_OPTS)
def spawn(self):
"""Spawn mongocryptd.
Note this method is thread safe; at most one mongocryptd will start
successfully.
"""
self._spawned = True
args = [self.opts._mongocryptd_spawn_path or "mongocryptd"]
args.extend(self.opts._mongocryptd_spawn_args)
_spawn_daemon(args)
def mark_command(self, database, cmd):
"""Mark a command for encryption.
:Parameters:
- `database`: The database on which to run this command.
- `cmd`: The BSON command to run.
:Returns:
The marked command response from mongocryptd.
"""
if not self._spawned and not self.opts._mongocryptd_bypass_spawn:
self.spawn()
# Database.command only supports mutable mappings so we need to decode
# the raw BSON command first.
inflated_cmd = _inflate_bson(cmd, DEFAULT_RAW_BSON_OPTIONS)
try:
res = self.mongocryptd_client[database].command(
inflated_cmd, codec_options=DEFAULT_RAW_BSON_OPTIONS
)
except ServerSelectionTimeoutError:
if self.opts._mongocryptd_bypass_spawn:
raise
self.spawn()
res = self.mongocryptd_client[database].command(
inflated_cmd, codec_options=DEFAULT_RAW_BSON_OPTIONS
)
return res.raw
def fetch_keys(self, filter):
"""Yields one or more keys from the key vault.
:Parameters:
- `filter`: The filter to pass to find.
:Returns:
A generator which yields the requested keys from the key vault.
"""
with self.key_vault_coll.find(RawBSONDocument(filter)) as cursor:
for key in cursor:
yield key.raw
def insert_data_key(self, data_key):
"""Insert a data key into the key vault.
:Parameters:
- `data_key`: The data key document to insert.
:Returns:
The _id of the inserted data key document.
"""
raw_doc = RawBSONDocument(data_key, _KEY_VAULT_OPTS)
data_key_id = raw_doc.get("_id")
if not isinstance(data_key_id, uuid.UUID):
raise TypeError("data_key _id must be a UUID")
self.key_vault_coll.insert_one(raw_doc)
return Binary(data_key_id.bytes, subtype=UUID_SUBTYPE)
def bson_encode(self, doc):
"""Encode a document to BSON.
A document can be any mapping type (like :class:`dict`).
:Parameters:
- `doc`: mapping type representing a document
:Returns:
The encoded BSON bytes.
"""
return encode(doc)
def close(self):
"""Release resources.
Note it is not safe to call this method from __del__ or any GC hooks.
"""
self.client_ref = None
self.key_vault_coll = None
if self.mongocryptd_client:
self.mongocryptd_client.close()
self.mongocryptd_client = None
class _Encrypter(object):
"""Encrypts and decrypts MongoDB commands.
This class is used to support automatic encryption and decryption of
MongoDB commands."""
def __init__(self, client, opts):
"""Create a _Encrypter for a client.
:Parameters:
- `client`: The encrypted MongoClient.
- `opts`: The encrypted client's :class:`AutoEncryptionOpts`.
"""
if opts._schema_map is None:
schema_map = None
else:
schema_map = _dict_to_bson(opts._schema_map, False, _DATA_KEY_OPTS)
if opts._encrypted_fields_map is None:
encrypted_fields_map = None
else:
encrypted_fields_map = _dict_to_bson(opts._encrypted_fields_map, False, _DATA_KEY_OPTS)
self._bypass_auto_encryption = opts._bypass_auto_encryption
self._internal_client = None
def _get_internal_client(encrypter, mongo_client):
if mongo_client.options.pool_options.max_pool_size is None:
# Unlimited pool size, use the same client.
return mongo_client
# Else - limited pool size, use an internal client.
if encrypter._internal_client is not None:
return encrypter._internal_client
internal_client = mongo_client._duplicate(minPoolSize=0, auto_encryption_opts=None)
encrypter._internal_client = internal_client
return internal_client
if opts._key_vault_client is not None:
key_vault_client = opts._key_vault_client
else:
key_vault_client = _get_internal_client(self, client)
if opts._bypass_auto_encryption:
metadata_client = None
else:
metadata_client = _get_internal_client(self, client)
db, coll = opts._key_vault_namespace.split(".", 1)
key_vault_coll = key_vault_client[db][coll]
mongocryptd_client: MongoClient = MongoClient(
opts._mongocryptd_uri, connect=False, serverSelectionTimeoutMS=_MONGOCRYPTD_TIMEOUT_MS
)
io_callbacks = _EncryptionIO(metadata_client, key_vault_coll, mongocryptd_client, opts)
self._auto_encrypter = AutoEncrypter(
io_callbacks,
MongoCryptOptions(
opts._kms_providers,
schema_map,
crypt_shared_lib_path=opts._crypt_shared_lib_path,
crypt_shared_lib_required=opts._crypt_shared_lib_required,
bypass_encryption=opts._bypass_auto_encryption,
encrypted_fields_map=encrypted_fields_map,
bypass_query_analysis=opts._bypass_query_analysis,
),
)
self._closed = False
def encrypt(self, database, cmd, codec_options):
"""Encrypt a MongoDB command.
:Parameters:
- `database`: The database for this command.
- `cmd`: A command document.
- `codec_options`: The CodecOptions to use while encoding `cmd`.
:Returns:
The encrypted command to execute.
"""
self._check_closed()
encoded_cmd = _dict_to_bson(cmd, False, codec_options)
with _wrap_encryption_errors():
encrypted_cmd = self._auto_encrypter.encrypt(database, encoded_cmd)
# TODO: PYTHON-1922 avoid decoding the encrypted_cmd.
encrypt_cmd = _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS)
return encrypt_cmd
def decrypt(self, response):
"""Decrypt a MongoDB command response.
:Parameters:
- `response`: A MongoDB command response as BSON.
:Returns:
The decrypted command response.
"""
self._check_closed()
with _wrap_encryption_errors():
return self._auto_encrypter.decrypt(response)
def _check_closed(self):
if self._closed:
raise InvalidOperation("Cannot use MongoClient after close")
def close(self):
"""Cleanup resources."""
self._closed = True
self._auto_encrypter.close()
if self._internal_client:
self._internal_client.close()
self._internal_client = None
class Algorithm(str, enum.Enum):
"""An enum that defines the supported encryption algorithms."""
AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
"""AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic."""
AEAD_AES_256_CBC_HMAC_SHA_512_Random = "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
"""AEAD_AES_256_CBC_HMAC_SHA_512_Random."""
INDEXED = "Indexed"
"""Indexed.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
UNINDEXED = "Unindexed"
"""Unindexed.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
class QueryType(enum.IntEnum):
"""**(BETA)** An enum that defines the supported values for explicit encryption query_type.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
EQUALITY = 1
"""Used to encrypt a value for an equality query."""
class ClientEncryption(object):
"""Explicit client-side field level encryption."""
def __init__(
self,
kms_providers: Mapping[str, Any],
key_vault_namespace: str,
key_vault_client: MongoClient,
codec_options: CodecOptions,
kms_tls_options: Optional[Mapping[str, Any]] = None,
) -> None:
"""Explicit client-side field level encryption.
The ClientEncryption class encapsulates explicit operations on a key
vault collection that cannot be done directly on a MongoClient. Similar
to configuring auto encryption on a MongoClient, it is constructed with
a MongoClient (to a MongoDB cluster containing the key vault
collection), KMS provider configuration, and keyVaultNamespace. It
provides an API for explicitly encrypting and decrypting values, and
creating data keys. It does not provide an API to query keys from the
key vault collection, as this can be done directly on the MongoClient.
See :ref:`explicit-client-side-encryption` for an example.
:Parameters:
- `kms_providers`: Map of KMS provider options. The `kms_providers`
map values differ by provider:
- `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
These are the AWS access key ID and AWS secret access key used
to generate KMS messages. An optional "sessionToken" may be
included to support temporary AWS credentials.
- `azure`: Map with "tenantId", "clientId", and "clientSecret" as
strings. Additionally, "identityPlatformEndpoint" may also be
specified as a string (defaults to 'login.microsoftonline.com').
These are the Azure Active Directory credentials used to
generate Azure Key Vault messages.
- `gcp`: Map with "email" as a string and "privateKey"
as `bytes` or a base64 encoded string.
Additionally, "endpoint" may also be specified as a string
(defaults to 'oauth2.googleapis.com'). These are the
credentials used to generate Google Cloud KMS messages.
- `kmip`: Map with "endpoint" as a host with required port.
For example: ``{"endpoint": "example.com:443"}``.
- `local`: Map with "key" as `bytes` (96 bytes in length) or
a base64 encoded string which decodes
to 96 bytes. "key" is the master key used to encrypt/decrypt
data keys. This key should be generated and stored as securely
as possible.
- `key_vault_namespace`: The namespace for the key vault collection.
The key vault collection contains all data keys used for encryption
and decryption. Data keys are stored as documents in this MongoDB
collection. Data keys are protected with encryption by a KMS
provider.
- `key_vault_client`: A MongoClient connected to a MongoDB cluster
containing the `key_vault_namespace` collection.
- `codec_options`: An instance of
:class:`~bson.codec_options.CodecOptions` to use when encoding a
value for encryption and decoding the decrypted BSON value. This
should be the same CodecOptions instance configured on the
MongoClient, Database, or Collection used to access application
data.
- `kms_tls_options` (optional): A map of KMS provider names to TLS
options to use when creating secure connections to KMS providers.
Accepts the same TLS options as
:class:`pymongo.mongo_client.MongoClient`. For example, to
override the system default CA file::
kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}}
Or to supply a client certificate::
kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}
.. versionchanged:: 4.0
Added the `kms_tls_options` parameter and the "kmip" KMS provider.
.. versionadded:: 3.9
"""
if not _HAVE_PYMONGOCRYPT:
raise ConfigurationError(
"client-side field level encryption requires the pymongocrypt "
"library: install a compatible version with: "
"python -m pip install 'pymongo[encryption]'"
)
if not isinstance(codec_options, CodecOptions):
raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions")
self._kms_providers = kms_providers
self._key_vault_namespace = key_vault_namespace
self._key_vault_client = key_vault_client
self._codec_options = codec_options
db, coll = key_vault_namespace.split(".", 1)
key_vault_coll = key_vault_client[db][coll]
opts = AutoEncryptionOpts(
kms_providers, key_vault_namespace, kms_tls_options=kms_tls_options
)
self._io_callbacks: Optional[_EncryptionIO] = _EncryptionIO(
None, key_vault_coll, None, opts
)
self._encryption = ExplicitEncrypter(
self._io_callbacks, MongoCryptOptions(kms_providers, None)
)
def create_data_key(
self,
kms_provider: str,
master_key: Optional[Mapping[str, Any]] = None,
key_alt_names: Optional[Sequence[str]] = None,
) -> Binary:
"""Create and insert a new data key into the key vault collection.
:Parameters:
- `kms_provider`: The KMS provider to use. Supported values are
"aws", "azure", "gcp", "kmip", and "local".
- `master_key`: Identifies a KMS-specific key used to encrypt the
new data key. If the kmsProvider is "local" the `master_key` is
not applicable and may be omitted.
If the `kms_provider` is "aws" it is required and has the
following fields::
- `region` (string): Required. The AWS region, e.g. "us-east-1".
- `key` (string): Required. The Amazon Resource Name (ARN) to
the AWS customer.
- `endpoint` (string): Optional. An alternate host to send KMS
requests to. May include port number, e.g.
"kms.us-east-1.amazonaws.com:443".
If the `kms_provider` is "azure" it is required and has the
following fields::
- `keyVaultEndpoint` (string): Required. Host with optional
port, e.g. "example.vault.azure.net".
- `keyName` (string): Required. Key name in the key vault.
- `keyVersion` (string): Optional. Version of the key to use.
If the `kms_provider` is "gcp" it is required and has the
following fields::
- `projectId` (string): Required. The Google cloud project ID.
- `location` (string): Required. The GCP location, e.g. "us-east1".
- `keyRing` (string): Required. Name of the key ring that contains
the key to use.
- `keyName` (string): Required. Name of the key to use.
- `keyVersion` (string): Optional. Version of the key to use.
- `endpoint` (string): Optional. Host with optional port.
Defaults to "cloudkms.googleapis.com".
If the `kms_provider` is "kmip" it is optional and has the
following fields::
- `keyId` (string): Optional. `keyId` is the KMIP Unique
Identifier to a 96 byte KMIP Secret Data managed object. If
keyId is omitted, the driver creates a random 96 byte KMIP
Secret Data managed object.
- `endpoint` (string): Optional. Host with optional
port, e.g. "example.vault.azure.net:".
- `key_alt_names` (optional): An optional list of string alternate
names used to reference a key. If a key is created with alternate
names, then encryption may refer to the key by the unique alternate
name instead of by ``key_id``. The following example shows creating
and referring to a data key by alternate name::
client_encryption.create_data_key("local", keyAltNames=["name1"])
# reference the key with the alternate name
client_encryption.encrypt("457-55-5462", keyAltName="name1",
algorithm=Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random)
:Returns:
The ``_id`` of the created data key document as a
:class:`~bson.binary.Binary` with subtype
:data:`~bson.binary.UUID_SUBTYPE`.
"""
self._check_closed()
with _wrap_encryption_errors():
return self._encryption.create_data_key(
kms_provider, master_key=master_key, key_alt_names=key_alt_names
)
def encrypt(
self,
value: Any,
algorithm: str,
key_id: Optional[Binary] = None,
key_alt_name: Optional[str] = None,
index_key_id: Optional[Binary] = None,
query_type: Optional[int] = None,
contention_factor: Optional[int] = None,
) -> Binary:
"""Encrypt a BSON value with a given key and algorithm.
Note that exactly one of ``key_id`` or ``key_alt_name`` must be
provided.
:Parameters:
- `value`: The BSON value to encrypt.
- `algorithm` (string): The encryption algorithm to use. See
:class:`Algorithm` for some valid options.
- `key_id`: Identifies a data key by ``_id`` which must be a
:class:`~bson.binary.Binary` with subtype 4 (
:attr:`~bson.binary.UUID_SUBTYPE`).
- `key_alt_name`: Identifies a key vault document by 'keyAltName'.
- `index_key_id`: **(BETA)** The index key id to use for Queryable Encryption. Must be
a :class:`~bson.binary.Binary` with subtype 4 (:attr:`~bson.binary.UUID_SUBTYPE`).
- `query_type` (int): **(BETA)** The query type to execute. See
:class:`QueryType` for valid options.
- `contention_factor` (int): **(BETA)** The contention factor to use
when the algorithm is :attr:`Algorithm.INDEXED`.
.. note:: `index_key_id`, `query_type`, and `contention_factor` are part of the
Queryable Encryption beta. Backwards-breaking changes may be made before the
final release.
:Returns:
The encrypted value, a :class:`~bson.binary.Binary` with subtype 6.
.. versionchanged:: 4.2
Added the `index_key_id`, `query_type`, and `contention_factor` parameters.
"""
self._check_closed()
if key_id is not None and not (
isinstance(key_id, Binary) and key_id.subtype == UUID_SUBTYPE
):
raise TypeError("key_id must be a bson.binary.Binary with subtype 4")
if index_key_id is not None and not (
isinstance(index_key_id, Binary) and index_key_id.subtype == UUID_SUBTYPE
):
raise TypeError("index_key_id must be a bson.binary.Binary with subtype 4")
doc = encode({"v": value}, codec_options=self._codec_options)
with _wrap_encryption_errors():
encrypted_doc = self._encryption.encrypt(
doc,
algorithm,
key_id=key_id,
key_alt_name=key_alt_name,
index_key_id=index_key_id,
query_type=query_type,
contention_factor=contention_factor,
)
return decode(encrypted_doc)["v"] # type: ignore[index]
def decrypt(self, value: Binary) -> Any:
"""Decrypt an encrypted value.
:Parameters:
- `value` (Binary): The encrypted value, a
:class:`~bson.binary.Binary` with subtype 6.
:Returns:
The decrypted BSON value.
"""
self._check_closed()
if not (isinstance(value, Binary) and value.subtype == 6):
raise TypeError("value to decrypt must be a bson.binary.Binary with subtype 6")
with _wrap_encryption_errors():
doc = encode({"v": value})
decrypted_doc = self._encryption.decrypt(doc)
return decode(decrypted_doc, codec_options=self._codec_options)["v"]
def __enter__(self) -> "ClientEncryption":
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.close()
def _check_closed(self):
if self._encryption is None:
raise InvalidOperation("Cannot use closed ClientEncryption")
def close(self) -> None:
"""Release resources.
Note that using this class in a with-statement will automatically call
:meth:`close`::
with ClientEncryption(...) as client_encryption:
encrypted = client_encryption.encrypt(value, ...)
decrypted = client_encryption.decrypt(encrypted)
"""
if self._io_callbacks:
self._io_callbacks.close()
self._encryption.close()
self._io_callbacks = None
self._encryption = None | pymongo/encryption.py | import contextlib
import enum
import socket
import uuid
import weakref
from typing import Any, Mapping, Optional, Sequence
try:
from pymongocrypt.auto_encrypter import AutoEncrypter
from pymongocrypt.errors import MongoCryptError # noqa: F401
from pymongocrypt.explicit_encrypter import ExplicitEncrypter
from pymongocrypt.mongocrypt import MongoCryptOptions
from pymongocrypt.state_machine import MongoCryptCallback
_HAVE_PYMONGOCRYPT = True
except ImportError:
_HAVE_PYMONGOCRYPT = False
MongoCryptCallback = object
from bson import _dict_to_bson, decode, encode
from bson.binary import STANDARD, UUID_SUBTYPE, Binary
from bson.codec_options import CodecOptions
from bson.errors import BSONError
from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson
from bson.son import SON
from pymongo import _csot
from pymongo.daemon import _spawn_daemon
from pymongo.encryption_options import AutoEncryptionOpts
from pymongo.errors import (
ConfigurationError,
EncryptionError,
InvalidOperation,
ServerSelectionTimeoutError,
)
from pymongo.mongo_client import MongoClient
from pymongo.network import BLOCKING_IO_ERRORS
from pymongo.pool import PoolOptions, _configured_socket
from pymongo.read_concern import ReadConcern
from pymongo.ssl_support import get_ssl_context
from pymongo.uri_parser import parse_host
from pymongo.write_concern import WriteConcern
_HTTPS_PORT = 443
_KMS_CONNECT_TIMEOUT = 10 # TODO: CDRIVER-3262 will define this value.
_MONGOCRYPTD_TIMEOUT_MS = 10000
_DATA_KEY_OPTS: CodecOptions = CodecOptions(document_class=SON, uuid_representation=STANDARD)
# Use RawBSONDocument codec options to avoid needlessly decoding
# documents from the key vault.
_KEY_VAULT_OPTS = CodecOptions(document_class=RawBSONDocument, uuid_representation=STANDARD)
@contextlib.contextmanager
def _wrap_encryption_errors():
"""Context manager to wrap encryption related errors."""
try:
yield
except BSONError:
# BSON encoding/decoding errors are unrelated to encryption so
# we should propagate them unchanged.
raise
except Exception as exc:
raise EncryptionError(exc)
class _EncryptionIO(MongoCryptCallback): # type: ignore
def __init__(self, client, key_vault_coll, mongocryptd_client, opts):
"""Internal class to perform I/O on behalf of pymongocrypt."""
self.client_ref: Any
# Use a weak ref to break reference cycle.
if client is not None:
self.client_ref = weakref.ref(client)
else:
self.client_ref = None
self.key_vault_coll = key_vault_coll.with_options(
codec_options=_KEY_VAULT_OPTS,
read_concern=ReadConcern(level="majority"),
write_concern=WriteConcern(w="majority"),
)
self.mongocryptd_client = mongocryptd_client
self.opts = opts
self._spawned = False
def kms_request(self, kms_context):
"""Complete a KMS request.
:Parameters:
- `kms_context`: A :class:`MongoCryptKmsContext`.
:Returns:
None
"""
endpoint = kms_context.endpoint
message = kms_context.message
provider = kms_context.kms_provider
ctx = self.opts._kms_ssl_contexts.get(provider)
if ctx is None:
# Enable strict certificate verification, OCSP, match hostname, and
# SNI using the system default CA certificates.
ctx = get_ssl_context(
None, # certfile
None, # passphrase
None, # ca_certs
None, # crlfile
False, # allow_invalid_certificates
False, # allow_invalid_hostnames
False,
) # disable_ocsp_endpoint_check
# CSOT: set timeout for socket creation.
connect_timeout = max(_csot.clamp_remaining(_KMS_CONNECT_TIMEOUT), 0.001)
opts = PoolOptions(
connect_timeout=connect_timeout,
socket_timeout=connect_timeout,
ssl_context=ctx,
)
host, port = parse_host(endpoint, _HTTPS_PORT)
conn = _configured_socket((host, port), opts)
try:
conn.sendall(message)
while kms_context.bytes_needed > 0:
# CSOT: update timeout.
conn.settimeout(max(_csot.clamp_remaining(_KMS_CONNECT_TIMEOUT), 0))
data = conn.recv(kms_context.bytes_needed)
if not data:
raise OSError("KMS connection closed")
kms_context.feed(data)
except BLOCKING_IO_ERRORS:
raise socket.timeout("timed out")
finally:
conn.close()
def collection_info(self, database, filter):
"""Get the collection info for a namespace.
The returned collection info is passed to libmongocrypt which reads
the JSON schema.
:Parameters:
- `database`: The database on which to run listCollections.
- `filter`: The filter to pass to listCollections.
:Returns:
The first document from the listCollections command response as BSON.
"""
with self.client_ref()[database].list_collections(filter=RawBSONDocument(filter)) as cursor:
for doc in cursor:
return _dict_to_bson(doc, False, _DATA_KEY_OPTS)
def spawn(self):
"""Spawn mongocryptd.
Note this method is thread safe; at most one mongocryptd will start
successfully.
"""
self._spawned = True
args = [self.opts._mongocryptd_spawn_path or "mongocryptd"]
args.extend(self.opts._mongocryptd_spawn_args)
_spawn_daemon(args)
def mark_command(self, database, cmd):
"""Mark a command for encryption.
:Parameters:
- `database`: The database on which to run this command.
- `cmd`: The BSON command to run.
:Returns:
The marked command response from mongocryptd.
"""
if not self._spawned and not self.opts._mongocryptd_bypass_spawn:
self.spawn()
# Database.command only supports mutable mappings so we need to decode
# the raw BSON command first.
inflated_cmd = _inflate_bson(cmd, DEFAULT_RAW_BSON_OPTIONS)
try:
res = self.mongocryptd_client[database].command(
inflated_cmd, codec_options=DEFAULT_RAW_BSON_OPTIONS
)
except ServerSelectionTimeoutError:
if self.opts._mongocryptd_bypass_spawn:
raise
self.spawn()
res = self.mongocryptd_client[database].command(
inflated_cmd, codec_options=DEFAULT_RAW_BSON_OPTIONS
)
return res.raw
def fetch_keys(self, filter):
"""Yields one or more keys from the key vault.
:Parameters:
- `filter`: The filter to pass to find.
:Returns:
A generator which yields the requested keys from the key vault.
"""
with self.key_vault_coll.find(RawBSONDocument(filter)) as cursor:
for key in cursor:
yield key.raw
def insert_data_key(self, data_key):
"""Insert a data key into the key vault.
:Parameters:
- `data_key`: The data key document to insert.
:Returns:
The _id of the inserted data key document.
"""
raw_doc = RawBSONDocument(data_key, _KEY_VAULT_OPTS)
data_key_id = raw_doc.get("_id")
if not isinstance(data_key_id, uuid.UUID):
raise TypeError("data_key _id must be a UUID")
self.key_vault_coll.insert_one(raw_doc)
return Binary(data_key_id.bytes, subtype=UUID_SUBTYPE)
def bson_encode(self, doc):
"""Encode a document to BSON.
A document can be any mapping type (like :class:`dict`).
:Parameters:
- `doc`: mapping type representing a document
:Returns:
The encoded BSON bytes.
"""
return encode(doc)
def close(self):
"""Release resources.
Note it is not safe to call this method from __del__ or any GC hooks.
"""
self.client_ref = None
self.key_vault_coll = None
if self.mongocryptd_client:
self.mongocryptd_client.close()
self.mongocryptd_client = None
class _Encrypter(object):
"""Encrypts and decrypts MongoDB commands.
This class is used to support automatic encryption and decryption of
MongoDB commands."""
def __init__(self, client, opts):
"""Create a _Encrypter for a client.
:Parameters:
- `client`: The encrypted MongoClient.
- `opts`: The encrypted client's :class:`AutoEncryptionOpts`.
"""
if opts._schema_map is None:
schema_map = None
else:
schema_map = _dict_to_bson(opts._schema_map, False, _DATA_KEY_OPTS)
if opts._encrypted_fields_map is None:
encrypted_fields_map = None
else:
encrypted_fields_map = _dict_to_bson(opts._encrypted_fields_map, False, _DATA_KEY_OPTS)
self._bypass_auto_encryption = opts._bypass_auto_encryption
self._internal_client = None
def _get_internal_client(encrypter, mongo_client):
if mongo_client.options.pool_options.max_pool_size is None:
# Unlimited pool size, use the same client.
return mongo_client
# Else - limited pool size, use an internal client.
if encrypter._internal_client is not None:
return encrypter._internal_client
internal_client = mongo_client._duplicate(minPoolSize=0, auto_encryption_opts=None)
encrypter._internal_client = internal_client
return internal_client
if opts._key_vault_client is not None:
key_vault_client = opts._key_vault_client
else:
key_vault_client = _get_internal_client(self, client)
if opts._bypass_auto_encryption:
metadata_client = None
else:
metadata_client = _get_internal_client(self, client)
db, coll = opts._key_vault_namespace.split(".", 1)
key_vault_coll = key_vault_client[db][coll]
mongocryptd_client: MongoClient = MongoClient(
opts._mongocryptd_uri, connect=False, serverSelectionTimeoutMS=_MONGOCRYPTD_TIMEOUT_MS
)
io_callbacks = _EncryptionIO(metadata_client, key_vault_coll, mongocryptd_client, opts)
self._auto_encrypter = AutoEncrypter(
io_callbacks,
MongoCryptOptions(
opts._kms_providers,
schema_map,
crypt_shared_lib_path=opts._crypt_shared_lib_path,
crypt_shared_lib_required=opts._crypt_shared_lib_required,
bypass_encryption=opts._bypass_auto_encryption,
encrypted_fields_map=encrypted_fields_map,
bypass_query_analysis=opts._bypass_query_analysis,
),
)
self._closed = False
def encrypt(self, database, cmd, codec_options):
"""Encrypt a MongoDB command.
:Parameters:
- `database`: The database for this command.
- `cmd`: A command document.
- `codec_options`: The CodecOptions to use while encoding `cmd`.
:Returns:
The encrypted command to execute.
"""
self._check_closed()
encoded_cmd = _dict_to_bson(cmd, False, codec_options)
with _wrap_encryption_errors():
encrypted_cmd = self._auto_encrypter.encrypt(database, encoded_cmd)
# TODO: PYTHON-1922 avoid decoding the encrypted_cmd.
encrypt_cmd = _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS)
return encrypt_cmd
def decrypt(self, response):
"""Decrypt a MongoDB command response.
:Parameters:
- `response`: A MongoDB command response as BSON.
:Returns:
The decrypted command response.
"""
self._check_closed()
with _wrap_encryption_errors():
return self._auto_encrypter.decrypt(response)
def _check_closed(self):
if self._closed:
raise InvalidOperation("Cannot use MongoClient after close")
def close(self):
"""Cleanup resources."""
self._closed = True
self._auto_encrypter.close()
if self._internal_client:
self._internal_client.close()
self._internal_client = None
class Algorithm(str, enum.Enum):
"""An enum that defines the supported encryption algorithms."""
AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
"""AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic."""
AEAD_AES_256_CBC_HMAC_SHA_512_Random = "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
"""AEAD_AES_256_CBC_HMAC_SHA_512_Random."""
INDEXED = "Indexed"
"""Indexed.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
UNINDEXED = "Unindexed"
"""Unindexed.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
class QueryType(enum.IntEnum):
"""**(BETA)** An enum that defines the supported values for explicit encryption query_type.
.. note:: Support for Queryable Encryption is in beta.
Backwards-breaking changes may be made before the final release.
.. versionadded:: 4.2
"""
EQUALITY = 1
"""Used to encrypt a value for an equality query."""
class ClientEncryption(object):
"""Explicit client-side field level encryption."""
def __init__(
self,
kms_providers: Mapping[str, Any],
key_vault_namespace: str,
key_vault_client: MongoClient,
codec_options: CodecOptions,
kms_tls_options: Optional[Mapping[str, Any]] = None,
) -> None:
"""Explicit client-side field level encryption.
The ClientEncryption class encapsulates explicit operations on a key
vault collection that cannot be done directly on a MongoClient. Similar
to configuring auto encryption on a MongoClient, it is constructed with
a MongoClient (to a MongoDB cluster containing the key vault
collection), KMS provider configuration, and keyVaultNamespace. It
provides an API for explicitly encrypting and decrypting values, and
creating data keys. It does not provide an API to query keys from the
key vault collection, as this can be done directly on the MongoClient.
See :ref:`explicit-client-side-encryption` for an example.
:Parameters:
- `kms_providers`: Map of KMS provider options. The `kms_providers`
map values differ by provider:
- `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
These are the AWS access key ID and AWS secret access key used
to generate KMS messages. An optional "sessionToken" may be
included to support temporary AWS credentials.
- `azure`: Map with "tenantId", "clientId", and "clientSecret" as
strings. Additionally, "identityPlatformEndpoint" may also be
specified as a string (defaults to 'login.microsoftonline.com').
These are the Azure Active Directory credentials used to
generate Azure Key Vault messages.
- `gcp`: Map with "email" as a string and "privateKey"
as `bytes` or a base64 encoded string.
Additionally, "endpoint" may also be specified as a string
(defaults to 'oauth2.googleapis.com'). These are the
credentials used to generate Google Cloud KMS messages.
- `kmip`: Map with "endpoint" as a host with required port.
For example: ``{"endpoint": "example.com:443"}``.
- `local`: Map with "key" as `bytes` (96 bytes in length) or
a base64 encoded string which decodes
to 96 bytes. "key" is the master key used to encrypt/decrypt
data keys. This key should be generated and stored as securely
as possible.
- `key_vault_namespace`: The namespace for the key vault collection.
The key vault collection contains all data keys used for encryption
and decryption. Data keys are stored as documents in this MongoDB
collection. Data keys are protected with encryption by a KMS
provider.
- `key_vault_client`: A MongoClient connected to a MongoDB cluster
containing the `key_vault_namespace` collection.
- `codec_options`: An instance of
:class:`~bson.codec_options.CodecOptions` to use when encoding a
value for encryption and decoding the decrypted BSON value. This
should be the same CodecOptions instance configured on the
MongoClient, Database, or Collection used to access application
data.
- `kms_tls_options` (optional): A map of KMS provider names to TLS
options to use when creating secure connections to KMS providers.
Accepts the same TLS options as
:class:`pymongo.mongo_client.MongoClient`. For example, to
override the system default CA file::
kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}}
Or to supply a client certificate::
kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}
.. versionchanged:: 4.0
Added the `kms_tls_options` parameter and the "kmip" KMS provider.
.. versionadded:: 3.9
"""
if not _HAVE_PYMONGOCRYPT:
raise ConfigurationError(
"client-side field level encryption requires the pymongocrypt "
"library: install a compatible version with: "
"python -m pip install 'pymongo[encryption]'"
)
if not isinstance(codec_options, CodecOptions):
raise TypeError("codec_options must be an instance of bson.codec_options.CodecOptions")
self._kms_providers = kms_providers
self._key_vault_namespace = key_vault_namespace
self._key_vault_client = key_vault_client
self._codec_options = codec_options
db, coll = key_vault_namespace.split(".", 1)
key_vault_coll = key_vault_client[db][coll]
opts = AutoEncryptionOpts(
kms_providers, key_vault_namespace, kms_tls_options=kms_tls_options
)
self._io_callbacks: Optional[_EncryptionIO] = _EncryptionIO(
None, key_vault_coll, None, opts
)
self._encryption = ExplicitEncrypter(
self._io_callbacks, MongoCryptOptions(kms_providers, None)
)
def create_data_key(
self,
kms_provider: str,
master_key: Optional[Mapping[str, Any]] = None,
key_alt_names: Optional[Sequence[str]] = None,
) -> Binary:
"""Create and insert a new data key into the key vault collection.
:Parameters:
- `kms_provider`: The KMS provider to use. Supported values are
"aws", "azure", "gcp", "kmip", and "local".
- `master_key`: Identifies a KMS-specific key used to encrypt the
new data key. If the kmsProvider is "local" the `master_key` is
not applicable and may be omitted.
If the `kms_provider` is "aws" it is required and has the
following fields::
- `region` (string): Required. The AWS region, e.g. "us-east-1".
- `key` (string): Required. The Amazon Resource Name (ARN) to
the AWS customer.
- `endpoint` (string): Optional. An alternate host to send KMS
requests to. May include port number, e.g.
"kms.us-east-1.amazonaws.com:443".
If the `kms_provider` is "azure" it is required and has the
following fields::
- `keyVaultEndpoint` (string): Required. Host with optional
port, e.g. "example.vault.azure.net".
- `keyName` (string): Required. Key name in the key vault.
- `keyVersion` (string): Optional. Version of the key to use.
If the `kms_provider` is "gcp" it is required and has the
following fields::
- `projectId` (string): Required. The Google cloud project ID.
- `location` (string): Required. The GCP location, e.g. "us-east1".
- `keyRing` (string): Required. Name of the key ring that contains
the key to use.
- `keyName` (string): Required. Name of the key to use.
- `keyVersion` (string): Optional. Version of the key to use.
- `endpoint` (string): Optional. Host with optional port.
Defaults to "cloudkms.googleapis.com".
If the `kms_provider` is "kmip" it is optional and has the
following fields::
- `keyId` (string): Optional. `keyId` is the KMIP Unique
Identifier to a 96 byte KMIP Secret Data managed object. If
keyId is omitted, the driver creates a random 96 byte KMIP
Secret Data managed object.
- `endpoint` (string): Optional. Host with optional
port, e.g. "example.vault.azure.net:".
- `key_alt_names` (optional): An optional list of string alternate
names used to reference a key. If a key is created with alternate
names, then encryption may refer to the key by the unique alternate
name instead of by ``key_id``. The following example shows creating
and referring to a data key by alternate name::
client_encryption.create_data_key("local", keyAltNames=["name1"])
# reference the key with the alternate name
client_encryption.encrypt("457-55-5462", keyAltName="name1",
algorithm=Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random)
:Returns:
The ``_id`` of the created data key document as a
:class:`~bson.binary.Binary` with subtype
:data:`~bson.binary.UUID_SUBTYPE`.
"""
self._check_closed()
with _wrap_encryption_errors():
return self._encryption.create_data_key(
kms_provider, master_key=master_key, key_alt_names=key_alt_names
)
def encrypt(
self,
value: Any,
algorithm: str,
key_id: Optional[Binary] = None,
key_alt_name: Optional[str] = None,
index_key_id: Optional[Binary] = None,
query_type: Optional[int] = None,
contention_factor: Optional[int] = None,
) -> Binary:
"""Encrypt a BSON value with a given key and algorithm.
Note that exactly one of ``key_id`` or ``key_alt_name`` must be
provided.
:Parameters:
- `value`: The BSON value to encrypt.
- `algorithm` (string): The encryption algorithm to use. See
:class:`Algorithm` for some valid options.
- `key_id`: Identifies a data key by ``_id`` which must be a
:class:`~bson.binary.Binary` with subtype 4 (
:attr:`~bson.binary.UUID_SUBTYPE`).
- `key_alt_name`: Identifies a key vault document by 'keyAltName'.
- `index_key_id`: **(BETA)** The index key id to use for Queryable Encryption. Must be
a :class:`~bson.binary.Binary` with subtype 4 (:attr:`~bson.binary.UUID_SUBTYPE`).
- `query_type` (int): **(BETA)** The query type to execute. See
:class:`QueryType` for valid options.
- `contention_factor` (int): **(BETA)** The contention factor to use
when the algorithm is :attr:`Algorithm.INDEXED`.
.. note:: `index_key_id`, `query_type`, and `contention_factor` are part of the
Queryable Encryption beta. Backwards-breaking changes may be made before the
final release.
:Returns:
The encrypted value, a :class:`~bson.binary.Binary` with subtype 6.
.. versionchanged:: 4.2
Added the `index_key_id`, `query_type`, and `contention_factor` parameters.
"""
self._check_closed()
if key_id is not None and not (
isinstance(key_id, Binary) and key_id.subtype == UUID_SUBTYPE
):
raise TypeError("key_id must be a bson.binary.Binary with subtype 4")
if index_key_id is not None and not (
isinstance(index_key_id, Binary) and index_key_id.subtype == UUID_SUBTYPE
):
raise TypeError("index_key_id must be a bson.binary.Binary with subtype 4")
doc = encode({"v": value}, codec_options=self._codec_options)
with _wrap_encryption_errors():
encrypted_doc = self._encryption.encrypt(
doc,
algorithm,
key_id=key_id,
key_alt_name=key_alt_name,
index_key_id=index_key_id,
query_type=query_type,
contention_factor=contention_factor,
)
return decode(encrypted_doc)["v"] # type: ignore[index]
def decrypt(self, value: Binary) -> Any:
"""Decrypt an encrypted value.
:Parameters:
- `value` (Binary): The encrypted value, a
:class:`~bson.binary.Binary` with subtype 6.
:Returns:
The decrypted BSON value.
"""
self._check_closed()
if not (isinstance(value, Binary) and value.subtype == 6):
raise TypeError("value to decrypt must be a bson.binary.Binary with subtype 6")
with _wrap_encryption_errors():
doc = encode({"v": value})
decrypted_doc = self._encryption.decrypt(doc)
return decode(decrypted_doc, codec_options=self._codec_options)["v"]
def __enter__(self) -> "ClientEncryption":
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.close()
def _check_closed(self):
if self._encryption is None:
raise InvalidOperation("Cannot use closed ClientEncryption")
def close(self) -> None:
"""Release resources.
Note that using this class in a with-statement will automatically call
:meth:`close`::
with ClientEncryption(...) as client_encryption:
encrypted = client_encryption.encrypt(value, ...)
decrypted = client_encryption.decrypt(encrypted)
"""
if self._io_callbacks:
self._io_callbacks.close()
self._encryption.close()
self._io_callbacks = None
self._encryption = None | 0.749821 | 0.099602 |
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Traditional Chinese language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
'attention (translation required)': 'attention',
'caution (translation required)': 'caution',
'danger (translation required)': 'danger',
'error (translation required)': 'error',
'hint (translation required)': 'hint',
'important (translation required)': 'important',
'note (translation required)': 'note',
'tip (translation required)': 'tip',
'warning (translation required)': 'warning',
'admonition (translation required)': 'admonition',
'sidebar (translation required)': 'sidebar',
'topic (translation required)': 'topic',
'line-block (translation required)': 'line-block',
'parsed-literal (translation required)': 'parsed-literal',
'rubric (translation required)': 'rubric',
'epigraph (translation required)': 'epigraph',
'highlights (translation required)': 'highlights',
'pull-quote (translation required)': 'pull-quote',
'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#'questions (translation required)': 'questions',
'table (translation required)': 'table',
'csv-table (translation required)': 'csv-table',
'list-table (translation required)': 'list-table',
#'qa (translation required)': 'questions',
#'faq (translation required)': 'questions',
'meta (translation required)': 'meta',
#'imagemap (translation required)': 'imagemap',
'image (translation required)': 'image',
'figure (translation required)': 'figure',
'include (translation required)': 'include',
'raw (translation required)': 'raw',
'replace (translation required)': 'replace',
'unicode (translation required)': 'unicode',
u'日期': 'date',
'class (translation required)': 'class',
'role (translation required)': 'role',
u'default-role (translation required)': 'default-role',
u'title (translation required)': 'title',
'contents (translation required)': 'contents',
'sectnum (translation required)': 'sectnum',
'section-numbering (translation required)': 'sectnum',
u'header (translation required)': 'header',
u'footer (translation required)': 'footer',
#'footnotes (translation required)': 'footnotes',
#'citations (translation required)': 'citations',
'target-notes (translation required)': 'target-notes',
'restructuredtext-test-directive': 'restructuredtext-test-directive'}
"""Traditional Chinese name to registered (in directives/__init__.py)
directive name mapping."""
roles = {
# language-dependent: fixed
'abbreviation (translation required)': 'abbreviation',
'ab (translation required)': 'abbreviation',
'acronym (translation required)': 'acronym',
'ac (translation required)': 'acronym',
'index (translation required)': 'index',
'i (translation required)': 'index',
'subscript (translation required)': 'subscript',
'sub (translation required)': 'subscript',
'superscript (translation required)': 'superscript',
'sup (translation required)': 'superscript',
'title-reference (translation required)': 'title-reference',
'title (translation required)': 'title-reference',
't (translation required)': 'title-reference',
'pep-reference (translation required)': 'pep-reference',
'pep (translation required)': 'pep-reference',
'rfc-reference (translation required)': 'rfc-reference',
'rfc (translation required)': 'rfc-reference',
'emphasis (translation required)': 'emphasis',
'strong (translation required)': 'strong',
'literal (translation required)': 'literal',
'named-reference (translation required)': 'named-reference',
'anonymous-reference (translation required)': 'anonymous-reference',
'footnote-reference (translation required)': 'footnote-reference',
'citation-reference (translation required)': 'citation-reference',
'substitution-reference (translation required)': 'substitution-reference',
'target (translation required)': 'target',
'uri-reference (translation required)': 'uri-reference',
'uri (translation required)': 'uri-reference',
'url (translation required)': 'uri-reference',
'raw (translation required)': 'raw',}
"""Mapping of Traditional Chinese role names to canonical role names for
interpreted text.""" | selenium/src/py/lib/docutils/parsers/rst/languages/zh_tw.py |
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Traditional Chinese language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
'attention (translation required)': 'attention',
'caution (translation required)': 'caution',
'danger (translation required)': 'danger',
'error (translation required)': 'error',
'hint (translation required)': 'hint',
'important (translation required)': 'important',
'note (translation required)': 'note',
'tip (translation required)': 'tip',
'warning (translation required)': 'warning',
'admonition (translation required)': 'admonition',
'sidebar (translation required)': 'sidebar',
'topic (translation required)': 'topic',
'line-block (translation required)': 'line-block',
'parsed-literal (translation required)': 'parsed-literal',
'rubric (translation required)': 'rubric',
'epigraph (translation required)': 'epigraph',
'highlights (translation required)': 'highlights',
'pull-quote (translation required)': 'pull-quote',
'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#'questions (translation required)': 'questions',
'table (translation required)': 'table',
'csv-table (translation required)': 'csv-table',
'list-table (translation required)': 'list-table',
#'qa (translation required)': 'questions',
#'faq (translation required)': 'questions',
'meta (translation required)': 'meta',
#'imagemap (translation required)': 'imagemap',
'image (translation required)': 'image',
'figure (translation required)': 'figure',
'include (translation required)': 'include',
'raw (translation required)': 'raw',
'replace (translation required)': 'replace',
'unicode (translation required)': 'unicode',
u'日期': 'date',
'class (translation required)': 'class',
'role (translation required)': 'role',
u'default-role (translation required)': 'default-role',
u'title (translation required)': 'title',
'contents (translation required)': 'contents',
'sectnum (translation required)': 'sectnum',
'section-numbering (translation required)': 'sectnum',
u'header (translation required)': 'header',
u'footer (translation required)': 'footer',
#'footnotes (translation required)': 'footnotes',
#'citations (translation required)': 'citations',
'target-notes (translation required)': 'target-notes',
'restructuredtext-test-directive': 'restructuredtext-test-directive'}
"""Traditional Chinese name to registered (in directives/__init__.py)
directive name mapping."""
roles = {
# language-dependent: fixed
'abbreviation (translation required)': 'abbreviation',
'ab (translation required)': 'abbreviation',
'acronym (translation required)': 'acronym',
'ac (translation required)': 'acronym',
'index (translation required)': 'index',
'i (translation required)': 'index',
'subscript (translation required)': 'subscript',
'sub (translation required)': 'subscript',
'superscript (translation required)': 'superscript',
'sup (translation required)': 'superscript',
'title-reference (translation required)': 'title-reference',
'title (translation required)': 'title-reference',
't (translation required)': 'title-reference',
'pep-reference (translation required)': 'pep-reference',
'pep (translation required)': 'pep-reference',
'rfc-reference (translation required)': 'rfc-reference',
'rfc (translation required)': 'rfc-reference',
'emphasis (translation required)': 'emphasis',
'strong (translation required)': 'strong',
'literal (translation required)': 'literal',
'named-reference (translation required)': 'named-reference',
'anonymous-reference (translation required)': 'anonymous-reference',
'footnote-reference (translation required)': 'footnote-reference',
'citation-reference (translation required)': 'citation-reference',
'substitution-reference (translation required)': 'substitution-reference',
'target (translation required)': 'target',
'uri-reference (translation required)': 'uri-reference',
'uri (translation required)': 'uri-reference',
'url (translation required)': 'uri-reference',
'raw (translation required)': 'raw',}
"""Mapping of Traditional Chinese role names to canonical role names for
interpreted text.""" | 0.536556 | 0.097305 |
from PySide6 import QtCore, QtGui, QtWidgets, QtXml
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.xbelTree = XbelTree()
self.setCentralWidget(self.xbelTree)
self.createActions()
self.createMenus()
self.statusBar().showMessage("Ready")
self.setWindowTitle("DOM Bookmarks")
self.resize(480, 320)
def open(self):
fileName = QtWidgets.QFileDialog.getOpenFileName(self,
"Open Bookmark File", QtCore.QDir.currentPath(),
"XBEL Files (*.xbel *.xml)")[0]
if not fileName:
return
inFile = QtCore.QFile(fileName)
if not inFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
QtWidgets.QMessageBox.warning(self, "DOM Bookmarks",
"Cannot read file %s:\n%s." % (fileName, inFile.errorString()))
return
if self.xbelTree.read(inFile):
self.statusBar().showMessage("File loaded", 2000)
def saveAs(self):
fileName = QtWidgets.QFileDialog.getSaveFileName(self,
"Save Bookmark File", QtCore.QDir.currentPath(),
"XBEL Files (*.xbel *.xml)")[0]
if not fileName:
return
outFile = QtCore.QFile(fileName)
if not outFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
QtWidgets.QMessageBox.warning(self, "DOM Bookmarks",
"Cannot write file %s:\n%s." % (fileName, outFile.errorString()))
return
if self.xbelTree.write(outFile):
self.statusBar().showMessage("File saved", 2000)
def about(self):
QtWidgets.QMessageBox.about(self, "About DOM Bookmarks",
"The <b>DOM Bookmarks</b> example demonstrates how to use Qt's "
"DOM classes to read and write XML documents.")
def createActions(self):
self.openAct = QtGui.QAction("&Open...", self, shortcut="Ctrl+O",
triggered=self.open)
self.saveAsAct = QtGui.QAction("&Save As...", self, shortcut="Ctrl+S",
triggered=self.saveAs)
self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=self.close)
self.aboutAct = QtGui.QAction("&About", self, triggered=self.about)
self.aboutQtAct = QtGui.QAction("About &Qt", self,
triggered=qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu("&File")
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.saveAsAct)
self.fileMenu.addAction(self.exitAct)
self.menuBar().addSeparator()
self.helpMenu = self.menuBar().addMenu("&Help")
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class XbelTree(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super(XbelTree, self).__init__(parent)
self.header().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
self.setHeaderLabels(("Title", "Location"))
self.domDocument = QtXml.QDomDocument()
self.domElementForItem = {}
self.folderIcon = QtGui.QIcon()
self.bookmarkIcon = QtGui.QIcon()
self.folderIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_DirClosedIcon),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.folderIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_DirOpenIcon),
QtGui.QIcon.Normal, QtGui.QIcon.On)
self.bookmarkIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_FileIcon))
def read(self, device):
ok, errorStr, errorLine, errorColumn = self.domDocument.setContent(device, True)
if not ok:
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"Parse error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr))
return False
root = self.domDocument.documentElement()
if root.tagName() != 'xbel':
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"The file is not an XBEL file.")
return False
elif root.hasAttribute('version') and root.attribute('version') != '1.0':
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"The file is not an XBEL version 1.0 file.")
return False
self.clear()
# It might not be connected.
try:
self.itemChanged.disconnect(self.updateDomElement)
except:
pass
child = root.firstChildElement('folder')
while not child.isNull():
self.parseFolderElement(child)
child = child.nextSiblingElement('folder')
self.itemChanged.connect(self.updateDomElement)
return True
def write(self, device):
indentSize = 4
out = QtCore.QTextStream(device)
self.domDocument.save(out, indentSize)
return True
def updateDomElement(self, item, column):
element = self.domElementForItem.get(id(item))
if not element.isNull():
if column == 0:
oldTitleElement = element.firstChildElement('title')
newTitleElement = self.domDocument.createElement('title')
newTitleText = self.domDocument.createTextNode(item.text(0))
newTitleElement.appendChild(newTitleText)
element.replaceChild(newTitleElement, oldTitleElement)
else:
if element.tagName() == 'bookmark':
element.setAttribute('href', item.text(1))
def parseFolderElement(self, element, parentItem=None):
item = self.createItem(element, parentItem)
title = element.firstChildElement('title').text()
if not title:
title = "Folder"
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
item.setIcon(0, self.folderIcon)
item.setText(0, title)
folded = (element.attribute('folded') != 'no')
self.setItemExpanded(item, not folded)
child = element.firstChildElement()
while not child.isNull():
if child.tagName() == 'folder':
self.parseFolderElement(child, item)
elif child.tagName() == 'bookmark':
childItem = self.createItem(child, item)
title = child.firstChildElement('title').text()
if not title:
title = "Folder"
childItem.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
childItem.setIcon(0, self.bookmarkIcon)
childItem.setText(0, title)
childItem.setText(1, child.attribute('href'))
elif child.tagName() == 'separator':
childItem = self.createItem(child, item)
childItem.setFlags(item.flags() & ~(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable))
childItem.setText(0, 30 * "\xb7")
child = child.nextSiblingElement()
def createItem(self, element, parentItem=None):
item = QtWidgets.QTreeWidgetItem()
if parentItem is not None:
item = QtWidgets.QTreeWidgetItem(parentItem)
else:
item = QtWidgets.QTreeWidgetItem(self)
self.domElementForItem[id(item)] = element
return item
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
mainWin.open()
sys.exit(app.exec_()) | venv/Lib/site-packages/PySide6/examples/xml/dombookmarks/dombookmarks.py | from PySide6 import QtCore, QtGui, QtWidgets, QtXml
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.xbelTree = XbelTree()
self.setCentralWidget(self.xbelTree)
self.createActions()
self.createMenus()
self.statusBar().showMessage("Ready")
self.setWindowTitle("DOM Bookmarks")
self.resize(480, 320)
def open(self):
fileName = QtWidgets.QFileDialog.getOpenFileName(self,
"Open Bookmark File", QtCore.QDir.currentPath(),
"XBEL Files (*.xbel *.xml)")[0]
if not fileName:
return
inFile = QtCore.QFile(fileName)
if not inFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
QtWidgets.QMessageBox.warning(self, "DOM Bookmarks",
"Cannot read file %s:\n%s." % (fileName, inFile.errorString()))
return
if self.xbelTree.read(inFile):
self.statusBar().showMessage("File loaded", 2000)
def saveAs(self):
fileName = QtWidgets.QFileDialog.getSaveFileName(self,
"Save Bookmark File", QtCore.QDir.currentPath(),
"XBEL Files (*.xbel *.xml)")[0]
if not fileName:
return
outFile = QtCore.QFile(fileName)
if not outFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
QtWidgets.QMessageBox.warning(self, "DOM Bookmarks",
"Cannot write file %s:\n%s." % (fileName, outFile.errorString()))
return
if self.xbelTree.write(outFile):
self.statusBar().showMessage("File saved", 2000)
def about(self):
QtWidgets.QMessageBox.about(self, "About DOM Bookmarks",
"The <b>DOM Bookmarks</b> example demonstrates how to use Qt's "
"DOM classes to read and write XML documents.")
def createActions(self):
self.openAct = QtGui.QAction("&Open...", self, shortcut="Ctrl+O",
triggered=self.open)
self.saveAsAct = QtGui.QAction("&Save As...", self, shortcut="Ctrl+S",
triggered=self.saveAs)
self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=self.close)
self.aboutAct = QtGui.QAction("&About", self, triggered=self.about)
self.aboutQtAct = QtGui.QAction("About &Qt", self,
triggered=qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu("&File")
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.saveAsAct)
self.fileMenu.addAction(self.exitAct)
self.menuBar().addSeparator()
self.helpMenu = self.menuBar().addMenu("&Help")
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class XbelTree(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super(XbelTree, self).__init__(parent)
self.header().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
self.setHeaderLabels(("Title", "Location"))
self.domDocument = QtXml.QDomDocument()
self.domElementForItem = {}
self.folderIcon = QtGui.QIcon()
self.bookmarkIcon = QtGui.QIcon()
self.folderIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_DirClosedIcon),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.folderIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_DirOpenIcon),
QtGui.QIcon.Normal, QtGui.QIcon.On)
self.bookmarkIcon.addPixmap(self.style().standardPixmap(QtWidgets.QStyle.SP_FileIcon))
def read(self, device):
ok, errorStr, errorLine, errorColumn = self.domDocument.setContent(device, True)
if not ok:
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"Parse error at line %d, column %d:\n%s" % (errorLine, errorColumn, errorStr))
return False
root = self.domDocument.documentElement()
if root.tagName() != 'xbel':
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"The file is not an XBEL file.")
return False
elif root.hasAttribute('version') and root.attribute('version') != '1.0':
QtWidgets.QMessageBox.information(self.window(), "DOM Bookmarks",
"The file is not an XBEL version 1.0 file.")
return False
self.clear()
# It might not be connected.
try:
self.itemChanged.disconnect(self.updateDomElement)
except:
pass
child = root.firstChildElement('folder')
while not child.isNull():
self.parseFolderElement(child)
child = child.nextSiblingElement('folder')
self.itemChanged.connect(self.updateDomElement)
return True
def write(self, device):
indentSize = 4
out = QtCore.QTextStream(device)
self.domDocument.save(out, indentSize)
return True
def updateDomElement(self, item, column):
element = self.domElementForItem.get(id(item))
if not element.isNull():
if column == 0:
oldTitleElement = element.firstChildElement('title')
newTitleElement = self.domDocument.createElement('title')
newTitleText = self.domDocument.createTextNode(item.text(0))
newTitleElement.appendChild(newTitleText)
element.replaceChild(newTitleElement, oldTitleElement)
else:
if element.tagName() == 'bookmark':
element.setAttribute('href', item.text(1))
def parseFolderElement(self, element, parentItem=None):
item = self.createItem(element, parentItem)
title = element.firstChildElement('title').text()
if not title:
title = "Folder"
item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
item.setIcon(0, self.folderIcon)
item.setText(0, title)
folded = (element.attribute('folded') != 'no')
self.setItemExpanded(item, not folded)
child = element.firstChildElement()
while not child.isNull():
if child.tagName() == 'folder':
self.parseFolderElement(child, item)
elif child.tagName() == 'bookmark':
childItem = self.createItem(child, item)
title = child.firstChildElement('title').text()
if not title:
title = "Folder"
childItem.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
childItem.setIcon(0, self.bookmarkIcon)
childItem.setText(0, title)
childItem.setText(1, child.attribute('href'))
elif child.tagName() == 'separator':
childItem = self.createItem(child, item)
childItem.setFlags(item.flags() & ~(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable))
childItem.setText(0, 30 * "\xb7")
child = child.nextSiblingElement()
def createItem(self, element, parentItem=None):
item = QtWidgets.QTreeWidgetItem()
if parentItem is not None:
item = QtWidgets.QTreeWidgetItem(parentItem)
else:
item = QtWidgets.QTreeWidgetItem(self)
self.domElementForItem[id(item)] = element
return item
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
mainWin.open()
sys.exit(app.exec_()) | 0.431464 | 0.055952 |
import pytest
from httpx import URL, Origin
from httpx.exceptions import InvalidURL
@pytest.mark.parametrize(
"given,idna,host,scheme,port",
[
(
"http://中国.icom.museum:80/",
"http://xn--fiqs8s.icom.museum:80/",
"xn--fiqs8s.icom.museum",
"http",
80,
),
(
"http://Königsgäßchen.de",
"http://xn--knigsgchen-b4a3dun.de",
"xn--knigsgchen-b4a3dun.de",
"http",
80,
),
("https://faß.de", "https://xn--fa-hia.de", "xn--fa-hia.de", "https", 443),
(
"https://βόλος.com:443",
"https://xn--nxasmm1c.com:443",
"xn--nxasmm1c.com",
"https",
443,
),
(
"http://ශ්රී.com:444",
"http://xn--10cl1a0b660p.com:444",
"xn--10cl1a0b660p.com",
"http",
444,
),
(
"https://نامهای.com:4433",
"https://xn--mgba3gch31f060k.com:4433",
"xn--mgba3gch31f060k.com",
"https",
4433,
),
],
ids=[
"http_with_port",
"unicode_tr46_compat",
"https_without_port",
"https_with_port",
"http_with_custom_port",
"https_with_custom_port",
],
)
def test_idna_url(given, idna, host, scheme, port):
url = URL(given)
assert url == URL(idna)
assert url.host == host
assert url.scheme == scheme
assert url.port == port
def test_url():
url = URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url.scheme == "https"
assert url.host == "example.org"
assert url.port == 123
assert url.authority == "example.org:123"
assert url.path == "/path/to/somewhere"
assert url.query == "abc=123"
assert url.fragment == "anchor"
assert (
repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')"
)
new = url.copy_with(scheme="http")
assert new == URL("http://example.org:123/path/to/somewhere?abc=123#anchor")
assert new.scheme == "http"
def test_url_eq_str():
url = URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor"
assert str(url) == url
def test_url_params():
url = URL("https://example.org:123/path/to/somewhere", params={"a": "123"})
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
url = URL("https://example.org:123/path/to/somewhere?b=456", params={"a": "123"})
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
def test_url_join():
"""
Some basic URL joining tests.
"""
url = URL("https://example.org:123/path/to/somewhere")
assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else"
assert (
url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else"
)
assert (
url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else"
)
assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"
def test_url_join_rfc3986():
"""
URL joining tests, as-per reference examples in RFC 3986.
https://tools.ietf.org/html/rfc3986#section-5.4
"""
url = URL("http://example.com/b/c/d;p?q")
with pytest.raises(InvalidURL):
assert url.join("g:h") == "g:h"
assert url.join("g") == "http://example.com/b/c/g"
assert url.join("./g") == "http://example.com/b/c/g"
assert url.join("g/") == "http://example.com/b/c/g/"
assert url.join("/g") == "http://example.com/g"
assert url.join("//g") == "http://g"
assert url.join("?y") == "http://example.com/b/c/d;p?y"
assert url.join("g?y") == "http://example.com/b/c/g?y"
assert url.join("#s") == "http://example.com/b/c/d;p?q#s"
assert url.join("g#s") == "http://example.com/b/c/g#s"
assert url.join("g?y#s") == "http://example.com/b/c/g?y#s"
assert url.join(";x") == "http://example.com/b/c/;x"
assert url.join("g;x") == "http://example.com/b/c/g;x"
assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s"
assert url.join("") == "http://example.com/b/c/d;p?q"
assert url.join(".") == "http://example.com/b/c/"
assert url.join("./") == "http://example.com/b/c/"
assert url.join("..") == "http://example.com/b/"
assert url.join("../") == "http://example.com/b/"
assert url.join("../g") == "http://example.com/b/g"
assert url.join("../..") == "http://example.com/"
assert url.join("../../") == "http://example.com/"
assert url.join("../../g") == "http://example.com/g"
assert url.join("../../../g") == "http://example.com/g"
assert url.join("../../../../g") == "http://example.com/g"
assert url.join("/./g") == "http://example.com/g"
assert url.join("/../g") == "http://example.com/g"
assert url.join("g.") == "http://example.com/b/c/g."
assert url.join(".g") == "http://example.com/b/c/.g"
assert url.join("g..") == "http://example.com/b/c/g.."
assert url.join("..g") == "http://example.com/b/c/..g"
assert url.join("./../g") == "http://example.com/b/g"
assert url.join("./g/.") == "http://example.com/b/c/g/"
assert url.join("g/./h") == "http://example.com/b/c/g/h"
assert url.join("g/../h") == "http://example.com/b/c/h"
assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y"
assert url.join("g;x=1/../y") == "http://example.com/b/c/y"
assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x"
assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x"
assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x"
assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x"
def test_url_set():
urls = (
URL("http://example.org:123/path/to/somewhere"),
URL("http://example.org:123/path/to/somewhere/else"),
)
url_set = set(urls)
assert all(url in urls for url in url_set)
def test_origin_from_url_string():
origin = Origin("https://example.com")
assert origin.scheme == "https"
assert origin.is_ssl
assert origin.host == "example.com"
assert origin.port == 443 | tests/models/test_url.py | import pytest
from httpx import URL, Origin
from httpx.exceptions import InvalidURL
@pytest.mark.parametrize(
"given,idna,host,scheme,port",
[
(
"http://中国.icom.museum:80/",
"http://xn--fiqs8s.icom.museum:80/",
"xn--fiqs8s.icom.museum",
"http",
80,
),
(
"http://Königsgäßchen.de",
"http://xn--knigsgchen-b4a3dun.de",
"xn--knigsgchen-b4a3dun.de",
"http",
80,
),
("https://faß.de", "https://xn--fa-hia.de", "xn--fa-hia.de", "https", 443),
(
"https://βόλος.com:443",
"https://xn--nxasmm1c.com:443",
"xn--nxasmm1c.com",
"https",
443,
),
(
"http://ශ්රී.com:444",
"http://xn--10cl1a0b660p.com:444",
"xn--10cl1a0b660p.com",
"http",
444,
),
(
"https://نامهای.com:4433",
"https://xn--mgba3gch31f060k.com:4433",
"xn--mgba3gch31f060k.com",
"https",
4433,
),
],
ids=[
"http_with_port",
"unicode_tr46_compat",
"https_without_port",
"https_with_port",
"http_with_custom_port",
"https_with_custom_port",
],
)
def test_idna_url(given, idna, host, scheme, port):
url = URL(given)
assert url == URL(idna)
assert url.host == host
assert url.scheme == scheme
assert url.port == port
def test_url():
url = URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url.scheme == "https"
assert url.host == "example.org"
assert url.port == 123
assert url.authority == "example.org:123"
assert url.path == "/path/to/somewhere"
assert url.query == "abc=123"
assert url.fragment == "anchor"
assert (
repr(url) == "URL('https://example.org:123/path/to/somewhere?abc=123#anchor')"
)
new = url.copy_with(scheme="http")
assert new == URL("http://example.org:123/path/to/somewhere?abc=123#anchor")
assert new.scheme == "http"
def test_url_eq_str():
url = URL("https://example.org:123/path/to/somewhere?abc=123#anchor")
assert url == "https://example.org:123/path/to/somewhere?abc=123#anchor"
assert str(url) == url
def test_url_params():
url = URL("https://example.org:123/path/to/somewhere", params={"a": "123"})
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
url = URL("https://example.org:123/path/to/somewhere?b=456", params={"a": "123"})
assert str(url) == "https://example.org:123/path/to/somewhere?a=123"
def test_url_join():
"""
Some basic URL joining tests.
"""
url = URL("https://example.org:123/path/to/somewhere")
assert url.join("/somewhere-else") == "https://example.org:123/somewhere-else"
assert (
url.join("somewhere-else") == "https://example.org:123/path/to/somewhere-else"
)
assert (
url.join("../somewhere-else") == "https://example.org:123/path/somewhere-else"
)
assert url.join("../../somewhere-else") == "https://example.org:123/somewhere-else"
def test_url_join_rfc3986():
"""
URL joining tests, as-per reference examples in RFC 3986.
https://tools.ietf.org/html/rfc3986#section-5.4
"""
url = URL("http://example.com/b/c/d;p?q")
with pytest.raises(InvalidURL):
assert url.join("g:h") == "g:h"
assert url.join("g") == "http://example.com/b/c/g"
assert url.join("./g") == "http://example.com/b/c/g"
assert url.join("g/") == "http://example.com/b/c/g/"
assert url.join("/g") == "http://example.com/g"
assert url.join("//g") == "http://g"
assert url.join("?y") == "http://example.com/b/c/d;p?y"
assert url.join("g?y") == "http://example.com/b/c/g?y"
assert url.join("#s") == "http://example.com/b/c/d;p?q#s"
assert url.join("g#s") == "http://example.com/b/c/g#s"
assert url.join("g?y#s") == "http://example.com/b/c/g?y#s"
assert url.join(";x") == "http://example.com/b/c/;x"
assert url.join("g;x") == "http://example.com/b/c/g;x"
assert url.join("g;x?y#s") == "http://example.com/b/c/g;x?y#s"
assert url.join("") == "http://example.com/b/c/d;p?q"
assert url.join(".") == "http://example.com/b/c/"
assert url.join("./") == "http://example.com/b/c/"
assert url.join("..") == "http://example.com/b/"
assert url.join("../") == "http://example.com/b/"
assert url.join("../g") == "http://example.com/b/g"
assert url.join("../..") == "http://example.com/"
assert url.join("../../") == "http://example.com/"
assert url.join("../../g") == "http://example.com/g"
assert url.join("../../../g") == "http://example.com/g"
assert url.join("../../../../g") == "http://example.com/g"
assert url.join("/./g") == "http://example.com/g"
assert url.join("/../g") == "http://example.com/g"
assert url.join("g.") == "http://example.com/b/c/g."
assert url.join(".g") == "http://example.com/b/c/.g"
assert url.join("g..") == "http://example.com/b/c/g.."
assert url.join("..g") == "http://example.com/b/c/..g"
assert url.join("./../g") == "http://example.com/b/g"
assert url.join("./g/.") == "http://example.com/b/c/g/"
assert url.join("g/./h") == "http://example.com/b/c/g/h"
assert url.join("g/../h") == "http://example.com/b/c/h"
assert url.join("g;x=1/./y") == "http://example.com/b/c/g;x=1/y"
assert url.join("g;x=1/../y") == "http://example.com/b/c/y"
assert url.join("g?y/./x") == "http://example.com/b/c/g?y/./x"
assert url.join("g?y/../x") == "http://example.com/b/c/g?y/../x"
assert url.join("g#s/./x") == "http://example.com/b/c/g#s/./x"
assert url.join("g#s/../x") == "http://example.com/b/c/g#s/../x"
def test_url_set():
urls = (
URL("http://example.org:123/path/to/somewhere"),
URL("http://example.org:123/path/to/somewhere/else"),
)
url_set = set(urls)
assert all(url in urls for url in url_set)
def test_origin_from_url_string():
origin = Origin("https://example.com")
assert origin.scheme == "https"
assert origin.is_ssl
assert origin.host == "example.com"
assert origin.port == 443 | 0.46393 | 0.477311 |
from __future__ import division, print_function, absolute_import
import pickle
import shutil
import os.path as osp
import warnings
from functools import partial
from collections import OrderedDict
import torch
import torch.nn as nn
from .tools import mkdir_if_missing
__all__ = [
'save_checkpoint', 'load_checkpoint', 'resume_from_checkpoint',
'open_all_layers', 'open_specified_layers', 'count_num_param',
'load_pretrained_weights'
]
def save_checkpoint(
state, save_dir, is_best=False, remove_module_from_keys=False
):
r"""Saves checkpoint.
Args:
state (dict): dictionary.
save_dir (str): directory to save checkpoint.
is_best (bool, optional): if True, this checkpoint will be copied and named
``model-best.pth.tar``. Default is False.
remove_module_from_keys (bool, optional): whether to remove "module."
from layer names. Default is False.
Examples::
>>> state = {
>>> 'state_dict': model.state_dict(),
>>> 'epoch': 10,
>>> 'rank1': 0.5,
>>> 'optimizer': optimizer.state_dict()
>>> }
>>> save_checkpoint(state, 'log/my_model')
"""
mkdir_if_missing(save_dir)
if remove_module_from_keys:
# remove 'module.' in state_dict's keys
state_dict = state['state_dict']
new_state_dict = OrderedDict()
for k, v in state_dict.items():
if k.startswith('module.'):
k = k[7:]
new_state_dict[k] = v
state['state_dict'] = new_state_dict
# save
epoch = state['epoch']
fpath = osp.join(save_dir, 'model.pth.tar-' + str(epoch))
torch.save(state, fpath)
print('Checkpoint saved to "{}"'.format(fpath))
if is_best:
shutil.copy(fpath, osp.join(osp.dirname(fpath), 'model-best.pth.tar'))
def load_checkpoint(fpath):
r"""Loads checkpoint.
``UnicodeDecodeError`` can be well handled, which means
python2-saved files can be read from python3.
Args:
fpath (str): path to checkpoint.
Returns:
dict
Examples::
>>> from torchreid.utils import load_checkpoint
>>> fpath = 'log/my_model/model.pth.tar-10'
>>> checkpoint = load_checkpoint(fpath)
"""
if fpath is None:
raise ValueError('File path is None')
if not osp.exists(fpath):
raise FileNotFoundError('File is not found at "{}"'.format(fpath))
map_location = None if torch.cuda.is_available() else 'cpu'
try:
checkpoint = torch.load(fpath, map_location=map_location)
except UnicodeDecodeError:
pickle.load = partial(pickle.load, encoding="latin1")
pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1")
checkpoint = torch.load(
fpath, pickle_module=pickle, map_location=map_location
)
except Exception:
print('Unable to load checkpoint from "{}"'.format(fpath))
raise
return checkpoint
def resume_from_checkpoint(fpath, model, optimizer=None, scheduler=None):
r"""Resumes training from a checkpoint.
This will load (1) model weights and (2) ``state_dict``
of optimizer if ``optimizer`` is not None.
Args:
fpath (str): path to checkpoint.
model (nn.Module): model.
optimizer (Optimizer, optional): an Optimizer.
scheduler (LRScheduler, optional): an LRScheduler.
Returns:
int: start_epoch.
Examples::
>>> from torchreid.utils import resume_from_checkpoint
>>> fpath = 'log/my_model/model.pth.tar-10'
>>> start_epoch = resume_from_checkpoint(
>>> fpath, model, optimizer, scheduler
>>> )
"""
print('Loading checkpoint from "{}"'.format(fpath))
checkpoint = load_checkpoint(fpath)
model.load_state_dict(checkpoint['state_dict'])
print('Loaded model weights')
if optimizer is not None and 'optimizer' in checkpoint.keys():
optimizer.load_state_dict(checkpoint['optimizer'])
print('Loaded optimizer')
if scheduler is not None and 'scheduler' in checkpoint.keys():
scheduler.load_state_dict(checkpoint['scheduler'])
print('Loaded scheduler')
start_epoch = checkpoint['epoch']
print('Last epoch = {}'.format(start_epoch))
if 'rank1' in checkpoint.keys():
print('Last rank1 = {:.1%}'.format(checkpoint['rank1']))
return start_epoch
def adjust_learning_rate(
optimizer,
base_lr,
epoch,
stepsize=20,
gamma=0.1,
linear_decay=False,
final_lr=0,
max_epoch=100
):
r"""Adjusts learning rate.
Deprecated.
"""
if linear_decay:
# linearly decay learning rate from base_lr to final_lr
frac_done = epoch / max_epoch
lr = frac_done*final_lr + (1.-frac_done) * base_lr
else:
# decay learning rate by gamma for every stepsize
lr = base_lr * (gamma**(epoch // stepsize))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def set_bn_to_eval(m):
r"""Sets BatchNorm layers to eval mode."""
# 1. no update for running mean and var
# 2. scale and shift parameters are still trainable
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.eval()
def open_all_layers(model):
r"""Opens all layers in model for training.
Examples::
>>> from torchreid.utils import open_all_layers
>>> open_all_layers(model)
"""
model.train()
for p in model.parameters():
p.requires_grad = True
def open_specified_layers(model, open_layers):
r"""Opens specified layers in model for training while keeping
other layers frozen.
Args:
model (nn.Module): neural net model.
open_layers (str or list): layers open for training.
Examples::
>>> from torchreid.utils import open_specified_layers
>>> # Only model.classifier will be updated.
>>> open_layers = 'classifier'
>>> open_specified_layers(model, open_layers)
>>> # Only model.fc and model.classifier will be updated.
>>> open_layers = ['fc', 'classifier']
>>> open_specified_layers(model, open_layers)
"""
if isinstance(model, nn.DataParallel):
model = model.module
if isinstance(open_layers, str):
open_layers = [open_layers]
for layer in open_layers:
assert hasattr(
model, layer
), '"{}" is not an attribute of the model, please provide the correct name'.format(
layer
)
for name, module in model.named_children():
if name in open_layers:
module.train()
for p in module.parameters():
p.requires_grad = True
else:
module.eval()
for p in module.parameters():
p.requires_grad = False
def count_num_param(model):
r"""Counts number of parameters in a model while ignoring ``self.classifier``.
Args:
model (nn.Module): network model.
Examples::
>>> from torchreid.utils import count_num_param
>>> model_size = count_num_param(model)
.. warning::
This method is deprecated in favor of
``torchreid.utils.compute_model_complexity``.
"""
warnings.warn(
'This method is deprecated and will be removed in the future.'
)
num_param = sum(p.numel() for p in model.parameters())
if isinstance(model, nn.DataParallel):
model = model.module
if hasattr(model,
'classifier') and isinstance(model.classifier, nn.Module):
# we ignore the classifier because it is unused at test time
num_param -= sum(p.numel() for p in model.classifier.parameters())
return num_param
def load_pretrained_weights(model, weight_path):
r"""Loads pretrianed weights to model.
Features::
- Incompatible layers (unmatched in name or size) will be ignored.
- Can automatically deal with keys containing "module.".
Args:
model (nn.Module): network model.
weight_path (str): path to pretrained weights.
Examples::
>>> from torchreid.utils import load_pretrained_weights
>>> weight_path = 'log/my_model/model-best.pth.tar'
>>> load_pretrained_weights(model, weight_path)
"""
checkpoint = load_checkpoint(weight_path)
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
else:
state_dict = checkpoint
model_dict = model.state_dict()
new_state_dict = OrderedDict()
matched_layers, discarded_layers = [], []
for k, v in state_dict.items():
if k.startswith('module.'):
k = k[7:] # discard module.
if k in model_dict and model_dict[k].size() == v.size():
new_state_dict[k] = v
matched_layers.append(k)
else:
discarded_layers.append(k)
model_dict.update(new_state_dict)
model.load_state_dict(model_dict)
if len(matched_layers) == 0:
warnings.warn(
'The pretrained weights "{}" cannot be loaded, '
'please check the key names manually '
'(** ignored and continue **)'.format(weight_path)
)
else:
print(
'Successfully loaded pretrained weights from "{}"'.
format(weight_path)
)
if len(discarded_layers) > 0:
print(
'** The following layers are discarded '
'due to unmatched keys or layer size: {}'.
format(discarded_layers)
) | torchreid/utils/torchtools.py | from __future__ import division, print_function, absolute_import
import pickle
import shutil
import os.path as osp
import warnings
from functools import partial
from collections import OrderedDict
import torch
import torch.nn as nn
from .tools import mkdir_if_missing
__all__ = [
'save_checkpoint', 'load_checkpoint', 'resume_from_checkpoint',
'open_all_layers', 'open_specified_layers', 'count_num_param',
'load_pretrained_weights'
]
def save_checkpoint(
state, save_dir, is_best=False, remove_module_from_keys=False
):
r"""Saves checkpoint.
Args:
state (dict): dictionary.
save_dir (str): directory to save checkpoint.
is_best (bool, optional): if True, this checkpoint will be copied and named
``model-best.pth.tar``. Default is False.
remove_module_from_keys (bool, optional): whether to remove "module."
from layer names. Default is False.
Examples::
>>> state = {
>>> 'state_dict': model.state_dict(),
>>> 'epoch': 10,
>>> 'rank1': 0.5,
>>> 'optimizer': optimizer.state_dict()
>>> }
>>> save_checkpoint(state, 'log/my_model')
"""
mkdir_if_missing(save_dir)
if remove_module_from_keys:
# remove 'module.' in state_dict's keys
state_dict = state['state_dict']
new_state_dict = OrderedDict()
for k, v in state_dict.items():
if k.startswith('module.'):
k = k[7:]
new_state_dict[k] = v
state['state_dict'] = new_state_dict
# save
epoch = state['epoch']
fpath = osp.join(save_dir, 'model.pth.tar-' + str(epoch))
torch.save(state, fpath)
print('Checkpoint saved to "{}"'.format(fpath))
if is_best:
shutil.copy(fpath, osp.join(osp.dirname(fpath), 'model-best.pth.tar'))
def load_checkpoint(fpath):
r"""Loads checkpoint.
``UnicodeDecodeError`` can be well handled, which means
python2-saved files can be read from python3.
Args:
fpath (str): path to checkpoint.
Returns:
dict
Examples::
>>> from torchreid.utils import load_checkpoint
>>> fpath = 'log/my_model/model.pth.tar-10'
>>> checkpoint = load_checkpoint(fpath)
"""
if fpath is None:
raise ValueError('File path is None')
if not osp.exists(fpath):
raise FileNotFoundError('File is not found at "{}"'.format(fpath))
map_location = None if torch.cuda.is_available() else 'cpu'
try:
checkpoint = torch.load(fpath, map_location=map_location)
except UnicodeDecodeError:
pickle.load = partial(pickle.load, encoding="latin1")
pickle.Unpickler = partial(pickle.Unpickler, encoding="latin1")
checkpoint = torch.load(
fpath, pickle_module=pickle, map_location=map_location
)
except Exception:
print('Unable to load checkpoint from "{}"'.format(fpath))
raise
return checkpoint
def resume_from_checkpoint(fpath, model, optimizer=None, scheduler=None):
r"""Resumes training from a checkpoint.
This will load (1) model weights and (2) ``state_dict``
of optimizer if ``optimizer`` is not None.
Args:
fpath (str): path to checkpoint.
model (nn.Module): model.
optimizer (Optimizer, optional): an Optimizer.
scheduler (LRScheduler, optional): an LRScheduler.
Returns:
int: start_epoch.
Examples::
>>> from torchreid.utils import resume_from_checkpoint
>>> fpath = 'log/my_model/model.pth.tar-10'
>>> start_epoch = resume_from_checkpoint(
>>> fpath, model, optimizer, scheduler
>>> )
"""
print('Loading checkpoint from "{}"'.format(fpath))
checkpoint = load_checkpoint(fpath)
model.load_state_dict(checkpoint['state_dict'])
print('Loaded model weights')
if optimizer is not None and 'optimizer' in checkpoint.keys():
optimizer.load_state_dict(checkpoint['optimizer'])
print('Loaded optimizer')
if scheduler is not None and 'scheduler' in checkpoint.keys():
scheduler.load_state_dict(checkpoint['scheduler'])
print('Loaded scheduler')
start_epoch = checkpoint['epoch']
print('Last epoch = {}'.format(start_epoch))
if 'rank1' in checkpoint.keys():
print('Last rank1 = {:.1%}'.format(checkpoint['rank1']))
return start_epoch
def adjust_learning_rate(
optimizer,
base_lr,
epoch,
stepsize=20,
gamma=0.1,
linear_decay=False,
final_lr=0,
max_epoch=100
):
r"""Adjusts learning rate.
Deprecated.
"""
if linear_decay:
# linearly decay learning rate from base_lr to final_lr
frac_done = epoch / max_epoch
lr = frac_done*final_lr + (1.-frac_done) * base_lr
else:
# decay learning rate by gamma for every stepsize
lr = base_lr * (gamma**(epoch // stepsize))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def set_bn_to_eval(m):
r"""Sets BatchNorm layers to eval mode."""
# 1. no update for running mean and var
# 2. scale and shift parameters are still trainable
classname = m.__class__.__name__
if classname.find('BatchNorm') != -1:
m.eval()
def open_all_layers(model):
r"""Opens all layers in model for training.
Examples::
>>> from torchreid.utils import open_all_layers
>>> open_all_layers(model)
"""
model.train()
for p in model.parameters():
p.requires_grad = True
def open_specified_layers(model, open_layers):
r"""Opens specified layers in model for training while keeping
other layers frozen.
Args:
model (nn.Module): neural net model.
open_layers (str or list): layers open for training.
Examples::
>>> from torchreid.utils import open_specified_layers
>>> # Only model.classifier will be updated.
>>> open_layers = 'classifier'
>>> open_specified_layers(model, open_layers)
>>> # Only model.fc and model.classifier will be updated.
>>> open_layers = ['fc', 'classifier']
>>> open_specified_layers(model, open_layers)
"""
if isinstance(model, nn.DataParallel):
model = model.module
if isinstance(open_layers, str):
open_layers = [open_layers]
for layer in open_layers:
assert hasattr(
model, layer
), '"{}" is not an attribute of the model, please provide the correct name'.format(
layer
)
for name, module in model.named_children():
if name in open_layers:
module.train()
for p in module.parameters():
p.requires_grad = True
else:
module.eval()
for p in module.parameters():
p.requires_grad = False
def count_num_param(model):
r"""Counts number of parameters in a model while ignoring ``self.classifier``.
Args:
model (nn.Module): network model.
Examples::
>>> from torchreid.utils import count_num_param
>>> model_size = count_num_param(model)
.. warning::
This method is deprecated in favor of
``torchreid.utils.compute_model_complexity``.
"""
warnings.warn(
'This method is deprecated and will be removed in the future.'
)
num_param = sum(p.numel() for p in model.parameters())
if isinstance(model, nn.DataParallel):
model = model.module
if hasattr(model,
'classifier') and isinstance(model.classifier, nn.Module):
# we ignore the classifier because it is unused at test time
num_param -= sum(p.numel() for p in model.classifier.parameters())
return num_param
def load_pretrained_weights(model, weight_path):
r"""Loads pretrianed weights to model.
Features::
- Incompatible layers (unmatched in name or size) will be ignored.
- Can automatically deal with keys containing "module.".
Args:
model (nn.Module): network model.
weight_path (str): path to pretrained weights.
Examples::
>>> from torchreid.utils import load_pretrained_weights
>>> weight_path = 'log/my_model/model-best.pth.tar'
>>> load_pretrained_weights(model, weight_path)
"""
checkpoint = load_checkpoint(weight_path)
if 'state_dict' in checkpoint:
state_dict = checkpoint['state_dict']
else:
state_dict = checkpoint
model_dict = model.state_dict()
new_state_dict = OrderedDict()
matched_layers, discarded_layers = [], []
for k, v in state_dict.items():
if k.startswith('module.'):
k = k[7:] # discard module.
if k in model_dict and model_dict[k].size() == v.size():
new_state_dict[k] = v
matched_layers.append(k)
else:
discarded_layers.append(k)
model_dict.update(new_state_dict)
model.load_state_dict(model_dict)
if len(matched_layers) == 0:
warnings.warn(
'The pretrained weights "{}" cannot be loaded, '
'please check the key names manually '
'(** ignored and continue **)'.format(weight_path)
)
else:
print(
'Successfully loaded pretrained weights from "{}"'.
format(weight_path)
)
if len(discarded_layers) > 0:
print(
'** The following layers are discarded '
'due to unmatched keys or layer size: {}'.
format(discarded_layers)
) | 0.864896 | 0.156137 |
import matplotlib
matplotlib.use('Agg')
from typing import Any, AnyStr
from matplotlib.figure import Figure
from datetime import datetime
from matplotlib.pyplot import title
from experiment_automator.constants import ExperimentConstants, SlackConstants
from textwrap import wrap
class ResultContainer(dict):
def __init__(self, attrs):
super().__init__({
ExperimentConstants.KEY_EXPERIMENT_RESULTS: {},
SlackConstants.KEY_SLACK_PAYLOAD: {
ExperimentConstants.KEY_EXPERIMENT_RESULTS: {},
}
})
self.attrs = attrs
def add_model_result(self, result_label: AnyStr, value: Any):
self.get_experiment_results_payload().update({result_label: value})
self.get_slack_payload().get(ExperimentConstants.KEY_EXPERIMENT_RESULTS).update({result_label: value})
def __save_figure(self, image_label: AnyStr, figure: Figure):
path = "%s-%s.png" % (image_label, datetime.now().strftime("%H:%M:%S"))
title("\n".join(wrap("%s" % list(self.attrs.values()))))
figure.savefig(path)
figure.clear()
return path
def __add_slack_attachment_image(self, image_label, image_path):
if self.get_slack_payload().get(SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS, None) is None:
self.get_slack_payload()[SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS] = []
self.get_slack_payload()[SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS].append((image_label, image_path))
def __add_to_storage(self, path: AnyStr):
# TODO Drive result will be added when Drive integration completed
pass
def add_figure(self, image_label: AnyStr, figure: Figure):
path = self.__save_figure(image_label, figure)
# Add figure to Slack as additional attachment
self.__add_slack_attachment_image(image_label, path)
# Add figure to storage
# TODO Adding figure to storage
def set_slack_main_figure(self, image_label: AnyStr, figure: Figure):
self.get_slack_payload()[SlackConstants.KEY_SLACK_MAIN_IMAGE] = self.__save_figure(image_label, figure)
def get_experiment_results_payload(self):
return self.get(ExperimentConstants.KEY_EXPERIMENT_RESULTS)
def get_slack_payload(self):
return self.get(SlackConstants.KEY_SLACK_PAYLOAD)
def __repr__(self):
return super().__repr__() | experiment_automator/result_container.py | import matplotlib
matplotlib.use('Agg')
from typing import Any, AnyStr
from matplotlib.figure import Figure
from datetime import datetime
from matplotlib.pyplot import title
from experiment_automator.constants import ExperimentConstants, SlackConstants
from textwrap import wrap
class ResultContainer(dict):
def __init__(self, attrs):
super().__init__({
ExperimentConstants.KEY_EXPERIMENT_RESULTS: {},
SlackConstants.KEY_SLACK_PAYLOAD: {
ExperimentConstants.KEY_EXPERIMENT_RESULTS: {},
}
})
self.attrs = attrs
def add_model_result(self, result_label: AnyStr, value: Any):
self.get_experiment_results_payload().update({result_label: value})
self.get_slack_payload().get(ExperimentConstants.KEY_EXPERIMENT_RESULTS).update({result_label: value})
def __save_figure(self, image_label: AnyStr, figure: Figure):
path = "%s-%s.png" % (image_label, datetime.now().strftime("%H:%M:%S"))
title("\n".join(wrap("%s" % list(self.attrs.values()))))
figure.savefig(path)
figure.clear()
return path
def __add_slack_attachment_image(self, image_label, image_path):
if self.get_slack_payload().get(SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS, None) is None:
self.get_slack_payload()[SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS] = []
self.get_slack_payload()[SlackConstants.KEY_SLACK_IMAGE_ATTACHMENTS].append((image_label, image_path))
def __add_to_storage(self, path: AnyStr):
# TODO Drive result will be added when Drive integration completed
pass
def add_figure(self, image_label: AnyStr, figure: Figure):
path = self.__save_figure(image_label, figure)
# Add figure to Slack as additional attachment
self.__add_slack_attachment_image(image_label, path)
# Add figure to storage
# TODO Adding figure to storage
def set_slack_main_figure(self, image_label: AnyStr, figure: Figure):
self.get_slack_payload()[SlackConstants.KEY_SLACK_MAIN_IMAGE] = self.__save_figure(image_label, figure)
def get_experiment_results_payload(self):
return self.get(ExperimentConstants.KEY_EXPERIMENT_RESULTS)
def get_slack_payload(self):
return self.get(SlackConstants.KEY_SLACK_PAYLOAD)
def __repr__(self):
return super().__repr__() | 0.5083 | 0.229665 |
_base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py'
model = dict(
pretrained='open-mmlab://res2net101_v1d_26w_4s',
backbone=dict(
type='Res2Net',
depth=101,
scales=4,
base_width=26,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True)))
# DATA
CATE_ID = '2'
classes_dict = {'1': 'visible body', '2': 'full body', '3': 'head', '4': 'vehicle'}
json_pre_dict = {'1': 'person_visible', '2': 'person_full', '3': 'person_head', '4':'vehicle'}
data_root = 'DATA/split_' + json_pre_dict[CATE_ID].split('_')[0] +'_train/'
anno_root = 'DATA/coco_format_json/'
classes = (classes_dict[CATE_ID],)
json_pre = json_pre_dict[CATE_ID]
dataset_type = 'CocoDataset'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=[(1333, 480), (1333, 960)],
multiscale_mode='range',
keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_train.json',
img_prefix=data_root + 'image_train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_val.json',
img_prefix=data_root + 'image_train',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_val.json',
img_prefix=data_root + 'image_train',
pipeline=test_pipeline))
# default_runtime
load_from = "./cpt/vfnet_r2_101_dcn_ms_2x_51.1.pth"
resume_from = None
# schedule_2x
# optimizer
optimizer = dict(type='SGD', lr=0.00125, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None) | configs/vfnet/vfnet_r2_101_fpn_mdconv_c3-c5_mstrain_2x_coco_cate2.py | _base_ = './vfnet_r50_fpn_mdconv_c3-c5_mstrain_2x_coco.py'
model = dict(
pretrained='open-mmlab://res2net101_v1d_26w_4s',
backbone=dict(
type='Res2Net',
depth=101,
scales=4,
base_width=26,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True)))
# DATA
CATE_ID = '2'
classes_dict = {'1': 'visible body', '2': 'full body', '3': 'head', '4': 'vehicle'}
json_pre_dict = {'1': 'person_visible', '2': 'person_full', '3': 'person_head', '4':'vehicle'}
data_root = 'DATA/split_' + json_pre_dict[CATE_ID].split('_')[0] +'_train/'
anno_root = 'DATA/coco_format_json/'
classes = (classes_dict[CATE_ID],)
json_pre = json_pre_dict[CATE_ID]
dataset_type = 'CocoDataset'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=[(1333, 480), (1333, 960)],
multiscale_mode='range',
keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_train.json',
img_prefix=data_root + 'image_train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_val.json',
img_prefix=data_root + 'image_train',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
classes=classes,
ann_file=anno_root + json_pre + '_val.json',
img_prefix=data_root + 'image_train',
pipeline=test_pipeline))
# default_runtime
load_from = "./cpt/vfnet_r2_101_dcn_ms_2x_51.1.pth"
resume_from = None
# schedule_2x
# optimizer
optimizer = dict(type='SGD', lr=0.00125, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None) | 0.430985 | 0.160661 |
import datetime
from pandas import DataFrame
from tests.utils import NormTestCase
class PythonTestCase(NormTestCase):
def test_python_declaration(self):
script = """
test := {{
from datetime import datetime
test = datetime.utcnow
}};
"""
self.execute(script)
lam = self.execute("test;")
self.assertTrue(lam is not None)
def test_python_query(self):
script = """
test := {{
from datetime import datetime
test = datetime.utcnow
}};
"""
self.execute(script)
result = self.execute("test();")
self.assertTrue(result is not None)
self.assertTrue(isinstance(result, datetime.datetime))
def test_python_query_on_data(self):
script = """
test := {{
import numpy as np
test = np.sin
}};
"""
self.execute(script)
script = """
a := (1, 2, 3)
| (1.1, 2.2, 3.3)
| (0.1, 0.2, 0.3)
;
"""
self.execute(script)
result = self.execute("test(a());")
self.assertTrue(result is not None)
def test_python_custom_function(self):
script = """
test := {{
def test(x):
return '{}-{}'.format(x.b, x.c)
}};
"""
self.execute(script)
script = """
a(b:String, c:String) := ("store", "truth")
| ("having", "evil")
;
"""
self.execute(script)
result = self.execute("test(a());")
self.assertTrue(result is not None)
self.assertTrue(isinstance(result, DataFrame))
def test_python_function_projection(self):
script = """
utcnow := {{
from datetime import datetime
utcnow = datetime.utcnow
}};
"""
self.execute(script)
script = """
a(b:String, c:String) := ("store", "truth")
| ("having", "evil")
;
"""
self.execute(script)
lam = self.execute("a &= utcnow()?time;")
self.assertTrue(lam is not None)
self.assertTrue(isinstance(lam.data, DataFrame))
self.assertTrue(lam.data['time'] is not None)
def test_python_function_projection2(self):
script = """
gaussian := {{
import numpy as np
def gaussian(v):
return np.exp(-v*v / 2)/np.sqrt(2*np.pi)
}};
"""
self.execute(script)
script = """
a(v: Float, mu: Float) := (1.2, 2.3)
| (1.0, 2.0)
;
"""
self.execute(script)
lam = self.execute("a &= gaussian(v)?p;")
self.assertTrue(lam is not None)
self.assertTrue(isinstance(lam.data, DataFrame))
self.assertTrue(lam.data['p'] is not None)
def test_python_code_expression(self):
self.execute("test(a: String, b: Integer);")
import pandas as pd
t1 = pd.DataFrame(data={'a': ['a', 'b', 'c'], 'b': [1, 2, 3]})
self.executor.python_context = locals()
lam = self.execute("test(a: String, b: Integer) := {{ t1 }};")
self.assertTrue(lam is not None)
self.assertTrue(all(lam.data['a'] == ['a', 'b', 'c']))
self.assertTrue(all(lam.data['b'] == [1, 2, 3]))
t2 = t1
t2.loc[1, 'a'] = 'e'
self.executor.python_context = locals()
lam = self.execute("test := {{ t2 }};")
self.assertTrue(lam is not None)
self.assertTrue(all(lam.data['a'] == ['a', 'e', 'c']))
self.assertTrue(all(lam.data['b'] == [1, 2, 3])) | tests/python_tests.py | import datetime
from pandas import DataFrame
from tests.utils import NormTestCase
class PythonTestCase(NormTestCase):
def test_python_declaration(self):
script = """
test := {{
from datetime import datetime
test = datetime.utcnow
}};
"""
self.execute(script)
lam = self.execute("test;")
self.assertTrue(lam is not None)
def test_python_query(self):
script = """
test := {{
from datetime import datetime
test = datetime.utcnow
}};
"""
self.execute(script)
result = self.execute("test();")
self.assertTrue(result is not None)
self.assertTrue(isinstance(result, datetime.datetime))
def test_python_query_on_data(self):
script = """
test := {{
import numpy as np
test = np.sin
}};
"""
self.execute(script)
script = """
a := (1, 2, 3)
| (1.1, 2.2, 3.3)
| (0.1, 0.2, 0.3)
;
"""
self.execute(script)
result = self.execute("test(a());")
self.assertTrue(result is not None)
def test_python_custom_function(self):
script = """
test := {{
def test(x):
return '{}-{}'.format(x.b, x.c)
}};
"""
self.execute(script)
script = """
a(b:String, c:String) := ("store", "truth")
| ("having", "evil")
;
"""
self.execute(script)
result = self.execute("test(a());")
self.assertTrue(result is not None)
self.assertTrue(isinstance(result, DataFrame))
def test_python_function_projection(self):
script = """
utcnow := {{
from datetime import datetime
utcnow = datetime.utcnow
}};
"""
self.execute(script)
script = """
a(b:String, c:String) := ("store", "truth")
| ("having", "evil")
;
"""
self.execute(script)
lam = self.execute("a &= utcnow()?time;")
self.assertTrue(lam is not None)
self.assertTrue(isinstance(lam.data, DataFrame))
self.assertTrue(lam.data['time'] is not None)
def test_python_function_projection2(self):
script = """
gaussian := {{
import numpy as np
def gaussian(v):
return np.exp(-v*v / 2)/np.sqrt(2*np.pi)
}};
"""
self.execute(script)
script = """
a(v: Float, mu: Float) := (1.2, 2.3)
| (1.0, 2.0)
;
"""
self.execute(script)
lam = self.execute("a &= gaussian(v)?p;")
self.assertTrue(lam is not None)
self.assertTrue(isinstance(lam.data, DataFrame))
self.assertTrue(lam.data['p'] is not None)
def test_python_code_expression(self):
self.execute("test(a: String, b: Integer);")
import pandas as pd
t1 = pd.DataFrame(data={'a': ['a', 'b', 'c'], 'b': [1, 2, 3]})
self.executor.python_context = locals()
lam = self.execute("test(a: String, b: Integer) := {{ t1 }};")
self.assertTrue(lam is not None)
self.assertTrue(all(lam.data['a'] == ['a', 'b', 'c']))
self.assertTrue(all(lam.data['b'] == [1, 2, 3]))
t2 = t1
t2.loc[1, 'a'] = 'e'
self.executor.python_context = locals()
lam = self.execute("test := {{ t2 }};")
self.assertTrue(lam is not None)
self.assertTrue(all(lam.data['a'] == ['a', 'e', 'c']))
self.assertTrue(all(lam.data['b'] == [1, 2, 3])) | 0.612541 | 0.544559 |
import logging
from typing import Iterator, Dict
import torch
from torch.optim import SGD
from torch.optim.optimizer import Optimizer
from tqdm import tqdm
from forte.common.configuration import Config
from forte.data import BaseExtractor
from forte.data.data_pack import DataPack
from forte.data.readers.conll03_reader import CoNLL03Reader
from forte.evaluation.ner_evaluator import CoNLLNEREvaluator
from forte.models.ner.model_factory import BiRecurrentConvCRF
from forte.pipeline import Pipeline
from forte.processors.base import Predictor
from forte.trainer.base.trainer import BaseTrainer
from forte.utils import create_import_error_msg
logger = logging.getLogger(__name__)
class TaggingTrainer(BaseTrainer):
def __init__(
self,
task_type: str,
config_data: Config,
config_model: Config,
config_extractors: Dict,
device,
):
super().__init__()
self.task_type = task_type
# All the configs
self.config_data: Config = config_data
self.config_model: Config = config_model
self.config_extractors: Dict = config_extractors
self.device = device
self.model = None
def create_tp_config(self) -> Dict:
return {
"preprocess": {"device": self.device.type},
"dataset": {"batch_size": self.config_data.batch_size_tokens},
"request": self.config_extractors,
}
def create_pack_iterator(self) -> Iterator[DataPack]:
reader = CoNLL03Reader()
train_pl: Pipeline = Pipeline()
train_pl.set_reader(reader)
train_pl.initialize()
yield from train_pl.process_dataset(self.config_data.train_path)
def train(self):
logging.info("Constructing the extractors and models.")
schemes: Dict = self.train_preprocessor.request["schemes"]
text_extractor: BaseExtractor = schemes["text_tag"]["extractor"]
char_extractor: BaseExtractor = schemes["char_tag"]["extractor"]
output_extractor: BaseExtractor = schemes["output_tag"]["extractor"]
self.model: BiRecurrentConvCRF = BiRecurrentConvCRF(
word_vocab=text_extractor.vocab.to_dict(),
char_vocab_size=len(char_extractor.vocab),
tag_vocab_size=len(output_extractor.vocab),
config_model=self.config_model,
)
self.model.to(self.device)
logging.info("Constructing the optimizer.")
optim: Optimizer = SGD(
self.model.parameters(),
lr=self.config_model.learning_rate,
momentum=self.config_model.momentum,
nesterov=True,
)
tp = self.train_preprocessor
logging.info("Constructing the validation pipeline.")
predictor = TaggingPredictor()
# Load the extractors to the predictor.
predictor.set_feature_requests(self.train_preprocessor.request)
predictor.load(self.model)
evaluator = CoNLLNEREvaluator()
output_extractor_configs = self.config_extractors["feature_scheme"][
"output_tag"
]["extractor"]["config"]
evaluator_config = {
"entry_type": output_extractor_configs["entry_type"],
"tagging_unit": output_extractor_configs["tagging_unit"],
"attribute": output_extractor_configs["attribute"],
}
val_reader = CoNLL03Reader(cache_in_memory=True)
val_pl: Pipeline = Pipeline()
val_pl.set_reader(val_reader)
val_pl.add(
predictor,
config={
"batcher": {
"batch_size": 10,
}
},
)
val_pl.add(evaluator, config=evaluator_config)
val_pl.initialize()
epoch: int = 0
train_err: int = 0
train_total: float = 0.0
train_sentence_len_sum: float = 0.0
logger.info("Start training.")
try:
from texar.torch.data import (
Batch,
) # pylint: disable=import-outside-toplevel
except ImportError as e:
raise ImportError(
create_import_error_msg(
"texar-pytorch", "extractor", "the extractor system"
)
) from e
while epoch < self.config_data.num_epochs:
epoch += 1
# Get iterator of preprocessed batch of train data
batch_iter: Iterator[Batch] = tp.get_train_batch_iterator()
for batch in tqdm(batch_iter):
word = batch["text_tag"]["data"]
char = batch["char_tag"]["data"]
output = batch["output_tag"]["data"]
word_masks = batch["text_tag"]["masks"][0]
optim.zero_grad()
loss = self.model(word, char, output, mask=word_masks)
loss.backward()
optim.step()
batch_train_err = loss.item() * batch.batch_size
train_err += batch_train_err
train_total += batch.batch_size
train_sentence_len_sum += torch.sum(
batch["text_tag"]["masks"][0]
).item()
logger.info(
"%dth Epoch training, "
"total number of examples: %d, "
"Average sentence length: %0.3f, "
"loss: %0.3f",
epoch,
train_total,
train_sentence_len_sum / train_total,
train_err / train_total,
)
train_err = 0
train_total = 0.0
train_sentence_len_sum = 0.0
val_pl.run(self.config_data.val_path)
logger.info(
"%dth Epoch evaluating, " "val result: %s",
epoch,
evaluator.get_result(),
)
class TaggingPredictor(Predictor):
def predict(self, data_batch: Dict) -> Dict:
val_output = self.model.decode(
input_word=data_batch["text_tag"]["data"],
input_char=data_batch["char_tag"]["data"],
mask=data_batch["text_tag"]["masks"][0],
)
val_output = val_output.numpy()
return {"output_tag": val_output} | examples/tagging/tagging_trainer.py | import logging
from typing import Iterator, Dict
import torch
from torch.optim import SGD
from torch.optim.optimizer import Optimizer
from tqdm import tqdm
from forte.common.configuration import Config
from forte.data import BaseExtractor
from forte.data.data_pack import DataPack
from forte.data.readers.conll03_reader import CoNLL03Reader
from forte.evaluation.ner_evaluator import CoNLLNEREvaluator
from forte.models.ner.model_factory import BiRecurrentConvCRF
from forte.pipeline import Pipeline
from forte.processors.base import Predictor
from forte.trainer.base.trainer import BaseTrainer
from forte.utils import create_import_error_msg
logger = logging.getLogger(__name__)
class TaggingTrainer(BaseTrainer):
def __init__(
self,
task_type: str,
config_data: Config,
config_model: Config,
config_extractors: Dict,
device,
):
super().__init__()
self.task_type = task_type
# All the configs
self.config_data: Config = config_data
self.config_model: Config = config_model
self.config_extractors: Dict = config_extractors
self.device = device
self.model = None
def create_tp_config(self) -> Dict:
return {
"preprocess": {"device": self.device.type},
"dataset": {"batch_size": self.config_data.batch_size_tokens},
"request": self.config_extractors,
}
def create_pack_iterator(self) -> Iterator[DataPack]:
reader = CoNLL03Reader()
train_pl: Pipeline = Pipeline()
train_pl.set_reader(reader)
train_pl.initialize()
yield from train_pl.process_dataset(self.config_data.train_path)
def train(self):
logging.info("Constructing the extractors and models.")
schemes: Dict = self.train_preprocessor.request["schemes"]
text_extractor: BaseExtractor = schemes["text_tag"]["extractor"]
char_extractor: BaseExtractor = schemes["char_tag"]["extractor"]
output_extractor: BaseExtractor = schemes["output_tag"]["extractor"]
self.model: BiRecurrentConvCRF = BiRecurrentConvCRF(
word_vocab=text_extractor.vocab.to_dict(),
char_vocab_size=len(char_extractor.vocab),
tag_vocab_size=len(output_extractor.vocab),
config_model=self.config_model,
)
self.model.to(self.device)
logging.info("Constructing the optimizer.")
optim: Optimizer = SGD(
self.model.parameters(),
lr=self.config_model.learning_rate,
momentum=self.config_model.momentum,
nesterov=True,
)
tp = self.train_preprocessor
logging.info("Constructing the validation pipeline.")
predictor = TaggingPredictor()
# Load the extractors to the predictor.
predictor.set_feature_requests(self.train_preprocessor.request)
predictor.load(self.model)
evaluator = CoNLLNEREvaluator()
output_extractor_configs = self.config_extractors["feature_scheme"][
"output_tag"
]["extractor"]["config"]
evaluator_config = {
"entry_type": output_extractor_configs["entry_type"],
"tagging_unit": output_extractor_configs["tagging_unit"],
"attribute": output_extractor_configs["attribute"],
}
val_reader = CoNLL03Reader(cache_in_memory=True)
val_pl: Pipeline = Pipeline()
val_pl.set_reader(val_reader)
val_pl.add(
predictor,
config={
"batcher": {
"batch_size": 10,
}
},
)
val_pl.add(evaluator, config=evaluator_config)
val_pl.initialize()
epoch: int = 0
train_err: int = 0
train_total: float = 0.0
train_sentence_len_sum: float = 0.0
logger.info("Start training.")
try:
from texar.torch.data import (
Batch,
) # pylint: disable=import-outside-toplevel
except ImportError as e:
raise ImportError(
create_import_error_msg(
"texar-pytorch", "extractor", "the extractor system"
)
) from e
while epoch < self.config_data.num_epochs:
epoch += 1
# Get iterator of preprocessed batch of train data
batch_iter: Iterator[Batch] = tp.get_train_batch_iterator()
for batch in tqdm(batch_iter):
word = batch["text_tag"]["data"]
char = batch["char_tag"]["data"]
output = batch["output_tag"]["data"]
word_masks = batch["text_tag"]["masks"][0]
optim.zero_grad()
loss = self.model(word, char, output, mask=word_masks)
loss.backward()
optim.step()
batch_train_err = loss.item() * batch.batch_size
train_err += batch_train_err
train_total += batch.batch_size
train_sentence_len_sum += torch.sum(
batch["text_tag"]["masks"][0]
).item()
logger.info(
"%dth Epoch training, "
"total number of examples: %d, "
"Average sentence length: %0.3f, "
"loss: %0.3f",
epoch,
train_total,
train_sentence_len_sum / train_total,
train_err / train_total,
)
train_err = 0
train_total = 0.0
train_sentence_len_sum = 0.0
val_pl.run(self.config_data.val_path)
logger.info(
"%dth Epoch evaluating, " "val result: %s",
epoch,
evaluator.get_result(),
)
class TaggingPredictor(Predictor):
def predict(self, data_batch: Dict) -> Dict:
val_output = self.model.decode(
input_word=data_batch["text_tag"]["data"],
input_char=data_batch["char_tag"]["data"],
mask=data_batch["text_tag"]["masks"][0],
)
val_output = val_output.numpy()
return {"output_tag": val_output} | 0.876463 | 0.130452 |
from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
import time_machine
from nautobot.dcim.models import DeviceType, Manufacturer, Platform
from nautobot.extras.choices import RelationshipTypeChoices
from nautobot.extras.models import Relationship, RelationshipAssociation, Status, Tag
from nautobot_device_lifecycle_mgmt.models import (
HardwareLCM,
InventoryItemSoftwareValidationResult,
SoftwareLCM,
ValidatedSoftwareLCM,
DeviceSoftwareValidationResult,
CVELCM,
VulnerabilityLCM,
SoftwareImageLCM,
)
from .conftest import create_devices, create_inventory_items, create_cves, create_softwares
class HardwareLCMTestCase(TestCase):
"""Tests for the HardwareLCM models."""
def setUp(self):
"""Set up base objects."""
self.manufacturer = Manufacturer.objects.create(name="Cisco")
self.device_type = DeviceType.objects.create(model="c9300-24", slug="c9300-24", manufacturer=self.manufacturer)
def test_create_hwlcm_success_eo_sale(self):
"""Successfully create basic notice with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2023, 4, 1))
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2023-04-01")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of sale: 2023-04-01")
def test_create_hwlcm_notice_success_eo_support(self):
"""Successfully create basic notice with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2022, 4, 1))
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_support), "2022-04-01")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of support: 2022-04-01")
def test_create_hwlcm_success_eo_sale_inventory_item(self):
"""Successfully create basic notice with end_of_sale."""
inventory_item = "WS-X6848-TX-2T"
hwlcm_obj = HardwareLCM.objects.create(inventory_item=inventory_item, end_of_sale=date(2023, 4, 1))
self.assertEqual(hwlcm_obj.inventory_item, inventory_item)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2023-04-01")
self.assertEqual(str(hwlcm_obj), f"Inventory Part: {inventory_item} - End of sale: 2023-04-01")
def test_create_hwlcm_notice_success_eo_all(self):
"""Successfully create basic notice."""
hwlcm_obj = HardwareLCM.objects.create(
device_type=self.device_type,
end_of_sale=date(2022, 4, 1),
end_of_support=date(2023, 4, 1),
end_of_sw_releases=date(2024, 4, 1),
end_of_security_patches=date(2025, 4, 1),
documentation_url="https://test.com",
)
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2022-04-01")
self.assertEqual(str(hwlcm_obj.end_of_support), "2023-04-01")
self.assertEqual(str(hwlcm_obj.end_of_sw_releases), "2024-04-01")
self.assertEqual(str(hwlcm_obj.end_of_security_patches), "2025-04-01")
self.assertEqual(hwlcm_obj.documentation_url, "https://test.com")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of support: 2023-04-01")
def test_create_hwlcm_notice_failed_missing_one_of(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(device_type=self.device_type)
self.assertEqual(failure_exception.exception.messages[0], "End of Sale or End of Support must be specified.")
def test_create_hwlcm_notice_failed_validation_documentation_url(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(
device_type=self.device_type, end_of_support=date(2023, 4, 1), documentation_url="test.com"
)
self.assertEqual(failure_exception.exception.messages[0], "Enter a valid URL.")
def test_create_hwlcm_notice_failed_validation_date(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(device_type=self.device_type, end_of_support="April 1st 2022")
self.assertIn("invalid date format. It must be in YYYY-MM-DD format.", failure_exception.exception.messages[0])
def test_expired_property_end_of_support_expired(self):
"""Test expired property is expired with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2021, 4, 1))
self.assertTrue(hwlcm_obj.expired)
def test_expired_property_end_of_support_not_expired(self):
"""Test expired property is NOT expired with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2099, 4, 1))
self.assertFalse(hwlcm_obj.expired)
def test_expired_property_end_of_sale_expired(self):
"""Test expired property is expired with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2021, 4, 1))
self.assertTrue(hwlcm_obj.expired)
def test_expired_property_end_of_sale_not_expired(self):
"""Test expired property is NOT expired with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2999, 4, 1))
self.assertFalse(hwlcm_obj.expired)
def test_expired_field_setting_end_of_sale_expired(self):
"""Test expired property is expired with end_of_sale when set within plugin settings."""
settings.PLUGINS_CONFIG["nautobot_device_lifecycle_mgmt"]["expired_field"] = "end_of_sale"
hwlcm_obj = HardwareLCM.objects.create(
device_type=self.device_type, end_of_sale=date(2021, 4, 1), end_of_support=date(2999, 4, 1)
)
self.assertTrue(hwlcm_obj.expired)
def test_expired_field_setting_end_of_sale_not_expired(self):
"""Test expired property is NOT expired with end_of_sale not existing but plugin setting set to end_of_sale."""
settings.PLUGINS_CONFIG["nautobot_device_lifecycle_mgmt"]["expired_field"] = "end_of_sale"
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2999, 4, 1))
self.assertFalse(hwlcm_obj.expired)
class SoftwareLCMTestCase(TestCase):
"""Tests for the SoftwareLCM model."""
def setUp(self):
"""Set up base objects."""
self.device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
def test_create_softwarelcm_required_only(self):
"""Successfully create SoftwareLCM with required fields only."""
softwarelcm = SoftwareLCM.objects.create(device_platform=self.device_platform, version="4.21.3F")
self.assertEqual(softwarelcm.device_platform, self.device_platform)
self.assertEqual(softwarelcm.version, "4.21.3F")
def test_create_softwarelcm_all(self):
"""Successfully create SoftwareLCM with all fields."""
softwarelcm_full = SoftwareLCM.objects.create(
device_platform=self.device_platform,
version="17.3.3 MD",
alias="Amsterdam-17.3.3 MD",
release_date=date(2019, 1, 10),
end_of_support=date(2022, 5, 15),
documentation_url="https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-15-4m-t/series.html",
long_term_support=False,
pre_release=True,
)
self.assertEqual(softwarelcm_full.device_platform, self.device_platform)
self.assertEqual(softwarelcm_full.version, "17.3.3 MD")
self.assertEqual(softwarelcm_full.alias, "Amsterdam-17.3.3 MD")
self.assertEqual(str(softwarelcm_full.release_date), "2019-01-10")
self.assertEqual(str(softwarelcm_full.end_of_support), "2022-05-15")
self.assertEqual(
softwarelcm_full.documentation_url,
"https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-15-4m-t/series.html",
)
self.assertEqual(softwarelcm_full.long_term_support, False)
self.assertEqual(softwarelcm_full.pre_release, True)
self.assertEqual(str(softwarelcm_full), f"{self.device_platform.name} - {softwarelcm_full.version}")
class ValidatedSoftwareLCMTestCase(TestCase):
"""Tests for the ValidatedSoftwareLCM model."""
def setUp(self):
"""Set up base objects."""
device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
self.software = SoftwareLCM.objects.create(
device_platform=device_platform,
version="17.3.3 MD",
release_date=date(2019, 1, 10),
)
manufacturer = Manufacturer.objects.create(name="Cisco", slug="cisco")
self.device_type_1 = DeviceType.objects.create(manufacturer=manufacturer, model="ASR-1000", slug="asr-1000")
self.device_type_2 = DeviceType.objects.create(manufacturer=manufacturer, model="CAT-3750", slug="cat-3750")
self.content_type_devicetype = ContentType.objects.get(app_label="dcim", model="devicetype")
def test_create_validatedsoftwarelcm_required_only(self):
"""Successfully create ValidatedSoftwareLCM with required fields only."""
validatedsoftwarelcm = ValidatedSoftwareLCM(
software=self.software,
start=date(2019, 1, 10),
)
validatedsoftwarelcm.device_types.set([self.device_type_1])
validatedsoftwarelcm.save()
self.assertEqual(validatedsoftwarelcm.software, self.software)
self.assertEqual(str(validatedsoftwarelcm.start), "2019-01-10")
self.assertEqual(list(validatedsoftwarelcm.device_types.all()), [self.device_type_1])
def test_create_validatedsoftwarelcm_all(self):
"""Successfully create ValidatedSoftwareLCM with all fields."""
validatedsoftwarelcm = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
end=date(2022, 11, 1),
preferred=False,
)
validatedsoftwarelcm.device_types.set([self.device_type_1])
validatedsoftwarelcm.save()
self.assertEqual(validatedsoftwarelcm.software, self.software)
self.assertEqual(str(validatedsoftwarelcm.start), "2020-04-15")
self.assertEqual(str(validatedsoftwarelcm.end), "2022-11-01")
self.assertEqual(list(validatedsoftwarelcm.device_types.all()), [self.device_type_1])
self.assertEqual(validatedsoftwarelcm.preferred, False)
self.assertEqual(str(validatedsoftwarelcm), f"{self.software} - Valid since: {validatedsoftwarelcm.start}")
def test_validatedsoftwarelcm_valid_property(self):
"""Test behavior of the 'valid' property."""
validatedsoftwarelcm_start_only = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
preferred=False,
)
validatedsoftwarelcm_start_only.device_types.set([self.device_type_1])
validatedsoftwarelcm_start_only.save()
validatedsoftwarelcm_start_end = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
end=date(2022, 11, 1),
preferred=False,
)
validatedsoftwarelcm_start_end.device_types.set([self.device_type_2])
validatedsoftwarelcm_start_end.save()
date_valid = date(2021, 6, 11)
date_before_valid_start = date(2018, 9, 26)
date_after_valid_end = date(2023, 1, 4)
with time_machine.travel(date_valid):
self.assertEqual(validatedsoftwarelcm_start_only.valid, True)
self.assertEqual(validatedsoftwarelcm_start_end.valid, True)
with time_machine.travel(date_before_valid_start):
self.assertEqual(validatedsoftwarelcm_start_only.valid, False)
self.assertEqual(validatedsoftwarelcm_start_end.valid, False)
with time_machine.travel(date_after_valid_end):
self.assertEqual(validatedsoftwarelcm_start_only.valid, True)
self.assertEqual(validatedsoftwarelcm_start_end.valid, False)
class DeviceSoftwareValidationResultTestCase(TestCase):
"""Tests for the DeviceSoftwareValidationResult model."""
def setUp(self):
"""Set up test objects."""
self.device = create_devices()[0]
self.platform = Platform.objects.all().first()
self.software = SoftwareLCM.objects.create(
device_platform=self.platform,
version="17.3.3 MD",
release_date="2019-01-10",
)
def test_create_devicesoftwarevalidationresult(self):
"""Successfully create SoftwareLCM with required fields only."""
validation_result = DeviceSoftwareValidationResult.objects.create(
device=self.device,
software=self.software,
is_validated=True,
)
self.assertEqual(validation_result.device, self.device)
self.assertEqual(validation_result.software, self.software)
self.assertEqual(validation_result.is_validated, True)
class InventoryItemSoftwareValidationResultTestCase(TestCase):
"""Tests for the DeviceSoftwareValidationResult model."""
def setUp(self):
"""Set up test objects."""
self.inventory_item = create_inventory_items()[0]
self.platform = Platform.objects.all().first()
self.software = SoftwareLCM.objects.create(
device_platform=self.platform,
version="17.3.3 MD",
release_date="2019-01-10",
)
def test_create_devicesoftwarevalidationresult(self):
"""Successfully create SoftwareLCM with required fields only."""
validation_result = InventoryItemSoftwareValidationResult.objects.create(
inventory_item=self.inventory_item,
software=self.software,
is_validated=True,
)
self.assertEqual(validation_result.inventory_item, self.inventory_item)
self.assertEqual(validation_result.software, self.software)
self.assertEqual(validation_result.is_validated, True)
class CVELCMTestCase(TestCase):
"""Tests for the CVELCM model."""
def setUp(self):
"""Set up the test objects."""
self.device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
self.softwarelcm = SoftwareLCM.objects.create(device_platform=self.device_platform, version="15.2(5)e")
self.cve_ct = ContentType.objects.get_for_model(CVELCM)
self.software_ct = ContentType.objects.get_for_model(SoftwareLCM)
self.relationship = Relationship.objects.get_or_create(
name="CVE to Software",
defaults={
"name": "CVE to Software",
"slug": "cve_soft",
"type": RelationshipTypeChoices.TYPE_MANY_TO_MANY,
"source_type": ContentType.objects.get_for_model(CVELCM),
"source_label": "Affected Softwares",
"destination_type": ContentType.objects.get_for_model(SoftwareLCM),
"destination_label": "Corresponding CVEs",
},
)[0]
self.status = Status.objects.create(
name="Fixed", slug="fixed", color="4caf50", description="Unit has been fixed"
)
self.status.content_types.set([self.cve_ct])
def test_create_cvelcm_required_only(self):
"""Successfully create CVELCM with required fields only."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-1391", published_date="2021-03-24", link="https://www.cvedetails.com/cve/CVE-2021-1391/"
)
self.assertEqual(cvelcm.name, "CVE-2021-1391")
self.assertEqual(cvelcm.published_date, "2021-03-24")
self.assertEqual(cvelcm.link, "https://www.cvedetails.com/cve/CVE-2021-1391/")
def test_create_cvelcm_all(self):
"""Successfully create CVELCM with all fields."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-34699",
published_date="2021-09-23",
link="https://www.cvedetails.com/cve/CVE-2021-34699/",
status=self.status,
description="Thanos",
severity="High",
cvss=6.8,
cvss_v2=6.9,
cvss_v3=6.7,
fix="Avengers",
comments="This is very bad juju.",
)
self.assertEqual(cvelcm.name, "CVE-2021-34699")
self.assertEqual(cvelcm.published_date, "2021-09-23")
self.assertEqual(cvelcm.link, "https://www.cvedetails.com/cve/CVE-2021-34699/")
self.assertEqual(cvelcm.status, self.status)
self.assertEqual(cvelcm.description, "Thanos")
self.assertEqual(cvelcm.severity, "High")
self.assertEqual(cvelcm.cvss, 6.8)
self.assertEqual(cvelcm.cvss_v2, 6.9)
self.assertEqual(cvelcm.cvss_v3, 6.7)
self.assertEqual(cvelcm.fix, "Avengers")
self.assertEqual(cvelcm.comments, "This is very bad juju.")
def test_create_cve_soft_relationship_association(self):
"""Successfully create a relationship between CVE and Software."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-1391", published_date="2021-03-24", link="https://www.cvedetails.com/cve/CVE-2021-1391/"
)
association = RelationshipAssociation.objects.create(
relationship_id=self.relationship.id,
source_id=cvelcm.id,
source_type_id=self.cve_ct.id,
destination_id=self.softwarelcm.id,
destination_type_id=self.software_ct.id,
)
cve_rels = cvelcm.get_relationships()
self.assertEqual(cve_rels["source"][self.relationship].first(), association)
class VulnerabilityLCMTestCase(TestCase):
"""Tests for the VulnerabilityLCM model."""
def setUp(self):
"""Set up the test objects."""
self.inv_items = create_inventory_items()
self.devices = [inv_item.device for inv_item in self.inv_items]
self.cves = create_cves()
self.softwares = create_softwares()
vuln_ct = ContentType.objects.get_for_model(VulnerabilityLCM)
self.status = Status.objects.create(
name="Exempt", slug="exempt", color="4caf50", description="This unit is exempt."
)
self.status.content_types.set([vuln_ct])
def test_create_vulnerabilitylcm_device_required_only(self):
"""Successfully create VulnerabilityLCM with required fields only."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[0], software=self.softwares[0], device=self.devices[0]
)
self.assertEqual(str(vulnerability), "Device: sw1 - Software: Cisco IOS - 15.1(2)M - CVE: CVE-2021-1391")
self.assertEqual(vulnerability.cve, self.cves[0])
self.assertEqual(vulnerability.software, self.softwares[0])
self.assertEqual(vulnerability.device, self.devices[0])
def test_create_vulnerabilitylcm_inventory_item_required_only(self):
"""Successfully create VulnerabilityLCM with required fields only."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[1], software=self.softwares[1], inventory_item=self.inv_items[1]
)
self.assertEqual(
str(vulnerability),
"Inventory Part: 100GBASE-SR4 QSFP Transceiver - Software: Cisco IOS - 4.22.9M - CVE: CVE-2021-44228",
)
self.assertEqual(vulnerability.cve, self.cves[1])
self.assertEqual(vulnerability.software, self.softwares[1])
self.assertEqual(vulnerability.inventory_item, self.inv_items[1])
def test_create_vulnerabilitylcm_all(self):
"""Successfully create VulnerabilityLCM with all fields."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[2], software=self.softwares[2], device=self.devices[2], status=self.status
)
self.assertEqual(str(vulnerability), "Device: sw3 - Software: Cisco IOS - 21.4R3 - CVE: CVE-2020-27134")
self.assertEqual(vulnerability.cve, self.cves[2])
self.assertEqual(vulnerability.software, self.softwares[2])
self.assertEqual(vulnerability.device, self.devices[2])
self.assertEqual(vulnerability.status, self.status)
class SoftwareImageLCMTestCase(TestCase):
"""Tests for the SoftwareImageLCM model."""
def setUp(self):
"""Set up base objects."""
device_platform = Platform.objects.get_or_create(name="Cisco IOS", slug="cisco_ios")[0]
self.software = SoftwareLCM.objects.create(
device_platform=device_platform,
version="17.3.3 MD",
release_date=date(2019, 1, 10),
)
manufacturer = Manufacturer.objects.create(name="Cisco", slug="cisco")
self.device_type_1 = DeviceType.objects.create(manufacturer=manufacturer, model="ASR-1000", slug="asr-1000")
self.device_type_2 = DeviceType.objects.create(manufacturer=manufacturer, model="CAT-3750", slug="cat-3750")
self.inventory_item = create_inventory_items()[0]
self.tag = Tag.objects.create(name="asr", slug="asr")
def test_create_softwareimage_required_only(self):
"""Successfully create SoftwareImageLCM with required fields only."""
softwareimage = SoftwareImageLCM(image_file_name="ios17.3.3md.img", software=self.software)
softwareimage.device_types.set([self.device_type_1])
softwareimage.save()
self.assertEqual(softwareimage.image_file_name, "ios17.3.3md.img")
self.assertEqual(softwareimage.software, self.software)
self.assertEqual(list(softwareimage.device_types.all()), [self.device_type_1])
def test_create_softwareimage_all(self):
"""Successfully create SoftwareImageLCM with all fields."""
softwareimage = SoftwareImageLCM(
image_file_name="ios17.3.3md.img",
software=self.software,
download_url="ftp://images.local/cisco/ios17.3.3md.img",
image_file_checksum="441rfabd75b0512r7fde7a7a66faa596",
default_image=True,
)
softwareimage.device_types.set([self.device_type_1])
softwareimage.inventory_items.set([self.inventory_item])
softwareimage.object_tags.set([self.tag])
softwareimage.save()
self.assertEqual(softwareimage.image_file_name, "ios17.3.3md.img")
self.assertEqual(softwareimage.software, self.software)
self.assertEqual(softwareimage.download_url, "ftp://images.local/cisco/ios17.3.3md.img")
self.assertEqual(softwareimage.image_file_checksum, "441rfabd75b0512r7fde7a7a66faa596")
self.assertEqual(softwareimage.default_image, True)
self.assertEqual(list(softwareimage.device_types.all()), [self.device_type_1])
self.assertEqual(list(softwareimage.inventory_items.all()), [self.inventory_item])
self.assertEqual(list(softwareimage.object_tags.all()), [self.tag])
self.assertEqual(str(softwareimage), f"{softwareimage.image_file_name}")
def test_validatedsoftwarelcm_valid_property(self):
"""Test behavior of the 'valid' property."""
validatedsoftwarelcm_start_only = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
preferred=False,
)
validatedsoftwarelcm_start_only.device_types.set([self.device_type_1])
validatedsoftwarelcm_start_only.save() | nautobot_device_lifecycle_mgmt/tests/test_model.py | from datetime import date
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
import time_machine
from nautobot.dcim.models import DeviceType, Manufacturer, Platform
from nautobot.extras.choices import RelationshipTypeChoices
from nautobot.extras.models import Relationship, RelationshipAssociation, Status, Tag
from nautobot_device_lifecycle_mgmt.models import (
HardwareLCM,
InventoryItemSoftwareValidationResult,
SoftwareLCM,
ValidatedSoftwareLCM,
DeviceSoftwareValidationResult,
CVELCM,
VulnerabilityLCM,
SoftwareImageLCM,
)
from .conftest import create_devices, create_inventory_items, create_cves, create_softwares
class HardwareLCMTestCase(TestCase):
"""Tests for the HardwareLCM models."""
def setUp(self):
"""Set up base objects."""
self.manufacturer = Manufacturer.objects.create(name="Cisco")
self.device_type = DeviceType.objects.create(model="c9300-24", slug="c9300-24", manufacturer=self.manufacturer)
def test_create_hwlcm_success_eo_sale(self):
"""Successfully create basic notice with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2023, 4, 1))
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2023-04-01")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of sale: 2023-04-01")
def test_create_hwlcm_notice_success_eo_support(self):
"""Successfully create basic notice with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2022, 4, 1))
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_support), "2022-04-01")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of support: 2022-04-01")
def test_create_hwlcm_success_eo_sale_inventory_item(self):
"""Successfully create basic notice with end_of_sale."""
inventory_item = "WS-X6848-TX-2T"
hwlcm_obj = HardwareLCM.objects.create(inventory_item=inventory_item, end_of_sale=date(2023, 4, 1))
self.assertEqual(hwlcm_obj.inventory_item, inventory_item)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2023-04-01")
self.assertEqual(str(hwlcm_obj), f"Inventory Part: {inventory_item} - End of sale: 2023-04-01")
def test_create_hwlcm_notice_success_eo_all(self):
"""Successfully create basic notice."""
hwlcm_obj = HardwareLCM.objects.create(
device_type=self.device_type,
end_of_sale=date(2022, 4, 1),
end_of_support=date(2023, 4, 1),
end_of_sw_releases=date(2024, 4, 1),
end_of_security_patches=date(2025, 4, 1),
documentation_url="https://test.com",
)
self.assertEqual(hwlcm_obj.device_type, self.device_type)
self.assertEqual(str(hwlcm_obj.end_of_sale), "2022-04-01")
self.assertEqual(str(hwlcm_obj.end_of_support), "2023-04-01")
self.assertEqual(str(hwlcm_obj.end_of_sw_releases), "2024-04-01")
self.assertEqual(str(hwlcm_obj.end_of_security_patches), "2025-04-01")
self.assertEqual(hwlcm_obj.documentation_url, "https://test.com")
self.assertEqual(str(hwlcm_obj), "Device Type: c9300-24 - End of support: 2023-04-01")
def test_create_hwlcm_notice_failed_missing_one_of(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(device_type=self.device_type)
self.assertEqual(failure_exception.exception.messages[0], "End of Sale or End of Support must be specified.")
def test_create_hwlcm_notice_failed_validation_documentation_url(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(
device_type=self.device_type, end_of_support=date(2023, 4, 1), documentation_url="test.com"
)
self.assertEqual(failure_exception.exception.messages[0], "Enter a valid URL.")
def test_create_hwlcm_notice_failed_validation_date(self):
"""Successfully create basic notice."""
with self.assertRaises(ValidationError) as failure_exception:
HardwareLCM.objects.create(device_type=self.device_type, end_of_support="April 1st 2022")
self.assertIn("invalid date format. It must be in YYYY-MM-DD format.", failure_exception.exception.messages[0])
def test_expired_property_end_of_support_expired(self):
"""Test expired property is expired with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2021, 4, 1))
self.assertTrue(hwlcm_obj.expired)
def test_expired_property_end_of_support_not_expired(self):
"""Test expired property is NOT expired with end_of_support."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2099, 4, 1))
self.assertFalse(hwlcm_obj.expired)
def test_expired_property_end_of_sale_expired(self):
"""Test expired property is expired with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2021, 4, 1))
self.assertTrue(hwlcm_obj.expired)
def test_expired_property_end_of_sale_not_expired(self):
"""Test expired property is NOT expired with end_of_sale."""
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_sale=date(2999, 4, 1))
self.assertFalse(hwlcm_obj.expired)
def test_expired_field_setting_end_of_sale_expired(self):
"""Test expired property is expired with end_of_sale when set within plugin settings."""
settings.PLUGINS_CONFIG["nautobot_device_lifecycle_mgmt"]["expired_field"] = "end_of_sale"
hwlcm_obj = HardwareLCM.objects.create(
device_type=self.device_type, end_of_sale=date(2021, 4, 1), end_of_support=date(2999, 4, 1)
)
self.assertTrue(hwlcm_obj.expired)
def test_expired_field_setting_end_of_sale_not_expired(self):
"""Test expired property is NOT expired with end_of_sale not existing but plugin setting set to end_of_sale."""
settings.PLUGINS_CONFIG["nautobot_device_lifecycle_mgmt"]["expired_field"] = "end_of_sale"
hwlcm_obj = HardwareLCM.objects.create(device_type=self.device_type, end_of_support=date(2999, 4, 1))
self.assertFalse(hwlcm_obj.expired)
class SoftwareLCMTestCase(TestCase):
"""Tests for the SoftwareLCM model."""
def setUp(self):
"""Set up base objects."""
self.device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
def test_create_softwarelcm_required_only(self):
"""Successfully create SoftwareLCM with required fields only."""
softwarelcm = SoftwareLCM.objects.create(device_platform=self.device_platform, version="4.21.3F")
self.assertEqual(softwarelcm.device_platform, self.device_platform)
self.assertEqual(softwarelcm.version, "4.21.3F")
def test_create_softwarelcm_all(self):
"""Successfully create SoftwareLCM with all fields."""
softwarelcm_full = SoftwareLCM.objects.create(
device_platform=self.device_platform,
version="17.3.3 MD",
alias="Amsterdam-17.3.3 MD",
release_date=date(2019, 1, 10),
end_of_support=date(2022, 5, 15),
documentation_url="https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-15-4m-t/series.html",
long_term_support=False,
pre_release=True,
)
self.assertEqual(softwarelcm_full.device_platform, self.device_platform)
self.assertEqual(softwarelcm_full.version, "17.3.3 MD")
self.assertEqual(softwarelcm_full.alias, "Amsterdam-17.3.3 MD")
self.assertEqual(str(softwarelcm_full.release_date), "2019-01-10")
self.assertEqual(str(softwarelcm_full.end_of_support), "2022-05-15")
self.assertEqual(
softwarelcm_full.documentation_url,
"https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-15-4m-t/series.html",
)
self.assertEqual(softwarelcm_full.long_term_support, False)
self.assertEqual(softwarelcm_full.pre_release, True)
self.assertEqual(str(softwarelcm_full), f"{self.device_platform.name} - {softwarelcm_full.version}")
class ValidatedSoftwareLCMTestCase(TestCase):
"""Tests for the ValidatedSoftwareLCM model."""
def setUp(self):
"""Set up base objects."""
device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
self.software = SoftwareLCM.objects.create(
device_platform=device_platform,
version="17.3.3 MD",
release_date=date(2019, 1, 10),
)
manufacturer = Manufacturer.objects.create(name="Cisco", slug="cisco")
self.device_type_1 = DeviceType.objects.create(manufacturer=manufacturer, model="ASR-1000", slug="asr-1000")
self.device_type_2 = DeviceType.objects.create(manufacturer=manufacturer, model="CAT-3750", slug="cat-3750")
self.content_type_devicetype = ContentType.objects.get(app_label="dcim", model="devicetype")
def test_create_validatedsoftwarelcm_required_only(self):
"""Successfully create ValidatedSoftwareLCM with required fields only."""
validatedsoftwarelcm = ValidatedSoftwareLCM(
software=self.software,
start=date(2019, 1, 10),
)
validatedsoftwarelcm.device_types.set([self.device_type_1])
validatedsoftwarelcm.save()
self.assertEqual(validatedsoftwarelcm.software, self.software)
self.assertEqual(str(validatedsoftwarelcm.start), "2019-01-10")
self.assertEqual(list(validatedsoftwarelcm.device_types.all()), [self.device_type_1])
def test_create_validatedsoftwarelcm_all(self):
"""Successfully create ValidatedSoftwareLCM with all fields."""
validatedsoftwarelcm = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
end=date(2022, 11, 1),
preferred=False,
)
validatedsoftwarelcm.device_types.set([self.device_type_1])
validatedsoftwarelcm.save()
self.assertEqual(validatedsoftwarelcm.software, self.software)
self.assertEqual(str(validatedsoftwarelcm.start), "2020-04-15")
self.assertEqual(str(validatedsoftwarelcm.end), "2022-11-01")
self.assertEqual(list(validatedsoftwarelcm.device_types.all()), [self.device_type_1])
self.assertEqual(validatedsoftwarelcm.preferred, False)
self.assertEqual(str(validatedsoftwarelcm), f"{self.software} - Valid since: {validatedsoftwarelcm.start}")
def test_validatedsoftwarelcm_valid_property(self):
"""Test behavior of the 'valid' property."""
validatedsoftwarelcm_start_only = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
preferred=False,
)
validatedsoftwarelcm_start_only.device_types.set([self.device_type_1])
validatedsoftwarelcm_start_only.save()
validatedsoftwarelcm_start_end = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
end=date(2022, 11, 1),
preferred=False,
)
validatedsoftwarelcm_start_end.device_types.set([self.device_type_2])
validatedsoftwarelcm_start_end.save()
date_valid = date(2021, 6, 11)
date_before_valid_start = date(2018, 9, 26)
date_after_valid_end = date(2023, 1, 4)
with time_machine.travel(date_valid):
self.assertEqual(validatedsoftwarelcm_start_only.valid, True)
self.assertEqual(validatedsoftwarelcm_start_end.valid, True)
with time_machine.travel(date_before_valid_start):
self.assertEqual(validatedsoftwarelcm_start_only.valid, False)
self.assertEqual(validatedsoftwarelcm_start_end.valid, False)
with time_machine.travel(date_after_valid_end):
self.assertEqual(validatedsoftwarelcm_start_only.valid, True)
self.assertEqual(validatedsoftwarelcm_start_end.valid, False)
class DeviceSoftwareValidationResultTestCase(TestCase):
"""Tests for the DeviceSoftwareValidationResult model."""
def setUp(self):
"""Set up test objects."""
self.device = create_devices()[0]
self.platform = Platform.objects.all().first()
self.software = SoftwareLCM.objects.create(
device_platform=self.platform,
version="17.3.3 MD",
release_date="2019-01-10",
)
def test_create_devicesoftwarevalidationresult(self):
"""Successfully create SoftwareLCM with required fields only."""
validation_result = DeviceSoftwareValidationResult.objects.create(
device=self.device,
software=self.software,
is_validated=True,
)
self.assertEqual(validation_result.device, self.device)
self.assertEqual(validation_result.software, self.software)
self.assertEqual(validation_result.is_validated, True)
class InventoryItemSoftwareValidationResultTestCase(TestCase):
"""Tests for the DeviceSoftwareValidationResult model."""
def setUp(self):
"""Set up test objects."""
self.inventory_item = create_inventory_items()[0]
self.platform = Platform.objects.all().first()
self.software = SoftwareLCM.objects.create(
device_platform=self.platform,
version="17.3.3 MD",
release_date="2019-01-10",
)
def test_create_devicesoftwarevalidationresult(self):
"""Successfully create SoftwareLCM with required fields only."""
validation_result = InventoryItemSoftwareValidationResult.objects.create(
inventory_item=self.inventory_item,
software=self.software,
is_validated=True,
)
self.assertEqual(validation_result.inventory_item, self.inventory_item)
self.assertEqual(validation_result.software, self.software)
self.assertEqual(validation_result.is_validated, True)
class CVELCMTestCase(TestCase):
"""Tests for the CVELCM model."""
def setUp(self):
"""Set up the test objects."""
self.device_platform = Platform.objects.create(name="Cisco IOS", slug="cisco_ios")
self.softwarelcm = SoftwareLCM.objects.create(device_platform=self.device_platform, version="15.2(5)e")
self.cve_ct = ContentType.objects.get_for_model(CVELCM)
self.software_ct = ContentType.objects.get_for_model(SoftwareLCM)
self.relationship = Relationship.objects.get_or_create(
name="CVE to Software",
defaults={
"name": "CVE to Software",
"slug": "cve_soft",
"type": RelationshipTypeChoices.TYPE_MANY_TO_MANY,
"source_type": ContentType.objects.get_for_model(CVELCM),
"source_label": "Affected Softwares",
"destination_type": ContentType.objects.get_for_model(SoftwareLCM),
"destination_label": "Corresponding CVEs",
},
)[0]
self.status = Status.objects.create(
name="Fixed", slug="fixed", color="4caf50", description="Unit has been fixed"
)
self.status.content_types.set([self.cve_ct])
def test_create_cvelcm_required_only(self):
"""Successfully create CVELCM with required fields only."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-1391", published_date="2021-03-24", link="https://www.cvedetails.com/cve/CVE-2021-1391/"
)
self.assertEqual(cvelcm.name, "CVE-2021-1391")
self.assertEqual(cvelcm.published_date, "2021-03-24")
self.assertEqual(cvelcm.link, "https://www.cvedetails.com/cve/CVE-2021-1391/")
def test_create_cvelcm_all(self):
"""Successfully create CVELCM with all fields."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-34699",
published_date="2021-09-23",
link="https://www.cvedetails.com/cve/CVE-2021-34699/",
status=self.status,
description="Thanos",
severity="High",
cvss=6.8,
cvss_v2=6.9,
cvss_v3=6.7,
fix="Avengers",
comments="This is very bad juju.",
)
self.assertEqual(cvelcm.name, "CVE-2021-34699")
self.assertEqual(cvelcm.published_date, "2021-09-23")
self.assertEqual(cvelcm.link, "https://www.cvedetails.com/cve/CVE-2021-34699/")
self.assertEqual(cvelcm.status, self.status)
self.assertEqual(cvelcm.description, "Thanos")
self.assertEqual(cvelcm.severity, "High")
self.assertEqual(cvelcm.cvss, 6.8)
self.assertEqual(cvelcm.cvss_v2, 6.9)
self.assertEqual(cvelcm.cvss_v3, 6.7)
self.assertEqual(cvelcm.fix, "Avengers")
self.assertEqual(cvelcm.comments, "This is very bad juju.")
def test_create_cve_soft_relationship_association(self):
"""Successfully create a relationship between CVE and Software."""
cvelcm = CVELCM.objects.create(
name="CVE-2021-1391", published_date="2021-03-24", link="https://www.cvedetails.com/cve/CVE-2021-1391/"
)
association = RelationshipAssociation.objects.create(
relationship_id=self.relationship.id,
source_id=cvelcm.id,
source_type_id=self.cve_ct.id,
destination_id=self.softwarelcm.id,
destination_type_id=self.software_ct.id,
)
cve_rels = cvelcm.get_relationships()
self.assertEqual(cve_rels["source"][self.relationship].first(), association)
class VulnerabilityLCMTestCase(TestCase):
"""Tests for the VulnerabilityLCM model."""
def setUp(self):
"""Set up the test objects."""
self.inv_items = create_inventory_items()
self.devices = [inv_item.device for inv_item in self.inv_items]
self.cves = create_cves()
self.softwares = create_softwares()
vuln_ct = ContentType.objects.get_for_model(VulnerabilityLCM)
self.status = Status.objects.create(
name="Exempt", slug="exempt", color="4caf50", description="This unit is exempt."
)
self.status.content_types.set([vuln_ct])
def test_create_vulnerabilitylcm_device_required_only(self):
"""Successfully create VulnerabilityLCM with required fields only."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[0], software=self.softwares[0], device=self.devices[0]
)
self.assertEqual(str(vulnerability), "Device: sw1 - Software: Cisco IOS - 15.1(2)M - CVE: CVE-2021-1391")
self.assertEqual(vulnerability.cve, self.cves[0])
self.assertEqual(vulnerability.software, self.softwares[0])
self.assertEqual(vulnerability.device, self.devices[0])
def test_create_vulnerabilitylcm_inventory_item_required_only(self):
"""Successfully create VulnerabilityLCM with required fields only."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[1], software=self.softwares[1], inventory_item=self.inv_items[1]
)
self.assertEqual(
str(vulnerability),
"Inventory Part: 100GBASE-SR4 QSFP Transceiver - Software: Cisco IOS - 4.22.9M - CVE: CVE-2021-44228",
)
self.assertEqual(vulnerability.cve, self.cves[1])
self.assertEqual(vulnerability.software, self.softwares[1])
self.assertEqual(vulnerability.inventory_item, self.inv_items[1])
def test_create_vulnerabilitylcm_all(self):
"""Successfully create VulnerabilityLCM with all fields."""
vulnerability = VulnerabilityLCM.objects.create(
cve=self.cves[2], software=self.softwares[2], device=self.devices[2], status=self.status
)
self.assertEqual(str(vulnerability), "Device: sw3 - Software: Cisco IOS - 21.4R3 - CVE: CVE-2020-27134")
self.assertEqual(vulnerability.cve, self.cves[2])
self.assertEqual(vulnerability.software, self.softwares[2])
self.assertEqual(vulnerability.device, self.devices[2])
self.assertEqual(vulnerability.status, self.status)
class SoftwareImageLCMTestCase(TestCase):
"""Tests for the SoftwareImageLCM model."""
def setUp(self):
"""Set up base objects."""
device_platform = Platform.objects.get_or_create(name="Cisco IOS", slug="cisco_ios")[0]
self.software = SoftwareLCM.objects.create(
device_platform=device_platform,
version="17.3.3 MD",
release_date=date(2019, 1, 10),
)
manufacturer = Manufacturer.objects.create(name="Cisco", slug="cisco")
self.device_type_1 = DeviceType.objects.create(manufacturer=manufacturer, model="ASR-1000", slug="asr-1000")
self.device_type_2 = DeviceType.objects.create(manufacturer=manufacturer, model="CAT-3750", slug="cat-3750")
self.inventory_item = create_inventory_items()[0]
self.tag = Tag.objects.create(name="asr", slug="asr")
def test_create_softwareimage_required_only(self):
"""Successfully create SoftwareImageLCM with required fields only."""
softwareimage = SoftwareImageLCM(image_file_name="ios17.3.3md.img", software=self.software)
softwareimage.device_types.set([self.device_type_1])
softwareimage.save()
self.assertEqual(softwareimage.image_file_name, "ios17.3.3md.img")
self.assertEqual(softwareimage.software, self.software)
self.assertEqual(list(softwareimage.device_types.all()), [self.device_type_1])
def test_create_softwareimage_all(self):
"""Successfully create SoftwareImageLCM with all fields."""
softwareimage = SoftwareImageLCM(
image_file_name="ios17.3.3md.img",
software=self.software,
download_url="ftp://images.local/cisco/ios17.3.3md.img",
image_file_checksum="441rfabd75b0512r7fde7a7a66faa596",
default_image=True,
)
softwareimage.device_types.set([self.device_type_1])
softwareimage.inventory_items.set([self.inventory_item])
softwareimage.object_tags.set([self.tag])
softwareimage.save()
self.assertEqual(softwareimage.image_file_name, "ios17.3.3md.img")
self.assertEqual(softwareimage.software, self.software)
self.assertEqual(softwareimage.download_url, "ftp://images.local/cisco/ios17.3.3md.img")
self.assertEqual(softwareimage.image_file_checksum, "441rfabd75b0512r7fde7a7a66faa596")
self.assertEqual(softwareimage.default_image, True)
self.assertEqual(list(softwareimage.device_types.all()), [self.device_type_1])
self.assertEqual(list(softwareimage.inventory_items.all()), [self.inventory_item])
self.assertEqual(list(softwareimage.object_tags.all()), [self.tag])
self.assertEqual(str(softwareimage), f"{softwareimage.image_file_name}")
def test_validatedsoftwarelcm_valid_property(self):
"""Test behavior of the 'valid' property."""
validatedsoftwarelcm_start_only = ValidatedSoftwareLCM(
software=self.software,
start=date(2020, 4, 15),
preferred=False,
)
validatedsoftwarelcm_start_only.device_types.set([self.device_type_1])
validatedsoftwarelcm_start_only.save() | 0.758511 | 0.21712 |
import argparse
import json
import logging
import lib.db as db
import lib.logs as logs
MAPPINGS = {
'problemCategoryAlgorithmAndNetworkOptimization':
'problemLevelIntermediateAnalysisAndDesignOfAlgorithms',
'problemCategoryCompetitiveProgramming':
'problemLevelAdvancedCompetitiveProgramming',
'problemCategoryElementaryDataStructures':
'problemLevelIntermediateDataStructuresAndAlgorithms',
'problemCategoryIntroductionToProgramming':
'problemLevelBasicIntroductionToProgramming',
'problemCategoryKarelEducation':
'problemLevelBasicKarel',
'problemCategoryMathematicalProblems':
'problemLevelIntermediateMathsInProgramming',
'problemCategorySpecializedTopics':
'problemLevelAdvancedSpecializedTopics',
}
def standardize_tags(dbconn: db.Connection) -> None:
'''Reads quality_tag suggestions and updates or deletes them'''
with dbconn.cursor() as cur:
cur.execute('''
SELECT `qualitynomination_id`, `contents`
FROM `QualityNominations`
WHERE `nomination` = 'quality_tag';
''')
to_update = []
for qualitynomination_id, json_contents in cur.fetchall():
try:
contents = json.loads(json_contents)
except json.JSONDecodeError: # pylint: disable=no-member
logging.exception(
'Failed to parse contents on qualitynomination %s',
qualitynomination_id
)
continue
if 'tag' not in contents or contents['tag'] not in MAPPINGS:
continue
contents['tag'] = MAPPINGS[contents['tag']]
to_update.append((json.dumps(contents), qualitynomination_id))
# Now update records
cur.executemany(
'''
UPDATE `QualityNominations`
SET `contents` = %s
WHERE `qualitynomination_id` = %s;
''',
to_update)
logging.info('Reviewers feedback tags updated.')
def main() -> None:
'''Main entrypoint.'''
parser = argparse.ArgumentParser(
description='Tags standardization.')
db.configure_parser(parser)
logs.configure_parser(parser)
args = parser.parse_args()
logs.init(parser.prog, args)
logging.info('Started')
dbconn = db.connect(args)
try:
standardize_tags(dbconn)
dbconn.conn.commit()
except: # noqa: bare-except
logging.exception('Failed to standardize tags.')
finally:
dbconn.conn.close()
logging.info('Finished')
if __name__ == '__main__':
main()
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 | stuff/standardize_tags.py | import argparse
import json
import logging
import lib.db as db
import lib.logs as logs
MAPPINGS = {
'problemCategoryAlgorithmAndNetworkOptimization':
'problemLevelIntermediateAnalysisAndDesignOfAlgorithms',
'problemCategoryCompetitiveProgramming':
'problemLevelAdvancedCompetitiveProgramming',
'problemCategoryElementaryDataStructures':
'problemLevelIntermediateDataStructuresAndAlgorithms',
'problemCategoryIntroductionToProgramming':
'problemLevelBasicIntroductionToProgramming',
'problemCategoryKarelEducation':
'problemLevelBasicKarel',
'problemCategoryMathematicalProblems':
'problemLevelIntermediateMathsInProgramming',
'problemCategorySpecializedTopics':
'problemLevelAdvancedSpecializedTopics',
}
def standardize_tags(dbconn: db.Connection) -> None:
'''Reads quality_tag suggestions and updates or deletes them'''
with dbconn.cursor() as cur:
cur.execute('''
SELECT `qualitynomination_id`, `contents`
FROM `QualityNominations`
WHERE `nomination` = 'quality_tag';
''')
to_update = []
for qualitynomination_id, json_contents in cur.fetchall():
try:
contents = json.loads(json_contents)
except json.JSONDecodeError: # pylint: disable=no-member
logging.exception(
'Failed to parse contents on qualitynomination %s',
qualitynomination_id
)
continue
if 'tag' not in contents or contents['tag'] not in MAPPINGS:
continue
contents['tag'] = MAPPINGS[contents['tag']]
to_update.append((json.dumps(contents), qualitynomination_id))
# Now update records
cur.executemany(
'''
UPDATE `QualityNominations`
SET `contents` = %s
WHERE `qualitynomination_id` = %s;
''',
to_update)
logging.info('Reviewers feedback tags updated.')
def main() -> None:
'''Main entrypoint.'''
parser = argparse.ArgumentParser(
description='Tags standardization.')
db.configure_parser(parser)
logs.configure_parser(parser)
args = parser.parse_args()
logs.init(parser.prog, args)
logging.info('Started')
dbconn = db.connect(args)
try:
standardize_tags(dbconn)
dbconn.conn.commit()
except: # noqa: bare-except
logging.exception('Failed to standardize tags.')
finally:
dbconn.conn.close()
logging.info('Finished')
if __name__ == '__main__':
main()
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 | 0.466846 | 0.127354 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="dns-prefetch" href="https://assets-cdn.github.com">
<link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars2.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars3.githubusercontent.com">
<link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
<link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
<meta content="origin-when-cross-origin" name="referrer" />
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/frameworks-a4bf54bef6fb.css" integrity="sha512-pL9Uvvb7LMqGC8jv/AyqZ7Ya6/HTgkhZzKwEsHOdsfaW2pr3fgzqjgKUSJfYkZ/klxwHrcu+tZwtNDTuw8vH6Q==" media="all" rel="stylesheet" />
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/github-75cd24798d34.css" integrity="sha512-dc0keY00aCrRfioqcdYQ98UTSdzfsomD32SjjZxTlBWZYAyBC5Vs4iLpxP6MfpDnYjYI1l6tT9GZJLiNQX5CaA==" media="all" rel="stylesheet" />
<meta name="viewport" content="width=device-width">
<title>UofTCourseCluster/extract_course_info_from_json_resp.py at master · XuchanBao/UofTCourseCluster</title>
<meta name="description" content="GitHub is where people build software. More than 28 million people use GitHub to discover, fork, and contribute to over 79 million projects.">
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">
<meta property="fb:app_id" content="1401488693436528">
<meta content="https://avatars0.githubusercontent.com/u/14989925?s=400&v=4" property="og:image" /><meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="XuchanBao/UofTCourseCluster" property="og:title" /><meta content="https://github.com/XuchanBao/UofTCourseCluster" property="og:url" /><meta content="Contribute to UofTCourseCluster development by creating an account on GitHub." property="og:description" />
<link rel="assets" href="https://assets-cdn.github.com/">
<link rel="web-socket" href="wss://live.github.com/_sockets/VjI6MjQwNDIxNTk4OmUyZmY4YTlhMTUzODI4MTU5MTE0OTJjNTliZTYwMTA0NzAyNmVjMGZmYjNiYTQyNmUxZjMxMzgwMTk0M2ViZWQ=--2736bfb6f9b4744d95a78e5a1a6d39c711dcfb9b">
<meta name="pjax-timeout" content="1000">
<link rel="sudo-modal" href="/sessions/sudo_modal">
<meta name="request-id" content="C55F:5711:3288837:59F4E28:5A9C7C3E" data-pjax-transient>
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK<KEY>">
<meta name="google-site-verification" content="<KEY>">
<meta name="google-site-verification" content="<KEY>">
<meta name="google-analytics" content="UA-3769691-2">
<meta content="collector.githubapp.com" name="octolytics-host" /><meta content="github" name="octolytics-app-id" /><meta content="https://collector.githubapp.com/github-external/browser_event" name="octolytics-event-url" /><meta content="C55F:5711:3288837:59F4E28:5A9C7C3E" name="octolytics-dimension-request_id" /><meta content="iad" name="octolytics-dimension-region_edge" /><meta content="iad" name="octolytics-dimension-region_render" /><meta content="24879621" name="octolytics-actor-id" /><meta content="bblwq" name="octolytics-actor-login" /><meta content="924f2dd045a91cb13348c581aec59d02d02614f874a8adc2ee6a6c54312ce653" name="octolytics-actor-hash" />
<meta content="https://github.com/hydro_browser_events" name="hydro-events-url" />
<meta content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" name="analytics-location" />
<meta class="js-ga-set" name="dimension1" content="Logged In">
<meta name="hostname" content="github.com">
<meta name="user-login" content="bblwq">
<meta name="expected-hostname" content="github.com">
<meta name="js-proxy-site-detection-payload" content="<KEY>>
<meta name="enabled-features" content="UNIVERSE_BANNER,FREE_TRIALS,MARKETPLACE_INSIGHTS,MARKETPLACE_INSIGHTS_CONVERSION_PERCENTAGES,JS_ROLLUP">
<meta name="html-safe-nonce" content="85c663690f9572ece1479db189f5f17d80e0affb">
<meta http-equiv="x-pjax-version" content="b0ac2aa1a7ed8a264683e3d563f09f82">
<link href="https://github.com/XuchanBao/UofTCourseCluster/commits/master.atom?token=<PASSWORD>sgAy3msH<PASSWORD>X-oFW5awks64qa7UwA%3D%3D" rel="alternate" title="Recent Commits to UofTCourseCluster:master" type="application/atom+xml">
<meta name="description" content="Contribute to UofTCourseCluster development by creating an account on GitHub.">
<meta name="go-import" content="github.com/XuchanBao/UofTCourseCluster git https://github.com/XuchanBao/UofTCourseCluster.git">
<meta content="14989925" name="octolytics-dimension-user_id" /><meta content="XuchanBao" name="octolytics-dimension-user_login" /><meta content="109784626" name="octolytics-dimension-repository_id" /><meta content="XuchanBao/UofTCourseCluster" name="octolytics-dimension-repository_nwo" /><meta content="false" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="109784626" name="octolytics-dimension-repository_network_root_id" /><meta content="XuchanBao/UofTCourseCluster" name="octolytics-dimension-repository_network_root_nwo" /><meta content="false" name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" />
<link rel="canonical" href="https://github.com/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000">
<link rel="icon" type="image/x-icon" class="js-site-favicon" href="https://assets-cdn.github.com/favicon.ico">
<meta name="theme-color" content="#1e2327">
<meta name="u2f-support" content="true">
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-in env-production page-blob">
<div class="position-relative js-header-wrapper ">
<a href="#start-of-content" tabindex="1" class="bg-black text-white p-3 show-on-focus js-skip-to-content">Skip to content</a>
<div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div>
<header class="Header f5" role="banner">
<div class="d-flex px-3 flex-justify-between container-lg">
<div class="d-flex flex-justify-between ">
<div class="">
<a class="header-logo-invertocat" href="https://github.com/" data-hotkey="g d" aria-label="Homepage" data-ga-click="Header, go to dashboard, icon:logo">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="32" version="1.1" viewBox="0 0 16 16" width="32"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 192.168.3.11 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
</div>
</div>
<div class="HeaderMenu d-flex flex-justify-between flex-auto">
<div class="d-flex">
<div class="">
<div class="header-search scoped-search site-scoped-search js-site-search" role="search">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/search" class="js-site-search-form" data-scoped-search-url="/XuchanBao/UofTCourseCluster/search" data-unscoped-search-url="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<label class="form-control header-search-wrapper js-chromeless-input-container">
<a href="/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py" class="header-search-scope no-underline">This repository</a>
<input type="text"
class="form-control header-search-input js-site-search-focus js-site-search-field is-clearable"
data-hotkey="s"
name="q"
value=""
placeholder="Search"
aria-label="Search this repository"
data-unscoped-placeholder="Search GitHub"
data-scoped-placeholder="Search"
autocapitalize="off">
<input type="hidden" class="js-site-search-type-field" name="type" >
</label>
</form></div>
</div>
<ul class="d-flex pl-2 flex-items-center text-bold list-style-none" role="navigation">
<li>
<a href="/pulls" aria-label="Pull requests you created" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:pulls context:user" data-hotkey="g p" data-selected-links="/pulls /pulls/assigned /pulls/mentioned /pulls">
Pull requests
</a> </li>
<li>
<a href="/issues" aria-label="Issues you created" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:issues context:user" data-hotkey="g i" data-selected-links="/issues /issues/assigned /issues/mentioned /issues">
Issues
</a> </li>
<li>
<a href="/marketplace" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:marketplace context:user" data-selected-links=" /marketplace">
Marketplace
</a> </li>
<li>
<a href="/explore" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship showcases showcases_search showcases_landing /explore">
Explore
</a> </li>
</ul>
</div>
<div class="d-flex">
<ul class="user-nav d-flex flex-items-center list-style-none" id="user-links">
<li class="dropdown js-menu-container">
<span class="d-inline-block px-2">
</span>
</li>
<li class="dropdown js-menu-container">
<details class="dropdown-details details-reset js-dropdown-details d-flex px-2 flex-items-center">
<summary class="HeaderNavlink"
aria-label="Create new…"
data-ga-click="Header, create new, icon:add">
<svg aria-hidden="true" class="octicon octicon-plus float-left mr-1 mt-1" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 9H7v5H5V9H0V7h5V2h2v5h5z"/></svg>
<span class="dropdown-caret mt-1"></span>
</summary>
<ul class="dropdown-menu dropdown-menu-sw">
<a class="dropdown-item" href="/new" data-ga-click="Header, create new repository">
New repository
</a>
<a class="dropdown-item" href="/new/import" data-ga-click="Header, import a repository">
Import repository
</a>
<a class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, create new gist">
New gist
</a>
<a class="dropdown-item" href="/organizations/new" data-ga-click="Header, create new organization">
New organization
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">
<span title="XuchanBao/UofTCourseCluster">This repository</span>
</div>
<a class="dropdown-item" href="/XuchanBao/UofTCourseCluster/issues/new" data-ga-click="Header, create new issue">
New issue
</a>
</ul>
</details>
</li>
<li class="dropdown js-menu-container">
<details class="dropdown-details details-reset js-dropdown-details d-flex pl-2 flex-items-center">
<summary class="HeaderNavlink name mt-1"
aria-label="View profile and more"
data-ga-click="Header, show menu, icon:avatar">
<img alt="@bblwq" class="avatar float-left mr-1" src="https://avatars1.githubusercontent.com/u/24879621?s=40&v=4" height="20" width="20">
<span class="dropdown-caret"></span>
</summary>
<ul class="dropdown-menu dropdown-menu-sw">
<li class="dropdown-header header-nav-current-user css-truncate">
Signed in as <strong class="css-truncate-target">bblwq</strong>
</li>
<li class="dropdown-divider"></li>
<li><a class="dropdown-item" href="/bblwq" data-ga-click="Header, go to profile, text:your profile">
Your profile
</a></li>
<li><a class="dropdown-item" href="/bblwq?tab=stars" data-ga-click="Header, go to starred repos, text:your stars">
Your stars
</a></li>
<li><a class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, your gists, text:your gists">Your gists</a></li>
<li class="dropdown-divider"></li>
<li><a class="dropdown-item" href="https://help.github.com" data-ga-click="Header, go to help, text:help">
Help
</a></li>
<li><a class="dropdown-item" href="/settings/profile" data-ga-click="Header, go to settings, icon:settings">
Settings
</a></li>
<li><!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/logout" class="logout-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form></li>
</ul>
</details>
</li>
</ul>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/logout" class="sr-only right-0" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form> </div>
</div>
</div>
</header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container">
</div>
<div role="main" class="application-main ">
<div itemscope itemtype="http://schema.org/SoftwareSourceCode" class="">
<div id="js-repo-pjax-container" data-pjax-container >
<div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav ">
<div class="repohead-details-container clearfix container">
<ul class="pagehead-actions">
<li>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/notifications/subscribe" class="js-social-container" data-autosubmit="true" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div> <input class="form-control" id="repository_id" name="repository_id" type="hidden" value="109784626" />
<div class="select-menu js-menu-container js-select-menu">
<a href="/XuchanBao/UofTCourseCluster/subscription"
class="btn btn-sm btn-with-count select-menu-button js-menu-target"
role="button"
aria-haspopup="true"
aria-expanded="false"
aria-label="Toggle repository notifications menu"
data-ga-click="Repository, click Watch settings, action:blob#show">
<span class="js-select-button">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</a>
<a class="social-count js-social-count"
href="/XuchanBao/UofTCourseCluster/watchers"
aria-label="1 user is watching this repository">
1
</a>
<div class="select-menu-modal-holder">
<div class="select-menu-modal subscription-menu-modal js-menu-content">
<div class="select-menu-header js-navigation-enable" tabindex="-1">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
<span class="select-menu-title">Notifications</span>
</div>
<div class="select-menu-list js-navigation-container" role="menu">
<div class="select-menu-item js-navigation-item selected" role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input checked="checked" id="do_included" name="do" type="radio" value="included" />
<span class="select-menu-item-heading">Not watching</span>
<span class="description">Be notified when participating or @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input id="do_subscribed" name="do" type="radio" value="subscribed" />
<span class="select-menu-item-heading">Watching</span>
<span class="description">Be notified of all conversations.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Unwatch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input id="do_ignore" name="do" type="radio" value="ignore" />
<span class="select-menu-item-heading">Ignoring</span>
<span class="description">Never be notified.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-mute" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8 2.81v10.38c0 .67-.81 1-1.28.53L3 10H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h2l3.72-3.72C7.19 1.81 8 2.14 8 2.81zm7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06L11.44 8 9.47 9.97l1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06L13.56 8l1.97-1.97z"/></svg>
Stop ignoring
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container on">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/unstar" class="starred js-social-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Unstar this repository" title="Unstar XuchanBao/UofTCourseCluster"
data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Unstar
</button>
<a class="social-count js-social-count" href="/XuchanBao/UofTCourseCluster/stargazers"
aria-label="1 user starred this repository">
1
</a>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/star" class="unstarred js-social-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Star this repository" title="Star XuchanBao/UofTCourseCluster"
data-ga-click="Repository, click star button, action:blob#show; text:Star">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Star
</button>
<a class="social-count js-social-count" href="/XuchanBao/UofTCourseCluster/stargazers"
aria-label="1 user starred this repository">
1
</a>
</form> </div>
</li>
<li>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/fork" class="btn-with-count" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button
type="submit"
class="btn btn-sm btn-with-count"
data-ga-click="Repository, show fork modal, action:blob#show; text:Fork"
title="Fork your own copy of XuchanBao/UofTCourseCluster to your account"
aria-label="Fork your own copy of XuchanBao/UofTCourseCluster to your account">
<svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
Fork
</button>
</form>
<a href="/XuchanBao/UofTCourseCluster/network" class="social-count"
aria-label="0 users forked this repository">
0
</a>
</li>
</ul>
<h1 class="private ">
<svg aria-hidden="true" class="octicon octicon-lock" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M4 13H3v-1h1v1zm8-6v7c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h1V4c0-2.2 1.8-4 4-4s4 1.8 4 4v2h1c.55 0 1 .45 1 1zM3.8 6h4.41V4c0-1.22-.98-2.2-2.2-2.2-1.22 0-2.2.98-2.2 2.2v2H3.8zM11 7H2v7h9V7zM4 8H3v1h1V8zm0 2H3v1h1v-1z"/></svg>
<span class="author" itemprop="author"><a href="/XuchanBao" class="url fn" rel="author">XuchanBao</a></span><!--
--><span class="path-divider">/</span><!--
--><strong itemprop="name"><a href="/XuchanBao/UofTCourseCluster" data-pjax="#js-repo-pjax-container">UofTCourseCluster</a></strong>
<span class="Label Label--outline v-align-middle">Private</span>
</h1>
</div>
<nav class="reponav js-repo-nav js-sidenav-container-pjax container"
itemscope
itemtype="http://schema.org/BreadcrumbList"
role="navigation"
data-pjax="#js-repo-pjax-container">
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /XuchanBao/UofTCourseCluster" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg>
<span itemprop="name">Code</span>
<meta itemprop="position" content="1">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /XuchanBao/UofTCourseCluster/issues" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg>
<span itemprop="name">Issues</span>
<span class="Counter">0</span>
<meta itemprop="position" content="2">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls checks /XuchanBao/UofTCourseCluster/pulls" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<span itemprop="name">Pull requests</span>
<span class="Counter">0</span>
<meta itemprop="position" content="3">
</a> </span>
<a href="/XuchanBao/UofTCourseCluster/projects" class="js-selected-navigation-item reponav-item" data-hotkey="g b" data-selected-links="repo_projects new_repo_project repo_project /XuchanBao/UofTCourseCluster/projects">
<svg aria-hidden="true" class="octicon octicon-project" height="16" version="1.1" viewBox="0 0 15 16" width="15"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
Projects
<span class="Counter" >0</span>
</a>
<a href="/XuchanBao/UofTCourseCluster/wiki" class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /XuchanBao/UofTCourseCluster/wiki">
<svg aria-hidden="true" class="octicon octicon-book" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z"/></svg>
Wiki
</a>
<a href="/XuchanBao/UofTCourseCluster/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors dependency_graph pulse /XuchanBao/UofTCourseCluster/pulse">
<svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg>
Insights
</a>
</nav>
</div>
<div class="container new-discussion-timeline experiment-repo-nav ">
<div class="repository-content ">
<a href="/XuchanBao/UofTCourseCluster/blob/d98adeba89f6a955803828959146032339afe258/scraping/extract_course_info_from_json_resp.py" class="d-none js-permalink-shortcut" data-hotkey="y">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:2b5c6dfa8bf9101e6ebfebe3c052eadc -->
<div class="file-navigation">
<div class="select-menu branch-select-menu js-menu-container js-select-menu float-left">
<button class=" btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w"
type="button" aria-label="Switch branches or tags" aria-expanded="false" aria-haspopup="true">
<i>Branch:</i>
<span class="js-select-button css-truncate-target">master</span>
</button>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax>
<div class="select-menu-modal">
<div class="select-menu-header">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
<span class="select-menu-title">Switch branches/tags</span>
</div>
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" aria-label="Find or create a branch…" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Find or create a branch…">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" data-filter-placeholder="Find or create a branch…" class="js-select-menu-tab" role="tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a>
</li>
</ul>
</div>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/bblwq/scraping/extract_course_info_from_json_resp.py"
data-name="bblwq"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
bblwq
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/jenny-cluster-algo-experiments/scraping/extract_course_info_from_json_resp.py"
data-name="jenny-cluster-algo-experiments"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
jenny-cluster-algo-experiments
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/jenny-scrapy/scraping/extract_course_info_from_json_resp.py"
data-name="jenny-scrapy"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
jenny-scrapy
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open selected"
href="/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py"
data-name="master"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
master
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/merge-sraped-data/scraping/extract_course_info_from_json_resp.py"
data-name="merge-sraped-data"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
merge-sraped-data
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/zoebranch/scraping/extract_course_info_from_json_resp.py"
data-name="zoebranch"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
zoebranch
</span>
</a>
</div>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/branches" class="js-create-branch select-menu-item select-menu-new-item-form js-navigation-item js-new-item-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<svg aria-hidden="true" class="octicon octicon-git-branch select-menu-item-icon" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M10 5c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v.3c-.02.52-.23.98-.63 1.38-.4.4-.86.61-1.38.63-.83.02-1.48.16-2 .45V4.72a1.993 1.993 0 0 0-1-3.72C.88 1 0 1.89 0 3a2 2 0 0 0 1 1.72v6.56c-.59.35-1 .99-1 1.72 0 1.11.89 2 2 2 1.11 0 2-.89 2-2 0-.53-.2-1-.53-1.36.09-.06.48-.41.59-.47.25-.11.56-.17.94-.17 1.05-.05 1.95-.45 2.75-1.25S8.95 7.77 9 6.73h-.02C9.59 6.37 10 5.73 10 5zM2 1.8c.66 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2C1.35 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2zm0 12.41c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm6-8c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Create branch: <span class="js-new-item-name"></span></span>
<span class="description">from ‘master’</span>
</div>
<input type="hidden" name="name" id="name" class="js-new-item-value">
<input type="hidden" name="branch" id="branch" value="master">
<input type="hidden" name="path" id="path" value="scraping/extract_course_info_from_json_resp.py">
</form>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div>
</div>
</div>
</div>
<div class="BtnGroup float-right">
<a href="/XuchanBao/UofTCourseCluster/find/master"
class="js-pjax-capture-input btn btn-sm BtnGroup-item"
data-pjax
data-hotkey="t">
Find file
</a>
<clipboard-copy
for="blob-path"
role="button"
aria-label="Copy file path to clipboard"
class="btn btn-sm BtnGroup-item tooltipped tooltipped-s"
data-copied-hint="Copied!">
Copy path
</clipboard-copy>
</div>
<div id="blob-path" class="breadcrumb">
<span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/XuchanBao/UofTCourseCluster" data-pjax="true"><span>UofTCourseCluster</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a href="/XuchanBao/UofTCourseCluster/tree/master/scraping" data-pjax="true"><span>scraping</span></a></span><span class="separator">/</span><strong class="final-path">extract_course_info_from_json_resp.py</strong>
</div>
</div>
<div class="commit-tease">
<span class="float-right">
<a class="commit-tease-sha" href="/XuchanBao/UofTCourseCluster/commit/e991e0b6e0953f98713671fa63d51611855060e0" data-pjax>
e991e0b
</a>
<relative-time datetime="2018-01-25T02:36:51Z">Jan 24, 2018</relative-time>
</span>
<div>
<img alt="" class="avatar" data-canonical-src="https://0.gravatar.com/avatar/00f9cd9ff503ba4ccd3e0f3eca760d1c?d=https%3A%2F%2Fassets-cdn.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png&r=g&s=140" height="20" src="https://camo.githubusercontent.com/760787ee917f1d55be81bb9fe3294b5ef6180b80/68747470733a2f2f302e67726176617461722e636f6d2f6176617461722f30306639636439666635303362613463636433653066336563613736306431633f643d68747470732533412532462532466173736574732d63646e2e6769746875622e636f6d253246696d6167657325324667726176617461727325324667726176617461722d757365722d3432302e706e6726723d6726733d313430" width="20" />
<span class="user-mention">xb1</span>
<a href="/XuchanBao/UofTCourseCluster/commit/e991e0b6e0953f98713671fa63d51611855060e0" class="message" data-pjax="true" title="Scrape CSC courses">Scrape CSC courses</a>
</div>
<div class="commit-tease-contributors">
<button type="button" class="btn-link muted-link contributors-toggle" data-facebox="#blob_contributors_box">
<strong>0</strong>
contributors
</button>
</div>
<div id="blob_contributors_box" style="display:none">
<h2 class="facebox-header" data-facebox-id="facebox-header">Users who have contributed to this file</h2>
<ul class="facebox-user-list" data-facebox-id="facebox-description">
</ul>
</div>
</div>
<div class="file">
<div class="file-header">
<div class="file-actions">
<div class="BtnGroup">
<a href="/XuchanBao/UofTCourseCluster/raw/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm BtnGroup-item" id="raw-url">Raw</a>
<a href="/XuchanBao/UofTCourseCluster/blame/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b">Blame</a>
<a href="/XuchanBao/UofTCourseCluster/commits/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm BtnGroup-item" rel="nofollow">History</a>
</div>
<a class="btn-octicon tooltipped tooltipped-nw"
href="github-windows://openRepo/https://github.com/XuchanBao/UofTCourseCluster?branch=master&filepath=scraping%2Fextract_course_info_from_json_resp.py"
aria-label="Open this file in GitHub Desktop"
data-ga-click="Repository, open with desktop, type:windows">
<svg aria-hidden="true" class="octicon octicon-device-desktop" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"/></svg>
</a>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/edit/master/scraping/extract_course_info_from_json_resp.py" class="inline-form js-update-url-with-hash" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button class="btn-octicon tooltipped tooltipped-nw" type="submit"
aria-label="Edit this file" data-hotkey="e" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-pencil" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg>
</button>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/delete/master/scraping/extract_course_info_from_json_resp.py" class="inline-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button class="btn-octicon btn-octicon-danger tooltipped tooltipped-nw" type="submit"
aria-label="Delete this file" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-trashcan" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg>
</button>
</form> </div>
<div class="file-info">
47 lines (36 sloc)
<span class="file-info-divider"></span>
1.16 KB
</div>
</div>
<div itemprop="text" class="blob-wrapper data type-python">
<table class="highlight tab-size js-file-line-container" data-tab-size="8">
<tr>
<td id="L1" class="blob-num js-line-number" data-line-number="1"></td>
<td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-k">import</span> pickle</td>
</tr>
<tr>
<td id="L2" class="blob-num js-line-number" data-line-number="2"></td>
<td id="LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L3" class="blob-num js-line-number" data-line-number="3"></td>
<td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">INDEX_TO_FEATURE</span> <span class="pl-k">=</span> {</td>
</tr>
<tr>
<td id="L4" class="blob-num js-line-number" data-line-number="4"></td>
<td id="LC4" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">0</span>: <span class="pl-c1">None</span>,</td>
</tr>
<tr>
<td id="L5" class="blob-num js-line-number" data-line-number="5"></td>
<td id="LC5" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">1</span>: <span class="pl-s"><span class="pl-pds">"</span>code<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L6" class="blob-num js-line-number" data-line-number="6"></td>
<td id="LC6" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">2</span>: <span class="pl-s"><span class="pl-pds">"</span>title<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L7" class="blob-num js-line-number" data-line-number="7"></td>
<td id="LC7" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">3</span>: <span class="pl-s"><span class="pl-pds">"</span>credit<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L8" class="blob-num js-line-number" data-line-number="8"></td>
<td id="LC8" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">4</span>: <span class="pl-s"><span class="pl-pds">"</span>location<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L9" class="blob-num js-line-number" data-line-number="9"></td>
<td id="LC9" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">5</span>: <span class="pl-s"><span class="pl-pds">"</span>department<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L10" class="blob-num js-line-number" data-line-number="10"></td>
<td id="LC10" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">6</span>: <span class="pl-s"><span class="pl-pds">"</span>session<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L11" class="blob-num js-line-number" data-line-number="11"></td>
<td id="LC11" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">7</span>: <span class="pl-s"><span class="pl-pds">"</span>campus<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L12" class="blob-num js-line-number" data-line-number="12"></td>
<td id="LC12" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">8</span>: <span class="pl-s"><span class="pl-pds">"</span>days of week<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L13" class="blob-num js-line-number" data-line-number="13"></td>
<td id="LC13" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">9</span>: <span class="pl-s"><span class="pl-pds">"</span>level<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L14" class="blob-num js-line-number" data-line-number="14"></td>
<td id="LC14" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">10</span>: <span class="pl-s"><span class="pl-pds">"</span>time of day<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L15" class="blob-num js-line-number" data-line-number="15"></td>
<td id="LC15" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="L16" class="blob-num js-line-number" data-line-number="16"></td>
<td id="LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L17" class="blob-num js-line-number" data-line-number="17"></td>
<td id="LC17" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">JSON_KEYNAME</span> <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">"</span>aaData<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L18" class="blob-num js-line-number" data-line-number="18"></td>
<td id="LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L19" class="blob-num js-line-number" data-line-number="19"></td>
<td id="LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L20" class="blob-num js-line-number" data-line-number="20"></td>
<td id="LC20" class="blob-code blob-code-inner js-file-line"><span class="pl-k">def</span> <span class="pl-en">extract_course_code</span>(<span class="pl-smi">html_string</span>):</td>
</tr>
<tr>
<td id="L21" class="blob-num js-line-number" data-line-number="21"></td>
<td id="LC21" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> html_string.split(<span class="pl-s"><span class="pl-pds">'</span></a><span class="pl-pds">'</span></span>)[<span class="pl-c1">0</span>].split(<span class="pl-s"><span class="pl-pds">'</span>><span class="pl-pds">'</span></span>)[<span class="pl-k">-</span><span class="pl-c1">1</span>]</td>
</tr>
<tr>
<td id="L22" class="blob-num js-line-number" data-line-number="22"></td>
<td id="LC22" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L23" class="blob-num js-line-number" data-line-number="23"></td>
<td id="LC23" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L24" class="blob-num js-line-number" data-line-number="24"></td>
<td id="LC24" class="blob-code blob-code-inner js-file-line"><span class="pl-k">def</span> <span class="pl-en">extract_course_info_from_resp_and_save</span>(<span class="pl-smi">resp_filename</span>, <span class="pl-smi">save_filename</span>):</td>
</tr>
<tr>
<td id="L25" class="blob-num js-line-number" data-line-number="25"></td>
<td id="LC25" class="blob-code blob-code-inner js-file-line"> resp_dict <span class="pl-k">=</span> pickle.load(<span class="pl-c1">open</span>(resp_filename, <span class="pl-s"><span class="pl-pds">'</span>rb<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L26" class="blob-num js-line-number" data-line-number="26"></td>
<td id="LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L27" class="blob-num js-line-number" data-line-number="27"></td>
<td id="LC27" class="blob-code blob-code-inner js-file-line"> all_courses <span class="pl-k">=</span> {}</td>
</tr>
<tr>
<td id="L28" class="blob-num js-line-number" data-line-number="28"></td>
<td id="LC28" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> course_info_list <span class="pl-k">in</span> resp_dict[<span class="pl-c1">JSON_KEYNAME</span>]:</td>
</tr>
<tr>
<td id="L29" class="blob-num js-line-number" data-line-number="29"></td>
<td id="LC29" class="blob-code blob-code-inner js-file-line"> course_info_dict <span class="pl-k">=</span> {}</td>
</tr>
<tr>
<td id="L30" class="blob-num js-line-number" data-line-number="30"></td>
<td id="LC30" class="blob-code blob-code-inner js-file-line"> course_key <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">"</span>default_key<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L31" class="blob-num js-line-number" data-line-number="31"></td>
<td id="LC31" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> i <span class="pl-k">in</span> <span class="pl-c1">range</span>(<span class="pl-c1">len</span>(course_info_list)):</td>
</tr>
<tr>
<td id="L32" class="blob-num js-line-number" data-line-number="32"></td>
<td id="LC32" class="blob-code blob-code-inner js-file-line"> feature <span class="pl-k">=</span> <span class="pl-c1">INDEX_TO_FEATURE</span>[i]</td>
</tr>
<tr>
<td id="L33" class="blob-num js-line-number" data-line-number="33"></td>
<td id="LC33" class="blob-code blob-code-inner js-file-line"> value <span class="pl-k">=</span> course_info_list[i]</td>
</tr>
<tr>
<td id="L34" class="blob-num js-line-number" data-line-number="34"></td>
<td id="LC34" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> <span class="pl-k">not</span> feature:</td>
</tr>
<tr>
<td id="L35" class="blob-num js-line-number" data-line-number="35"></td>
<td id="LC35" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">continue</span></td>
</tr>
<tr>
<td id="L36" class="blob-num js-line-number" data-line-number="36"></td>
<td id="LC36" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> feature <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">"</span>code<span class="pl-pds">"</span></span>:</td>
</tr>
<tr>
<td id="L37" class="blob-num js-line-number" data-line-number="37"></td>
<td id="LC37" class="blob-code blob-code-inner js-file-line"> value <span class="pl-k">=</span> extract_course_code(value)</td>
</tr>
<tr>
<td id="L38" class="blob-num js-line-number" data-line-number="38"></td>
<td id="LC38" class="blob-code blob-code-inner js-file-line"> course_key <span class="pl-k">=</span> value</td>
</tr>
<tr>
<td id="L39" class="blob-num js-line-number" data-line-number="39"></td>
<td id="LC39" class="blob-code blob-code-inner js-file-line"> course_info_dict[feature] <span class="pl-k">=</span> value</td>
</tr>
<tr>
<td id="L40" class="blob-num js-line-number" data-line-number="40"></td>
<td id="LC40" class="blob-code blob-code-inner js-file-line"> all_courses[course_key] <span class="pl-k">=</span> course_info_dict</td>
</tr>
<tr>
<td id="L41" class="blob-num js-line-number" data-line-number="41"></td>
<td id="LC41" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L42" class="blob-num js-line-number" data-line-number="42"></td>
<td id="LC42" class="blob-code blob-code-inner js-file-line"> pickle.dump(all_courses, <span class="pl-c1">open</span>(save_filename, <span class="pl-s"><span class="pl-pds">'</span>wb<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L43" class="blob-num js-line-number" data-line-number="43"></td>
<td id="LC43" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L44" class="blob-num js-line-number" data-line-number="44"></td>
<td id="LC44" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L45" class="blob-num js-line-number" data-line-number="45"></td>
<td id="LC45" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> <span class="pl-c1">__name__</span> <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">"</span>__main__<span class="pl-pds">"</span></span>:</td>
</tr>
<tr>
<td id="L46" class="blob-num js-line-number" data-line-number="46"></td>
<td id="LC46" class="blob-code blob-code-inner js-file-line"> extract_course_info_from_resp_and_save(<span class="pl-s"><span class="pl-pds">"</span>csc_resp.p<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>csc_courses.p<span class="pl-pds">"</span></span>)</td>
</tr>
</table>
<div class="BlobToolbar position-absolute js-file-line-actions dropdown js-menu-container js-select-menu d-none" aria-hidden="true">
<button class="btn-octicon ml-0 px-2 p-0 bg-white border border-gray-dark rounded-1 dropdown-toggle js-menu-target" id="js-file-line-action-button" type="button" aria-expanded="false" aria-haspopup="true" aria-label="Inline file action toolbar" aria-controls="inline-file-actions">
<svg aria-hidden="true" class="octicon octicon-kebab-horizontal" height="16" version="1.1" viewBox="0 0 13 16" width="13"><path fill-rule="evenodd" d="M1.5 9a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/></svg>
</button>
<div class="dropdown-menu-content js-menu-content" id="inline-file-actions">
<ul class="BlobToolbar-dropdown dropdown-menu dropdown-menu-se mt-2">
<li><a class="js-zeroclipboard dropdown-item" style="cursor:pointer;" id="js-copy-lines" data-original-text="Copy lines">Copy lines</a></li>
<li><a class="js-zeroclipboard dropdown-item" id= "js-copy-permalink" style="cursor:pointer;" data-original-text="Copy permalink">Copy permalink</a></li>
<li><a href="/XuchanBao/UofTCourseCluster/blame/d98adeba89f6a955803828959146032339afe258/scraping/extract_course_info_from_json_resp.py" class="dropdown-item js-update-url-with-hash" id="js-view-git-blame">View git blame</a></li>
<li><a href="/XuchanBao/UofTCourseCluster/issues/new" class="dropdown-item" id="js-new-issue">Open new issue</a></li>
</ul>
</div>
</div>
</div>
</div>
<button type="button" data-facebox="#jump-to-line" data-facebox-class="linejump" data-hotkey="l" class="d-none">Jump to Line</button>
<div id="jump-to-line" style="display:none">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="" class="js-jump-to-line-form" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<input class="form-control linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus>
<button type="submit" class="btn">Go</button>
</form> </div>
</div>
<div class="modal-backdrop js-touch-events"></div>
</div>
</div>
</div>
</div>
<div class="footer container-lg px-3" role="contentinfo">
<div class="position-relative d-flex flex-justify-between py-6 mt-6 f6 text-gray border-top border-gray-light ">
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3">© 2018 <span title="0.29434s from unicorn-512311803-vxzxm">GitHub</span>, Inc.</li>
<li class="mr-3"><a href="https://help.github.com/articles/github-terms-of-service/" data-ga-click="Footer, go to terms, text:terms">Terms</a></li>
<li class="mr-3"><a href="https://github.com/site/privacy" data-ga-click="Footer, go to privacy, text:privacy">Privacy</a></li>
<li class="mr-3"><a href="https://help.github.com/articles/github-security/" data-ga-click="Footer, go to security, text:security">Security</a></li>
<li class="mr-3"><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li>
<li><a href="https://help.github.com" data-ga-click="Footer, go to help, text:help">Help</a></li>
</ul>
<a href="https://github.com" aria-label="Homepage" class="footer-octicon" title="GitHub">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="24" version="1.1" viewBox="0 0 16 16" width="24"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 192.168.3.11 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 172.16.31.10.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 192.168.3.11.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3"><a href="https://github.com/contact" data-ga-click="Footer, go to contact, text:contact">Contact GitHub</a></li>
<li class="mr-3"><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li>
<li class="mr-3"><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li>
<li class="mr-3"><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li>
<li class="mr-3"><a href="https://github.com/blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li>
<li><a href="https://github.com/about" data-ga-click="Footer, go to about, text:about">About</a></li>
</ul>
</div>
</div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg>
<button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
</button>
You can't perform that action at this time.
</div>
<script crossorigin="anonymous" integrity="sha512-6oz7cTsS3E5enQjh4gWKU23tC78zIZqVJ1o5zMLCsAv5EEnmNsopwszDz7zx5IGWXU+H+sqeC5pHbt1Yxmh+sw==" src="https://assets-cdn.github.com/assets/frameworks-ea8cfb713b12.js" type="application/javascript"></script>
<script async="async" crossorigin="anonymous" integrity="sha512-9c2rT9XyOnZ3jV2cbM+DuSR1OpEKUJGUDkr0v+haFwhmfxPPd1UeLatTZ0I4To4RYxJwF02Os/o7LzvuSUK+VA==" src="https://assets-cdn.github.com/assets/github-f5cdab4fd5f2.js" type="application/javascript"></script>
<div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg>
<span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span>
<span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span>
</div>
<div class="facebox" id="facebox" style="display:none;">
<div class="facebox-popup">
<div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description">
</div>
<button type="button" class="facebox-close js-facebox-close" aria-label="Close modal">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
</button>
</div>
</div>
</body>
</html> | scraping/extract_course_info_from_json_resp.py | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="dns-prefetch" href="https://assets-cdn.github.com">
<link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars2.githubusercontent.com">
<link rel="dns-prefetch" href="https://avatars3.githubusercontent.com">
<link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
<link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
<meta content="origin-when-cross-origin" name="referrer" />
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/frameworks-a4bf54bef6fb.css" integrity="sha512-pL9Uvvb7LMqGC8jv/AyqZ7Ya6/HTgkhZzKwEsHOdsfaW2pr3fgzqjgKUSJfYkZ/klxwHrcu+tZwtNDTuw8vH6Q==" media="all" rel="stylesheet" />
<link crossorigin="anonymous" href="https://assets-cdn.github.com/assets/github-75cd24798d34.css" integrity="sha512-dc0keY00aCrRfioqcdYQ98UTSdzfsomD32SjjZxTlBWZYAyBC5Vs4iLpxP6MfpDnYjYI1l6tT9GZJLiNQX5CaA==" media="all" rel="stylesheet" />
<meta name="viewport" content="width=device-width">
<title>UofTCourseCluster/extract_course_info_from_json_resp.py at master · XuchanBao/UofTCourseCluster</title>
<meta name="description" content="GitHub is where people build software. More than 28 million people use GitHub to discover, fork, and contribute to over 79 million projects.">
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">
<meta property="fb:app_id" content="1401488693436528">
<meta content="https://avatars0.githubusercontent.com/u/14989925?s=400&v=4" property="og:image" /><meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="XuchanBao/UofTCourseCluster" property="og:title" /><meta content="https://github.com/XuchanBao/UofTCourseCluster" property="og:url" /><meta content="Contribute to UofTCourseCluster development by creating an account on GitHub." property="og:description" />
<link rel="assets" href="https://assets-cdn.github.com/">
<link rel="web-socket" href="wss://live.github.com/_sockets/VjI6MjQwNDIxNTk4OmUyZmY4YTlhMTUzODI4MTU5MTE0OTJjNTliZTYwMTA0NzAyNmVjMGZmYjNiYTQyNmUxZjMxMzgwMTk0M2ViZWQ=--2736bfb6f9b4744d95a78e5a1a6d39c711dcfb9b">
<meta name="pjax-timeout" content="1000">
<link rel="sudo-modal" href="/sessions/sudo_modal">
<meta name="request-id" content="C55F:5711:3288837:59F4E28:5A9C7C3E" data-pjax-transient>
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK<KEY>">
<meta name="google-site-verification" content="<KEY>">
<meta name="google-site-verification" content="<KEY>">
<meta name="google-analytics" content="UA-3769691-2">
<meta content="collector.githubapp.com" name="octolytics-host" /><meta content="github" name="octolytics-app-id" /><meta content="https://collector.githubapp.com/github-external/browser_event" name="octolytics-event-url" /><meta content="C55F:5711:3288837:59F4E28:5A9C7C3E" name="octolytics-dimension-request_id" /><meta content="iad" name="octolytics-dimension-region_edge" /><meta content="iad" name="octolytics-dimension-region_render" /><meta content="24879621" name="octolytics-actor-id" /><meta content="bblwq" name="octolytics-actor-login" /><meta content="924f2dd045a91cb13348c581aec59d02d02614f874a8adc2ee6a6c54312ce653" name="octolytics-actor-hash" />
<meta content="https://github.com/hydro_browser_events" name="hydro-events-url" />
<meta content="/<user-name>/<repo-name>/blob/show" data-pjax-transient="true" name="analytics-location" />
<meta class="js-ga-set" name="dimension1" content="Logged In">
<meta name="hostname" content="github.com">
<meta name="user-login" content="bblwq">
<meta name="expected-hostname" content="github.com">
<meta name="js-proxy-site-detection-payload" content="<KEY>>
<meta name="enabled-features" content="UNIVERSE_BANNER,FREE_TRIALS,MARKETPLACE_INSIGHTS,MARKETPLACE_INSIGHTS_CONVERSION_PERCENTAGES,JS_ROLLUP">
<meta name="html-safe-nonce" content="85c663690f9572ece1479db189f5f17d80e0affb">
<meta http-equiv="x-pjax-version" content="b0ac2aa1a7ed8a264683e3d563f09f82">
<link href="https://github.com/XuchanBao/UofTCourseCluster/commits/master.atom?token=<PASSWORD>sgAy3msH<PASSWORD>X-oFW5awks64qa7UwA%3D%3D" rel="alternate" title="Recent Commits to UofTCourseCluster:master" type="application/atom+xml">
<meta name="description" content="Contribute to UofTCourseCluster development by creating an account on GitHub.">
<meta name="go-import" content="github.com/XuchanBao/UofTCourseCluster git https://github.com/XuchanBao/UofTCourseCluster.git">
<meta content="14989925" name="octolytics-dimension-user_id" /><meta content="XuchanBao" name="octolytics-dimension-user_login" /><meta content="109784626" name="octolytics-dimension-repository_id" /><meta content="XuchanBao/UofTCourseCluster" name="octolytics-dimension-repository_nwo" /><meta content="false" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="109784626" name="octolytics-dimension-repository_network_root_id" /><meta content="XuchanBao/UofTCourseCluster" name="octolytics-dimension-repository_network_root_nwo" /><meta content="false" name="octolytics-dimension-repository_explore_github_marketplace_ci_cta_shown" />
<link rel="canonical" href="https://github.com/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<link rel="mask-icon" href="https://assets-cdn.github.com/pinned-octocat.svg" color="#000000">
<link rel="icon" type="image/x-icon" class="js-site-favicon" href="https://assets-cdn.github.com/favicon.ico">
<meta name="theme-color" content="#1e2327">
<meta name="u2f-support" content="true">
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-in env-production page-blob">
<div class="position-relative js-header-wrapper ">
<a href="#start-of-content" tabindex="1" class="bg-black text-white p-3 show-on-focus js-skip-to-content">Skip to content</a>
<div id="js-pjax-loader-bar" class="pjax-loader-bar"><div class="progress"></div></div>
<header class="Header f5" role="banner">
<div class="d-flex px-3 flex-justify-between container-lg">
<div class="d-flex flex-justify-between ">
<div class="">
<a class="header-logo-invertocat" href="https://github.com/" data-hotkey="g d" aria-label="Homepage" data-ga-click="Header, go to dashboard, icon:logo">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="32" version="1.1" viewBox="0 0 16 16" width="32"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 192.168.3.11 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
</div>
</div>
<div class="HeaderMenu d-flex flex-justify-between flex-auto">
<div class="d-flex">
<div class="">
<div class="header-search scoped-search site-scoped-search js-site-search" role="search">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/search" class="js-site-search-form" data-scoped-search-url="/XuchanBao/UofTCourseCluster/search" data-unscoped-search-url="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<label class="form-control header-search-wrapper js-chromeless-input-container">
<a href="/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py" class="header-search-scope no-underline">This repository</a>
<input type="text"
class="form-control header-search-input js-site-search-focus js-site-search-field is-clearable"
data-hotkey="s"
name="q"
value=""
placeholder="Search"
aria-label="Search this repository"
data-unscoped-placeholder="Search GitHub"
data-scoped-placeholder="Search"
autocapitalize="off">
<input type="hidden" class="js-site-search-type-field" name="type" >
</label>
</form></div>
</div>
<ul class="d-flex pl-2 flex-items-center text-bold list-style-none" role="navigation">
<li>
<a href="/pulls" aria-label="Pull requests you created" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:pulls context:user" data-hotkey="g p" data-selected-links="/pulls /pulls/assigned /pulls/mentioned /pulls">
Pull requests
</a> </li>
<li>
<a href="/issues" aria-label="Issues you created" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:issues context:user" data-hotkey="g i" data-selected-links="/issues /issues/assigned /issues/mentioned /issues">
Issues
</a> </li>
<li>
<a href="/marketplace" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:marketplace context:user" data-selected-links=" /marketplace">
Marketplace
</a> </li>
<li>
<a href="/explore" class="js-selected-navigation-item HeaderNavlink px-2" data-ga-click="Header, click, Nav menu - item:explore" data-selected-links="/explore /trending /trending/developers /integrations /integrations/feature/code /integrations/feature/collaborate /integrations/feature/ship showcases showcases_search showcases_landing /explore">
Explore
</a> </li>
</ul>
</div>
<div class="d-flex">
<ul class="user-nav d-flex flex-items-center list-style-none" id="user-links">
<li class="dropdown js-menu-container">
<span class="d-inline-block px-2">
</span>
</li>
<li class="dropdown js-menu-container">
<details class="dropdown-details details-reset js-dropdown-details d-flex px-2 flex-items-center">
<summary class="HeaderNavlink"
aria-label="Create new…"
data-ga-click="Header, create new, icon:add">
<svg aria-hidden="true" class="octicon octicon-plus float-left mr-1 mt-1" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 9H7v5H5V9H0V7h5V2h2v5h5z"/></svg>
<span class="dropdown-caret mt-1"></span>
</summary>
<ul class="dropdown-menu dropdown-menu-sw">
<a class="dropdown-item" href="/new" data-ga-click="Header, create new repository">
New repository
</a>
<a class="dropdown-item" href="/new/import" data-ga-click="Header, import a repository">
Import repository
</a>
<a class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, create new gist">
New gist
</a>
<a class="dropdown-item" href="/organizations/new" data-ga-click="Header, create new organization">
New organization
</a>
<div class="dropdown-divider"></div>
<div class="dropdown-header">
<span title="XuchanBao/UofTCourseCluster">This repository</span>
</div>
<a class="dropdown-item" href="/XuchanBao/UofTCourseCluster/issues/new" data-ga-click="Header, create new issue">
New issue
</a>
</ul>
</details>
</li>
<li class="dropdown js-menu-container">
<details class="dropdown-details details-reset js-dropdown-details d-flex pl-2 flex-items-center">
<summary class="HeaderNavlink name mt-1"
aria-label="View profile and more"
data-ga-click="Header, show menu, icon:avatar">
<img alt="@bblwq" class="avatar float-left mr-1" src="https://avatars1.githubusercontent.com/u/24879621?s=40&v=4" height="20" width="20">
<span class="dropdown-caret"></span>
</summary>
<ul class="dropdown-menu dropdown-menu-sw">
<li class="dropdown-header header-nav-current-user css-truncate">
Signed in as <strong class="css-truncate-target">bblwq</strong>
</li>
<li class="dropdown-divider"></li>
<li><a class="dropdown-item" href="/bblwq" data-ga-click="Header, go to profile, text:your profile">
Your profile
</a></li>
<li><a class="dropdown-item" href="/bblwq?tab=stars" data-ga-click="Header, go to starred repos, text:your stars">
Your stars
</a></li>
<li><a class="dropdown-item" href="https://gist.github.com/" data-ga-click="Header, your gists, text:your gists">Your gists</a></li>
<li class="dropdown-divider"></li>
<li><a class="dropdown-item" href="https://help.github.com" data-ga-click="Header, go to help, text:help">
Help
</a></li>
<li><a class="dropdown-item" href="/settings/profile" data-ga-click="Header, go to settings, icon:settings">
Settings
</a></li>
<li><!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/logout" class="logout-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form></li>
</ul>
</details>
</li>
</ul>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/logout" class="sr-only right-0" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button type="submit" class="dropdown-item dropdown-signout" data-ga-click="Header, sign out, icon:logout">
Sign out
</button>
</form> </div>
</div>
</div>
</header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container">
</div>
<div role="main" class="application-main ">
<div itemscope itemtype="http://schema.org/SoftwareSourceCode" class="">
<div id="js-repo-pjax-container" data-pjax-container >
<div class="pagehead repohead instapaper_ignore readability-menu experiment-repo-nav ">
<div class="repohead-details-container clearfix container">
<ul class="pagehead-actions">
<li>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/notifications/subscribe" class="js-social-container" data-autosubmit="true" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div> <input class="form-control" id="repository_id" name="repository_id" type="hidden" value="109784626" />
<div class="select-menu js-menu-container js-select-menu">
<a href="/XuchanBao/UofTCourseCluster/subscription"
class="btn btn-sm btn-with-count select-menu-button js-menu-target"
role="button"
aria-haspopup="true"
aria-expanded="false"
aria-label="Toggle repository notifications menu"
data-ga-click="Repository, click Watch settings, action:blob#show">
<span class="js-select-button">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</a>
<a class="social-count js-social-count"
href="/XuchanBao/UofTCourseCluster/watchers"
aria-label="1 user is watching this repository">
1
</a>
<div class="select-menu-modal-holder">
<div class="select-menu-modal subscription-menu-modal js-menu-content">
<div class="select-menu-header js-navigation-enable" tabindex="-1">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
<span class="select-menu-title">Notifications</span>
</div>
<div class="select-menu-list js-navigation-container" role="menu">
<div class="select-menu-item js-navigation-item selected" role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input checked="checked" id="do_included" name="do" type="radio" value="included" />
<span class="select-menu-item-heading">Not watching</span>
<span class="description">Be notified when participating or @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Watch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input id="do_subscribed" name="do" type="radio" value="subscribed" />
<span class="select-menu-item-heading">Watching</span>
<span class="description">Be notified of all conversations.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-eye" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.06 2C3 2 0 8 0 8s3 6 8.06 6C13 14 16 8 16 8s-3-6-7.94-6zM8 12c-2.2 0-4-1.78-4-4 0-2.2 1.8-4 4-4 2.22 0 4 1.8 4 4 0 2.22-1.78 4-4 4zm2-4c0 1.11-.89 2-2 2-1.11 0-2-.89-2-2 0-1.11.89-2 2-2 1.11 0 2 .89 2 2z"/></svg>
Unwatch
</span>
</div>
</div>
<div class="select-menu-item js-navigation-item " role="menuitem" tabindex="0">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<div class="select-menu-item-text">
<input id="do_ignore" name="do" type="radio" value="ignore" />
<span class="select-menu-item-heading">Ignoring</span>
<span class="description">Never be notified.</span>
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-mute" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8 2.81v10.38c0 .67-.81 1-1.28.53L3 10H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h2l3.72-3.72C7.19 1.81 8 2.14 8 2.81zm7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06L11.44 8 9.47 9.97l1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06L13.56 8l1.97-1.97z"/></svg>
Stop ignoring
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container on">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/unstar" class="starred js-social-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Unstar this repository" title="Unstar XuchanBao/UofTCourseCluster"
data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Unstar
</button>
<a class="social-count js-social-count" href="/XuchanBao/UofTCourseCluster/stargazers"
aria-label="1 user starred this repository">
1
</a>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/star" class="unstarred js-social-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<input type="hidden" name="context" value="repository"></input>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Star this repository" title="Star XuchanBao/UofTCourseCluster"
data-ga-click="Repository, click star button, action:blob#show; text:Star">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Star
</button>
<a class="social-count js-social-count" href="/XuchanBao/UofTCourseCluster/stargazers"
aria-label="1 user starred this repository">
1
</a>
</form> </div>
</li>
<li>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/fork" class="btn-with-count" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button
type="submit"
class="btn btn-sm btn-with-count"
data-ga-click="Repository, show fork modal, action:blob#show; text:Fork"
title="Fork your own copy of XuchanBao/UofTCourseCluster to your account"
aria-label="Fork your own copy of XuchanBao/UofTCourseCluster to your account">
<svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
Fork
</button>
</form>
<a href="/XuchanBao/UofTCourseCluster/network" class="social-count"
aria-label="0 users forked this repository">
0
</a>
</li>
</ul>
<h1 class="private ">
<svg aria-hidden="true" class="octicon octicon-lock" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M4 13H3v-1h1v1zm8-6v7c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h1V4c0-2.2 1.8-4 4-4s4 1.8 4 4v2h1c.55 0 1 .45 1 1zM3.8 6h4.41V4c0-1.22-.98-2.2-2.2-2.2-1.22 0-2.2.98-2.2 2.2v2H3.8zM11 7H2v7h9V7zM4 8H3v1h1V8zm0 2H3v1h1v-1z"/></svg>
<span class="author" itemprop="author"><a href="/XuchanBao" class="url fn" rel="author">XuchanBao</a></span><!--
--><span class="path-divider">/</span><!--
--><strong itemprop="name"><a href="/XuchanBao/UofTCourseCluster" data-pjax="#js-repo-pjax-container">UofTCourseCluster</a></strong>
<span class="Label Label--outline v-align-middle">Private</span>
</h1>
</div>
<nav class="reponav js-repo-nav js-sidenav-container-pjax container"
itemscope
itemtype="http://schema.org/BreadcrumbList"
role="navigation"
data-pjax="#js-repo-pjax-container">
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches repo_packages /XuchanBao/UofTCourseCluster" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg>
<span itemprop="name">Code</span>
<meta itemprop="position" content="1">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /XuchanBao/UofTCourseCluster/issues" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg>
<span itemprop="name">Issues</span>
<span class="Counter">0</span>
<meta itemprop="position" content="2">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/XuchanBao/UofTCourseCluster/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls checks /XuchanBao/UofTCourseCluster/pulls" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<span itemprop="name">Pull requests</span>
<span class="Counter">0</span>
<meta itemprop="position" content="3">
</a> </span>
<a href="/XuchanBao/UofTCourseCluster/projects" class="js-selected-navigation-item reponav-item" data-hotkey="g b" data-selected-links="repo_projects new_repo_project repo_project /XuchanBao/UofTCourseCluster/projects">
<svg aria-hidden="true" class="octicon octicon-project" height="16" version="1.1" viewBox="0 0 15 16" width="15"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
Projects
<span class="Counter" >0</span>
</a>
<a href="/XuchanBao/UofTCourseCluster/wiki" class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /XuchanBao/UofTCourseCluster/wiki">
<svg aria-hidden="true" class="octicon octicon-book" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z"/></svg>
Wiki
</a>
<a href="/XuchanBao/UofTCourseCluster/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors dependency_graph pulse /XuchanBao/UofTCourseCluster/pulse">
<svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg>
Insights
</a>
</nav>
</div>
<div class="container new-discussion-timeline experiment-repo-nav ">
<div class="repository-content ">
<a href="/XuchanBao/UofTCourseCluster/blob/d98adeba89f6a955803828959146032339afe258/scraping/extract_course_info_from_json_resp.py" class="d-none js-permalink-shortcut" data-hotkey="y">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:2b5c6dfa8bf9101e6ebfebe3c052eadc -->
<div class="file-navigation">
<div class="select-menu branch-select-menu js-menu-container js-select-menu float-left">
<button class=" btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w"
type="button" aria-label="Switch branches or tags" aria-expanded="false" aria-haspopup="true">
<i>Branch:</i>
<span class="js-select-button css-truncate-target">master</span>
</button>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax>
<div class="select-menu-modal">
<div class="select-menu-header">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
<span class="select-menu-title">Switch branches/tags</span>
</div>
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" aria-label="Find or create a branch…" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Find or create a branch…">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" data-filter-placeholder="Find or create a branch…" class="js-select-menu-tab" role="tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a>
</li>
</ul>
</div>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/bblwq/scraping/extract_course_info_from_json_resp.py"
data-name="bblwq"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
bblwq
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/jenny-cluster-algo-experiments/scraping/extract_course_info_from_json_resp.py"
data-name="jenny-cluster-algo-experiments"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
jenny-cluster-algo-experiments
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/jenny-scrapy/scraping/extract_course_info_from_json_resp.py"
data-name="jenny-scrapy"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
jenny-scrapy
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open selected"
href="/XuchanBao/UofTCourseCluster/blob/master/scraping/extract_course_info_from_json_resp.py"
data-name="master"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
master
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/merge-sraped-data/scraping/extract_course_info_from_json_resp.py"
data-name="merge-sraped-data"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
merge-sraped-data
</span>
</a>
<a class="select-menu-item js-navigation-item js-navigation-open "
href="/XuchanBao/UofTCourseCluster/blob/zoebranch/scraping/extract_course_info_from_json_resp.py"
data-name="zoebranch"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
zoebranch
</span>
</a>
</div>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/branches" class="js-create-branch select-menu-item select-menu-new-item-form js-navigation-item js-new-item-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<svg aria-hidden="true" class="octicon octicon-git-branch select-menu-item-icon" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M10 5c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v.3c-.02.52-.23.98-.63 1.38-.4.4-.86.61-1.38.63-.83.02-1.48.16-2 .45V4.72a1.993 1.993 0 0 0-1-3.72C.88 1 0 1.89 0 3a2 2 0 0 0 1 1.72v6.56c-.59.35-1 .99-1 1.72 0 1.11.89 2 2 2 1.11 0 2-.89 2-2 0-.53-.2-1-.53-1.36.09-.06.48-.41.59-.47.25-.11.56-.17.94-.17 1.05-.05 1.95-.45 2.75-1.25S8.95 7.77 9 6.73h-.02C9.59 6.37 10 5.73 10 5zM2 1.8c.66 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2C1.35 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2zm0 12.41c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm6-8c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Create branch: <span class="js-new-item-name"></span></span>
<span class="description">from ‘master’</span>
</div>
<input type="hidden" name="name" id="name" class="js-new-item-value">
<input type="hidden" name="branch" id="branch" value="master">
<input type="hidden" name="path" id="path" value="scraping/extract_course_info_from_json_resp.py">
</form>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div>
</div>
</div>
</div>
<div class="BtnGroup float-right">
<a href="/XuchanBao/UofTCourseCluster/find/master"
class="js-pjax-capture-input btn btn-sm BtnGroup-item"
data-pjax
data-hotkey="t">
Find file
</a>
<clipboard-copy
for="blob-path"
role="button"
aria-label="Copy file path to clipboard"
class="btn btn-sm BtnGroup-item tooltipped tooltipped-s"
data-copied-hint="Copied!">
Copy path
</clipboard-copy>
</div>
<div id="blob-path" class="breadcrumb">
<span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/XuchanBao/UofTCourseCluster" data-pjax="true"><span>UofTCourseCluster</span></a></span></span><span class="separator">/</span><span class="js-path-segment"><a href="/XuchanBao/UofTCourseCluster/tree/master/scraping" data-pjax="true"><span>scraping</span></a></span><span class="separator">/</span><strong class="final-path">extract_course_info_from_json_resp.py</strong>
</div>
</div>
<div class="commit-tease">
<span class="float-right">
<a class="commit-tease-sha" href="/XuchanBao/UofTCourseCluster/commit/e991e0b6e0953f98713671fa63d51611855060e0" data-pjax>
e991e0b
</a>
<relative-time datetime="2018-01-25T02:36:51Z">Jan 24, 2018</relative-time>
</span>
<div>
<img alt="" class="avatar" data-canonical-src="https://0.gravatar.com/avatar/00f9cd9ff503ba4ccd3e0f3eca760d1c?d=https%3A%2F%2Fassets-cdn.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png&r=g&s=140" height="20" src="https://camo.githubusercontent.com/760787ee917f1d55be81bb9fe3294b5ef6180b80/68747470733a2f2f302e67726176617461722e636f6d2f6176617461722f30306639636439666635303362613463636433653066336563613736306431633f643d68747470732533412532462532466173736574732d63646e2e6769746875622e636f6d253246696d6167657325324667726176617461727325324667726176617461722d757365722d3432302e706e6726723d6726733d313430" width="20" />
<span class="user-mention">xb1</span>
<a href="/XuchanBao/UofTCourseCluster/commit/e991e0b6e0953f98713671fa63d51611855060e0" class="message" data-pjax="true" title="Scrape CSC courses">Scrape CSC courses</a>
</div>
<div class="commit-tease-contributors">
<button type="button" class="btn-link muted-link contributors-toggle" data-facebox="#blob_contributors_box">
<strong>0</strong>
contributors
</button>
</div>
<div id="blob_contributors_box" style="display:none">
<h2 class="facebox-header" data-facebox-id="facebox-header">Users who have contributed to this file</h2>
<ul class="facebox-user-list" data-facebox-id="facebox-description">
</ul>
</div>
</div>
<div class="file">
<div class="file-header">
<div class="file-actions">
<div class="BtnGroup">
<a href="/XuchanBao/UofTCourseCluster/raw/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm BtnGroup-item" id="raw-url">Raw</a>
<a href="/XuchanBao/UofTCourseCluster/blame/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b">Blame</a>
<a href="/XuchanBao/UofTCourseCluster/commits/master/scraping/extract_course_info_from_json_resp.py" class="btn btn-sm BtnGroup-item" rel="nofollow">History</a>
</div>
<a class="btn-octicon tooltipped tooltipped-nw"
href="github-windows://openRepo/https://github.com/XuchanBao/UofTCourseCluster?branch=master&filepath=scraping%2Fextract_course_info_from_json_resp.py"
aria-label="Open this file in GitHub Desktop"
data-ga-click="Repository, open with desktop, type:windows">
<svg aria-hidden="true" class="octicon octicon-device-desktop" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M15 2H1c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5.34c-.25.61-.86 1.39-2.34 2h8c-1.48-.61-2.09-1.39-2.34-2H15c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm0 9H1V3h14v8z"/></svg>
</a>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/edit/master/scraping/extract_course_info_from_json_resp.py" class="inline-form js-update-url-with-hash" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button class="btn-octicon tooltipped tooltipped-nw" type="submit"
aria-label="Edit this file" data-hotkey="e" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-pencil" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M0 12v3h3l8-8-3-3-8 8zm3 2H1v-2h1v1h1v1zm10.3-9.3L12 6 9 3l1.3-1.3a.996.996 0 0 1 1.41 0l1.59 1.59c.39.39.39 1.02 0 1.41z"/></svg>
</button>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/XuchanBao/UofTCourseCluster/delete/master/scraping/extract_course_info_from_json_resp.py" class="inline-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button class="btn-octicon btn-octicon-danger tooltipped tooltipped-nw" type="submit"
aria-label="Delete this file" data-disable-with>
<svg aria-hidden="true" class="octicon octicon-trashcan" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 2H9c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1H2c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1v9c0 .55.45 1 1 1h7c.55 0 1-.45 1-1V5c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 12H3V5h1v8h1V5h1v8h1V5h1v8h1V5h1v9zm1-10H2V3h9v1z"/></svg>
</button>
</form> </div>
<div class="file-info">
47 lines (36 sloc)
<span class="file-info-divider"></span>
1.16 KB
</div>
</div>
<div itemprop="text" class="blob-wrapper data type-python">
<table class="highlight tab-size js-file-line-container" data-tab-size="8">
<tr>
<td id="L1" class="blob-num js-line-number" data-line-number="1"></td>
<td id="LC1" class="blob-code blob-code-inner js-file-line"><span class="pl-k">import</span> pickle</td>
</tr>
<tr>
<td id="L2" class="blob-num js-line-number" data-line-number="2"></td>
<td id="LC2" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L3" class="blob-num js-line-number" data-line-number="3"></td>
<td id="LC3" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">INDEX_TO_FEATURE</span> <span class="pl-k">=</span> {</td>
</tr>
<tr>
<td id="L4" class="blob-num js-line-number" data-line-number="4"></td>
<td id="LC4" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">0</span>: <span class="pl-c1">None</span>,</td>
</tr>
<tr>
<td id="L5" class="blob-num js-line-number" data-line-number="5"></td>
<td id="LC5" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">1</span>: <span class="pl-s"><span class="pl-pds">"</span>code<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L6" class="blob-num js-line-number" data-line-number="6"></td>
<td id="LC6" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">2</span>: <span class="pl-s"><span class="pl-pds">"</span>title<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L7" class="blob-num js-line-number" data-line-number="7"></td>
<td id="LC7" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">3</span>: <span class="pl-s"><span class="pl-pds">"</span>credit<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L8" class="blob-num js-line-number" data-line-number="8"></td>
<td id="LC8" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">4</span>: <span class="pl-s"><span class="pl-pds">"</span>location<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L9" class="blob-num js-line-number" data-line-number="9"></td>
<td id="LC9" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">5</span>: <span class="pl-s"><span class="pl-pds">"</span>department<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L10" class="blob-num js-line-number" data-line-number="10"></td>
<td id="LC10" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">6</span>: <span class="pl-s"><span class="pl-pds">"</span>session<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L11" class="blob-num js-line-number" data-line-number="11"></td>
<td id="LC11" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">7</span>: <span class="pl-s"><span class="pl-pds">"</span>campus<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L12" class="blob-num js-line-number" data-line-number="12"></td>
<td id="LC12" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">8</span>: <span class="pl-s"><span class="pl-pds">"</span>days of week<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L13" class="blob-num js-line-number" data-line-number="13"></td>
<td id="LC13" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">9</span>: <span class="pl-s"><span class="pl-pds">"</span>level<span class="pl-pds">"</span></span>,</td>
</tr>
<tr>
<td id="L14" class="blob-num js-line-number" data-line-number="14"></td>
<td id="LC14" class="blob-code blob-code-inner js-file-line"> <span class="pl-c1">10</span>: <span class="pl-s"><span class="pl-pds">"</span>time of day<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L15" class="blob-num js-line-number" data-line-number="15"></td>
<td id="LC15" class="blob-code blob-code-inner js-file-line">}</td>
</tr>
<tr>
<td id="L16" class="blob-num js-line-number" data-line-number="16"></td>
<td id="LC16" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L17" class="blob-num js-line-number" data-line-number="17"></td>
<td id="LC17" class="blob-code blob-code-inner js-file-line"><span class="pl-c1">JSON_KEYNAME</span> <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">"</span>aaData<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L18" class="blob-num js-line-number" data-line-number="18"></td>
<td id="LC18" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L19" class="blob-num js-line-number" data-line-number="19"></td>
<td id="LC19" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L20" class="blob-num js-line-number" data-line-number="20"></td>
<td id="LC20" class="blob-code blob-code-inner js-file-line"><span class="pl-k">def</span> <span class="pl-en">extract_course_code</span>(<span class="pl-smi">html_string</span>):</td>
</tr>
<tr>
<td id="L21" class="blob-num js-line-number" data-line-number="21"></td>
<td id="LC21" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">return</span> html_string.split(<span class="pl-s"><span class="pl-pds">'</span></a><span class="pl-pds">'</span></span>)[<span class="pl-c1">0</span>].split(<span class="pl-s"><span class="pl-pds">'</span>><span class="pl-pds">'</span></span>)[<span class="pl-k">-</span><span class="pl-c1">1</span>]</td>
</tr>
<tr>
<td id="L22" class="blob-num js-line-number" data-line-number="22"></td>
<td id="LC22" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L23" class="blob-num js-line-number" data-line-number="23"></td>
<td id="LC23" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L24" class="blob-num js-line-number" data-line-number="24"></td>
<td id="LC24" class="blob-code blob-code-inner js-file-line"><span class="pl-k">def</span> <span class="pl-en">extract_course_info_from_resp_and_save</span>(<span class="pl-smi">resp_filename</span>, <span class="pl-smi">save_filename</span>):</td>
</tr>
<tr>
<td id="L25" class="blob-num js-line-number" data-line-number="25"></td>
<td id="LC25" class="blob-code blob-code-inner js-file-line"> resp_dict <span class="pl-k">=</span> pickle.load(<span class="pl-c1">open</span>(resp_filename, <span class="pl-s"><span class="pl-pds">'</span>rb<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L26" class="blob-num js-line-number" data-line-number="26"></td>
<td id="LC26" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L27" class="blob-num js-line-number" data-line-number="27"></td>
<td id="LC27" class="blob-code blob-code-inner js-file-line"> all_courses <span class="pl-k">=</span> {}</td>
</tr>
<tr>
<td id="L28" class="blob-num js-line-number" data-line-number="28"></td>
<td id="LC28" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> course_info_list <span class="pl-k">in</span> resp_dict[<span class="pl-c1">JSON_KEYNAME</span>]:</td>
</tr>
<tr>
<td id="L29" class="blob-num js-line-number" data-line-number="29"></td>
<td id="LC29" class="blob-code blob-code-inner js-file-line"> course_info_dict <span class="pl-k">=</span> {}</td>
</tr>
<tr>
<td id="L30" class="blob-num js-line-number" data-line-number="30"></td>
<td id="LC30" class="blob-code blob-code-inner js-file-line"> course_key <span class="pl-k">=</span> <span class="pl-s"><span class="pl-pds">"</span>default_key<span class="pl-pds">"</span></span></td>
</tr>
<tr>
<td id="L31" class="blob-num js-line-number" data-line-number="31"></td>
<td id="LC31" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">for</span> i <span class="pl-k">in</span> <span class="pl-c1">range</span>(<span class="pl-c1">len</span>(course_info_list)):</td>
</tr>
<tr>
<td id="L32" class="blob-num js-line-number" data-line-number="32"></td>
<td id="LC32" class="blob-code blob-code-inner js-file-line"> feature <span class="pl-k">=</span> <span class="pl-c1">INDEX_TO_FEATURE</span>[i]</td>
</tr>
<tr>
<td id="L33" class="blob-num js-line-number" data-line-number="33"></td>
<td id="LC33" class="blob-code blob-code-inner js-file-line"> value <span class="pl-k">=</span> course_info_list[i]</td>
</tr>
<tr>
<td id="L34" class="blob-num js-line-number" data-line-number="34"></td>
<td id="LC34" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> <span class="pl-k">not</span> feature:</td>
</tr>
<tr>
<td id="L35" class="blob-num js-line-number" data-line-number="35"></td>
<td id="LC35" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">continue</span></td>
</tr>
<tr>
<td id="L36" class="blob-num js-line-number" data-line-number="36"></td>
<td id="LC36" class="blob-code blob-code-inner js-file-line"> <span class="pl-k">if</span> feature <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">"</span>code<span class="pl-pds">"</span></span>:</td>
</tr>
<tr>
<td id="L37" class="blob-num js-line-number" data-line-number="37"></td>
<td id="LC37" class="blob-code blob-code-inner js-file-line"> value <span class="pl-k">=</span> extract_course_code(value)</td>
</tr>
<tr>
<td id="L38" class="blob-num js-line-number" data-line-number="38"></td>
<td id="LC38" class="blob-code blob-code-inner js-file-line"> course_key <span class="pl-k">=</span> value</td>
</tr>
<tr>
<td id="L39" class="blob-num js-line-number" data-line-number="39"></td>
<td id="LC39" class="blob-code blob-code-inner js-file-line"> course_info_dict[feature] <span class="pl-k">=</span> value</td>
</tr>
<tr>
<td id="L40" class="blob-num js-line-number" data-line-number="40"></td>
<td id="LC40" class="blob-code blob-code-inner js-file-line"> all_courses[course_key] <span class="pl-k">=</span> course_info_dict</td>
</tr>
<tr>
<td id="L41" class="blob-num js-line-number" data-line-number="41"></td>
<td id="LC41" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L42" class="blob-num js-line-number" data-line-number="42"></td>
<td id="LC42" class="blob-code blob-code-inner js-file-line"> pickle.dump(all_courses, <span class="pl-c1">open</span>(save_filename, <span class="pl-s"><span class="pl-pds">'</span>wb<span class="pl-pds">'</span></span>))</td>
</tr>
<tr>
<td id="L43" class="blob-num js-line-number" data-line-number="43"></td>
<td id="LC43" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L44" class="blob-num js-line-number" data-line-number="44"></td>
<td id="LC44" class="blob-code blob-code-inner js-file-line">
</td>
</tr>
<tr>
<td id="L45" class="blob-num js-line-number" data-line-number="45"></td>
<td id="LC45" class="blob-code blob-code-inner js-file-line"><span class="pl-k">if</span> <span class="pl-c1">__name__</span> <span class="pl-k">==</span> <span class="pl-s"><span class="pl-pds">"</span>__main__<span class="pl-pds">"</span></span>:</td>
</tr>
<tr>
<td id="L46" class="blob-num js-line-number" data-line-number="46"></td>
<td id="LC46" class="blob-code blob-code-inner js-file-line"> extract_course_info_from_resp_and_save(<span class="pl-s"><span class="pl-pds">"</span>csc_resp.p<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>csc_courses.p<span class="pl-pds">"</span></span>)</td>
</tr>
</table>
<div class="BlobToolbar position-absolute js-file-line-actions dropdown js-menu-container js-select-menu d-none" aria-hidden="true">
<button class="btn-octicon ml-0 px-2 p-0 bg-white border border-gray-dark rounded-1 dropdown-toggle js-menu-target" id="js-file-line-action-button" type="button" aria-expanded="false" aria-haspopup="true" aria-label="Inline file action toolbar" aria-controls="inline-file-actions">
<svg aria-hidden="true" class="octicon octicon-kebab-horizontal" height="16" version="1.1" viewBox="0 0 13 16" width="13"><path fill-rule="evenodd" d="M1.5 9a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/></svg>
</button>
<div class="dropdown-menu-content js-menu-content" id="inline-file-actions">
<ul class="BlobToolbar-dropdown dropdown-menu dropdown-menu-se mt-2">
<li><a class="js-zeroclipboard dropdown-item" style="cursor:pointer;" id="js-copy-lines" data-original-text="Copy lines">Copy lines</a></li>
<li><a class="js-zeroclipboard dropdown-item" id= "js-copy-permalink" style="cursor:pointer;" data-original-text="Copy permalink">Copy permalink</a></li>
<li><a href="/XuchanBao/UofTCourseCluster/blame/d98adeba89f6a955803828959146032339afe258/scraping/extract_course_info_from_json_resp.py" class="dropdown-item js-update-url-with-hash" id="js-view-git-blame">View git blame</a></li>
<li><a href="/XuchanBao/UofTCourseCluster/issues/new" class="dropdown-item" id="js-new-issue">Open new issue</a></li>
</ul>
</div>
</div>
</div>
</div>
<button type="button" data-facebox="#jump-to-line" data-facebox-class="linejump" data-hotkey="l" class="d-none">Jump to Line</button>
<div id="jump-to-line" style="display:none">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="" class="js-jump-to-line-form" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<input class="form-control linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" aria-label="Jump to line" autofocus>
<button type="submit" class="btn">Go</button>
</form> </div>
</div>
<div class="modal-backdrop js-touch-events"></div>
</div>
</div>
</div>
</div>
<div class="footer container-lg px-3" role="contentinfo">
<div class="position-relative d-flex flex-justify-between py-6 mt-6 f6 text-gray border-top border-gray-light ">
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3">© 2018 <span title="0.29434s from unicorn-512311803-vxzxm">GitHub</span>, Inc.</li>
<li class="mr-3"><a href="https://help.github.com/articles/github-terms-of-service/" data-ga-click="Footer, go to terms, text:terms">Terms</a></li>
<li class="mr-3"><a href="https://github.com/site/privacy" data-ga-click="Footer, go to privacy, text:privacy">Privacy</a></li>
<li class="mr-3"><a href="https://help.github.com/articles/github-security/" data-ga-click="Footer, go to security, text:security">Security</a></li>
<li class="mr-3"><a href="https://status.github.com/" data-ga-click="Footer, go to status, text:status">Status</a></li>
<li><a href="https://help.github.com" data-ga-click="Footer, go to help, text:help">Help</a></li>
</ul>
<a href="https://github.com" aria-label="Homepage" class="footer-octicon" title="GitHub">
<svg aria-hidden="true" class="octicon octicon-mark-github" height="24" version="1.1" viewBox="0 0 16 16" width="24"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 192.168.3.11 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 172.16.31.10.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 192.168.3.11.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
</a>
<ul class="list-style-none d-flex flex-wrap ">
<li class="mr-3"><a href="https://github.com/contact" data-ga-click="Footer, go to contact, text:contact">Contact GitHub</a></li>
<li class="mr-3"><a href="https://developer.github.com" data-ga-click="Footer, go to api, text:api">API</a></li>
<li class="mr-3"><a href="https://training.github.com" data-ga-click="Footer, go to training, text:training">Training</a></li>
<li class="mr-3"><a href="https://shop.github.com" data-ga-click="Footer, go to shop, text:shop">Shop</a></li>
<li class="mr-3"><a href="https://github.com/blog" data-ga-click="Footer, go to blog, text:blog">Blog</a></li>
<li><a href="https://github.com/about" data-ga-click="Footer, go to about, text:about">About</a></li>
</ul>
</div>
</div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg>
<button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
</button>
You can't perform that action at this time.
</div>
<script crossorigin="anonymous" integrity="sha512-6oz7cTsS3E5enQjh4gWKU23tC78zIZqVJ1o5zMLCsAv5EEnmNsopwszDz7zx5IGWXU+H+sqeC5pHbt1Yxmh+sw==" src="https://assets-cdn.github.com/assets/frameworks-ea8cfb713b12.js" type="application/javascript"></script>
<script async="async" crossorigin="anonymous" integrity="sha512-9c2rT9XyOnZ3jV2cbM+DuSR1OpEKUJGUDkr0v+haFwhmfxPPd1UeLatTZ0I4To4RYxJwF02Os/o7LzvuSUK+VA==" src="https://assets-cdn.github.com/assets/github-f5cdab4fd5f2.js" type="application/javascript"></script>
<div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none">
<svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"/></svg>
<span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span>
<span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span>
</div>
<div class="facebox" id="facebox" style="display:none;">
<div class="facebox-popup">
<div class="facebox-content" role="dialog" aria-labelledby="facebox-header" aria-describedby="facebox-description">
</div>
<button type="button" class="facebox-close js-facebox-close" aria-label="Close modal">
<svg aria-hidden="true" class="octicon octicon-x" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
</button>
</div>
</div>
</body>
</html> | 0.424293 | 0.151184 |
# Quick notebook to prepae examples (not the tfrecord kind) from Project Gutenborgs Bible text
# In[1]:
import re
# In[2]:
txt = open('./pg10.txt').read()
# In[3]:
split_reg = re.compile('\n{4}')
# # split the raw text of the bible into books
# In[4]:
books = split_reg.split(txt)
# In[5]:
books = books[4:] # The first 4 are preamble from project gutenberg
# Split each book into the name of the book and its text
# In[6]:
book_verse_spliter = re.compile('\n{3}(?=1:1)',flags=re.MULTILINE) #The look ahead makes sure the book starts at chapter 1 verse 1
book,verses = book_verse_spliter.split(books[1])
# In[7]:
books[1][:100]
# In[8]:
verses[:100]
# Split all the text in one book into verses. Make it a dict of chapter, verse and text
# In[9]:
verses_splitter = re.compile('(?P<chapter>\d+):(?P<verse>\d+)(?P<text>.+?)(?=\d+\:\d+)',)
# In[10]:
gen = verses_splitter.finditer(verses.replace("\n",""))
# In[11]:
next(gen).groupdict()
# Lets run all of that on the entire bible
# In[12]:
examples= []
book_id = 0
book_map={}
for num,book in enumerate(books):
splitted = book_verse_spliter.split(book)
if len(splitted) >1:
book_name, book_text = splitted
book_name = book_name.strip().replace('\n', ' ')
if book_name.startswith("The "): #This filters out other junk in the dataset
for verse_regex_match in verses_splitter.finditer(book_text.replace("\n"," ")):
example = verse_regex_match.groupdict()
example.update({"book":book_name,"book_id":book_id,"text":example["text"].strip()})
examples.append(example)
book_map[book_name] =book_id
book_id+=1
# In[13]:
len(examples)
# Lets save it
# In[14]:
import pickle
pickle.dump(examples,open('./bible_data.pkl','wb'))
# # Now we make them into TF records
# In[15]:
import tensorflow as tf
from preppy import BibPreppy
# In[16]:
import random
random.shuffle(examples)
val,train = examples[:3000], examples[3000:]
# In[17]:
BP =BibPreppy(tokenizer_fn=list) #Charecter level tokenization
for (data,path) in [(val,'./val.tfrecord'),(train,'./train.tfrecord')]:
with open(path,'w') as f:
writer = tf.python_io.TFRecordWriter(f.name)
for example in data:
record = BP.sequence_to_tf_example(sequence=example["text"],book_id=example["book_id"])
writer.write(record.SerializeToString())
# In[18]:
BP.update_reverse_vocab()
BP.book_map.update(book_map)
# In[19]:
pickle.dump(BP,open('./preppy.pkl','wb'))
# In[20]:
len(BP.vocab),len(BP.book_map)
# In[23]:
BP.vocab["<START>"]
# In[24]:
BP.vocab | PrepareBibleExamples.py |
# Quick notebook to prepae examples (not the tfrecord kind) from Project Gutenborgs Bible text
# In[1]:
import re
# In[2]:
txt = open('./pg10.txt').read()
# In[3]:
split_reg = re.compile('\n{4}')
# # split the raw text of the bible into books
# In[4]:
books = split_reg.split(txt)
# In[5]:
books = books[4:] # The first 4 are preamble from project gutenberg
# Split each book into the name of the book and its text
# In[6]:
book_verse_spliter = re.compile('\n{3}(?=1:1)',flags=re.MULTILINE) #The look ahead makes sure the book starts at chapter 1 verse 1
book,verses = book_verse_spliter.split(books[1])
# In[7]:
books[1][:100]
# In[8]:
verses[:100]
# Split all the text in one book into verses. Make it a dict of chapter, verse and text
# In[9]:
verses_splitter = re.compile('(?P<chapter>\d+):(?P<verse>\d+)(?P<text>.+?)(?=\d+\:\d+)',)
# In[10]:
gen = verses_splitter.finditer(verses.replace("\n",""))
# In[11]:
next(gen).groupdict()
# Lets run all of that on the entire bible
# In[12]:
examples= []
book_id = 0
book_map={}
for num,book in enumerate(books):
splitted = book_verse_spliter.split(book)
if len(splitted) >1:
book_name, book_text = splitted
book_name = book_name.strip().replace('\n', ' ')
if book_name.startswith("The "): #This filters out other junk in the dataset
for verse_regex_match in verses_splitter.finditer(book_text.replace("\n"," ")):
example = verse_regex_match.groupdict()
example.update({"book":book_name,"book_id":book_id,"text":example["text"].strip()})
examples.append(example)
book_map[book_name] =book_id
book_id+=1
# In[13]:
len(examples)
# Lets save it
# In[14]:
import pickle
pickle.dump(examples,open('./bible_data.pkl','wb'))
# # Now we make them into TF records
# In[15]:
import tensorflow as tf
from preppy import BibPreppy
# In[16]:
import random
random.shuffle(examples)
val,train = examples[:3000], examples[3000:]
# In[17]:
BP =BibPreppy(tokenizer_fn=list) #Charecter level tokenization
for (data,path) in [(val,'./val.tfrecord'),(train,'./train.tfrecord')]:
with open(path,'w') as f:
writer = tf.python_io.TFRecordWriter(f.name)
for example in data:
record = BP.sequence_to_tf_example(sequence=example["text"],book_id=example["book_id"])
writer.write(record.SerializeToString())
# In[18]:
BP.update_reverse_vocab()
BP.book_map.update(book_map)
# In[19]:
pickle.dump(BP,open('./preppy.pkl','wb'))
# In[20]:
len(BP.vocab),len(BP.book_map)
# In[23]:
BP.vocab["<START>"]
# In[24]:
BP.vocab | 0.44071 | 0.606324 |
from brownie import *
from brownie.network.contract import InterfaceContainer
import json
import csv
def main():
global contracts, acct
thisNetwork = network.show_active()
# == Load config =======================================================================================================================
if thisNetwork == "development":
acct = accounts[0]
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "testnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "rsk-testnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "rsk-mainnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/mainnet_contracts.json')
else:
raise Exception("network not supported")
# load deployed contracts addresses
contracts = json.load(configFile)
vestingRegistryLogic = Contract.from_abi(
"VestingRegistryLogic",
address=contracts['VestingRegistryProxy'],
abi=VestingRegistryLogic.abi,
owner=acct)
# open the file in universal line ending mode
with open('./scripts/deployment/distribution/vestingmigrationstest.csv', 'rU') as infile:
#read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for row in reader:
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
# extract the variables you want
tokenOwners = data['tokenOwner']
vestingCreationTypes = data['vestingCreationType']
print(tokenOwners)
print(vestingCreationTypes)
data = vestingRegistryLogic.addDeployedVestings.encode_input(tokenOwners, vestingCreationTypes)
print(data)
multisig = Contract.from_abi("MultiSig", address=contracts['multisig'], abi=MultiSigWallet.abi, owner=acct)
print(multisig)
tx = multisig.submitTransaction(vestingRegistryLogic.address, 0, data, {'allow_revert':True})
print(tx.revert_msg)
txId = tx.events["Submission"]["transactionId"]
print(txId) | scripts/deployment/distribution/create_vesting_migrations.py | from brownie import *
from brownie.network.contract import InterfaceContainer
import json
import csv
def main():
global contracts, acct
thisNetwork = network.show_active()
# == Load config =======================================================================================================================
if thisNetwork == "development":
acct = accounts[0]
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "testnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "rsk-testnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/testnet_contracts.json')
elif thisNetwork == "rsk-mainnet":
acct = accounts.load("rskdeployer")
configFile = open('./scripts/contractInteraction/mainnet_contracts.json')
else:
raise Exception("network not supported")
# load deployed contracts addresses
contracts = json.load(configFile)
vestingRegistryLogic = Contract.from_abi(
"VestingRegistryLogic",
address=contracts['VestingRegistryProxy'],
abi=VestingRegistryLogic.abi,
owner=acct)
# open the file in universal line ending mode
with open('./scripts/deployment/distribution/vestingmigrationstest.csv', 'rU') as infile:
#read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for row in reader:
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
# extract the variables you want
tokenOwners = data['tokenOwner']
vestingCreationTypes = data['vestingCreationType']
print(tokenOwners)
print(vestingCreationTypes)
data = vestingRegistryLogic.addDeployedVestings.encode_input(tokenOwners, vestingCreationTypes)
print(data)
multisig = Contract.from_abi("MultiSig", address=contracts['multisig'], abi=MultiSigWallet.abi, owner=acct)
print(multisig)
tx = multisig.submitTransaction(vestingRegistryLogic.address, 0, data, {'allow_revert':True})
print(tx.revert_msg)
txId = tx.events["Submission"]["transactionId"]
print(txId) | 0.431105 | 0.10307 |
from random import randrange
from typing import List, Tuple
PointType = Tuple[int, int]
VectorType = PointType
SeaType = Tuple[List[int], ...]
SEA_WIDTH = 6
DESTROYER_LENGTH = 2
CRUISER_LENGTH = 3
AIRCRAFT_CARRIER_LENGTH = 4
def random_vector() -> Tuple[int, int]:
while True:
vector = (randrange(-1, 2), randrange(-1, 2))
if vector == (0, 0):
# We can't have a zero vector, so try again
continue
return vector
def add_vector(point: PointType, vector: VectorType) -> PointType:
return (point[0] + vector[0], point[1] + vector[1])
def place_ship(sea: SeaType, size: int, code: int) -> None:
while True:
start = (randrange(1, SEA_WIDTH + 1), randrange(1, SEA_WIDTH + 1))
vector = random_vector()
# Get potential ship points
point = start
points = []
for _ in range(size):
point = add_vector(point, vector)
points.append(point)
if not all([is_within_sea(point, sea) for point in points]) or any(
[value_at(point, sea) for point in points]
):
# ship out of bounds or crosses other ship, trying again
continue
# We found a valid spot, so actually place it now
for point in points:
set_value_at(code, point, sea)
break
def print_encoded_sea(sea: SeaType) -> None:
for x in range(len(sea)):
print(" ".join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)]))
def is_within_sea(point: PointType, sea: SeaType) -> bool:
return (1 <= point[0] <= len(sea)) and (1 <= point[1] <= len(sea))
def has_ship(sea: SeaType, code: int) -> bool:
return any(code in row for row in sea)
def count_sunk(sea: SeaType, *codes: int) -> int:
return sum(not has_ship(sea, code) for code in codes)
def value_at(point: PointType, sea: SeaType) -> int:
return sea[point[1] - 1][point[0] - 1]
def set_value_at(value: int, point: PointType, sea: SeaType) -> None:
sea[point[1] - 1][point[0] - 1] = value
def get_next_target(sea: SeaType) -> PointType:
while True:
try:
guess = input("? ")
point = guess.split(",")
if len(point) != 2:
raise ValueError()
point = (int(point[0]), int(point[1]))
if not is_within_sea(point, sea):
raise ValueError()
return point
except ValueError:
print(
f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA."
)
def setup_ships(sea: SeaType):
place_ship(sea, DESTROYER_LENGTH, 1)
place_ship(sea, DESTROYER_LENGTH, 2)
place_ship(sea, CRUISER_LENGTH, 3)
place_ship(sea, CRUISER_LENGTH, 4)
place_ship(sea, AIRCRAFT_CARRIER_LENGTH, 5)
place_ship(sea, AIRCRAFT_CARRIER_LENGTH, 6)
def main() -> None:
sea = tuple([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH))
setup_ships(sea)
print(
"""
BATTLE
CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
THE FOLLOWING CODE OF THE BAD GUYS' FLEET DISPOSITION
HAS BEEN CAPTURED BUT NOT DECODED:
"""
)
print_encoded_sea(sea)
print(
"""
DE-CODE IT AND USE IT IF YOU CAN
BUT KEEP THE DE-CODING METHOD A SECRET.
START GAME"""
)
splashes = 0
hits = 0
while True:
target = get_next_target(sea)
target_value = value_at(target, sea)
if target_value < 0:
print(
f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT."
)
if target_value <= 0:
print("SPLASH! TRY AGAIN.")
splashes += 1
continue
print(f"A DIRECT HIT ON SHIP NUMBER {target_value}")
hits += 1
set_value_at(-target_value, target, sea)
if not has_ship(sea, target_value):
print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.")
print("SO FAR, THE BAD GUYS HAVE LOST")
print(
f"{count_sunk(sea, 1, 2)} DESTROYER(S),",
f"{count_sunk(sea, 3, 4)} CRUISER(S),",
f"AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).",
)
if any(has_ship(sea, code) for code in range(1, 7)):
print(f"YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}")
continue
print(
"YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET "
f"WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}"
)
if not splashes:
print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.")
print("\n****************************")
break
if __name__ == "__main__":
main() | 09_Battle/python/battle.py | from random import randrange
from typing import List, Tuple
PointType = Tuple[int, int]
VectorType = PointType
SeaType = Tuple[List[int], ...]
SEA_WIDTH = 6
DESTROYER_LENGTH = 2
CRUISER_LENGTH = 3
AIRCRAFT_CARRIER_LENGTH = 4
def random_vector() -> Tuple[int, int]:
while True:
vector = (randrange(-1, 2), randrange(-1, 2))
if vector == (0, 0):
# We can't have a zero vector, so try again
continue
return vector
def add_vector(point: PointType, vector: VectorType) -> PointType:
return (point[0] + vector[0], point[1] + vector[1])
def place_ship(sea: SeaType, size: int, code: int) -> None:
while True:
start = (randrange(1, SEA_WIDTH + 1), randrange(1, SEA_WIDTH + 1))
vector = random_vector()
# Get potential ship points
point = start
points = []
for _ in range(size):
point = add_vector(point, vector)
points.append(point)
if not all([is_within_sea(point, sea) for point in points]) or any(
[value_at(point, sea) for point in points]
):
# ship out of bounds or crosses other ship, trying again
continue
# We found a valid spot, so actually place it now
for point in points:
set_value_at(code, point, sea)
break
def print_encoded_sea(sea: SeaType) -> None:
for x in range(len(sea)):
print(" ".join([str(sea[y][x]) for y in range(len(sea) - 1, -1, -1)]))
def is_within_sea(point: PointType, sea: SeaType) -> bool:
return (1 <= point[0] <= len(sea)) and (1 <= point[1] <= len(sea))
def has_ship(sea: SeaType, code: int) -> bool:
return any(code in row for row in sea)
def count_sunk(sea: SeaType, *codes: int) -> int:
return sum(not has_ship(sea, code) for code in codes)
def value_at(point: PointType, sea: SeaType) -> int:
return sea[point[1] - 1][point[0] - 1]
def set_value_at(value: int, point: PointType, sea: SeaType) -> None:
sea[point[1] - 1][point[0] - 1] = value
def get_next_target(sea: SeaType) -> PointType:
while True:
try:
guess = input("? ")
point = guess.split(",")
if len(point) != 2:
raise ValueError()
point = (int(point[0]), int(point[1]))
if not is_within_sea(point, sea):
raise ValueError()
return point
except ValueError:
print(
f"INVALID. SPECIFY TWO NUMBERS FROM 1 TO {len(sea)}, SEPARATED BY A COMMA."
)
def setup_ships(sea: SeaType):
place_ship(sea, DESTROYER_LENGTH, 1)
place_ship(sea, DESTROYER_LENGTH, 2)
place_ship(sea, CRUISER_LENGTH, 3)
place_ship(sea, CRUISER_LENGTH, 4)
place_ship(sea, AIRCRAFT_CARRIER_LENGTH, 5)
place_ship(sea, AIRCRAFT_CARRIER_LENGTH, 6)
def main() -> None:
sea = tuple([0 for _ in range(SEA_WIDTH)] for _ in range(SEA_WIDTH))
setup_ships(sea)
print(
"""
BATTLE
CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
THE FOLLOWING CODE OF THE BAD GUYS' FLEET DISPOSITION
HAS BEEN CAPTURED BUT NOT DECODED:
"""
)
print_encoded_sea(sea)
print(
"""
DE-CODE IT AND USE IT IF YOU CAN
BUT KEEP THE DE-CODING METHOD A SECRET.
START GAME"""
)
splashes = 0
hits = 0
while True:
target = get_next_target(sea)
target_value = value_at(target, sea)
if target_value < 0:
print(
f"YOU ALREADY PUT A HOLE IN SHIP NUMBER {abs(target_value)} AT THAT POINT."
)
if target_value <= 0:
print("SPLASH! TRY AGAIN.")
splashes += 1
continue
print(f"A DIRECT HIT ON SHIP NUMBER {target_value}")
hits += 1
set_value_at(-target_value, target, sea)
if not has_ship(sea, target_value):
print("AND YOU SUNK IT. HURRAH FOR THE GOOD GUYS.")
print("SO FAR, THE BAD GUYS HAVE LOST")
print(
f"{count_sunk(sea, 1, 2)} DESTROYER(S),",
f"{count_sunk(sea, 3, 4)} CRUISER(S),",
f"AND {count_sunk(sea, 5, 6)} AIRCRAFT CARRIER(S).",
)
if any(has_ship(sea, code) for code in range(1, 7)):
print(f"YOUR CURRENT SPLASH/HIT RATIO IS {splashes}/{hits}")
continue
print(
"YOU HAVE TOTALLY WIPED OUT THE BAD GUYS' FLEET "
f"WITH A FINAL SPLASH/HIT RATIO OF {splashes}/{hits}"
)
if not splashes:
print("CONGRATULATIONS -- A DIRECT HIT EVERY TIME.")
print("\n****************************")
break
if __name__ == "__main__":
main() | 0.672547 | 0.639567 |
import os
import platform
from setuptools import (
find_packages,
setup,
)
py_version = platform.python_version()
PACKAGE_VERSION = '3.1.5'
EXTRAS_REQUIRE = {
'tester': [
'coverage',
'pep8',
'pyflakes',
'pylint',
'pytest-cov'
],
'docs': [
"mock",
"sphinx-better-theme>=0.1.4",
"click>=5.1",
"configparser==3.5.0",
"contextlib2>=0.5.4",
"py-solc>=0.4.0",
"pytest>=2.7.2",
"sphinx",
"sphinx_rtd_theme>=0.1.9",
"toposort>=1.4",
"urllib3",
"tronapi",
"wheel >= 0.31.0"
],
'dev': [
"bumpversion",
"flaky>=3.3.0",
"hypothesis>=3.31.2",
"pytest>=3.5.0,<4",
"pytest-mock==1.*",
"pytest-pythonpath>=0.3",
"pytest-watch==4.*",
"pytest-xdist==1.*",
"setuptools>=38.6.0",
"tox>=1.8.0",
"twine >= 1.11.0",
"tqdm",
"when-changed"
]
}
EXTRAS_REQUIRE['dev'] = (
EXTRAS_REQUIRE['tester'] +
EXTRAS_REQUIRE['docs'] +
EXTRAS_REQUIRE['dev']
)
install_requires = [
"toolz>=0.9.0,<1.0.0;implementation_name=='pypy'",
"cytoolz>=0.9.0,<1.0.0;implementation_name=='cpython'",
"eth-abi>=2.0.0b6,<3.0.0",
"eth-account>=0.5.3,<0.6.0",
"eth-utils>=1.3.0,<2.0.0",
"eth-hash[pycryptodome]>=0.2.0,<1.0.0",
"trx-utils",
"hexbytes>=0.1.0,<1.0.0",
"requests>=2.16.0,<3.0.0",
"base58",
"ecdsa",
'attrdict',
]
this_dir = os.path.dirname(__file__)
readme_filename = os.path.join(this_dir, 'README.rst')
with open(readme_filename) as f:
PACKAGE_LONG_DESCRIPTION = f.read()
setup(
name='tronapi',
version=PACKAGE_VERSION,
description='A Python API for interacting with Tron (TRX)',
long_description=PACKAGE_LONG_DESCRIPTION,
long_description_content_type='text/x-rst',
keywords='tron tron-api tron-api-python iexbase',
url='https://github.com/iexbase/tron-api-python',
author='<NAME>',
author_email='<EMAIL>',
license='MIT License',
zip_safe=False,
python_requires='>=3.6,<4',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
packages=find_packages(exclude=['examples']),
include_package_data=True,
install_requires=install_requires,
tests_require=EXTRAS_REQUIRE['tester'],
extras_require=EXTRAS_REQUIRE,
) | setup.py | import os
import platform
from setuptools import (
find_packages,
setup,
)
py_version = platform.python_version()
PACKAGE_VERSION = '3.1.5'
EXTRAS_REQUIRE = {
'tester': [
'coverage',
'pep8',
'pyflakes',
'pylint',
'pytest-cov'
],
'docs': [
"mock",
"sphinx-better-theme>=0.1.4",
"click>=5.1",
"configparser==3.5.0",
"contextlib2>=0.5.4",
"py-solc>=0.4.0",
"pytest>=2.7.2",
"sphinx",
"sphinx_rtd_theme>=0.1.9",
"toposort>=1.4",
"urllib3",
"tronapi",
"wheel >= 0.31.0"
],
'dev': [
"bumpversion",
"flaky>=3.3.0",
"hypothesis>=3.31.2",
"pytest>=3.5.0,<4",
"pytest-mock==1.*",
"pytest-pythonpath>=0.3",
"pytest-watch==4.*",
"pytest-xdist==1.*",
"setuptools>=38.6.0",
"tox>=1.8.0",
"twine >= 1.11.0",
"tqdm",
"when-changed"
]
}
EXTRAS_REQUIRE['dev'] = (
EXTRAS_REQUIRE['tester'] +
EXTRAS_REQUIRE['docs'] +
EXTRAS_REQUIRE['dev']
)
install_requires = [
"toolz>=0.9.0,<1.0.0;implementation_name=='pypy'",
"cytoolz>=0.9.0,<1.0.0;implementation_name=='cpython'",
"eth-abi>=2.0.0b6,<3.0.0",
"eth-account>=0.5.3,<0.6.0",
"eth-utils>=1.3.0,<2.0.0",
"eth-hash[pycryptodome]>=0.2.0,<1.0.0",
"trx-utils",
"hexbytes>=0.1.0,<1.0.0",
"requests>=2.16.0,<3.0.0",
"base58",
"ecdsa",
'attrdict',
]
this_dir = os.path.dirname(__file__)
readme_filename = os.path.join(this_dir, 'README.rst')
with open(readme_filename) as f:
PACKAGE_LONG_DESCRIPTION = f.read()
setup(
name='tronapi',
version=PACKAGE_VERSION,
description='A Python API for interacting with Tron (TRX)',
long_description=PACKAGE_LONG_DESCRIPTION,
long_description_content_type='text/x-rst',
keywords='tron tron-api tron-api-python iexbase',
url='https://github.com/iexbase/tron-api-python',
author='<NAME>',
author_email='<EMAIL>',
license='MIT License',
zip_safe=False,
python_requires='>=3.6,<4',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
packages=find_packages(exclude=['examples']),
include_package_data=True,
install_requires=install_requires,
tests_require=EXTRAS_REQUIRE['tester'],
extras_require=EXTRAS_REQUIRE,
) | 0.24963 | 0.252724 |
__author__ = '<NAME> @MadMax93'
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import peakutils
import matplotlib.gridspec as gridspec
from peakutils.plot import plot as pplot
from matplotlib.offsetbox import AnchoredText
class Visualization(object):
def visualise_raw_data_combined(self, raw_data_array):
data_x = raw_data_array['X']
data_y = raw_data_array['Y']
data_z = raw_data_array['Z']
array_len = range(0, len(raw_data_array))
fig, ax = plt.subplots(1, sharex=True)
xl, = ax.plot(array_len, data_x, 'r', label='X-Axis')
fig.suptitle('Raw signal all axes combined')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
yl, = ax.plot(array_len, data_y, 'b', label='Y-Axis')
zl, = ax.plot(array_len, data_z, 'g', label='Z-Axis')
fig.legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'),loc='center right', fontsize=9)
#plt.show()
def visualise_raw_data_separate(self, raw_data_array):
data_x = raw_data_array['X']
data_y = raw_data_array['Y']
data_z = raw_data_array['Z']
array_len = range(0, len(raw_data_array))
fig, ax = plt.subplots(3, sharex=True)
xl, = ax[0].plot(array_len, data_x, 'r', label='X-Axis')
fig.suptitle('Raw signal all axes combined', fontsize='large')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
yl, = ax[1].plot(array_len, data_y, 'b', label='Y-Axis')
zl, = ax[2].plot(array_len, data_z, 'g', label='Z-Axis')
ax[0].set_title('Raw signal - X-Axis', fontsize='medium')
ax[1].set_title('Raw signal - Y-Axis', fontsize='medium')
ax[2].set_title('Raw signal - Z-Axis', fontsize='medium')
fig.legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'), loc='center right', fontsize=9)
#plt.show()
def visualise_signals_and_xyz_and_maximum_power_spectrum(self, filtered_signal_x, filtered_signal_y, filtered_signal_z, y_x, y_y, y_z, y_max, frq, peak_tupel, rr):
array_len = range(0, len(filtered_signal_x))
N = y_x.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(2, 1)
fig.suptitle('Combined plot with the bandpass filtered signals, power spectra and the rr.', fontsize="large")
ax[0].plot(array_len, filtered_signal_x, 'r', label='Bandpass filtered X')
ax[0].plot(array_len, filtered_signal_y, 'b', label='Bandpass filtered Y')
ax[0].plot(array_len, filtered_signal_z, 'g', label='Bandpass filtered Z')
ax[0].set_xlabel('Time in points (50dp/sec)')
ax[0].set_ylabel('Amplitude')
ax[0].legend(loc='best', fontsize=9)
ax[0].set_title("Bandpass filtered signals for X,Y,Z", fontsize="medium")
# plotting the spectrum
half_N = int(N/2)
ax[1].plot(frq, 2.0/N * np.abs(y_x[0:half_N]), 'r', label='Power spectrum X')
ax[1].plot(frq, 2.0/N * np.abs(y_y[0:half_N]), 'b', label='Power spectrum Y')
ax[1].plot(frq, 2.0/N * np.abs(y_z[0:half_N]), 'g', label='Power spectrum Z')
ax[1].plot(frq, 2.0/N * np.abs(y_max[0:half_N]), 'y', label='Maximum Power spectrum')
ax[1].plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
#ax[1].text(0.8, 0, 'RR = %d' % rr)
anchored_text = AnchoredText('RR = %f' % rr, loc=4)
ax[1].add_artist(anchored_text)
ax[1].set_xlabel('Frequency in Hz')
ax[1].set_ylabel('Power spectrum density')
ax[1].set_xlim([0.1, 0.6])
ax[1].legend(loc='best', fontsize=9)
ax[1].set_title("Power spectra - Marked peak and calculated RR", fontsize="medium")
# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)
#plt.show()
def visualise_filtered_signal_combined(self, filtered_array_x, filtered_array_y, filtered_array_z):
array_len = range(0, len(filtered_array_x))
fig, ax = plt.subplots(1, sharex=True, sharey=True)
# Plot all axes in one plot
fig.suptitle('Bandpass filtered Signal (0.2-0.45hz) - X-, Y-, Z-Axis combined')
ax.plot(array_len, filtered_array_x, 'r', label='X-Axis')
ax.plot(array_len, filtered_array_y, 'b', label='Y-Axis')
ax.plot(array_len, filtered_array_z, 'g', label='Z-Axis')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_filtered_signal_separate(self, filtered_array_x, filtered_array_y, filtered_array_z):
array_len = range(0, len(filtered_array_x))
# Plt all three Axis in one Figure using same X- and Y_x- Axis
fig, ax = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle('Bandpass filtered signal (0.2-0.45hz) separate for all axes', fontsize='large')
#fig.tight_layout()
xl, = ax[0].plot(array_len, filtered_array_x, 'r')
ax[0].set_title('Bandpass filtered signal - X-Axis', fontsize='medium')
yl, = ax[1].plot(array_len, filtered_array_y, 'b')
ax[1].set_title('Bandpass filtered signal - Y-Axis', fontsize='medium')
zl, = ax[2].plot(array_len, filtered_array_z, 'g')
ax[2].set_title('Bandpass filtered signal - Z-Axis', fontsize='medium')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
ax[0].legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'), loc='upper right', fontsize=9)
#plt.show()
def visualise_filter_design(self, b, a, sample_rate):
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
w, h = signal.freqz(b, a, worN=2000)
plt.plot((sample_rate * 0.5 / np.pi) * w, abs(h), label='Butterworth order 4')
plt.plot([0, 0.5 * sample_rate], [np.sqrt(0.5), np.sqrt(0.5)], '--', label='sqrt(0.5)')
plt.title('Bandpass filter design - Butterworth order 4 - 0.2 - 0.45Hz')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.xlim([0, 1])
plt.ylim([0, 1.1])
plt.grid(True)
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_power_spectrum_combined(self, frq, y_x, **kwargs):
y_y = kwargs.get('y_y', None)
y_z = kwargs.get('y_z', None)
y_max = kwargs.get('y_max', None)
rr = kwargs.get('rr', None)
peak_tupel = kwargs.get('peak_tupel', None)
N = y_x.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(1)
fig.suptitle('Power spectra for X-, Y-, Z-Axis', fontsize="large")
# plotting the spectrum
ax.plot(frq, 2.0/N * np.abs(y_x[0:N/2]), 'r', label='Power spectrum X')
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_y[0:N/2]), 'b', label='Power spectrum Y')
if y_z is not None:
ax.plot(frq, 2.0/N * np.abs(y_z[0:N/2]), 'g', label='Power spectrum Z')
if y_max is not None:
ax.plot(frq, 2.0/N * np.abs(y_max[0:N/2]), 'y', label='Maximum Power spectrum')
if peak_tupel is not None:
ax.plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
if rr is not None:
anchored_text = AnchoredText('RR = %f' % rr, loc=4)
plt.add_artist(anchored_text)
plt.xlabel('Frequency in Hz')
plt.ylabel('Power spectrum density')
plt.xlim([0.1, 0.6])
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_peak(self, frq, y_max, peak_tupel, **kwargs):
y_x = kwargs.get('y_x', None)
y_y = kwargs.get('y_y', None)
y_z = kwargs.get('y_z', None)
rr = kwargs.get('rr', None)
N = y_max.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(1)
fig.suptitle('Maximum power spectrum with peak.', fontsize="large")
# plotting the spectrum
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_x[0:N/2]), 'r', label='Power spectrum X')
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_y[0:N/2]), 'b', label='Power spectrum Y')
if y_z is not None:
ax.plot(frq, 2.0/N * np.abs(y_z[0:N/2]), 'g', label='Power spectrum Z')
ax.plot(frq, 2.0/N * np.abs(y_max[0:N/2]), 'y', label='Maximum Power spectrum')
ax.plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
text = 'Peak = %f ; %f' %(peak_tupel[0], peak_tupel[1])
#ax.add_artist(anchored_text)
if rr is not None:
text += '\n' + 'RR = %f' %rr
anchored_text = AnchoredText(text, loc=4, prop=dict(color='Black', size=9))
ax.add_artist(anchored_text)
ax.set_xlabel('Frequency in Hz')
ax.set_ylabel('Power spectrum density')
ax.set_xlim([0.1, 0.6])
plt.legend(loc='best', fontsize=9)
#plt.show() | Code/Visualization.py | __author__ = '<NAME> @MadMax93'
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
import peakutils
import matplotlib.gridspec as gridspec
from peakutils.plot import plot as pplot
from matplotlib.offsetbox import AnchoredText
class Visualization(object):
def visualise_raw_data_combined(self, raw_data_array):
data_x = raw_data_array['X']
data_y = raw_data_array['Y']
data_z = raw_data_array['Z']
array_len = range(0, len(raw_data_array))
fig, ax = plt.subplots(1, sharex=True)
xl, = ax.plot(array_len, data_x, 'r', label='X-Axis')
fig.suptitle('Raw signal all axes combined')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
yl, = ax.plot(array_len, data_y, 'b', label='Y-Axis')
zl, = ax.plot(array_len, data_z, 'g', label='Z-Axis')
fig.legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'),loc='center right', fontsize=9)
#plt.show()
def visualise_raw_data_separate(self, raw_data_array):
data_x = raw_data_array['X']
data_y = raw_data_array['Y']
data_z = raw_data_array['Z']
array_len = range(0, len(raw_data_array))
fig, ax = plt.subplots(3, sharex=True)
xl, = ax[0].plot(array_len, data_x, 'r', label='X-Axis')
fig.suptitle('Raw signal all axes combined', fontsize='large')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
yl, = ax[1].plot(array_len, data_y, 'b', label='Y-Axis')
zl, = ax[2].plot(array_len, data_z, 'g', label='Z-Axis')
ax[0].set_title('Raw signal - X-Axis', fontsize='medium')
ax[1].set_title('Raw signal - Y-Axis', fontsize='medium')
ax[2].set_title('Raw signal - Z-Axis', fontsize='medium')
fig.legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'), loc='center right', fontsize=9)
#plt.show()
def visualise_signals_and_xyz_and_maximum_power_spectrum(self, filtered_signal_x, filtered_signal_y, filtered_signal_z, y_x, y_y, y_z, y_max, frq, peak_tupel, rr):
array_len = range(0, len(filtered_signal_x))
N = y_x.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(2, 1)
fig.suptitle('Combined plot with the bandpass filtered signals, power spectra and the rr.', fontsize="large")
ax[0].plot(array_len, filtered_signal_x, 'r', label='Bandpass filtered X')
ax[0].plot(array_len, filtered_signal_y, 'b', label='Bandpass filtered Y')
ax[0].plot(array_len, filtered_signal_z, 'g', label='Bandpass filtered Z')
ax[0].set_xlabel('Time in points (50dp/sec)')
ax[0].set_ylabel('Amplitude')
ax[0].legend(loc='best', fontsize=9)
ax[0].set_title("Bandpass filtered signals for X,Y,Z", fontsize="medium")
# plotting the spectrum
half_N = int(N/2)
ax[1].plot(frq, 2.0/N * np.abs(y_x[0:half_N]), 'r', label='Power spectrum X')
ax[1].plot(frq, 2.0/N * np.abs(y_y[0:half_N]), 'b', label='Power spectrum Y')
ax[1].plot(frq, 2.0/N * np.abs(y_z[0:half_N]), 'g', label='Power spectrum Z')
ax[1].plot(frq, 2.0/N * np.abs(y_max[0:half_N]), 'y', label='Maximum Power spectrum')
ax[1].plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
#ax[1].text(0.8, 0, 'RR = %d' % rr)
anchored_text = AnchoredText('RR = %f' % rr, loc=4)
ax[1].add_artist(anchored_text)
ax[1].set_xlabel('Frequency in Hz')
ax[1].set_ylabel('Power spectrum density')
ax[1].set_xlim([0.1, 0.6])
ax[1].legend(loc='best', fontsize=9)
ax[1].set_title("Power spectra - Marked peak and calculated RR", fontsize="medium")
# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)
#plt.show()
def visualise_filtered_signal_combined(self, filtered_array_x, filtered_array_y, filtered_array_z):
array_len = range(0, len(filtered_array_x))
fig, ax = plt.subplots(1, sharex=True, sharey=True)
# Plot all axes in one plot
fig.suptitle('Bandpass filtered Signal (0.2-0.45hz) - X-, Y-, Z-Axis combined')
ax.plot(array_len, filtered_array_x, 'r', label='X-Axis')
ax.plot(array_len, filtered_array_y, 'b', label='Y-Axis')
ax.plot(array_len, filtered_array_z, 'g', label='Z-Axis')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_filtered_signal_separate(self, filtered_array_x, filtered_array_y, filtered_array_z):
array_len = range(0, len(filtered_array_x))
# Plt all three Axis in one Figure using same X- and Y_x- Axis
fig, ax = plt.subplots(3, sharex=True, sharey=True)
fig.suptitle('Bandpass filtered signal (0.2-0.45hz) separate for all axes', fontsize='large')
#fig.tight_layout()
xl, = ax[0].plot(array_len, filtered_array_x, 'r')
ax[0].set_title('Bandpass filtered signal - X-Axis', fontsize='medium')
yl, = ax[1].plot(array_len, filtered_array_y, 'b')
ax[1].set_title('Bandpass filtered signal - Y-Axis', fontsize='medium')
zl, = ax[2].plot(array_len, filtered_array_z, 'g')
ax[2].set_title('Bandpass filtered signal - Z-Axis', fontsize='medium')
plt.xlabel('Time in points (50dp/sec)')
plt.ylabel('Signal value')
ax[0].legend((xl, yl, zl), ('X-Axis', 'Y-Axis', 'Z-Axis'), loc='upper right', fontsize=9)
#plt.show()
def visualise_filter_design(self, b, a, sample_rate):
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
w, h = signal.freqz(b, a, worN=2000)
plt.plot((sample_rate * 0.5 / np.pi) * w, abs(h), label='Butterworth order 4')
plt.plot([0, 0.5 * sample_rate], [np.sqrt(0.5), np.sqrt(0.5)], '--', label='sqrt(0.5)')
plt.title('Bandpass filter design - Butterworth order 4 - 0.2 - 0.45Hz')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.xlim([0, 1])
plt.ylim([0, 1.1])
plt.grid(True)
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_power_spectrum_combined(self, frq, y_x, **kwargs):
y_y = kwargs.get('y_y', None)
y_z = kwargs.get('y_z', None)
y_max = kwargs.get('y_max', None)
rr = kwargs.get('rr', None)
peak_tupel = kwargs.get('peak_tupel', None)
N = y_x.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(1)
fig.suptitle('Power spectra for X-, Y-, Z-Axis', fontsize="large")
# plotting the spectrum
ax.plot(frq, 2.0/N * np.abs(y_x[0:N/2]), 'r', label='Power spectrum X')
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_y[0:N/2]), 'b', label='Power spectrum Y')
if y_z is not None:
ax.plot(frq, 2.0/N * np.abs(y_z[0:N/2]), 'g', label='Power spectrum Z')
if y_max is not None:
ax.plot(frq, 2.0/N * np.abs(y_max[0:N/2]), 'y', label='Maximum Power spectrum')
if peak_tupel is not None:
ax.plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
if rr is not None:
anchored_text = AnchoredText('RR = %f' % rr, loc=4)
plt.add_artist(anchored_text)
plt.xlabel('Frequency in Hz')
plt.ylabel('Power spectrum density')
plt.xlim([0.1, 0.6])
plt.legend(loc='best', fontsize=9)
#plt.show()
def visualise_peak(self, frq, y_max, peak_tupel, **kwargs):
y_x = kwargs.get('y_x', None)
y_y = kwargs.get('y_y', None)
y_z = kwargs.get('y_z', None)
rr = kwargs.get('rr', None)
N = y_max.size
#plt.xkcd() #HAHA! COMIC STYLE - XKCD
fig, ax = plt.subplots(1)
fig.suptitle('Maximum power spectrum with peak.', fontsize="large")
# plotting the spectrum
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_x[0:N/2]), 'r', label='Power spectrum X')
if y_y is not None:
ax.plot(frq, 2.0/N * np.abs(y_y[0:N/2]), 'b', label='Power spectrum Y')
if y_z is not None:
ax.plot(frq, 2.0/N * np.abs(y_z[0:N/2]), 'g', label='Power spectrum Z')
ax.plot(frq, 2.0/N * np.abs(y_max[0:N/2]), 'y', label='Maximum Power spectrum')
ax.plot(peak_tupel[0], peak_tupel[1], 'rx', label='Peak')
text = 'Peak = %f ; %f' %(peak_tupel[0], peak_tupel[1])
#ax.add_artist(anchored_text)
if rr is not None:
text += '\n' + 'RR = %f' %rr
anchored_text = AnchoredText(text, loc=4, prop=dict(color='Black', size=9))
ax.add_artist(anchored_text)
ax.set_xlabel('Frequency in Hz')
ax.set_ylabel('Power spectrum density')
ax.set_xlim([0.1, 0.6])
plt.legend(loc='best', fontsize=9)
#plt.show() | 0.670393 | 0.682389 |
from __future__ import absolute_import
import six
from thrift.util.Recursive import fix_spec
from thrift.Thrift import *
from thrift.protocol.TProtocol import TProtocolException
import pprint
import warnings
from thrift import Thrift
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.protocol import THeaderProtocol
try:
from thrift.protocol import fastproto
except:
fastproto = None
all_structs = []
UTF8STRINGS = bool(0) or sys.version_info.major >= 3
__all__ = ['UTF8STRINGS', 'EmptyEnum', 'City', 'Company', 'Internship', 'UnEnumStruct', 'Range', 'struct1', 'struct2', 'struct3', 'union1', 'union2']
class EmptyEnum:
_VALUES_TO_NAMES = {
}
_NAMES_TO_VALUES = {
}
class City:
NYC = 0
MPK = 1
SEA = 2
LON = 3
_VALUES_TO_NAMES = {
0: "NYC",
1: "MPK",
2: "SEA",
3: "LON",
}
_NAMES_TO_VALUES = {
"NYC": 0,
"MPK": 1,
"SEA": 2,
"LON": 3,
}
class Company:
FACEBOOK = 0
WHATSAPP = 1
OCULUS = 2
INSTAGRAM = 3
_VALUES_TO_NAMES = {
0: "FACEBOOK",
1: "WHATSAPP",
2: "OCULUS",
3: "INSTAGRAM",
}
_NAMES_TO_VALUES = {
"FACEBOOK": 0,
"WHATSAPP": 1,
"OCULUS": 2,
"INSTAGRAM": 3,
}
class Internship:
"""
Attributes:
- weeks
- title
- employer
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.weeks = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.title = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I32:
self.employer = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
if self.weeks == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'weeks' was not found in serialized data! Struct: Internship")
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('Internship')
if self.weeks != None:
oprot.writeFieldBegin('weeks', TType.I32, 1)
oprot.writeI32(self.weeks)
oprot.writeFieldEnd()
if self.title != None:
oprot.writeFieldBegin('title', TType.STRING, 2)
oprot.writeString(self.title.encode('utf-8')) if UTF8STRINGS and not isinstance(self.title, bytes) else oprot.writeString(self.title)
oprot.writeFieldEnd()
if self.employer != None:
oprot.writeFieldBegin('employer', TType.I32, 3)
oprot.writeI32(self.employer)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.weeks, indent=0)
value = padding.join(value.splitlines(True))
L.append(' weeks=%s' % (value))
value = pprint.pformat(self.title, indent=0)
value = padding.join(value.splitlines(True))
L.append(' title=%s' % (value))
value = pprint.pformat(self.employer, indent=0)
value = padding.join(value.splitlines(True))
L.append(' employer=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class UnEnumStruct:
"""
Attributes:
- city
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.city = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('UnEnumStruct')
if self.city != None:
oprot.writeFieldBegin('city', TType.I32, 1)
oprot.writeI32(self.city)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.city, indent=0)
value = padding.join(value.splitlines(True))
L.append(' city=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class Range:
"""
Attributes:
- min
- max
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.min = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.max = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
if self.min == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'min' was not found in serialized data! Struct: Range")
if self.max == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'max' was not found in serialized data! Struct: Range")
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('Range')
if self.min != None:
oprot.writeFieldBegin('min', TType.I32, 1)
oprot.writeI32(self.min)
oprot.writeFieldEnd()
if self.max != None:
oprot.writeFieldBegin('max', TType.I32, 2)
oprot.writeI32(self.max)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.min, indent=0)
value = padding.join(value.splitlines(True))
L.append(' min=%s' % (value))
value = pprint.pformat(self.max, indent=0)
value = padding.join(value.splitlines(True))
L.append(' max=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct1:
"""
Attributes:
- a
- b
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.a = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.b = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct1')
if self.a != None:
oprot.writeFieldBegin('a', TType.I32, 1)
oprot.writeI32(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.STRING, 2)
oprot.writeString(self.b.encode('utf-8')) if UTF8STRINGS and not isinstance(self.b, bytes) else oprot.writeString(self.b)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct2:
"""
Attributes:
- a
- b
- c
- d
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.a = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.b = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
self.c = struct1()
self.c.read(iprot)
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.LIST:
self.d = []
(_etype3, _size0) = iprot.readListBegin()
if _size0 >= 0:
for _i4 in six.moves.range(_size0):
_elem5 = iprot.readI32()
self.d.append(_elem5)
else:
while iprot.peekList():
_elem6 = iprot.readI32()
self.d.append(_elem6)
iprot.readListEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct2')
if self.a != None:
oprot.writeFieldBegin('a', TType.I32, 1)
oprot.writeI32(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.STRING, 2)
oprot.writeString(self.b.encode('utf-8')) if UTF8STRINGS and not isinstance(self.b, bytes) else oprot.writeString(self.b)
oprot.writeFieldEnd()
if self.c != None:
oprot.writeFieldBegin('c', TType.STRUCT, 3)
self.c.write(oprot)
oprot.writeFieldEnd()
if self.d != None:
oprot.writeFieldBegin('d', TType.LIST, 4)
oprot.writeListBegin(TType.I32, len(self.d))
for iter7 in self.d:
oprot.writeI32(iter7)
oprot.writeListEnd()
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
value = pprint.pformat(self.c, indent=0)
value = padding.join(value.splitlines(True))
L.append(' c=%s' % (value))
value = pprint.pformat(self.d, indent=0)
value = padding.join(value.splitlines(True))
L.append(' d=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct3:
"""
Attributes:
- a
- b
- c
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.a = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.b = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
self.c = struct2()
self.c.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct3')
if self.a != None:
oprot.writeFieldBegin('a', TType.STRING, 1)
oprot.writeString(self.a.encode('utf-8')) if UTF8STRINGS and not isinstance(self.a, bytes) else oprot.writeString(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.I32, 2)
oprot.writeI32(self.b)
oprot.writeFieldEnd()
if self.c != None:
oprot.writeFieldBegin('c', TType.STRUCT, 3)
self.c.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
value = pprint.pformat(self.c, indent=0)
value = padding.join(value.splitlines(True))
L.append(' c=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class union1(object):
"""
Attributes:
- i
- d
"""
thrift_spec = None
__init__ = None
__EMPTY__ = 0
I = 1
D = 2
@staticmethod
def isUnion():
return True
def get_i(self):
assert self.field == 1
return self.value
def get_d(self):
assert self.field == 2
return self.value
def set_i(self, value):
self.field = 1
self.value = value
def set_d(self, value):
self.field = 2
self.value = value
def getType(self):
return self.field
def __repr__(self):
value = pprint.pformat(self.value)
member = ''
if self.field == 1:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('i', value)
if self.field == 2:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('d', value)
return "%s(%s)" % (self.__class__.__name__, member)
def read(self, iprot):
self.field = 0
self.value = None
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
i = iprot.readI32()
assert self.field == 0 and self.value is None
self.set_i(i)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.DOUBLE:
d = iprot.readDouble()
assert self.field == 0 and self.value is None
self.set_d(d)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeUnionBegin('union1')
if self.field == 1:
oprot.writeFieldBegin('i', TType.I32, 1)
i = self.value
oprot.writeI32(i)
oprot.writeFieldEnd()
if self.field == 2:
oprot.writeFieldBegin('d', TType.DOUBLE, 2)
d = self.value
oprot.writeDouble(d)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeUnionEnd()
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class union2(object):
"""
Attributes:
- i
- d
- s
- u
"""
thrift_spec = None
__init__ = None
__EMPTY__ = 0
I = 1
D = 2
S = 3
U = 4
@staticmethod
def isUnion():
return True
def get_i(self):
assert self.field == 1
return self.value
def get_d(self):
assert self.field == 2
return self.value
def get_s(self):
assert self.field == 3
return self.value
def get_u(self):
assert self.field == 4
return self.value
def set_i(self, value):
self.field = 1
self.value = value
def set_d(self, value):
self.field = 2
self.value = value
def set_s(self, value):
self.field = 3
self.value = value
def set_u(self, value):
self.field = 4
self.value = value
def getType(self):
return self.field
def __repr__(self):
value = pprint.pformat(self.value)
member = ''
if self.field == 1:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('i', value)
if self.field == 2:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('d', value)
if self.field == 3:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('s', value)
if self.field == 4:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('u', value)
return "%s(%s)" % (self.__class__.__name__, member)
def read(self, iprot):
self.field = 0
self.value = None
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
i = iprot.readI32()
assert self.field == 0 and self.value is None
self.set_i(i)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.DOUBLE:
d = iprot.readDouble()
assert self.field == 0 and self.value is None
self.set_d(d)
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
s = struct1()
s.read(iprot)
assert self.field == 0 and self.value is None
self.set_s(s)
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.STRUCT:
u = union1()
u.read(iprot)
assert self.field == 0 and self.value is None
self.set_u(u)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeUnionBegin('union2')
if self.field == 1:
oprot.writeFieldBegin('i', TType.I32, 1)
i = self.value
oprot.writeI32(i)
oprot.writeFieldEnd()
if self.field == 2:
oprot.writeFieldBegin('d', TType.DOUBLE, 2)
d = self.value
oprot.writeDouble(d)
oprot.writeFieldEnd()
if self.field == 3:
oprot.writeFieldBegin('s', TType.STRUCT, 3)
s = self.value
s.write(oprot)
oprot.writeFieldEnd()
if self.field == 4:
oprot.writeFieldBegin('u', TType.STRUCT, 4)
u = self.value
u.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeUnionEnd()
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
all_structs.append(Internship)
Internship.thrift_spec = (
None, # 0
(1, TType.I32, 'weeks', None, None, 0, ), # 1
(2, TType.STRING, 'title', True, None, 2, ), # 2
(3, TType.I32, 'employer', Company, None, 1, ), # 3
)
Internship.thrift_struct_annotations = {
}
Internship.thrift_field_annotations = {
}
def Internship__init__(self, weeks=None, title=None, employer=None,):
self.weeks = weeks
self.title = title
self.employer = employer
Internship.__init__ = Internship__init__
def Internship__setstate__(self, state):
state.setdefault('weeks', None)
state.setdefault('title', None)
state.setdefault('employer', None)
self.__dict__ = state
Internship.__getstate__ = lambda self: self.__dict__.copy()
Internship.__setstate__ = Internship__setstate__
all_structs.append(UnEnumStruct)
UnEnumStruct.thrift_spec = (
None, # 0
(1, TType.I32, 'city', City, -1, 2, ), # 1
)
UnEnumStruct.thrift_struct_annotations = {
}
UnEnumStruct.thrift_field_annotations = {
}
def UnEnumStruct__init__(self, city=UnEnumStruct.thrift_spec[1][4],):
self.city = city
UnEnumStruct.__init__ = UnEnumStruct__init__
def UnEnumStruct__setstate__(self, state):
state.setdefault('city', -1)
self.__dict__ = state
UnEnumStruct.__getstate__ = lambda self: self.__dict__.copy()
UnEnumStruct.__setstate__ = UnEnumStruct__setstate__
all_structs.append(Range)
Range.thrift_spec = (
None, # 0
(1, TType.I32, 'min', None, None, 0, ), # 1
(2, TType.I32, 'max', None, None, 0, ), # 2
)
Range.thrift_struct_annotations = {
}
Range.thrift_field_annotations = {
}
def Range__init__(self, min=None, max=None,):
self.min = min
self.max = max
Range.__init__ = Range__init__
def Range__setstate__(self, state):
state.setdefault('min', None)
state.setdefault('max', None)
self.__dict__ = state
Range.__getstate__ = lambda self: self.__dict__.copy()
Range.__setstate__ = Range__setstate__
all_structs.append(struct1)
struct1.thrift_spec = (
None, # 0
(1, TType.I32, 'a', None, 1234567, 2, ), # 1
(2, TType.STRING, 'b', True, "<uninitialized>", 2, ), # 2
)
struct1.thrift_struct_annotations = {
}
struct1.thrift_field_annotations = {
}
def struct1__init__(self, a=struct1.thrift_spec[1][4], b=struct1.thrift_spec[2][4],):
self.a = a
self.b = b
struct1.__init__ = struct1__init__
def struct1__setstate__(self, state):
state.setdefault('a', 1234567)
state.setdefault('b', "<uninitialized>")
self.__dict__ = state
struct1.__getstate__ = lambda self: self.__dict__.copy()
struct1.__setstate__ = struct1__setstate__
all_structs.append(struct2)
struct2.thrift_spec = (
None, # 0
(1, TType.I32, 'a', None, None, 2, ), # 1
(2, TType.STRING, 'b', True, None, 2, ), # 2
(3, TType.STRUCT, 'c', [struct1, struct1.thrift_spec, False], None, 2, ), # 3
(4, TType.LIST, 'd', (TType.I32,None), None, 2, ), # 4
)
struct2.thrift_struct_annotations = {
}
struct2.thrift_field_annotations = {
}
def struct2__init__(self, a=None, b=None, c=None, d=None,):
self.a = a
self.b = b
self.c = c
self.d = d
struct2.__init__ = struct2__init__
def struct2__setstate__(self, state):
state.setdefault('a', None)
state.setdefault('b', None)
state.setdefault('c', None)
state.setdefault('d', None)
self.__dict__ = state
struct2.__getstate__ = lambda self: self.__dict__.copy()
struct2.__setstate__ = struct2__setstate__
all_structs.append(struct3)
struct3.thrift_spec = (
None, # 0
(1, TType.STRING, 'a', True, None, 2, ), # 1
(2, TType.I32, 'b', None, None, 2, ), # 2
(3, TType.STRUCT, 'c', [struct2, struct2.thrift_spec, False], None, 2, ), # 3
)
struct3.thrift_struct_annotations = {
}
struct3.thrift_field_annotations = {
}
def struct3__init__(self, a=None, b=None, c=None,):
self.a = a
self.b = b
self.c = c
struct3.__init__ = struct3__init__
def struct3__setstate__(self, state):
state.setdefault('a', None)
state.setdefault('b', None)
state.setdefault('c', None)
self.__dict__ = state
struct3.__getstate__ = lambda self: self.__dict__.copy()
struct3.__setstate__ = struct3__setstate__
all_structs.append(union1)
union1.thrift_spec = (
None, # 0
(1, TType.I32, 'i', None, None, 2, ), # 1
(2, TType.DOUBLE, 'd', None, None, 2, ), # 2
)
union1.thrift_struct_annotations = {
}
union1.thrift_field_annotations = {
}
def union1__init__(self, i=None, d=None,):
self.field = 0
self.value = None
if i is not None:
assert self.field == 0 and self.value is None
self.field = 1
self.value = i
if d is not None:
assert self.field == 0 and self.value is None
self.field = 2
self.value = d
union1.__init__ = union1__init__
all_structs.append(union2)
union2.thrift_spec = (
None, # 0
(1, TType.I32, 'i', None, None, 2, ), # 1
(2, TType.DOUBLE, 'd', None, None, 2, ), # 2
(3, TType.STRUCT, 's', [struct1, struct1.thrift_spec, False], None, 2, ), # 3
(4, TType.STRUCT, 'u', [union1, union1.thrift_spec, True], None, 2, ), # 4
)
union2.thrift_struct_annotations = {
}
union2.thrift_field_annotations = {
}
def union2__init__(self, i=None, d=None, s=None, u=None,):
self.field = 0
self.value = None
if i is not None:
assert self.field == 0 and self.value is None
self.field = 1
self.value = i
if d is not None:
assert self.field == 0 and self.value is None
self.field = 2
self.value = d
if s is not None:
assert self.field == 0 and self.value is None
self.field = 3
self.value = s
if u is not None:
assert self.field == 0 and self.value is None
self.field = 4
self.value = u
union2.__init__ = union2__init__
fix_spec(all_structs)
del all_structs | thrift/compiler/test/fixtures/constants/gen-py/module/ttypes.py |
from __future__ import absolute_import
import six
from thrift.util.Recursive import fix_spec
from thrift.Thrift import *
from thrift.protocol.TProtocol import TProtocolException
import pprint
import warnings
from thrift import Thrift
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.protocol import THeaderProtocol
try:
from thrift.protocol import fastproto
except:
fastproto = None
all_structs = []
UTF8STRINGS = bool(0) or sys.version_info.major >= 3
__all__ = ['UTF8STRINGS', 'EmptyEnum', 'City', 'Company', 'Internship', 'UnEnumStruct', 'Range', 'struct1', 'struct2', 'struct3', 'union1', 'union2']
class EmptyEnum:
_VALUES_TO_NAMES = {
}
_NAMES_TO_VALUES = {
}
class City:
NYC = 0
MPK = 1
SEA = 2
LON = 3
_VALUES_TO_NAMES = {
0: "NYC",
1: "MPK",
2: "SEA",
3: "LON",
}
_NAMES_TO_VALUES = {
"NYC": 0,
"MPK": 1,
"SEA": 2,
"LON": 3,
}
class Company:
FACEBOOK = 0
WHATSAPP = 1
OCULUS = 2
INSTAGRAM = 3
_VALUES_TO_NAMES = {
0: "FACEBOOK",
1: "WHATSAPP",
2: "OCULUS",
3: "INSTAGRAM",
}
_NAMES_TO_VALUES = {
"FACEBOOK": 0,
"WHATSAPP": 1,
"OCULUS": 2,
"INSTAGRAM": 3,
}
class Internship:
"""
Attributes:
- weeks
- title
- employer
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.weeks = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.title = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I32:
self.employer = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
if self.weeks == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'weeks' was not found in serialized data! Struct: Internship")
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('Internship')
if self.weeks != None:
oprot.writeFieldBegin('weeks', TType.I32, 1)
oprot.writeI32(self.weeks)
oprot.writeFieldEnd()
if self.title != None:
oprot.writeFieldBegin('title', TType.STRING, 2)
oprot.writeString(self.title.encode('utf-8')) if UTF8STRINGS and not isinstance(self.title, bytes) else oprot.writeString(self.title)
oprot.writeFieldEnd()
if self.employer != None:
oprot.writeFieldBegin('employer', TType.I32, 3)
oprot.writeI32(self.employer)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.weeks, indent=0)
value = padding.join(value.splitlines(True))
L.append(' weeks=%s' % (value))
value = pprint.pformat(self.title, indent=0)
value = padding.join(value.splitlines(True))
L.append(' title=%s' % (value))
value = pprint.pformat(self.employer, indent=0)
value = padding.join(value.splitlines(True))
L.append(' employer=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class UnEnumStruct:
"""
Attributes:
- city
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.city = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('UnEnumStruct')
if self.city != None:
oprot.writeFieldBegin('city', TType.I32, 1)
oprot.writeI32(self.city)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.city, indent=0)
value = padding.join(value.splitlines(True))
L.append(' city=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class Range:
"""
Attributes:
- min
- max
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.min = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.max = iprot.readI32()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
if self.min == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'min' was not found in serialized data! Struct: Range")
if self.max == None:
raise TProtocolException(TProtocolException.MISSING_REQUIRED_FIELD, "Required field 'max' was not found in serialized data! Struct: Range")
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('Range')
if self.min != None:
oprot.writeFieldBegin('min', TType.I32, 1)
oprot.writeI32(self.min)
oprot.writeFieldEnd()
if self.max != None:
oprot.writeFieldBegin('max', TType.I32, 2)
oprot.writeI32(self.max)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.min, indent=0)
value = padding.join(value.splitlines(True))
L.append(' min=%s' % (value))
value = pprint.pformat(self.max, indent=0)
value = padding.join(value.splitlines(True))
L.append(' max=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct1:
"""
Attributes:
- a
- b
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.a = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.b = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct1')
if self.a != None:
oprot.writeFieldBegin('a', TType.I32, 1)
oprot.writeI32(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.STRING, 2)
oprot.writeString(self.b.encode('utf-8')) if UTF8STRINGS and not isinstance(self.b, bytes) else oprot.writeString(self.b)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct2:
"""
Attributes:
- a
- b
- c
- d
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.a = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.STRING:
self.b = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
self.c = struct1()
self.c.read(iprot)
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.LIST:
self.d = []
(_etype3, _size0) = iprot.readListBegin()
if _size0 >= 0:
for _i4 in six.moves.range(_size0):
_elem5 = iprot.readI32()
self.d.append(_elem5)
else:
while iprot.peekList():
_elem6 = iprot.readI32()
self.d.append(_elem6)
iprot.readListEnd()
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct2')
if self.a != None:
oprot.writeFieldBegin('a', TType.I32, 1)
oprot.writeI32(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.STRING, 2)
oprot.writeString(self.b.encode('utf-8')) if UTF8STRINGS and not isinstance(self.b, bytes) else oprot.writeString(self.b)
oprot.writeFieldEnd()
if self.c != None:
oprot.writeFieldBegin('c', TType.STRUCT, 3)
self.c.write(oprot)
oprot.writeFieldEnd()
if self.d != None:
oprot.writeFieldBegin('d', TType.LIST, 4)
oprot.writeListBegin(TType.I32, len(self.d))
for iter7 in self.d:
oprot.writeI32(iter7)
oprot.writeListEnd()
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
value = pprint.pformat(self.c, indent=0)
value = padding.join(value.splitlines(True))
L.append(' c=%s' % (value))
value = pprint.pformat(self.d, indent=0)
value = padding.join(value.splitlines(True))
L.append(' d=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class struct3:
"""
Attributes:
- a
- b
- c
"""
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
@staticmethod
def isUnion():
return False
def read(self, iprot):
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRING:
self.a = iprot.readString().decode('utf-8') if UTF8STRINGS else iprot.readString()
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.b = iprot.readI32()
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
self.c = struct2()
self.c.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
self.checkRequired()
def checkRequired(self):
return
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, False], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeStructBegin('struct3')
if self.a != None:
oprot.writeFieldBegin('a', TType.STRING, 1)
oprot.writeString(self.a.encode('utf-8')) if UTF8STRINGS and not isinstance(self.a, bytes) else oprot.writeString(self.a)
oprot.writeFieldEnd()
if self.b != None:
oprot.writeFieldBegin('b', TType.I32, 2)
oprot.writeI32(self.b)
oprot.writeFieldEnd()
if self.c != None:
oprot.writeFieldBegin('c', TType.STRUCT, 3)
self.c.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def __repr__(self):
L = []
padding = ' ' * 4
value = pprint.pformat(self.a, indent=0)
value = padding.join(value.splitlines(True))
L.append(' a=%s' % (value))
value = pprint.pformat(self.b, indent=0)
value = padding.join(value.splitlines(True))
L.append(' b=%s' % (value))
value = pprint.pformat(self.c, indent=0)
value = padding.join(value.splitlines(True))
L.append(' c=%s' % (value))
return "%s(\n%s)" % (self.__class__.__name__, ",\n".join(L))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
# Override the __hash__ function for Python3 - t10434117
if not six.PY2:
__hash__ = object.__hash__
class union1(object):
"""
Attributes:
- i
- d
"""
thrift_spec = None
__init__ = None
__EMPTY__ = 0
I = 1
D = 2
@staticmethod
def isUnion():
return True
def get_i(self):
assert self.field == 1
return self.value
def get_d(self):
assert self.field == 2
return self.value
def set_i(self, value):
self.field = 1
self.value = value
def set_d(self, value):
self.field = 2
self.value = value
def getType(self):
return self.field
def __repr__(self):
value = pprint.pformat(self.value)
member = ''
if self.field == 1:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('i', value)
if self.field == 2:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('d', value)
return "%s(%s)" % (self.__class__.__name__, member)
def read(self, iprot):
self.field = 0
self.value = None
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
i = iprot.readI32()
assert self.field == 0 and self.value is None
self.set_i(i)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.DOUBLE:
d = iprot.readDouble()
assert self.field == 0 and self.value is None
self.set_d(d)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeUnionBegin('union1')
if self.field == 1:
oprot.writeFieldBegin('i', TType.I32, 1)
i = self.value
oprot.writeI32(i)
oprot.writeFieldEnd()
if self.field == 2:
oprot.writeFieldBegin('d', TType.DOUBLE, 2)
d = self.value
oprot.writeDouble(d)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeUnionEnd()
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class union2(object):
"""
Attributes:
- i
- d
- s
- u
"""
thrift_spec = None
__init__ = None
__EMPTY__ = 0
I = 1
D = 2
S = 3
U = 4
@staticmethod
def isUnion():
return True
def get_i(self):
assert self.field == 1
return self.value
def get_d(self):
assert self.field == 2
return self.value
def get_s(self):
assert self.field == 3
return self.value
def get_u(self):
assert self.field == 4
return self.value
def set_i(self, value):
self.field = 1
self.value = value
def set_d(self, value):
self.field = 2
self.value = value
def set_s(self, value):
self.field = 3
self.value = value
def set_u(self, value):
self.field = 4
self.value = value
def getType(self):
return self.field
def __repr__(self):
value = pprint.pformat(self.value)
member = ''
if self.field == 1:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('i', value)
if self.field == 2:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('d', value)
if self.field == 3:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('s', value)
if self.field == 4:
padding = ' ' * 2
value = padding.join(value.splitlines(True))
member = '\n %s=%s' % ('u', value)
return "%s(%s)" % (self.__class__.__name__, member)
def read(self, iprot):
self.field = 0
self.value = None
if (isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0)
self.checkRequired()
return
if (isinstance(iprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeaderProtocolAccelerate) and iprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastproto is not None:
fastproto.decode(self, iprot.trans, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2)
self.checkRequired()
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
i = iprot.readI32()
assert self.field == 0 and self.value is None
self.set_i(i)
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.DOUBLE:
d = iprot.readDouble()
assert self.field == 0 and self.value is None
self.set_d(d)
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRUCT:
s = struct1()
s.read(iprot)
assert self.field == 0 and self.value is None
self.set_s(s)
else:
iprot.skip(ftype)
elif fid == 4:
if ftype == TType.STRUCT:
u = union1()
u.read(iprot)
assert self.field == 0 and self.value is None
self.set_u(u)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if (isinstance(oprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_BINARY_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=0))
return
if (isinstance(oprot, TCompactProtocol.TCompactProtocolAccelerated) or (isinstance(oprot, THeaderProtocol.THeaderProtocolAccelerate) and oprot.get_protocol_id() == THeaderProtocol.THeaderProtocol.T_COMPACT_PROTOCOL)) and self.thrift_spec is not None and fastproto is not None:
oprot.trans.write(fastproto.encode(self, [self.__class__, self.thrift_spec, True], utf8strings=UTF8STRINGS, protoid=2))
return
oprot.writeUnionBegin('union2')
if self.field == 1:
oprot.writeFieldBegin('i', TType.I32, 1)
i = self.value
oprot.writeI32(i)
oprot.writeFieldEnd()
if self.field == 2:
oprot.writeFieldBegin('d', TType.DOUBLE, 2)
d = self.value
oprot.writeDouble(d)
oprot.writeFieldEnd()
if self.field == 3:
oprot.writeFieldBegin('s', TType.STRUCT, 3)
s = self.value
s.write(oprot)
oprot.writeFieldEnd()
if self.field == 4:
oprot.writeFieldBegin('u', TType.STRUCT, 4)
u = self.value
u.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeUnionEnd()
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
all_structs.append(Internship)
Internship.thrift_spec = (
None, # 0
(1, TType.I32, 'weeks', None, None, 0, ), # 1
(2, TType.STRING, 'title', True, None, 2, ), # 2
(3, TType.I32, 'employer', Company, None, 1, ), # 3
)
Internship.thrift_struct_annotations = {
}
Internship.thrift_field_annotations = {
}
def Internship__init__(self, weeks=None, title=None, employer=None,):
self.weeks = weeks
self.title = title
self.employer = employer
Internship.__init__ = Internship__init__
def Internship__setstate__(self, state):
state.setdefault('weeks', None)
state.setdefault('title', None)
state.setdefault('employer', None)
self.__dict__ = state
Internship.__getstate__ = lambda self: self.__dict__.copy()
Internship.__setstate__ = Internship__setstate__
all_structs.append(UnEnumStruct)
UnEnumStruct.thrift_spec = (
None, # 0
(1, TType.I32, 'city', City, -1, 2, ), # 1
)
UnEnumStruct.thrift_struct_annotations = {
}
UnEnumStruct.thrift_field_annotations = {
}
def UnEnumStruct__init__(self, city=UnEnumStruct.thrift_spec[1][4],):
self.city = city
UnEnumStruct.__init__ = UnEnumStruct__init__
def UnEnumStruct__setstate__(self, state):
state.setdefault('city', -1)
self.__dict__ = state
UnEnumStruct.__getstate__ = lambda self: self.__dict__.copy()
UnEnumStruct.__setstate__ = UnEnumStruct__setstate__
all_structs.append(Range)
Range.thrift_spec = (
None, # 0
(1, TType.I32, 'min', None, None, 0, ), # 1
(2, TType.I32, 'max', None, None, 0, ), # 2
)
Range.thrift_struct_annotations = {
}
Range.thrift_field_annotations = {
}
def Range__init__(self, min=None, max=None,):
self.min = min
self.max = max
Range.__init__ = Range__init__
def Range__setstate__(self, state):
state.setdefault('min', None)
state.setdefault('max', None)
self.__dict__ = state
Range.__getstate__ = lambda self: self.__dict__.copy()
Range.__setstate__ = Range__setstate__
all_structs.append(struct1)
struct1.thrift_spec = (
None, # 0
(1, TType.I32, 'a', None, 1234567, 2, ), # 1
(2, TType.STRING, 'b', True, "<uninitialized>", 2, ), # 2
)
struct1.thrift_struct_annotations = {
}
struct1.thrift_field_annotations = {
}
def struct1__init__(self, a=struct1.thrift_spec[1][4], b=struct1.thrift_spec[2][4],):
self.a = a
self.b = b
struct1.__init__ = struct1__init__
def struct1__setstate__(self, state):
state.setdefault('a', 1234567)
state.setdefault('b', "<uninitialized>")
self.__dict__ = state
struct1.__getstate__ = lambda self: self.__dict__.copy()
struct1.__setstate__ = struct1__setstate__
all_structs.append(struct2)
struct2.thrift_spec = (
None, # 0
(1, TType.I32, 'a', None, None, 2, ), # 1
(2, TType.STRING, 'b', True, None, 2, ), # 2
(3, TType.STRUCT, 'c', [struct1, struct1.thrift_spec, False], None, 2, ), # 3
(4, TType.LIST, 'd', (TType.I32,None), None, 2, ), # 4
)
struct2.thrift_struct_annotations = {
}
struct2.thrift_field_annotations = {
}
def struct2__init__(self, a=None, b=None, c=None, d=None,):
self.a = a
self.b = b
self.c = c
self.d = d
struct2.__init__ = struct2__init__
def struct2__setstate__(self, state):
state.setdefault('a', None)
state.setdefault('b', None)
state.setdefault('c', None)
state.setdefault('d', None)
self.__dict__ = state
struct2.__getstate__ = lambda self: self.__dict__.copy()
struct2.__setstate__ = struct2__setstate__
all_structs.append(struct3)
struct3.thrift_spec = (
None, # 0
(1, TType.STRING, 'a', True, None, 2, ), # 1
(2, TType.I32, 'b', None, None, 2, ), # 2
(3, TType.STRUCT, 'c', [struct2, struct2.thrift_spec, False], None, 2, ), # 3
)
struct3.thrift_struct_annotations = {
}
struct3.thrift_field_annotations = {
}
def struct3__init__(self, a=None, b=None, c=None,):
self.a = a
self.b = b
self.c = c
struct3.__init__ = struct3__init__
def struct3__setstate__(self, state):
state.setdefault('a', None)
state.setdefault('b', None)
state.setdefault('c', None)
self.__dict__ = state
struct3.__getstate__ = lambda self: self.__dict__.copy()
struct3.__setstate__ = struct3__setstate__
all_structs.append(union1)
union1.thrift_spec = (
None, # 0
(1, TType.I32, 'i', None, None, 2, ), # 1
(2, TType.DOUBLE, 'd', None, None, 2, ), # 2
)
union1.thrift_struct_annotations = {
}
union1.thrift_field_annotations = {
}
def union1__init__(self, i=None, d=None,):
self.field = 0
self.value = None
if i is not None:
assert self.field == 0 and self.value is None
self.field = 1
self.value = i
if d is not None:
assert self.field == 0 and self.value is None
self.field = 2
self.value = d
union1.__init__ = union1__init__
all_structs.append(union2)
union2.thrift_spec = (
None, # 0
(1, TType.I32, 'i', None, None, 2, ), # 1
(2, TType.DOUBLE, 'd', None, None, 2, ), # 2
(3, TType.STRUCT, 's', [struct1, struct1.thrift_spec, False], None, 2, ), # 3
(4, TType.STRUCT, 'u', [union1, union1.thrift_spec, True], None, 2, ), # 4
)
union2.thrift_struct_annotations = {
}
union2.thrift_field_annotations = {
}
def union2__init__(self, i=None, d=None, s=None, u=None,):
self.field = 0
self.value = None
if i is not None:
assert self.field == 0 and self.value is None
self.field = 1
self.value = i
if d is not None:
assert self.field == 0 and self.value is None
self.field = 2
self.value = d
if s is not None:
assert self.field == 0 and self.value is None
self.field = 3
self.value = s
if u is not None:
assert self.field == 0 and self.value is None
self.field = 4
self.value = u
union2.__init__ = union2__init__
fix_spec(all_structs)
del all_structs | 0.383988 | 0.105902 |
from flask import request
from flask_restful import Resource
from flask_jwt_extended import jwt_required
from {{cookiecutter.app_name}}.models import User
from {{cookiecutter.app_name}}.extensions import ma, db
from {{cookiecutter.app_name}}.commons.pagination import paginate
class UserSchema(ma.ModelSchema):
id = ma.Int(dump_only=True)
password = ma.String(load_only=True, required=True)
class Meta:
model = User
sqla_session = db.session
class UserResource(Resource):
"""Single object resource
---
get:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
responses:
200:
content:
application/json:
schema:
type: object
properties:
user: UserSchema
404:
description: user does not exists
put:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
requestBody:
content:
application/json:
schema:
UserSchema
responses:
200:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user updated
user: UserSchema
404:
description: user does not exists
delete:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
responses:
200:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user deleted
404:
description: user does not exists
"""
method_decorators = [jwt_required]
def get(self, user_id):
schema = UserSchema()
user = User.query.get_or_404(user_id)
return {"user": schema.dump(user)}
def put(self, user_id):
schema = UserSchema(partial=True)
user = User.query.get_or_404(user_id)
user = schema.load(request.json, instance=user)
db.session.commit()
return {"msg": "user updated", "user": schema.dump(user)}
def delete(self, user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return {"msg": "user deleted"}
class UserList(Resource):
"""Creation and get_all
---
get:
tags:
- api
responses:
200:
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/PaginatedResult'
- type: object
properties:
results:
type: array
items:
$ref: '#/components/schemas/UserSchema'
post:
tags:
- api
requestBody:
content:
application/json:
schema:
UserSchema
responses:
201:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user created
user: UserSchema
"""
method_decorators = [jwt_required]
def get(self):
schema = UserSchema(many=True)
query = User.query
return paginate(query, schema)
def post(self):
schema = UserSchema()
user = schema.load(request.json)
db.session.add(user)
db.session.commit()
return {"msg": "user created", "user": schema.dump(user)}, 201 | {{cookiecutter.project_name}}/{{cookiecutter.app_name}}/api/resources/user.py | from flask import request
from flask_restful import Resource
from flask_jwt_extended import jwt_required
from {{cookiecutter.app_name}}.models import User
from {{cookiecutter.app_name}}.extensions import ma, db
from {{cookiecutter.app_name}}.commons.pagination import paginate
class UserSchema(ma.ModelSchema):
id = ma.Int(dump_only=True)
password = ma.String(load_only=True, required=True)
class Meta:
model = User
sqla_session = db.session
class UserResource(Resource):
"""Single object resource
---
get:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
responses:
200:
content:
application/json:
schema:
type: object
properties:
user: UserSchema
404:
description: user does not exists
put:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
requestBody:
content:
application/json:
schema:
UserSchema
responses:
200:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user updated
user: UserSchema
404:
description: user does not exists
delete:
tags:
- api
parameters:
- in: path
name: user_id
schema:
type: integer
responses:
200:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user deleted
404:
description: user does not exists
"""
method_decorators = [jwt_required]
def get(self, user_id):
schema = UserSchema()
user = User.query.get_or_404(user_id)
return {"user": schema.dump(user)}
def put(self, user_id):
schema = UserSchema(partial=True)
user = User.query.get_or_404(user_id)
user = schema.load(request.json, instance=user)
db.session.commit()
return {"msg": "user updated", "user": schema.dump(user)}
def delete(self, user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return {"msg": "user deleted"}
class UserList(Resource):
"""Creation and get_all
---
get:
tags:
- api
responses:
200:
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/PaginatedResult'
- type: object
properties:
results:
type: array
items:
$ref: '#/components/schemas/UserSchema'
post:
tags:
- api
requestBody:
content:
application/json:
schema:
UserSchema
responses:
201:
content:
application/json:
schema:
type: object
properties:
msg:
type: string
example: user created
user: UserSchema
"""
method_decorators = [jwt_required]
def get(self):
schema = UserSchema(many=True)
query = User.query
return paginate(query, schema)
def post(self):
schema = UserSchema()
user = schema.load(request.json)
db.session.add(user)
db.session.commit()
return {"msg": "user created", "user": schema.dump(user)}, 201 | 0.619471 | 0.089733 |
import asyncio
import json
from asyncio import Event
from typing import Optional, Union, Dict, Any, Tuple, TYPE_CHECKING
from aiohttp import FormData, WSMsgType, WebSocketError
from arclet.edoves.main.server_docker import BaseServerDocker, DockerBehavior, BaseDockerMetaComponent
from arclet.edoves.main.network import NetworkStatus
from arclet.edoves.main.utilles import error_check, DatetimeEncoder, IOStatus
from arclet.edoves.main.utilles.logger import Logger
from arclet.edoves.main.utilles.security import MIRAI_API_HTTP_DEFAULT
from arclet.edoves.builtin.medium import DictMedium
from arclet.edoves.builtin.client import AiohttpClient, AiohttpWSConnection
from arclet.edoves.builtin.event.network import DockerOperate
if TYPE_CHECKING:
from .protocol import MAHProtocol
class MAHDockerMeta(BaseDockerMetaComponent):
protocol: "MAHProtocol"
verify_code: str = MIRAI_API_HTTP_DEFAULT
client: AiohttpClient
session_keys: Dict[str, int] = {}
class MAHBehavior(DockerBehavior):
data: MAHDockerMeta
conn_ev: Event
logger: Logger.logger
async def ws_connection(self) -> Union[AiohttpWSConnection, None]:
self.logger = self.data.protocol.current_scene.edoves.logger
retry_count = 0
while self.data.state in (NetworkStatus.CONNECTING, NetworkStatus.RETRYING):
if retry_count >= self.data.protocol.current_scene.config.ensure_retries:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connect failed")
self.data.protocol.current_scene.sig_exit.set()
return
try:
try:
return await self.connect()
except Exception as e:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: {e}")
await self.quit()
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker stopped")
await asyncio.sleep(5.0)
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker restarting...")
self.data.state = NetworkStatus.RETRYING
retry_count += 1
except asyncio.CancelledError:
self.data.state = NetworkStatus.DISMISS
await self.quit()
async def connect(self):
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connecting...")
async with self.data.client.ensure_network(
self.data.protocol.current_scene.config.url(
"all",
qq=str(self.data.protocol.current_scene.config.account),
verifyKey=str(self.data.protocol.current_scene.config.verify_token)
)
) as resp:
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connected.")
self.data.state = NetworkStatus.CONNECTED
return resp
def activate(self):
async def wait_start(operate: DictMedium):
while not operate.content.get("start"):
await asyncio.sleep(0.01)
self.data.protocol.current_scene.edoves.logger.info(
f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker start!"
)
self.data.state = NetworkStatus.CONNECTING
response = await self.ws_connection()
self.data.protocol.screen.set_call(operate.mid, response)
def quit_listen(operate: DictMedium):
if operate.content.get('stop'):
self.data.state = IOStatus.CLOSE_WAIT
self.io.add_handler(DockerOperate, wait_start, quit_listen)
async def session_fetch(self) -> Optional[DictMedium]:
ws_conn: AiohttpWSConnection = self.data.protocol.current_scene.protagonist['connect_info']
try:
ws_message = await ws_conn.receive(timeout=60.0)
except asyncio.TimeoutError:
self.data.state = NetworkStatus.TIMEOUT
try:
try:
self.logger.debug(f"{self.data.protocol.current_scene.scene_name}: WSConnection trying ping...")
await ws_conn.ping()
self.data.state = NetworkStatus.CONNECTED
except Exception as e:
self.logger.exception(
f"{self.data.protocol.current_scene.scene_name}: WSConnection ping failed: {e!r}"
)
else:
return
except asyncio.CancelledError:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: WSConnection cancelled, stop")
self.data.state = IOStatus.CLOSE_WAIT
else:
if ws_message.type is WSMsgType.TEXT:
received_data: dict = json.loads(ws_message.data)
raw_data = received_data['data']
if 'session' in raw_data:
self.data.session_keys[self.data.protocol.current_scene.scene_name] = raw_data['session']
self.logger.success(f"{self.data.protocol.current_scene.scene_name}: get session key")
await self.data.protocol.ensure_self()
return
try:
error_check(raw_data)
return DictMedium().create(
self.data.protocol.current_scene.protagonist,
raw_data,
"DataReceived"
)
except Exception as e:
self.logger.error(
f"{self.data.protocol.current_scene.scene_name}: WSConnection's data has error: {e}"
)
elif ws_message.type is WSMsgType.CLOSE:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: server close WSConnection.")
self.data.state = IOStatus.CLOSE_WAIT
return
elif ws_message.type is WSMsgType.CLOSED:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: WSConnection has been closed.")
self.data.state = IOStatus.CLOSED
raise WebSocketError(1, "WSConnection closed.")
elif ws_message.type is WSMsgType.PONG:
self.logger.debug(
f"{self.data.protocol.current_scene.scene_name}: WSConnection received pong from remote"
)
elif ws_message.type == WSMsgType.ERROR:
self.logger.error(
f"{self.data.protocol.current_scene.scene_name}: WSConnection error: " + ws_message.data
)
return
else:
self.logger.warning(
f"{self.data.protocol.current_scene.scene_name}: "
f"WSConnection detected a unknown message type: {ws_message.type}"
)
return
async def quit(self):
try:
await self.data.client.close()
await self.data.protocol.current_scene.protagonist['connect_info'].close()
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: WSConnection disconnected")
except TypeError:
return
async def session_handle(
self,
method: str,
action: str,
content: Optional[Union[Dict[str, Any], str, FormData]] = None,
**kwargs
):
content = content or {}
if not self.data.client:
raise RuntimeError(f"{self.data.protocol.current_scene.scene_name}: Unable to get client!")
if method in ("GET", "get"):
if isinstance(content, str):
content = json.loads(content)
async with self.data.client.get(
self.data.protocol.current_scene.config.url(action, **content)
) as response:
resp_json: dict = await response.read_json()
elif method in ("POST", "Update", "post"):
if not isinstance(content, str):
content = json.dumps(content, cls=DatetimeEncoder)
async with self.data.client.post(
self.data.protocol.current_scene.config.url(action), data=content
) as response:
resp_json: dict = await response.read_json()
else: # MULTIPART
if isinstance(content, FormData):
form = content
elif isinstance(content, dict):
form = FormData(quote_fields=False)
for k, v in content.items():
v: Union[str, bytes, Tuple[Any, dict]]
if isinstance(v, tuple):
form.add_field(k, v[0], **v[1])
else:
form.add_field(k, v)
else:
raise ValueError
async with self.data.client.post(
self.data.protocol.current_scene.config.url(action), data=form
) as response:
resp_json: dict = await response.read_json()
if "data" in resp_json:
resp = resp_json["data"]
else:
resp = resp_json
error_check(resp_json.get('code'))
return resp
class MAHServerDocker(BaseServerDocker):
prefab_metadata = MAHDockerMeta
prefab_behavior = MAHBehavior
metadata: MAHDockerMeta | arclet/edoves/mah/server_docker.py | import asyncio
import json
from asyncio import Event
from typing import Optional, Union, Dict, Any, Tuple, TYPE_CHECKING
from aiohttp import FormData, WSMsgType, WebSocketError
from arclet.edoves.main.server_docker import BaseServerDocker, DockerBehavior, BaseDockerMetaComponent
from arclet.edoves.main.network import NetworkStatus
from arclet.edoves.main.utilles import error_check, DatetimeEncoder, IOStatus
from arclet.edoves.main.utilles.logger import Logger
from arclet.edoves.main.utilles.security import MIRAI_API_HTTP_DEFAULT
from arclet.edoves.builtin.medium import DictMedium
from arclet.edoves.builtin.client import AiohttpClient, AiohttpWSConnection
from arclet.edoves.builtin.event.network import DockerOperate
if TYPE_CHECKING:
from .protocol import MAHProtocol
class MAHDockerMeta(BaseDockerMetaComponent):
protocol: "MAHProtocol"
verify_code: str = MIRAI_API_HTTP_DEFAULT
client: AiohttpClient
session_keys: Dict[str, int] = {}
class MAHBehavior(DockerBehavior):
data: MAHDockerMeta
conn_ev: Event
logger: Logger.logger
async def ws_connection(self) -> Union[AiohttpWSConnection, None]:
self.logger = self.data.protocol.current_scene.edoves.logger
retry_count = 0
while self.data.state in (NetworkStatus.CONNECTING, NetworkStatus.RETRYING):
if retry_count >= self.data.protocol.current_scene.config.ensure_retries:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connect failed")
self.data.protocol.current_scene.sig_exit.set()
return
try:
try:
return await self.connect()
except Exception as e:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: {e}")
await self.quit()
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker stopped")
await asyncio.sleep(5.0)
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker restarting...")
self.data.state = NetworkStatus.RETRYING
retry_count += 1
except asyncio.CancelledError:
self.data.state = NetworkStatus.DISMISS
await self.quit()
async def connect(self):
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connecting...")
async with self.data.client.ensure_network(
self.data.protocol.current_scene.config.url(
"all",
qq=str(self.data.protocol.current_scene.config.account),
verifyKey=str(self.data.protocol.current_scene.config.verify_token)
)
) as resp:
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker connected.")
self.data.state = NetworkStatus.CONNECTED
return resp
def activate(self):
async def wait_start(operate: DictMedium):
while not operate.content.get("start"):
await asyncio.sleep(0.01)
self.data.protocol.current_scene.edoves.logger.info(
f"{self.data.protocol.current_scene.scene_name}: MAHServerDocker start!"
)
self.data.state = NetworkStatus.CONNECTING
response = await self.ws_connection()
self.data.protocol.screen.set_call(operate.mid, response)
def quit_listen(operate: DictMedium):
if operate.content.get('stop'):
self.data.state = IOStatus.CLOSE_WAIT
self.io.add_handler(DockerOperate, wait_start, quit_listen)
async def session_fetch(self) -> Optional[DictMedium]:
ws_conn: AiohttpWSConnection = self.data.protocol.current_scene.protagonist['connect_info']
try:
ws_message = await ws_conn.receive(timeout=60.0)
except asyncio.TimeoutError:
self.data.state = NetworkStatus.TIMEOUT
try:
try:
self.logger.debug(f"{self.data.protocol.current_scene.scene_name}: WSConnection trying ping...")
await ws_conn.ping()
self.data.state = NetworkStatus.CONNECTED
except Exception as e:
self.logger.exception(
f"{self.data.protocol.current_scene.scene_name}: WSConnection ping failed: {e!r}"
)
else:
return
except asyncio.CancelledError:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: WSConnection cancelled, stop")
self.data.state = IOStatus.CLOSE_WAIT
else:
if ws_message.type is WSMsgType.TEXT:
received_data: dict = json.loads(ws_message.data)
raw_data = received_data['data']
if 'session' in raw_data:
self.data.session_keys[self.data.protocol.current_scene.scene_name] = raw_data['session']
self.logger.success(f"{self.data.protocol.current_scene.scene_name}: get session key")
await self.data.protocol.ensure_self()
return
try:
error_check(raw_data)
return DictMedium().create(
self.data.protocol.current_scene.protagonist,
raw_data,
"DataReceived"
)
except Exception as e:
self.logger.error(
f"{self.data.protocol.current_scene.scene_name}: WSConnection's data has error: {e}"
)
elif ws_message.type is WSMsgType.CLOSE:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: server close WSConnection.")
self.data.state = IOStatus.CLOSE_WAIT
return
elif ws_message.type is WSMsgType.CLOSED:
self.logger.warning(f"{self.data.protocol.current_scene.scene_name}: WSConnection has been closed.")
self.data.state = IOStatus.CLOSED
raise WebSocketError(1, "WSConnection closed.")
elif ws_message.type is WSMsgType.PONG:
self.logger.debug(
f"{self.data.protocol.current_scene.scene_name}: WSConnection received pong from remote"
)
elif ws_message.type == WSMsgType.ERROR:
self.logger.error(
f"{self.data.protocol.current_scene.scene_name}: WSConnection error: " + ws_message.data
)
return
else:
self.logger.warning(
f"{self.data.protocol.current_scene.scene_name}: "
f"WSConnection detected a unknown message type: {ws_message.type}"
)
return
async def quit(self):
try:
await self.data.client.close()
await self.data.protocol.current_scene.protagonist['connect_info'].close()
self.logger.info(f"{self.data.protocol.current_scene.scene_name}: WSConnection disconnected")
except TypeError:
return
async def session_handle(
self,
method: str,
action: str,
content: Optional[Union[Dict[str, Any], str, FormData]] = None,
**kwargs
):
content = content or {}
if not self.data.client:
raise RuntimeError(f"{self.data.protocol.current_scene.scene_name}: Unable to get client!")
if method in ("GET", "get"):
if isinstance(content, str):
content = json.loads(content)
async with self.data.client.get(
self.data.protocol.current_scene.config.url(action, **content)
) as response:
resp_json: dict = await response.read_json()
elif method in ("POST", "Update", "post"):
if not isinstance(content, str):
content = json.dumps(content, cls=DatetimeEncoder)
async with self.data.client.post(
self.data.protocol.current_scene.config.url(action), data=content
) as response:
resp_json: dict = await response.read_json()
else: # MULTIPART
if isinstance(content, FormData):
form = content
elif isinstance(content, dict):
form = FormData(quote_fields=False)
for k, v in content.items():
v: Union[str, bytes, Tuple[Any, dict]]
if isinstance(v, tuple):
form.add_field(k, v[0], **v[1])
else:
form.add_field(k, v)
else:
raise ValueError
async with self.data.client.post(
self.data.protocol.current_scene.config.url(action), data=form
) as response:
resp_json: dict = await response.read_json()
if "data" in resp_json:
resp = resp_json["data"]
else:
resp = resp_json
error_check(resp_json.get('code'))
return resp
class MAHServerDocker(BaseServerDocker):
prefab_metadata = MAHDockerMeta
prefab_behavior = MAHBehavior
metadata: MAHDockerMeta | 0.595845 | 0.110904 |
import numpy as np
import cvxpy as cp
from cvxpy.error import SolverError
from cvxpy.tests.base_test import BaseTest
class TestSupportFunctions(BaseTest):
"""
Test the implementation of support function atoms.
Relevant source code includes:
cvxpy.atoms.suppfunc
cvxpy.transforms.suppfunc
cvxpy.reductions.dcp2cone.atom_canonicalizers.suppfunc_canon
"""
def test_Rn(self) -> None:
np.random.seed(0)
n = 5
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [])
a = np.random.randn(n,)
y = cp.Variable(shape=(n,))
cons = [sigma(y - a) <= 0] # "<= num" for any num >= 0 is valid.
objective = cp.Minimize(a @ y)
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
actual = prob.value
expected = np.dot(a, a)
self.assertLessEqual(abs(actual - expected), 1e-6)
actual = y.value
expected = a
self.assertLessEqual(np.linalg.norm(actual - expected, ord=2), 1e-6)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-8)
def test_vector1norm(self) -> None:
n = 3
np.random.seed(1)
a = np.random.randn(n,)
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - a, 1) <= 1])
y = np.random.randn(n,)
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [y == y_var])
prob.solve(solver='ECOS')
actual = prob.value
expected = a @ y + np.linalg.norm(y, ord=np.inf)
self.assertLessEqual(abs(actual - expected), 1e-5)
self.assertLessEqual(abs(prob.objective.expr.value - prob.value), 1e-5)
def test_vector2norm(self) -> None:
n = 3
np.random.seed(1)
a = np.random.randn(n,)
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - a, 2) <= 1])
y = np.random.randn(n,)
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [y == y_var])
prob.solve(solver='ECOS')
actual = prob.value
expected = a @ y + np.linalg.norm(y, ord=2)
self.assertLessEqual(abs(actual - expected), 1e-6)
self.assertLessEqual(abs(prob.objective.expr.value - prob.value), 1e-6)
def test_rectangular_variable(self) -> None:
np.random.seed(2)
rows, cols = 4, 2
a = np.random.randn(rows, cols)
x = cp.Variable(shape=(rows, cols))
sigma = cp.suppfunc(x, [x[:, 0] == 0])
y = cp.Variable(shape=(rows, cols))
cons = [sigma(y - a) <= 0]
objective = cp.Minimize(cp.sum_squares(y.flatten()))
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
expect = np.hstack([np.zeros(shape=(rows, 1)), a[:, [1]]])
actual = y.value
self.assertLessEqual(np.linalg.norm(actual - expect, ord=2), 1e-6)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
def test_psd_dualcone(self) -> None:
np.random.seed(5)
n = 3
X = cp.Variable(shape=(n, n))
sigma = cp.suppfunc(X, [X >> 0])
A = np.random.randn(n, n)
Y = cp.Variable(shape=(n, n))
objective = cp.Minimize(cp.norm(A.ravel(order='F') + Y.flatten()))
cons = [sigma(Y) <= 0] # Y is negative definite.
prob = cp.Problem(objective, cons)
prob.solve(solver='SCS', eps=1e-8)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
eigs = np.linalg.eigh(Y.value)[0]
self.assertLessEqual(np.max(eigs), 1e-6)
def test_largest_singvalue(self) -> None:
np.random.seed(3)
rows, cols = 3, 4
A = np.random.randn(rows, cols)
A_sv = np.linalg.svd(A, compute_uv=False)
X = cp.Variable(shape=(rows, cols))
sigma = cp.suppfunc(X, [cp.sigma_max(X) <= 1])
Y = cp.Variable(shape=(rows, cols))
cons = [Y == A]
prob = cp.Problem(cp.Minimize(sigma(Y)), cons)
prob.solve(solver='SCS', eps=1e-8)
actual = prob.value
expect = np.sum(A_sv)
self.assertLessEqual(abs(actual - expect), 1e-6)
def test_expcone_1(self) -> None:
x = cp.Variable(shape=(1,))
tempcons = [cp.exp(x[0]) <= np.exp(1), cp.exp(-x[0]) <= np.exp(1)]
sigma = cp.suppfunc(x, tempcons)
y = cp.Variable(shape=(1,))
obj_expr = y[0]
cons = [sigma(y) <= 1]
# ^ That just means -1 <= y[0] <= 1
prob = cp.Problem(cp.Minimize(obj_expr), cons)
prob.solve(solver='ECOS')
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
self.assertLessEqual(abs(y.value - (-1)), 1e-6)
def test_expcone_2(self) -> None:
x = cp.Variable(shape=(3,))
tempcons = [cp.sum(x) <= 1.0, cp.sum(x) >= 0.1, x >= 0.01,
cp.kl_div(x[1], x[0]) + x[1] - x[0] + x[2] <= 0]
sigma = cp.suppfunc(x, tempcons)
y = cp.Variable(shape=(3,))
a = np.array([-3, -2, -1]) # this is negative of objective in mosek_conif.py example
expr = -sigma(y)
objective = cp.Maximize(expr)
cons = [y == a]
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
# Check for expected objective value
epi_actual = prob.value
direct_actual = expr.value
expect = 0.235348211
self.assertLessEqual(abs(epi_actual - expect), 1e-6)
self.assertLessEqual(abs(direct_actual - expect), 1e-6)
def test_basic_lmi(self) -> None:
np.random.seed(4)
n = 3
A = np.random.randn(n, n)
A = A.T @ A
X = cp.Variable(shape=(n, n)) # will fail if you try PSD=True, or symmetric=Trues
sigma = cp.suppfunc(X, [0 << X, cp.lambda_max(X) <= 1])
Y = cp.Variable(shape=(n, n))
cons = [Y == A]
expr = sigma(Y)
prob = cp.Problem(cp.Minimize(expr), cons) # opt value of support func would be at X=I.
prob.solve(solver='SCS', eps=1e-8)
actual1 = prob.value # computed with epigraph
actual2 = expr.value # computed by evaluating support function, as a maximization problem.
self.assertLessEqual(abs(actual1 - actual2), 1e-6)
expect = np.trace(A)
self.assertLessEqual(abs(actual1 - expect), 1e-4)
def test_invalid_solver(self) -> None:
n = 3
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - np.random.randn(n,), 2) <= 1])
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [np.random.randn(n,) == y_var])
with self.assertRaisesRegex(
SolverError, ".*could not be reduced to a QP.*"):
prob.solve(solver='OSQP')
def test_invalid_variable(self) -> None:
x = cp.Variable(shape=(2, 2), symmetric=True)
with self.assertRaises(ValueError):
cp.suppfunc(x, [])
def test_invalid_constraint(self) -> None:
x = cp.Variable(shape=(3,))
a = cp.Parameter(shape=(3,))
cons = [a @ x == 1]
with self.assertRaises(ValueError):
cp.suppfunc(x, cons) | cvxpy/tests/test_suppfunc.py | import numpy as np
import cvxpy as cp
from cvxpy.error import SolverError
from cvxpy.tests.base_test import BaseTest
class TestSupportFunctions(BaseTest):
"""
Test the implementation of support function atoms.
Relevant source code includes:
cvxpy.atoms.suppfunc
cvxpy.transforms.suppfunc
cvxpy.reductions.dcp2cone.atom_canonicalizers.suppfunc_canon
"""
def test_Rn(self) -> None:
np.random.seed(0)
n = 5
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [])
a = np.random.randn(n,)
y = cp.Variable(shape=(n,))
cons = [sigma(y - a) <= 0] # "<= num" for any num >= 0 is valid.
objective = cp.Minimize(a @ y)
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
actual = prob.value
expected = np.dot(a, a)
self.assertLessEqual(abs(actual - expected), 1e-6)
actual = y.value
expected = a
self.assertLessEqual(np.linalg.norm(actual - expected, ord=2), 1e-6)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-8)
def test_vector1norm(self) -> None:
n = 3
np.random.seed(1)
a = np.random.randn(n,)
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - a, 1) <= 1])
y = np.random.randn(n,)
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [y == y_var])
prob.solve(solver='ECOS')
actual = prob.value
expected = a @ y + np.linalg.norm(y, ord=np.inf)
self.assertLessEqual(abs(actual - expected), 1e-5)
self.assertLessEqual(abs(prob.objective.expr.value - prob.value), 1e-5)
def test_vector2norm(self) -> None:
n = 3
np.random.seed(1)
a = np.random.randn(n,)
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - a, 2) <= 1])
y = np.random.randn(n,)
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [y == y_var])
prob.solve(solver='ECOS')
actual = prob.value
expected = a @ y + np.linalg.norm(y, ord=2)
self.assertLessEqual(abs(actual - expected), 1e-6)
self.assertLessEqual(abs(prob.objective.expr.value - prob.value), 1e-6)
def test_rectangular_variable(self) -> None:
np.random.seed(2)
rows, cols = 4, 2
a = np.random.randn(rows, cols)
x = cp.Variable(shape=(rows, cols))
sigma = cp.suppfunc(x, [x[:, 0] == 0])
y = cp.Variable(shape=(rows, cols))
cons = [sigma(y - a) <= 0]
objective = cp.Minimize(cp.sum_squares(y.flatten()))
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
expect = np.hstack([np.zeros(shape=(rows, 1)), a[:, [1]]])
actual = y.value
self.assertLessEqual(np.linalg.norm(actual - expect, ord=2), 1e-6)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
def test_psd_dualcone(self) -> None:
np.random.seed(5)
n = 3
X = cp.Variable(shape=(n, n))
sigma = cp.suppfunc(X, [X >> 0])
A = np.random.randn(n, n)
Y = cp.Variable(shape=(n, n))
objective = cp.Minimize(cp.norm(A.ravel(order='F') + Y.flatten()))
cons = [sigma(Y) <= 0] # Y is negative definite.
prob = cp.Problem(objective, cons)
prob.solve(solver='SCS', eps=1e-8)
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
eigs = np.linalg.eigh(Y.value)[0]
self.assertLessEqual(np.max(eigs), 1e-6)
def test_largest_singvalue(self) -> None:
np.random.seed(3)
rows, cols = 3, 4
A = np.random.randn(rows, cols)
A_sv = np.linalg.svd(A, compute_uv=False)
X = cp.Variable(shape=(rows, cols))
sigma = cp.suppfunc(X, [cp.sigma_max(X) <= 1])
Y = cp.Variable(shape=(rows, cols))
cons = [Y == A]
prob = cp.Problem(cp.Minimize(sigma(Y)), cons)
prob.solve(solver='SCS', eps=1e-8)
actual = prob.value
expect = np.sum(A_sv)
self.assertLessEqual(abs(actual - expect), 1e-6)
def test_expcone_1(self) -> None:
x = cp.Variable(shape=(1,))
tempcons = [cp.exp(x[0]) <= np.exp(1), cp.exp(-x[0]) <= np.exp(1)]
sigma = cp.suppfunc(x, tempcons)
y = cp.Variable(shape=(1,))
obj_expr = y[0]
cons = [sigma(y) <= 1]
# ^ That just means -1 <= y[0] <= 1
prob = cp.Problem(cp.Minimize(obj_expr), cons)
prob.solve(solver='ECOS')
viol = cons[0].violation()
self.assertLessEqual(viol, 1e-6)
self.assertLessEqual(abs(y.value - (-1)), 1e-6)
def test_expcone_2(self) -> None:
x = cp.Variable(shape=(3,))
tempcons = [cp.sum(x) <= 1.0, cp.sum(x) >= 0.1, x >= 0.01,
cp.kl_div(x[1], x[0]) + x[1] - x[0] + x[2] <= 0]
sigma = cp.suppfunc(x, tempcons)
y = cp.Variable(shape=(3,))
a = np.array([-3, -2, -1]) # this is negative of objective in mosek_conif.py example
expr = -sigma(y)
objective = cp.Maximize(expr)
cons = [y == a]
prob = cp.Problem(objective, cons)
prob.solve(solver='ECOS')
# Check for expected objective value
epi_actual = prob.value
direct_actual = expr.value
expect = 0.235348211
self.assertLessEqual(abs(epi_actual - expect), 1e-6)
self.assertLessEqual(abs(direct_actual - expect), 1e-6)
def test_basic_lmi(self) -> None:
np.random.seed(4)
n = 3
A = np.random.randn(n, n)
A = A.T @ A
X = cp.Variable(shape=(n, n)) # will fail if you try PSD=True, or symmetric=Trues
sigma = cp.suppfunc(X, [0 << X, cp.lambda_max(X) <= 1])
Y = cp.Variable(shape=(n, n))
cons = [Y == A]
expr = sigma(Y)
prob = cp.Problem(cp.Minimize(expr), cons) # opt value of support func would be at X=I.
prob.solve(solver='SCS', eps=1e-8)
actual1 = prob.value # computed with epigraph
actual2 = expr.value # computed by evaluating support function, as a maximization problem.
self.assertLessEqual(abs(actual1 - actual2), 1e-6)
expect = np.trace(A)
self.assertLessEqual(abs(actual1 - expect), 1e-4)
def test_invalid_solver(self) -> None:
n = 3
x = cp.Variable(shape=(n,))
sigma = cp.suppfunc(x, [cp.norm(x - np.random.randn(n,), 2) <= 1])
y_var = cp.Variable(shape=(n,))
prob = cp.Problem(cp.Minimize(sigma(y_var)), [np.random.randn(n,) == y_var])
with self.assertRaisesRegex(
SolverError, ".*could not be reduced to a QP.*"):
prob.solve(solver='OSQP')
def test_invalid_variable(self) -> None:
x = cp.Variable(shape=(2, 2), symmetric=True)
with self.assertRaises(ValueError):
cp.suppfunc(x, [])
def test_invalid_constraint(self) -> None:
x = cp.Variable(shape=(3,))
a = cp.Parameter(shape=(3,))
cons = [a @ x == 1]
with self.assertRaises(ValueError):
cp.suppfunc(x, cons) | 0.645679 | 0.745676 |
import argparse
import ast
import traceback
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Sequence
DEBUG_STATEMENTS = {
'ipdb',
'pdb',
'pdbr',
'pudb',
'pydevd_pycharm',
'q',
'rdb',
'rpdb',
'wdb',
}
class Debug(NamedTuple):
line: int
col: int
name: str
reason: str
class DebugStatementParser(ast.NodeVisitor):
def __init__(self) -> None:
self.breakpoints: List[Debug] = []
def visit_Import(self, node: ast.Import) -> None:
for name in node.names:
if name.name in DEBUG_STATEMENTS:
st = Debug(node.lineno, node.col_offset, name.name, 'imported')
self.breakpoints.append(st)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.module in DEBUG_STATEMENTS:
st = Debug(node.lineno, node.col_offset, node.module, 'imported')
self.breakpoints.append(st)
def visit_Call(self, node: ast.Call) -> None:
"""python3.7+ breakpoint()"""
if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
self.breakpoints.append(st)
self.generic_visit(node)
def check_file(filename: str) -> int:
try:
with open(filename, 'rb') as f:
ast_obj = ast.parse(f.read(), filename=filename)
except SyntaxError:
print(f'{filename} - Could not parse ast')
print()
print('\t' + traceback.format_exc().replace('\n', '\n\t'))
print()
return 1
visitor = DebugStatementParser()
visitor.visit(ast_obj)
for bp in visitor.breakpoints:
print(f'{filename}:{bp.line}:{bp.col} - {bp.name} {bp.reason}')
return int(bool(visitor.breakpoints))
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to run')
args = parser.parse_args(argv)
retv = 0
for filename in args.filenames:
retv |= check_file(filename)
return retv
if __name__ == '__main__':
exit(main()) | pre_commit_hooks/debug_statement_hook.py | import argparse
import ast
import traceback
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Sequence
DEBUG_STATEMENTS = {
'ipdb',
'pdb',
'pdbr',
'pudb',
'pydevd_pycharm',
'q',
'rdb',
'rpdb',
'wdb',
}
class Debug(NamedTuple):
line: int
col: int
name: str
reason: str
class DebugStatementParser(ast.NodeVisitor):
def __init__(self) -> None:
self.breakpoints: List[Debug] = []
def visit_Import(self, node: ast.Import) -> None:
for name in node.names:
if name.name in DEBUG_STATEMENTS:
st = Debug(node.lineno, node.col_offset, name.name, 'imported')
self.breakpoints.append(st)
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
if node.module in DEBUG_STATEMENTS:
st = Debug(node.lineno, node.col_offset, node.module, 'imported')
self.breakpoints.append(st)
def visit_Call(self, node: ast.Call) -> None:
"""python3.7+ breakpoint()"""
if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint':
st = Debug(node.lineno, node.col_offset, node.func.id, 'called')
self.breakpoints.append(st)
self.generic_visit(node)
def check_file(filename: str) -> int:
try:
with open(filename, 'rb') as f:
ast_obj = ast.parse(f.read(), filename=filename)
except SyntaxError:
print(f'{filename} - Could not parse ast')
print()
print('\t' + traceback.format_exc().replace('\n', '\n\t'))
print()
return 1
visitor = DebugStatementParser()
visitor.visit(ast_obj)
for bp in visitor.breakpoints:
print(f'{filename}:{bp.line}:{bp.col} - {bp.name} {bp.reason}')
return int(bool(visitor.breakpoints))
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to run')
args = parser.parse_args(argv)
retv = 0
for filename in args.filenames:
retv |= check_file(filename)
return retv
if __name__ == '__main__':
exit(main()) | 0.606149 | 0.146087 |
import magma as m
import mantle
def define_simple_circuit(T, circ_name, has_clk=False):
class _Circuit(m.Circuit):
__test__ = False # Disable pytest discovery
name = circ_name
IO = ["I", m.In(T), "O", m.Out(T)]
if has_clk:
IO += ["CLK", m.In(m.Clock)]
@classmethod
def definition(io):
m.wire(io.I, io.O)
return _Circuit
TestBasicCircuit = define_simple_circuit(m.Bit, "BasicCircuit")
TestArrayCircuit = define_simple_circuit(m.Array(3, m.Bit), "ArrayCircuit")
TestSIntCircuit = define_simple_circuit(m.SInt(3), "SIntCircuit")
TestNestedArraysCircuit = define_simple_circuit(m.Array(3, m.Bits(4)),
"NestedArraysCircuit")
TestDoubleNestedArraysCircuit = define_simple_circuit(
m.Array(2, m.Array(3, m.Bits(4))), "DoubleNestedArraysCircuit")
TestBasicClkCircuit = define_simple_circuit(m.Bit, "BasicClkCircuit", True)
TestBasicClkCircuitCopy = define_simple_circuit(m.Bit, "BasicClkCircuitCopy",
True)
TestTupleCircuit = define_simple_circuit(m.Tuple(a=m.Bits(4), b=m.Bits(4)),
"TupleCircuit")
T = m.Bits(3)
class TestPeekCircuit(m.Circuit):
__test__ = False # Disable pytest discovery
IO = ["I", m.In(T), "O0", m.Out(T), "O1", m.Out(T)]
@classmethod
def definition(io):
m.wire(io.I, io.O0)
m.wire(io.I, io.O1)
class ConfigReg(m.Circuit):
IO = ["D", m.In(m.Bits(2)), "Q", m.Out(m.Bits(2))] + \
m.ClockInterface(has_ce=True)
@classmethod
def definition(io):
reg = mantle.Register(2, has_ce=True, name="conf_reg")
io.Q <= reg(io.D, CE=io.CE)
class SimpleALU(m.Circuit):
IO = ["a", m.In(m.UInt(16)),
"b", m.In(m.UInt(16)),
"c", m.Out(m.UInt(16)),
"config_data", m.In(m.Bits(2)),
"config_en", m.In(m.Enable),
] + m.ClockInterface()
@classmethod
def definition(io):
opcode = ConfigReg(name="config_reg")(io.config_data, CE=io.config_en)
io.c <= mantle.mux(
[io.a + io.b, io.a - io.b, io.a * io.b, io.a / io.b], opcode) | tests/common.py | import magma as m
import mantle
def define_simple_circuit(T, circ_name, has_clk=False):
class _Circuit(m.Circuit):
__test__ = False # Disable pytest discovery
name = circ_name
IO = ["I", m.In(T), "O", m.Out(T)]
if has_clk:
IO += ["CLK", m.In(m.Clock)]
@classmethod
def definition(io):
m.wire(io.I, io.O)
return _Circuit
TestBasicCircuit = define_simple_circuit(m.Bit, "BasicCircuit")
TestArrayCircuit = define_simple_circuit(m.Array(3, m.Bit), "ArrayCircuit")
TestSIntCircuit = define_simple_circuit(m.SInt(3), "SIntCircuit")
TestNestedArraysCircuit = define_simple_circuit(m.Array(3, m.Bits(4)),
"NestedArraysCircuit")
TestDoubleNestedArraysCircuit = define_simple_circuit(
m.Array(2, m.Array(3, m.Bits(4))), "DoubleNestedArraysCircuit")
TestBasicClkCircuit = define_simple_circuit(m.Bit, "BasicClkCircuit", True)
TestBasicClkCircuitCopy = define_simple_circuit(m.Bit, "BasicClkCircuitCopy",
True)
TestTupleCircuit = define_simple_circuit(m.Tuple(a=m.Bits(4), b=m.Bits(4)),
"TupleCircuit")
T = m.Bits(3)
class TestPeekCircuit(m.Circuit):
__test__ = False # Disable pytest discovery
IO = ["I", m.In(T), "O0", m.Out(T), "O1", m.Out(T)]
@classmethod
def definition(io):
m.wire(io.I, io.O0)
m.wire(io.I, io.O1)
class ConfigReg(m.Circuit):
IO = ["D", m.In(m.Bits(2)), "Q", m.Out(m.Bits(2))] + \
m.ClockInterface(has_ce=True)
@classmethod
def definition(io):
reg = mantle.Register(2, has_ce=True, name="conf_reg")
io.Q <= reg(io.D, CE=io.CE)
class SimpleALU(m.Circuit):
IO = ["a", m.In(m.UInt(16)),
"b", m.In(m.UInt(16)),
"c", m.Out(m.UInt(16)),
"config_data", m.In(m.Bits(2)),
"config_en", m.In(m.Enable),
] + m.ClockInterface()
@classmethod
def definition(io):
opcode = ConfigReg(name="config_reg")(io.config_data, CE=io.config_en)
io.c <= mantle.mux(
[io.a + io.b, io.a - io.b, io.a * io.b, io.a / io.b], opcode) | 0.511717 | 0.629689 |
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
import datetime
from time import sleep
import codecs
from ghsTools import ghsTools
import database
import mail
from utils import datetime_utils
from utils.generic import clear_output
def main():
"""Runs the main program
"""
cred = credentials.Certificate("./secrets/firestore_creds.json")
firebase_admin.initialize_app(
cred, {
"databaseURL": "https://ghs-app-5a0ba.firebaseio.com/",
'databaseAuthVariableOverride': {
'uid': 'my-service-worker'
}
})
recent_problems = []
pulse_amount = 0
last_time_offline = {}
last_time_online = {}
ghsTools().set_monitoring_info(True, time_till_next_run, "Server-Monitor")
while True:
time_till_next_run = 7
pulse_amount += 1
db_info_ref = db.reference("db-info").get()
monitoring_info = db_info_ref["monitoring"]
with open("email_list.txt") as email_list_file:
email_list = email_list_file.read().split("\n")
for service_name in monitoring_info:
clear_output(5)
print("--------------------------------")
print("Checking:", service_name)
service_info = monitoring_info[service_name]
print("Service Information:", service_info)
service_pulse_time = db_info_ref["pulses"][service_name]["Pulse-Time"]
current_time = datetime.datetime.now()
datetime_version_of_pulse_time = datetime_utils.cast_regular_as_datetime(
service_pulse_time)
time_diff = current_time - datetime_version_of_pulse_time
seconds_diff = time_diff.seconds
print("Time Diff for Service:", seconds_diff)
if service_info["email-notification"]:
if seconds_diff > service_info["pulse-time-diffs-(secs)"] and service_name not in recent_problems:
print("Problem with", service_name, "sending email now")
with codecs.open("problem.html", "r") as problem_html:
problem_html_lines = problem_html.read()
filled_html_file = problem_html_lines.format(
program_name=service_name, pulse_rate=service_info["pulse-time-diffs-(secs)"], pulse_time_delta=service_info["pulse-time-diffs-(secs)"])
for email in email_list:
mail.send_email(
filled_html_file, email, "Problem with " + service_name)
recent_problems.append(service_name)
elif service_name in recent_problems and seconds_diff < service_info["pulse-time-diffs-(secs)"]:
print(service_name, "is back online, sending email")
with codecs.open("good_status.html", "r") as good_status_html:
good_status_lines = good_status_html.read()
filled_html_file = good_status_lines.format(
program_name=service_name, pulse_rate=service_info["pulse-time-diffs-(secs)"])
for email in email_list:
mail.send_email(filled_html_file,
email, service_name + " Fixed")
recent_problems.remove(service_name)
else:
print(service_name, "looks fine")
try:
if pulse_amount == 1:
last_time_offline[service_name] = db_info_ref["statuses"][service_name]["last-time-offline"]
last_time_online[service_name] = db_info_ref["statuses"][service_name]["last-time-online"]
except KeyError:
last_time_offline[service_name] = "N/A"
last_time_online[service_name] = "N/A"
if seconds_diff > service_info["pulse-time-diffs-(secs)"]:
last_time_offline[service_name] = str(datetime.datetime.now())
database.set_service_status(
service_name, False, last_time_online[service_name], last_time_offline[service_name])
else:
last_time_online[service_name] = str(datetime.datetime.now())
database.set_service_status(
service_name, True, last_time_online[service_name], last_time_offline[service_name])
ghsTools().update_pulse(pulse_amount, "Server-Monitor")
sleep(time_till_next_run)
if __name__ == "__main__":
main() | serverMonitor/main.py | import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
import datetime
from time import sleep
import codecs
from ghsTools import ghsTools
import database
import mail
from utils import datetime_utils
from utils.generic import clear_output
def main():
"""Runs the main program
"""
cred = credentials.Certificate("./secrets/firestore_creds.json")
firebase_admin.initialize_app(
cred, {
"databaseURL": "https://ghs-app-5a0ba.firebaseio.com/",
'databaseAuthVariableOverride': {
'uid': 'my-service-worker'
}
})
recent_problems = []
pulse_amount = 0
last_time_offline = {}
last_time_online = {}
ghsTools().set_monitoring_info(True, time_till_next_run, "Server-Monitor")
while True:
time_till_next_run = 7
pulse_amount += 1
db_info_ref = db.reference("db-info").get()
monitoring_info = db_info_ref["monitoring"]
with open("email_list.txt") as email_list_file:
email_list = email_list_file.read().split("\n")
for service_name in monitoring_info:
clear_output(5)
print("--------------------------------")
print("Checking:", service_name)
service_info = monitoring_info[service_name]
print("Service Information:", service_info)
service_pulse_time = db_info_ref["pulses"][service_name]["Pulse-Time"]
current_time = datetime.datetime.now()
datetime_version_of_pulse_time = datetime_utils.cast_regular_as_datetime(
service_pulse_time)
time_diff = current_time - datetime_version_of_pulse_time
seconds_diff = time_diff.seconds
print("Time Diff for Service:", seconds_diff)
if service_info["email-notification"]:
if seconds_diff > service_info["pulse-time-diffs-(secs)"] and service_name not in recent_problems:
print("Problem with", service_name, "sending email now")
with codecs.open("problem.html", "r") as problem_html:
problem_html_lines = problem_html.read()
filled_html_file = problem_html_lines.format(
program_name=service_name, pulse_rate=service_info["pulse-time-diffs-(secs)"], pulse_time_delta=service_info["pulse-time-diffs-(secs)"])
for email in email_list:
mail.send_email(
filled_html_file, email, "Problem with " + service_name)
recent_problems.append(service_name)
elif service_name in recent_problems and seconds_diff < service_info["pulse-time-diffs-(secs)"]:
print(service_name, "is back online, sending email")
with codecs.open("good_status.html", "r") as good_status_html:
good_status_lines = good_status_html.read()
filled_html_file = good_status_lines.format(
program_name=service_name, pulse_rate=service_info["pulse-time-diffs-(secs)"])
for email in email_list:
mail.send_email(filled_html_file,
email, service_name + " Fixed")
recent_problems.remove(service_name)
else:
print(service_name, "looks fine")
try:
if pulse_amount == 1:
last_time_offline[service_name] = db_info_ref["statuses"][service_name]["last-time-offline"]
last_time_online[service_name] = db_info_ref["statuses"][service_name]["last-time-online"]
except KeyError:
last_time_offline[service_name] = "N/A"
last_time_online[service_name] = "N/A"
if seconds_diff > service_info["pulse-time-diffs-(secs)"]:
last_time_offline[service_name] = str(datetime.datetime.now())
database.set_service_status(
service_name, False, last_time_online[service_name], last_time_offline[service_name])
else:
last_time_online[service_name] = str(datetime.datetime.now())
database.set_service_status(
service_name, True, last_time_online[service_name], last_time_offline[service_name])
ghsTools().update_pulse(pulse_amount, "Server-Monitor")
sleep(time_till_next_run)
if __name__ == "__main__":
main() | 0.329284 | 0.077588 |
import copy
from quant import const
from quant.error import Error
from quant.utils import logger
from quant.tasks import SingleTask
from quant.order import ORDER_TYPE_LIMIT
from quant.order import Order
from quant.position import Position
from quant.event import EventOrder
class Trade:
""" Trade Module.
Attributes:
strategy: What's name would you want to created for your strategy.
platform: Exchange platform name. e.g. `binance` / `okex` / `bitmex`.
symbol: Symbol name for your trade. e.g. `BTC/USDT`.
host: HTTP request host.
wss: Websocket address.
account: Account name for this trade exchange.
access_key: Account's ACCESS KEY.
secret_key: Account's SECRET KEY.
passphrase: API KEY Passphrase. (Only for `OKEx`)
asset_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `asset_update_callback` is like `async def on_asset_update_callback(asset: Asset): pass` and this
callback function will be executed asynchronous when received AssetEvent.
order_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `order_update_callback` is like `async def on_order_update_callback(order: Order): pass` and this
callback function will be executed asynchronous when some order state updated.
position_update_callback: You can use this param to specific a async callback function when you initializing
Trade object. `position_update_callback` is like `async def on_position_update_callback(position: Position): pass`
and this callback function will be executed asynchronous when position updated.
init_success_callback: You can use this param to specific a async callback function when you initializing Trade
object. `init_success_callback` is like `async def on_init_success_callback(success: bool, error: Error, **kwargs): pass`
and this callback function will be executed asynchronous after Trade module object initialized successfully.
"""
def __init__(self, strategy=None, platform=None, symbol=None, host=None, wss=None, account=None, access_key=None,
secret_key=None, passphrase=None, asset_update_callback=None, order_update_callback=None,
position_update_callback=None, init_success_callback=None, **kwargs):
"""initialize trade object."""
kwargs["strategy"] = strategy
kwargs["platform"] = platform
kwargs["symbol"] = symbol
kwargs["host"] = host
kwargs["wss"] = wss
kwargs["account"] = account
kwargs["access_key"] = access_key
kwargs["secret_key"] = secret_key
kwargs["passphrase"] = <PASSWORD>
kwargs["asset_update_callback"] = asset_update_callback
kwargs["order_update_callback"] = self._on_order_update_callback
kwargs["position_update_callback"] = self._on_position_update_callback
kwargs["init_success_callback"] = self._on_init_success_callback
self._raw_params = copy.copy(kwargs)
self._order_update_callback = order_update_callback
self._position_update_callback = position_update_callback
self._init_success_callback = init_success_callback
if platform == const.OKEX:
from quant.platform.okex import OKExTrade as T
elif platform == const.OKEX_MARGIN:
from quant.platform.okex_margin import OKExMarginTrade as T
elif platform == const.OKEX_FUTURE:
from quant.platform.okex_future import OKExFutureTrade as T
elif platform == const.OKEX_SWAP:
from quant.platform.okex_swap import OKExSwapTrade as T
elif platform == const.DERIBIT:
from quant.platform.deribit import DeribitTrade as T
elif platform == const.BITMEX:
from quant.platform.bitmex import BitmexTrade as T
elif platform == const.BINANCE:
from quant.platform.binance import BinanceTrade as T
elif platform == const.BINANCE_FUTURE:
from quant.platform.binance_future import BinanceFutureTrade as T
elif platform == const.HUOBI:
from quant.platform.huobi import HuobiTrade as T
elif platform == const.COINSUPER:
from quant.platform.coinsuper import CoinsuperTrade as T
elif platform == const.COINSUPER_PRE:
from quant.platform.coinsuper_pre import CoinsuperPreTrade as T
elif platform == const.KRAKEN:
from quant.platform.kraken import KrakenTrade as T
elif platform == const.GATE:
from quant.platform.gate import GateTrade as T
elif platform == const.KUCOIN:
from quant.platform.kucoin import KucoinTrade as T
elif platform == const.HUOBI_FUTURE:
from quant.platform.huobi_future import HuobiFutureTrade as T
else:
logger.error("platform error:", platform, caller=self)
e = Error("platform error")
SingleTask.run(self._init_success_callback, False, e)
return
kwargs.pop("platform")
self._t = T(**kwargs)
@property
def assets(self):
return self._t.assets
@property
def orders(self):
return self._t.orders
@property
def position(self):
return self._t.position
@property
def rest_api(self):
return self._t.rest_api
async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT, **kwargs):
""" Create an order.
Args:
action: Trade direction, `BUY` or `SELL`.
price: Price of each contract.
quantity: The buying or selling quantity.
order_type: Specific type of order, `LIMIT` or `MARKET`. (default is `LIMIT`)
Returns:
order_no: Order ID if created successfully, otherwise it's None.
error: Error information, otherwise it's None.
"""
order_no, error = await self._t.create_order(action, price, quantity, order_type, **kwargs)
return order_no, error
async def revoke_order(self, *order_nos):
""" Revoke (an) order(s).
Args:
order_nos: Order id list, you can set this param to 0 or multiple items. If you set 0 param, you can cancel
all orders for this symbol(initialized in Trade object). If you set 1 param, you can cancel an order.
If you set multiple param, you can cancel multiple orders. Do not set param length more than 100.
Returns:
success: If execute successfully, return success information, otherwise it's None.
error: If execute failed, return error information, otherwise it's None.
"""
success, error = await self._t.revoke_order(*order_nos)
return success, error
async def get_open_order_nos(self):
""" Get open order id list.
Args:
None.
Returns:
order_nos: Open order id list, otherwise it's None.
error: Error information, otherwise it's None.
"""
result, error = await self._t.get_open_order_nos()
return result, error
async def _on_order_update_callback(self, order: Order):
""" Order information update callback.
Args:
order: Order object.
"""
o = {
"platform": order.platform,
"account": order.account,
"strategy": order.strategy,
"order_no": order.order_no,
"action": order.action,
"order_type": order.order_type,
"symbol": order.symbol,
"price": order.price,
"quantity": order.quantity,
"remain": order.remain,
"status": order.status,
"avg_price": order.avg_price,
"trade_type": order.trade_type,
"ctime": order.ctime,
"utime": order.utime
}
EventOrder(**o).publish()
if self._order_update_callback:
SingleTask.run(self._order_update_callback, order)
async def _on_position_update_callback(self, position: Position):
""" Position information update callback.
Args:
position: Position object.
"""
if self._position_update_callback:
SingleTask.run(self._position_update_callback, position)
async def _on_init_success_callback(self, success: bool, error: Error):
""" Callback function when initialize Trade module finished.
Args:
success: `True` if initialize Trade module success, otherwise `False`.
error: `Error object` if initialize Trade module failed, otherwise `None`.
"""
if self._init_success_callback:
params = {
"strategy": self._raw_params["strategy"],
"platform": self._raw_params["platform"],
"symbol": self._raw_params["symbol"],
"account": self._raw_params["account"]
}
await self._init_success_callback(success, error, **params) | quant/trade.py | import copy
from quant import const
from quant.error import Error
from quant.utils import logger
from quant.tasks import SingleTask
from quant.order import ORDER_TYPE_LIMIT
from quant.order import Order
from quant.position import Position
from quant.event import EventOrder
class Trade:
""" Trade Module.
Attributes:
strategy: What's name would you want to created for your strategy.
platform: Exchange platform name. e.g. `binance` / `okex` / `bitmex`.
symbol: Symbol name for your trade. e.g. `BTC/USDT`.
host: HTTP request host.
wss: Websocket address.
account: Account name for this trade exchange.
access_key: Account's ACCESS KEY.
secret_key: Account's SECRET KEY.
passphrase: API KEY Passphrase. (Only for `OKEx`)
asset_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `asset_update_callback` is like `async def on_asset_update_callback(asset: Asset): pass` and this
callback function will be executed asynchronous when received AssetEvent.
order_update_callback: You can use this param to specific a async callback function when you initializing Trade
object. `order_update_callback` is like `async def on_order_update_callback(order: Order): pass` and this
callback function will be executed asynchronous when some order state updated.
position_update_callback: You can use this param to specific a async callback function when you initializing
Trade object. `position_update_callback` is like `async def on_position_update_callback(position: Position): pass`
and this callback function will be executed asynchronous when position updated.
init_success_callback: You can use this param to specific a async callback function when you initializing Trade
object. `init_success_callback` is like `async def on_init_success_callback(success: bool, error: Error, **kwargs): pass`
and this callback function will be executed asynchronous after Trade module object initialized successfully.
"""
def __init__(self, strategy=None, platform=None, symbol=None, host=None, wss=None, account=None, access_key=None,
secret_key=None, passphrase=None, asset_update_callback=None, order_update_callback=None,
position_update_callback=None, init_success_callback=None, **kwargs):
"""initialize trade object."""
kwargs["strategy"] = strategy
kwargs["platform"] = platform
kwargs["symbol"] = symbol
kwargs["host"] = host
kwargs["wss"] = wss
kwargs["account"] = account
kwargs["access_key"] = access_key
kwargs["secret_key"] = secret_key
kwargs["passphrase"] = <PASSWORD>
kwargs["asset_update_callback"] = asset_update_callback
kwargs["order_update_callback"] = self._on_order_update_callback
kwargs["position_update_callback"] = self._on_position_update_callback
kwargs["init_success_callback"] = self._on_init_success_callback
self._raw_params = copy.copy(kwargs)
self._order_update_callback = order_update_callback
self._position_update_callback = position_update_callback
self._init_success_callback = init_success_callback
if platform == const.OKEX:
from quant.platform.okex import OKExTrade as T
elif platform == const.OKEX_MARGIN:
from quant.platform.okex_margin import OKExMarginTrade as T
elif platform == const.OKEX_FUTURE:
from quant.platform.okex_future import OKExFutureTrade as T
elif platform == const.OKEX_SWAP:
from quant.platform.okex_swap import OKExSwapTrade as T
elif platform == const.DERIBIT:
from quant.platform.deribit import DeribitTrade as T
elif platform == const.BITMEX:
from quant.platform.bitmex import BitmexTrade as T
elif platform == const.BINANCE:
from quant.platform.binance import BinanceTrade as T
elif platform == const.BINANCE_FUTURE:
from quant.platform.binance_future import BinanceFutureTrade as T
elif platform == const.HUOBI:
from quant.platform.huobi import HuobiTrade as T
elif platform == const.COINSUPER:
from quant.platform.coinsuper import CoinsuperTrade as T
elif platform == const.COINSUPER_PRE:
from quant.platform.coinsuper_pre import CoinsuperPreTrade as T
elif platform == const.KRAKEN:
from quant.platform.kraken import KrakenTrade as T
elif platform == const.GATE:
from quant.platform.gate import GateTrade as T
elif platform == const.KUCOIN:
from quant.platform.kucoin import KucoinTrade as T
elif platform == const.HUOBI_FUTURE:
from quant.platform.huobi_future import HuobiFutureTrade as T
else:
logger.error("platform error:", platform, caller=self)
e = Error("platform error")
SingleTask.run(self._init_success_callback, False, e)
return
kwargs.pop("platform")
self._t = T(**kwargs)
@property
def assets(self):
return self._t.assets
@property
def orders(self):
return self._t.orders
@property
def position(self):
return self._t.position
@property
def rest_api(self):
return self._t.rest_api
async def create_order(self, action, price, quantity, order_type=ORDER_TYPE_LIMIT, **kwargs):
""" Create an order.
Args:
action: Trade direction, `BUY` or `SELL`.
price: Price of each contract.
quantity: The buying or selling quantity.
order_type: Specific type of order, `LIMIT` or `MARKET`. (default is `LIMIT`)
Returns:
order_no: Order ID if created successfully, otherwise it's None.
error: Error information, otherwise it's None.
"""
order_no, error = await self._t.create_order(action, price, quantity, order_type, **kwargs)
return order_no, error
async def revoke_order(self, *order_nos):
""" Revoke (an) order(s).
Args:
order_nos: Order id list, you can set this param to 0 or multiple items. If you set 0 param, you can cancel
all orders for this symbol(initialized in Trade object). If you set 1 param, you can cancel an order.
If you set multiple param, you can cancel multiple orders. Do not set param length more than 100.
Returns:
success: If execute successfully, return success information, otherwise it's None.
error: If execute failed, return error information, otherwise it's None.
"""
success, error = await self._t.revoke_order(*order_nos)
return success, error
async def get_open_order_nos(self):
""" Get open order id list.
Args:
None.
Returns:
order_nos: Open order id list, otherwise it's None.
error: Error information, otherwise it's None.
"""
result, error = await self._t.get_open_order_nos()
return result, error
async def _on_order_update_callback(self, order: Order):
""" Order information update callback.
Args:
order: Order object.
"""
o = {
"platform": order.platform,
"account": order.account,
"strategy": order.strategy,
"order_no": order.order_no,
"action": order.action,
"order_type": order.order_type,
"symbol": order.symbol,
"price": order.price,
"quantity": order.quantity,
"remain": order.remain,
"status": order.status,
"avg_price": order.avg_price,
"trade_type": order.trade_type,
"ctime": order.ctime,
"utime": order.utime
}
EventOrder(**o).publish()
if self._order_update_callback:
SingleTask.run(self._order_update_callback, order)
async def _on_position_update_callback(self, position: Position):
""" Position information update callback.
Args:
position: Position object.
"""
if self._position_update_callback:
SingleTask.run(self._position_update_callback, position)
async def _on_init_success_callback(self, success: bool, error: Error):
""" Callback function when initialize Trade module finished.
Args:
success: `True` if initialize Trade module success, otherwise `False`.
error: `Error object` if initialize Trade module failed, otherwise `None`.
"""
if self._init_success_callback:
params = {
"strategy": self._raw_params["strategy"],
"platform": self._raw_params["platform"],
"symbol": self._raw_params["symbol"],
"account": self._raw_params["account"]
}
await self._init_success_callback(success, error, **params) | 0.854824 | 0.155976 |
from jnius import autoclass
import re
import io
from PIL import Image
from parsers.contenttypeanalyzer import ContentTypeAnalyzer
from parsers.ocrproxy import OCRProxy, OCRProxyResponse
from parsers.fileparserresponse import FileParserResponse
from parsers.binarystringparser import BinaryStringParser
class TikaParser:
def __init__(self, Logger, TikaCallTimeoutSeconds):
self.logger = Logger
self.ocrProxy = OCRProxy()
self.ByteArrayInputStream = autoclass('java.io.ByteArrayInputStream')
self.Metadata = autoclass('org.apache.tika.metadata.Metadata')
self.AutoDetectParser = autoclass('org.apache.tika.parser.AutoDetectParser')
self.BodyContentHandler = autoclass('org.apache.tika.sax.BodyContentHandler')
self.TikaConfig = autoclass('org.apache.tika.config.TikaConfig')
self.config = self.TikaConfig('/tika-config.xml')
self.parser = self.AutoDetectParser(self.config)
def Parse(self, FileName, FileData):
resp = FileParserResponse()
try:
meta = self.Metadata()
if FileName and FileName != '':
meta.set(self.Metadata.RESOURCE_NAME_KEY, FileName)
contentHandler = self.BodyContentHandler(-1)
inputStream = self.ByteArrayInputStream(FileData)
self.parser.parse(inputStream, contentHandler, meta)
try:
resp.text = contentHandler.toString()
except Exception as convEx:
resp.text = BinaryStringParser.Parse(convEx.object)
for name in meta.names():
try:
resp.meta[name] = meta.get(name)
except:
resp.meta[name] = ''
inputStream = None
contentHandler = None
if 'Content-Type' in resp.meta and ContentTypeAnalyzer.IsImageByContentType(resp.meta['Content-Type']):
self.logger.LogMessage('info','performing ocr on {0}'.format(FileName))
ocrResp = self.ocrProxy.PerformOCR(FileData)
if ocrResp.success:
resp.text = self.NormalizeText('{0}{1}'.format(resp.text, ocrResp.text))
resp.ocrPerformed = True
if not ocrResp.success:
self.logger.LogMessage('info','could not perform ocr on {0} {1}'.format(FileName, ocrResp.message))
resp.thumbnail = self.GenerateThumbnail(FileData)
resp.success = True
except Exception as ex:
resp.success = False
resp.message = str(ex)
return resp
def GenerateThumbnail(self, ImageData, MaxWidth = 1000, MaxHeigh = 5000, Quality = 70, Dpi = 50):
try:
image = Image.open(io.BytesIO(ImageData))
if 'compression' in image.info and image.info['compression']=='tiff_jpeg':
return None
image.thumbnail((MaxWidth,MaxHeigh))
bytesIO = io.BytesIO()
image.convert('RGB').save(bytesIO, format='JPEG', quality=Quality)
return (bytesIO.getvalue(), 'image/jpeg')
except:
pass
return None
def NormalizeText(self, Text):
regex = re.compile(r'([\s]*[\r]*\n){2,}')
return re.sub(regex, '\r\n', Text) | Pipeline/parsers/tikaparser.py | from jnius import autoclass
import re
import io
from PIL import Image
from parsers.contenttypeanalyzer import ContentTypeAnalyzer
from parsers.ocrproxy import OCRProxy, OCRProxyResponse
from parsers.fileparserresponse import FileParserResponse
from parsers.binarystringparser import BinaryStringParser
class TikaParser:
def __init__(self, Logger, TikaCallTimeoutSeconds):
self.logger = Logger
self.ocrProxy = OCRProxy()
self.ByteArrayInputStream = autoclass('java.io.ByteArrayInputStream')
self.Metadata = autoclass('org.apache.tika.metadata.Metadata')
self.AutoDetectParser = autoclass('org.apache.tika.parser.AutoDetectParser')
self.BodyContentHandler = autoclass('org.apache.tika.sax.BodyContentHandler')
self.TikaConfig = autoclass('org.apache.tika.config.TikaConfig')
self.config = self.TikaConfig('/tika-config.xml')
self.parser = self.AutoDetectParser(self.config)
def Parse(self, FileName, FileData):
resp = FileParserResponse()
try:
meta = self.Metadata()
if FileName and FileName != '':
meta.set(self.Metadata.RESOURCE_NAME_KEY, FileName)
contentHandler = self.BodyContentHandler(-1)
inputStream = self.ByteArrayInputStream(FileData)
self.parser.parse(inputStream, contentHandler, meta)
try:
resp.text = contentHandler.toString()
except Exception as convEx:
resp.text = BinaryStringParser.Parse(convEx.object)
for name in meta.names():
try:
resp.meta[name] = meta.get(name)
except:
resp.meta[name] = ''
inputStream = None
contentHandler = None
if 'Content-Type' in resp.meta and ContentTypeAnalyzer.IsImageByContentType(resp.meta['Content-Type']):
self.logger.LogMessage('info','performing ocr on {0}'.format(FileName))
ocrResp = self.ocrProxy.PerformOCR(FileData)
if ocrResp.success:
resp.text = self.NormalizeText('{0}{1}'.format(resp.text, ocrResp.text))
resp.ocrPerformed = True
if not ocrResp.success:
self.logger.LogMessage('info','could not perform ocr on {0} {1}'.format(FileName, ocrResp.message))
resp.thumbnail = self.GenerateThumbnail(FileData)
resp.success = True
except Exception as ex:
resp.success = False
resp.message = str(ex)
return resp
def GenerateThumbnail(self, ImageData, MaxWidth = 1000, MaxHeigh = 5000, Quality = 70, Dpi = 50):
try:
image = Image.open(io.BytesIO(ImageData))
if 'compression' in image.info and image.info['compression']=='tiff_jpeg':
return None
image.thumbnail((MaxWidth,MaxHeigh))
bytesIO = io.BytesIO()
image.convert('RGB').save(bytesIO, format='JPEG', quality=Quality)
return (bytesIO.getvalue(), 'image/jpeg')
except:
pass
return None
def NormalizeText(self, Text):
regex = re.compile(r'([\s]*[\r]*\n){2,}')
return re.sub(regex, '\r\n', Text) | 0.429908 | 0.080538 |
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import functools
import glob
import os
import re
import sys
from concurrent.futures import ProcessPoolExecutor
import setuptools
from isort import SortImports, __version__
from isort.settings import DEFAULT_SECTIONS, default, from_path, should_skip
from .pie_slice import itemsview
INTRO = r"""
/#######################################################################\
`sMMy`
.yyyy- `
##soos## ./o.
` ``..-..` ``...`.`` ` ```` ``-ssso```
.s:-y- .+osssssso/. ./ossss+:so+:` :+o-`/osso:+sssssssso/
.s::y- osss+.``.`` -ssss+-.`-ossso` ssssso/::..::+ssss:::.
.s::y- /ssss+//:-.` `ssss+ `ssss+ sssso` :ssss`
.s::y- `-/+oossssso/ `ssss/ sssso ssss/ :ssss`
.y-/y- ````:ssss` ossso. :ssss: ssss/ :ssss.
`/so:` `-//::/osss+ `+ssss+-/ossso: /sso- `osssso/.
\/ `-/oooo++/- .:/++:/++/-` .. `://++/.
isort your Python imports for you so you don't have to
VERSION {0}
\########################################################################/
""".format(__version__)
shebang_re = re.compile(br'^#!.*\bpython[23w]?\b')
def is_python_file(path):
if path.endswith('.py'):
return True
try:
with open(path, 'rb') as fp:
line = fp.readline(100)
except IOError:
return False
else:
return bool(shebang_re.match(line))
class SortAttempt(object):
def __init__(self, incorrectly_sorted, skipped):
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
def sort_imports(file_name, **arguments):
try:
result = SortImports(file_name, **arguments)
return SortAttempt(result.incorrectly_sorted, result.skipped)
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(file_name, e))
return None
def iter_source_code(paths, config, skipped):
"""Iterate over all Python source files defined in paths."""
for path in paths:
if os.path.isdir(path):
if should_skip(path, config, os.getcwd()):
skipped.append(path)
continue
for dirpath, dirnames, filenames in os.walk(
path, topdown=True, followlinks=True
):
for dirname in list(dirnames):
if should_skip(dirname, config, dirpath):
skipped.append(dirname)
dirnames.remove(dirname)
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if is_python_file(filepath):
if should_skip(filename, config, dirpath):
skipped.append(filename)
else:
yield filepath
else:
yield path
class ISortCommand(setuptools.Command):
"""The :class:`ISortCommand` class is used by setuptools to perform
imports checks on registered modules.
"""
description = "Run isort on modules registered in setuptools"
user_options = []
def initialize_options(self):
default_settings = default.copy()
for (key, value) in itemsview(default_settings):
setattr(self, key, value)
def finalize_options(self):
"Get options from config files."
self.arguments = {}
computed_settings = from_path(os.getcwd())
for (key, value) in itemsview(computed_settings):
self.arguments[key] = value
def distribution_files(self):
"""Find distribution packages."""
# This is verbatim from flake8
if self.distribution.packages:
package_dirs = self.distribution.package_dir or {}
for package in self.distribution.packages:
pkg_dir = package
if package in package_dirs:
pkg_dir = package_dirs[package]
elif '' in package_dirs:
pkg_dir = package_dirs[''] + os.path.sep + pkg_dir
yield pkg_dir.replace('.', os.path.sep)
if self.distribution.py_modules:
for filename in self.distribution.py_modules:
yield "%s.py" % filename
# Don't miss the setup.py file itself
yield "setup.py"
def run(self):
arguments = self.arguments
wrong_sorted_files = False
arguments['check'] = True
for path in self.distribution_files():
for python_file in glob.iglob(os.path.join(path, '*.py')):
try:
incorrectly_sorted = SortImports(python_file, **arguments).incorrectly_sorted
if incorrectly_sorted:
wrong_sorted_files = True
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(python_file, e))
if wrong_sorted_files:
exit(1)
def create_parser():
parser = argparse.ArgumentParser(description='Sort Python import definitions alphabetically '
'within logical sections.')
inline_args_group = parser.add_mutually_exclusive_group()
parser.add_argument('-a', '--add-import', dest='add_imports', action='append',
help='Adds the specified import line to all files, '
'automatically determining correct placement.')
parser.add_argument('-ac', '--atomic', dest='atomic', action='store_true',
help="Ensures the output doesn't save if the resulting file contains syntax errors.")
parser.add_argument('-af', '--force-adds', dest='force_adds', action='store_true',
help='Forces import adds even if the original file is empty.')
parser.add_argument('-b', '--builtin', dest='known_standard_library', action='append',
help='Force sortImports to recognize a module as part of the python standard library.')
parser.add_argument('-c', '--check-only', action='store_true', dest="check",
help='Checks the file for unsorted / unformatted imports and prints them to the '
'command line without modifying the file.')
parser.add_argument('-ca', '--combine-as', dest='combine_as_imports', action='store_true',
help="Combines as imports on the same line.")
parser.add_argument('-cs', '--combine-star', dest='combine_star', action='store_true',
help="Ensures that if a star import is present, nothing else is imported from that namespace.")
parser.add_argument('-d', '--stdout', help='Force resulting output to stdout, instead of in-place.',
dest='write_to_stdout', action='store_true')
parser.add_argument('-df', '--diff', dest='show_diff', action='store_true',
help="Prints a diff of all the changes isort would make to a file, instead of "
"changing it in place")
parser.add_argument('-ds', '--no-sections', help='Put all imports into the same section bucket', dest='no_sections',
action='store_true')
parser.add_argument('-dt', '--dont-order-by-type', dest='dont_order_by_type',
action='store_true', help='Only order imports alphabetically, do not attempt type ordering')
parser.add_argument('-e', '--balanced', dest='balanced_wrapping', action='store_true',
help='Balances wrapping to produce the most consistent line length possible')
parser.add_argument('-f', '--future', dest='known_future_library', action='append',
help='Force sortImports to recognize a module as part of the future compatibility libraries.')
parser.add_argument('-fas', '--force-alphabetical-sort', action='store_true', dest="force_alphabetical_sort",
help='Force all imports to be sorted as a single section')
parser.add_argument('-fass', '--force-alphabetical-sort-within-sections', action='store_true',
dest="force_alphabetical_sort", help='Force all imports to be sorted alphabetically within a '
'section')
parser.add_argument('-ff', '--from-first', dest='from_first',
help="Switches the typical ordering preference, showing from imports first then straight ones.")
parser.add_argument('-fgw', '--force-grid-wrap', nargs='?', const=2, type=int, dest="force_grid_wrap",
help='Force number of from imports (defaults to 2) to be grid wrapped regardless of line '
'length')
parser.add_argument('-fss', '--force-sort-within-sections', action='store_true', dest="force_sort_within_sections",
help='Force imports to be sorted by module, independent of import_type')
parser.add_argument('-i', '--indent', help='String to place for indents defaults to " " (4 spaces).',
dest='indent', type=str)
parser.add_argument('-j', '--jobs', help='Number of files to process in parallel.',
dest='jobs', type=int)
parser.add_argument('-k', '--keep-direct-and-as', dest='keep_direct_and_as_imports', action='store_true',
help="Turns off default behavior that removes direct imports when as imports exist.")
parser.add_argument('-l', '--lines', help='[Deprecated] The max length of an import line (used for wrapping '
'long imports).',
dest='line_length', type=int)
parser.add_argument('-lai', '--lines-after-imports', dest='lines_after_imports', type=int)
parser.add_argument('-lbt', '--lines-between-types', dest='lines_between_types', type=int)
parser.add_argument('-le', '--line-ending', dest='line_ending',
help="Forces line endings to the specified value. If not set, values will be guessed per-file.")
parser.add_argument('-ls', '--length-sort', help='Sort imports by their string length.',
dest='length_sort', action='store_true')
parser.add_argument('-m', '--multi-line', dest='multi_line_output', type=int, choices=[0, 1, 2, 3, 4, 5],
help='Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, '
'5-vert-grid-grouped, 6-vert-grid-grouped-no-comma).')
inline_args_group.add_argument('-nis', '--no-inline-sort', dest='no_inline_sort', action='store_true',
help='Leaves `from` imports with multiple imports \'as-is\' (e.g. `from foo import a, c ,b`).')
parser.add_argument('-nlb', '--no-lines-before', help='Sections which should not be split with previous by empty lines',
dest='no_lines_before', action='append')
parser.add_argument('-ns', '--dont-skip', help='Files that sort imports should never skip over.',
dest='not_skip', action='append')
parser.add_argument('-o', '--thirdparty', dest='known_third_party', action='append',
help='Force sortImports to recognize a module as being part of a third party library.')
parser.add_argument('-ot', '--order-by-type', dest='order_by_type',
action='store_true', help='Order imports by type in addition to alphabetically')
parser.add_argument('-p', '--project', dest='known_first_party', action='append',
help='Force sortImports to recognize a module as being part of the current python project.')
parser.add_argument('-q', '--quiet', action='store_true', dest="quiet",
help='Shows extra quiet output, only errors are outputted.')
parser.add_argument('-r', '--remove-import', dest='remove_imports', action='append',
help='Removes the specified import from all files.')
parser.add_argument('-rc', '--recursive', dest='recursive', action='store_true',
help='Recursively look for Python files of which to sort imports')
parser.add_argument('-s', '--skip', help='Files that sort imports should skip over. If you want to skip multiple '
'files you should specify twice: --skip file1 --skip file2.', dest='skip', action='append')
parser.add_argument('-sd', '--section-default', dest='default_section',
help='Sets the default section for imports (by default FIRSTPARTY) options: ' +
str(DEFAULT_SECTIONS))
parser.add_argument('-sg', '--skip-glob', help='Files that sort imports should skip over.', dest='skip_glob',
action='append')
inline_args_group.add_argument('-sl', '--force-single-line-imports', dest='force_single_line', action='store_true',
help='Forces all from imports to appear on their own line')
parser.add_argument('-sp', '--settings-path', dest="settings_path",
help='Explicitly set the settings path instead of auto determining based on file location.')
parser.add_argument('-t', '--top', help='Force specific imports to the top of their appropriate section.',
dest='force_to_top', action='append')
parser.add_argument('-tc', '--trailing-comma', dest='include_trailing_comma', action='store_true',
help='Includes a trailing comma on multi line imports that include parentheses.')
parser.add_argument('-up', '--use-parentheses', dest='use_parentheses', action='store_true',
help='Use parenthesis for line continuation on length limit instead of slashes.')
parser.add_argument('-v', '--version', action='store_true', dest='show_version')
parser.add_argument('-vb', '--verbose', action='store_true', dest="verbose",
help='Shows verbose output, such as when files are skipped or when a check is successful.')
parser.add_argument('--virtual-env', dest='virtual_env',
help='Virtual environment to use for determining whether a package is third-party')
parser.add_argument('-vn', '--version-number', action='version', version=__version__,
help='Returns just the current version number without the logo')
parser.add_argument('-w', '--line-width', help='The max length of an import line (used for wrapping long imports).',
dest='line_length', type=int)
parser.add_argument('-wl', '--wrap-length', dest='wrap_length',
help="Specifies how long lines that are wrapped should be, if not set line_length is used.")
parser.add_argument('-ws', '--ignore-whitespace', action='store_true', dest="ignore_whitespace",
help='Tells isort to ignore whitespace differences when --check-only is being used.')
parser.add_argument('-y', '--apply', dest='apply', action='store_true',
help='Tells isort to apply changes recursively without asking')
parser.add_argument('files', nargs='*', help='One or more Python source files that need their imports sorted.')
arguments = {key: value for key, value in itemsview(vars(parser.parse_args())) if value}
if 'dont_order_by_type' in arguments:
arguments['order_by_type'] = False
return arguments
def main():
arguments = create_parser()
if arguments.get('show_version'):
print(INTRO)
return
if 'settings_path' in arguments:
sp = arguments['settings_path']
arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(sp) else os.path.dirname(os.path.abspath(sp))
if not os.path.isdir(arguments['settings_path']):
print("WARNING: settings_path dir does not exist: {0}".format(arguments['settings_path']))
if 'virtual_env' in arguments:
venv = arguments['virtual_env']
arguments['virtual_env'] = os.path.abspath(venv)
if not os.path.isdir(arguments['virtual_env']):
print("WARNING: virtual_env dir does not exist: {0}".format(arguments['virtual_env']))
file_names = arguments.pop('files', [])
if file_names == ['-']:
SortImports(file_contents=sys.stdin.read(), write_to_stdout=True, **arguments)
else:
if not file_names:
file_names = ['.']
arguments['recursive'] = True
if not arguments.get('apply', False):
arguments['ask_to_apply'] = True
config = from_path(os.path.abspath(file_names[0]) or os.getcwd()).copy()
config.update(arguments)
wrong_sorted_files = False
skipped = []
if arguments.get('recursive', False):
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config['verbose'] or config.get('show_logo', False):
print(INTRO)
jobs = arguments.get('jobs')
if jobs:
executor = ProcessPoolExecutor(max_workers=jobs)
for sort_attempt in executor.map(functools.partial(sort_imports, **arguments), file_names):
if not sort_attempt:
continue
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get('check', False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1
else:
for file_name in file_names:
try:
sort_attempt = SortImports(file_name, **arguments)
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get('check', False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(file_name, e))
if wrong_sorted_files:
exit(1)
num_skipped += len(skipped)
if num_skipped and not arguments.get('quiet', False):
if config['verbose']:
for was_skipped in skipped:
print("WARNING: {0} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting".format(was_skipped))
print("Skipped {0} files".format(num_skipped))
if __name__ == "__main__":
main() | isort/main.py | from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import functools
import glob
import os
import re
import sys
from concurrent.futures import ProcessPoolExecutor
import setuptools
from isort import SortImports, __version__
from isort.settings import DEFAULT_SECTIONS, default, from_path, should_skip
from .pie_slice import itemsview
INTRO = r"""
/#######################################################################\
`sMMy`
.yyyy- `
##soos## ./o.
` ``..-..` ``...`.`` ` ```` ``-ssso```
.s:-y- .+osssssso/. ./ossss+:so+:` :+o-`/osso:+sssssssso/
.s::y- osss+.``.`` -ssss+-.`-ossso` ssssso/::..::+ssss:::.
.s::y- /ssss+//:-.` `ssss+ `ssss+ sssso` :ssss`
.s::y- `-/+oossssso/ `ssss/ sssso ssss/ :ssss`
.y-/y- ````:ssss` ossso. :ssss: ssss/ :ssss.
`/so:` `-//::/osss+ `+ssss+-/ossso: /sso- `osssso/.
\/ `-/oooo++/- .:/++:/++/-` .. `://++/.
isort your Python imports for you so you don't have to
VERSION {0}
\########################################################################/
""".format(__version__)
shebang_re = re.compile(br'^#!.*\bpython[23w]?\b')
def is_python_file(path):
if path.endswith('.py'):
return True
try:
with open(path, 'rb') as fp:
line = fp.readline(100)
except IOError:
return False
else:
return bool(shebang_re.match(line))
class SortAttempt(object):
def __init__(self, incorrectly_sorted, skipped):
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
def sort_imports(file_name, **arguments):
try:
result = SortImports(file_name, **arguments)
return SortAttempt(result.incorrectly_sorted, result.skipped)
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(file_name, e))
return None
def iter_source_code(paths, config, skipped):
"""Iterate over all Python source files defined in paths."""
for path in paths:
if os.path.isdir(path):
if should_skip(path, config, os.getcwd()):
skipped.append(path)
continue
for dirpath, dirnames, filenames in os.walk(
path, topdown=True, followlinks=True
):
for dirname in list(dirnames):
if should_skip(dirname, config, dirpath):
skipped.append(dirname)
dirnames.remove(dirname)
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if is_python_file(filepath):
if should_skip(filename, config, dirpath):
skipped.append(filename)
else:
yield filepath
else:
yield path
class ISortCommand(setuptools.Command):
"""The :class:`ISortCommand` class is used by setuptools to perform
imports checks on registered modules.
"""
description = "Run isort on modules registered in setuptools"
user_options = []
def initialize_options(self):
default_settings = default.copy()
for (key, value) in itemsview(default_settings):
setattr(self, key, value)
def finalize_options(self):
"Get options from config files."
self.arguments = {}
computed_settings = from_path(os.getcwd())
for (key, value) in itemsview(computed_settings):
self.arguments[key] = value
def distribution_files(self):
"""Find distribution packages."""
# This is verbatim from flake8
if self.distribution.packages:
package_dirs = self.distribution.package_dir or {}
for package in self.distribution.packages:
pkg_dir = package
if package in package_dirs:
pkg_dir = package_dirs[package]
elif '' in package_dirs:
pkg_dir = package_dirs[''] + os.path.sep + pkg_dir
yield pkg_dir.replace('.', os.path.sep)
if self.distribution.py_modules:
for filename in self.distribution.py_modules:
yield "%s.py" % filename
# Don't miss the setup.py file itself
yield "setup.py"
def run(self):
arguments = self.arguments
wrong_sorted_files = False
arguments['check'] = True
for path in self.distribution_files():
for python_file in glob.iglob(os.path.join(path, '*.py')):
try:
incorrectly_sorted = SortImports(python_file, **arguments).incorrectly_sorted
if incorrectly_sorted:
wrong_sorted_files = True
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(python_file, e))
if wrong_sorted_files:
exit(1)
def create_parser():
parser = argparse.ArgumentParser(description='Sort Python import definitions alphabetically '
'within logical sections.')
inline_args_group = parser.add_mutually_exclusive_group()
parser.add_argument('-a', '--add-import', dest='add_imports', action='append',
help='Adds the specified import line to all files, '
'automatically determining correct placement.')
parser.add_argument('-ac', '--atomic', dest='atomic', action='store_true',
help="Ensures the output doesn't save if the resulting file contains syntax errors.")
parser.add_argument('-af', '--force-adds', dest='force_adds', action='store_true',
help='Forces import adds even if the original file is empty.')
parser.add_argument('-b', '--builtin', dest='known_standard_library', action='append',
help='Force sortImports to recognize a module as part of the python standard library.')
parser.add_argument('-c', '--check-only', action='store_true', dest="check",
help='Checks the file for unsorted / unformatted imports and prints them to the '
'command line without modifying the file.')
parser.add_argument('-ca', '--combine-as', dest='combine_as_imports', action='store_true',
help="Combines as imports on the same line.")
parser.add_argument('-cs', '--combine-star', dest='combine_star', action='store_true',
help="Ensures that if a star import is present, nothing else is imported from that namespace.")
parser.add_argument('-d', '--stdout', help='Force resulting output to stdout, instead of in-place.',
dest='write_to_stdout', action='store_true')
parser.add_argument('-df', '--diff', dest='show_diff', action='store_true',
help="Prints a diff of all the changes isort would make to a file, instead of "
"changing it in place")
parser.add_argument('-ds', '--no-sections', help='Put all imports into the same section bucket', dest='no_sections',
action='store_true')
parser.add_argument('-dt', '--dont-order-by-type', dest='dont_order_by_type',
action='store_true', help='Only order imports alphabetically, do not attempt type ordering')
parser.add_argument('-e', '--balanced', dest='balanced_wrapping', action='store_true',
help='Balances wrapping to produce the most consistent line length possible')
parser.add_argument('-f', '--future', dest='known_future_library', action='append',
help='Force sortImports to recognize a module as part of the future compatibility libraries.')
parser.add_argument('-fas', '--force-alphabetical-sort', action='store_true', dest="force_alphabetical_sort",
help='Force all imports to be sorted as a single section')
parser.add_argument('-fass', '--force-alphabetical-sort-within-sections', action='store_true',
dest="force_alphabetical_sort", help='Force all imports to be sorted alphabetically within a '
'section')
parser.add_argument('-ff', '--from-first', dest='from_first',
help="Switches the typical ordering preference, showing from imports first then straight ones.")
parser.add_argument('-fgw', '--force-grid-wrap', nargs='?', const=2, type=int, dest="force_grid_wrap",
help='Force number of from imports (defaults to 2) to be grid wrapped regardless of line '
'length')
parser.add_argument('-fss', '--force-sort-within-sections', action='store_true', dest="force_sort_within_sections",
help='Force imports to be sorted by module, independent of import_type')
parser.add_argument('-i', '--indent', help='String to place for indents defaults to " " (4 spaces).',
dest='indent', type=str)
parser.add_argument('-j', '--jobs', help='Number of files to process in parallel.',
dest='jobs', type=int)
parser.add_argument('-k', '--keep-direct-and-as', dest='keep_direct_and_as_imports', action='store_true',
help="Turns off default behavior that removes direct imports when as imports exist.")
parser.add_argument('-l', '--lines', help='[Deprecated] The max length of an import line (used for wrapping '
'long imports).',
dest='line_length', type=int)
parser.add_argument('-lai', '--lines-after-imports', dest='lines_after_imports', type=int)
parser.add_argument('-lbt', '--lines-between-types', dest='lines_between_types', type=int)
parser.add_argument('-le', '--line-ending', dest='line_ending',
help="Forces line endings to the specified value. If not set, values will be guessed per-file.")
parser.add_argument('-ls', '--length-sort', help='Sort imports by their string length.',
dest='length_sort', action='store_true')
parser.add_argument('-m', '--multi-line', dest='multi_line_output', type=int, choices=[0, 1, 2, 3, 4, 5],
help='Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, '
'5-vert-grid-grouped, 6-vert-grid-grouped-no-comma).')
inline_args_group.add_argument('-nis', '--no-inline-sort', dest='no_inline_sort', action='store_true',
help='Leaves `from` imports with multiple imports \'as-is\' (e.g. `from foo import a, c ,b`).')
parser.add_argument('-nlb', '--no-lines-before', help='Sections which should not be split with previous by empty lines',
dest='no_lines_before', action='append')
parser.add_argument('-ns', '--dont-skip', help='Files that sort imports should never skip over.',
dest='not_skip', action='append')
parser.add_argument('-o', '--thirdparty', dest='known_third_party', action='append',
help='Force sortImports to recognize a module as being part of a third party library.')
parser.add_argument('-ot', '--order-by-type', dest='order_by_type',
action='store_true', help='Order imports by type in addition to alphabetically')
parser.add_argument('-p', '--project', dest='known_first_party', action='append',
help='Force sortImports to recognize a module as being part of the current python project.')
parser.add_argument('-q', '--quiet', action='store_true', dest="quiet",
help='Shows extra quiet output, only errors are outputted.')
parser.add_argument('-r', '--remove-import', dest='remove_imports', action='append',
help='Removes the specified import from all files.')
parser.add_argument('-rc', '--recursive', dest='recursive', action='store_true',
help='Recursively look for Python files of which to sort imports')
parser.add_argument('-s', '--skip', help='Files that sort imports should skip over. If you want to skip multiple '
'files you should specify twice: --skip file1 --skip file2.', dest='skip', action='append')
parser.add_argument('-sd', '--section-default', dest='default_section',
help='Sets the default section for imports (by default FIRSTPARTY) options: ' +
str(DEFAULT_SECTIONS))
parser.add_argument('-sg', '--skip-glob', help='Files that sort imports should skip over.', dest='skip_glob',
action='append')
inline_args_group.add_argument('-sl', '--force-single-line-imports', dest='force_single_line', action='store_true',
help='Forces all from imports to appear on their own line')
parser.add_argument('-sp', '--settings-path', dest="settings_path",
help='Explicitly set the settings path instead of auto determining based on file location.')
parser.add_argument('-t', '--top', help='Force specific imports to the top of their appropriate section.',
dest='force_to_top', action='append')
parser.add_argument('-tc', '--trailing-comma', dest='include_trailing_comma', action='store_true',
help='Includes a trailing comma on multi line imports that include parentheses.')
parser.add_argument('-up', '--use-parentheses', dest='use_parentheses', action='store_true',
help='Use parenthesis for line continuation on length limit instead of slashes.')
parser.add_argument('-v', '--version', action='store_true', dest='show_version')
parser.add_argument('-vb', '--verbose', action='store_true', dest="verbose",
help='Shows verbose output, such as when files are skipped or when a check is successful.')
parser.add_argument('--virtual-env', dest='virtual_env',
help='Virtual environment to use for determining whether a package is third-party')
parser.add_argument('-vn', '--version-number', action='version', version=__version__,
help='Returns just the current version number without the logo')
parser.add_argument('-w', '--line-width', help='The max length of an import line (used for wrapping long imports).',
dest='line_length', type=int)
parser.add_argument('-wl', '--wrap-length', dest='wrap_length',
help="Specifies how long lines that are wrapped should be, if not set line_length is used.")
parser.add_argument('-ws', '--ignore-whitespace', action='store_true', dest="ignore_whitespace",
help='Tells isort to ignore whitespace differences when --check-only is being used.')
parser.add_argument('-y', '--apply', dest='apply', action='store_true',
help='Tells isort to apply changes recursively without asking')
parser.add_argument('files', nargs='*', help='One or more Python source files that need their imports sorted.')
arguments = {key: value for key, value in itemsview(vars(parser.parse_args())) if value}
if 'dont_order_by_type' in arguments:
arguments['order_by_type'] = False
return arguments
def main():
arguments = create_parser()
if arguments.get('show_version'):
print(INTRO)
return
if 'settings_path' in arguments:
sp = arguments['settings_path']
arguments['settings_path'] = os.path.abspath(sp) if os.path.isdir(sp) else os.path.dirname(os.path.abspath(sp))
if not os.path.isdir(arguments['settings_path']):
print("WARNING: settings_path dir does not exist: {0}".format(arguments['settings_path']))
if 'virtual_env' in arguments:
venv = arguments['virtual_env']
arguments['virtual_env'] = os.path.abspath(venv)
if not os.path.isdir(arguments['virtual_env']):
print("WARNING: virtual_env dir does not exist: {0}".format(arguments['virtual_env']))
file_names = arguments.pop('files', [])
if file_names == ['-']:
SortImports(file_contents=sys.stdin.read(), write_to_stdout=True, **arguments)
else:
if not file_names:
file_names = ['.']
arguments['recursive'] = True
if not arguments.get('apply', False):
arguments['ask_to_apply'] = True
config = from_path(os.path.abspath(file_names[0]) or os.getcwd()).copy()
config.update(arguments)
wrong_sorted_files = False
skipped = []
if arguments.get('recursive', False):
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config['verbose'] or config.get('show_logo', False):
print(INTRO)
jobs = arguments.get('jobs')
if jobs:
executor = ProcessPoolExecutor(max_workers=jobs)
for sort_attempt in executor.map(functools.partial(sort_imports, **arguments), file_names):
if not sort_attempt:
continue
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get('check', False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1
else:
for file_name in file_names:
try:
sort_attempt = SortImports(file_name, **arguments)
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get('check', False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1
except IOError as e:
print("WARNING: Unable to parse file {0} due to {1}".format(file_name, e))
if wrong_sorted_files:
exit(1)
num_skipped += len(skipped)
if num_skipped and not arguments.get('quiet', False):
if config['verbose']:
for was_skipped in skipped:
print("WARNING: {0} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting".format(was_skipped))
print("Skipped {0} files".format(num_skipped))
if __name__ == "__main__":
main() | 0.429669 | 0.239227 |
import random
from django.core.exceptions import ValidationError
from django.db import models
from django import forms
from staging.generators import BaseGenerator
class RandomObjectFilterForm(forms.Form):
filter_name = forms.CharField(label=u'queryset filter name', required=False)
filter_value = forms.CharField(label=u'queryset filter value', required=False)
def clean(self):
data = super(RandomObjectFilterForm, self).clean()
if (data.get('filter_name') or data.get('filter_value')) and (not data.get('filter_name') or not data.get('filter_value')):
raise ValidationError('Filter name and value must be specified both or omitted')
return data
class NotInitialized():
pass
class Generator(BaseGenerator):
name = 'Random object from queryset'
slug = 'random-object'
for_fields = [models.ForeignKey, models.OneToOneField]
options_form = RandomObjectFilterForm
def __init__(self):
self.objects_left = NotInitialized
def save(self, obj, field, form_data):
if field.unique:
if self.objects_left == NotInitialized:
self.objects_left = self._get_qs(getattr(obj.__class__, field.name).field, form_data)
setattr(obj, field.name, self._generate_unique())
else:
setattr(obj, field.name, self._generate(obj, field.name, form_data))
def _get_qs(self, field, form_data):
filter_name = form_data.get('filter_name')
filter_value = form_data.get('filter_value')
if filter_name and filter_value:
args = {filter_name: filter_value}
return list(field.related.parent_model.objects.filter(**args))
return list(field.related.parent_model.objects.all())
def _generate(self, obj, field_name, form_data):
qs = self._get_qs(getattr(obj.__class__, field_name).field, form_data)
return random.choice(qs)
def _generate_unique(self):
if self.objects_left:
object_ = random.choice(self.objects_left)
self.objects_left = [x for x in self.objects_left if x != object_]
return object_ | staging/generators/random_object.py | import random
from django.core.exceptions import ValidationError
from django.db import models
from django import forms
from staging.generators import BaseGenerator
class RandomObjectFilterForm(forms.Form):
filter_name = forms.CharField(label=u'queryset filter name', required=False)
filter_value = forms.CharField(label=u'queryset filter value', required=False)
def clean(self):
data = super(RandomObjectFilterForm, self).clean()
if (data.get('filter_name') or data.get('filter_value')) and (not data.get('filter_name') or not data.get('filter_value')):
raise ValidationError('Filter name and value must be specified both or omitted')
return data
class NotInitialized():
pass
class Generator(BaseGenerator):
name = 'Random object from queryset'
slug = 'random-object'
for_fields = [models.ForeignKey, models.OneToOneField]
options_form = RandomObjectFilterForm
def __init__(self):
self.objects_left = NotInitialized
def save(self, obj, field, form_data):
if field.unique:
if self.objects_left == NotInitialized:
self.objects_left = self._get_qs(getattr(obj.__class__, field.name).field, form_data)
setattr(obj, field.name, self._generate_unique())
else:
setattr(obj, field.name, self._generate(obj, field.name, form_data))
def _get_qs(self, field, form_data):
filter_name = form_data.get('filter_name')
filter_value = form_data.get('filter_value')
if filter_name and filter_value:
args = {filter_name: filter_value}
return list(field.related.parent_model.objects.filter(**args))
return list(field.related.parent_model.objects.all())
def _generate(self, obj, field_name, form_data):
qs = self._get_qs(getattr(obj.__class__, field_name).field, form_data)
return random.choice(qs)
def _generate_unique(self):
if self.objects_left:
object_ = random.choice(self.objects_left)
self.objects_left = [x for x in self.objects_left if x != object_]
return object_ | 0.370795 | 0.138055 |
import os
import time
from tensorboard.compat.proto import event_pb2
from tensorboard.compat.proto.config_pb2 import RunMetadata
from tensorboard.compat.proto.event_pb2 import Event, SessionLog
from tensorboard.compat.proto.graph_pb2 import GraphDef
from tensorboard.compat.proto.step_stats_pb2 import DeviceStepStats, StepStats
from tensorboard.compat.proto.summary_pb2 import Summary
from tensorboard.compat.proto.versions_pb2 import VersionDef
from tensorboard.summary.writer.event_file_writer import EventFileWriter
from .nnabla_graph import GraphVisitor
class FileWriter(object):
r"""Write protocol buffers to event files.
Args:
log_dir (str): Directory where event file will be written.
max_queue (int, optional): Size of the queue for pending events and summaries before one of the 'add' calls
forces a flush to disk. Defaults to 10.
flush_secs (int, optional): How often, in seconds, to flush the pending events and summaries to disk. Defaults
to every two minutes (120s).
filename_suffix (str, optional): Suffix added to all event filenames in the log_dir directory.
"""
def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix=''):
log_dir = str(log_dir)
self.event_writer = EventFileWriter(
log_dir, max_queue, flush_secs, filename_suffix)
def get_logdir(self):
r"""Returns the directory where event file will be written."""
return self.event_writer.get_logdir()
def add_event(self, event, step=None, walltime=None):
r"""Adds an event to the event file.
Args:
event: An `Event` protocol buffer.
step (int, optional): Optional global step value for training process to record with the
event.
walltime: float. Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
event.wall_time = time.time() if walltime is None else walltime
if step is not None:
event.step = int(step)
self.event_writer.add_event(event)
def add_summary(self, summary, global_step=None, walltime=None):
r"""Adds a `Summary` protocol buffer to the event file.
Args:
summary: A `Summary` protocol buffer.
global_step (int, optional): Optional global step value for training process to record
with the summary.
walltime (float, optional): Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
event = event_pb2.Event(summary=summary)
self.add_event(event, global_step, walltime)
def add_graph(self, graph_profile, walltime=None):
r"""Adds a `Graph` and step stats protocol buffer to the event file.
Args:
graph_profile: A `Graph` and step stats protocol buffer.
walltime (float, optional): Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
graph = graph_profile[0]
stepstats = graph_profile[1]
event = event_pb2.Event(graph_def=graph.SerializeToString())
self.add_event(event, None, walltime)
trm = event_pb2.TaggedRunMetadata(
tag='step1', run_metadata=stepstats.SerializeToString())
event = event_pb2.Event(tagged_run_metadata=trm)
self.add_event(event, None, walltime)
def flush(self):
r"""Flushes the event file to disk."""
self.event_writer.flush()
def close(self):
r"""Flushes the event file to disk and close the file."""
self.event_writer.close()
def reopen(self):
r"""Reopens the EventFileWriter."""
self.event_writer.reopen()
class SummaryWriter(object):
r"""Creates a `SummaryWriter` that will write out events and summaries to the event file.
Args:
log_dir (string): Save directory location. Default is
runs/CURRENT_DATETIME_HOSTNAME, which changes after each run.
Use hierarchical folder structure to compare
between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
for each new experiment to compare across them.
comment (string): Comment log_dir suffix appended to the default `log_dir`. If `log_dir` is assigned, this
argument has no effect.
purge_step (int): Note that crashed and resumed experiments should have the same ``log_dir``.
max_queue (int): Size of the queue for pending events and
summaries before one of the 'add' calls forces a flush to disk.
Default is ten items.
flush_secs (int): How often, in seconds, to flush the
pending events and summaries to disk. Default is every two minutes.
filename_suffix (string): Suffix added to all event filenames in
the log_dir directory. More details on filename construction in
tensorboard.summary.writer.event_file_writer.EventFileWriter.
"""
def __init__(self, log_dir=None, comment='', purge_step=None, max_queue=10,
flush_secs=120, filename_suffix=''):
if not log_dir:
import socket
from datetime import datetime
current_time = datetime.now().strftime('%b%d_%H-%M-%S')
log_dir = os.path.join(
'runs', current_time + '_' + socket.gethostname() + comment)
self.log_dir = log_dir
self.purge_step = purge_step
self.max_queue = max_queue
self.flush_secs = flush_secs
self.filename_suffix = filename_suffix
# Initialize the file writers, but they can be cleared out on close
# and recreated later as needed.
self.file_writer = self.all_writers = None
self._get_file_writer()
def _get_file_writer(self):
"""Returns the default FileWriter instance. Recreates it if closed."""
if self.all_writers is None or self.file_writer is None:
self.file_writer = FileWriter(self.log_dir, self.max_queue,
self.flush_secs, self.filename_suffix)
self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
if self.purge_step is not None:
most_recent_step = self.purge_step
self.file_writer.add_event(
Event(step=most_recent_step, file_version='brain.Event:2'))
self.file_writer.add_event(
Event(step=most_recent_step, session_log=SessionLog(status=SessionLog.START)))
self.purge_step = None
return self.file_writer
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
r"""Add a scalar value."""
scalar_value = float(scalar_value)
self._get_file_writer().add_summary(
Summary(value=[Summary.Value(tag=tag, simple_value=scalar_value)]),
global_step, walltime
)
def add_image(self, tag, img, global_step=None, walltime=None):
r"""Add an image."""
self._get_file_writer().add_summary(
Summary(value=[Summary.Value(tag=tag, image=img)])
)
def add_graph(self, model, *args, **kargs):
visitor = GraphVisitor(model, *args, **kargs)
stepstats = RunMetadata(step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")]))
graph = GraphDef(node=visitor._graph, versions=VersionDef(producer=22))
self._get_file_writer().add_graph((graph, stepstats))
def flush(self):
"""Flushes the event file to disk.
Call this method to make sure that all pending events have been written to
disk.
"""
if self.all_writers is None:
return
for writer in self.all_writers.values():
writer.flush()
def close(self):
if self.all_writers is None:
return # ignore double close
for writer in self.all_writers.values():
writer.flush()
writer.close()
self.file_writer = self.all_writers = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close() | nnabla_nas/utils/tensorboard/writer.py |
import os
import time
from tensorboard.compat.proto import event_pb2
from tensorboard.compat.proto.config_pb2 import RunMetadata
from tensorboard.compat.proto.event_pb2 import Event, SessionLog
from tensorboard.compat.proto.graph_pb2 import GraphDef
from tensorboard.compat.proto.step_stats_pb2 import DeviceStepStats, StepStats
from tensorboard.compat.proto.summary_pb2 import Summary
from tensorboard.compat.proto.versions_pb2 import VersionDef
from tensorboard.summary.writer.event_file_writer import EventFileWriter
from .nnabla_graph import GraphVisitor
class FileWriter(object):
r"""Write protocol buffers to event files.
Args:
log_dir (str): Directory where event file will be written.
max_queue (int, optional): Size of the queue for pending events and summaries before one of the 'add' calls
forces a flush to disk. Defaults to 10.
flush_secs (int, optional): How often, in seconds, to flush the pending events and summaries to disk. Defaults
to every two minutes (120s).
filename_suffix (str, optional): Suffix added to all event filenames in the log_dir directory.
"""
def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix=''):
log_dir = str(log_dir)
self.event_writer = EventFileWriter(
log_dir, max_queue, flush_secs, filename_suffix)
def get_logdir(self):
r"""Returns the directory where event file will be written."""
return self.event_writer.get_logdir()
def add_event(self, event, step=None, walltime=None):
r"""Adds an event to the event file.
Args:
event: An `Event` protocol buffer.
step (int, optional): Optional global step value for training process to record with the
event.
walltime: float. Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
event.wall_time = time.time() if walltime is None else walltime
if step is not None:
event.step = int(step)
self.event_writer.add_event(event)
def add_summary(self, summary, global_step=None, walltime=None):
r"""Adds a `Summary` protocol buffer to the event file.
Args:
summary: A `Summary` protocol buffer.
global_step (int, optional): Optional global step value for training process to record
with the summary.
walltime (float, optional): Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
event = event_pb2.Event(summary=summary)
self.add_event(event, global_step, walltime)
def add_graph(self, graph_profile, walltime=None):
r"""Adds a `Graph` and step stats protocol buffer to the event file.
Args:
graph_profile: A `Graph` and step stats protocol buffer.
walltime (float, optional): Optional walltime to override the default (current) walltime
(from time.time()) seconds after epoch.
"""
graph = graph_profile[0]
stepstats = graph_profile[1]
event = event_pb2.Event(graph_def=graph.SerializeToString())
self.add_event(event, None, walltime)
trm = event_pb2.TaggedRunMetadata(
tag='step1', run_metadata=stepstats.SerializeToString())
event = event_pb2.Event(tagged_run_metadata=trm)
self.add_event(event, None, walltime)
def flush(self):
r"""Flushes the event file to disk."""
self.event_writer.flush()
def close(self):
r"""Flushes the event file to disk and close the file."""
self.event_writer.close()
def reopen(self):
r"""Reopens the EventFileWriter."""
self.event_writer.reopen()
class SummaryWriter(object):
r"""Creates a `SummaryWriter` that will write out events and summaries to the event file.
Args:
log_dir (string): Save directory location. Default is
runs/CURRENT_DATETIME_HOSTNAME, which changes after each run.
Use hierarchical folder structure to compare
between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc.
for each new experiment to compare across them.
comment (string): Comment log_dir suffix appended to the default `log_dir`. If `log_dir` is assigned, this
argument has no effect.
purge_step (int): Note that crashed and resumed experiments should have the same ``log_dir``.
max_queue (int): Size of the queue for pending events and
summaries before one of the 'add' calls forces a flush to disk.
Default is ten items.
flush_secs (int): How often, in seconds, to flush the
pending events and summaries to disk. Default is every two minutes.
filename_suffix (string): Suffix added to all event filenames in
the log_dir directory. More details on filename construction in
tensorboard.summary.writer.event_file_writer.EventFileWriter.
"""
def __init__(self, log_dir=None, comment='', purge_step=None, max_queue=10,
flush_secs=120, filename_suffix=''):
if not log_dir:
import socket
from datetime import datetime
current_time = datetime.now().strftime('%b%d_%H-%M-%S')
log_dir = os.path.join(
'runs', current_time + '_' + socket.gethostname() + comment)
self.log_dir = log_dir
self.purge_step = purge_step
self.max_queue = max_queue
self.flush_secs = flush_secs
self.filename_suffix = filename_suffix
# Initialize the file writers, but they can be cleared out on close
# and recreated later as needed.
self.file_writer = self.all_writers = None
self._get_file_writer()
def _get_file_writer(self):
"""Returns the default FileWriter instance. Recreates it if closed."""
if self.all_writers is None or self.file_writer is None:
self.file_writer = FileWriter(self.log_dir, self.max_queue,
self.flush_secs, self.filename_suffix)
self.all_writers = {self.file_writer.get_logdir(): self.file_writer}
if self.purge_step is not None:
most_recent_step = self.purge_step
self.file_writer.add_event(
Event(step=most_recent_step, file_version='brain.Event:2'))
self.file_writer.add_event(
Event(step=most_recent_step, session_log=SessionLog(status=SessionLog.START)))
self.purge_step = None
return self.file_writer
def add_scalar(self, tag, scalar_value, global_step=None, walltime=None):
r"""Add a scalar value."""
scalar_value = float(scalar_value)
self._get_file_writer().add_summary(
Summary(value=[Summary.Value(tag=tag, simple_value=scalar_value)]),
global_step, walltime
)
def add_image(self, tag, img, global_step=None, walltime=None):
r"""Add an image."""
self._get_file_writer().add_summary(
Summary(value=[Summary.Value(tag=tag, image=img)])
)
def add_graph(self, model, *args, **kargs):
visitor = GraphVisitor(model, *args, **kargs)
stepstats = RunMetadata(step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")]))
graph = GraphDef(node=visitor._graph, versions=VersionDef(producer=22))
self._get_file_writer().add_graph((graph, stepstats))
def flush(self):
"""Flushes the event file to disk.
Call this method to make sure that all pending events have been written to
disk.
"""
if self.all_writers is None:
return
for writer in self.all_writers.values():
writer.flush()
def close(self):
if self.all_writers is None:
return # ignore double close
for writer in self.all_writers.values():
writer.flush()
writer.close()
self.file_writer = self.all_writers = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close() | 0.888221 | 0.265299 |
from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import re
from django.core.exceptions import (ImproperlyConfigured, ObjectDoesNotExist,
ValidationError as DjValidationError)
from django.core.validators import (slug_re, comma_separated_int_list_re,
MinLengthValidator, MaxLengthValidator)
from spyne.error import (ResourceNotFoundError, ValidationError as
BaseValidationError, Fault)
from spyne.model import primitive
from spyne.model.complex import ComplexModelMeta, ComplexModelBase
from spyne.service import ServiceBase
from spyne.util.cdict import cdict
from spyne.util.odict import odict
from spyne.util.six import add_metaclass
# regex is based on http://www.w3.org/TR/xforms20/#xforms:email
email_re = re.compile(
r"[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+"
r"(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*@"
r"[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+"
r"(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*", re.IGNORECASE)
def _handle_minlength(validator, params):
new_min = validator.limit_value
old_min = params.setdefault('min_len', new_min)
params['min_len'] = max(old_min, new_min)
def _handle_maxlength(validator, params):
new_max = validator.limit_value
old_max = params.setdefault('max_len', new_max)
params['max_len'] = min(old_max, new_max)
class BaseDjangoFieldMapper(object):
"""Abstrace base class for field mappers."""
_VALIDATOR_HANDLERS = cdict({
MinLengthValidator: _handle_minlength,
MaxLengthValidator: _handle_maxlength,
})
@staticmethod
def is_field_nullable(field, **kwargs):
"""Return True if django field is nullable."""
return field.null
@staticmethod
def is_field_blank(field, **kwargs):
"""Return True if django field is blank."""
return field.blank
def map(self, field, **kwargs):
"""Map field to spyne model.
:param field: Django Field instance
:param kwargs: Extra params to configure spyne model
:returns: tuple (field attribute name, mapped spyne model)
"""
params = kwargs.copy()
self._process_validators(field.validators, params)
nullable = self.is_field_nullable(field, **kwargs)
blank = self.is_field_blank(field, **kwargs)
required = not (field.has_default() or blank or field.primary_key)
if field.has_default():
params['default'] = field.get_default()
spyne_model = self.get_spyne_model(field, **kwargs)
customized_model = spyne_model(nullable=nullable,
min_occurs=int(required), **params)
return (field.attname, customized_model)
def get_spyne_model(self, field, **kwargs):
"""Return spyne model for given Django field."""
raise NotImplementedError
def _process_validators(self, validators, params):
for v in validators:
handler = self._VALIDATOR_HANDLERS.get(type(v))
if handler:
handler(v, params)
class DjangoFieldMapper(BaseDjangoFieldMapper):
"""Basic mapper for django fields."""
def __init__(self, spyne_model):
"""Django field mapper constructor."""
self.spyne_model = spyne_model
def get_spyne_model(self, field, **kwargs):
"""Return configured spyne model."""
return self.spyne_model
class DecimalMapper(DjangoFieldMapper):
"""Mapper for DecimalField."""
def map(self, field, **kwargs):
"""Map DecimalField to spyne model.
:returns: tuple (field attribute name, mapped spyne model)
"""
params = kwargs.copy()
params.update({
'total_digits': field.max_digits,
'fraction_digits': field.decimal_places,
})
return super(DecimalMapper, self).map(field, **params)
class RelationMapper(BaseDjangoFieldMapper):
"""Mapper for relation fields (ForeignKey, OneToOneField)."""
def __init__(self, django_model_mapper):
"""Constructor for relation field mapper."""
self.django_model_mapper = django_model_mapper
@staticmethod
def is_field_blank(field, **kwargs):
"""Return True if `optional_relations` is set.
Otherwise use basic behaviour.
"""
optional_relations = kwargs.get('optional_relations', False)
return (optional_relations or
BaseDjangoFieldMapper.is_field_blank(field, **kwargs))
def get_spyne_model(self, field, **kwargs):
"""Return spyne model configured by related field."""
related_field = field.rel.get_related_field()
field_type = related_field.__class__.__name__
field_mapper = self.django_model_mapper.get_field_mapper(field_type)
_, related_spyne_model = field_mapper.map(related_field, **kwargs)
return related_spyne_model
class DjangoModelMapper(object):
r"""Mapper from django models to spyne complex models.
You can extend it registering new field types: ::
class NullBooleanMapper(DjangoFieldMapper):
def map(self, field, **kwargs):
params = kwargs.copy()
# your mapping logic goes here
return super(NullBooleanMapper, self).map(field, **params)
default_model_mapper.register_field_mapper('NullBooleanField', \
NullBooleanMapper(primitive.Boolean))
You may subclass it if you want different mapping logic for different
Django models.
"""
field_mapper_class = DjangoFieldMapper
class UnknownFieldMapperException(Exception):
"""Raises when there is no field mapper for given django_type."""
def __init__(self, django_spyne_models=()):
"""Register field mappers in internal registry."""
self._registry = {}
for django_type, spyne_model in django_spyne_models:
self.register(django_type, spyne_model)
def get_field_mapper(self, django_type):
"""Get mapper registered for given django_type.
:param django_type: Django internal field type
:returns: registered mapper
:raises: :exc:`UnknownFieldMapperException`
"""
try:
return self._registry[django_type]
except KeyError:
raise self.UnknownFieldMapperException(
'No mapper for field type {0}'.format(django_type))
def register(self, django_type, spyne_model):
"""Register default field mapper for django_type and spyne_model.
:param django_type: Django internal field type
:param spyne_model: Spyne model, usually primitive
"""
field_mapper = self.field_mapper_class(spyne_model)
self.register_field_mapper(django_type, field_mapper)
def register_field_mapper(self, django_type, field_mapper):
"""Register field mapper for django_type.
:param django_type: Django internal field type
:param field_mapper: :class:`DjangoFieldMapper` instance
"""
self._registry[django_type] = field_mapper
@staticmethod
def _get_fields(django_model, exclude=None):
field_names = set(exclude) if exclude is not None else set()
meta = django_model._meta # pylint: disable=W0212
unknown_fields_names = field_names.difference(
meta.get_all_field_names())
if unknown_fields_names:
raise ImproperlyConfigured(
'Unknown field names: {0}'
.format(', '.join(unknown_fields_names)))
return [field for field in meta.fields if field.name not in
field_names]
def map(self, django_model, exclude=None, **kwargs):
"""Prepare dict of model fields mapped to spyne models.
:param django_model: Django model class.
:param exclude: list of fields excluded from mapping.
:param kwargs: extra kwargs are passed to all field mappers
:returns: dict mapping attribute names to spyne models
:raises: :exc:`UnknownFieldMapperException`
"""
field_map = odict()
for field in self._get_fields(django_model, exclude):
field_type = field.__class__.__name__
try:
field_mapper = self._registry[field_type]
except KeyError:
# mapper for this field is not registered
if not (field.has_default() or field.null):
# field is required
raise self.UnknownFieldMapperException(
'No mapper for field type {0}'.format(field_type))
else:
# skip this field
logger.info('Field {0} is skipped from mapping.')
continue
attr_name, spyne_model = field_mapper.map(field, **kwargs)
field_map[attr_name] = spyne_model
return field_map
def strip_regex_metachars(pattern):
"""Strip ^ and $ from pattern begining and end.
According to http://www.w3.org/TR/xmlschema-0/#regexAppendix XMLSchema
expression language does not contain the metacharacters ^ and $.
:returns: stripped pattern string
"""
start = 0
till = len(pattern)
if pattern.startswith('^'):
start = 1
if pattern.endswith('$'):
till -= 1
return pattern[start:till]
DEFAULT_FIELD_MAP = (
('AutoField', primitive.Integer32),
('CharField', primitive.NormalizedString),
('SlugField', primitive.Unicode(
type_name='Slug', pattern=strip_regex_metachars(slug_re.pattern))),
('TextField', primitive.Unicode),
('EmailField', primitive.Unicode(
type_name='Email', pattern=strip_regex_metachars(email_re.pattern))),
('CommaSeparatedIntegerField', primitive.Unicode(
type_name='CommaSeparatedField',
pattern=strip_regex_metachars(comma_separated_int_list_re.pattern))),
('URLField', primitive.AnyUri),
('FilePathField', primitive.Unicode),
('BooleanField', primitive.Boolean),
('NullBooleanField', primitive.Boolean),
('IntegerField', primitive.Integer),
('BigIntegerField', primitive.Integer64),
('PositiveIntegerField', primitive.UnsignedInteger32),
('SmallIntegerField', primitive.Integer16),
('PositiveSmallIntegerField', primitive.UnsignedInteger16),
('FloatField', primitive.Double),
('TimeField', primitive.Time),
('DateField', primitive.Date),
('DateTimeField', primitive.DateTime),
# simple fixed defaults for relation fields
('ForeignKey', primitive.Integer32),
('OneToOneField', primitive.Integer32),
)
def model_mapper_factory(mapper_class, field_map):
"""Factory for model mappers.
The factory is useful to create custom field mappers based on default one.
"""
model_mapper = mapper_class(field_map)
# register relation field mappers that are aware of related field type
model_mapper.register_field_mapper(
'ForeignKey', RelationMapper(model_mapper))
model_mapper.register_field_mapper(
'OneToOneField', RelationMapper(model_mapper))
model_mapper.register_field_mapper('DecimalField',
DecimalMapper(primitive.Decimal))
return model_mapper
default_model_mapper = model_mapper_factory(DjangoModelMapper,
DEFAULT_FIELD_MAP)
class DjangoComplexModelMeta(ComplexModelMeta):
"""Meta class for complex spyne models representing Django models."""
def __new__(mcs, name, bases, attrs): # pylint: disable=C0202
"""Populate new complex type from configured Django model."""
super_new = super(DjangoComplexModelMeta, mcs).__new__
abstract = bool(attrs.get('__abstract__', False))
if abstract:
# skip processing of abstract models
return super_new(mcs, name, bases, attrs)
attributes = attrs.get('Attributes')
if attributes is None:
raise ImproperlyConfigured('You have to define Attributes and '
'specify Attributes.django_model')
if getattr(attributes, 'django_model', None) is None:
raise ImproperlyConfigured('You have to define django_model '
'attribute in Attributes')
mapper = getattr(attributes, 'django_mapper', default_model_mapper)
attributes.django_mapper = mapper
exclude = getattr(attributes, 'django_exclude', None)
optional_relations = getattr(attributes, 'django_optional_relations',
False)
spyne_attrs = mapper.map(attributes.django_model, exclude=exclude,
optional_relations=optional_relations)
spyne_attrs.update(attrs)
return super_new(mcs, name, bases, spyne_attrs)
@add_metaclass(DjangoComplexModelMeta)
class DjangoComplexModel(ComplexModelBase):
"""Base class with Django model mapping support.
Sample usage: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
Attribute :attr:`django_model` is required for Django model mapping
machinery. You can customize your types defining custom type fields: ::
class PersonType(DjangoComplexModel):
gender = primitive.Unicode(pattern='^[FM]$')
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
There is an option to specify custom mapper: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
django_mapper = my_custom_mapper
You can also exclude some fields from mapping: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
django_exclude = ['phone']
You may set `django_optional_relations`` attribute flag to indicate
that relation fields (ForeignKey, OneToOneField) of your model are
optional. This is useful when you want to create base and related
instances in remote procedure. In this case primary key of base model is
not yet available.
"""
__abstract__ = True
class ObjectNotFoundError(ResourceNotFoundError):
"""Fault constructed from `model.DoesNotExist` exception."""
def __init__(self, does_not_exist_exc):
"""Construct fault with code Client.<object_name>NotFound."""
message = str(does_not_exist_exc)
object_name = message.split()[0]
# we do not want to reuse initialization of ResourceNotFoundError
Fault.__init__(
self, faultcode='Client.{0}NotFound'.format(object_name),
faultstring=message)
class ValidationError(BaseValidationError):
"""Fault constructed from `ValidationError` exception."""
def __init__(self, validation_error_exc):
"""Construct fault with code Client.<validation_error_type_name>."""
message = str(validation_error_exc)
# we do not want to reuse initialization of BaseValidationError
Fault.__init__(
self, faultcode='Client.{0}'.format(
type(validation_error_exc).__name__), faultstring=message)
class DjangoServiceBase(ServiceBase):
"""Service with common Django exception handling."""
@classmethod
def call_wrapper(cls, ctx):
"""Handle common Django exceptions."""
try:
out_object = super(DjangoServiceBase, cls).call_wrapper(ctx)
except ObjectDoesNotExist as e:
raise ObjectNotFoundError(e)
except DjValidationError as e:
raise ValidationError(e)
return out_object | spyne/util/django.py | from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import re
from django.core.exceptions import (ImproperlyConfigured, ObjectDoesNotExist,
ValidationError as DjValidationError)
from django.core.validators import (slug_re, comma_separated_int_list_re,
MinLengthValidator, MaxLengthValidator)
from spyne.error import (ResourceNotFoundError, ValidationError as
BaseValidationError, Fault)
from spyne.model import primitive
from spyne.model.complex import ComplexModelMeta, ComplexModelBase
from spyne.service import ServiceBase
from spyne.util.cdict import cdict
from spyne.util.odict import odict
from spyne.util.six import add_metaclass
# regex is based on http://www.w3.org/TR/xforms20/#xforms:email
email_re = re.compile(
r"[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+"
r"(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*@"
r"[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+"
r"(\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*", re.IGNORECASE)
def _handle_minlength(validator, params):
new_min = validator.limit_value
old_min = params.setdefault('min_len', new_min)
params['min_len'] = max(old_min, new_min)
def _handle_maxlength(validator, params):
new_max = validator.limit_value
old_max = params.setdefault('max_len', new_max)
params['max_len'] = min(old_max, new_max)
class BaseDjangoFieldMapper(object):
"""Abstrace base class for field mappers."""
_VALIDATOR_HANDLERS = cdict({
MinLengthValidator: _handle_minlength,
MaxLengthValidator: _handle_maxlength,
})
@staticmethod
def is_field_nullable(field, **kwargs):
"""Return True if django field is nullable."""
return field.null
@staticmethod
def is_field_blank(field, **kwargs):
"""Return True if django field is blank."""
return field.blank
def map(self, field, **kwargs):
"""Map field to spyne model.
:param field: Django Field instance
:param kwargs: Extra params to configure spyne model
:returns: tuple (field attribute name, mapped spyne model)
"""
params = kwargs.copy()
self._process_validators(field.validators, params)
nullable = self.is_field_nullable(field, **kwargs)
blank = self.is_field_blank(field, **kwargs)
required = not (field.has_default() or blank or field.primary_key)
if field.has_default():
params['default'] = field.get_default()
spyne_model = self.get_spyne_model(field, **kwargs)
customized_model = spyne_model(nullable=nullable,
min_occurs=int(required), **params)
return (field.attname, customized_model)
def get_spyne_model(self, field, **kwargs):
"""Return spyne model for given Django field."""
raise NotImplementedError
def _process_validators(self, validators, params):
for v in validators:
handler = self._VALIDATOR_HANDLERS.get(type(v))
if handler:
handler(v, params)
class DjangoFieldMapper(BaseDjangoFieldMapper):
"""Basic mapper for django fields."""
def __init__(self, spyne_model):
"""Django field mapper constructor."""
self.spyne_model = spyne_model
def get_spyne_model(self, field, **kwargs):
"""Return configured spyne model."""
return self.spyne_model
class DecimalMapper(DjangoFieldMapper):
"""Mapper for DecimalField."""
def map(self, field, **kwargs):
"""Map DecimalField to spyne model.
:returns: tuple (field attribute name, mapped spyne model)
"""
params = kwargs.copy()
params.update({
'total_digits': field.max_digits,
'fraction_digits': field.decimal_places,
})
return super(DecimalMapper, self).map(field, **params)
class RelationMapper(BaseDjangoFieldMapper):
"""Mapper for relation fields (ForeignKey, OneToOneField)."""
def __init__(self, django_model_mapper):
"""Constructor for relation field mapper."""
self.django_model_mapper = django_model_mapper
@staticmethod
def is_field_blank(field, **kwargs):
"""Return True if `optional_relations` is set.
Otherwise use basic behaviour.
"""
optional_relations = kwargs.get('optional_relations', False)
return (optional_relations or
BaseDjangoFieldMapper.is_field_blank(field, **kwargs))
def get_spyne_model(self, field, **kwargs):
"""Return spyne model configured by related field."""
related_field = field.rel.get_related_field()
field_type = related_field.__class__.__name__
field_mapper = self.django_model_mapper.get_field_mapper(field_type)
_, related_spyne_model = field_mapper.map(related_field, **kwargs)
return related_spyne_model
class DjangoModelMapper(object):
r"""Mapper from django models to spyne complex models.
You can extend it registering new field types: ::
class NullBooleanMapper(DjangoFieldMapper):
def map(self, field, **kwargs):
params = kwargs.copy()
# your mapping logic goes here
return super(NullBooleanMapper, self).map(field, **params)
default_model_mapper.register_field_mapper('NullBooleanField', \
NullBooleanMapper(primitive.Boolean))
You may subclass it if you want different mapping logic for different
Django models.
"""
field_mapper_class = DjangoFieldMapper
class UnknownFieldMapperException(Exception):
"""Raises when there is no field mapper for given django_type."""
def __init__(self, django_spyne_models=()):
"""Register field mappers in internal registry."""
self._registry = {}
for django_type, spyne_model in django_spyne_models:
self.register(django_type, spyne_model)
def get_field_mapper(self, django_type):
"""Get mapper registered for given django_type.
:param django_type: Django internal field type
:returns: registered mapper
:raises: :exc:`UnknownFieldMapperException`
"""
try:
return self._registry[django_type]
except KeyError:
raise self.UnknownFieldMapperException(
'No mapper for field type {0}'.format(django_type))
def register(self, django_type, spyne_model):
"""Register default field mapper for django_type and spyne_model.
:param django_type: Django internal field type
:param spyne_model: Spyne model, usually primitive
"""
field_mapper = self.field_mapper_class(spyne_model)
self.register_field_mapper(django_type, field_mapper)
def register_field_mapper(self, django_type, field_mapper):
"""Register field mapper for django_type.
:param django_type: Django internal field type
:param field_mapper: :class:`DjangoFieldMapper` instance
"""
self._registry[django_type] = field_mapper
@staticmethod
def _get_fields(django_model, exclude=None):
field_names = set(exclude) if exclude is not None else set()
meta = django_model._meta # pylint: disable=W0212
unknown_fields_names = field_names.difference(
meta.get_all_field_names())
if unknown_fields_names:
raise ImproperlyConfigured(
'Unknown field names: {0}'
.format(', '.join(unknown_fields_names)))
return [field for field in meta.fields if field.name not in
field_names]
def map(self, django_model, exclude=None, **kwargs):
"""Prepare dict of model fields mapped to spyne models.
:param django_model: Django model class.
:param exclude: list of fields excluded from mapping.
:param kwargs: extra kwargs are passed to all field mappers
:returns: dict mapping attribute names to spyne models
:raises: :exc:`UnknownFieldMapperException`
"""
field_map = odict()
for field in self._get_fields(django_model, exclude):
field_type = field.__class__.__name__
try:
field_mapper = self._registry[field_type]
except KeyError:
# mapper for this field is not registered
if not (field.has_default() or field.null):
# field is required
raise self.UnknownFieldMapperException(
'No mapper for field type {0}'.format(field_type))
else:
# skip this field
logger.info('Field {0} is skipped from mapping.')
continue
attr_name, spyne_model = field_mapper.map(field, **kwargs)
field_map[attr_name] = spyne_model
return field_map
def strip_regex_metachars(pattern):
"""Strip ^ and $ from pattern begining and end.
According to http://www.w3.org/TR/xmlschema-0/#regexAppendix XMLSchema
expression language does not contain the metacharacters ^ and $.
:returns: stripped pattern string
"""
start = 0
till = len(pattern)
if pattern.startswith('^'):
start = 1
if pattern.endswith('$'):
till -= 1
return pattern[start:till]
DEFAULT_FIELD_MAP = (
('AutoField', primitive.Integer32),
('CharField', primitive.NormalizedString),
('SlugField', primitive.Unicode(
type_name='Slug', pattern=strip_regex_metachars(slug_re.pattern))),
('TextField', primitive.Unicode),
('EmailField', primitive.Unicode(
type_name='Email', pattern=strip_regex_metachars(email_re.pattern))),
('CommaSeparatedIntegerField', primitive.Unicode(
type_name='CommaSeparatedField',
pattern=strip_regex_metachars(comma_separated_int_list_re.pattern))),
('URLField', primitive.AnyUri),
('FilePathField', primitive.Unicode),
('BooleanField', primitive.Boolean),
('NullBooleanField', primitive.Boolean),
('IntegerField', primitive.Integer),
('BigIntegerField', primitive.Integer64),
('PositiveIntegerField', primitive.UnsignedInteger32),
('SmallIntegerField', primitive.Integer16),
('PositiveSmallIntegerField', primitive.UnsignedInteger16),
('FloatField', primitive.Double),
('TimeField', primitive.Time),
('DateField', primitive.Date),
('DateTimeField', primitive.DateTime),
# simple fixed defaults for relation fields
('ForeignKey', primitive.Integer32),
('OneToOneField', primitive.Integer32),
)
def model_mapper_factory(mapper_class, field_map):
"""Factory for model mappers.
The factory is useful to create custom field mappers based on default one.
"""
model_mapper = mapper_class(field_map)
# register relation field mappers that are aware of related field type
model_mapper.register_field_mapper(
'ForeignKey', RelationMapper(model_mapper))
model_mapper.register_field_mapper(
'OneToOneField', RelationMapper(model_mapper))
model_mapper.register_field_mapper('DecimalField',
DecimalMapper(primitive.Decimal))
return model_mapper
default_model_mapper = model_mapper_factory(DjangoModelMapper,
DEFAULT_FIELD_MAP)
class DjangoComplexModelMeta(ComplexModelMeta):
"""Meta class for complex spyne models representing Django models."""
def __new__(mcs, name, bases, attrs): # pylint: disable=C0202
"""Populate new complex type from configured Django model."""
super_new = super(DjangoComplexModelMeta, mcs).__new__
abstract = bool(attrs.get('__abstract__', False))
if abstract:
# skip processing of abstract models
return super_new(mcs, name, bases, attrs)
attributes = attrs.get('Attributes')
if attributes is None:
raise ImproperlyConfigured('You have to define Attributes and '
'specify Attributes.django_model')
if getattr(attributes, 'django_model', None) is None:
raise ImproperlyConfigured('You have to define django_model '
'attribute in Attributes')
mapper = getattr(attributes, 'django_mapper', default_model_mapper)
attributes.django_mapper = mapper
exclude = getattr(attributes, 'django_exclude', None)
optional_relations = getattr(attributes, 'django_optional_relations',
False)
spyne_attrs = mapper.map(attributes.django_model, exclude=exclude,
optional_relations=optional_relations)
spyne_attrs.update(attrs)
return super_new(mcs, name, bases, spyne_attrs)
@add_metaclass(DjangoComplexModelMeta)
class DjangoComplexModel(ComplexModelBase):
"""Base class with Django model mapping support.
Sample usage: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
Attribute :attr:`django_model` is required for Django model mapping
machinery. You can customize your types defining custom type fields: ::
class PersonType(DjangoComplexModel):
gender = primitive.Unicode(pattern='^[FM]$')
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
There is an option to specify custom mapper: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
django_mapper = my_custom_mapper
You can also exclude some fields from mapping: ::
class PersonType(DjangoComplexModel):
class Attributes(DjangoComplexModel.Attributes):
django_model = Person
django_exclude = ['phone']
You may set `django_optional_relations`` attribute flag to indicate
that relation fields (ForeignKey, OneToOneField) of your model are
optional. This is useful when you want to create base and related
instances in remote procedure. In this case primary key of base model is
not yet available.
"""
__abstract__ = True
class ObjectNotFoundError(ResourceNotFoundError):
"""Fault constructed from `model.DoesNotExist` exception."""
def __init__(self, does_not_exist_exc):
"""Construct fault with code Client.<object_name>NotFound."""
message = str(does_not_exist_exc)
object_name = message.split()[0]
# we do not want to reuse initialization of ResourceNotFoundError
Fault.__init__(
self, faultcode='Client.{0}NotFound'.format(object_name),
faultstring=message)
class ValidationError(BaseValidationError):
"""Fault constructed from `ValidationError` exception."""
def __init__(self, validation_error_exc):
"""Construct fault with code Client.<validation_error_type_name>."""
message = str(validation_error_exc)
# we do not want to reuse initialization of BaseValidationError
Fault.__init__(
self, faultcode='Client.{0}'.format(
type(validation_error_exc).__name__), faultstring=message)
class DjangoServiceBase(ServiceBase):
"""Service with common Django exception handling."""
@classmethod
def call_wrapper(cls, ctx):
"""Handle common Django exceptions."""
try:
out_object = super(DjangoServiceBase, cls).call_wrapper(ctx)
except ObjectDoesNotExist as e:
raise ObjectNotFoundError(e)
except DjValidationError as e:
raise ValidationError(e)
return out_object | 0.761627 | 0.102844 |
import datetime
import click
import psycopg2
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server.TServer import TThreadPoolServer
from gen_auth.auth import TAuthService
from gen_auth.auth.ttypes import TAccount, TInvalidCredentialsException
class Handler:
def __init__(self, db_host):
self._db_host = db_host
def sign_up(self, username, password, first_name, last_name):
conn = psycopg2.connect("dbname='{dbname}' host='{host}'".format(
dbname="microblog_bench", host=self._db_host))
cursor = conn.cursor()
now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
cursor.execute("""
INSERT INTO Accounts (username, password, first_name, last_name,
created_at)
VALUES ('{username}', '{password}', '{first_name}', '{last_name}',
'{now}')
RETURNING id
""".format(username=username, password=password, first_name=first_name,
last_name=last_name, now=now))
account_id = cursor.fetchone()[0]
conn.commit()
conn.close()
return TAccount(id=account_id, username=username, first_name=first_name,
last_name=last_name, created_at=now)
def sign_in(self, username, password):
conn = psycopg2.connect("dbname='{dbname}' host='{host}'".format(
dbname="microblog_bench", host=self._db_host))
cursor = conn.cursor()
cursor.execute("""
SELECT id, password, first_name, last_name, created_at
FROM Accounts
WHERE username = '{username}'
""".format(username=username))
row = cursor.fetchone()
conn.commit()
conn.close()
if row is None:
raise TInvalidCredentialsException()
account_id, password_, first_name, last_name, created_at = row
if password != password_:
raise TInvalidCredentialsException()
return TAccount(id=account_id, username=username, first_name=first_name,
last_name=last_name, created_at=created_at)
class Server:
def __init__(self, ip_address, port, thread_pool_size, db_host):
self._ip_address = ip_address
self._port = port
self._thread_pool_size = thread_pool_size
self._db_host = db_host
def serve(self):
handler = Handler(self._db_host)
processor = TAuthService.Processor(handler)
transport = TSocket.TServerSocket(host=self._ip_address, port=self._port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
tserver = TThreadPoolServer(processor, transport, tfactory, pfactory)
tserver.setNumThreads(self._thread_pool_size)
tserver.serve()
@click.command()
@click.option("--ip_address", prompt="IP Address")
@click.option("--port", prompt="Port")
@click.option("--thread_pool_size", prompt="Thread pool size", type=click.INT)
@click.option("--db_host", prompt="PostgreSQL host")
def main(ip_address, port, thread_pool_size, db_host):
server = Server(ip_address, port, thread_pool_size, db_host)
server.serve()
if __name__ == "__main__":
main() | WISEServices/auth/src/py/server.py | import datetime
import click
import psycopg2
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server.TServer import TThreadPoolServer
from gen_auth.auth import TAuthService
from gen_auth.auth.ttypes import TAccount, TInvalidCredentialsException
class Handler:
def __init__(self, db_host):
self._db_host = db_host
def sign_up(self, username, password, first_name, last_name):
conn = psycopg2.connect("dbname='{dbname}' host='{host}'".format(
dbname="microblog_bench", host=self._db_host))
cursor = conn.cursor()
now = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
cursor.execute("""
INSERT INTO Accounts (username, password, first_name, last_name,
created_at)
VALUES ('{username}', '{password}', '{first_name}', '{last_name}',
'{now}')
RETURNING id
""".format(username=username, password=password, first_name=first_name,
last_name=last_name, now=now))
account_id = cursor.fetchone()[0]
conn.commit()
conn.close()
return TAccount(id=account_id, username=username, first_name=first_name,
last_name=last_name, created_at=now)
def sign_in(self, username, password):
conn = psycopg2.connect("dbname='{dbname}' host='{host}'".format(
dbname="microblog_bench", host=self._db_host))
cursor = conn.cursor()
cursor.execute("""
SELECT id, password, first_name, last_name, created_at
FROM Accounts
WHERE username = '{username}'
""".format(username=username))
row = cursor.fetchone()
conn.commit()
conn.close()
if row is None:
raise TInvalidCredentialsException()
account_id, password_, first_name, last_name, created_at = row
if password != password_:
raise TInvalidCredentialsException()
return TAccount(id=account_id, username=username, first_name=first_name,
last_name=last_name, created_at=created_at)
class Server:
def __init__(self, ip_address, port, thread_pool_size, db_host):
self._ip_address = ip_address
self._port = port
self._thread_pool_size = thread_pool_size
self._db_host = db_host
def serve(self):
handler = Handler(self._db_host)
processor = TAuthService.Processor(handler)
transport = TSocket.TServerSocket(host=self._ip_address, port=self._port)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
tserver = TThreadPoolServer(processor, transport, tfactory, pfactory)
tserver.setNumThreads(self._thread_pool_size)
tserver.serve()
@click.command()
@click.option("--ip_address", prompt="IP Address")
@click.option("--port", prompt="Port")
@click.option("--thread_pool_size", prompt="Thread pool size", type=click.INT)
@click.option("--db_host", prompt="PostgreSQL host")
def main(ip_address, port, thread_pool_size, db_host):
server = Server(ip_address, port, thread_pool_size, db_host)
server.serve()
if __name__ == "__main__":
main() | 0.384797 | 0.058453 |
import argparse
import signal
import os
import sys
import time
import pyinotify
import requests
import base64
import json
import fnmatch
import time
def now():
return(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
def signalHandler(signum, frame):
print "%s : sprinkler.py receive signal %d" % (now(), signum)
print "%s : Stop watching %s" % (now(), args.Incoming_directory)
wm.rm_watch(wdd.values())
notifier.stop()
sys.exit()
def duplicate_file(str):
for pattern in Exclude:
if fnmatch.fnmatch(str, pattern):
return
for dir in args.Outcoming_directories:
if dir != 'Trash':
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : Duplicate %s to %s/%s" % (now(), str, dir,
os.path.basename(str))
os.link(str, "%s/%s" % (dir, os.path.basename(str)))
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : Unlink %s" % (now(), str)
os.unlink(str)
parser = argparse.ArgumentParser(
"Duplicate one incoming directory in several outcoming directories")
parser.add_argument('Incoming_directory', type=str, help='Incoming directory')
parser.add_argument('Consul_index_md5', type=str, help='Consul md5 index')
parser.add_argument('Outcoming_directories', type=str, nargs='+',
help='Outcoming directories')
args = parser.parse_args()
signal.signal(signal.SIGTERM, signalHandler)
signal.signal(signal.SIGHUP, signalHandler)
signal.signal(signal.SIGINT, signalHandler)
# Parametres
Max_Age = int(os.environ.get("DUPLICATORFTP_WATCHER_MAX_AGE"))
Log_Level = os.environ.get("DUPLICATORFTP_LOG_LEVEL")
Consul = os.environ.get("DUPLICATORFTP_CONSUL")
# Url pour requeter consul (fichier settings de la voie)
url = "http://%s/v1/kv/ftp_duplicator/incoming_directories/%s/settings" \
% (Consul, os.path.basename(args.Incoming_directory))
reply = requests.get(url)
if reply.status_code != 200:
print "%s : Error : Consul return code %d" % (now(), reply.status_code)
result = reply.json()
settings = json.loads(base64.b64decode(result[0]['Value']))
Exclude = settings['exclude']
# Creation eventuelle des repertoires output
for dir in args.Outcoming_directories:
if dir != 'Trash' and not os.path.isdir(dir):
print "%s : Directory %s created" % (now(), dir)
os.mkdir(dir)
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO | \
pyinotify.IN_MOVE_SELF | pyinotify.IN_DELETE_SELF
class Monitor(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : File %s created" % (now(), event.pathname)
duplicate_file(event.pathname)
def process_IN_MOVED_TO(self, event):
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : File move to: %s" % (now(), event.pathname)
duplicate_file(event.pathname)
def process_IN_MOVE_SELF(self, event):
print "%s : Directory: %s moved" % (now(), event.pathname)
print "%s : Stop watching %s" % (now(), args.Incoming_directory)
wm.rm_watch(args.Incoming_directory)
notifier.stop()
def process_IN_DELETE_SELF(self, event):
print "%s : Directory: %s removed" % (now(), event.pathname)
notifier = pyinotify.Notifier(wm, Monitor(), timeout=1000) #timeout de 1000ms sur le check-events()
wdd = wm.add_watch(args.Incoming_directory, mask)
print "%s : Start watching %s" % (now(), args.Incoming_directory)
# Recuperation des fichiers presents sur le repertoire a surveiller
list_files = os.listdir(args.Incoming_directory)
for file in list_files:
file_path = "%s/%s" % (args.Incoming_directory, file)
age = int(time.time() - os.stat(file_path).st_mtime)
if age > Max_Age:
# Fichier trop vieux : on le supprime
print "%s : File %s : abort transfer and remove" % (now(), file)
os.unlink(file_path)
else:
# On genere un evenement IN_MOVE par un double deplacement
os.rename(file_path, "/data/tmp/%s" % file)
os.rename("/data/tmp/%s" % file, file_path)
while True:
try:
# process the queue of events as explained above
notifier.process_events()
if notifier.check_events():
# read notified events and enqeue them
notifier.read_events()
# you can do some tasks here...
except KeyboardInterrupt:
# destroy the inotify's instance on this interrupt (stop monitoring)
notifier.stop()
break | root/usr/local/bin/sprinkler.py | import argparse
import signal
import os
import sys
import time
import pyinotify
import requests
import base64
import json
import fnmatch
import time
def now():
return(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
def signalHandler(signum, frame):
print "%s : sprinkler.py receive signal %d" % (now(), signum)
print "%s : Stop watching %s" % (now(), args.Incoming_directory)
wm.rm_watch(wdd.values())
notifier.stop()
sys.exit()
def duplicate_file(str):
for pattern in Exclude:
if fnmatch.fnmatch(str, pattern):
return
for dir in args.Outcoming_directories:
if dir != 'Trash':
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : Duplicate %s to %s/%s" % (now(), str, dir,
os.path.basename(str))
os.link(str, "%s/%s" % (dir, os.path.basename(str)))
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : Unlink %s" % (now(), str)
os.unlink(str)
parser = argparse.ArgumentParser(
"Duplicate one incoming directory in several outcoming directories")
parser.add_argument('Incoming_directory', type=str, help='Incoming directory')
parser.add_argument('Consul_index_md5', type=str, help='Consul md5 index')
parser.add_argument('Outcoming_directories', type=str, nargs='+',
help='Outcoming directories')
args = parser.parse_args()
signal.signal(signal.SIGTERM, signalHandler)
signal.signal(signal.SIGHUP, signalHandler)
signal.signal(signal.SIGINT, signalHandler)
# Parametres
Max_Age = int(os.environ.get("DUPLICATORFTP_WATCHER_MAX_AGE"))
Log_Level = os.environ.get("DUPLICATORFTP_LOG_LEVEL")
Consul = os.environ.get("DUPLICATORFTP_CONSUL")
# Url pour requeter consul (fichier settings de la voie)
url = "http://%s/v1/kv/ftp_duplicator/incoming_directories/%s/settings" \
% (Consul, os.path.basename(args.Incoming_directory))
reply = requests.get(url)
if reply.status_code != 200:
print "%s : Error : Consul return code %d" % (now(), reply.status_code)
result = reply.json()
settings = json.loads(base64.b64decode(result[0]['Value']))
Exclude = settings['exclude']
# Creation eventuelle des repertoires output
for dir in args.Outcoming_directories:
if dir != 'Trash' and not os.path.isdir(dir):
print "%s : Directory %s created" % (now(), dir)
os.mkdir(dir)
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO | \
pyinotify.IN_MOVE_SELF | pyinotify.IN_DELETE_SELF
class Monitor(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : File %s created" % (now(), event.pathname)
duplicate_file(event.pathname)
def process_IN_MOVED_TO(self, event):
if Log_Level == 'verbose' or Log_Level =='debug':
print "%s : File move to: %s" % (now(), event.pathname)
duplicate_file(event.pathname)
def process_IN_MOVE_SELF(self, event):
print "%s : Directory: %s moved" % (now(), event.pathname)
print "%s : Stop watching %s" % (now(), args.Incoming_directory)
wm.rm_watch(args.Incoming_directory)
notifier.stop()
def process_IN_DELETE_SELF(self, event):
print "%s : Directory: %s removed" % (now(), event.pathname)
notifier = pyinotify.Notifier(wm, Monitor(), timeout=1000) #timeout de 1000ms sur le check-events()
wdd = wm.add_watch(args.Incoming_directory, mask)
print "%s : Start watching %s" % (now(), args.Incoming_directory)
# Recuperation des fichiers presents sur le repertoire a surveiller
list_files = os.listdir(args.Incoming_directory)
for file in list_files:
file_path = "%s/%s" % (args.Incoming_directory, file)
age = int(time.time() - os.stat(file_path).st_mtime)
if age > Max_Age:
# Fichier trop vieux : on le supprime
print "%s : File %s : abort transfer and remove" % (now(), file)
os.unlink(file_path)
else:
# On genere un evenement IN_MOVE par un double deplacement
os.rename(file_path, "/data/tmp/%s" % file)
os.rename("/data/tmp/%s" % file, file_path)
while True:
try:
# process the queue of events as explained above
notifier.process_events()
if notifier.check_events():
# read notified events and enqeue them
notifier.read_events()
# you can do some tasks here...
except KeyboardInterrupt:
# destroy the inotify's instance on this interrupt (stop monitoring)
notifier.stop()
break | 0.115923 | 0.075142 |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
for line in open("qimage2ndarray/__init__.py"):
if line.startswith("__version__"):
exec(line)
setup(name = 'qimage2ndarray',
version = __version__,
description = 'Conversion between QImages and numpy.ndarrays.',
author = "<NAME>",
author_email = "<EMAIL>",
url = "https://github.com/hmeine/qimage2ndarray",
download_url = "https://github.com/hmeine/qimage2ndarray/releases",
keywords = ["QImage", "numpy", "ndarray", "image", "convert", "PyQt4", "PyQt5", "PySide"],
install_requires = ['numpy'],
extras_require = dict(PyQt4 = 'PyQt4',
PyQt5 = 'PyQt5',
PySide = 'PySide',
PySide2 = 'PySide2'),
tests_require = 'nose',
packages = ['qimage2ndarray'],
long_description = """\
qimage2ndarray is a small python extension for quickly converting
between QImages and numpy.ndarrays (in both directions). These are
very common tasks when programming e.g. scientific visualizations in
Python using PyQt4 as the GUI library.
* Supports conversion of scalar and RGB data, with arbitrary dtypes
and memory layout, with and without alpha channels, into QImages
(e.g. for display or saving using Qt).
* qimage2ndarray makes it possible to create ndarrays that are
*views* into a given QImage's memory.
This allows for very efficient data handling and makes it possible
to modify Qt image data in-place (e.g. for brightness/gamma or alpha
mask modifications).
* Masked arrays are also supported and are converted into QImages
with transparent pixels.
* Supports recarrays (and comes with an appropriate dtype) for
convenient access to RGB(A) channels.
* Supports value scaling / normalization to 0..255 for convenient
display of arbitrary NumPy arrays.
* qimage2ndarray is stable and unit-tested.
""",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Topic :: Multimedia :: Graphics",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
]
) | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
for line in open("qimage2ndarray/__init__.py"):
if line.startswith("__version__"):
exec(line)
setup(name = 'qimage2ndarray',
version = __version__,
description = 'Conversion between QImages and numpy.ndarrays.',
author = "<NAME>",
author_email = "<EMAIL>",
url = "https://github.com/hmeine/qimage2ndarray",
download_url = "https://github.com/hmeine/qimage2ndarray/releases",
keywords = ["QImage", "numpy", "ndarray", "image", "convert", "PyQt4", "PyQt5", "PySide"],
install_requires = ['numpy'],
extras_require = dict(PyQt4 = 'PyQt4',
PyQt5 = 'PyQt5',
PySide = 'PySide',
PySide2 = 'PySide2'),
tests_require = 'nose',
packages = ['qimage2ndarray'],
long_description = """\
qimage2ndarray is a small python extension for quickly converting
between QImages and numpy.ndarrays (in both directions). These are
very common tasks when programming e.g. scientific visualizations in
Python using PyQt4 as the GUI library.
* Supports conversion of scalar and RGB data, with arbitrary dtypes
and memory layout, with and without alpha channels, into QImages
(e.g. for display or saving using Qt).
* qimage2ndarray makes it possible to create ndarrays that are
*views* into a given QImage's memory.
This allows for very efficient data handling and makes it possible
to modify Qt image data in-place (e.g. for brightness/gamma or alpha
mask modifications).
* Masked arrays are also supported and are converted into QImages
with transparent pixels.
* Supports recarrays (and comes with an appropriate dtype) for
convenient access to RGB(A) channels.
* Supports value scaling / normalization to 0..255 for convenient
display of arbitrary NumPy arrays.
* qimage2ndarray is stable and unit-tested.
""",
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Topic :: Multimedia :: Graphics",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: User Interfaces",
]
) | 0.626353 | 0.386879 |
import os
import random
from collections import deque
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
from sklearn.metrics import f1_score, precision_recall_curve
import matplotlib.pyplot as plt
import glob
from tqdm import tqdm
from utilities.feature_extractor import FeatureExtractor, convert_time
BATCH_SIZE = 16
VAL_SIZE = 0.15
EPOCHS = 50
PATIENCE = 5
LR_RATE = 0.0005
class TypeDataset(Dataset):
def __init__(self, file):
self.extractor = FeatureExtractor()
ground, data, comboground = self.extractor.extract_types(file)
self.x = torch.from_numpy(np.array(data))
self.y = torch.from_numpy(np.array(ground))
self.z = torch.from_numpy(np.array(comboground))
self.samples = self.x.shape[0]
def __getitem__(self, index):
return self.x[index].float(), self.y[index].long(), self.z[index].float()
def __len__(self):
return self.samples
class LstmClustering(nn.Module):
def __init__(self):
super().__init__()
self.lstm1 = nn.LSTM(input_size=13, hidden_size=128, batch_first=True, num_layers=2)
self.lin = nn.Linear(3*128, 128)
self.out = nn.Linear(128, 3)
self.clu = nn.Linear(3*128, 256)
self.clu2 = nn.Linear(256, 128)
self.cluout = nn.Linear(128, 1)
self.sig = nn.Sigmoid()
self.soft = nn.Softmax(dim=1)
def forward(self, x, h_t=None, c_t=None):
if h_t is None or c_t is None:
x, (h_n, c_n) = self.lstm1(x)
else:
x, (h_n, c_n) = self.lstm1(x, (h_t, c_t))
x = F.relu(x)
lstmout = torch.flatten(x, start_dim=1)
x1 = F.dropout(F.relu(self.lin(lstmout)), training=self.training)
x1 = self.out(x1)
x2 = F.dropout(F.relu(self.clu(lstmout)), training=self.training)
x2 = self.cluout(F.relu(self.clu2(x2)))
if not self.training:
x1 = self.soft(x1)
x2 = self.sig(x2)
return x1, x2, h_n, c_n
def start_training(self, dir, device, outputdir="..\\models\\default", ev_set=None, file_set=None):
if not os.path.exists(outputdir):
os.mkdir(outputdir)
modelname = dir.split('\\')[-1]
all_files = [f for f in glob.glob(os.path.join(dir, "**/*.osu"), recursive=True)]
eval_files_len = int(len(all_files) * VAL_SIZE) + 1
folders = glob.glob(os.path.join(dir, "*\\"))
np.random.shuffle(folders)
eval_files = []
i = 0
while len(eval_files) < eval_files_len:
eval_files.extend([f for f in glob.glob(os.path.join(folders[i], "*.osu"))])
i += 1
files = [x for x in all_files if x not in eval_files]
np.random.shuffle(files)
if ev_set is not None and file_set is not None:
eval_files = np.load(ev_set)
files = np.load(file_set)
optimizer = optim.Adam(self.parameters(), lr=LR_RATE)
loss_fn1 = nn.CrossEntropyLoss()
loss_fn2 = nn.BCEWithLogitsLoss()
loss_vals = []
val_losses = []
highest_f = 0
loss_vals = []
f_scores = []
prev_val_loss = float('inf')
prev_state = self.state_dict()
model_thresh = 0
training_patience = PATIENCE
for epoch in range(EPOCHS):
self.train()
running_loss = 0
dataset_len = 0
np.random.shuffle(files)
for i, file in enumerate(files):
try:
dataset = TypeDataset(file)
loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE)
dataset_len += len(loader)
print("Epoch: " + str(epoch) + "/" + str(EPOCHS) + ", data: " + str(i) + "/" + str(len(files)))
for (batch_X, batch_Y, batch_Z) in tqdm(loader):
optimizer.zero_grad()
out1, out2, _, _ = self(batch_X.to(device))
loss1 = loss_fn1(out1.view(-1, 3), batch_Y.to(device))
loss2 = loss_fn2(out2.view(-1), batch_Z.to(device))
loss = loss1 + loss2
loss.backward()
optimizer.step()
running_loss += loss.item()
except FileNotFoundError as e:
print(str(e))
files.remove(file)
train_loss = running_loss/dataset_len
print("loss: ", train_loss)
loss_vals.append(train_loss)
val_loss, f1, thresh, _ = self.evaluate(eval_files, device)
if prev_val_loss < val_loss:
print("loss increased", abs(training_patience - 5))
training_patience -= 1
if training_patience == -1:
print("Early training stop checkpoint after", epoch, "epochs")
torch.save(prev_state, os.path.join(outputdir, "seq_clust_model_check.pth"))
np.save(os.path.join(outputdir, "seq_clust_thresh.npy"), np.array(model_thresh))
else:
prev_state = self.state_dict()
training_patience = PATIENCE
model_thresh = thresh
prev_val_loss = val_loss
f_scores.append(f1)
val_losses.append(val_loss)
if f_scores[-1] > highest_f:
np.save(os.path.join(outputdir, "seq_clust_thresh_best_f1.npy"), np.array(thresh))
torch.save(self.state_dict(), os.path.join(outputdir, "seq_clust_model_best_f1.pth"))
highest_f = f_scores[-1]
np.save(os.path.join(outputdir, "seq_clust_thresh.npy"), np.array(thresh))
np.save(os.path.join(outputdir, "train_files.npy"), np.array(files))
np.save(os.path.join(outputdir, "val_files.npy"), np.array(eval_files))
torch.save(self.state_dict(), os.path.join(outputdir, "seq_clust_model.pth"))
return loss_vals, val_losses, f_scores
def evaluate(self, files, device, dir=None, model=None):
if model is not None:
self.load_state_dict(torch.load(os.path.join(model, "seq_clust_model.pth"), map_location=device))
if dir is not None:
files = [f for f in glob.glob(os.path.join(dir, "**/*.osu"), recursive=True)]
ground = []
loss_fn1 = nn.CrossEntropyLoss()
loss_fn2 = nn.BCEWithLogitsLoss()
running_loss = 0
dataset_len = 0
with torch.no_grad():
self.eval()
predictions = []
combo_pred = []
ground = []
combo_ground = []
for i, file in tqdm(enumerate(files)):
try:
dataset = TypeDataset(file)
loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE)
dataset_len += len(loader)
for i, (batch_X, batch_Y, batch_Z) in enumerate(loader):
out1, out2, _, _ = self(batch_X.to(device))
loss1 = loss_fn1(out1.view(-1, 3), batch_Y.to(device))
loss2 = loss_fn2(out2.view(-1), batch_Z.to(device))
loss = loss1 + loss2
running_loss += loss.item()
predictions.extend(torch.argmax(out1.cpu(), dim=1))
ground.extend(batch_Y.numpy())
combo_pred.extend(out2.cpu())
combo_ground.extend(batch_Z.cpu())
except FileNotFoundError as e:
print(str(e))
files.remove(file)
predictions = np.array(predictions)
ground = np.array(ground)
combo_pred = np.array(combo_pred)
combo_ground = np.array(combo_ground)
print(combo_pred)
pr, re, thresh = precision_recall_curve(combo_ground, combo_pred)
fscore = (2*pr*re)/(pr+re)
ix = np.argmax(fscore)
print("Best:", thresh[ix], "f1score:", fscore[ix])
print(running_loss/dataset_len)
sequence_f1 = f1_score(ground, predictions, average='micro')
combo_threshed = np.zeros(len(combo_pred))
for i, pred in enumerate(combo_pred):
if pred >= thresh[ix]:
combo_threshed[i] = 1
print(combo_threshed)
combo_f1 = f1_score(combo_ground, combo_threshed)
print("ppl:", torch.exp(torch.tensor(running_loss/dataset_len)))
print("seqf1:", sequence_f1)
print("combof1:", combo_f1)
print((sequence_f1 + combo_f1) / 2)
return running_loss/dataset_len, ((sequence_f1 + combo_f1) / 2), thresh[ix], torch.exp(torch.tensor(running_loss/dataset_len))
def infer(self, onsets, target_diff, sections, global_tempo, local_tempo, device, model="..\\models\\default"):
self.load_state_dict(torch.load(os.path.join(model, "seq_clust_model.pth"), map_location=device))
thresh = np.load(os.path.join(model, "seq_clust_thresh.npy"))
predictions = []
combo_preds = []
with torch.no_grad():
self.eval()
h_0 = None
c_0 = None
prev_time = 0
out = 0
curr_tempo = -1
tempo = (1 / local_tempo[0][1]) * 60 * 1000
past_var_feat = deque([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, convert_time(onsets[0], (1 / local_tempo[0][1]) * 60 * 1000)]], maxlen=3)
const_t = np.array(global_tempo)
difficulty = target_diff
for x in tqdm(range(onsets[:-1].shape[0])):
for (t, flag, _, _) in np.flip(sections):
if t < x:
if flag == -1 and target_diff != 0:
difficulty = target_diff - 1
elif flag == 1 and target_diff != 5:
difficulty = target_diff + 1
else:
difficulty = target_diff
const_feat = np.append(const_t, np.eye(6)[difficulty])
if curr_tempo + 1 < local_tempo.shape[0]:
if onsets[x] >= local_tempo[curr_tempo][0]:
curr_tempo += 1
tempo = (1 / local_tempo[curr_tempo][1]) * 60 * 1000
if out == 1:
typ = np.eye(3)[out]
out = 0
predictions.append(2)
combo_preds.append(0)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [0, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
continue
if out == 2:
typ = np.eye(3)[out]
out = 0
predictions.append(5)
combo_preds.append(0)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [0, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
continue
input = []
features = list(past_var_feat)
for i in features:
frame = np.append(const_feat, i)
input.append(frame)
input = torch.from_numpy(np.array(input)).float()
out, combo, h_0, c_0 = self(input.view(-1, 3, 13).to(device), h_0, c_0)
out = torch.argmax(out.view(3), dim=0).cpu()
if convert_time(onsets[x + 1] - onsets[x], tempo) > 2 and out == 1:
out == 0
combo = combo.cpu().item()
if combo > thresh:
combo = 1
else:
combo = 0
combo_preds.append(combo)
typ = np.eye(3)[out]
if out == 2:
predictions.append(4)
else:
predictions.append(out)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [combo, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
if out == 1:
combo_preds.append(0)
elif out == 2:
combo_preds.append(0)
else:
input = []
features = list(past_var_feat)
for i in features:
frame = np.append(const_feat, i)
input.append(frame)
input = torch.from_numpy(np.array(input)).float()
out, combo, h_0, c_0 = self(input.view(-1, 3, 13).to(device), h_0, c_0)
out = torch.argmax(out.view(3), dim=0).cpu()
if out == 1 or out == 2:
out = 0
combo = combo.cpu().item()
if combo > thresh:
combo = 1
else:
combo = 0
combo_preds.append(combo)
predictions.append(out)
return np.array(predictions), np.array(combo_preds)
def prob_func(combo_len):
return -0.3038 + 3.3241 / combo_len
def cluster_onsets(onsets, tempo):
random.seed(onsets[0])
n_combo = np.zeros_like(onsets)
n_combo[0] = 1
combo_len = 1
prev_onset = onsets[0]
local_avg = 0
curr_tempo = -1
for i, onset in enumerate(onsets[1:-1]):
if curr_tempo + 1 < tempo.shape[0]:
if onset >= tempo[curr_tempo + 1][0]:
curr_tempo += 1
dist = convert_time(onset - prev_onset, 1 / tempo[curr_tempo][1] * 60 * 1000)
if n_combo[i] == 1:
local_avg = dist
else:
local_avg += dist
local_avg /= 2
if dist > (local_avg + 0.1) or dist > 4.95:
n_combo[i + 1] = 1
combo_len = 0
elif round(combo_len / 2) >= 4:
if random.random() > prob_func(combo_len):
n_combo[i + 1] = 1
combo_len = 0
combo_len += 1
prev_onset = onset
return n_combo | code/modules/clustering_module.py | import os
import random
from collections import deque
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
from sklearn.metrics import f1_score, precision_recall_curve
import matplotlib.pyplot as plt
import glob
from tqdm import tqdm
from utilities.feature_extractor import FeatureExtractor, convert_time
BATCH_SIZE = 16
VAL_SIZE = 0.15
EPOCHS = 50
PATIENCE = 5
LR_RATE = 0.0005
class TypeDataset(Dataset):
def __init__(self, file):
self.extractor = FeatureExtractor()
ground, data, comboground = self.extractor.extract_types(file)
self.x = torch.from_numpy(np.array(data))
self.y = torch.from_numpy(np.array(ground))
self.z = torch.from_numpy(np.array(comboground))
self.samples = self.x.shape[0]
def __getitem__(self, index):
return self.x[index].float(), self.y[index].long(), self.z[index].float()
def __len__(self):
return self.samples
class LstmClustering(nn.Module):
def __init__(self):
super().__init__()
self.lstm1 = nn.LSTM(input_size=13, hidden_size=128, batch_first=True, num_layers=2)
self.lin = nn.Linear(3*128, 128)
self.out = nn.Linear(128, 3)
self.clu = nn.Linear(3*128, 256)
self.clu2 = nn.Linear(256, 128)
self.cluout = nn.Linear(128, 1)
self.sig = nn.Sigmoid()
self.soft = nn.Softmax(dim=1)
def forward(self, x, h_t=None, c_t=None):
if h_t is None or c_t is None:
x, (h_n, c_n) = self.lstm1(x)
else:
x, (h_n, c_n) = self.lstm1(x, (h_t, c_t))
x = F.relu(x)
lstmout = torch.flatten(x, start_dim=1)
x1 = F.dropout(F.relu(self.lin(lstmout)), training=self.training)
x1 = self.out(x1)
x2 = F.dropout(F.relu(self.clu(lstmout)), training=self.training)
x2 = self.cluout(F.relu(self.clu2(x2)))
if not self.training:
x1 = self.soft(x1)
x2 = self.sig(x2)
return x1, x2, h_n, c_n
def start_training(self, dir, device, outputdir="..\\models\\default", ev_set=None, file_set=None):
if not os.path.exists(outputdir):
os.mkdir(outputdir)
modelname = dir.split('\\')[-1]
all_files = [f for f in glob.glob(os.path.join(dir, "**/*.osu"), recursive=True)]
eval_files_len = int(len(all_files) * VAL_SIZE) + 1
folders = glob.glob(os.path.join(dir, "*\\"))
np.random.shuffle(folders)
eval_files = []
i = 0
while len(eval_files) < eval_files_len:
eval_files.extend([f for f in glob.glob(os.path.join(folders[i], "*.osu"))])
i += 1
files = [x for x in all_files if x not in eval_files]
np.random.shuffle(files)
if ev_set is not None and file_set is not None:
eval_files = np.load(ev_set)
files = np.load(file_set)
optimizer = optim.Adam(self.parameters(), lr=LR_RATE)
loss_fn1 = nn.CrossEntropyLoss()
loss_fn2 = nn.BCEWithLogitsLoss()
loss_vals = []
val_losses = []
highest_f = 0
loss_vals = []
f_scores = []
prev_val_loss = float('inf')
prev_state = self.state_dict()
model_thresh = 0
training_patience = PATIENCE
for epoch in range(EPOCHS):
self.train()
running_loss = 0
dataset_len = 0
np.random.shuffle(files)
for i, file in enumerate(files):
try:
dataset = TypeDataset(file)
loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE)
dataset_len += len(loader)
print("Epoch: " + str(epoch) + "/" + str(EPOCHS) + ", data: " + str(i) + "/" + str(len(files)))
for (batch_X, batch_Y, batch_Z) in tqdm(loader):
optimizer.zero_grad()
out1, out2, _, _ = self(batch_X.to(device))
loss1 = loss_fn1(out1.view(-1, 3), batch_Y.to(device))
loss2 = loss_fn2(out2.view(-1), batch_Z.to(device))
loss = loss1 + loss2
loss.backward()
optimizer.step()
running_loss += loss.item()
except FileNotFoundError as e:
print(str(e))
files.remove(file)
train_loss = running_loss/dataset_len
print("loss: ", train_loss)
loss_vals.append(train_loss)
val_loss, f1, thresh, _ = self.evaluate(eval_files, device)
if prev_val_loss < val_loss:
print("loss increased", abs(training_patience - 5))
training_patience -= 1
if training_patience == -1:
print("Early training stop checkpoint after", epoch, "epochs")
torch.save(prev_state, os.path.join(outputdir, "seq_clust_model_check.pth"))
np.save(os.path.join(outputdir, "seq_clust_thresh.npy"), np.array(model_thresh))
else:
prev_state = self.state_dict()
training_patience = PATIENCE
model_thresh = thresh
prev_val_loss = val_loss
f_scores.append(f1)
val_losses.append(val_loss)
if f_scores[-1] > highest_f:
np.save(os.path.join(outputdir, "seq_clust_thresh_best_f1.npy"), np.array(thresh))
torch.save(self.state_dict(), os.path.join(outputdir, "seq_clust_model_best_f1.pth"))
highest_f = f_scores[-1]
np.save(os.path.join(outputdir, "seq_clust_thresh.npy"), np.array(thresh))
np.save(os.path.join(outputdir, "train_files.npy"), np.array(files))
np.save(os.path.join(outputdir, "val_files.npy"), np.array(eval_files))
torch.save(self.state_dict(), os.path.join(outputdir, "seq_clust_model.pth"))
return loss_vals, val_losses, f_scores
def evaluate(self, files, device, dir=None, model=None):
if model is not None:
self.load_state_dict(torch.load(os.path.join(model, "seq_clust_model.pth"), map_location=device))
if dir is not None:
files = [f for f in glob.glob(os.path.join(dir, "**/*.osu"), recursive=True)]
ground = []
loss_fn1 = nn.CrossEntropyLoss()
loss_fn2 = nn.BCEWithLogitsLoss()
running_loss = 0
dataset_len = 0
with torch.no_grad():
self.eval()
predictions = []
combo_pred = []
ground = []
combo_ground = []
for i, file in tqdm(enumerate(files)):
try:
dataset = TypeDataset(file)
loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE)
dataset_len += len(loader)
for i, (batch_X, batch_Y, batch_Z) in enumerate(loader):
out1, out2, _, _ = self(batch_X.to(device))
loss1 = loss_fn1(out1.view(-1, 3), batch_Y.to(device))
loss2 = loss_fn2(out2.view(-1), batch_Z.to(device))
loss = loss1 + loss2
running_loss += loss.item()
predictions.extend(torch.argmax(out1.cpu(), dim=1))
ground.extend(batch_Y.numpy())
combo_pred.extend(out2.cpu())
combo_ground.extend(batch_Z.cpu())
except FileNotFoundError as e:
print(str(e))
files.remove(file)
predictions = np.array(predictions)
ground = np.array(ground)
combo_pred = np.array(combo_pred)
combo_ground = np.array(combo_ground)
print(combo_pred)
pr, re, thresh = precision_recall_curve(combo_ground, combo_pred)
fscore = (2*pr*re)/(pr+re)
ix = np.argmax(fscore)
print("Best:", thresh[ix], "f1score:", fscore[ix])
print(running_loss/dataset_len)
sequence_f1 = f1_score(ground, predictions, average='micro')
combo_threshed = np.zeros(len(combo_pred))
for i, pred in enumerate(combo_pred):
if pred >= thresh[ix]:
combo_threshed[i] = 1
print(combo_threshed)
combo_f1 = f1_score(combo_ground, combo_threshed)
print("ppl:", torch.exp(torch.tensor(running_loss/dataset_len)))
print("seqf1:", sequence_f1)
print("combof1:", combo_f1)
print((sequence_f1 + combo_f1) / 2)
return running_loss/dataset_len, ((sequence_f1 + combo_f1) / 2), thresh[ix], torch.exp(torch.tensor(running_loss/dataset_len))
def infer(self, onsets, target_diff, sections, global_tempo, local_tempo, device, model="..\\models\\default"):
self.load_state_dict(torch.load(os.path.join(model, "seq_clust_model.pth"), map_location=device))
thresh = np.load(os.path.join(model, "seq_clust_thresh.npy"))
predictions = []
combo_preds = []
with torch.no_grad():
self.eval()
h_0 = None
c_0 = None
prev_time = 0
out = 0
curr_tempo = -1
tempo = (1 / local_tempo[0][1]) * 60 * 1000
past_var_feat = deque([[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, convert_time(onsets[0], (1 / local_tempo[0][1]) * 60 * 1000)]], maxlen=3)
const_t = np.array(global_tempo)
difficulty = target_diff
for x in tqdm(range(onsets[:-1].shape[0])):
for (t, flag, _, _) in np.flip(sections):
if t < x:
if flag == -1 and target_diff != 0:
difficulty = target_diff - 1
elif flag == 1 and target_diff != 5:
difficulty = target_diff + 1
else:
difficulty = target_diff
const_feat = np.append(const_t, np.eye(6)[difficulty])
if curr_tempo + 1 < local_tempo.shape[0]:
if onsets[x] >= local_tempo[curr_tempo][0]:
curr_tempo += 1
tempo = (1 / local_tempo[curr_tempo][1]) * 60 * 1000
if out == 1:
typ = np.eye(3)[out]
out = 0
predictions.append(2)
combo_preds.append(0)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [0, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
continue
if out == 2:
typ = np.eye(3)[out]
out = 0
predictions.append(5)
combo_preds.append(0)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [0, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
continue
input = []
features = list(past_var_feat)
for i in features:
frame = np.append(const_feat, i)
input.append(frame)
input = torch.from_numpy(np.array(input)).float()
out, combo, h_0, c_0 = self(input.view(-1, 3, 13).to(device), h_0, c_0)
out = torch.argmax(out.view(3), dim=0).cpu()
if convert_time(onsets[x + 1] - onsets[x], tempo) > 2 and out == 1:
out == 0
combo = combo.cpu().item()
if combo > thresh:
combo = 1
else:
combo = 0
combo_preds.append(combo)
typ = np.eye(3)[out]
if out == 2:
predictions.append(4)
else:
predictions.append(out)
prev_time = onsets[x] - prev_time
next_time = onsets[x + 1] - onsets[x]
past_var_feat.append(np.append(typ, [combo, convert_time(prev_time, tempo), convert_time(next_time, tempo)]))
if out == 1:
combo_preds.append(0)
elif out == 2:
combo_preds.append(0)
else:
input = []
features = list(past_var_feat)
for i in features:
frame = np.append(const_feat, i)
input.append(frame)
input = torch.from_numpy(np.array(input)).float()
out, combo, h_0, c_0 = self(input.view(-1, 3, 13).to(device), h_0, c_0)
out = torch.argmax(out.view(3), dim=0).cpu()
if out == 1 or out == 2:
out = 0
combo = combo.cpu().item()
if combo > thresh:
combo = 1
else:
combo = 0
combo_preds.append(combo)
predictions.append(out)
return np.array(predictions), np.array(combo_preds)
def prob_func(combo_len):
return -0.3038 + 3.3241 / combo_len
def cluster_onsets(onsets, tempo):
random.seed(onsets[0])
n_combo = np.zeros_like(onsets)
n_combo[0] = 1
combo_len = 1
prev_onset = onsets[0]
local_avg = 0
curr_tempo = -1
for i, onset in enumerate(onsets[1:-1]):
if curr_tempo + 1 < tempo.shape[0]:
if onset >= tempo[curr_tempo + 1][0]:
curr_tempo += 1
dist = convert_time(onset - prev_onset, 1 / tempo[curr_tempo][1] * 60 * 1000)
if n_combo[i] == 1:
local_avg = dist
else:
local_avg += dist
local_avg /= 2
if dist > (local_avg + 0.1) or dist > 4.95:
n_combo[i + 1] = 1
combo_len = 0
elif round(combo_len / 2) >= 4:
if random.random() > prob_func(combo_len):
n_combo[i + 1] = 1
combo_len = 0
combo_len += 1
prev_onset = onset
return n_combo | 0.776029 | 0.33112 |
from ykdl.util.html import get_content, add_header
from ykdl.util.match import match1, matchall
from ykdl.extractor import VideoExtractor
from ykdl.videoinfo import VideoInfo
from ykdl.compact import urlencode
from .util import get_h5enc, ub98484234
import json
douyu_match_pattern = [ 'class="hroom_id" value="([^"]+)',
'data-room_id="([^"]+)'
]
class Douyutv(VideoExtractor):
name = u'斗鱼直播 (DouyuTV)'
stream_ids = ['OG', 'BD10M', 'BD8M', 'BD4M', 'BD', 'TD', 'HD', 'SD']
profile_2_id = {
'原画': 'OG',
'蓝光10M': 'BD10M',
'蓝光8M': 'BD8M',
'蓝光4M': 'BD4M',
'蓝光': 'BD',
'超清': 'TD',
'高清': 'HD',
'流畅': 'SD'
}
def prepare(self):
info = VideoInfo(self.name, True)
add_header("Referer", 'https://www.douyu.com')
html = get_content(self.url)
self.vid = match1(html, '\$ROOM\.room_id\s*=\s*(\d+)',
'room_id\s*=\s*(\d+)',
'"room_id.?":(\d+)',
'data-onlineid=(\d+)')
title = match1(html, 'Title-head\w*">([^<]+)<')
artist = match1(html, 'Title-anchorName\w*" title="([^"]+)"')
if not title or not artist:
room_data = json.loads(get_content('https://open.douyucdn.cn/api/RoomApi/room/' + self.vid))
if room_data['error'] == 0:
room_data = room_data['data']
title = room_data['room_name']
artist = room_data['owner_name']
info.title = u'{} - {}'.format(title, artist)
info.artist = artist
js_enc = get_h5enc(html, self.vid)
params = {
'cdn': '',
'iar': 0,
'ive': 0
}
ub98484234(js_enc, self, params)
def get_live_info(rate=0):
params['rate'] = rate
data = urlencode(params)
if not isinstance(data, bytes):
data = data.encode()
html_content = get_content('https://www.douyu.com/lapi/live/getH5Play/{}'.format(self.vid), data=data)
self.logger.debug(html_content)
live_data = json.loads(html_content)
if live_data['error']:
return live_data['msg']
live_data = live_data["data"]
real_url = '{}/{}'.format(live_data['rtmp_url'], live_data['rtmp_live'])
rate_2_profile = dict((rate['rate'], rate['name']) for rate in live_data['multirates'])
video_profile = rate_2_profile[live_data['rate']]
if '原画' in video_profile:
stream = 'OG'
else:
stream = self.profile_2_id[video_profile]
if stream in info.streams:
return
info.stream_types.append(stream)
info.streams[stream] = {
'container': match1(live_data['rtmp_live'], '\.(\w+)\?'),
'video_profile': video_profile,
'src' : [real_url],
'size': float('inf')
}
error_msges = []
if rate == 0:
rate_2_profile.pop(0, None)
rate_2_profile.pop(live_data['rate'], None)
for rate in rate_2_profile:
error_msg = get_live_info(rate)
if error_msg:
error_msges.append(error_msg)
if error_msges:
return ', '.join(error_msges)
error_msg = get_live_info()
assert len(info.stream_types), error_msg
info.stream_types = sorted(info.stream_types, key=self.stream_ids.index)
return info
def prepare_list(self):
html = get_content(self.url)
return matchall(html, *douyu_match_pattern)
site = Douyutv() | ykdl/extractors/douyu/live.py |
from ykdl.util.html import get_content, add_header
from ykdl.util.match import match1, matchall
from ykdl.extractor import VideoExtractor
from ykdl.videoinfo import VideoInfo
from ykdl.compact import urlencode
from .util import get_h5enc, ub98484234
import json
douyu_match_pattern = [ 'class="hroom_id" value="([^"]+)',
'data-room_id="([^"]+)'
]
class Douyutv(VideoExtractor):
name = u'斗鱼直播 (DouyuTV)'
stream_ids = ['OG', 'BD10M', 'BD8M', 'BD4M', 'BD', 'TD', 'HD', 'SD']
profile_2_id = {
'原画': 'OG',
'蓝光10M': 'BD10M',
'蓝光8M': 'BD8M',
'蓝光4M': 'BD4M',
'蓝光': 'BD',
'超清': 'TD',
'高清': 'HD',
'流畅': 'SD'
}
def prepare(self):
info = VideoInfo(self.name, True)
add_header("Referer", 'https://www.douyu.com')
html = get_content(self.url)
self.vid = match1(html, '\$ROOM\.room_id\s*=\s*(\d+)',
'room_id\s*=\s*(\d+)',
'"room_id.?":(\d+)',
'data-onlineid=(\d+)')
title = match1(html, 'Title-head\w*">([^<]+)<')
artist = match1(html, 'Title-anchorName\w*" title="([^"]+)"')
if not title or not artist:
room_data = json.loads(get_content('https://open.douyucdn.cn/api/RoomApi/room/' + self.vid))
if room_data['error'] == 0:
room_data = room_data['data']
title = room_data['room_name']
artist = room_data['owner_name']
info.title = u'{} - {}'.format(title, artist)
info.artist = artist
js_enc = get_h5enc(html, self.vid)
params = {
'cdn': '',
'iar': 0,
'ive': 0
}
ub98484234(js_enc, self, params)
def get_live_info(rate=0):
params['rate'] = rate
data = urlencode(params)
if not isinstance(data, bytes):
data = data.encode()
html_content = get_content('https://www.douyu.com/lapi/live/getH5Play/{}'.format(self.vid), data=data)
self.logger.debug(html_content)
live_data = json.loads(html_content)
if live_data['error']:
return live_data['msg']
live_data = live_data["data"]
real_url = '{}/{}'.format(live_data['rtmp_url'], live_data['rtmp_live'])
rate_2_profile = dict((rate['rate'], rate['name']) for rate in live_data['multirates'])
video_profile = rate_2_profile[live_data['rate']]
if '原画' in video_profile:
stream = 'OG'
else:
stream = self.profile_2_id[video_profile]
if stream in info.streams:
return
info.stream_types.append(stream)
info.streams[stream] = {
'container': match1(live_data['rtmp_live'], '\.(\w+)\?'),
'video_profile': video_profile,
'src' : [real_url],
'size': float('inf')
}
error_msges = []
if rate == 0:
rate_2_profile.pop(0, None)
rate_2_profile.pop(live_data['rate'], None)
for rate in rate_2_profile:
error_msg = get_live_info(rate)
if error_msg:
error_msges.append(error_msg)
if error_msges:
return ', '.join(error_msges)
error_msg = get_live_info()
assert len(info.stream_types), error_msg
info.stream_types = sorted(info.stream_types, key=self.stream_ids.index)
return info
def prepare_list(self):
html = get_content(self.url)
return matchall(html, *douyu_match_pattern)
site = Douyutv() | 0.412885 | 0.206774 |
import datetime
import mock
from keystoneclient import access
from keystoneclient import httpclient
from keystoneclient.openstack.common import timeutils
from keystoneclient.tests import utils
from keystoneclient.tests.v2_0 import client_fixtures
try:
import keyring # noqa
import pickle # noqa
except ImportError:
keyring = None
PROJECT_SCOPED_TOKEN = client_fixtures.project_scoped_token()
# These mirror values from PROJECT_SCOPED_TOKEN
USERNAME = 'exampleuser'
AUTH_URL = 'http://public.com:5000/v2.0'
TOKEN = '<KEY>'
PASSWORD = 'password'
TENANT = 'tenant'
TENANT_ID = 'tenant_id'
class KeyringTest(utils.TestCase):
def setUp(self):
if keyring is None:
self.skipTest(
'optional package keyring or pickle is not installed')
class MemoryKeyring(keyring.backend.KeyringBackend):
"""A Simple testing keyring.
This class supports stubbing an initial password to be returned by
setting password, and allows easy password and key retrieval. Also
records if a password was retrieved.
"""
def __init__(self):
self.key = None
self.password = None
self.fetched = False
self.get_password_called = False
self.set_password_called = False
def supported(self):
return 1
def get_password(self, service, username):
self.get_password_called = True
key = username + '@' + service
# make sure we don't get passwords crossed if one is enforced.
if self.key and self.key != key:
return None
if self.password:
self.fetched = True
return self.password
def set_password(self, service, username, password):
self.set_password_called = True
self.key = username + '@' + service
self.password = password
super(KeyringTest, self).setUp()
self.memory_keyring = MemoryKeyring()
keyring.set_keyring(self.memory_keyring)
def test_no_keyring_key(self):
"""Ensure that if we don't have use_keyring set in the client that
the keyring is never accessed.
"""
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL)
# stub and check that a new token is received
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# make sure that we never touched the keyring
self.assertFalse(self.memory_keyring.get_password_called)
self.assertFalse(self.memory_keyring.set_password_called)
def test_build_keyring_key(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL)
keyring_key = cl._build_keyring_key(auth_url=AUTH_URL,
username=USERNAME,
tenant_name=TENANT,
tenant_id=TENANT_ID,
token=TOKEN)
self.assertEqual(keyring_key,
'%s/%s/%s/%s/%s' %
(AUTH_URL, TENANT_ID, TENANT, TOKEN, USERNAME))
def test_set_and_get_keyring_expired(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# set an expired token into the keyring
auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
auth_ref['token']['expires'] = timeutils.isotime(expired)
self.memory_keyring.password = pickle.dumps(auth_ref)
# stub and check that a new token is received, so not using expired
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# check that a value was returned from the keyring
self.assertTrue(self.memory_keyring.fetched)
# check that the new token has been loaded into the keyring
new_auth_ref = pickle.loads(self.memory_keyring.password)
self.assertEqual(new_auth_ref['token']['expires'],
PROJECT_SCOPED_TOKEN['access']['token']['expires'])
def test_get_keyring(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# set an token into the keyring
auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
future = timeutils.utcnow() + datetime.timedelta(minutes=30)
auth_ref['token']['expires'] = timeutils.isotime(future)
self.memory_keyring.password = pickle.dumps(auth_ref)
# don't stub get_raw_token so will fail if authenticate happens
self.assertTrue(cl.authenticate())
self.assertTrue(self.memory_keyring.fetched)
def test_set_keyring(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# stub and check that a new token is received
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# we checked the keyring, but we didn't find anything
self.assertTrue(self.memory_keyring.get_password_called)
self.assertFalse(self.memory_keyring.fetched)
# check that the new token has been loaded into the keyring
self.assertTrue(self.memory_keyring.set_password_called)
new_auth_ref = pickle.loads(self.memory_keyring.password)
self.assertEqual(new_auth_ref.auth_token, TOKEN)
self.assertEqual(new_auth_ref['token'],
PROJECT_SCOPED_TOKEN['access']['token'])
self.assertEqual(new_auth_ref.username, USERNAME) | keystoneclient/tests/test_keyring.py |
import datetime
import mock
from keystoneclient import access
from keystoneclient import httpclient
from keystoneclient.openstack.common import timeutils
from keystoneclient.tests import utils
from keystoneclient.tests.v2_0 import client_fixtures
try:
import keyring # noqa
import pickle # noqa
except ImportError:
keyring = None
PROJECT_SCOPED_TOKEN = client_fixtures.project_scoped_token()
# These mirror values from PROJECT_SCOPED_TOKEN
USERNAME = 'exampleuser'
AUTH_URL = 'http://public.com:5000/v2.0'
TOKEN = '<KEY>'
PASSWORD = 'password'
TENANT = 'tenant'
TENANT_ID = 'tenant_id'
class KeyringTest(utils.TestCase):
def setUp(self):
if keyring is None:
self.skipTest(
'optional package keyring or pickle is not installed')
class MemoryKeyring(keyring.backend.KeyringBackend):
"""A Simple testing keyring.
This class supports stubbing an initial password to be returned by
setting password, and allows easy password and key retrieval. Also
records if a password was retrieved.
"""
def __init__(self):
self.key = None
self.password = None
self.fetched = False
self.get_password_called = False
self.set_password_called = False
def supported(self):
return 1
def get_password(self, service, username):
self.get_password_called = True
key = username + '@' + service
# make sure we don't get passwords crossed if one is enforced.
if self.key and self.key != key:
return None
if self.password:
self.fetched = True
return self.password
def set_password(self, service, username, password):
self.set_password_called = True
self.key = username + '@' + service
self.password = password
super(KeyringTest, self).setUp()
self.memory_keyring = MemoryKeyring()
keyring.set_keyring(self.memory_keyring)
def test_no_keyring_key(self):
"""Ensure that if we don't have use_keyring set in the client that
the keyring is never accessed.
"""
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL)
# stub and check that a new token is received
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# make sure that we never touched the keyring
self.assertFalse(self.memory_keyring.get_password_called)
self.assertFalse(self.memory_keyring.set_password_called)
def test_build_keyring_key(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL)
keyring_key = cl._build_keyring_key(auth_url=AUTH_URL,
username=USERNAME,
tenant_name=TENANT,
tenant_id=TENANT_ID,
token=TOKEN)
self.assertEqual(keyring_key,
'%s/%s/%s/%s/%s' %
(AUTH_URL, TENANT_ID, TENANT, TOKEN, USERNAME))
def test_set_and_get_keyring_expired(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# set an expired token into the keyring
auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
auth_ref['token']['expires'] = timeutils.isotime(expired)
self.memory_keyring.password = pickle.dumps(auth_ref)
# stub and check that a new token is received, so not using expired
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# check that a value was returned from the keyring
self.assertTrue(self.memory_keyring.fetched)
# check that the new token has been loaded into the keyring
new_auth_ref = pickle.loads(self.memory_keyring.password)
self.assertEqual(new_auth_ref['token']['expires'],
PROJECT_SCOPED_TOKEN['access']['token']['expires'])
def test_get_keyring(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# set an token into the keyring
auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
future = timeutils.utcnow() + datetime.timedelta(minutes=30)
auth_ref['token']['expires'] = timeutils.isotime(future)
self.memory_keyring.password = pickle.dumps(auth_ref)
# don't stub get_raw_token so will fail if authenticate happens
self.assertTrue(cl.authenticate())
self.assertTrue(self.memory_keyring.fetched)
def test_set_keyring(self):
cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
tenant_id=TENANT_ID, auth_url=AUTH_URL,
use_keyring=True)
# stub and check that a new token is received
method = 'get_raw_token_from_identity_service'
with mock.patch.object(cl, method) as meth:
meth.return_value = (True, PROJECT_SCOPED_TOKEN)
self.assertTrue(cl.authenticate())
self.assertEqual(1, meth.call_count)
# we checked the keyring, but we didn't find anything
self.assertTrue(self.memory_keyring.get_password_called)
self.assertFalse(self.memory_keyring.fetched)
# check that the new token has been loaded into the keyring
self.assertTrue(self.memory_keyring.set_password_called)
new_auth_ref = pickle.loads(self.memory_keyring.password)
self.assertEqual(new_auth_ref.auth_token, TOKEN)
self.assertEqual(new_auth_ref['token'],
PROJECT_SCOPED_TOKEN['access']['token'])
self.assertEqual(new_auth_ref.username, USERNAME) | 0.558086 | 0.14072 |
from PIL import Image
import ass
from datetime import timedelta
import sys
doc = ass.document.Document()
SCALE = 2
DPI = 72
doc.styles.append(ass.document.Style(
name="Default",
shadow=0,
outline=0,
alignment=7,
bold=False,
margin_l=int(1.25 * DPI * SCALE),
margin_r=int(1.25 * DPI * SCALE),
margin_v=0,
fontname="Garamond",
fontsize=13 * SCALE,
primary_color=ass.document.Color.BLACK
))
doc.events.append(ass.document.Dialogue(
start=timedelta(0),
end=timedelta(milliseconds=1),
margin_v=int(0.5 * DPI * SCALE),
style="Default",
text="{\\an2}- 1 -"
))
doc.events.append(ass.document.Dialogue(
start=timedelta(0),
end=timedelta(milliseconds=1),
margin_v=int(1.5 * DPI * SCALE),
style="Default",
text="""
{\\fs72}Lorem Ipsum{\\r}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras adipiscing leo
nec lorem vulputate gravida. Maecenas vitae sodales elit. Fusce eget malesuada
neque, sed imperdiet mi. Etiam vel urna aliquam, aliquet nunc et, bibendum leo.
Donec a neque risus. Sed sit amet lectus vel quam imperdiet pulvinar. Donec a
justo vitae metus suscipit dapibus. In lacinia vestibulum vestibulum. Integer
turpis sapien, varius eget mi vel, lobortis congue eros. Aenean euismod urna
non augue ultrices luctus. Morbi mattis pharetra dapibus. Sed egestas est quis
augue faucibus, in porttitor enim porta. Nulla scelerisque tellus ac odio
euismod, at venenatis risus cursus. Sed tincidunt augue nibh. Ut interdum, est
quis mattis dignissim, eros sem pulvinar libero, vel iaculis turpis lorem vitae
tortor. Sed ac nunc in ipsum cursus aliquam.
Curabitur a massa elementum purus condimentum adipiscing. Maecenas dapibus
aliquet eros, vestibulum fermentum diam posuere et. Nulla facilisi. Phasellus
massa neque, auctor vitae fringilla sed, interdum eget magna. Nunc ultrices
sagittis velit, vel sagittis ligula pulvinar nec. Sed in nisi accumsan, gravida
purus a, vehicula nisi. Nam sed felis et urna mattis auctor. Proin non odio
tristique, cursus nibh sed, porttitor lacus. Mauris ultrices purus ut metus
accumsan accumsan id eu lorem. Vivamus non libero tempor, sodales erat sit
amet, iaculis lorem. Aenean pulvinar luctus nulla, non aliquet arcu placerat a.
Sed rhoncus nunc nec pulvinar venenatis. Proin euismod aliquam justo, eget
rhoncus ante interdum vitae.
Curabitur urna nibh, blandit eget massa quis, molestie convallis tellus. Duis
nec metus non lorem hendrerit eleifend a sed mauris. Proin et sapien sit amet
lorem hendrerit ultrices vel eget diam. Donec in euismod nisi. Nunc et tellus
eget tellus cursus semper ac et elit. Duis rhoncus nulla mollis elit bibendum,
quis posuere ligula pharetra. Maecenas urna risus, varius a lorem et, imperdiet
faucibus purus. Vestibulum facilisis leo nec sapien sollicitudin rutrum eu in
enim. Praesent a augue nisl. Praesent sollicitudin dignissim ipsum quis
ultrices.
Pellentesque pellentesque metus ac velit vestibulum, eu semper diam placerat.
Praesent tempor lectus vitae sapien accumsan vulputate. Duis porttitor massa
sit amet felis rhoncus, a auctor lorem hendrerit. Vestibulum cursus metus vel
blandit feugiat. Vivamus dignissim diam sed mauris pellentesque euismod. Mauris
a fermentum ipsum. Praesent quis sapien ultrices, aliquet quam non, lacinia
lacus. Sed interdum risus vel turpis molestie dictum. Quisque vel placerat
tortor, id hendrerit mi. Curabitur blandit enim vel nisl volutpat rutrum.
Quisque molestie pharetra augue, id dapibus mi facilisis ac. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac turpis
egestas. Vivamus consectetur lacus ut lacinia gravida. Aenean interdum ac
mauris vitae lacinia. Class aptent taciti sociosqu ad litora torquent per
conubia nostra, per inceptos himenaeos.
Vivamus sit amet felis urna. Donec pulvinar iaculis mi, non posuere lectus
eleifend non. Ut a mi et nulla pretium semper. Donec placerat egestas
fringilla. Sed scelerisque lorem et orci vestibulum egestas. Vestibulum mattis
dolor at eros facilisis hendrerit. Aliquam ac nisi eget velit tempus ornare.
Quisque vel elementum lacus. Pellentesque ornare ligula eget dictum consequat.
Nam id urna et nunc tempus auctor. Nullam nec ornare justo. Fusce auctor
viverra nibh, vitae sodales leo lacinia at. Quisque sed nisi nibh. Aliquam
pellentesque ligula id orci auctor convallis. Etiam et nisl sagittis,
malesuada enim sit amet, malesuada ante.
""".strip().replace("\n\n", "\\N\\N").replace("\n", " ")))
SIZE = (int(8.5 * DPI * SCALE), int(11 * DPI * SCALE))
doc.play_res_x, doc.play_res_y = SIZE
doc.wrap_style = 1
ctx = ass.renderer.Context()
r = ctx.make_renderer()
r.set_fonts(fontconfig_config="/usr/local/etc/fonts/fonts.conf")
r.set_all_sizes(SIZE)
sys.stdout.write("loading document... ")
sys.stdout.flush()
t = ctx.make_track()
t.populate(doc)
print("ok! {} styles, {} events".format(len(t.styles), len(t.events)))
im_out = Image.new("RGB", SIZE, 0xffffff)
im_data = im_out.load()
for img in r.render_frame(t, timedelta(0)):
r, g, b, a = img.rgba
for y in range(img.h):
for x in range(img.w):
a_src = img[x, y] * (256 - a) // 256
r_dst, g_dst, b_dst = im_data[x + img.dst_x, y + img.dst_y]
r_out = ((r * a_src) + (r_dst * (256 - a_src))) // 256
g_out = ((g * a_src) + (g_dst * (256 - a_src))) // 256
b_out = ((b * a_src) + (b_dst * (256 - a_src))) // 256
im_data[x + img.dst_x, y + img.dst_y] = (r_out, g_out, b_out)
im_out.show()
im_out.save("test.png") | renderer_test.py |
from PIL import Image
import ass
from datetime import timedelta
import sys
doc = ass.document.Document()
SCALE = 2
DPI = 72
doc.styles.append(ass.document.Style(
name="Default",
shadow=0,
outline=0,
alignment=7,
bold=False,
margin_l=int(1.25 * DPI * SCALE),
margin_r=int(1.25 * DPI * SCALE),
margin_v=0,
fontname="Garamond",
fontsize=13 * SCALE,
primary_color=ass.document.Color.BLACK
))
doc.events.append(ass.document.Dialogue(
start=timedelta(0),
end=timedelta(milliseconds=1),
margin_v=int(0.5 * DPI * SCALE),
style="Default",
text="{\\an2}- 1 -"
))
doc.events.append(ass.document.Dialogue(
start=timedelta(0),
end=timedelta(milliseconds=1),
margin_v=int(1.5 * DPI * SCALE),
style="Default",
text="""
{\\fs72}Lorem Ipsum{\\r}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras adipiscing leo
nec lorem vulputate gravida. Maecenas vitae sodales elit. Fusce eget malesuada
neque, sed imperdiet mi. Etiam vel urna aliquam, aliquet nunc et, bibendum leo.
Donec a neque risus. Sed sit amet lectus vel quam imperdiet pulvinar. Donec a
justo vitae metus suscipit dapibus. In lacinia vestibulum vestibulum. Integer
turpis sapien, varius eget mi vel, lobortis congue eros. Aenean euismod urna
non augue ultrices luctus. Morbi mattis pharetra dapibus. Sed egestas est quis
augue faucibus, in porttitor enim porta. Nulla scelerisque tellus ac odio
euismod, at venenatis risus cursus. Sed tincidunt augue nibh. Ut interdum, est
quis mattis dignissim, eros sem pulvinar libero, vel iaculis turpis lorem vitae
tortor. Sed ac nunc in ipsum cursus aliquam.
Curabitur a massa elementum purus condimentum adipiscing. Maecenas dapibus
aliquet eros, vestibulum fermentum diam posuere et. Nulla facilisi. Phasellus
massa neque, auctor vitae fringilla sed, interdum eget magna. Nunc ultrices
sagittis velit, vel sagittis ligula pulvinar nec. Sed in nisi accumsan, gravida
purus a, vehicula nisi. Nam sed felis et urna mattis auctor. Proin non odio
tristique, cursus nibh sed, porttitor lacus. Mauris ultrices purus ut metus
accumsan accumsan id eu lorem. Vivamus non libero tempor, sodales erat sit
amet, iaculis lorem. Aenean pulvinar luctus nulla, non aliquet arcu placerat a.
Sed rhoncus nunc nec pulvinar venenatis. Proin euismod aliquam justo, eget
rhoncus ante interdum vitae.
Curabitur urna nibh, blandit eget massa quis, molestie convallis tellus. Duis
nec metus non lorem hendrerit eleifend a sed mauris. Proin et sapien sit amet
lorem hendrerit ultrices vel eget diam. Donec in euismod nisi. Nunc et tellus
eget tellus cursus semper ac et elit. Duis rhoncus nulla mollis elit bibendum,
quis posuere ligula pharetra. Maecenas urna risus, varius a lorem et, imperdiet
faucibus purus. Vestibulum facilisis leo nec sapien sollicitudin rutrum eu in
enim. Praesent a augue nisl. Praesent sollicitudin dignissim ipsum quis
ultrices.
Pellentesque pellentesque metus ac velit vestibulum, eu semper diam placerat.
Praesent tempor lectus vitae sapien accumsan vulputate. Duis porttitor massa
sit amet felis rhoncus, a auctor lorem hendrerit. Vestibulum cursus metus vel
blandit feugiat. Vivamus dignissim diam sed mauris pellentesque euismod. Mauris
a fermentum ipsum. Praesent quis sapien ultrices, aliquet quam non, lacinia
lacus. Sed interdum risus vel turpis molestie dictum. Quisque vel placerat
tortor, id hendrerit mi. Curabitur blandit enim vel nisl volutpat rutrum.
Quisque molestie pharetra augue, id dapibus mi facilisis ac. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac turpis
egestas. Vivamus consectetur lacus ut lacinia gravida. Aenean interdum ac
mauris vitae lacinia. Class aptent taciti sociosqu ad litora torquent per
conubia nostra, per inceptos himenaeos.
Vivamus sit amet felis urna. Donec pulvinar iaculis mi, non posuere lectus
eleifend non. Ut a mi et nulla pretium semper. Donec placerat egestas
fringilla. Sed scelerisque lorem et orci vestibulum egestas. Vestibulum mattis
dolor at eros facilisis hendrerit. Aliquam ac nisi eget velit tempus ornare.
Quisque vel elementum lacus. Pellentesque ornare ligula eget dictum consequat.
Nam id urna et nunc tempus auctor. Nullam nec ornare justo. Fusce auctor
viverra nibh, vitae sodales leo lacinia at. Quisque sed nisi nibh. Aliquam
pellentesque ligula id orci auctor convallis. Etiam et nisl sagittis,
malesuada enim sit amet, malesuada ante.
""".strip().replace("\n\n", "\\N\\N").replace("\n", " ")))
SIZE = (int(8.5 * DPI * SCALE), int(11 * DPI * SCALE))
doc.play_res_x, doc.play_res_y = SIZE
doc.wrap_style = 1
ctx = ass.renderer.Context()
r = ctx.make_renderer()
r.set_fonts(fontconfig_config="/usr/local/etc/fonts/fonts.conf")
r.set_all_sizes(SIZE)
sys.stdout.write("loading document... ")
sys.stdout.flush()
t = ctx.make_track()
t.populate(doc)
print("ok! {} styles, {} events".format(len(t.styles), len(t.events)))
im_out = Image.new("RGB", SIZE, 0xffffff)
im_data = im_out.load()
for img in r.render_frame(t, timedelta(0)):
r, g, b, a = img.rgba
for y in range(img.h):
for x in range(img.w):
a_src = img[x, y] * (256 - a) // 256
r_dst, g_dst, b_dst = im_data[x + img.dst_x, y + img.dst_y]
r_out = ((r * a_src) + (r_dst * (256 - a_src))) // 256
g_out = ((g * a_src) + (g_dst * (256 - a_src))) // 256
b_out = ((b * a_src) + (b_dst * (256 - a_src))) // 256
im_data[x + img.dst_x, y + img.dst_y] = (r_out, g_out, b_out)
im_out.show()
im_out.save("test.png") | 0.184473 | 0.111193 |
import json
from os.path import join
from twisted.trial import unittest
from twisted.internet.defer import inlineCallbacks
from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor
from slyd.bot import create_bot_resource
from .utils import TestSite, test_spec_manager
from .settings import RESOURCE_DIR
class BotTest(unittest.TestCase):
def setUp(self):
# configure bot resource
sm = test_spec_manager()
self.bot_resource = create_bot_resource(sm)
self.botsite = TestSite(self.bot_resource)
# configure fake website to crawl
docroot = join(RESOURCE_DIR, 'docroot')
factory = Site(File(docroot))
self.listen_port = reactor.listenTCP(8997, factory)
def _fetch(self, url, **params):
req = dict(params)
req.setdefault('request', {})['url'] = url
request_json = json.dumps(req)
return self.botsite.post('fetch', data=request_json)
@inlineCallbacks
def test_fetch(self):
# test status code
result = yield self._fetch("http://localhost:8997/notexists")
self.assertEqual(result.responseCode, 200)
status = json.loads(result.value())['response']['status']
self.assertEqual(status, 404)
# get an existing file
test_url = "http://localhost:8997/test.html"
result = yield self._fetch(test_url)
self.assertEqual(result.responseCode, 200)
value = json.loads(result.value())
# expect 200 response and base href added
self.assertEqual(value['response']['status'], 200)
self.assertIn('<base href="%s"' % test_url, value['page'])
# parse fetched data
test_url = "http://localhost:8997/pin1.html"
result = yield self._fetch(test_url, spider='pinterest.com')
self.assertEqual(result.responseCode, 200)
value = json.loads(result.value())
# check item
item = value['items'][0]
self.assertEqual(item['url'], test_url)
self.assertEqual(item['name'][0], u'<NAME>')
# check links
self.assertIn('links', value)
def tearDown(self):
self.bot_resource.stop()
self.listen_port.stopListening() | slyd/tests/test_bot.py | import json
from os.path import join
from twisted.trial import unittest
from twisted.internet.defer import inlineCallbacks
from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor
from slyd.bot import create_bot_resource
from .utils import TestSite, test_spec_manager
from .settings import RESOURCE_DIR
class BotTest(unittest.TestCase):
def setUp(self):
# configure bot resource
sm = test_spec_manager()
self.bot_resource = create_bot_resource(sm)
self.botsite = TestSite(self.bot_resource)
# configure fake website to crawl
docroot = join(RESOURCE_DIR, 'docroot')
factory = Site(File(docroot))
self.listen_port = reactor.listenTCP(8997, factory)
def _fetch(self, url, **params):
req = dict(params)
req.setdefault('request', {})['url'] = url
request_json = json.dumps(req)
return self.botsite.post('fetch', data=request_json)
@inlineCallbacks
def test_fetch(self):
# test status code
result = yield self._fetch("http://localhost:8997/notexists")
self.assertEqual(result.responseCode, 200)
status = json.loads(result.value())['response']['status']
self.assertEqual(status, 404)
# get an existing file
test_url = "http://localhost:8997/test.html"
result = yield self._fetch(test_url)
self.assertEqual(result.responseCode, 200)
value = json.loads(result.value())
# expect 200 response and base href added
self.assertEqual(value['response']['status'], 200)
self.assertIn('<base href="%s"' % test_url, value['page'])
# parse fetched data
test_url = "http://localhost:8997/pin1.html"
result = yield self._fetch(test_url, spider='pinterest.com')
self.assertEqual(result.responseCode, 200)
value = json.loads(result.value())
# check item
item = value['items'][0]
self.assertEqual(item['url'], test_url)
self.assertEqual(item['name'][0], u'<NAME>')
# check links
self.assertIn('links', value)
def tearDown(self):
self.bot_resource.stop()
self.listen_port.stopListening() | 0.385259 | 0.118309 |
import fire
from fastai.text import *
from fastai.lm_rnn import *
def freeze_all_but(learner, n):
c=learner.get_layer_groups()
for l in c: set_trainable(l, False)
set_trainable(c[n], True)
def train_clas(dir_path, cuda_id, lm_id='', clas_id=None, bs=64, cl=1, backwards=False, startat=0, unfreeze=True,
lr=0.01, dropmult=1.0, bpe=False, use_clr=True,
use_regular_schedule=False, use_discriminative=True, last=False, chain_thaw=False,
from_scratch=False, train_file_id=''):
print(f'dir_path {dir_path}; cuda_id {cuda_id}; lm_id {lm_id}; clas_id {clas_id}; bs {bs}; cl {cl}; backwards {backwards}; '
f'dropmult {dropmult} unfreeze {unfreeze} startat {startat}; bpe {bpe}; use_clr {use_clr};'
f'use_regular_schedule {use_regular_schedule}; use_discriminative {use_discriminative}; last {last};'
f'chain_thaw {chain_thaw}; from_scratch {from_scratch}; train_file_id {train_file_id}')
if not hasattr(torch._C, '_cuda_setDevice'):
print('CUDA not available. Setting device=-1.')
cuda_id = -1
torch.cuda.set_device(cuda_id)
PRE = 'bwd_' if backwards else 'fwd_'
PRE = 'bpe_' + PRE if bpe else PRE
IDS = 'bpe' if bpe else 'ids'
train_file_id = train_file_id if train_file_id == '' else f'_{train_file_id}'
dir_path = Path(dir_path)
lm_id = lm_id if lm_id == '' else f'{lm_id}_'
clas_id = lm_id if clas_id is None else clas_id
clas_id = clas_id if clas_id == '' else f'{clas_id}_'
intermediate_clas_file = f'{PRE}{clas_id}clas_0'
final_clas_file = f'{PRE}{clas_id}clas_1'
lm_file = f'{PRE}{lm_id}lm_enc'
lm_path = dir_path / 'models' / f'{lm_file}.h5'
assert lm_path.exists(), f'Error: {lm_path} does not exist.'
bptt,em_sz,nh,nl = 70,400,1150,3
opt_fn = partial(optim.Adam, betas=(0.8, 0.99))
if backwards:
trn_sent = np.load(dir_path / 'tmp' / f'trn_{IDS}{train_file_id}_bwd.npy')
val_sent = np.load(dir_path / 'tmp' / f'val_{IDS}_bwd.npy')
else:
trn_sent = np.load(dir_path / 'tmp' / f'trn_{IDS}{train_file_id}.npy')
val_sent = np.load(dir_path / 'tmp' / f'val_{IDS}.npy')
trn_lbls = np.load(dir_path / 'tmp' / f'lbl_trn{train_file_id}.npy')
val_lbls = np.load(dir_path / 'tmp' / f'lbl_val.npy')
assert trn_lbls.shape[1] == 1 and val_lbls.shape[1] == 1, 'This classifier uses cross entropy loss and only support single label samples'
trn_lbls = trn_lbls.flatten()
val_lbls = val_lbls.flatten()
trn_lbls -= trn_lbls.min()
val_lbls -= val_lbls.min()
c=int(trn_lbls.max())+1
if bpe: vs=30002
else:
itos = pickle.load(open(dir_path / 'tmp' / 'itos.pkl', 'rb'))
vs = len(itos)
trn_ds = TextDataset(trn_sent, trn_lbls)
val_ds = TextDataset(val_sent, val_lbls)
trn_samp = SortishSampler(trn_sent, key=lambda x: len(trn_sent[x]), bs=bs//2)
val_samp = SortSampler(val_sent, key=lambda x: len(val_sent[x]))
trn_dl = DataLoader(trn_ds, bs//2, transpose=True, num_workers=1, pad_idx=1, sampler=trn_samp)
val_dl = DataLoader(val_ds, bs, transpose=True, num_workers=1, pad_idx=1, sampler=val_samp)
md = ModelData(dir_path, trn_dl, val_dl)
dps = np.array([0.4,0.5,0.05,0.3,0.4])*dropmult
#dps = np.array([0.5, 0.4, 0.04, 0.3, 0.6])*dropmult
#dps = np.array([0.65,0.48,0.039,0.335,0.34])*dropmult
#dps = np.array([0.6,0.5,0.04,0.3,0.4])*dropmult
m = get_rnn_classifier(bptt, 20*70, c, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1,
layers=[em_sz*3, 50, c], drops=[dps[4], 0.1],
dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])
learn = RNN_Learner(md, TextModel(to_gpu(m)), opt_fn=opt_fn)
learn.reg_fn = partial(seq2seq_reg, alpha=2, beta=1)
learn.clip=25.
learn.metrics = [accuracy]
lrm = 2.6
if use_discriminative:
lrs = np.array([lr/(lrm**4), lr/(lrm**3), lr/(lrm**2), lr/lrm, lr])
else:
lrs = lr
wd = 1e-6
if not from_scratch:
learn.load_encoder(lm_file)
else:
print('Training classifier from scratch. LM encoder is not loaded.')
use_regular_schedule = True
if (startat<1) and not last and not chain_thaw and not from_scratch:
learn.freeze_to(-1)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
learn.freeze_to(-2)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8, 3))
learn.save(intermediate_clas_file)
elif startat==1:
learn.load(intermediate_clas_file)
if chain_thaw:
lrs = np.array([0.0001, 0.0001, 0.0001, 0.0001, 0.001])
print('Using chain-thaw. Unfreezing all layers one at a time...')
n_layers = len(learn.get_layer_groups())
print('# of layers:', n_layers)
# fine-tune last layer
learn.freeze_to(-1)
print('Fine-tuning last layer...')
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
n = 0
# fine-tune all layers up to the second-last one
while n < n_layers-1:
print('Fine-tuning layer #%d.' % n)
freeze_all_but(learn, n)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
n += 1
if unfreeze:
learn.unfreeze()
else:
learn.freeze_to(-3)
if last:
print('Fine-tuning only the last layer...')
learn.freeze_to(-1)
if use_regular_schedule:
print('Using regular schedule. Setting use_clr=None, n_cycles=cl, cycle_len=None.')
use_clr = None
n_cycles = cl
cl = None
else:
n_cycles = 1
learn.fit(lrs, n_cycles, wds=wd, cycle_len=cl, use_clr=(8,8) if use_clr else None)
print('Plotting lrs...')
learn.sched.plot_lr()
learn.save(final_clas_file)
if __name__ == '__main__': fire.Fire(train_clas) | courses/dl2/imdb_scripts/train_clas.py | import fire
from fastai.text import *
from fastai.lm_rnn import *
def freeze_all_but(learner, n):
c=learner.get_layer_groups()
for l in c: set_trainable(l, False)
set_trainable(c[n], True)
def train_clas(dir_path, cuda_id, lm_id='', clas_id=None, bs=64, cl=1, backwards=False, startat=0, unfreeze=True,
lr=0.01, dropmult=1.0, bpe=False, use_clr=True,
use_regular_schedule=False, use_discriminative=True, last=False, chain_thaw=False,
from_scratch=False, train_file_id=''):
print(f'dir_path {dir_path}; cuda_id {cuda_id}; lm_id {lm_id}; clas_id {clas_id}; bs {bs}; cl {cl}; backwards {backwards}; '
f'dropmult {dropmult} unfreeze {unfreeze} startat {startat}; bpe {bpe}; use_clr {use_clr};'
f'use_regular_schedule {use_regular_schedule}; use_discriminative {use_discriminative}; last {last};'
f'chain_thaw {chain_thaw}; from_scratch {from_scratch}; train_file_id {train_file_id}')
if not hasattr(torch._C, '_cuda_setDevice'):
print('CUDA not available. Setting device=-1.')
cuda_id = -1
torch.cuda.set_device(cuda_id)
PRE = 'bwd_' if backwards else 'fwd_'
PRE = 'bpe_' + PRE if bpe else PRE
IDS = 'bpe' if bpe else 'ids'
train_file_id = train_file_id if train_file_id == '' else f'_{train_file_id}'
dir_path = Path(dir_path)
lm_id = lm_id if lm_id == '' else f'{lm_id}_'
clas_id = lm_id if clas_id is None else clas_id
clas_id = clas_id if clas_id == '' else f'{clas_id}_'
intermediate_clas_file = f'{PRE}{clas_id}clas_0'
final_clas_file = f'{PRE}{clas_id}clas_1'
lm_file = f'{PRE}{lm_id}lm_enc'
lm_path = dir_path / 'models' / f'{lm_file}.h5'
assert lm_path.exists(), f'Error: {lm_path} does not exist.'
bptt,em_sz,nh,nl = 70,400,1150,3
opt_fn = partial(optim.Adam, betas=(0.8, 0.99))
if backwards:
trn_sent = np.load(dir_path / 'tmp' / f'trn_{IDS}{train_file_id}_bwd.npy')
val_sent = np.load(dir_path / 'tmp' / f'val_{IDS}_bwd.npy')
else:
trn_sent = np.load(dir_path / 'tmp' / f'trn_{IDS}{train_file_id}.npy')
val_sent = np.load(dir_path / 'tmp' / f'val_{IDS}.npy')
trn_lbls = np.load(dir_path / 'tmp' / f'lbl_trn{train_file_id}.npy')
val_lbls = np.load(dir_path / 'tmp' / f'lbl_val.npy')
assert trn_lbls.shape[1] == 1 and val_lbls.shape[1] == 1, 'This classifier uses cross entropy loss and only support single label samples'
trn_lbls = trn_lbls.flatten()
val_lbls = val_lbls.flatten()
trn_lbls -= trn_lbls.min()
val_lbls -= val_lbls.min()
c=int(trn_lbls.max())+1
if bpe: vs=30002
else:
itos = pickle.load(open(dir_path / 'tmp' / 'itos.pkl', 'rb'))
vs = len(itos)
trn_ds = TextDataset(trn_sent, trn_lbls)
val_ds = TextDataset(val_sent, val_lbls)
trn_samp = SortishSampler(trn_sent, key=lambda x: len(trn_sent[x]), bs=bs//2)
val_samp = SortSampler(val_sent, key=lambda x: len(val_sent[x]))
trn_dl = DataLoader(trn_ds, bs//2, transpose=True, num_workers=1, pad_idx=1, sampler=trn_samp)
val_dl = DataLoader(val_ds, bs, transpose=True, num_workers=1, pad_idx=1, sampler=val_samp)
md = ModelData(dir_path, trn_dl, val_dl)
dps = np.array([0.4,0.5,0.05,0.3,0.4])*dropmult
#dps = np.array([0.5, 0.4, 0.04, 0.3, 0.6])*dropmult
#dps = np.array([0.65,0.48,0.039,0.335,0.34])*dropmult
#dps = np.array([0.6,0.5,0.04,0.3,0.4])*dropmult
m = get_rnn_classifier(bptt, 20*70, c, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1,
layers=[em_sz*3, 50, c], drops=[dps[4], 0.1],
dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])
learn = RNN_Learner(md, TextModel(to_gpu(m)), opt_fn=opt_fn)
learn.reg_fn = partial(seq2seq_reg, alpha=2, beta=1)
learn.clip=25.
learn.metrics = [accuracy]
lrm = 2.6
if use_discriminative:
lrs = np.array([lr/(lrm**4), lr/(lrm**3), lr/(lrm**2), lr/lrm, lr])
else:
lrs = lr
wd = 1e-6
if not from_scratch:
learn.load_encoder(lm_file)
else:
print('Training classifier from scratch. LM encoder is not loaded.')
use_regular_schedule = True
if (startat<1) and not last and not chain_thaw and not from_scratch:
learn.freeze_to(-1)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
learn.freeze_to(-2)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8, 3))
learn.save(intermediate_clas_file)
elif startat==1:
learn.load(intermediate_clas_file)
if chain_thaw:
lrs = np.array([0.0001, 0.0001, 0.0001, 0.0001, 0.001])
print('Using chain-thaw. Unfreezing all layers one at a time...')
n_layers = len(learn.get_layer_groups())
print('# of layers:', n_layers)
# fine-tune last layer
learn.freeze_to(-1)
print('Fine-tuning last layer...')
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
n = 0
# fine-tune all layers up to the second-last one
while n < n_layers-1:
print('Fine-tuning layer #%d.' % n)
freeze_all_but(learn, n)
learn.fit(lrs, 1, wds=wd, cycle_len=None if use_regular_schedule else 1,
use_clr=None if use_regular_schedule or not use_clr else (8,3))
n += 1
if unfreeze:
learn.unfreeze()
else:
learn.freeze_to(-3)
if last:
print('Fine-tuning only the last layer...')
learn.freeze_to(-1)
if use_regular_schedule:
print('Using regular schedule. Setting use_clr=None, n_cycles=cl, cycle_len=None.')
use_clr = None
n_cycles = cl
cl = None
else:
n_cycles = 1
learn.fit(lrs, n_cycles, wds=wd, cycle_len=cl, use_clr=(8,8) if use_clr else None)
print('Plotting lrs...')
learn.sched.plot_lr()
learn.save(final_clas_file)
if __name__ == '__main__': fire.Fire(train_clas) | 0.276788 | 0.157979 |
"""Affine Scalar Tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.internal import test_case
from tensorflow_probability.python.internal import test_util as tfp_test_util
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import
@test_util.run_all_in_graph_and_eager_modes
class _AffineScalarBijectorTest(object):
"""Tests correctness of the Y = scale @ x + shift transformation."""
def testProperties(self):
# scale corresponds to 1.
bijector = tfb.AffineScalar(shift=-1.)
self.assertStartsWith(bijector.name, "affine_scalar")
def testTinyScale(self):
log_scale = tf.cast(-2000., self.dtype)
x = tf.cast(1., self.dtype)
scale = tf.exp(log_scale)
fldj_linear = tfb.AffineScalar(scale=scale).forward_log_det_jacobian(
x, event_ndims=0)
fldj_log = tfb.AffineScalar(log_scale=log_scale).forward_log_det_jacobian(
x, event_ndims=0)
fldj_linear_, fldj_log_ = self.evaluate([fldj_linear, fldj_log])
# Using the linear scale will saturate to 0, and produce bad log-det
# Jacobians.
self.assertNotEqual(fldj_linear_, fldj_log_)
self.assertAllClose(-2000., fldj_log_)
def testNoBatchScalar(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
bijector = tfb.AffineScalar(shift=self.dtype(-1.), scale=self.dtype(2.))
x = self.dtype([1., 2, 3]) # Three scalar samples (no batches).
self.assertAllClose([1., 3, 5], run(bijector.forward, x))
self.assertAllClose([1., 1.5, 2.], run(bijector.inverse, x))
self.assertAllClose(
-np.log(2.),
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testOneBatchScalarViaIdentityUserProvidesShiftOnly(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batched shift
bijector = tfb.AffineScalar(shift=self.dtype([1.]))
x = self.dtype([1.]) # One sample from one batches.
self.assertAllClose([2.], run(bijector.forward, x))
self.assertAllClose([0.], run(bijector.inverse, x))
self.assertAllClose(
0.,
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testOneBatchScalarViaIdentityUserProvidesScaleOnly(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batched scale
bijector = tfb.AffineScalar(scale=self.dtype([2.]))
x = self.dtype([1.]) # One sample from one batches.
self.assertAllClose([2.], run(bijector.forward, x))
self.assertAllClose([0.5], run(bijector.inverse, x))
self.assertAllClose(
[np.log(0.5)],
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testTwoBatchScalarIdentityViaIdentity(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batch of 2 shifts
bijector = tfb.AffineScalar(shift=self.dtype([1., -1]))
x = self.dtype([1., 1]) # One sample from each of two batches.
self.assertAllClose([2., 0], run(bijector.forward, x))
self.assertAllClose([0., 2], run(bijector.inverse, x))
self.assertAllClose(
0.,
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testTwoBatchScalarIdentityViaScale(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batch of 2 scales and 2 shifts
bijector = tfb.AffineScalar(
shift=self.dtype([1., -1]),
scale=self.dtype([2., 1]))
x = self.dtype([1., 1]) # One sample from each of two batches.
self.assertAllClose([3., 0], run(bijector.forward, x))
self.assertAllClose([0., 2], run(bijector.inverse, x))
self.assertAllClose(
[-np.log(2), 0.],
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testScalarCongruency(self):
bijector = tfb.AffineScalar(shift=self.dtype(3.6), scale=self.dtype(0.42))
bijector_test_util.assert_scalar_congruency(
bijector,
lower_x=self.dtype(-2.),
upper_x=self.dtype(2.),
eval_func=self.evaluate)
def testScalarCongruencyLogScale(self):
bijector = tfb.AffineScalar(
shift=self.dtype(3.6), log_scale=self.dtype(np.log(0.42)))
bijector_test_util.assert_scalar_congruency(
bijector,
lower_x=self.dtype(-2.),
upper_x=self.dtype(2.),
eval_func=self.evaluate)
@tfp_test_util.jax_disable_variable_test
def testVariableGradients(self):
b = tfb.AffineScalar(
shift=tf.Variable(1.),
scale=tf.Variable(2.))
with tf.GradientTape() as tape:
y = b.forward(.1)
self.assertAllNotNone(tape.gradient(y, [b.shift, b.scale]))
def testImmutableScaleAssertion(self):
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
b = tfb.AffineScalar(scale=0., validate_args=True)
_ = self.evaluate(b.forward(1.))
def testVariableScaleAssertion(self):
v = tf.Variable(0.)
self.evaluate(v.initializer)
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
b = tfb.AffineScalar(scale=v, validate_args=True)
_ = self.evaluate(b.forward(1.))
def testModifiedVariableScaleAssertion(self):
v = tf.Variable(1.)
self.evaluate(v.initializer)
b = tfb.AffineScalar(scale=v, validate_args=True)
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
with tf.control_dependencies([v.assign(0.)]):
_ = self.evaluate(b.forward(1.))
class AffineScalarBijectorTestFloat32(test_case.TestCase,
_AffineScalarBijectorTest):
dtype = np.float32
class AffineScalarBijectorTestFloat64(test_case.TestCase,
_AffineScalarBijectorTest):
dtype = np.float64
if __name__ == "__main__":
tf.test.main() | tensorflow_probability/python/bijectors/affine_scalar_test.py | """Affine Scalar Tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v1 as tf1
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.internal import test_case
from tensorflow_probability.python.internal import test_util as tfp_test_util
from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import
@test_util.run_all_in_graph_and_eager_modes
class _AffineScalarBijectorTest(object):
"""Tests correctness of the Y = scale @ x + shift transformation."""
def testProperties(self):
# scale corresponds to 1.
bijector = tfb.AffineScalar(shift=-1.)
self.assertStartsWith(bijector.name, "affine_scalar")
def testTinyScale(self):
log_scale = tf.cast(-2000., self.dtype)
x = tf.cast(1., self.dtype)
scale = tf.exp(log_scale)
fldj_linear = tfb.AffineScalar(scale=scale).forward_log_det_jacobian(
x, event_ndims=0)
fldj_log = tfb.AffineScalar(log_scale=log_scale).forward_log_det_jacobian(
x, event_ndims=0)
fldj_linear_, fldj_log_ = self.evaluate([fldj_linear, fldj_log])
# Using the linear scale will saturate to 0, and produce bad log-det
# Jacobians.
self.assertNotEqual(fldj_linear_, fldj_log_)
self.assertAllClose(-2000., fldj_log_)
def testNoBatchScalar(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
bijector = tfb.AffineScalar(shift=self.dtype(-1.), scale=self.dtype(2.))
x = self.dtype([1., 2, 3]) # Three scalar samples (no batches).
self.assertAllClose([1., 3, 5], run(bijector.forward, x))
self.assertAllClose([1., 1.5, 2.], run(bijector.inverse, x))
self.assertAllClose(
-np.log(2.),
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testOneBatchScalarViaIdentityUserProvidesShiftOnly(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batched shift
bijector = tfb.AffineScalar(shift=self.dtype([1.]))
x = self.dtype([1.]) # One sample from one batches.
self.assertAllClose([2.], run(bijector.forward, x))
self.assertAllClose([0.], run(bijector.inverse, x))
self.assertAllClose(
0.,
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testOneBatchScalarViaIdentityUserProvidesScaleOnly(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batched scale
bijector = tfb.AffineScalar(scale=self.dtype([2.]))
x = self.dtype([1.]) # One sample from one batches.
self.assertAllClose([2.], run(bijector.forward, x))
self.assertAllClose([0.5], run(bijector.inverse, x))
self.assertAllClose(
[np.log(0.5)],
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testTwoBatchScalarIdentityViaIdentity(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batch of 2 shifts
bijector = tfb.AffineScalar(shift=self.dtype([1., -1]))
x = self.dtype([1., 1]) # One sample from each of two batches.
self.assertAllClose([2., 0], run(bijector.forward, x))
self.assertAllClose([0., 2], run(bijector.inverse, x))
self.assertAllClose(
0.,
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testTwoBatchScalarIdentityViaScale(self):
def static_run(fun, x, **kwargs):
return self.evaluate(fun(x, **kwargs))
def dynamic_run(fun, x_value, **kwargs):
x_value = np.array(x_value, dtype=self.dtype)
x = tf1.placeholder_with_default(x_value, shape=None)
return self.evaluate(fun(x, **kwargs))
for run in (static_run, dynamic_run):
# Batch of 2 scales and 2 shifts
bijector = tfb.AffineScalar(
shift=self.dtype([1., -1]),
scale=self.dtype([2., 1]))
x = self.dtype([1., 1]) # One sample from each of two batches.
self.assertAllClose([3., 0], run(bijector.forward, x))
self.assertAllClose([0., 2], run(bijector.inverse, x))
self.assertAllClose(
[-np.log(2), 0.],
run(bijector.inverse_log_det_jacobian, x, event_ndims=0))
def testScalarCongruency(self):
bijector = tfb.AffineScalar(shift=self.dtype(3.6), scale=self.dtype(0.42))
bijector_test_util.assert_scalar_congruency(
bijector,
lower_x=self.dtype(-2.),
upper_x=self.dtype(2.),
eval_func=self.evaluate)
def testScalarCongruencyLogScale(self):
bijector = tfb.AffineScalar(
shift=self.dtype(3.6), log_scale=self.dtype(np.log(0.42)))
bijector_test_util.assert_scalar_congruency(
bijector,
lower_x=self.dtype(-2.),
upper_x=self.dtype(2.),
eval_func=self.evaluate)
@tfp_test_util.jax_disable_variable_test
def testVariableGradients(self):
b = tfb.AffineScalar(
shift=tf.Variable(1.),
scale=tf.Variable(2.))
with tf.GradientTape() as tape:
y = b.forward(.1)
self.assertAllNotNone(tape.gradient(y, [b.shift, b.scale]))
def testImmutableScaleAssertion(self):
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
b = tfb.AffineScalar(scale=0., validate_args=True)
_ = self.evaluate(b.forward(1.))
def testVariableScaleAssertion(self):
v = tf.Variable(0.)
self.evaluate(v.initializer)
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
b = tfb.AffineScalar(scale=v, validate_args=True)
_ = self.evaluate(b.forward(1.))
def testModifiedVariableScaleAssertion(self):
v = tf.Variable(1.)
self.evaluate(v.initializer)
b = tfb.AffineScalar(scale=v, validate_args=True)
with self.assertRaisesOpError("Argument `scale` must be non-zero"):
with tf.control_dependencies([v.assign(0.)]):
_ = self.evaluate(b.forward(1.))
class AffineScalarBijectorTestFloat32(test_case.TestCase,
_AffineScalarBijectorTest):
dtype = np.float32
class AffineScalarBijectorTestFloat64(test_case.TestCase,
_AffineScalarBijectorTest):
dtype = np.float64
if __name__ == "__main__":
tf.test.main() | 0.91571 | 0.538437 |
import os
import glob
import json
import tqdm
import pickle
import functools
from indra.sources import eidos
from read_pmids import OUTPUT_PATH
from indra.tools import assemble_corpus as ac
from indra.assemblers.html import HtmlAssembler
def fix_provenance(stmts, pmid):
for stmt in stmts:
for ev in stmt.evidence:
ev.pmid = pmid
ev.text_refs['PMID'] = pmid
def process_file(fname, grounder):
pmid = os.path.splitext(os.path.basename(fname))[0]
with open(fname, 'r') as fh:
jd = json.load(fh)
ep = eidos.process_json_bio(json_dict=jd, grounder=grounder)
stmts = ep.statements
fix_provenance(stmts, pmid)
return stmts
def get_custom_grounder():
from gilda.grounder import Grounder
from gilda.grounder import load_terms_file
from gilda.resources import get_grounding_terms
from gilda.generate_terms import terms_from_obo_url
conso_terms = terms_from_obo_url(
'https://raw.githubusercontent.com/pharmacome/conso/master/export/'
'conso.obo',
prefix='conso')
terms = load_terms_file(get_grounding_terms())
for term in conso_terms:
try:
terms[term.norm_text].append(term)
except KeyError:
terms[term.norm_text] = [term]
gr = Grounder(terms)
return functools.partial(grounder_wrapper,
grounder=gr)
def grounder_wrapper(text, context, grounder):
matches = grounder.ground(text, context)
if not matches:
return {}
else:
return {matches[0].term.db: matches[0].term.id}
if __name__ == '__main__':
version = 'v1'
output_fname = os.path.join(OUTPUT_PATH, f'eidos_{version}.pkl')
fnames = glob.glob(os.path.join(OUTPUT_PATH, '*.jsonld'))
all_stmts = []
grounder = get_custom_grounder()
for fname in tqdm.tqdm(fnames):
stmts = process_file(fname, grounder=grounder)
all_stmts += stmts
stmts = ac.map_grounding(all_stmts)
stmts = ac.run_preassembly(stmts)
with open(output_fname, 'wb') as fh:
pickle.dump(stmts, fh)
ha = HtmlAssembler(stmts)
ha.save_model(os.path.join(OUTPUT_PATH, f'eidos_{version}.html')) | eidos/process_output.py | import os
import glob
import json
import tqdm
import pickle
import functools
from indra.sources import eidos
from read_pmids import OUTPUT_PATH
from indra.tools import assemble_corpus as ac
from indra.assemblers.html import HtmlAssembler
def fix_provenance(stmts, pmid):
for stmt in stmts:
for ev in stmt.evidence:
ev.pmid = pmid
ev.text_refs['PMID'] = pmid
def process_file(fname, grounder):
pmid = os.path.splitext(os.path.basename(fname))[0]
with open(fname, 'r') as fh:
jd = json.load(fh)
ep = eidos.process_json_bio(json_dict=jd, grounder=grounder)
stmts = ep.statements
fix_provenance(stmts, pmid)
return stmts
def get_custom_grounder():
from gilda.grounder import Grounder
from gilda.grounder import load_terms_file
from gilda.resources import get_grounding_terms
from gilda.generate_terms import terms_from_obo_url
conso_terms = terms_from_obo_url(
'https://raw.githubusercontent.com/pharmacome/conso/master/export/'
'conso.obo',
prefix='conso')
terms = load_terms_file(get_grounding_terms())
for term in conso_terms:
try:
terms[term.norm_text].append(term)
except KeyError:
terms[term.norm_text] = [term]
gr = Grounder(terms)
return functools.partial(grounder_wrapper,
grounder=gr)
def grounder_wrapper(text, context, grounder):
matches = grounder.ground(text, context)
if not matches:
return {}
else:
return {matches[0].term.db: matches[0].term.id}
if __name__ == '__main__':
version = 'v1'
output_fname = os.path.join(OUTPUT_PATH, f'eidos_{version}.pkl')
fnames = glob.glob(os.path.join(OUTPUT_PATH, '*.jsonld'))
all_stmts = []
grounder = get_custom_grounder()
for fname in tqdm.tqdm(fnames):
stmts = process_file(fname, grounder=grounder)
all_stmts += stmts
stmts = ac.map_grounding(all_stmts)
stmts = ac.run_preassembly(stmts)
with open(output_fname, 'wb') as fh:
pickle.dump(stmts, fh)
ha = HtmlAssembler(stmts)
ha.save_model(os.path.join(OUTPUT_PATH, f'eidos_{version}.html')) | 0.247623 | 0.075653 |
from rlkit.envs.multitask.point2d import MultitaskImagePoint2DEnv
from rlkit.envs.multitask.pusher2d import FullPusher2DEnv
from rlkit.launchers.arglauncher import run_variants
import rlkit.misc.hyperparameter as hyp
from rlkit.torch.vae.relabeled_vae_experiment import experiment
if __name__ == "__main__":
# noinspection PyTypeChecker
vae_paths = {
"4": "ashvin/vae/new-pusher2d/run11/id0/itr_1000.pkl",
"8": "ashvin/vae/new-pusher2d/run11/id1/itr_1000.pkl",
"16": "ashvin/vae/new-pusher2d/run11/id2/itr_1000.pkl",
"32": "ashvin/vae/new-pusher2d/run11/id3/itr_1000.pkl"
}
variant = dict(
algo_kwargs=dict(
num_epochs=505,
num_steps_per_epoch=1000,
num_steps_per_eval=1000,
tau=1e-2,
batch_size=128,
max_path_length=100,
discount=0.99,
# qf_learning_rate=1e-3,
# policy_learning_rate=1e-4,
),
env_kwargs=dict(
include_puck=True,
arm_range=0.1,
use_big_red_puck=True,
reward_params=dict(
type="sparse",
epsilon=0.2,
# puck_reward_only=True,
),
),
replay_kwargs=dict(
fraction_goals_are_rollout_goals=0.2,
fraction_goals_are_env_goals=0.5,
),
algorithm='TD3',
normalize=False,
rdim=4,
render=False,
env=FullPusher2DEnv,
use_env_goals=True,
vae_paths=vae_paths,
wrap_mujoco_env=True,
do_state_based_exp=False,
exploration_noise=0.1,
)
n_seeds = 3
search_space = {
'exploration_type': [
'ou',
],
'env_kwargs.arm_range': [0.5],
'env_kwargs.reward_params.epsilon': [0.5],
'algo_kwargs.num_updates_per_env_step': [1, 4],
'algo_kwargs.discount': [0.99],
'replay_kwargs.fraction_goals_are_env_goals': [0.5,],
'replay_kwargs.fraction_goals_are_rollout_goals': [0.2,],
'exploration_noise': [0.2],
'algo_kwargs.reward_scale': [1e-4],
'training_mode': ['train', ],
'testing_mode': ['test', ],
'rdim': [4, 8, 16, 32],
'seedid': range(n_seeds),
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
)
run_variants(experiment, sweeper.iterate_hyperparameters(), run_id=1) | experiments/ashvin/vae/fixed3/pusher2d/vae_dense3.py | from rlkit.envs.multitask.point2d import MultitaskImagePoint2DEnv
from rlkit.envs.multitask.pusher2d import FullPusher2DEnv
from rlkit.launchers.arglauncher import run_variants
import rlkit.misc.hyperparameter as hyp
from rlkit.torch.vae.relabeled_vae_experiment import experiment
if __name__ == "__main__":
# noinspection PyTypeChecker
vae_paths = {
"4": "ashvin/vae/new-pusher2d/run11/id0/itr_1000.pkl",
"8": "ashvin/vae/new-pusher2d/run11/id1/itr_1000.pkl",
"16": "ashvin/vae/new-pusher2d/run11/id2/itr_1000.pkl",
"32": "ashvin/vae/new-pusher2d/run11/id3/itr_1000.pkl"
}
variant = dict(
algo_kwargs=dict(
num_epochs=505,
num_steps_per_epoch=1000,
num_steps_per_eval=1000,
tau=1e-2,
batch_size=128,
max_path_length=100,
discount=0.99,
# qf_learning_rate=1e-3,
# policy_learning_rate=1e-4,
),
env_kwargs=dict(
include_puck=True,
arm_range=0.1,
use_big_red_puck=True,
reward_params=dict(
type="sparse",
epsilon=0.2,
# puck_reward_only=True,
),
),
replay_kwargs=dict(
fraction_goals_are_rollout_goals=0.2,
fraction_goals_are_env_goals=0.5,
),
algorithm='TD3',
normalize=False,
rdim=4,
render=False,
env=FullPusher2DEnv,
use_env_goals=True,
vae_paths=vae_paths,
wrap_mujoco_env=True,
do_state_based_exp=False,
exploration_noise=0.1,
)
n_seeds = 3
search_space = {
'exploration_type': [
'ou',
],
'env_kwargs.arm_range': [0.5],
'env_kwargs.reward_params.epsilon': [0.5],
'algo_kwargs.num_updates_per_env_step': [1, 4],
'algo_kwargs.discount': [0.99],
'replay_kwargs.fraction_goals_are_env_goals': [0.5,],
'replay_kwargs.fraction_goals_are_rollout_goals': [0.2,],
'exploration_noise': [0.2],
'algo_kwargs.reward_scale': [1e-4],
'training_mode': ['train', ],
'testing_mode': ['test', ],
'rdim': [4, 8, 16, 32],
'seedid': range(n_seeds),
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
)
run_variants(experiment, sweeper.iterate_hyperparameters(), run_id=1) | 0.511229 | 0.305892 |
import sys
import time
from functools import partial
from PySide import QtGui
import harmony.session
import harmony.ui.widget.factory
import harmony.ui.error_tree
import harmony.ui.publisher
class Publisher(harmony.ui.publisher.Publisher):
'''Customised publisher.'''
def _publish(self, instance):
'''Perform publish.'''
for index in range(5):
time.sleep(1)
return instance
class Factory(harmony.ui.widget.factory.Factory):
'''Customised widget factory.'''
def __init__(self, *args, **kw):
self.project_tree = {}
for show_key in ('show_a', 'show_b'):
show = self.project_tree.setdefault(show_key, {})
scenes = show['scenes'] = {}
assets = show['assets'] = {}
for scene_key in ('sc001', 'sc002', 'sc003'):
scene = scenes[scene_key] = {}
shots = scene['shots'] = {}
for shot_key in ('001', '002', '003', '004'):
shot = shots[shot_key] = {}
shot['assets'] = {}
if show_key == 'show_a':
for asset_key in ('astronaut', 'space_station'):
assets[asset_key] = {}
elif show_key == 'show_b':
for asset_key in ('dinosaur', 'amber', 'scientist'):
assets[asset_key] = {}
super(Factory, self).__init__(*args, **kw)
def _query_users(self):
'''Return a list of valid users.'''
users = [
{'firstname': 'Martin', 'lastname': 'Pengelly-Phillips',
'email': '<EMAIL>', 'username': 'martin'},
{'firstname': 'Joe', 'lastname': 'Blogs',
'email': '<EMAIL>', 'username': 'joe'}
]
return map(partial(self.session.instantiate, 'harmony:/user'), users)
def _query_scopes(self, scope, domain=None):
'''Return list of entries for *scope* using *domain*.'''
scopes = []
if domain is None:
domain = {}
if scope == 'show':
shows = sorted(self.project_tree.keys())
for show in shows:
scopes.append({
'name': show.replace('_', ' ').title(),
'id': show
})
elif scope == 'scene':
show_id = domain.get('show', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = sorted(show.get('scenes', {}).keys())
for scene in scenes:
scopes.append({
'name': scene.replace('_', ' ').title(),
'id': scene
})
elif scope == 'shot':
show_id = domain.get('show', {}).get('id')
scene_id = domain.get('scene', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = show.get('scenes', {})
scene = scenes.get(scene_id, {})
shots = sorted(scene.get('shots', {}).keys())
for shot in shots:
scopes.append({
'name': shot.replace('_', ' ').title(),
'id': shot
})
elif scope == 'asset':
show_id = domain.get('show', {}).get('id')
scene_id = domain.get('scene', {}).get('id')
shot_id = domain.get('shot', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = show.get('scenes', {})
scene = scenes.get(scene_id, {})
shots = scene.get('shots', {})
shot = shots.get(shot_id)
if shot:
assets = shot.get('assets', {}).keys()
else:
assets = show.get('assets', {}).keys()
for asset in assets:
scopes.append({
'name': asset.replace('_', ' ').title(),
'id': asset
})
return map(
partial(
self.session.instantiate, 'harmony:/scope/{0}'.format(scope)
),
scopes
)
def main(arguments=None):
'''Interactive test of dynamic UI building from schema.'''
if arguments is None:
arguments = sys.argv
application = QtGui.QApplication(arguments)
session = harmony.session.Session()
factory = Factory(session)
dialog = Publisher(session, factory)
dialog.resize(600, 800)
dialog.show()
value = dialog.value()
value['note'] = 'Hello world!'
dialog.setValue(value)
sys.exit(application.exec_())
if __name__ == '__main__':
raise SystemExit(main()) | test/interactive/publisher.py |
import sys
import time
from functools import partial
from PySide import QtGui
import harmony.session
import harmony.ui.widget.factory
import harmony.ui.error_tree
import harmony.ui.publisher
class Publisher(harmony.ui.publisher.Publisher):
'''Customised publisher.'''
def _publish(self, instance):
'''Perform publish.'''
for index in range(5):
time.sleep(1)
return instance
class Factory(harmony.ui.widget.factory.Factory):
'''Customised widget factory.'''
def __init__(self, *args, **kw):
self.project_tree = {}
for show_key in ('show_a', 'show_b'):
show = self.project_tree.setdefault(show_key, {})
scenes = show['scenes'] = {}
assets = show['assets'] = {}
for scene_key in ('sc001', 'sc002', 'sc003'):
scene = scenes[scene_key] = {}
shots = scene['shots'] = {}
for shot_key in ('001', '002', '003', '004'):
shot = shots[shot_key] = {}
shot['assets'] = {}
if show_key == 'show_a':
for asset_key in ('astronaut', 'space_station'):
assets[asset_key] = {}
elif show_key == 'show_b':
for asset_key in ('dinosaur', 'amber', 'scientist'):
assets[asset_key] = {}
super(Factory, self).__init__(*args, **kw)
def _query_users(self):
'''Return a list of valid users.'''
users = [
{'firstname': 'Martin', 'lastname': 'Pengelly-Phillips',
'email': '<EMAIL>', 'username': 'martin'},
{'firstname': 'Joe', 'lastname': 'Blogs',
'email': '<EMAIL>', 'username': 'joe'}
]
return map(partial(self.session.instantiate, 'harmony:/user'), users)
def _query_scopes(self, scope, domain=None):
'''Return list of entries for *scope* using *domain*.'''
scopes = []
if domain is None:
domain = {}
if scope == 'show':
shows = sorted(self.project_tree.keys())
for show in shows:
scopes.append({
'name': show.replace('_', ' ').title(),
'id': show
})
elif scope == 'scene':
show_id = domain.get('show', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = sorted(show.get('scenes', {}).keys())
for scene in scenes:
scopes.append({
'name': scene.replace('_', ' ').title(),
'id': scene
})
elif scope == 'shot':
show_id = domain.get('show', {}).get('id')
scene_id = domain.get('scene', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = show.get('scenes', {})
scene = scenes.get(scene_id, {})
shots = sorted(scene.get('shots', {}).keys())
for shot in shots:
scopes.append({
'name': shot.replace('_', ' ').title(),
'id': shot
})
elif scope == 'asset':
show_id = domain.get('show', {}).get('id')
scene_id = domain.get('scene', {}).get('id')
shot_id = domain.get('shot', {}).get('id')
show = self.project_tree.get(show_id, {})
scenes = show.get('scenes', {})
scene = scenes.get(scene_id, {})
shots = scene.get('shots', {})
shot = shots.get(shot_id)
if shot:
assets = shot.get('assets', {}).keys()
else:
assets = show.get('assets', {}).keys()
for asset in assets:
scopes.append({
'name': asset.replace('_', ' ').title(),
'id': asset
})
return map(
partial(
self.session.instantiate, 'harmony:/scope/{0}'.format(scope)
),
scopes
)
def main(arguments=None):
'''Interactive test of dynamic UI building from schema.'''
if arguments is None:
arguments = sys.argv
application = QtGui.QApplication(arguments)
session = harmony.session.Session()
factory = Factory(session)
dialog = Publisher(session, factory)
dialog.resize(600, 800)
dialog.show()
value = dialog.value()
value['note'] = 'Hello world!'
dialog.setValue(value)
sys.exit(application.exec_())
if __name__ == '__main__':
raise SystemExit(main()) | 0.422981 | 0.218357 |
#!/usr/bin/env pythons
class CONF:
def __init__(self):
self.TABLE_NAME = 'table_name'
self.TABLET_NUM = 'tablet_number'
self.KEY_SIZE = 'key_size(B)' # Bytes
self.VALUE_SIZE = 'value_sizeB(B)' # Bytes
self.KEY_SEED = 'key_seed'
self.VALUE_SEED = 'value_seed'
self.STEP = 'step'
self.ENTRY_SIZE = 'entry_size(B)' # Bytes
self.ENTRY_NUM = 'entry_number(M)' # MB
self.LG_NUM = 'lg_number'
self.CF_NUM = 'cf_number'
self.CF = 'cf'
self.KV = 'kv_mode'
self.WRITE_SPEED_LIMIT = 'write_speed_limit(M)'
self.READ_SPEED_LIMIT = 'read_speed_limit(Qps)'
self.MODE_SEQ_WRITE = 'sw'
self.MODE_RAND_WRITE = 'rw'
self.MODE_READ = 'r'
self.MODE_SCAN = 's'
self.MODE = 'mode'
self.SCAN_BUFFER = 'scan_buffer(M)'
self.TERA_BENCH = ''
self.SPLIT_SIZE = 'split_size'
self.SCHEMA = 'table_schema'
self.g_speed_limit = 0
self.g_datasize = 0
self.g_web_report = True
self.g_web_report_type = ''
self.TS_NUMBER = 'ts_number'
self.g_test_conf = {self.TABLE_NAME: '', self.TABLET_NUM: 0, self.KEY_SIZE: 20, self.VALUE_SIZE: 1024,
self.KEY_SEED: '', self.VALUE_SEED: '', self.STEP: 'False',
self.ENTRY_SIZE: 20 + 1024, self.ENTRY_NUM: 0, self.LG_NUM: 0, self.CF_NUM: 1, self.CF: '',
self.KV: None, self.WRITE_SPEED_LIMIT: 0, self.READ_SPEED_LIMIT: 0, self.MODE: '',
self.SCAN_BUFFER: 0, self.TS_NUMBER: 0, self.SPLIT_SIZE: 0, self.SCHEMA: ''}
conf = CONF()
class Stat:
def __init__(self):
self.READY = 'kReady'
self.OFFLINE = 'kOffLine'
self.ONKICK = 'kOnKick'
self.WAITKICK = 'kWaitKick'
self.TS_STATUS_KEYS = [self.READY, self.OFFLINE, self.ONKICK, self.WAITKICK]
self.T_TOTAL = 'tablet_total'
self.T_BUSY = 'tablet_onbusy'
self.T_SPLIT = 'tablet_onsplit'
self.T_LOAD = 'tablet_onload'
self.SCAN = 'scan_size'
self.WRITE = 'write_size'
self.READ_SIZE = 'read_size'
self.READ_ROWS = 'read_rows'
self.READ_DELAY = 'rand_read_delay'
self.DFS_READ = 'dfs_io_r'
self.DFS_WRITE = 'dfs_io_w'
self.LOCAL_READ = 'local_io_r'
self.LOCAL_WRITE = 'local_io_w'
self.CPU = 'cpu_usage'
self.MEM = 'mem_used'
self.STAT_KEYS = [self.T_TOTAL, self.T_BUSY, self.T_SPLIT, self.T_LOAD, self.SCAN, self.WRITE, self.READ_SIZE,
self.READ_ROWS, self.DFS_READ, self.READ_DELAY, self.DFS_WRITE, self.LOCAL_READ,
self.LOCAL_WRITE, self.CPU, self.MEM]
self.ACCUMULATE_PART = [self.SCAN, self.WRITE, self.READ_SIZE, self.READ_ROWS, self.DFS_READ, self.READ_DELAY,
self.DFS_WRITE, self.LOCAL_READ, self.LOCAL_WRITE, self.CPU, self.MEM]
self.RATIO_PART = [self.T_BUSY, self.T_SPLIT, self.T_LOAD]
self.WRITE_AMP = 'write_amplification'
self.READ_AMP = 'read_amplification'
self.SCAN_AMP = 'scan_amplification'
self.g_ts_status = {}
for item in self.TS_STATUS_KEYS:
self.g_ts_status.update({item: 0})
self.g_stat = {}
for item in self.STAT_KEYS:
self.g_stat.update({item: 0})
stat = Stat()
class Common:
def __init__(self):
self.TERACLI = './teracli --flagfile=../conf/tera.flag'
self.TERAMO = './teramo'
self.TMP_DIR = '../tmp/'
self.CREATE = 'create'
self.DROP = 'drop'
self.QUERY_INTERVAL = 20
self.REPORT_INTERVAL = 10 * 60 * 60
self.MICRO = 1000000
self.MEGA = 1024.0 * 1024.0
self.RANDOM_MAX = 2147483254
self.EMAIL_BLOCK_TITLE = ''
self.SENDMAIL = '/usr/sbin/sendmail'
self.MAIL_PATH = '../tmp/mail_report'
self.WEB_PATH = '../tmp/web_report'
self.MAIL_HEADER = 'Sender: tera_eva <<EMAIL>>\nTo: tera_dev <<EMAIL>>\n\
Content-type: text/html\nSubject: EVA report\n\n'
self.g_query_thread = None
self.g_query_event = None
self.g_report_thread = None
self.g_exit = False
self.g_force_exit = False
self.g_logger = None
self.g_next_query_time = 0
self.g_last_query_ts = 0
self.g_query_times = 0
common = Common() | src/benchmark/eva/eva_var.py |
#!/usr/bin/env pythons
class CONF:
def __init__(self):
self.TABLE_NAME = 'table_name'
self.TABLET_NUM = 'tablet_number'
self.KEY_SIZE = 'key_size(B)' # Bytes
self.VALUE_SIZE = 'value_sizeB(B)' # Bytes
self.KEY_SEED = 'key_seed'
self.VALUE_SEED = 'value_seed'
self.STEP = 'step'
self.ENTRY_SIZE = 'entry_size(B)' # Bytes
self.ENTRY_NUM = 'entry_number(M)' # MB
self.LG_NUM = 'lg_number'
self.CF_NUM = 'cf_number'
self.CF = 'cf'
self.KV = 'kv_mode'
self.WRITE_SPEED_LIMIT = 'write_speed_limit(M)'
self.READ_SPEED_LIMIT = 'read_speed_limit(Qps)'
self.MODE_SEQ_WRITE = 'sw'
self.MODE_RAND_WRITE = 'rw'
self.MODE_READ = 'r'
self.MODE_SCAN = 's'
self.MODE = 'mode'
self.SCAN_BUFFER = 'scan_buffer(M)'
self.TERA_BENCH = ''
self.SPLIT_SIZE = 'split_size'
self.SCHEMA = 'table_schema'
self.g_speed_limit = 0
self.g_datasize = 0
self.g_web_report = True
self.g_web_report_type = ''
self.TS_NUMBER = 'ts_number'
self.g_test_conf = {self.TABLE_NAME: '', self.TABLET_NUM: 0, self.KEY_SIZE: 20, self.VALUE_SIZE: 1024,
self.KEY_SEED: '', self.VALUE_SEED: '', self.STEP: 'False',
self.ENTRY_SIZE: 20 + 1024, self.ENTRY_NUM: 0, self.LG_NUM: 0, self.CF_NUM: 1, self.CF: '',
self.KV: None, self.WRITE_SPEED_LIMIT: 0, self.READ_SPEED_LIMIT: 0, self.MODE: '',
self.SCAN_BUFFER: 0, self.TS_NUMBER: 0, self.SPLIT_SIZE: 0, self.SCHEMA: ''}
conf = CONF()
class Stat:
def __init__(self):
self.READY = 'kReady'
self.OFFLINE = 'kOffLine'
self.ONKICK = 'kOnKick'
self.WAITKICK = 'kWaitKick'
self.TS_STATUS_KEYS = [self.READY, self.OFFLINE, self.ONKICK, self.WAITKICK]
self.T_TOTAL = 'tablet_total'
self.T_BUSY = 'tablet_onbusy'
self.T_SPLIT = 'tablet_onsplit'
self.T_LOAD = 'tablet_onload'
self.SCAN = 'scan_size'
self.WRITE = 'write_size'
self.READ_SIZE = 'read_size'
self.READ_ROWS = 'read_rows'
self.READ_DELAY = 'rand_read_delay'
self.DFS_READ = 'dfs_io_r'
self.DFS_WRITE = 'dfs_io_w'
self.LOCAL_READ = 'local_io_r'
self.LOCAL_WRITE = 'local_io_w'
self.CPU = 'cpu_usage'
self.MEM = 'mem_used'
self.STAT_KEYS = [self.T_TOTAL, self.T_BUSY, self.T_SPLIT, self.T_LOAD, self.SCAN, self.WRITE, self.READ_SIZE,
self.READ_ROWS, self.DFS_READ, self.READ_DELAY, self.DFS_WRITE, self.LOCAL_READ,
self.LOCAL_WRITE, self.CPU, self.MEM]
self.ACCUMULATE_PART = [self.SCAN, self.WRITE, self.READ_SIZE, self.READ_ROWS, self.DFS_READ, self.READ_DELAY,
self.DFS_WRITE, self.LOCAL_READ, self.LOCAL_WRITE, self.CPU, self.MEM]
self.RATIO_PART = [self.T_BUSY, self.T_SPLIT, self.T_LOAD]
self.WRITE_AMP = 'write_amplification'
self.READ_AMP = 'read_amplification'
self.SCAN_AMP = 'scan_amplification'
self.g_ts_status = {}
for item in self.TS_STATUS_KEYS:
self.g_ts_status.update({item: 0})
self.g_stat = {}
for item in self.STAT_KEYS:
self.g_stat.update({item: 0})
stat = Stat()
class Common:
def __init__(self):
self.TERACLI = './teracli --flagfile=../conf/tera.flag'
self.TERAMO = './teramo'
self.TMP_DIR = '../tmp/'
self.CREATE = 'create'
self.DROP = 'drop'
self.QUERY_INTERVAL = 20
self.REPORT_INTERVAL = 10 * 60 * 60
self.MICRO = 1000000
self.MEGA = 1024.0 * 1024.0
self.RANDOM_MAX = 2147483254
self.EMAIL_BLOCK_TITLE = ''
self.SENDMAIL = '/usr/sbin/sendmail'
self.MAIL_PATH = '../tmp/mail_report'
self.WEB_PATH = '../tmp/web_report'
self.MAIL_HEADER = 'Sender: tera_eva <<EMAIL>>\nTo: tera_dev <<EMAIL>>\n\
Content-type: text/html\nSubject: EVA report\n\n'
self.g_query_thread = None
self.g_query_event = None
self.g_report_thread = None
self.g_exit = False
self.g_force_exit = False
self.g_logger = None
self.g_next_query_time = 0
self.g_last_query_ts = 0
self.g_query_times = 0
common = Common() | 0.144783 | 0.072112 |
import unittest2
class Test_ClientFactoryMixin(unittest2.TestCase):
def _getTargetClass(self):
from gcloud.client import _ClientFactoryMixin
return _ClientFactoryMixin
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_virtual(self):
self.assertRaises(NotImplementedError, self._makeOne)
class TestClient(unittest2.TestCase):
def setUp(self):
KLASS = self._getTargetClass()
self.original_cnxn_class = KLASS._connection_class
KLASS._connection_class = _MockConnection
def tearDown(self):
KLASS = self._getTargetClass()
KLASS._connection_class = self.original_cnxn_class
def _getTargetClass(self):
from gcloud.client import Client
return Client
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor_defaults(self):
from gcloud._testing import _Monkey
from gcloud import client
CREDENTIALS = object()
FUNC_CALLS = []
def mock_get_credentials():
FUNC_CALLS.append('get_credentials')
return CREDENTIALS
with _Monkey(client, get_credentials=mock_get_credentials):
client_obj = self._makeOne()
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(FUNC_CALLS, ['get_credentials'])
def test_ctor_explicit(self):
CREDENTIALS = object()
HTTP = object()
client_obj = self._makeOne(credentials=CREDENTIALS, http=HTTP)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertTrue(client_obj.connection.http is HTTP)
def test_from_service_account_json(self):
from gcloud._testing import _Monkey
from gcloud import client
KLASS = self._getTargetClass()
CREDENTIALS = object()
_CALLED = []
def mock_creds(arg1):
_CALLED.append((arg1,))
return CREDENTIALS
BOGUS_ARG = object()
with _Monkey(client, get_for_service_account_json=mock_creds):
client_obj = KLASS.from_service_account_json(BOGUS_ARG)
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(_CALLED, [(BOGUS_ARG,)])
def test_from_service_account_json_fail(self):
KLASS = self._getTargetClass()
CREDENTIALS = object()
self.assertRaises(TypeError, KLASS.from_service_account_json, None,
credentials=CREDENTIALS)
def test_from_service_account_p12(self):
from gcloud._testing import _Monkey
from gcloud import client
KLASS = self._getTargetClass()
CREDENTIALS = object()
_CALLED = []
def mock_creds(arg1, arg2):
_CALLED.append((arg1, arg2))
return CREDENTIALS
BOGUS_ARG1 = object()
BOGUS_ARG2 = object()
with _Monkey(client, get_for_service_account_p12=mock_creds):
client_obj = KLASS.from_service_account_p12(BOGUS_ARG1, BOGUS_ARG2)
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(_CALLED, [(BOGUS_ARG1, BOGUS_ARG2)])
def test_from_service_account_p12_fail(self):
KLASS = self._getTargetClass()
CREDENTIALS = object()
self.assertRaises(TypeError, KLASS.from_service_account_p12, None,
None, credentials=CREDENTIALS)
class TestJSONClient(unittest2.TestCase):
def setUp(self):
KLASS = self._getTargetClass()
self.original_cnxn_class = KLASS._connection_class
KLASS._connection_class = _MockConnection
def tearDown(self):
KLASS = self._getTargetClass()
KLASS._connection_class = self.original_cnxn_class
def _getTargetClass(self):
from gcloud.client import JSONClient
return JSONClient
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor_defaults(self):
from gcloud._testing import _Monkey
from gcloud import client
PROJECT = 'PROJECT'
CREDENTIALS = object()
FUNC_CALLS = []
def mock_get_proj():
FUNC_CALLS.append('_get_production_project')
return PROJECT
def mock_get_credentials():
FUNC_CALLS.append('get_credentials')
return CREDENTIALS
with _Monkey(client, get_credentials=mock_get_credentials,
_get_production_project=mock_get_proj):
client_obj = self._makeOne()
self.assertTrue(client_obj.project is PROJECT)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(FUNC_CALLS,
['_get_production_project', 'get_credentials'])
def test_ctor_missing_project(self):
from gcloud._testing import _Monkey
from gcloud import client
FUNC_CALLS = []
def mock_get_proj():
FUNC_CALLS.append('_get_production_project')
return None
with _Monkey(client, _get_production_project=mock_get_proj):
self.assertRaises(ValueError, self._makeOne)
self.assertEqual(FUNC_CALLS, ['_get_production_project'])
def test_ctor_w_invalid_project(self):
CREDENTIALS = object()
HTTP = object()
with self.assertRaises(ValueError):
self._makeOne(project=object(), credentials=CREDENTIALS, http=HTTP)
def test_ctor_explicit(self):
PROJECT = 'PROJECT'
CREDENTIALS = object()
HTTP = object()
client_obj = self._makeOne(project=PROJECT, credentials=CREDENTIALS,
http=HTTP)
self.assertTrue(client_obj.project is PROJECT)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertTrue(client_obj.connection.http is HTTP)
class _MockConnection(object):
def __init__(self, credentials=None, http=None):
self.credentials = credentials
self.http = http | src/lib/gcloud/test_client.py |
import unittest2
class Test_ClientFactoryMixin(unittest2.TestCase):
def _getTargetClass(self):
from gcloud.client import _ClientFactoryMixin
return _ClientFactoryMixin
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_virtual(self):
self.assertRaises(NotImplementedError, self._makeOne)
class TestClient(unittest2.TestCase):
def setUp(self):
KLASS = self._getTargetClass()
self.original_cnxn_class = KLASS._connection_class
KLASS._connection_class = _MockConnection
def tearDown(self):
KLASS = self._getTargetClass()
KLASS._connection_class = self.original_cnxn_class
def _getTargetClass(self):
from gcloud.client import Client
return Client
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor_defaults(self):
from gcloud._testing import _Monkey
from gcloud import client
CREDENTIALS = object()
FUNC_CALLS = []
def mock_get_credentials():
FUNC_CALLS.append('get_credentials')
return CREDENTIALS
with _Monkey(client, get_credentials=mock_get_credentials):
client_obj = self._makeOne()
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(FUNC_CALLS, ['get_credentials'])
def test_ctor_explicit(self):
CREDENTIALS = object()
HTTP = object()
client_obj = self._makeOne(credentials=CREDENTIALS, http=HTTP)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertTrue(client_obj.connection.http is HTTP)
def test_from_service_account_json(self):
from gcloud._testing import _Monkey
from gcloud import client
KLASS = self._getTargetClass()
CREDENTIALS = object()
_CALLED = []
def mock_creds(arg1):
_CALLED.append((arg1,))
return CREDENTIALS
BOGUS_ARG = object()
with _Monkey(client, get_for_service_account_json=mock_creds):
client_obj = KLASS.from_service_account_json(BOGUS_ARG)
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(_CALLED, [(BOGUS_ARG,)])
def test_from_service_account_json_fail(self):
KLASS = self._getTargetClass()
CREDENTIALS = object()
self.assertRaises(TypeError, KLASS.from_service_account_json, None,
credentials=CREDENTIALS)
def test_from_service_account_p12(self):
from gcloud._testing import _Monkey
from gcloud import client
KLASS = self._getTargetClass()
CREDENTIALS = object()
_CALLED = []
def mock_creds(arg1, arg2):
_CALLED.append((arg1, arg2))
return CREDENTIALS
BOGUS_ARG1 = object()
BOGUS_ARG2 = object()
with _Monkey(client, get_for_service_account_p12=mock_creds):
client_obj = KLASS.from_service_account_p12(BOGUS_ARG1, BOGUS_ARG2)
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(_CALLED, [(BOGUS_ARG1, BOGUS_ARG2)])
def test_from_service_account_p12_fail(self):
KLASS = self._getTargetClass()
CREDENTIALS = object()
self.assertRaises(TypeError, KLASS.from_service_account_p12, None,
None, credentials=CREDENTIALS)
class TestJSONClient(unittest2.TestCase):
def setUp(self):
KLASS = self._getTargetClass()
self.original_cnxn_class = KLASS._connection_class
KLASS._connection_class = _MockConnection
def tearDown(self):
KLASS = self._getTargetClass()
KLASS._connection_class = self.original_cnxn_class
def _getTargetClass(self):
from gcloud.client import JSONClient
return JSONClient
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_ctor_defaults(self):
from gcloud._testing import _Monkey
from gcloud import client
PROJECT = 'PROJECT'
CREDENTIALS = object()
FUNC_CALLS = []
def mock_get_proj():
FUNC_CALLS.append('_get_production_project')
return PROJECT
def mock_get_credentials():
FUNC_CALLS.append('get_credentials')
return CREDENTIALS
with _Monkey(client, get_credentials=mock_get_credentials,
_get_production_project=mock_get_proj):
client_obj = self._makeOne()
self.assertTrue(client_obj.project is PROJECT)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertEqual(FUNC_CALLS,
['_get_production_project', 'get_credentials'])
def test_ctor_missing_project(self):
from gcloud._testing import _Monkey
from gcloud import client
FUNC_CALLS = []
def mock_get_proj():
FUNC_CALLS.append('_get_production_project')
return None
with _Monkey(client, _get_production_project=mock_get_proj):
self.assertRaises(ValueError, self._makeOne)
self.assertEqual(FUNC_CALLS, ['_get_production_project'])
def test_ctor_w_invalid_project(self):
CREDENTIALS = object()
HTTP = object()
with self.assertRaises(ValueError):
self._makeOne(project=object(), credentials=CREDENTIALS, http=HTTP)
def test_ctor_explicit(self):
PROJECT = 'PROJECT'
CREDENTIALS = object()
HTTP = object()
client_obj = self._makeOne(project=PROJECT, credentials=CREDENTIALS,
http=HTTP)
self.assertTrue(client_obj.project is PROJECT)
self.assertTrue(isinstance(client_obj.connection, _MockConnection))
self.assertTrue(client_obj.connection.credentials is CREDENTIALS)
self.assertTrue(client_obj.connection.http is HTTP)
class _MockConnection(object):
def __init__(self, credentials=None, http=None):
self.credentials = credentials
self.http = http | 0.58948 | 0.198763 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dataflow import apis
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dataflow import dataflow_util
from googlecloudsdk.core import properties
def _CommonArgs(parser):
"""Register flags for this command.
Args:
parser: argparse.ArgumentParser to register arguments with.
"""
parser.add_argument(
'job_name',
metavar='JOB_NAME',
help='The unique name to assign to the job.')
parser.add_argument(
'--gcs-location',
help=('The Google Cloud Storage location of the job template to run. '
"(Must be a URL beginning with 'gs://'.)"),
type=arg_parsers.RegexpValidator(r'^gs://.*',
'Must begin with \'gs://\''),
required=True)
parser.add_argument(
'--staging-location',
help=('The Google Cloud Storage location to stage temporary files. '
"(Must be a URL beginning with 'gs://'.)"),
type=arg_parsers.RegexpValidator(r'^gs://.*',
'Must begin with \'gs://\''))
parser.add_argument(
'--zone',
type=arg_parsers.RegexpValidator(r'\w+-\w+\d-\w',
'must provide a valid zone'),
help='The zone to run the workers in.')
parser.add_argument(
'--service-account-email',
type=arg_parsers.RegexpValidator(r'.*@.*\..*',
'must provide a valid email address'),
help='The service account to run the workers as.')
parser.add_argument(
'--max-workers', type=int, help='The maximum number of workers to run.')
parser.add_argument(
'--parameters',
metavar='PARAMETERS',
type=arg_parsers.ArgDict(),
action=arg_parsers.UpdateAction,
help='The parameters to pass to the job.')
# TODO(b/139889563): Mark as required when default region is removed
parser.add_argument(
'--region',
metavar='REGION_ID',
help=('The region ID of the job\'s regional endpoint. ' +
dataflow_util.DEFAULT_REGION_MESSAGE))
parser.add_argument(
'--disable-public-ips',
action=actions.StoreBooleanProperty(
properties.VALUES.dataflow.disable_public_ips),
help='The Cloud Dataflow workers must not use public IP addresses.'
)
def _CommonRun(args, support_beta_features=False):
"""Runs the command.
Args:
args: The arguments that were provided to this command invocation.
support_beta_features: True, if using the beta command.
Returns:
A Job message.
"""
num_workers = None
worker_machine_type = None
network = None
subnetwork = None
dataflow_kms_key = None
if support_beta_features:
num_workers = args.num_workers
worker_machine_type = args.worker_machine_type
network = args.network
subnetwork = args.subnetwork
dataflow_kms_key = args.dataflow_kms_key
arguments = apis.TemplateArguments(
project_id=properties.VALUES.core.project.Get(required=True),
region_id=dataflow_util.GetRegion(args),
job_name=args.job_name,
gcs_location=args.gcs_location,
zone=args.zone,
max_workers=args.max_workers,
num_workers=num_workers,
network=network,
subnetwork=subnetwork,
worker_machine_type=worker_machine_type,
staging_location=args.staging_location,
kms_key_name=dataflow_kms_key,
disable_public_ips=properties.VALUES.dataflow.disable_public_ips.GetBool(
),
parameters=args.parameters,
service_account_email=args.service_account_email)
flex_template = properties.VALUES.dataflow.flex_template.GetBool()
if flex_template:
return apis.Templates.CreateJobFromFlexTemplate(arguments)
else:
return apis.Templates.Create(arguments)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Run(base.Command):
"""Runs a job from the specified path."""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
return _CommonRun(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class RunBeta(Run):
"""Runs a job from the specified path."""
@staticmethod
def Args(parser):
_CommonArgs(parser)
parser.add_argument(
'--num-workers', type=int, help='The initial number of workers to use.')
parser.add_argument(
'--worker-machine-type',
help='The type of machine to use for workers. Defaults to '
'server-specified.')
parser.add_argument(
'--subnetwork',
help='The Compute Engine subnetwork for launching instances '
'to run your pipeline.')
parser.add_argument(
'--network',
help='The Compute Engine network for launching instances to '
'run your pipeline.')
parser.add_argument(
'--dataflow-kms-key',
help='The Cloud KMS key to protect the job resources.')
parser.add_argument(
'--flex-template',
action=actions.StoreBooleanProperty(
properties.VALUES.dataflow.flex_template),
help='The job template to run is a flex template.'
)
def Run(self, args):
return _CommonRun(args, True) | google-cloud-sdk/lib/surface/dataflow/jobs/run.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dataflow import apis
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dataflow import dataflow_util
from googlecloudsdk.core import properties
def _CommonArgs(parser):
"""Register flags for this command.
Args:
parser: argparse.ArgumentParser to register arguments with.
"""
parser.add_argument(
'job_name',
metavar='JOB_NAME',
help='The unique name to assign to the job.')
parser.add_argument(
'--gcs-location',
help=('The Google Cloud Storage location of the job template to run. '
"(Must be a URL beginning with 'gs://'.)"),
type=arg_parsers.RegexpValidator(r'^gs://.*',
'Must begin with \'gs://\''),
required=True)
parser.add_argument(
'--staging-location',
help=('The Google Cloud Storage location to stage temporary files. '
"(Must be a URL beginning with 'gs://'.)"),
type=arg_parsers.RegexpValidator(r'^gs://.*',
'Must begin with \'gs://\''))
parser.add_argument(
'--zone',
type=arg_parsers.RegexpValidator(r'\w+-\w+\d-\w',
'must provide a valid zone'),
help='The zone to run the workers in.')
parser.add_argument(
'--service-account-email',
type=arg_parsers.RegexpValidator(r'.*@.*\..*',
'must provide a valid email address'),
help='The service account to run the workers as.')
parser.add_argument(
'--max-workers', type=int, help='The maximum number of workers to run.')
parser.add_argument(
'--parameters',
metavar='PARAMETERS',
type=arg_parsers.ArgDict(),
action=arg_parsers.UpdateAction,
help='The parameters to pass to the job.')
# TODO(b/139889563): Mark as required when default region is removed
parser.add_argument(
'--region',
metavar='REGION_ID',
help=('The region ID of the job\'s regional endpoint. ' +
dataflow_util.DEFAULT_REGION_MESSAGE))
parser.add_argument(
'--disable-public-ips',
action=actions.StoreBooleanProperty(
properties.VALUES.dataflow.disable_public_ips),
help='The Cloud Dataflow workers must not use public IP addresses.'
)
def _CommonRun(args, support_beta_features=False):
"""Runs the command.
Args:
args: The arguments that were provided to this command invocation.
support_beta_features: True, if using the beta command.
Returns:
A Job message.
"""
num_workers = None
worker_machine_type = None
network = None
subnetwork = None
dataflow_kms_key = None
if support_beta_features:
num_workers = args.num_workers
worker_machine_type = args.worker_machine_type
network = args.network
subnetwork = args.subnetwork
dataflow_kms_key = args.dataflow_kms_key
arguments = apis.TemplateArguments(
project_id=properties.VALUES.core.project.Get(required=True),
region_id=dataflow_util.GetRegion(args),
job_name=args.job_name,
gcs_location=args.gcs_location,
zone=args.zone,
max_workers=args.max_workers,
num_workers=num_workers,
network=network,
subnetwork=subnetwork,
worker_machine_type=worker_machine_type,
staging_location=args.staging_location,
kms_key_name=dataflow_kms_key,
disable_public_ips=properties.VALUES.dataflow.disable_public_ips.GetBool(
),
parameters=args.parameters,
service_account_email=args.service_account_email)
flex_template = properties.VALUES.dataflow.flex_template.GetBool()
if flex_template:
return apis.Templates.CreateJobFromFlexTemplate(arguments)
else:
return apis.Templates.Create(arguments)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Run(base.Command):
"""Runs a job from the specified path."""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
return _CommonRun(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class RunBeta(Run):
"""Runs a job from the specified path."""
@staticmethod
def Args(parser):
_CommonArgs(parser)
parser.add_argument(
'--num-workers', type=int, help='The initial number of workers to use.')
parser.add_argument(
'--worker-machine-type',
help='The type of machine to use for workers. Defaults to '
'server-specified.')
parser.add_argument(
'--subnetwork',
help='The Compute Engine subnetwork for launching instances '
'to run your pipeline.')
parser.add_argument(
'--network',
help='The Compute Engine network for launching instances to '
'run your pipeline.')
parser.add_argument(
'--dataflow-kms-key',
help='The Cloud KMS key to protect the job resources.')
parser.add_argument(
'--flex-template',
action=actions.StoreBooleanProperty(
properties.VALUES.dataflow.flex_template),
help='The job template to run is a flex template.'
)
def Run(self, args):
return _CommonRun(args, True) | 0.682997 | 0.102574 |