Exemple #1
0
def drawPlayAgainMenu(DISPLAYSURF):
    play_again_option = Option(DISPLAYSURF, WHITE, font, "PLAY AGAIN?", (config.display_x // 2 - 100, config.display_y // 2 - 100))
    while (True):
        play_again_option.draw()
        for option in playAgainMenuOptions:
            option.draw()
        drawStatsMenu(DISPLAYSURF)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            for option in playAgainMenuOptions:
                if option.rect.collidepoint(pygame.mouse.get_pos()):
                    option.hovered = True
                    #sound_hover_menu_item.play()
                    if event.type == MOUSEBUTTONUP:
                        # play sound
                        sound_select_menu_item.play()

                        if option.text == "YES":
                            os.execl(sys.executable, sys.executable, *sys.argv)
                            return False
                        if option.text == "NO":
                            pygame.quit()
                            sys.exit()
                        if option.text == "MAIN MENU":
                            drawMainMenu(DISPLAYSURF)
                        option.hovered = False
                else:
                    option.hovered = False

        pygame.display.update()
    return True
Exemple #2
0
def init_db():
    connection = SQLEngine.connect()
    context = MigrationContext.configure(connection)
    current_revision = context.get_current_revision()
    logger.boot('Database revision: %s', current_revision)
    if current_revision is None:
        DataBase.metadata.create_all(SQLEngine)

    config = Config(ALEMBIC_CONFIG)
    script = ScriptDirectory.from_config(config)
    head_revision = script.get_current_head()
    if current_revision is None or current_revision != head_revision:
        logger.boot('Upgrading database to version %s.', head_revision)
        command.upgrade(config, 'head')
        from option import Option
        session = Session()
        options = session.query(Option).first()
        if options is None:
            options = Option()
        options.version = head_revision
        session.add(options)
        from pulse import Pulse
        pulse = session.query(Pulse).first()
        if pulse is None:
            pulse = Pulse()
        session.add(pulse)
        session.commit()
Exemple #3
0
def init_db():
    connection = SQLEngine.connect()
    context = MigrationContext.configure(connection)
    current_revision = context.get_current_revision()
    logger.boot('Database revision: %s', current_revision)
    #if current_revision is None:
    #    from option import Option
    #    DataBase.metadata.create_all(SQLEngine)
    #    session = Session()
    #    options = Option()
    #    options.date_created = datetime.now()
    #    options.version = None
    #    #options.port = 4400
    #    #options.wizlock = False
    #    session.add(options)
    #    session.commit()
    #    logger.boot('Database created and initialized.')

    config = Config(ALEMBIC_CONFIG)
    script = ScriptDirectory.from_config(config)
    head_revision = script.get_current_head()
    if current_revision is None or current_revision != head_revision:
        logger.boot('Upgrading database to version %s.', head_revision)
        command.upgrade(config, 'head')
        from option import Option
        session = Session()
        options = session.query(Option).first()
        if options is None:
            options = Option()
            options.date_created = datetime.now()
            session.add(options)
            logger.boot('Database created and initialized.')
        options.version = head_revision
        session.commit()
Exemple #4
0
    def __new__(cls):
        if cls.__instance is None:
            i = object.__new__(cls)

            i.SQLEngine = SQLEngine
            i.DataBase = DataBase
            i.Session = Session

            i.connection = SQLEngine.connect()
            i.context = MigrationContext.configure(i.connection)
            i.current_revision = i.context.get_current_revision()
            logger.boot('Database revision: %s', i.current_revision)

            i.config = Config(ALEMBIC_CONFIG)
            i.script = ScriptDirectory.from_config(i.config)
            i.head_revision = i.script.get_current_head()
            if i.current_revision is None or i.current_revision != i.head_revision:
                logger.boot('Upgrading database to version %s.', i.head_revision)
                command.upgrade(i.config, 'head')
                from option import Option
                from log import Log
                session = Session()
                options = session.query(Option).first()
                if options is None:
                    options = Option()
                    session.add(options)
                options.version = i.head_revision
                session.commit()
                i.current_revision = i.head_revision

            cls.__instance = i
            h = SQLAlchemyHandler()
            logger.addHandler(h)
            return cls.__instance
Exemple #5
0
  def get_option(self, model, subject):
    option = Option(subject.uri)

    statement = RDF.Statement(subject,
                              RDF.Uri("http://okfnpad.org/flow/0.1/node"),
                              None)

    uri = None
    for s in model.find_statements(statement):
      if s.object.is_resource():
        uri = s.object.uri

    option.node = uri

    statement = RDF.Statement(subject,
                              RDF.Uri("http://okfnpad.org/flow/0.1/text"),
                              None)

    for s in model.find_statements(statement):
      if s.object.is_literal():
        option.text = s.object.literal_value['string']

    statement = RDF.Statement(subject,
                              RDF.Uri("http://okfnpad.org/flow/0.1/query"),
                              None)

    for s in model.find_statements(statement):
      if s.object.is_literal():
        option.query = s.object.literal_value['string']

    return option
Exemple #6
0
 def generateAllowedList(self, possibility, guess, fullColors):
     guessSet = set(guess)
     allowed = []
     dummy = iter(possibility)
     skip = False
     for place in range(self.width):
         if guess[place] in fullColors:
             allowed.append([guess[place]])
         else:
             d = next(dummy)
             if d == -1:
                 allowed.append(list(set(range(self.height)) - guessSet))
             else:
                 color = d
                 if color == guess[place]:
                     skip = True
                     break
                 else:
                     #halfColor at a different place it was in the guess
                     allowed.append([color])
     if not skip:
         option = Option(self.width, self.height)
         option.setDataByAllowedList(allowed)
         return option
     else:
         return None
Exemple #7
0
 def sete(self, name, opt):
     """Sets option `name` to dictionary or Option `opt`."""
     if not opt.has_key('type'):
         opt['type'] = 'Empty'
     if not opt.has_key('handle'):
         opt['handle'] = name
     if isinstance(opt, dict):
         opt = Option(**opt)
         opt.set_base_kid(self.kid_base)
     self.desc[name] = opt
     return True
Exemple #8
0
def get_option():
    args = parse_args()
    option = Option()
    option.f = convert_name_to_number(args.f)
    option.t = convert_name_to_number(args.t)

    # not implemented
    if args.list:
        option.list = args.list
    option.a = False


    return option
Exemple #9
0
 def set_value(self, name, value, strict=True):
     name_parts = name.split(".", 1)
     prefix = name_parts[0]
     try:
         candidate = getattr(self, prefix)
     except KeyError:
         if strict:
             raise
         candidate = Option(name)
         setattr(self, prefix, candidate)
     candidate_type = type(candidate)
     if candidate_type == Namespace:
         candidate.set_value(name_parts[1], value, strict)
     else:
         candidate.set_value(value)
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.setWindowTitle('ConvertAll')
     modPath = os.path.abspath(sys.path[0])
     if modPath.endswith('.zip'):  # for py2exe
         modPath = os.path.dirname(modPath)
     iconPathList = [iconPath, os.path.join(modPath, 'icons/'),
                      os.path.join(modPath, '../icons')]
     self.icons = icondict.IconDict()
     self.icons.addIconPath(filter(None, iconPathList))
     try:
         QtGui.QApplication.setWindowIcon(self.icons['convertall_med'])
     except KeyError:
         pass
     self.helpView = None
     self.findDlg = None
     self.option = Option('convertall', 20)
     self.option.loadAll(optiondefaults.defaultList)
     try:
         num = ConvertDlg.unitData.readData()
         print '%d units loaded' % num
     except unitdata.UnitDataError, text:
         QtGui.QMessageBox.warning(self, 'ConvertAll',
                                   'Error in unit data - %s' % text)
         sys.exit(1)
Exemple #11
0
 def __init__(self, arg):
     self.curl = pycurl.Curl()
     self.option = Option()
     self.option.parse(arg)
     self.log = Log(self.option.isVerboseMode())
     self.datas = []
     config = json.loads(open(Epilader.JSON_CONF).read())
     self.login    = config["login"]
     self.password = config["password"]
     self.notes = Notes(config["projets"], config["modules"])
Exemple #12
0
    def add_option(self, name, *args, **kwargs):
        """add an option to the namespace.   This can take two forms:
              'name' is a string representing the name of an option and the
              kwargs are its parameters, or 'name' is an instance of an Option
              object
        """
        if isinstance(name, Option):
            an_option = name
            name = an_option.name
        else:
            an_option = Option(name, *args, **kwargs)

        current_namespace = self
        name_parts = name.split('.')
        for a_path_component in name_parts[:-1]:
            if a_path_component not in current_namespace:
                current_namespace[a_path_component] = Namespace()
            current_namespace = current_namespace[a_path_component]
        an_option.name = name_parts[-1]

        setattr(current_namespace, an_option.name, an_option)
Exemple #13
0
 def joinOptions(self, newOptions):
     joinedOptions = []
     print("joining with new options:")
     self.printOptions(newOptions)
     for option in self.options:
         for newOption in newOptions:
             joinedOption = Option.newFromMerge(option, newOption)
             if joinedOption.isValid():
                 joinedOptions.append(joinedOption)
     joinedOptions = self.cleanOptions(joinedOptions)
     self.options = joinedOptions
     print("results in:")
     self.printOptions(joinedOptions)
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.setWindowTitle('ConvertAll')
     icons.setupIcons()
     self.setWindowIcon(icons.iconDict['convert'])
     self.helpView = None
     self.findDlg = None
     self.option = Option('convertall', 20)
     self.option.loadAll(optiondefaults.defaultList)
     try:
         ConvertDlg.unitData.readData()
     except unitdata.UnitDataError, text:
         QtGui.QMessageBox.warning(self, 'ConvertAll',
                                   'Error in unit data - %s' % text)
         sys.exit(1)
Exemple #15
0
    def _process_option(self, node, args):
        '''Return Option, that contain values produced using args comed from step declaration'''
        opt = Option(node.attrib.get('repr'))
        name = node.attrib['name']

        if 'default' in node.attrib:
            opt.set_default_val(Variant.from_string(node.attrib['default'], node.attrib['type']))
        elif 'default_ref' in node.attrib:
            ref = node.attrib['default_ref'].strip()
            if ref in self._inputs:
                opt.set_default_val(self._inputs[ref].get())
            else:
                raise RuntimeError('Reference to currently undefined symbol: ' + ref)
        else:
            for child in node: #check by RELAXNG
                if child.tag == 'default':
                    opt.set_default_val(self._eval_expression(child))

        if name in args:
            opt.set_val(args[name])
        
        return opt
 def __init__(self):
     labels = ['init', 'move', 'check', 'finish']
     Option.__init__(self, labels, 'finish')
Exemple #17
0
 def addCommonOptions(self):
     help = Option(["--help"], "{}")
     version = Option(["--version"], "{}")
     self.options.add(help)
     self.options.add(version)
Exemple #18
0
            user_info['os'] = 'Windows'
        elif platform.system() == 'Linux':
            user_info['os'] = 'Linux'
        elif platform.system() == 'Darwin':
            user_info['os'] = 'Darwin'

        user_info['handle'] = input('* Codeforces Handle: ')

        mkdir = input('* mkdir option [true/false]: ')

        while True:
            if mkdir == 'true' or mkdir == 'false':
                break
            mkdir = input('* mkdir option [true/false]: ')

        if mkdir == 'false':
            user_info['mkdir'] = False
        if mkdir == 'true':
            user_info['mkdir'] = True
            user_info['dir_name'] = input('* directory name format: ')
            # user_info['dir_name'] = [CONTEST]

        # user_info['source_name'] = input('* source name format: ')
        user_info['source_name'] = "[CONTEST]-[INDEX]: [TITLE]"

        crawler = Crawler()
        option = Option(user_info)
        Main(crawler, option, user_info).run()
    except KeyboardInterrupt:
        print('\n* bye\n')
    def __init__(self):
        labels = ['init', 'turn', 'ahead', 'turnback', 'goback', 'finish']
        Option.__init__(self, labels, 'finish')

        self.target_pose = 0
Exemple #20
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()
        # check if particles should be enabled
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        base.width = self.pipe.getDisplayWidth()
        base.height = self.pipe.getDisplayHeight()

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # # setup new window properties
            props = WindowProperties()
            # # # Fullscreen
            props.setFullscreen(True)
            # # # set the window size to the screen resolution
            props.setSize(w, h)
            # # request the new properties
            base.win.requestProperties(props)
            pass
        elif base.appRunner:
            # As when the application is started as appRunner instance
            # it doesn't respect our loadPrcFile configurations specific
            # to the window, hence we need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                #TODO: Check for all window specific variables like
                #      fullscreen, screen size, title and window
                #      decoration that you have in your configuration
                #      and set them by your own.
                if mainConfig.getVariableName(dec) == "fullscreen":
                    if not mainConfig.getDeclaration(dec).getBoolWord(0): break
                    # get the displays width and height
                    w = self.pipe.getDisplayWidth()
                    h = self.pipe.getDisplayHeight()
                    # set window properties
                    # clear all properties not previously set
                    base.win.clearRejectedProperties()
                    # setup new window properties
                    props = WindowProperties()
                    # Fullscreen
                    props.setFullscreen(True)
                    # set the window size to the screen resolution
                    props.setSize(w, h)
                    # request the new properties
                    base.win.requestProperties(props)
                    break
                pass

        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig
        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()

    def postInit(self):
        #
        # initialize game content
        #
        # camera
        base.camLens.setNearFar(1.0, 10000)
        base.camLens.setFov(75)

        a = 33
        base.camera.setPos(0, -a, a + 3)  #80)
        # collision
        base.cTrav = CollisionTraverser("base collision traverser")
        base.cHandler = CollisionHandlerEvent()
        base.cPusher = CollisionHandlerPusher()
        base.cQueue = CollisionHandlerQueue()
        base.globalClock = ClockObject.getGlobalClock()
        base.cHandler.addInPattern('%fn-into-%in')
        base.cHandler.addOutPattern('%fn-out-%in')
        base.cHandler.addAgainPattern('%fn-again-%in')
        # ai init
        base.AIworld = AIWorld(render)
        # 3d manager
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)
        # manager
        self.archiveManager = ArchiveManager()
        self.mapManager = MapManager()
        self.initHeroInfo = None
        # Lock
        self.lock = threading.Lock()
        self.gameThread = None

        self.filters = CommonFilters(base.win, base.cam)
        # UI
        self.menu = Menu()
        self.option = Option()
        self.archive = Archive()
        self.death = Death()
        # self.oobe()
        #self.Archive_status = 0
        # self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        # self.menuMusic.setLoop(True)
        # self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        # self.fightMusic.setLoop(True)
        # base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        self.titleVideo, self.titleCard = loadVideo('title.mp4')

        self.isInited = False
        self.isSkip = False
        self.isRenew = False
        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Game", self.request, ["Archive"])
        self.accept("Menu-Option", self.request, ["Option"])
        self.accept("Menu-Quit", self.quit)
        self.menu.show()

    def exitMenu(self):
        self.ignore("Menu-Game")
        self.ignore("Menu-Option")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterOption(self):
        show_cursor()
        self.accept("ChangeVolume", self.ChangeMusic)
        self.accept("ChangeSound", self.ChangeSound)
        self.option.show()

    def exitOption(self):
        self.ignore("ChangeVolume")
        self.ignore("ChangeSound")
        self.option.hide()

    def enterArchive(self):
        show_cursor()
        self.accept("LoadArchive", self.LoadArchive)
        self.accept("DeleteArchive", self.DeleteArchive)
        self.accept("UpdateArchive", self.UpdateArchive)
        self.accept("NewGame", self.NewGame)
        self.UpdateArchive()

    def exitArchive(self):
        self.archive.hide()
        self.ignore("LoadArchive")
        self.ignore("DeleteArchive")
        self.ignore("UpdateArchive")
        self.ignore("NewGame")

    def enterPause(self):
        # self.accept("Pause-Newgame")
        # self.accept("Pause-Option")
        # self.accept("Pause-Back")
        show_cursor()

    def exitPause(self):
        self.ignore("Pause-Newgame")
        self.ignore("Pause-Option")
        self.ignore("Pause-Back")

    def enterInitGame(self):
        if Nodebug:
            self.titleCard.show()
            self.titleVideo.play()

    def exitInitGame(self):
        if Nodebug:
            self.titleCard.hide()
            self.titleVideo.stop()

    def enterGame(self):
        self.accept("hero-death", self.request, ["Death"])
        self.accept('game-end', self.request, ['Menu'])
        base.messenger.send('game-start', [self.isRenew])

    def exitGame(self):
        self.ignore('hero-death')
        #self.archiveManager.SaveArchive(self.archiveID,MapManager.ToDict(self.mapManager))
        pass

    def enterDeath(self):
        self.mapManager.index = 0  # renew
        self.accept("Death-Game", self.NewGame)
        self.accept("Death-Menu", self.request, ["Menu"])
        self.accept("Death-Quit", self.quit)
        self.death.show()
        show_cursor()

    def exitDeath(self):
        self.ignore("Death-Menu")
        self.ignore("Death-Quit")
        self.death.hide()

    #
    # FSM PART END
    #

    @print_func_time
    def NewGame(self):
        delayTime = self.titleVideo.length()
        archiveDir = self.archiveManager.basedir
        self.isInited = False
        self.request('InitGame')
        delayTime = self.titleVideo.length()
        if not self.isSkip:
            self.timer = threading.Timer(delayTime, self._accept_skip)
            self.timer.start()
        self.isInited = False
        checkThread = threading.Thread(target=self._thread_check, name='check')
        checkThread.start()
        self.gameThread = threading.Thread(target=self._initGame,
                                           args=(None, archiveDir),
                                           name='newgame')
        self.gameThread.start()

    def _thread_check(self):
        while (not self.isInited or not self.isSkip):
            pass
        self.isInited = False
        self.request('Game')

    @print_func_time
    def _accept_skip(self):
        self.lock.acquire()
        try:
            self.isSkip = True
        finally:
            self.lock.release()

    def _initGame(self, archive, archivePath):
        sTime = time.time()
        self.isInited = False
        self.mapManager.archivePath = archivePath
        #self.filters.setBloom()
        if self.mapManager.hero == None:
            self.mapManager.loadResource()
            self.initHeroInfo = Hero.ToDict(self.mapManager.hero)
        self.mapManager.hero.reInit(self.initHeroInfo)

        if archive == None:
            self.mapManager.genMap()
            self.isRenew = True
            if not self.isSkip:
                self.acceptOnce('enter', self._accept_skip)
        else:
            self.mapManager.reInit(archive)
            self.isRenew = False
            if not self.isSkip:
                self.acceptOnce('enter', self._accept_skip)

        self.isInited = True

    @print_func_time
    def LoadGame(self):
        self.Archive_status = 1
        self.request("Archive")

    def ChangeMusic(self):
        print self.option.slider_volume['value']

    def ChangeMusic(self):
        base.musicManager.setVolume(self.option.slider_volume['value'] / 100)

    def ChangeSound(self):
        base.sfxManagerList[0].setVolume(self.option.slider_sound['value'] /
                                         100)

    def DeleteArchive(self):
        self.archiveManager.DeleteArchive(self.archive.v[0])
        self.UpdateArchive()

    def LoadArchive(self):
        self.archiveID = self.archive.v[0]
        archive = self.archiveManager.ReadArchive(self.archiveID)
        archiveDir = self.archiveManager.basedir
        delayTime = self.titleVideo.length()
        self.request('InitGame')
        if not self.isSkip:
            self.timer = threading.Timer(delayTime, self._accept_skip)
            self.timer.start()
        self.isInited = False
        checkThread = threading.Thread(target=self._thread_check, name='check')
        checkThread.start()
        self.gameThread = threading.Thread(target=self._initGame,
                                           args=(archive, archiveDir),
                                           name='newgame')
        self.gameThread.start()

    def UpdateArchive(self):
        msg = self.archiveManager.GetArchiveListShortMsg()
        self.archive.show(msg)

    #
    # BASIC FUNCTIONS
    #

    def __escape(self):
        if self.state == "Menu":
            self.gameThread = None
            self.quit()
        elif self.state == "Game":
            archive = MapManager.ToDict(self.mapManager)
            self.archiveManager.SaveArchive(self.archive.v[0], archive)
            self.mapManager.room.request("Idle")
            base.musicManager.stopAllSounds()
            base.sfxManagerList[0].stopAllSounds()

            self.request("Menu")
        else:
            self.request("Menu")

    def quit(self):
        """This function will stop the application"""
        self.userExit()

    def __writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        # These TODO tags are as a reminder for to add any new config
        # variables that may occur in the future
        #TODO: get values of configurations here
        particles = "#f" if not base.particleMgrEnabled else "#t"
        volume = str(round(base.musicManager.getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        #TODO: add any configuration variable name that you have added
        customConfigVariables = [
            "", "particles-enabled", "audio-mute", "audio-volume"
        ]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base or other
                #       manual config changes by the user
                if page.getVariableName(dec) in customConfigVariables:
                    decl = page.modifyDeclaration(dec)
                    removeDecls.append(decl)
            for dec in removeDecls:
                page.deleteDeclaration(dec)
            # NOTE: particles-enabled and audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # Particles
            page.makeDeclaration("particles-enabled", particles)
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", mute)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("{} Pandaconfig".format(appName))
            # set OpenGL to be the default
            page.makeDeclaration("load-display", "pandagl")
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size in the config file
            page.makeDeclaration("win-size", "{} {}".format(w, h))
            # set the default to fullscreen in the config file
            page.makeDeclaration("fullscreen", "1")
            # particles
            page.makeDeclaration("particles-enabled", "#t")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", "#f")
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
Exemple #21
0
from selector import Selector
from parameter import Parameter
from root import Root
import parametertypes
import tileform
from option import Option

root = Root("root",
    parameters = [
        Parameter("starting_port", tileForm=tileform.msgRouterForm, defaultValue=7000, parameterType=parametertypes.Port, label="Starting Port"),
        Selector("tls_config", tileForm=tileform.tlsForm, defaultValue="disabled", label="Choose whether TLS is enabled or not", enumValues=[Option("disabled", "TLS Disabled"), Option("enabled", "TLS Enabled")],
            parameters={
                "enabled": [
                    Parameter("cert_pem", pcfFormName="rsa_server_cert", parameterType=parametertypes.CertPem, placeholder="Message Router's Server Certificate"),
                    Parameter("private_key_pem", pcfFormName="rsa_server_cert", parameterType=parametertypes.PrivateKeyPem),
                    Parameter("broker_validate_cert_disabled", parameterType=parametertypes.Boolean,visibleInBoshManifest=False),
                    Parameter("trusted_root_certificates", optional=True, parameterType=parametertypes.Text),
                ],
            }
        ),
        Selector("application_access_auth_scheme", tileForm=tileform.appAccessForm, defaultValue="vmr_internal", enumValues=[Option("vmr_internal", "VMR Internal"), Option("ldap_server", "LDAP Server")]),
        Parameter("vmr_admin_password", tileForm=tileform.mgmtAccessForm, parameterType=parametertypes.Password, placeholder="admin password"),
        Selector("management_access_auth_scheme", tileForm=tileform.mgmtAccessForm, defaultValue="vmr_internal", enumValues=[Option("vmr_internal", "VMR Internal"), Option("ldap_server", "LDAP Server")],
            parameters={
                "ldap_server": [
                    Parameter("ldap_mgmt_read_only_groups", optional=True, placeholder="'cn=readonly,cn=groups,dc=example,dc=com'"),
                    Parameter("ldap_mgmt_read_write_groups", optional=True, placeholder="'cn=readwrite,cn=groups,dc=example,dc=com'"),
                    Parameter("ldap_mgmt_admin_groups", optional=True, placeholder="'cn=admin,cn=groups,dc=example,dc=com'")
                ]
            }
        ),
Exemple #22
0
 def __init__(self):
     labels = ['init', 'lift_up', 'adj_ev', 'finish']
     Option.__init__(self, labels, 'finish')
     self.arm_angles = None
     self.tar_pos = None
Exemple #23
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('ConvertAll')
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip'):  # for py2exe
            modPath = os.path.dirname(modPath)
        iconPathList = [iconPath, os.path.join(modPath, 'icons/'),
                         os.path.join(modPath, '../icons')]
        self.icons = icondict.IconDict()
        self.icons.addIconPath([path for path in iconPathList if path])
        try:
            QApplication.setWindowIcon(self.icons['convertall_med'])
        except KeyError:
            pass
        self.helpView = None
        self.basesDialog = None
        self.fractionDialog = None
        self.option = Option('convertall', 25)
        self.option.loadAll(optiondefaults.defaultList)
        self.colorSet = colorset.ColorSet(self.option)
        if self.option.strData('ColorTheme') != 'system':
            self.colorSet.setAppColors()
        self.sysFont = self.font()
        self.guiFont = None
        fontStr = self.option.strData('GuiFont', True)
        if fontStr:
            guiFont = self.font()
            if guiFont.fromString(fontStr):
                QApplication.setFont(guiFont)
                self.guiFont = guiFont
        self.recentUnits = recentunits.RecentUnits(self.option)
        try:
            num = ConvertDlg.unitData.readData()
        except unitdata.UnitDataError as text:
            QMessageBox.warning(self, 'ConvertAll',
                                _('Error in unit data - {0}').  format(text))
            sys.exit(1)
        try:
            print(_('{0} units loaded').format(num))
        except UnicodeError:
            print('{0} units loaded'.format(num))
        self.fromGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.toGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.unitButtons = []
        self.textButtons = []

        topLayout = QHBoxLayout(self)    # divide main, buttons
        mainLayout = QVBoxLayout()
        mainLayout.setSpacing(8)
        topLayout.addLayout(mainLayout)
        unitLayout = QGridLayout()       # unit selection
        unitLayout.setVerticalSpacing(3)
        unitLayout.setHorizontalSpacing(20)
        mainLayout.addLayout(unitLayout)

        fromLabel = QLabel(_('From Unit'))
        unitLayout.addWidget(fromLabel, 0, 0)
        self.fromUnitEdit = unitedit.UnitEdit(self.fromGroup)
        unitLayout.addWidget(self.fromUnitEdit, 1, 0)
        self.fromUnitEdit.setFocus()

        toLabel = QLabel(_('To Unit'))
        unitLayout.addWidget(toLabel, 0, 1)
        self.toUnitEdit = unitedit.UnitEdit(self.toGroup)
        unitLayout.addWidget(self.toUnitEdit, 1, 1)
        self.fromUnitEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toUnitEdit.gotFocus.connect(self.fromUnitEdit.setInactive)

        vertButtonLayout = QVBoxLayout()
        vertButtonLayout.setSpacing(2)
        mainLayout.addLayout(vertButtonLayout)

        self.unitListView = unitlistview.UnitListView(ConvertDlg.unitData)
        mainLayout.addWidget(self.unitListView)
        self.fromUnitEdit.currentChanged.connect(self.unitListView.
                                                 updateFiltering)
        self.toUnitEdit.currentChanged.connect(self.unitListView.
                                               updateFiltering)
        self.fromUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.toUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.unitListView.unitChanged.connect(self.fromUnitEdit.unitUpdate)
        self.unitListView.unitChanged.connect(self.toUnitEdit.unitUpdate)
        self.unitListView.haveCurrentUnit.connect(self.enableButtons)
        self.unitListView.setFocusPolicy(Qt.NoFocus)

        textButtonLayout = QHBoxLayout()
        textButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(textButtonLayout)
        textButtonLayout.addStretch(1)
        self.textButtons.append(QPushButton('{0} (^2)'.format(_('Square'))))
        self.textButtons.append(QPushButton('{0} (^3)'.format(_('Cube'))))
        self.textButtons.append(QPushButton('{0} (*)'.format(_('Multiply'))))
        self.textButtons.append(QPushButton('{0} (/)'.format(_('Divide'))))
        for button in self.textButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            textButtonLayout.addWidget(button)
            button.clicked.connect(self.unitListView.addUnitText)
        textButtonLayout.addStretch(1)

        unitButtonLayout = QHBoxLayout()
        unitButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(unitButtonLayout)
        unitButtonLayout.addStretch(1)
        self.clearButton = QPushButton(_('Clear Unit'))
        self.clearButton.clicked.connect(self.unitListView.clearUnitText)
        self.recentButton = QPushButton(_('Recent Unit'))
        self.recentButton.clicked.connect(self.recentMenu)
        self.filterButton = QPushButton(_('Filter List'))
        self.filterButton.clicked.connect(self.filterMenu)
        self.unitButtons = [self.clearButton, self.recentButton,
                            self.filterButton]
        for button in self.unitButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            unitButtonLayout.addWidget(button)
        unitButtonLayout.addStretch(1)
        self.showHideButtons()

        numberLayout = QGridLayout()
        numberLayout.setVerticalSpacing(3)
        mainLayout.addLayout(numberLayout)
        statusLabel = QLabel(_('Set units'))
        statusLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        mainLayout.addWidget(statusLabel)

        fromNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(fromNumLabel, 0, 0)
        self.fromNumEdit = numedit.NumEdit(self.fromGroup, self.toGroup,
                                           fromNumLabel, statusLabel,
                                           self.recentUnits, True)
        numberLayout.addWidget(self.fromNumEdit, 1, 0)
        self.fromUnitEdit.unitChanged.connect(self.fromNumEdit.unitUpdate)
        self.fromNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.fromNumEdit.setEnabled(False)
        equalsLabel = QLabel(' = ')
        equalsLabel.setFont(QFont(self.font().family(), 20))
        numberLayout.addWidget(equalsLabel, 0, 1, 2, 1)

        toNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(toNumLabel, 0, 3)
        self.toNumEdit = numedit.NumEdit(self.toGroup, self.fromGroup,
                                         toNumLabel, statusLabel,
                                         self.recentUnits, False)
        numberLayout.addWidget(self.toNumEdit, 1, 3)
        self.toUnitEdit.unitChanged.connect(self.toNumEdit.unitUpdate)
        self.toNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.toNumEdit.setEnabled(False)
        self.fromNumEdit.convertNum.connect(self.toNumEdit.setNum)
        self.toNumEdit.convertNum.connect(self.fromNumEdit.setNum)
        self.fromNumEdit.convertRqd.connect(self.toNumEdit.convert)
        self.toNumEdit.convertRqd.connect(self.fromNumEdit.convert)

        buttonLayout = QVBoxLayout()     # major buttons
        topLayout.addLayout(buttonLayout)
        closeButton = QPushButton(_('&Close'))
        buttonLayout.addWidget(closeButton)
        closeButton.setFocusPolicy(Qt.NoFocus)
        closeButton.clicked.connect(self.close)
        optionsButton = QPushButton(_('&Options...'))
        buttonLayout.addWidget(optionsButton)
        optionsButton.setFocusPolicy(Qt.NoFocus)
        optionsButton.clicked.connect(self.changeOptions)
        basesButton = QPushButton(_('&Bases...'))
        buttonLayout.addWidget(basesButton)
        basesButton.setFocusPolicy(Qt.NoFocus)
        basesButton.clicked.connect(self.showBases)
        fractionsButton = QPushButton(_('&Fractions...'))
        buttonLayout.addWidget(fractionsButton)
        fractionsButton.setFocusPolicy(Qt.NoFocus)
        fractionsButton.clicked.connect(self.showFractions)
        helpButton = QPushButton(_('&Help...'))
        buttonLayout.addWidget(helpButton)
        helpButton.setFocusPolicy(Qt.NoFocus)
        helpButton.clicked.connect(self.help)
        aboutButton = QPushButton(_('&About...'))
        buttonLayout.addWidget(aboutButton)
        aboutButton.setFocusPolicy(Qt.NoFocus)
        aboutButton.clicked.connect(self.about)
        buttonLayout.addStretch()

        if self.option.boolData('RemenberDlgPos'):
            rect = QRect(self.option.intData('MainDlgXPos', 0, 10000),
                         self.option.intData('MainDlgYPos', 0, 10000),
                         self.option.intData('MainDlgXSize', 0, 10000),
                         self.option.intData('MainDlgYSize', 0, 10000))
            if rect.isValid():
                availRect = (QApplication.primaryScreen().
                             availableVirtualGeometry())
                topMargin = self.option.intData('MainDlgTopMargin', 0, 1000)
                otherMargin = self.option.intData('MainDlgOtherMargin', 0,
                                                  1000)
                # remove frame space from available rect
                availRect.adjust(otherMargin, topMargin,
                                 -otherMargin, -otherMargin)
                finalRect = rect.intersected(availRect)
                if finalRect.isEmpty():
                    rect.moveTo(0, 0)
                    finalRect = rect.intersected(availRect)
                if finalRect.isValid():
                    self.setGeometry(finalRect)
        if self.option.boolData('LoadLastUnit') and len(self.recentUnits) > 1:
            self.fromGroup.update(self.recentUnits[0])
            self.fromUnitEdit.unitUpdate()
            self.toGroup.update(self.recentUnits[1])
            self.toUnitEdit.unitUpdate()
            self.unitListView.updateFiltering()
            self.fromNumEdit.setFocus()
            self.fromNumEdit.selectAll()
        if self.option.boolData('ShowStartupTip'):
            self.show()
            tipDialog = TipDialog(self.option, self)
            tipDialog.exec_()
Exemple #24
0
class Daemon:

	def __init__(self, project_file):
		self.config = None
		self.option = None
		self.project = None

		# resource attributes
		self.cloud = None
		self.database = None
		self.schedule = None

		# project file controls configuration
		self.project_file = project_file

	@staticmethod
	def cleanup():
		"""Override: Optional cleanup code."""
		logger.info('Application exit')

	def main(self):
		"""Override: Main code goes here."""
		pass

	def run(self, *args, **kwargs):
		"""
		Options
		--onetime[=1] run once, then exit; use if called by an external scheduler.
		--nonwait[=1] run immediately without waiting for scheduler to determine execution.
		"""

		# make sure root sessions folder exists
		create_folder('../sessions')

		# TODO: We start logging before we read config and options so we don't know datapool or anything else.
		# TODO: We should log to a default app log and then SWITCH LOG file over after we process options and
		# TODO: and config files ??? (2018-09-25)
		log_setup(log_file_name=f'../sessions/{script_name()}.log')
		log_session_info()

		self.setup(*args, **kwargs)
		self.start()

		# scheduling behavior based on --onetime, --nowait option
		if self.option('onetime') == '1':
			# one-time run; use when this script is being called by an external scheduler
			logger.info('Option(onetime=1): executing once')
			self.main()
		else:
			if self.option('nowait') == '1':
				# no-wait option; execute immediately without waiting for scheduler to initiate
				logger.info('Option(nowait=1): executing immediately, then following regular schedule')
				self.main()

			# standard wait for scheduled time slot and run logic
			while True:
				if self.schedule.wait():
					self.main()
				else:
					break

		self.cleanup()

	def setup(self, *args, **kwargs):
		"""Override: Optional setup code (called once)."""
		pass

	def start(self):
		"""
		Override: Code called on initial start and subsequent restarts.

		Must set:
		- self.option = Option()
		- self.schedule = Schedule()

		Note: We don't load resources here; resources are loaded on demand.
		"""

		# load standard config
		config = ConfigSectionKey('../conf', '../local')
		self.config = config
		config.load('bootstrap.ini', 'bootstrap')
		config.load('init.ini')
		config.load('connect.ini')

		# load project specific config
		self.config.load(self.project_file)

		# load project specific options from optional project specific environ var
		environ_var = just_file_stem(self.project_file).lower()
		self.option = Option(environ_var, options=config('project').options)

		# load project specific schedule
		self.schedule = Schedule(config('schedule'))

		# diagnostics
		self.option.dump()
		self.config('project').dump(False)
		self.config('schedule').dump(False)
Exemple #25
0
 def resolve(self, src: SourceFile):
     ctx: PlayParser.CompilationUnitContext = Option().nodes[src]
     for i in ctx.importDeclaration():
         cls = SymbolTable().get_class(i.qualifiedName().getText())
         src.imports[cls.name] = cls
Exemple #26
0
        mkdir = input('* mkdir option [true/false]: ')
    option_info['mkdir'] = True if mkdir == 'true' else False
    if mkdir == 'true':
        option_info['dir_name'] = input('* Directory name format: ')
    option_info['source_name'] = input('* Source name format: ')

    return option_info


if __name__ == '__main__':
    try:
        if os.path.isdir(DEFAULT_DOWNLOAD_DIR):
            sys.exit(ERROR_FORMAT % ('init', "Directory '%s' already exists") %
                     DEFAULT_DOWNLOAD_DIR)
        os.makedirs(DEFAULT_DOWNLOAD_DIR)

        network = Network()
        user_id = input('* BOJ id: ')
        user_password = getpass.getpass('* BOJ password: '******'login', result))
        print(PRINT_FORMAT % (result))

        option_info = set_options()
        option = Option(option_info)

        Main(network, option).run()
    except KeyboardInterrupt:
        print('\n* bye\n')
Exemple #27
0
 def parse_option_metadata(self, option_metadata):
     for metadata in option_metadata:
         expiry = metadata['expiry']
         [year, month, day] = expiry.split('-')
         expiry = datetime.datetime(year=int(year), month=int(month), day=int(day), tzinfo=pytz.UTC)
         option_type = metadata['type']
         strike = int(float(metadata['strike']))
         option = Option(underlying_pair=self.underlying_pair,
                         option_type=option_type,
                         strike=strike,
                         expiry=expiry
                         )
         option.delta = float(metadata['delta'])
         option.gamma = float(metadata['gamma'])
         option.theta = float(metadata['theta'])
         option.wvega = float(metadata['wvega'])
         option.vega = float(metadata['vega'])
         option.vol = float(metadata['vol'])
         if 'best_bid' in metadata:
             option.best_bid = ast.literal_eval(metadata['best_bid'])
         if 'best_ask' in metadata:
             option.best_ask = ast.literal_eval(metadata['best_ask'])
         if 'exchange_symbol' in metadata:
             option.exchange_symbol = metadata['exchange_symbol']
         if option_type not in self.options:
             self.options[option_type] = {}
         if expiry not in self.options[option_type]:
             self.options[option_type][expiry] = {}
         self.options[option_type][expiry][strike] = option
         self.options_by_name[option.exchange_symbol] = option
Exemple #28
0
 def set_option(self, options: dict):
     o = Option()
     o.set_extra_vars(options)
     return o.result
#!/usr/bin python
# -*- coding: utf-8 -*-
from option import Option

option = Option()
option.print_options()
option.check_multi_option()
Exemple #30
0
 def __init__(self):
     labels = ['init', 'pre_armbk', 'hold', 'finish']
     Option.__init__(self, labels, 'finish')
     self.pre_arm_angles = device.pre_arm_angles
     self.pre_armbk_angles = [-90, 0, 90, 0, 0]
     self.armbk_angles = [-90, -60, 60, 90, 0]
Exemple #31
0
def drawLeaderboardMenu(DISPLAYSURF):
    DISPLAYSURF.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    connection = mysql.connector.connect(user = config.USER, password = config.PASSWORD, host = config.HOST, database = config.DATABASE)
    cursor = connection.cursor()

    query = ("SELECT name, total_kills FROM high_scores "
         "ORDER BY total_kills DESC "
         "LIMIT 10")

    cursor.execute(query)

    x_spacing = 250
    y_spacing = 0

    for (name, score) in cursor:
        name_option = Option(DISPLAYSURF, BLUE, font, "Name: " + str(name), (config.display_x // 2 - config.display_x // 4, (config.display_y // 5 + y_spacing)))
        score_option = Option(DISPLAYSURF, BLUE, font, "Score: " + str(score), (config.display_x // 2 + config.display_x // 10, (config.display_y // 5 + y_spacing)))
        name_option.draw()
        score_option.draw()
        y_spacing += 50

    back_option = Option(DISPLAYSURF, BLUE, font, "BACK", (config.display_x // 2 - len("BACK") * 10, (config.display_y - 100)))
    while(True):
        for event in pygame.event.get():
            if back_option.rect.collidepoint(pygame.mouse.get_pos()):
                back_option.hovered = True
                #sound_hover_menu_item.play()
                if event.type == MOUSEBUTTONUP:
                    # play sound
                    sound_select_menu_item.play()
                    cursor.close()
                    connection.close()
                    drawMainMenu(DISPLAYSURF)
                    return
            else:
                back_option.hovered = False
        pygame.display.update()
        back_option.draw()
    cursor.close()
    connection.close()
Exemple #32
0
class ConvertDlg(QWidget):
    """Main dialog for ConvertAll program.
    """
    unitData = unitdata.UnitData()
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('ConvertAll')
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip'):  # for py2exe
            modPath = os.path.dirname(modPath)
        iconPathList = [iconPath, os.path.join(modPath, 'icons/'),
                         os.path.join(modPath, '../icons')]
        self.icons = icondict.IconDict()
        self.icons.addIconPath([path for path in iconPathList if path])
        try:
            QApplication.setWindowIcon(self.icons['convertall_med'])
        except KeyError:
            pass
        self.helpView = None
        self.basesDialog = None
        self.fractionDialog = None
        self.option = Option('convertall', 25)
        self.option.loadAll(optiondefaults.defaultList)
        self.colorSet = colorset.ColorSet(self.option)
        if self.option.strData('ColorTheme') != 'system':
            self.colorSet.setAppColors()
        self.sysFont = self.font()
        self.guiFont = None
        fontStr = self.option.strData('GuiFont', True)
        if fontStr:
            guiFont = self.font()
            if guiFont.fromString(fontStr):
                QApplication.setFont(guiFont)
                self.guiFont = guiFont
        self.recentUnits = recentunits.RecentUnits(self.option)
        try:
            num = ConvertDlg.unitData.readData()
        except unitdata.UnitDataError as text:
            QMessageBox.warning(self, 'ConvertAll',
                                _('Error in unit data - {0}').  format(text))
            sys.exit(1)
        try:
            print(_('{0} units loaded').format(num))
        except UnicodeError:
            print('{0} units loaded'.format(num))
        self.fromGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.toGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.unitButtons = []
        self.textButtons = []

        topLayout = QHBoxLayout(self)    # divide main, buttons
        mainLayout = QVBoxLayout()
        mainLayout.setSpacing(8)
        topLayout.addLayout(mainLayout)
        unitLayout = QGridLayout()       # unit selection
        unitLayout.setVerticalSpacing(3)
        unitLayout.setHorizontalSpacing(20)
        mainLayout.addLayout(unitLayout)

        fromLabel = QLabel(_('From Unit'))
        unitLayout.addWidget(fromLabel, 0, 0)
        self.fromUnitEdit = unitedit.UnitEdit(self.fromGroup)
        unitLayout.addWidget(self.fromUnitEdit, 1, 0)
        self.fromUnitEdit.setFocus()

        toLabel = QLabel(_('To Unit'))
        unitLayout.addWidget(toLabel, 0, 1)
        self.toUnitEdit = unitedit.UnitEdit(self.toGroup)
        unitLayout.addWidget(self.toUnitEdit, 1, 1)
        self.fromUnitEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toUnitEdit.gotFocus.connect(self.fromUnitEdit.setInactive)

        vertButtonLayout = QVBoxLayout()
        vertButtonLayout.setSpacing(2)
        mainLayout.addLayout(vertButtonLayout)

        self.unitListView = unitlistview.UnitListView(ConvertDlg.unitData)
        mainLayout.addWidget(self.unitListView)
        self.fromUnitEdit.currentChanged.connect(self.unitListView.
                                                 updateFiltering)
        self.toUnitEdit.currentChanged.connect(self.unitListView.
                                               updateFiltering)
        self.fromUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.toUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.unitListView.unitChanged.connect(self.fromUnitEdit.unitUpdate)
        self.unitListView.unitChanged.connect(self.toUnitEdit.unitUpdate)
        self.unitListView.haveCurrentUnit.connect(self.enableButtons)
        self.unitListView.setFocusPolicy(Qt.NoFocus)

        textButtonLayout = QHBoxLayout()
        textButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(textButtonLayout)
        textButtonLayout.addStretch(1)
        self.textButtons.append(QPushButton('{0} (^2)'.format(_('Square'))))
        self.textButtons.append(QPushButton('{0} (^3)'.format(_('Cube'))))
        self.textButtons.append(QPushButton('{0} (*)'.format(_('Multiply'))))
        self.textButtons.append(QPushButton('{0} (/)'.format(_('Divide'))))
        for button in self.textButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            textButtonLayout.addWidget(button)
            button.clicked.connect(self.unitListView.addUnitText)
        textButtonLayout.addStretch(1)

        unitButtonLayout = QHBoxLayout()
        unitButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(unitButtonLayout)
        unitButtonLayout.addStretch(1)
        self.clearButton = QPushButton(_('Clear Unit'))
        self.clearButton.clicked.connect(self.unitListView.clearUnitText)
        self.recentButton = QPushButton(_('Recent Unit'))
        self.recentButton.clicked.connect(self.recentMenu)
        self.filterButton = QPushButton(_('Filter List'))
        self.filterButton.clicked.connect(self.filterMenu)
        self.unitButtons = [self.clearButton, self.recentButton,
                            self.filterButton]
        for button in self.unitButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            unitButtonLayout.addWidget(button)
        unitButtonLayout.addStretch(1)
        self.showHideButtons()

        numberLayout = QGridLayout()
        numberLayout.setVerticalSpacing(3)
        mainLayout.addLayout(numberLayout)
        statusLabel = QLabel(_('Set units'))
        statusLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        mainLayout.addWidget(statusLabel)

        fromNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(fromNumLabel, 0, 0)
        self.fromNumEdit = numedit.NumEdit(self.fromGroup, self.toGroup,
                                           fromNumLabel, statusLabel,
                                           self.recentUnits, True)
        numberLayout.addWidget(self.fromNumEdit, 1, 0)
        self.fromUnitEdit.unitChanged.connect(self.fromNumEdit.unitUpdate)
        self.fromNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.fromNumEdit.setEnabled(False)
        equalsLabel = QLabel(' = ')
        equalsLabel.setFont(QFont(self.font().family(), 20))
        numberLayout.addWidget(equalsLabel, 0, 1, 2, 1)

        toNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(toNumLabel, 0, 3)
        self.toNumEdit = numedit.NumEdit(self.toGroup, self.fromGroup,
                                         toNumLabel, statusLabel,
                                         self.recentUnits, False)
        numberLayout.addWidget(self.toNumEdit, 1, 3)
        self.toUnitEdit.unitChanged.connect(self.toNumEdit.unitUpdate)
        self.toNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.toNumEdit.setEnabled(False)
        self.fromNumEdit.convertNum.connect(self.toNumEdit.setNum)
        self.toNumEdit.convertNum.connect(self.fromNumEdit.setNum)
        self.fromNumEdit.convertRqd.connect(self.toNumEdit.convert)
        self.toNumEdit.convertRqd.connect(self.fromNumEdit.convert)

        buttonLayout = QVBoxLayout()     # major buttons
        topLayout.addLayout(buttonLayout)
        closeButton = QPushButton(_('&Close'))
        buttonLayout.addWidget(closeButton)
        closeButton.setFocusPolicy(Qt.NoFocus)
        closeButton.clicked.connect(self.close)
        optionsButton = QPushButton(_('&Options...'))
        buttonLayout.addWidget(optionsButton)
        optionsButton.setFocusPolicy(Qt.NoFocus)
        optionsButton.clicked.connect(self.changeOptions)
        basesButton = QPushButton(_('&Bases...'))
        buttonLayout.addWidget(basesButton)
        basesButton.setFocusPolicy(Qt.NoFocus)
        basesButton.clicked.connect(self.showBases)
        fractionsButton = QPushButton(_('&Fractions...'))
        buttonLayout.addWidget(fractionsButton)
        fractionsButton.setFocusPolicy(Qt.NoFocus)
        fractionsButton.clicked.connect(self.showFractions)
        helpButton = QPushButton(_('&Help...'))
        buttonLayout.addWidget(helpButton)
        helpButton.setFocusPolicy(Qt.NoFocus)
        helpButton.clicked.connect(self.help)
        aboutButton = QPushButton(_('&About...'))
        buttonLayout.addWidget(aboutButton)
        aboutButton.setFocusPolicy(Qt.NoFocus)
        aboutButton.clicked.connect(self.about)
        buttonLayout.addStretch()

        if self.option.boolData('RemenberDlgPos'):
            rect = QRect(self.option.intData('MainDlgXPos', 0, 10000),
                         self.option.intData('MainDlgYPos', 0, 10000),
                         self.option.intData('MainDlgXSize', 0, 10000),
                         self.option.intData('MainDlgYSize', 0, 10000))
            if rect.isValid():
                availRect = (QApplication.primaryScreen().
                             availableVirtualGeometry())
                topMargin = self.option.intData('MainDlgTopMargin', 0, 1000)
                otherMargin = self.option.intData('MainDlgOtherMargin', 0,
                                                  1000)
                # remove frame space from available rect
                availRect.adjust(otherMargin, topMargin,
                                 -otherMargin, -otherMargin)
                finalRect = rect.intersected(availRect)
                if finalRect.isEmpty():
                    rect.moveTo(0, 0)
                    finalRect = rect.intersected(availRect)
                if finalRect.isValid():
                    self.setGeometry(finalRect)
        if self.option.boolData('LoadLastUnit') and len(self.recentUnits) > 1:
            self.fromGroup.update(self.recentUnits[0])
            self.fromUnitEdit.unitUpdate()
            self.toGroup.update(self.recentUnits[1])
            self.toUnitEdit.unitUpdate()
            self.unitListView.updateFiltering()
            self.fromNumEdit.setFocus()
            self.fromNumEdit.selectAll()
        if self.option.boolData('ShowStartupTip'):
            self.show()
            tipDialog = TipDialog(self.option, self)
            tipDialog.exec_()

    def recentMenu(self):
        """Show a menu with recently used units.
        """
        button = self.sender()
        menu = QMenu()
        for unit in self.recentUnits:
            action = menu.addAction(unit)
        menu.triggered.connect(self.insertRecent)
        menu.exec_(button.mapToGlobal(QPoint(0, 0)))

    def insertRecent(self, action):
        """Insert the recent unit from the given action.
        """
        editor = (self.fromUnitEdit if self.fromUnitEdit.activeEditor else
                  self.toUnitEdit)
        editor.unitGroup.update(action.text())
        editor.unitUpdate()
        self.unitListView.updateFiltering()

    def filterMenu(self):
        """Show a menu with unit types for filtering or clear filter if set.
        """
        if self.unitListView.typeFilter:  # clear filter
            self.unitListView.typeFilter = ''
            self.unitListView.updateFiltering()
            self.filterButton.setText(_('Filter List'))
        else:  # show filter menu
            button = self.sender()
            menu = QMenu()
            for unitType in ConvertDlg.unitData.typeList:
                action = menu.addAction(unitType)
            menu.triggered.connect(self.startTypeFilter)
            menu.exec_(button.mapToGlobal(QPoint(0, 0)))

    def startTypeFilter(self, action):
        """Start type filter based on the given action.
        """
        self.unitListView.typeFilter = action.text()
        self.unitListView.updateFiltering()
        self.filterButton.setText(_('Clear Filter'))

    def enableButtons(self, editActive, hasUnit):
        """Enable text editing buttons if have a current unit.
        """
        for button in self.textButtons:
            button.setEnabled(hasUnit)
        self.clearButton.setEnabled(editActive)
        self.recentButton.setEnabled(editActive and len(self.recentUnits))

    def showHideButtons(self):
        """Show or hide text modify buttons.
        """
        textButtonsVisible = self.option.boolData('ShowOpButtons')
        unitButtonsVisible = self.option.boolData('ShowUnitButtons')
        for button in self.textButtons:
            if textButtonsVisible:
                button.show()
            else:
                button.hide()
        for button in self.unitButtons:
            if unitButtonsVisible:
                button.show()
            else:
                button.hide()

    def changeOptions(self):
        """Show dialog for option changes.
        """
        dlg = optiondlg.OptionDlg(self.option, self)
        dlg.startGroupBox(_('Result Precision'))
        optiondlg.OptionDlgInt(dlg, 'DecimalPlaces', _('Decimal places'),
                               0, UnitGroup.maxDecPlcs)
        dlg.endGroupBox()
        optiondlg.OptionDlgRadio(dlg, 'Notation', _('Result Display'),
                              [('general', _('Use short representation')),
                               ('fixed', _('Use fixed decimal places')),
                               ('scientific', _('Use scientific notation')),
                               ('engineering', _('Use engineering notation'))])
        dlg.startGroupBox(_('Recent Units'))
        optiondlg.OptionDlgInt(dlg, 'RecentUnits', _('Number saved'), 2, 99)
        optiondlg.OptionDlgBool(dlg, 'LoadLastUnit',
                                _('Load last units at startup'))
        dlg.startGroupBox(_('User Interface'))
        optiondlg.OptionDlgBool(dlg, 'ShowOpButtons',
                                _('Show operator buttons (1st row)'))
        optiondlg.OptionDlgBool(dlg, 'ShowUnitButtons',
                                _('Show unit buttons (2nd row)'))
        optiondlg.OptionDlgBool(dlg, 'ShowStartupTip',
                                _('Show tip at startup'))
        optiondlg.OptionDlgBool(dlg, 'RemenberDlgPos',
                                _('Remember window position'))
        dlg.startGroupBox(_('Appearance'))
        optiondlg.OptionDlgPush(dlg, _('Set GUI Colors'), self.showColorDlg)
        optiondlg.OptionDlgPush(dlg, _('Set GUI Fonts'), self.showFontDlg)
        if dlg.exec_() == QDialog.Accepted:
            self.option.writeChanges()
            self.recentUnits.updateQuantity()
            self.showHideButtons()
            self.fromNumEdit.unitUpdate()
            self.toNumEdit.unitUpdate()

    def showColorDlg(self):
        """Show the color change dialog.
        """
        self.colorSet.showDialog(self)

    def showFontDlg(self):
        """Show the custom font dialog.
        """
        dialog = fontset.CustomFontDialog(self.sysFont, self.guiFont, self)
        if dialog.exec_() == QDialog.Accepted:
            newFont = dialog.resultingFont()
            if newFont:
                self.option.changeData('GuiFont', newFont.toString(), True)
                self.guiFont = newFont
            else:   # use system font
                self.option.changeData('GuiFont', '', True)
                self.guiFont = None
                newFont = self.sysFont
            QApplication.setFont(newFont)

    def showBases(self):
        """Show the dialog for base conversions.
        """
        if not self.basesDialog:
            self.basesDialog = bases.BasesDialog()
        self.basesDialog.show()

    def showFractions(self):
        """Show the dialog for fraction conversions.
        """
        if not self.fractionDialog:
            self.fractionDialog = bases.FractionDialog()
        self.fractionDialog.show()

    def findHelpFile(self):
        """Return the path to the help file.
        """
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip'):  # for py2exe
            modPath = os.path.dirname(modPath)
        pathList = [helpFilePath, os.path.join(modPath, '../doc/'),
                    modPath, os.path.join(modPath, 'doc/')]
        fileList = ['README.html']
        if lang and lang != 'C':
            fileList[0:0] = ['README_{0}.html'.format(lang),
                             'README_{0}.html'.format(lang[:2])]
        for path in [path for path in pathList if path]:
            for fileName in fileList:
                fullPath = os.path.join(path, fileName)
                if os.access(fullPath, os.R_OK):
                    return fullPath
        return ''

    def help(self):
        """View the ReadMe file.
        """
        if not self.helpView:
            path = self.findHelpFile()
            if not path:
                QMessageBox.warning(self, 'ConvertAll',
                                    _('Read Me file not found'))
                return
            self.helpView = helpview.HelpView(path,
                                              _('ConvertAll README File'),
                                              self.icons)
        self.helpView.show()

    def about(self):
        """Show about info.
        """
        QMessageBox.about(self, 'ConvertAll',
                          _('ConvertAll Version {0}\nby {1}').
                          format(__version__, __author__))

    def closeEvent(self, event):
        """Save window data on close.
        """
        if self.option.boolData('RemenberDlgPos'):
            contentsRect = self.geometry()
            frameRect = self.frameGeometry()
            self.option.changeData('MainDlgXSize', contentsRect.width(), True)
            self.option.changeData('MainDlgYSize', contentsRect.height(), True)
            self.option.changeData('MainDlgXPos', contentsRect.x(), True)
            self.option.changeData('MainDlgYPos', contentsRect.y(), True)
            self.option.changeData('MainDlgTopMargin',
                                   contentsRect.y() - frameRect.y(), True)
            self.option.changeData('MainDlgOtherMargin',
                                   contentsRect.x() - frameRect.x(), True)
        self.recentUnits.writeList()
        self.option.writeChanges()
        event.accept()
class ConvertDlg(QtGui.QWidget):
    """Main dialog for ConvertAll program"""
    unitData = unitdata.UnitData()
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('ConvertAll')
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip'):  # for py2exe
            modPath = os.path.dirname(modPath)
        iconPathList = [iconPath, os.path.join(modPath, 'icons/'),
                         os.path.join(modPath, '../icons')]
        self.icons = icondict.IconDict()
        self.icons.addIconPath(filter(None, iconPathList))
        try:
            QtGui.QApplication.setWindowIcon(self.icons['convertall_med'])
        except KeyError:
            pass
        self.helpView = None
        self.findDlg = None
        self.option = Option('convertall', 20)
        self.option.loadAll(optiondefaults.defaultList)
        try:
            num = ConvertDlg.unitData.readData()
            print '%d units loaded' % num
        except unitdata.UnitDataError, text:
            QtGui.QMessageBox.warning(self, 'ConvertAll',
                                      'Error in unit data - %s' % text)
            sys.exit(1)
        self.fromGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.toGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.origPal = QtGui.QApplication.palette()
        self.updateColors()
        self.textButtons = []

        topLayout = QtGui.QHBoxLayout(self)    # divide main, buttons
        mainLayout = QtGui.QVBoxLayout()
        topLayout.addLayout(mainLayout)
        unitLayout = QtGui.QHBoxLayout()       # unit selection
        mainLayout.addLayout(unitLayout)

        fromBox = QtGui.QGroupBox('From Unit')
        unitLayout.addWidget(fromBox)
        fromLayout = QtGui.QVBoxLayout(fromBox)
        fromLayout.setSpacing(3)
        self.fromUnitEdit = unitedit.UnitEdit(self.fromGroup)
        fromLayout.addWidget(self.fromUnitEdit)
        self.fromUnitEdit.setFocus()
        self.fromUnitListView = unitlistview.UnitListView(self.fromGroup, 0)
        fromLayout.addWidget(self.fromUnitListView)
        self.connect(self.fromUnitEdit, QtCore.SIGNAL('currentChanged'),
                     self.fromUnitListView.updateSelection)
        self.connect(self.fromUnitListView, QtCore.SIGNAL('unitChanged'),
                     self.fromUnitEdit.unitUpdate)
        self.fromUnitListView.setFocusProxy(self.fromUnitEdit)
        self.addButtons(self.fromGroup, self.fromUnitListView, fromLayout)

        toBox = QtGui.QGroupBox('To Unit')
        unitLayout.addWidget(toBox)
        toLayout = QtGui.QVBoxLayout(toBox)
        toLayout.setSpacing(3)
        self.toUnitEdit = unitedit.UnitEdit(self.toGroup)
        toLayout.addWidget(self.toUnitEdit)
        self.toUnitListView = unitlistview.UnitListView(self.toGroup, 1)
        toLayout.addWidget(self.toUnitListView)
        self.connect(self.toUnitEdit, QtCore.SIGNAL('currentChanged'),
                     self.toUnitListView.updateSelection)
        self.connect(self.toUnitListView, QtCore.SIGNAL('unitChanged'),
                     self.toUnitEdit.unitUpdate)
        self.toUnitListView.setFocusProxy(self.toUnitEdit)
        self.addButtons(self.toGroup, self.toUnitListView, toLayout)
        self.showHideButtons()

        numberLayout = QtGui.QHBoxLayout()
        mainLayout.addLayout(numberLayout)
        statusLabel = QtGui.QLabel('Set units')
        statusLabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
        mainLayout.addWidget(statusLabel)

        fromNumBox = QtGui.QGroupBox('No Unit Set')
        numberLayout.addWidget(fromNumBox)
        fromNumLayout = QtGui.QVBoxLayout(fromNumBox)
        self.fromNumEdit = numedit.NumEdit(self.fromGroup, self.toGroup,
                                           fromNumBox, statusLabel, True)
        fromNumLayout.addWidget(self.fromNumEdit)
        self.connect(self.fromUnitEdit, QtCore.SIGNAL('unitChanged'),
                     self.fromNumEdit.unitUpdate)
        self.fromNumEdit.setEnabled(False)
        equalsLabel = QtGui.QLabel(' = ')
        equalsLabel.setFont(QtGui.QFont(self.font().family(), 30))
        numberLayout.addWidget(equalsLabel)

        toNumBox = QtGui.QGroupBox('No Unit Set')
        numberLayout.addWidget(toNumBox)
        toNumLayout = QtGui.QVBoxLayout(toNumBox)
        self.toNumEdit = numedit.NumEdit(self.toGroup, self.fromGroup,
                                         toNumBox, statusLabel, False)
        toNumLayout.addWidget(self.toNumEdit)
        self.connect(self.toUnitEdit, QtCore.SIGNAL('unitChanged'),
                     self.toNumEdit.unitUpdate)
        self.toNumEdit.setEnabled(False)
        self.connect(self.fromNumEdit, QtCore.SIGNAL('convertNum(QString &)'),
                     self.toNumEdit.setNum)
        self.connect(self.toNumEdit, QtCore.SIGNAL('convertNum(QString &)'),
                     self.fromNumEdit.setNum)
        self.connect(self.fromNumEdit, QtCore.SIGNAL('convertRqd'),
                     self.toNumEdit.convert)
        self.connect(self.toNumEdit, QtCore.SIGNAL('convertRqd'),
                     self.fromNumEdit.convert)

        buttonLayout = QtGui.QVBoxLayout()     # major buttons
        topLayout.addLayout(buttonLayout)
        closeButton = QtGui.QPushButton('&Close')
        buttonLayout.addWidget(closeButton)
        closeButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.connect(closeButton, QtCore.SIGNAL('clicked()'), self.close)
        finderButton = QtGui.QPushButton('&Unit Finder...')
        buttonLayout.addWidget(finderButton)
        finderButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.connect(finderButton, QtCore.SIGNAL('clicked()'), self.showFinder)
        optionsButton = QtGui.QPushButton('&Options...')
        buttonLayout.addWidget(optionsButton)
        optionsButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.connect(optionsButton, QtCore.SIGNAL('clicked()'),
                     self.changeOptions)
        helpButton = QtGui.QPushButton('&Help...')
        buttonLayout.addWidget(helpButton)
        helpButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.connect(helpButton, QtCore.SIGNAL('clicked()'), self.help)
        aboutButton = QtGui.QPushButton('&About...')
        buttonLayout.addWidget(aboutButton)
        aboutButton.setFocusPolicy(QtCore.Qt.NoFocus)
        self.connect(aboutButton, QtCore.SIGNAL('clicked()'), self.about)
        buttonLayout.addStretch()

        xSize = self.option.intData('MainDlgXSize', 0, 10000)
        ySize = self.option.intData('MainDlgYSize', 0, 10000)
        if xSize and ySize:
            self.resize(xSize, ySize)
        self.move(self.option.intData('MainDlgXPos', 0, 10000),
                  self.option.intData('MainDlgYPos', 0, 10000))
def main(user, executeTrades, timeInterval, test):
    # TODO: use executeTrades flag to decide whether to trade automatically
    # TODO: execute trades automatically if profit > margin or delta gap > margin
    # TODO: setup tracking for a purchased strangle (i.e. email if profit > margin, or earnings is the next day, or delta spread is large)
    # TODO: analysis tools (option price vs xsigma over time, line for stock price, bar for earnings date), (option prices at different strikes over time), (option price vs delta over time)

    if test:
        print("--------------TEST MODE---------------")

    print(user, executeTrades, timeInterval)
    while True:
        cal = USTradingCalendar()
        eastern = timezone("US/Eastern")
        currentTime = datetime.datetime.now(eastern)
        currentDate = datetime.date.today()
        easternHour = currentTime.hour
        easternMinute = currentTime.minute
        isDuringMarketHours = (easternHour == 6 and easternMinute > 30) or (
            easternHour > 6 and easternHour < 16)
        isWeekday = currentDate.isoweekday() in range(1, 6)
        isTradingHoliday = currentDate in cal.holidays(
            start=currentDate, end=currentDate + datetime.timedelta(days=1))
        if (not isDuringMarketHours or not isWeekday
                or isTradingHoliday) and (not test):
            print(
                "It is either not during market hours or is a holiday. Sleeping until next observation..."
            )
            time.sleep(60 * timeInterval)
            continue

        if not test:
            print("Connecting to IB...")
            ib = ibUtils.connect()

        for symbol in TESTING_WATCH_LIST:
            print("\nSymbol:", symbol)
            print(datetime.datetime.now())
            print("Getting contract...")
            if not test:
                contract = ibUtils.getStockQualifiedContract(symbol, ib)
            print("Getting ticker...")
            if not test:
                ticker = ibUtils.getTicker(contract, ib)
            print("Getting earnings date...")
            if not test:
                earningsDate = ibUtils.getNextEarningsDate(contract, ib)
            else:
                earningsDate = datetime.date(2018, 10, 23)

            if not test:
                stockPrice = ticker.marketPrice()
                print("Getting option details...")
                nextExpiry, optionTickers = ibUtils.getOptions(
                    contract, stockPrice, earningsDate, ib)
            else:
                stockPrice = 23.53
                nextExpiry = datetime.date(2018, 11, 16)

            hv2yr = get2yrVolatility(symbol)
            stock = Stock(symbol, stockPrice)

            if not test:
                options = []
                for optionTicker in optionTickers:
                    if not optionTicker.bid or optionTicker.bid <= 0 or not optionTicker.ask or optionTicker.ask <= 0:
                        continue
                    else:
                        options.append(
                            Option(hv2yr, optionTicker.contract.strike,
                                   optionTicker.contract.right == 'C',
                                   optionTicker.bid, optionTicker.ask,
                                   nextExpiry))
            else:
                options = [
                    Option(hv2yr, 22.0, True, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 23.0, True, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 24.0, True, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 25.0, True, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 22.0, False, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 23.0, False, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 24.0, False, 3.30, 3.35, nextExpiry),
                    Option(hv2yr, 25.0, False, 3.30, 3.35, nextExpiry)
                ]
            for option in options:
                option.setDaySigma(stock)
                if option.daySigma == None:
                    continue
                option.setDelta(stock, hv2yr)
                option.setTimeDecay(stock)

            # TODO: compute delta for options

            cwd = os.getcwd()
            if not test:
                traderPath = os.path.join(cwd, user)

            else:
                testPath = os.path.join(cwd, "test")
                traderPath = os.path.join(testPath, user)
                testExists = os.path.isdir(testPath)
                if not testExists:
                    os.mkdir(testPath)

            stockPath = os.path.join(traderPath, symbol)
            earningsDatePath = os.path.join(stockPath,
                                            earningsDate.strftime("%d%b%Y"))
            expiryDatePath = os.path.join(earningsDatePath,
                                          nextExpiry.strftime("%d%b%Y"))

            traderExists = os.path.isdir(traderPath)
            stockExists = os.path.isdir(stockPath)
            earningsDateExists = os.path.isdir(earningsDatePath)
            expiryDateExists = os.path.isdir(expiryDatePath)

            if not traderExists:
                os.mkdir(traderPath)

            if not stockExists:
                os.mkdir(stockPath)

            if not earningsDateExists:
                os.mkdir(earningsDatePath)

            if not expiryDateExists:
                os.mkdir(expiryDatePath)

            for option in options:
                if option.daySigma == None:
                    continue
                putCall = "call" if option.call else "put"
                optionPath = os.path.join(
                    expiryDatePath,
                    putCall + "_" + str(option.strike) + ".csv")
                optionExists = os.path.exists(optionPath)
                date = datetime.datetime.now().strftime("%d%b%Y%H%M%S")
                if not optionExists:
                    df = pd.DataFrame(columns=[
                        "Datetime", "StockPrice", "OptionPrice", "XSigma",
                        "Delta", "TimeDecayOneDay"
                    ])
                    df.to_csv(optionPath, index=False)

                df = pd.read_csv(optionPath)
                df = df.append(pd.Series(
                    {
                        "Datetime": date,
                        "StockPrice": stock.currentPrice,
                        "OptionPrice": option.cost,
                        "XSigma": option.daySigma / hv2yr,
                        "Delta": option.delta,
                        "TimeDecayOneDay": option.timeDecay
                    },
                    name=date),
                               ignore_index=True)
                df.to_csv(optionPath, index=False)

        ib.disconnect()
        print("Sleeping between observations...\n")
        ib.sleep(60 * timeInterval)
Exemple #35
0
 def __init__(self):
     labels = ['init', 'pre_armbk', 'pre_fetch', 'finish']
     Option.__init__(self, labels, 'finish')
     self.goal_angles = None
     self.pre_prefetch_angles = [0, 0, 150, 0, 0]
Exemple #36
0
def add_options():
    """
    Add expected config params.

    returns:
        list[options]
    """
    options = []

    options.append(Option(section='default',
                          param='filled_taxonomies',
                          type=(list, str),
                          required=True,
                          default_value=None))

    options.append(Option(section='default',
                          param='empty_taxonomies',
                          type=str,
                          required=True,
                          default_value=None))

    options.append(Option(section='default',
                          param='output_taxonomies',
                          type=str,
                          required=True,
                          default_value=None))

    options.append(Option(section='default',
                          param='language',
                          type=str,
                          required=False,
                          default_value='english'))

    options.append(Option(section='default',
                          param='vector_threshold',
                          type=float,
                          required=False,
                          default_value=0.3))

    options.append(Option(section='default',
                          param='vector_space_output',
                          type=str,
                          required=True,
                          default_value=None))

    # word2vec options

    options.append(Option(section='word2vec',
                          param='min_count',
                          type=int,
                          required=False,
                          default_value=0))

    options.append(Option(section='word2vec',
                          param='iter',
                          type=int,
                          required=False,
                          default_value=10))

    options.append(Option(section='word2vec',
                          param='window',
                          type=int,
                          required=False,
                          default_value=5))

    options.append(Option(section='word2vec',
                          param='negative',
                          type=int,
                          required=False,
                          default_value=5))

    options.append(Option(section='word2vec',
                          param='size',
                          type=int,
                          required=False,
                          default_value=50))

    options.append(Option(section='word2vec',
                          param='alpha',
                          type=float,
                          required=False,
                          default_value=0.025))

    options.append(Option(section='word2vec',
                          param='workers',
                          type=int,
                          required=False,
                          default_value=4))

    return options
Exemple #37
0
 def __init__(self, feedbacker):
     self.feedbacker = feedbacker
     self.width = feedbacker.width
     self.height = feedbacker.height
     self.options = [Option.newWithTrue(self.width, self.height)]
Exemple #38
0
    print q
    q.enqueue(*range(9))
    print q
    for i in range(0, len(q)):
        print(q[i], q[-i - 1])
    q.enqueue(*range(9, 12))
    print q
    q.dequeue(5)
    print q
    while len(q):
        print q[0]
        q.dequeue()

    # Test AtariBuffer
    from option import Option
    opt = Option('config.json')
    opt['bufSize'] = 9
    opt['histLen'] = 2
    buffer = AtariBuffer(opt)
    for i in range(1, 3):
        buffer.append(np.ones([1, 1]) * 255 / i, i, i - 1, False)
        buffer.appendAction(0, True)
    buffer.append(np.ones([1, 1]) * 255 / 3, 3, 3 - 1, True)
    buffer.appendAction(0, False)
    for i in range(4, 10):
        buffer.append(np.ones([1, 1]) * 255 / i, i, i - 1, False)
        buffer.appendAction(0, True)
    buffer.append(np.ones([1, 1]) * 255 / 10, 10, 10 - 1, True)
    buffer.appendAction(0, False)
    print 'len:', len(buffer)
    for i in range(len(buffer)):
Exemple #39
0
        strikes = [int(k) for k in strikes]
        strikes.sort()
        logging.info('Available strikes: ' + str(strikes))
        # TODO Show the user which is current underlying price or at least
        # where ATM is at the selection dialog
        selectionList = SelectionList(strikes)
        selectionList.mainloop()
        if selectionList.selection:
            strike = int(selectionList.selection)
            logging.info('Selected ' + str(strike) + ' as calendar strike')
        else:
            logging.info('User quitted')
            sys.exit()

        near_term_opt = Option.from_pandas(df[(df['m_expiry'] == near_term)
                                              & (df['m_strike'] == strike)],
                                           amount=-1)
        next_term_opt = Option.from_pandas(df[(df['m_expiry'] == next_term)
                                              & (df['m_strike'] == strike)],
                                           amount=1)

        calendar = CalendarSpread(near_term_opt, next_term_opt)
        logging.info('Plotting ' + str(near_term) + '/' + str(next_term) +
                     ' risk graph')
        print near_term_opt
        print next_term_opt

        r = 0.01
        t = 0  # TODO set t
        breakevens, max_profit, max_loss = calendar.plot(  # TODO Remove IV
            risk_free_rate=r,
Exemple #40
0
 def __init__(self):
     labels = ['init', 'find_pos', 'go', 'check', 'finish']
     Option.__init__(self, labels, 'finish')
     self.human = None
     self.room = None
Exemple #41
0
    res_rgb = rgb * np.stack(
        (mask_tmp, mask_tmp, mask_tmp), axis=2)  # 二值结果映射到原图
    res_rgb = res_rgb.astype(np.uint8)

    mask_res = mask * res
    damage_ratio = mask_res.sum() / mask.sum()

    # 保存结果
    res_path = r'data\{}\damage-eval-{:.4f}.jpg'.format(opt.name, damage_ratio)
    plt.imsave(res_path, res_rgb)

    return damage_ratio


if __name__ == '__main__':
    opt = Option()
    img = cv2.imread(opt.img_path)
    mask = np.zeros(img.shape[0:2], dtype=np.uint8)
    pts = []

    cv2.namedWindow('image', 0)
    cv2.setMouseCallback('image', on_mouse, [img, mask, pts])

    cv2.imshow('image', img)
    cv2.waitKey(0)

    rgb = plt.imread(opt.img_path)
    mask_tmp = mask.copy().astype(np.float)
    mask_tmp[mask == 1] = 0.5
    mask_tmp[mask == 0] = 1
    res_rgb = rgb * np.stack(
Exemple #42
0
    def backtest(self):

        #now we want to loop through and create options objects that we bought and sold at the roll
        rolled_options = []
        rolled_strikes = []
        rolled_prices = []
        roll_posted = []
        df = self.df
        for index, row in df.iterrows():
            #hardcoding 2 as risk free rate for now
            options_rolled = []
            option_strikes = []
            option_prices = []
            for i, option in enumerate(self.strategy):
                option_type = option[0]
                zscore = option[1]
                buy_sell = option[2]
                #30 delta put
                #problem is we don't know implied vol until we define strike
                #don't know strike until we get implied vol
                #strike = strike_from_delta(row['roll_SPY'],row['roll_days_to_expir']/365,.01,row['roll_VIX']/100,.30,option_type)
                if self.backtest_type == 'constant_margin':
                    if i == 0:
                        strike = calculate_strike(option_type, row['roll_SPY'],
                                                  row['roll_VIX'], zscore)
                        implied_vol = get_implied_vol(option_type, strike,
                                                      row['roll_SPY'],
                                                      row['roll_VIX'],
                                                      row['roll_SKEW'])
                        o = Option(buy_sell, option_type, row['roll_SPY'],
                                   strike, row['roll_days_to_expir'] / 365,
                                   None, .01, implied_vol / 100, 0.03)
                        o.get_price_delta()
                        options_rolled.append([o])
                        option_strikes.append(strike)
                        option_prices.append(o.calc_price)
                        if i == 0:
                            #this is the sold put
                            amt_posted = strike / self.leverage
                        #maitenance = strike1 - strike2
                        #.7 = maitenance / amt_posted
                        #.7 * amt_posted
                        #willing to lose at maximum 70%
                        strike2 = strike - (self.max_loss * amt_posted)
                        implied_vol = get_implied_vol(option_type, strike2,
                                                      row['roll_SPY'],
                                                      row['roll_VIX'],
                                                      row['roll_SKEW'])
                        o2 = Option('BUY', option_type, row['roll_SPY'],
                                    strike2, row['roll_days_to_expir'] / 365,
                                    None, .01, implied_vol / 100, 0.03)
                        o2.get_price_delta()
                        options_rolled.append([o2])
                        option_strikes.append(strike2)
                        option_prices.append(o2.calc_price)

                        #we don't need to get any other options calculations in this strategy
                        break

                else:

                    strike = calculate_strike(option_type, row['roll_SPY'],
                                              row['roll_VIX'], zscore)
                    implied_vol = get_implied_vol(option_type, strike,
                                                  row['roll_SPY'],
                                                  row['roll_VIX'],
                                                  row['roll_SKEW'])
                    o = Option(buy_sell, option_type, row['roll_SPY'], strike,
                               row['roll_days_to_expir'] / 365, None, .01,
                               implied_vol / 100, 0.03)
                    o.get_price_delta()
                    options_rolled.append([o])
                    option_strikes.append(strike)
                    option_prices.append(o.calc_price)
                    if i == 0:
                        #this is the sold put
                        amt_posted = strike / self.leverage

            rolled_options.append(options_rolled)
            rolled_strikes.append(option_strikes)
            rolled_prices.append(option_prices)
            roll_posted.append(amt_posted)
        df['rolled_options'] = rolled_options
        df['rolled_strikes'] = rolled_strikes
        df['rolled_prices'] = rolled_prices
        df['previous_rolled_strikes'] = df['rolled_strikes'].shift(1)
        df['previous_rolled_strikes'] = df['previous_rolled_strikes'].fillna(
            method='bfill')
        df['previous_days_to_expir'] = (
            df['next_expiration'].shift(1).fillna(method='bfill') -
            df['date']).dt.days
        df['roll_posted'] = roll_posted
        df['roll_posted'] = df['roll_posted'].shift(1).fillna(method='bfill')
        #now we create a time series of the same options measured as time decays and the market moves
        options_list = []
        prices_list = []
        delta_list = []
        vega_list = []
        theta_list = []
        gamma_list = []
        portfolio_prices = []
        portfolio_deltas = []
        portfolio_vegas = []
        portfolio_thetas = []
        portfolio_gammas = []
        previous_option_price = []
        maintenances_list = []
        margin_triggers = []

        for index, row in df.iterrows():
            #hardcoding 2 as risk free rate for now
            options = []
            prices = []
            deltas = []
            vegas = []
            thetas = []
            gammas = []
            previous_rolled_option_price = []
            for i, option in enumerate(self.strategy):

                option_type = option[0]
                zscore = option[1]
                buy_sell = option[2]
                strike = row['rolled_strikes'][i]
                implied_vol = get_implied_vol(option_type, strike, row['SPY'],
                                              row['VIX'], row['SKEW'])
                o = Option(buy_sell, option_type, row['SPY'], strike,
                           row['days_to_expir'] / 365, None, .02,
                           implied_vol / 100, 0.03)
                o.get_price_delta()
                options.append([o])
                prices.append(o.calc_price)
                deltas.append(o.delta)
                o.get_vega()
                vegas.append(o.vega)
                o.get_theta()
                thetas.append(o.theta)
                o.get_gamma()
                gammas.append(o.gamma)

                ##caculate price on previously rolled option
                ##if backtester is too slow we could add in a codition that it must be roll to caculate, otherwise previous option = current option

                previous_strike = row['previous_rolled_strikes'][i]
                previous_implied_vol = get_implied_vol(option_type,
                                                       previous_strike,
                                                       row['SPY'], row['VIX'],
                                                       row['SKEW'])
                o_previous = Option(buy_sell, option_type, row['SPY'],
                                    previous_strike,
                                    row['previous_days_to_expir'] / 365, None,
                                    .02, previous_implied_vol / 100, 0.03)
                o_previous.get_price_delta()
                previous_rolled_option_price.append(o_previous.calc_price)

                #-price for sold calls
                #for the sold naked put
                if i == 0:
                    if (len(self.strategy) > 1
                            and (self.strategy[0][2] == 'SELL'
                                 and self.strategy[1][2] == 'BUY')):
                        #then we're doing a spread
                        maintenance = row['previous_rolled_strikes'][0] - row[
                            'previous_rolled_strikes'][1]
                        margin_trigger = maintenance > row['roll_posted']

                    elif self.backtest_type == 'constant_margin':
                        maintenance = row['previous_rolled_strikes'][0] - row[
                            'previous_rolled_strikes'][1]
                        margin_trigger = maintenance > row['roll_posted']

                    else:
                        maintenance = calculate_maintenance_requirements(
                            o_previous, row['SPY'])
                        margin_trigger = maintenance > row['roll_posted']

            previous_option_price.append(previous_rolled_option_price)
            options_list.append(options)
            prices_list.append(prices)
            delta_list.append(deltas)
            vega_list.append(vegas)
            theta_list.append(thetas)
            gamma_list.append(gammas)
            #averages for portfolio attributes
            portfolio_price = sum(prices) / float(len(prices))
            portfolio_delta = sum(deltas) / float(len(deltas))
            portfolio_vega = sum(vegas) / float(len(vegas))
            portfolio_theta = sum(thetas) / float(len(thetas))
            portfolio_gamma = sum(gammas) / float(len(gammas))
            portfolio_prices.append(portfolio_price)
            portfolio_deltas.append(portfolio_delta)
            portfolio_vegas.append(portfolio_vega)
            portfolio_thetas.append(portfolio_theta)
            portfolio_gammas.append(portfolio_gamma)
            maintenances_list.append(maintenance)
            margin_triggers.append(margin_trigger)

        df['previous_option_current_price'] = previous_option_price
        df['options'] = options_list
        df['prices'] = prices_list
        df['deltas'] = delta_list
        df['vegas'] = vega_list
        df['thetas'] = theta_list
        df['gammas'] = gamma_list
        df['portfolio_price'] = portfolio_prices
        df['portfolio_delta'] = portfolio_deltas
        df['portfolio_vega'] = portfolio_vegas
        df['portfolio_theta'] = portfolio_thetas
        df['portfolio_gamma'] = portfolio_gammas
        df['maintenance'] = maintenances_list

        df['previous_prices'] = df['prices'].shift(1)
        df['previous_prices'] = df['previous_prices'].fillna(method='bfill')
        df['margin_trigger'] = margin_triggers

        returns_list = []
        portfolio_returns = []
        for index, row in df.iterrows():
            returns = []
            for i, option in enumerate(self.strategy):
                if i == 0:
                    #log the put's stike to calculate other returns and leverage from
                    #key assumption - all leverage revolves around the sold put
                    previous_rolled_strike = row['previous_rolled_strikes'][i]
                current_price = row['previous_option_current_price'][i]
                previous_price = row['previous_prices'][i]
                ret = (current_price - previous_price) / previous_rolled_strike
                returns.append(ret)
            returns_list.append(returns)
            portfolio_return = sum(returns)
            portfolio_returns.append(portfolio_return)

        df['returns_list'] = returns_list
        df['portfolio_returns_raw'] = portfolio_returns
        #Lever
        df['portfolio_returns_raw'] = df[
            'portfolio_returns_raw'] * self.leverage

        ##initialize delta hedging
        ##short the spy to keep delta at a steady .3
        df['spy_return'] = (df['SPY'] -
                            df['SPY'].shift(1)) / (df['SPY'].shift(1))
        #0 for first return
        #df['spy_return'] = df['spy_return'].fillna(0)

        #lever other portfolio metrics as well like greeks
        df['portfolio_delta'] = df['portfolio_delta'] * self.leverage

        #df['delta_adjustment'] = .6 - df['portfolio_delta']
        #take the delta adjustment one step in the future (that is you look at your portfolio delta at the end of the day and then short the spy by that amount)
        #df['delta_adjustment'] = df['delta_adjustment'].shift(1).fillna(0)

        #df['short_spy_return'] = df['delta_adjustment'] * df['spy_return']
        #df['portfolio_returns_raw'] = df['portfolio_returns_raw'] + df['short_spy_return']

        df['portfolio_vega'] = df['portfolio_vega'] * self.leverage
        df['portfolio_theta'] = df['portfolio_theta'] * self.leverage
        df['portfolio_gamma'] = df['portfolio_gamma'] * self.leverage

        #cum_sum of returns within roll period
        df['roll_period'] = df['roll_date'].shift(1)
        df['roll_period'] = df['roll_period'].fillna(method='bfill')
        df['next_roll_period'] = df['next_roll_date'].shift(1)
        df['next_roll_period'] = df['next_roll_period'].fillna(method='bfill')

        df['roll_cumulative_return_raw'] = df.groupby(
            'roll_period')['portfolio_returns_raw'].cumsum()

        #here we start each roll out with the cumulative returns of rolls before it

        cum_rolls = (df.groupby('next_roll_period')
                     ['roll_cumulative_return_raw'].last() + 1).cumprod()
        cum_rolls = cum_rolls.drop(
            cum_rolls.index[len(cum_rolls) - 1]).rename('previous_roll_return')
        df = df.set_index('roll_period').join(cum_rolls,
                                              how='left').set_index('date')
        df['previous_roll_return'] = df['previous_roll_return'].fillna(1)
        df['daily_returns_cumulative'] = (df['roll_cumulative_return_raw'] +
                                          1) * df['previous_roll_return']
        #df[(df['date'] > '2005-2-25') & (df['date'] < '2011-9-16')]['daily_returns_cumulative'].plot()
        df['roll_period'] = df['roll_date'].shift(1)
        #calculate margin pct
        df['margin_pct'] = df['maintenance'] / df['roll_posted']

        self.results = df
        print('backtest complete')
        return None
Exemple #43
0
    PATH_TO_CKPT = os.path.join(CWD_PATH, "model", MODEL_NAME,
                                "frozen_inference_graph.pb")

    model = Model(PATH_TO_CKPT)
    model.setup()

    PATH_TO_LABELS = os.path.join(CWD_PATH, "label", "mscoco_label_map.pbtxt")

    label = Label(PATH_TO_LABELS)
    label.setup()

    detector = Detector()
    detector.setModel(model)

    opt = Option()
    opt.type = False
    opt.color = False
    opt.speed = True
    opt.stay = False

    tracker = Tracker()

    objectClass = ["bicycle", "car", "motorcycle", "bus", "truck"]

    if args.video is None:
        video_src = 0
    else:
        video_src = args.video

    cap = cv2.VideoCapture(video_src)
Exemple #44
0
class Epilader:
    INTRA_URL = "https://intra.epitech.eu/"
    JSON_CONF = "./Config/conf.json"

    def __init__(self, arg):
        self.curl = pycurl.Curl()
        self.option = Option()
        self.option.parse(arg)
        self.log = Log(self.option.isVerboseMode())
        self.datas = []
        config = json.loads(open(Epilader.JSON_CONF).read())
        self.login    = config["login"]
        self.password = config["password"]
        self.notes = Notes(config["projets"], config["modules"])

    def __del__(self):
        self.curl.close()

    def set_cookies(self):
        self.curl.setopt(self.curl.POST, 1)
        self.curl.setopt(self.curl.URL, Epilader.INTRA_URL)
        self.curl.setopt(self.curl.POSTFIELDS, 'login='******'&password='******'')

    def find_gpa(self, request_result):
        request_result = json.loads(request_result)
        try:
            gpa = float([x for x in request_result["gpa"] if (x["cycle"] == "bachelor")][0]['gpa'])
        except:
            self.log.error(Log.NO_GPA)
            return -1
        return gpa

    def find_moyenne(self, request_result):
        self.notes.init()
        request_result = json.loads(request_result)
        for note in request_result["notes"]:
            self.notes.add_note(note)
        return self.notes.moyenne()

    def request(self, href):
        self.curl.setopt(self.curl.URL, href)
        reponse = io.BytesIO()
        self.curl.setopt(self.curl.WRITEFUNCTION, reponse.write)
        try:
            self.curl.perform()
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            self.log.error(Log.REQUEST_FAIL)
            print ; return ""
        return reponse.getvalue().decode("utf-8")

    def launch(self):
        try:
            while True:
                user = input()
                if user == "" or user == "EOF":
                    return
                href_gpa = Epilader.INTRA_URL + "user/" + user + "/?format=json"
                href_note = Epilader.INTRA_URL + "user/" + user + "/notes/?format=json"
                if user[0] != '#':
                    gpa = self.find_gpa(self.request(href_gpa))
                    moyenne = self.find_moyenne(self.request(href_note))
                    self.log.write(user + "\t: " + str(gpa) + "\t: " + str(moyenne))
                    if gpa > 0:
                      self.datas.append([user, gpa, moyenne])
        except (KeyboardInterrupt, EOFError):
            print("KeyboardInterrupt") ; return

    def sort(self):
        self.datas.sort(key=lambda x: x[1], reverse=True)

    def display(self):
        rank = 1
        for d in self.datas:
            self.option.write(str(rank) + " " + d[0] + "\t" + str(d[1]) + "\t" + str(d[2]) + "\n")
            rank += 1