Ejemplo n.º 1
0
def init():
    global window, context, images, workspace, visual
    SDL_Init(SDL_INIT_VIDEO)
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
    window = SDL_CreateWindow(b"textended-edit",
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE)
    context = SDL_GL_CreateContext(window)
    images = sdlut.ImageResources()
    SDL_StartTextInput()

    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    options = dict(
        background=(0x27/255.0, 0x28/255.0, 0x22/255.0, 1),
        font=font.load("assets/OpenSans.fnt"),
        font_size=12,
        page_width=320,
        color=(1, 1, 1, 1),
        white=(1, 1, 1, 1),
        color_string=(1, 1, 0.5, 1.0),
        color_notation=(1.0, 1.0, 1.0, 0.2),
        color_notation_error=(1.0, 0.5, 0.5, 0.2),
        color_empty=(1.0, 1.0, 1.0, 0.5),
        color_external=(1.0, 1.0, 1.0, 0.1),
        )
    workspace = Workspace()
    document = workspace.get(sys.argv[1])
    visual = Visual(images, document, options)
Ejemplo n.º 2
0
    def on_initialize(self, params):
        self.root_uri = params['rootUri']
        self.workspace = Workspace(self.root_uri, self.f18_path, self.f18_args)
        return {
            'capabilities': {
                'textDocumentSync': {
                    'openClose': True,
                    'change': 1,
                    'save': {
                        'includeText': True
                    },
                },
                'definitionProvider': True,
                'documentSymbolProvider': True,
                # 'completionProvider': {
                #    'resolveProvider': False,
                #    'triggerCharacters': ['%']
                # },

                # 'referencesProvider': True,
                # 'hoverProvider': True,
                # 'implementationProvider': True,
                # 'renameProvider': True,
                # 'workspaceSymbolProvider': True,
            }
        }
def test_add_project_to_workspace_oneProject():
    project = Project("New project",
                      JSON={
                          'name': "New project in JSON",
                          'created': "10/31/2019",
                          'edited': "10/31/2019",
                          'description':
                          "filler description for testing purposes",
                          'protocol': "UDP",
                          'change_protocol': "TCP",
                          'src_port': "1234",
                          'dst_port': "8080",
                          'author': "author1",
                          'path': "",
                          'dissector': ""
                      })

    workspace = Workspace("New Workspace",
                          JSON={
                              'name': "New Workspace",
                              'projects': {},
                              'created': "10/31/2019",
                              'edited': "10/31/2019",
                              'path': 'path'
                          })

    workspace.add_project_to_workspace(project)
    test_json = workspace.get_json()

    assert test_json['projects'][0] == project
    assert workspace.projects[0] == project
Ejemplo n.º 4
0
    def run(self):
        config = self._decode_config()
        self._print_debug('[cppcheck] config: {}'.format(config))

        workspace = Workspace(config.get('include_paths'))
        workspace_files = workspace.calculate()

        if not len(workspace_files) > 0:
            return

        self._print_debug('[cppcheck] analyzing {} files'.format(
            len(workspace_files)))

        file_list_path = self._build_file_list(workspace_files)
        plugin_config = config.get('config', {})
        command = Command(plugin_config, file_list_path).build()

        self._print_debug('[cppcheck] command: {}'.format(command))

        results = self._run_command(command)
        issues = self._parse_results(results)

        for issue in issues:
            # cppcheck will emit issues for files outside of the workspace,
            # like header files. This ensures that we only emit issues for
            # files in the workspace.
            if issue and workspace.should_include(issue["location"]["path"]):
                print('{}\0'.format(json.dumps(issue)))
Ejemplo n.º 5
0
def update_NET_DESKTOP_GEOMETRY(force=False):
    global properties, xinerama

    old_geom = properties["_NET_DESKTOP_GEOMETRY"]
    old_xinerama = xinerama

    time.sleep(1)

    properties["_NET_DESKTOP_GEOMETRY"] = ptxcb.XROOT.get_desktop_geometry()
    xinerama = ptxcb.connection.xinerama_get_screens()

    if old_xinerama != xinerama or force:
        if not force and len(old_xinerama) == len(xinerama):
            for mon in Workspace.iter_all_monitors():
                mid = mon.id
                mon.refresh_bounds(
                    xinerama[mid]["x"], xinerama[mid]["y"], xinerama[mid]["width"], xinerama[mid]["height"]
                )
                mon.calculate_workarea()
        else:
            for mon in Workspace.iter_all_monitors():
                for tiler in mon.tilers:
                    tiler.destroy()

            for wid in Window.WINDOWS.keys():
                Window.remove(wid)

            for wsid in Workspace.WORKSPACES.keys():
                Monitor.remove(wsid)
                Workspace.remove(wsid)

            reset_properties()
            load_properties()
Ejemplo n.º 6
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.createActions()
        self.createMenuBar()
        self.createToolBar()
        self.setCentralWidget(self.createCentralWidget())
        self.setWindowIcon(QIcon('images/logo.png'))
        self.loadSettings()

    def createActions(self):
        self.fileAction = QAction(QIcon('images/map.png'), u'文件', self)
        self.helpAction = QAction(QIcon('images/add.png'), u'帮助', self)

    def createMenuBar(self):
        fileMenu = self.menuBar().addMenu(u'文件')
        fileMenu.addAction(self.fileAction)
        fileMenu.addSeparator()
        fileMenu.addAction(self.helpAction)
        helpMenu = self.menuBar().addMenu(u'帮助')
        helpMenu.addAction(self.helpAction)
        helpMenu.triggered.connect(self.actionTest)

    def createToolBar(self):
        toolBar = self.addToolBar(u'文件')
        toolBar.setIconSize(QSize(16, 16))
        toolBar.setMovable(False)
        toolBar.addAction(self.fileAction)
        toolBar.addSeparator()
        toolBar.addAction(self.helpAction)

    def createCentralWidget(self):
        self.centralWidget = Workspace()
        return self.centralWidget

    def actionTest(self):
        print('test')

    def loadSettings(self):
        settings = QSettings()
        geometry = settings.value('MainWindow/geometry')

        #如果设置文件存在,那么geometry的值一定存在,否则说明是第一次启动,跳过之后的设置读取过程
        if not geometry:
            return
        self.restoreGeometry(geometry)

    def saveSettings(self):
        settings = QSettings()
        settings.beginGroup('MainWindow')
        settings.setValue('geometry', self.saveGeometry())
        settings.endGroup()

    def closeEvent(self, e):
        self.saveSettings()
        self.centralWidget.saveSettings()
Ejemplo n.º 7
0
    def __init__(self,
                 initial=None,
                 workspace='',
                 policy='random',
                 context=None,
                 **options):
        # Signals / Callbacks handlers will be invoked potentially at different
        # worker processes. State provides a local context to save data.

        #Executor signals
        self.will_start_run = Signal()
        self.will_finish_run = Signal()
        self.will_fork_state = Signal()
        self.will_store_state = Signal()
        self.will_load_state = Signal()
        self.will_terminate_state = Signal()
        self.will_generate_testcase = Signal()

        #Be sure every state will forward us their signals
        self.will_load_state += self._register_state_callbacks

        #The main executor lock. Acquire this for accessing shared objects
        self._lock = manager.Condition(manager.RLock())

        #Shutdown Event
        self._shutdown = manager.Event()

        #States on storage. Shared dict state name ->  state stats
        self._states = manager.list()

        #Number of currently running workers. Initially no runnign workers
        self._running = manager.Value('i', 0)

        self._workspace = Workspace(self._lock, workspace)

        #Executor wide shared context
        if context is None:
            context = {}
        self._shared_context = manager.dict(context)

        #scheduling priority policy (wip)
        self.policy = Random()

        if self.load_workspace():
            if initial is not None:
                logger.error("Ignoring initial state")
            # We loaded state ids, now load the actual state

            current_state_id = self.get()
            initial = self._workspace.load_state(current_state_id)
            self._register_state_callbacks(initial, current_state_id)

        self.add(initial)
        ##FIXME PUBSUB  We need to forward signals here so they get declared
        ##forward signals from initial state so they are declared here
        self._register_state_callbacks(initial, 0)  # id param unused
Ejemplo n.º 8
0
class Compose:
    def __init__(self, workspace, strict=True):
        '''
        Object to manage working with Docker-Compose on the CLI. exposes
        a natural language for performing common tasks with docker in
        juju charms.

        @param workspace - Define the CWD for docker-compose execution

        @param strict - Enable/disable workspace validation
        '''
        self.workspace = Workspace(workspace)
        if strict:
            self.workspace.validate()

    def up(self, service=None):
        '''
        Convenience method that wraps `docker-compose up`

        usage: c.up('nginx')  to start the 'nginx' service from the
        defined `docker-compose.yml` as a daemon
        '''
        if service:
            cmd = "docker-compose up -d {}".format(service)
        else:
            cmd = "docker-compose up -d"
        self.run(cmd)

    def kill(self, service=None):
        '''
        Convenience method that wraps `docker-compose kill`

        usage: c.kill('nginx')  to kill the 'nginx' service from the
        defined `docker-compose.yml`
        '''
        if service:
            cmd = "docker-compose kill {}".format(service)
        else:
            cmd = "docker-compose kill"
        self.run(cmd)

    def run(self, cmd):
        '''
        chdir sets working context on the workspace

        @param: cmd - String of the command to run. eg: echo "hello world"
        the string is passed through shlex.parse() for convenience.

        returns STDOUT of command execution

        usage: c.run('docker-compose ps')
        '''
        with chdir("{}".format(self.workspace)):
            out = check_output(split(cmd))
            return out
Ejemplo n.º 9
0
class Compose:
    def __init__(self, workspace, strict=True):
        '''
        Object to manage working with Docker-Compose on the CLI. exposes
        a natural language for performing common tasks with docker in
        juju charms.

        @param workspace - Define the CWD for docker-compose execution

        @param strict - Enable/disable workspace validation
        '''
        self.workspace = Workspace(workspace)
        if strict:
            self.workspace.validate()

    def up(self, service=None):
        '''
        Convenience method that wraps `docker-compose up`

        usage: c.up('nginx')  to start the 'nginx' service from the
        defined `docker-compose.yml` as a daemon
        '''
        if service:
            cmd = "docker-compose up -d {}".format(service)
        else:
            cmd = "docker-compose up -d"
        self.run(cmd)

    def kill(self, service=None):
        '''
        Convenience method that wraps `docker-compose kill`

        usage: c.kill('nginx')  to kill the 'nginx' service from the
        defined `docker-compose.yml`
        '''
        if service:
            cmd = "docker-compose kill {}".format(service)
        else:
            cmd = "docker-compose kill"
        self.run(cmd)

    def run(self, cmd):
        '''
        chdir sets working context on the workspace

        @param: cmd - String of the command to run. eg: echo "hello world"
        the string is passed through shlex.parse() for convenience.

        returns STDOUT of command execution

        usage: c.run('docker-compose ps')
        '''
        with chdir("{}".format(self.workspace)):
            out = check_output(split(cmd))
            return out
def test_add_project_to_workspace_float():
    workspace = Workspace("New Workspace",
                          JSON={
                              'name': "New Workspace",
                              'projects': {},
                              'created': "10/31/2019",
                              'edited': "10/31/2019",
                              'path': 'path'
                          })

    assert workspace.add_project_to_workspace(1.0) == None
Ejemplo n.º 11
0
 def load_workspace(self, location) -> bool:
     try:
         self.workspace = Workspace(self, location, self.token, style=self.style, orient=tk.HORIZONTAL)
         self.workspace.grid(row=0, column=0, sticky=tk.NSEW)
         return True
     except FileNotFoundError:
         print("Directory: {0} does not exist".format(location))
     except NotADirectoryError:
         print("{0} is not a directory".format(location))
     except PermissionError:
         print("You do not have permissions to change to {0}".format(location))
def test_add_project_to_workspace_string():
    workspace = Workspace("New Workspace",
                          JSON={
                              'name': "New Workspace",
                              'projects': {},
                              'created': "10/31/2019",
                              'edited': "10/31/2019",
                              'path': 'path'
                          })

    assert workspace.add_project_to_workspace("random string") == None
Ejemplo n.º 13
0
def demo():
    root = tkinter.Tk()
    root.title("Motion Planning")
    universal_height = 1000

    nb = ttk.Notebook(root)
    page1 = ttk.Frame(nb, width= 1080,height = universal_height)
    page2 = ttk.Frame(nb,width = 1080,height = universal_height)

    nb.add(page1, text='Workspace')
    nb.add(page2, text='Configspace')
    nb.grid(column=0)
 
    workspace = Workspace("./resources/robot_BW_small.bmp", "./resources/Room_BW_small.bmp", page1)
    configspace = Configspace(page2)
    controller = Controller(workspace,configspace)


    workspace.drawAll(workspace.currentPos[0],workspace.currentPos[1])
    def callback(event):
        # print ("clicked at", event.x, event.y)
        controller.drawMouseOffSet(event.x, event.y)
        if controller.isInCollision(): setBackgroundColor(page1,"red")
        else: setBackgroundColor(page1,"green")

    workspace.label.bind("<Button-1>", callback)

    def moveRobotOnPath(val):
        if controller.isAllInitialized():
            controller.setSolutionPathOnCurrentPos(int(val))
            controller.drawCurrentPos()
            if controller.isInCollision(): setBackgroundColor(page1,"red")
            else: setBackgroundColor(page1,"green")

    slider = Scale(page1, from_=0, to=200, orient=HORIZONTAL, command=moveRobotOnPath)
    slider.config(length=600)
    
    def set_goal():
        controller.setCurrentPosAsGoal()
        slider['from_'] = 0
        slider['to_'] = len(configspace.solutionPath)-1

    setGoalButton = ttk.Button(page1, text = 'Set Goal',command = set_goal)
    setGoalButton.pack(side=tkinter.RIGHT)

    def set_init():
        controller.setCurrentPosAsInit()
    setInitButton = ttk.Button(page1, text = 'Set Init',command = set_init)
    setInitButton.pack(side=tkinter.RIGHT)

    slider.pack()

    root.mainloop()
Ejemplo n.º 14
0
    def __init__(self, workspace, strict=True):
        '''
        Object to manage working with Docker-Compose on the CLI. exposes
        a natural language for performing common tasks with docker in
        juju charms.

        @param workspace - Define the CWD for docker-compose execution

        @param strict - Enable/disable workspace validation
        '''
        self.workspace = Workspace(workspace)
        if strict:
            self.workspace.validate()
Ejemplo n.º 15
0
 def workspace_report(self, args):
     """
     Reports the relevant information for the iRODS workspace.  Export and event history can be limited by
     start and end dates.  The end date is extended 1 day since the end date alone is not inclusive.
     :param args: optional start and end dates
     """
     start_date = args.start_date
     end_date = args.end_date + datetime.timedelta(days=1)
     show_dataset_owners = args.show_dataset_owners
     workspace = Workspace(dashboard=self,
                           start_date=start_date,
                           end_date=end_date)
     workspace.display(show_dataset_owners)
Ejemplo n.º 16
0
def publish_collections(collection_set_specs, allow_collection_removal):
    """ Main method that publishes all collections for all
    defined targets """
    try:
        oai_node_obj = oai_node.OAIFetchNode()
        workspace = Workspace(oai_node_obj, allow_collection_removal)
        # sets to publish if nothing is sent in will return a set of collections so that if called
        # every day, by the end of the month no matter what all collections will be ran
        collections = oai_node_obj.get_sets_to_publish(collection_set_specs)
        for targetPath, taragetName in settings.TARGETS:
            try:
                module = importlib.import_module(targetPath)
                target = getattr(module, taragetName)()
            except ImportError as e:
                raise ImportError(
                    "Could not import target '%s' (Is it on sys.path? Is there an import error in the settings file?): %s"
                    % (targetPath, e)
                )

            log.info('Running publish process for target %s' % target)

            #The publish summary is a summary for all collections
            publish_summary = PublishSummary(target.title, target.target_settings['PUBLISH_URL'])
            for collection in collections:
                collection_name = collection[0]
                collection_id = collection[1]
                collection_library_format = collection[2]
                if collection_id:
                    log.info('Starting publishing process for set %s' % collection_name)
                else:
                    log.info('Starting publishing process for all sets.')
                
                # reset couch before we start updating the collection
                workspace.reset_collection()
                workspace.set_collection(target.title, collection_id, collection_name, 
                                         collection_library_format)
               
                try:
                    target.update_collection(workspace)
                except Exception, e:
                    # exceptions should be handled inside the update_collection method, this
                    # really should never occur unless one codes the target wrong
                    publish_exception = PublishException("Un-caught exception during publish.", e)
                    log.error(publish_exception)
                    workspace.collection_summary.add_error(publish_exception)
                finally:
                    # finally email the summary out
                    workspace.collection_summary.email_summary()
                    publish_summary.add_collection_summary(workspace.collection_summary)
                # After the full publish sleep for a bit to let the node indexer catch up
                time.sleep(10)
Ejemplo n.º 17
0
    def initialise_workspaces(self):
        for workspace_config in config.get_config('workspace_config'):
            (name, geometry) = workspace_config
            if geometry is not None:
                new_workspace = Workspace(name=name,
                                          geometry=geometry,
                                          state=SCREEN_STATE.ACTIVE)
                self.viewable_screen_count += 1
            else:
                new_workspace = Workspace(name=name)

            self.add_child(new_workspace)

        self.update_active_workspaces_statuses()
Ejemplo n.º 18
0
class rccd:
    def __init__(self):
        self.ws = Workspace()

    def find_component_path(self, searched_component):
        path = self.ws.find_only_component(searched_component)
        if (path):
            print(path)
        else:
            pass

    def list_comp(self):
        components = self.ws.list_components_names()
        for component in components:
            print(component)
Ejemplo n.º 19
0
    def __init__(self,
                 initial=None,
                 workspace=None,
                 policy='random',
                 context=None,
                 **kwargs):
        super(Executor, self).__init__(**kwargs)

        # Signals / Callbacks handlers will be invoked potentially at different
        # worker processes. State provides a local context to save data.

        self.subscribe('did_load_state', self._register_state_callbacks)

        # The main executor lock. Acquire this for accessing shared objects
        self._lock = manager.Condition(manager.RLock())

        # Shutdown Event
        self._shutdown = manager.Event()

        # States on storage. Shared dict state name ->  state stats
        self._states = manager.list()

        # Number of currently running workers. Initially no running workers
        self._running = manager.Value('i', 0)

        self._workspace = Workspace(self._lock, workspace)

        # Executor wide shared context
        if context is None:
            context = {}
        self._shared_context = manager.dict(context)

        #scheduling priority policy (wip)
        #Set policy
        policies = {
            'random': Random,
            'uncovered': Uncovered,
            'branchlimited': BranchLimited,
        }
        self._policy = policies[policy](self)
        assert isinstance(self._policy, Policy)

        if self.load_workspace():
            if initial is not None:
                logger.error("Ignoring initial state")
        else:
            if initial is not None:
                self.add(initial)
Ejemplo n.º 20
0
    def add_workspace(self, name=None):
        if name is None:
            name = self.get_new_index()

        new_workspace = Workspace(name=name)
        self.add_child(new_workspace)
        return new_workspace
Ejemplo n.º 21
0
def create_nc_coverage_merage_resource():
    '''
        # NOTE: 尝试将创建 nc coverage 使用 -> resource.py -> Coverage 的方式实现
        # TODO:[-] 20-03-23
    '''
    coverage_title = 'ceshi_coverage_01'
    # TODO:[*] 20-03-24 注意此处会引发严重bug,在指定 工作区 下若不存在指定的 store 会出现 错误
    store_name = 'nmefc_2016072112_opdr'
    coverage_store = 'nmefc_wind'
    layer_name = 'ceshi_coverage_01'
    work_space = 'my_test_2'
    cat: Catalog = Catalog("http://localhost:8082/geoserver/rest",
                           username="******",
                           password="******")
    ws = Workspace(cat, work_space)
    store = CoverageStore(cat, ws, 'nmefc_wind_dir_xy')

    # layer = CoverageLayer(cat, 'ceshi_name', 'ceshi_native_name', 'ceshi_tile', 'ceshi_native_coveragename')
    # coverage = Coverage(cat, ws, store, 'view_nmefc_wind')

    # TODO:[-] 20-03-24 使用 -> customer_layer -> CoverageLayer
    # coverage = CoverageLayer(cat, WORK_SPACE)
    # coverage.create_layer(coverage_title, store_name, [dict(name='x_wind_10m'), dict(name='y_wind_10m')])
    bands = [dict(name='x_wind_10m'), dict(name='y_wind_10m')]
    coverage_layer = CoverageLayer(cat, work_space, store_name)
    # TODO:[*] 20-03-24 此处若使用 layer_name:ceshi_coverage_01 而不使用 coverage_store:nmefc_wind 则会引发 msg 的bug
    coverage_layer.publish(layer_name, bands)
    pass
Ejemplo n.º 22
0
def update_NET_WORKAREA():
    global properties

    properties["_NET_WORKAREA"] = ptxcb.XROOT.get_workarea()

    for mon in Workspace.iter_all_monitors():
        mon.calculate_workarea()
Ejemplo n.º 23
0
 def init_workspace_and_projects(self):
     """Initializes Workspace and ProjectsManager."""
     assert self._projects is None
     assert self._workspace is None
     self._workspace = Workspace(factory=self)
     self._projects = ProjectsManager(factory=self)
     self._projects.init_workspace()
def test_create_workspace_without_params():
    workspace = Workspace()
    assert workspace.name == None
    assert workspace.JSON['name'] == None
    assert workspace.JSON['projects'] == {}
    assert workspace.JSON['created'] == None
    assert workspace.JSON['edited'] == None
    assert workspace.JSON['path'] == None
Ejemplo n.º 25
0
def update_NET_NUMBER_OF_DESKTOPS():
    global properties, xinerama

    old = properties["_NET_NUMBER_OF_DESKTOPS"]
    properties["_NET_NUMBER_OF_DESKTOPS"] = ptxcb.XROOT.get_number_of_desktops()

    # Add destops...
    if old < properties["_NET_NUMBER_OF_DESKTOPS"]:
        for wsid in xrange(old, properties["_NET_NUMBER_OF_DESKTOPS"]):
            Workspace.add(wsid)
            Monitor.add(wsid, xinerama)

    # Remove desktops
    elif old > properties["_NET_NUMBER_OF_DESKTOPS"]:
        for wsid in xrange(properties["_NET_NUMBER_OF_DESKTOPS"], old):
            Monitor.remove(wsid)
            Workspace.remove(wsid)
def test_get_json():
    workspace = Workspace(None,
                          JSON={
                              'name': "New Workspace in JSON",
                              'projects': {},
                              'created': "10/31/2019",
                              'edited': "10/31/2019",
                              'path': 'path'
                          })
    assert workspace.name == "New Workspace in JSON"

    test_json = workspace.get_json()
    assert test_json['name'] == "New Workspace in JSON"
    assert test_json['projects'] == {}
    assert test_json['created'] == "10/31/2019"
    assert test_json['edited'] == "10/31/2019"
    assert test_json['path'] == 'path'
def test_create_workspace_firstparam():
    workspace = Workspace("New Workspace")
    assert workspace.name == "New Workspace"
    assert workspace.JSON['name'] == None
    assert workspace.JSON['projects'] == {}
    assert workspace.JSON['created'] == None
    assert workspace.JSON['edited'] == None
    assert workspace.JSON['path'] == None
Ejemplo n.º 28
0
async def set_workspace(ws, workspace_name):
    global workspace
    workspace = Workspace(workspace_name)
    await ws.send(
        json.dumps({
            'type': 'message',
            'message': 'Switched to workspace %s.' % workspace.name
        }))
Ejemplo n.º 29
0
    def __init__(self):
        self.viewable_screen_count = 0
        self.last_active_window_id = None
        self.workspaces = []

        for workspace_config in config.WORKSPACE_CONFIG:
            (name, geometry) = workspace_config
            if geometry is not None:
                new_workspace = Workspace(self, name, geometry,
                                          SCREEN_STATE.ACTIVE)
                self.viewable_screen_count += 1
            else:
                new_workspace = Workspace(self, name)

            self.workspaces.append(new_workspace)

        self.update_active_workspaces_statuses()
Ejemplo n.º 30
0
    def start(self):
        # Script statup steps
        logger.info('PolyEngine v1.0')
        config = Config('config.ini')

        project_name = config.check_setting('PolyEngine', 'Name')
        logger.info('Starting project {}', project_name)

        message = config.check_setting('PolyEngine', 'Message')
        logger.info(message)

        # Source directory of project based on config file
        source_directory = config.check_setting('Compile', 'SourceDirectory')

        # Create the temporary code modification workspace
        workspace = Workspace(source_directory)
        workspace.create_workspace()

        # Process the files
        for f in workspace.source_files:
            if f is not None:
                processor = Processing(f)
                processor.process()

        for f in workspace.header_files:
            if f is not None:
                processor = Processing(f)
                processor.process()

        # Initialize the compiler once information has been loaded
        output_file = config.check_setting('Compile', 'Output')
        commands = config.check_setting('Compile', 'Commands')
        compiler_option = config.check_setting('Compile', 'Compiler')

        if compiler_option == 'gcc' or compiler_option == 'g++':
            compiler = Compile(compiler_option, workspace.source_files,
                               commands, output_file)
            compiler.compile()
        else:
            logger.error('Invalid compiler option selected.')
            exit('Invalid compiler.')

        # Cleanup workspace and exit
        print()
        Cleanup.clean_exit(workspace.work_path)
Ejemplo n.º 31
0
class rccd:
    def __init__(self):
        self.ws = Workspace()

    def save_filtered_component(self, searched_component):
        options = self.ws.find_components(searched_component)
        if options is not None:
            if len(options) == 1:
                save_output(f"{options[0]}")
            elif len(options) > 1:
                selected = self.ws.ask_for_path_selection(options)
                if selected is None:
                    save_output("")
                else:
                    save_output(selected)
            else:
                save_output("")
        else:
            save_output("")
Ejemplo n.º 32
0
    def __init__(self, run):
        super(Window, self).__init__(1024, 600, caption="Copycat", vsync=False)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        self.clock = pyglet.clock.ClockDisplay()
        self.show_fps = False

        self.done = False
        self.time = 0
        self.speed = 15
        self.playing = False

        self.run = run

        background = pyglet.resource.image("blackboard.png")
        self.background = pyglet.sprite.Sprite(background)
        self.saved_temp = 0
        self.batch = pyglet.graphics.Batch()

        self.play = pyglet.resource.image("play.png")
        self.pause = pyglet.resource.image("pause.png")
        self.play.anchor_x = self.play.width / 2.0
        self.play.anchor_y = self.play.height / 2.0
        self.pause.anchor_x = self.pause.width / 2.0
        self.pause.anchor_y = self.pause.height / 2.0
        self.button = Button(self.play, 30, 580,
                             self.on_play_button, self.batch)

        self.timer = pyglet.text.Label("0", "EraserDust", 18, x=512, y=574,
                                       color=(255,255,255, 125), batch=self.batch,
                                       halign="center", anchor_x="center")

        self.rule = pyglet.text.Label("", "EraserDust", 16, x=512, y=445,
                                      color=(255,255,255, 190), batch=self.batch,
                                      halign="center", anchor_x="center")

        self.slipnet = Slipnet(self.run.slipnet, 0, 0, 512, 300, self.batch)
        self.coderack = Coderack(self.run.coderack, 512, 0, 512, 300, self.batch)
        self.workspace = Workspace(self.run.workspace, 0, 300, 1024, 300, self.batch)

        pyglet.clock.schedule(self.update)
Ejemplo n.º 33
0
 def __init__(self, X_origin, Y_origin, Z_origin, X_limit, Y_limit,
              L1, L2, L3):
     self.x_o = float(X_origin)
     self.y_o = float(Y_origin)
     self.z_o = float(Z_origin)
     self.MAX_X = float(X_limit)
     self.MAX_Y = float(Y_limit)
     self.L1 = float(L1)
     self.L2 = float(L2)
     self.L3 = float(L3)
     self.workspace = Workspace(X_origin, Y_origin, Z_origin, L1, L2, L3)
Ejemplo n.º 34
0
def main():
    parser = argparse.ArgumentParser(
        description="provides various info about components/workspaces")
    parser.add_argument('argument', nargs='?', choices=['list', 'listws'])

    argcomplete.autocomplete(parser)
    args = parser.parse_args()
    ws = Workspace()

    if args.argument == 'list':
        try:
            ws.list_workspaces()
        except KeyboardInterrupt:
            print("\nCanceled")

    elif args.argument == 'listws':

        print("Registered workspaces are :")
        for workspace in ws.workspace_paths:
            print(f"\t{workspace}")
    else:
        parser.error("sorry no such option is available ")
Ejemplo n.º 35
0
def command_request(command):

    # Verify if the command is comming from slack
    if(request.form["token"] != verification_token):
        return "", 401 

    commandWorkspace = Workspace.get(Workspace.team_id == request.form['team_id'])

    if(commandWorkspace == None):
        return "Workspace not found", 404
        
    andrew.emitEvent(CommandEvent(CommandEvent.COMMANDSEND,request.form, commandWorkspace))
    return "", 200
Ejemplo n.º 36
0
    def __init__(self, workspace, strict=True):
        '''
        Object to manage working with Docker-Compose on the CLI. exposes
        a natural language for performing common tasks with docker in
        juju charms.

        @param workspace - Define the CWD for docker-compose execution

        @param strict - Enable/disable workspace validation
        '''
        self.workspace = Workspace(workspace)
        if strict:
            self.workspace.validate()
Ejemplo n.º 37
0
    def __init__(self, initial=None, workspace='', policy='random', context=None, **options):
        # Signals / Callbacks handlers will be invoked potentially at different
        # worker processes. State provides a local context to save data.

        #Executor signals
        self.will_start_run = Signal()
        self.will_finish_run = Signal()
        self.will_fork_state = Signal()
        self.will_store_state = Signal()
        self.will_load_state = Signal()
        self.will_terminate_state = Signal()
        self.will_generate_testcase = Signal()

        #Be sure every state will forward us their signals
        self.will_load_state += self._register_state_callbacks

        #The main executor lock. Acquire this for accessing shared objects
        self._lock = manager.Condition(manager.RLock())

        #Shutdown Event
        self._shutdown = manager.Event()

        #States on storage. Shared dict state name ->  state stats
        self._states = manager.list()

        #Number of currently running workers. Initially no runnign workers
        self._running = manager.Value('i', 0 )

        self._workspace = Workspace(self._lock, workspace)

        #Executor wide shared context
        if context is None:
            context = {}
        self._shared_context = manager.dict(context)
    
        #scheduling priority policy (wip)
        self.policy = Random()

        if self.load_workspace():
            if initial is not None:
                logger.error("Ignoring initial state")
            # We loaded state ids, now load the actual state

            current_state_id = self.get()
            initial = self._workspace.load_state(current_state_id)
            self._register_state_callbacks(initial, current_state_id)

        self.add(initial)
        ##FIXME PUBSUB  We need to forward signals here so they get declared
        ##forward signals from initial state so they are declared here
        self._register_state_callbacks(initial, 0) # id param unused
Ejemplo n.º 38
0
    def _move(self, direction, value):
        """ Moves object into direction by value. """

        for view in Workspace().get3DView():
            offset = Vector((0.0, 0.0, 0.0))
            if direction == "horizontal":
                offset.x = value
            elif direction == "vertical":
                offset.y = value
            elif direction == "straightforward":
                offset.z = value

            bpy.context.scene.objects.active.location \
             = view.view_rotation*offset + bpy.context.scene.objects.active.location
def test_create_workspace_allparams():
    workspace = Workspace("New Workspace",
                          JSON={
                              'name': "New Workspace",
                              'projects': {},
                              'created': "10/31/2019",
                              'edited': "10/31/2019",
                              'path': 'path'
                          })
    assert workspace.name == "New Workspace"
    assert workspace.JSON['projects'] == {}
    assert workspace.JSON['created'] == "10/31/2019"
    assert workspace.JSON['edited'] == "10/31/2019"
    assert workspace.JSON['path'] == 'path'
Ejemplo n.º 40
0
    def prompt_for_workspace(self):
        no_args = len(self._args) == 0
        if no_args:
            self.print_workspaces()
            return (None, [])
        index = self._parse_index(self._args[0])

        (subdir, i) = index
        if i is None:
            self.print_workspaces(subdir)
            return (None, [])

        ws = Workspace.all(subdir)
        if i < 0 or i >= len(ws):
            print "Index out of range: %d" % i
            self.print_workspaces()
            return (None, [])

        return (ws[i], self._args[1:])
Ejemplo n.º 41
0
    def createDockWindows(self):
        animate = animationWidget.QAnimationView(self)
        self.dockAnimate = QtGui.QDockWidget(self)
        self.dockAnimate.setWidget(animate)
        self.dockAnimate.setWindowTitle("Animation")
        #self.dockTemplate = DockTemplate(self)
        self.dockPlot = DockPlot(self)
        self.dockVariable = DockVariable(self)
        self.workspace = Workspace(self)
        self.varProp = VariableProperties(self)
        #self.workspace.addProject("Relative Humidity")
        #self.workspace.addProject("Total Cloudiness")
        #self.workspace.addProject("Temperature Anomaly")
        #self.workspace.addProject()
        self.dockCalculator = DockCalculator(self)
        self.plotProp = PlotProperties.instance(self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.workspace)
        #self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockTemplate)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockAnimate)
        #self.tabifyDockWidget(self.workspace, self.dockTemplate)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockPlot)
        #self.tabifyDockWidget(self.dockTemplate, self.dockPlot)
        self.workspace.raise_()
        self.varProp.hide()
        self.plotProp.hide()
        self.dockAnimate.hide()

        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockVariable)
        #self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.varProp)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockCalculator)
        self.tabifyDockWidget(self.dockCalculator, self.plotProp) 
        try:
            # For now only puts the diagnostics widget if the metrics module is present
            import metrics
            from diagnosticsDockWidget import DiagnosticsDockWidget
            self.diagnosticsWidget = DiagnosticsDockWidget(self)
            self.diagnosticsWidget.hide()
            self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.diagnosticsWidget)
            self.tabifyDockWidget(self.plotProp, self.diagnosticsWidget)
        except:
            pass
Ejemplo n.º 42
0
class Robot_Kinematics:
    """
    Constructor for Robot_Kin Class.
        The Robot's coordinates refers to the location of the base plate's
        center of mass that is connected to link 1
        X_origin: Robot X coordinate in the world: float(inches)
        Y_origin: Robot Y coordinate in the world: float(inches)
        Z_origin: Robot Z coordinate in the world: float(inches)
        X_limit: The length of the field in the X direction: float(inches)
        Y_limt: The length of the field in the Y direction: float(inches)
        LX: The length of link X
        """
    def __init__(self, X_origin, Y_origin, Z_origin, X_limit, Y_limit,
                 L1, L2, L3):
        self.x_o = float(X_origin)
        self.y_o = float(Y_origin)
        self.z_o = float(Z_origin)
        self.MAX_X = float(X_limit)
        self.MAX_Y = float(Y_limit)
        self.L1 = float(L1)
        self.L2 = float(L2)
        self.L3 = float(L3)
        self.workspace = Workspace(X_origin, Y_origin, Z_origin, L1, L2, L3)
        

    """
    Converts the coordinates of a point in the world system to coordinates
    of a point in the robots system, where the robot's location is the origin.
    To keep things simple, the axis of the robots system are alined with the
    axis of the world's:
    X: World's X coord: float
    Y: World's Y coord: float
    Z: World's Z coord: float

    returns tuple of (xp, yp, zp) of robot coordinates
    """
    def convertWorldCoord(self, X, Y, Z):
        xr = self.x_o - X
        yr = self.y_o - Y
        zr = Z - self.z_o
        return (xr, yr, zr)

    """
    Given the coordinates of Point C(the endpoint of Link 3 connected to
    Link 4), returns the angles of theta1, theta2,and theta3 in a tuple.
    XC: X coord of Point C: float
    YC: Y coord of Point C: float
    ZC: Y coord of Point C: float

    return tuple(theta1, theta2, theta3) in radians
    """
    def findThetas(self, XC, YC, ZC):
        theta1 = math.atan2(YC, XC) # Theta1
        
        # Point A Coords (Point connected to Link 1 and 2)
        XA = self.L1*math.cos(theta1)
        YA = self.L1*math.sin(theta1)
        ZA = 0.0

        #Distance of Point A and Point C in XY Plane
        rc = math.sqrt(math.pow((XC-XA), 2) + math.pow((YC-YA),2))

        #Distance of Point A and Point C in XYZ Space
        dc = math.sqrt(math.pow((ZC-ZA), 2) + math.pow(rc, 2))

        gamma_arg = ((math.pow(dc,2) + math.pow(self.L2,2) - math.pow(self.L3,2))/(2*dc*self.L2))
        theta2 = math.atan2(rc, ZC) - math.acos(gamma_arg)

        beta_arg = ((math.pow(self.L2, 2)+math.pow(self.L3, 2) - math.pow(dc, 2))/(2*self.L2*self.L3))
        theta3 = math.pi - math.acos(beta_arg)

        return(theta1, theta2, theta3)

    """
    Returns a boolean to determine if point is reachable(within the workspace
    of the robot)
    X: X coord in the world: float (inches)
    Y: Y coord in the world: float (inches)
    Z: Z coord in the wolrd: float (inches)
    """
    def isReachable(self, X, Y, Z):
        return self.workspace.containsPoint(X, Y, Z)

    """
    Creates the Jacobian representation for kinematics using theta 1, 2, and 3
    """
    def makeJacobian(theta1, theta2, theta3):
        #Forward kinematics derivative for theta1
        Xd1 = self.L1*math.cos(theta1) + self.L2*math.sin(theta2)*math.cos(theta1) + self.L3*math.sin(theta2+theta3)*math.cos(theta1)
        Yd1 = (self.L1*math.sin(theta1)+self.L2*math.sin(theta2)*math.sin(theta1)+ self.L3*math.sin(theta2+theta3)*math.sin(theta1))*(-1)
        Zd1 = 0.0

        #Forward kinematics derivative for theta2
        Xd2 = self.L2*math.cos(theta2)*math.sin(theta1) + self.L3*math.cos(theta2+theta3)*math.sin(theta1)
        Yd2 = self.L2*math.cos(theta2)*math.cos(theta1) + self.L3*math.cos(theta2+theta3)*math.cos(theta1)
        Zd2 = self.L2*math.sin(theta2) + self.L3*math.sin(theta2+theta3)

        #Forward kinematics derivative for theta3
        Xd3 = self.L3*math.cos(theta2+theta3)*math.sin(theta1)
        Yd3 = self.L3*math.cos(theta2+theta3)*math.cos(theta1)
        Zd3 = self.L3*math.sin(theta2+theta3)

        return ((Xd1, Xd2, Xd3),(Yd1, Yd2, Yd3), (Zd1, Zd2, Zd3))


    """
    Finds the torque 2 and 3 to order to provide Fx, Fy, and Fz
    """
    def findTorques(Fx, Fy, theta1, theta2, theta3):
        Jacobian = makeJacobian(theta1, theta2, theta3)
        torque2 = Jacobian[0,1]*Fx + Jacobian[1,1]*Fy + Jacobian[2,1]*Fz
        torque3 = Jacobian[0,2]*Fx + Jacobian[1,2]*Fy + Jacobian[2,2]*Fz
        return(torque2, torque3)
Ejemplo n.º 43
0
class UVCDATMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None,customPath=None,styles=None):
        super(UVCDATMainWindow, self).__init__(parent)
        self.root=self
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setDocumentMode(True)
        #init user options
        self.initCustomize(customPath,styles)
        self.root = self
        #self.tool_bar = mainToolbarWidget.QMainToolBarContainer(self)
        self.canvas=[]
        
        self.canvas.append(vcs.init())
        self.colormapEditor =QColormapEditor(self) 
        # Create the command recorder widget
        self.recorder = commandsRecorderWidget.QCommandsRecorderWidget(self)
        #Adds a shortcut to the record function
        self.record = self.recorder.record
        self.preferences = preferencesWidget.QPreferencesDialog(self)
        self.preferences.hide()
        self.cdmsCacheWidget = CdmsCacheWidget(self)
#        self.regridding = regriddingWidget.QRegriddingDialog(self)
#        self.regridding.hide()
        ###########################################################
        # Init Menu Widget
        ###########################################################
        self.mainMenu = mainMenuWidget.QMenuWidget(self)
        self.createDockWindows()
        self.createActions()
        self.updateMenuActions()
        self.embedSpreadsheet()
        self.connectSignals()
        self.resize(1150,800)
        
    def initCustomize(self,customPath,styles):
        if customPath is None:
            customPath=os.path.join(os.environ["HOME"],".uvcdat","customizeUVCDAT.py")
            
        if os.path.exists(customPath):
            execfile(customPath,customizeUVCDAT.__dict__,customizeUVCDAT.__dict__)

        if styles is None:
            styles=customizeUVCDAT.appStyles
            
        icon = QtGui.QIcon(customizeUVCDAT.appIcon)
        self.setWindowIcon(icon)

        ## cdms2 setup section
        cdms2.axis.time_aliases+=customizeUVCDAT.timeAliases
        cdms2.axis.level_aliases+=customizeUVCDAT.levelAliases
        cdms2.axis.latitude_aliases+=customizeUVCDAT.latitudeAliases
        cdms2.axis.longitude_aliases+=customizeUVCDAT.longitudeAliases
        cdms2.setNetcdfShuffleFlag(customizeUVCDAT.ncShuffle)
        cdms2.setNetcdfDeflateFlag(customizeUVCDAT.ncDeflate)
        cdms2.setNetcdfDeflateLevelFlag(customizeUVCDAT.ncDeflateLevel)
        
        ## StylesSheet
        st=""
        if isinstance(styles,str):
            st = styles
        elif isinstance(styles,dict):
            for k in styles.keys():
                val = styles[k]
                if isinstance(val,QtGui.QColor):
                    val = str(val.name())
                st+="%s:%s; " % (k,val)
        if len(st)>0: self.setStyleSheet(st)

        ###########################################################
        ###########################################################
        ## Prettyness
        ###########################################################
        ###########################################################
        #self.setGeometry(0,0, 1100,800)
        self.setWindowTitle('The Ultrascale Visualization Climate Data Analysis Tools - (UV-CDAT)')
        ## self.resize(1100,800)
        #self.setMinimumWidth(1100)
        self.main_window_placement()
     
    def main_window_placement(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/4, (screen.height()-size.height())/5)

    def createDockWindows(self):
        animate = animationWidget.QAnimationView(self)
        self.dockAnimate = QtGui.QDockWidget(self)
        self.dockAnimate.setWidget(animate)
        self.dockAnimate.setWindowTitle("Animation")
        #self.dockTemplate = DockTemplate(self)
        self.dockPlot = DockPlot(self)
        self.dockVariable = DockVariable(self)
        self.workspace = Workspace(self)
        self.varProp = VariableProperties(self)
        #self.workspace.addProject("Relative Humidity")
        #self.workspace.addProject("Total Cloudiness")
        #self.workspace.addProject("Temperature Anomaly")
        #self.workspace.addProject()
        self.dockCalculator = DockCalculator(self)
        self.plotProp = PlotProperties.instance(self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.workspace)
        #self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockTemplate)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockAnimate)
        #self.tabifyDockWidget(self.workspace, self.dockTemplate)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockPlot)
        #self.tabifyDockWidget(self.dockTemplate, self.dockPlot)
        self.workspace.raise_()
        self.varProp.hide()
        self.plotProp.hide()
        self.dockAnimate.hide()

        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockVariable)
        #self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.varProp)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dockCalculator)
        self.tabifyDockWidget(self.dockCalculator, self.plotProp) 
        try:
            # For now only puts the diagnostics widget if the metrics module is present
            import metrics
            from diagnosticsDockWidget import DiagnosticsDockWidget
            self.diagnosticsWidget = DiagnosticsDockWidget(self)
            self.diagnosticsWidget.hide()
            self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.diagnosticsWidget)
            self.tabifyDockWidget(self.plotProp, self.diagnosticsWidget)
        except:
            pass


    def createActions(self):
        # Quit Action
        self.actionExit = QtGui.QAction("Quit", self,
                                        triggered=self.quit)
        #VisTrails Window
        self.showBuilderWindowAct = QtGui.QAction("Builder", self,
                                 triggered=self.showBuilderWindowActTriggered)
        self.showVistrailsConsoleAct = QtGui.QAction("Console", self,
                                triggered=self.showVistrailsConsoleActTriggered)
        #About Message
        self.showAboutMessageAct = QtGui.QAction("About UV-CDAT...", self,
                                triggered=self.showAboutMessageActTriggered)
        
    def updateMenuActions(self):
        #menu File Actions
        self.ui.menuFile.addAction(self.workspace.btnNewProject)
        self.ui.menuFile.addAction(self.workspace.btnOpenProject)
        self.ui.menuFile.addSeparator()
        self.ui.menuFile.addAction(self.workspace.btnCloseProject)
        self.ui.menuFile.addSeparator()
        self.ui.menuFile.addAction(self.workspace.btnSaveProject)
        self.ui.menuFile.addAction(self.workspace.btnSaveProjectAs)
        self.ui.menuFile.addSeparator()
        self.ui.menuFile.addAction(self.actionExit)
        #menu View Actions
        self.ui.menuView.addAction(self.workspace.toggleViewAction())
        #self.ui.menuView.addAction(self.dockTemplate.toggleViewAction())
        self.ui.menuView.addAction(self.dockPlot.toggleViewAction())
        self.ui.menuView.addAction(self.dockVariable.toggleViewAction())
        self.ui.menuView.addAction(self.dockCalculator.toggleViewAction())
        self.ui.menuView.addAction(self.plotProp.toggleViewAction())
        #VisTrails Menu
        self.ui.menuVisTrails.addAction(self.showBuilderWindowAct)
        self.ui.menuVisTrails.addAction(self.showVistrailsConsoleAct)
        #About message
        self.ui.menuHelp.addAction(self.showAboutMessageAct)
        
    def showBuilderWindowActTriggered(self):
        from gui.vistrails_window import _app
        _app.show()
        _app.raise_()
        _app.qactions['history'].trigger()
        _app.get_current_tab().zoomToFit()
        _app.qactions['pipeline'].trigger()
        _app.get_current_tab().zoomToFit()
        #self.get_current_project_controller().re_layout_workflow()
        
        
    def showVistrailsConsoleActTriggered(self):
        from gui.shell import QShellDialog
        QShellDialog.instance().set_visible(True)
        
    def showAboutMessageActTriggered(self):
        import core.uvcdat
        import vistrails.core.system
        class About(QtGui.QLabel):
            def mousePressEvent(self, e):
                self.emit(QtCore.SIGNAL("clicked()"))

        dlg = QtGui.QDialog(self, QtCore.Qt.FramelessWindowHint)
        layout = QtGui.QVBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(0)
        bgimage = About(dlg)
        #The application disclaimer image
        pixmap = QtGui.QPixmap(
            vistrails.core.system.vistrails_root_directory() +
            '/gui/uvcdat/resources/images/disclaimer.png')
        bgimage.setPixmap(pixmap)
        layout.addWidget(bgimage)
        dlg.setLayout(layout)
        text = "<font color=\"#105E99\"><b>%s</b></font>" % \
            core.uvcdat.short_about_string()
        version = About(text, dlg)
        version.setGeometry(11,50,450,30)
        self.connect(bgimage,
                     QtCore.SIGNAL('clicked()'),
                     dlg,
                     QtCore.SLOT('accept()'))
        self.connect(version,
                     QtCore.SIGNAL('clicked()'),
                     dlg,
                     QtCore.SLOT('accept()'))
        dlg.setSizeGripEnabled(False)
        dlg.exec_()
        
    def connectSignals(self):
        
        self.connect(self.spreadsheetWindow.tabControllerStack,
                     QtCore.SIGNAL("add_tab"),
                     self.workspace.add_sheet_tab)
        self.connect(self.spreadsheetWindow.tabControllerStack,
                     QtCore.SIGNAL("remove_tab"),
                     self.workspace.remove_sheet_tab)
        self.connect(self.spreadsheetWindow.tabControllerStack,
                     QtCore.SIGNAL("change_tab_text"),
                     self.workspace.change_tab_text)
        
    def closeEvent(self, e):
        """ closeEvent(e: QCloseEvent) -> None
        Only hide the builder window

        """
        if not self.quit():
            e.ignore()
        
    def quit(self):
        #FIXME
        #ask to save projects
        print "quitting"
        if self.preferences.confirmB4Exit.isChecked():
            # put here code to confirm exit
            pass
        if self.preferences.saveB4Exit.isChecked():
            self.preferences.saveState()
        from gui.vistrails_window import _app
        _app._is_quitting = True
        if _app.close_all_vistrails():

            # DAK: removing this call as it seems to cause a
            # RuntimeError with QVersionTreeScene.selectionChanged;
            # it also does not appear in the VisTrails code
            # _app.deleteLater()
            QtCore.QCoreApplication.quit()
            # In case the quit() failed (when Qt doesn't have the main
            # event loop), we have to return True still
            return True
        _app._is_quitting = False
        return False
        QtGui.QApplication.instance().quit()
        
    def showVariableProperties(self):
        varProp = VariableProperties.instance()
        varProp.show()
        
    def showPlotProperties(self):
        plotProp = PlotProperties.instance()
        plotProp.show()
        
    def embedSpreadsheet(self):
        self.spreadsheetWindow = spreadsheetController.findSpreadsheetWindow(show=False)
        self.setCentralWidget(self.spreadsheetWindow)
        self.spreadsheetWindow.setVisible(True)
        
    def cleanup(self):
        self.setCentralWidget(QtGui.QWidget())
        self.spreadsheetWindow.setParent(None)

    def stick_defvar_into_main_dict(self,var):
        __main__.__dict__[var.id]=var

    def stick_main_dict_into_defvar(self,results=None):
        #First evaluate if there's any var in the result
        res = None
        if results is not None:
            tmp = __main__.__dict__[results]
        else:
            tmp=None
        added = []
        remove =[]
        if isinstance(tmp,cdms2.tvariable.TransientVariable):
            __main__.__dict__[tmp.id]=tmp
            added.append(tmp.id)
            res = tmp.id
        elif tmp is not None:
            self.processList(tmp,added)
            
        if results is not None:
            del(__main__.__dict__[results])
        for k in __main__.__dict__:
            if isinstance(__main__.__dict__[k],cdms2.tvariable.TransientVariable):
                if __main__.__dict__[k].id in added and k!=__main__.__dict__[k].id:
                    remove.append( __main__.__dict__[k].id)
                    res = k
                if not k in remove:
                    __main__.__dict__[k].id=k
                    self.dockVariable.widget().addVariable(__main__.__dict__[k])
#                    # Send information to controller so the Variable can be reconstructed
#                    # later. The best way is by emitting a signal to be processed by the
#                    # main window. When this panel becomes a global panel, then we will do
#                    # that. For now I will talk to the main window directly.
#        
#                    from api import get_current_project_controller
#                    from vistrails.packages.uvcdat_cdms.init import CDMSVariable
#                    controller = get_current_project_controller()
#                    if controller.get_defined_variable(k) is None:
#                        cdmsVar = CDMSVariable(filename=None, name=k)
#                        controller.add_defined_variable(cdmsVar)
        for r in remove:
            del(__main__.__dict__[r])

        return res
    
    def processList(self,myList,added):
        for v in myList:
            if isinstance(v,cdms2.tvariable.TransientVariable):
                __main__.__dict__[v.id]=v
                added.append(v.id)
            elif isinstance(v,(list,tuple)):
                self.processList(v,added)
            elif isinstance(v,dict):
                self.processList(dict.values(),added)
        return

    def get_current_project_controller(self):
        return self.workspace.get_current_project_controller()
    
    def get_project_controller_by_name(self, name):
        return self.workspace.get_project_controller_by_name(name)
    
    def link_registry(self):
        self.dockPlot.link_registry()
        
    def warning(self, msg):
        print "WARNING: %s" % msg
        if not get_vistrails_configuration().noDebugPopups:
            QtGui.QMessageBox.warning(self, "Warning", msg)
Ejemplo n.º 44
0
def apply_config():
    Command.init()

    for mon in Workspace.iter_all_monitors():
        if config.get_option("tile_on_startup", mon.workspace.id, mon.id):
            mon.tile(force_tiling=True)
Ejemplo n.º 45
0
 def print_workspaces(self, subdir=None):
     ws = Workspace.all(subdir)
     for i in range(len(ws)):
         print "%d: %s" % (i, ws[i].summary_line())
Ejemplo n.º 46
0
class Window(pyglet.window.Window):
    """The main window keeps track of what scene is currently being viewed,
    manages the gui elements that are always on screen, and takes care of
    updating the simulation."""

    def __init__(self, run):
        super(Window, self).__init__(1024, 600, caption="Copycat", vsync=False)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        self.clock = pyglet.clock.ClockDisplay()
        self.show_fps = False

        self.done = False
        self.time = 0
        self.speed = 15
        self.playing = False

        self.run = run

        background = pyglet.resource.image("blackboard.png")
        self.background = pyglet.sprite.Sprite(background)
        self.saved_temp = 0
        self.batch = pyglet.graphics.Batch()

        self.play = pyglet.resource.image("play.png")
        self.pause = pyglet.resource.image("pause.png")
        self.play.anchor_x = self.play.width / 2.0
        self.play.anchor_y = self.play.height / 2.0
        self.pause.anchor_x = self.pause.width / 2.0
        self.pause.anchor_y = self.pause.height / 2.0
        self.button = Button(self.play, 30, 580,
                             self.on_play_button, self.batch)

        self.timer = pyglet.text.Label("0", "EraserDust", 18, x=512, y=574,
                                       color=(255,255,255, 125), batch=self.batch,
                                       halign="center", anchor_x="center")

        self.rule = pyglet.text.Label("", "EraserDust", 16, x=512, y=445,
                                      color=(255,255,255, 190), batch=self.batch,
                                      halign="center", anchor_x="center")

        self.slipnet = Slipnet(self.run.slipnet, 0, 0, 512, 300, self.batch)
        self.coderack = Coderack(self.run.coderack, 512, 0, 512, 300, self.batch)
        self.workspace = Workspace(self.run.workspace, 0, 300, 1024, 300, self.batch)

        pyglet.clock.schedule(self.update)

    def on_key_press(self, symbol, modifiers):
        if symbol == pyglet.window.key.ESCAPE:
            pyglet.app.exit()
        elif symbol == pyglet.window.key.F and modifiers == pyglet.window.key.MOD_CTRL:
            self.show_fps = not self.show_fps
        elif symbol == pyglet.window.key.SPACE:
            self.button.on_key_press(symbol, modifiers)
    
    def on_mouse_press(self, x, y, button, modifiers):
        self.button.on_mouse_press(x, y, button, modifiers)
        
    def on_mouse_release(self, x, y, button, modifiers):
        self.button.on_mouse_release(x, y, button, modifiers)

    def on_play_button(self):
        self.playing = not self.playing
        if self.playing:
            self.button.sprite.image = self.pause
        else:
            self.button.sprite.image = self.play

    def update(self, dt):
        self.button.update(dt) 

        if self.done or not self.playing:
            return

        # Update each graphical module.
        self.slipnet.update(dt)
        self.coderack.update(dt)
        self.workspace.update(dt)

        # Check for completion.
        if self.run.workspace.answer_string:
            self.rule.text = self.run.workspace.rule.to_string()
            self.done = True

        # Update the timestep display.
        time = str(self.run.coderack.time / self.run.timestep)
        if self.timer.text != time:
            self.timer.text = time

        # Update the temperature display.
        target_temp = self.run.workspace.temperature * 2.55
        if abs(self.saved_temp - target_temp) > .001:
            self.saved_temp += (target_temp - self.saved_temp) * dt
            self.background.color = (240,
                                     255 - self.saved_temp / 1.4,
                                     255 - self.saved_temp / 1.15)
        
        # Update the simulation at the given speed.
        self.time += dt
        if self.time >= 1.0 / self.speed:
            self.run.step()
            self.time = 0

    def on_draw(self):
        self.clear()
        self.background.draw()
        self.batch.draw()
        if self.show_fps:
            self.clock.draw()
Ejemplo n.º 47
0
 def print_subdirs(self):
     subdirs = Workspace.all_subdirs()
     for subdir in subdirs:
         print subdir
Ejemplo n.º 48
0
class Executor(object):
    '''
    The executor guides the execution of an initial state or a paused previous run. 
    It handles all exceptional conditions (system calls, memory faults, concretization, etc.)
    '''

    def __init__(self, initial=None, workspace='', policy='random', context=None, **options):
        # Signals / Callbacks handlers will be invoked potentially at different
        # worker processes. State provides a local context to save data.

        #Executor signals
        self.will_start_run = Signal()
        self.will_finish_run = Signal()
        self.will_fork_state = Signal()
        self.will_store_state = Signal()
        self.will_load_state = Signal()
        self.will_terminate_state = Signal()
        self.will_generate_testcase = Signal()

        #Be sure every state will forward us their signals
        self.will_load_state += self._register_state_callbacks

        #The main executor lock. Acquire this for accessing shared objects
        self._lock = manager.Condition(manager.RLock())

        #Shutdown Event
        self._shutdown = manager.Event()

        #States on storage. Shared dict state name ->  state stats
        self._states = manager.list()

        #Number of currently running workers. Initially no runnign workers
        self._running = manager.Value('i', 0 )

        self._workspace = Workspace(self._lock, workspace)

        #Executor wide shared context
        if context is None:
            context = {}
        self._shared_context = manager.dict(context)
    
        #scheduling priority policy (wip)
        self.policy = Random()

        if self.load_workspace():
            if initial is not None:
                logger.error("Ignoring initial state")
            # We loaded state ids, now load the actual state

            current_state_id = self.get()
            initial = self._workspace.load_state(current_state_id)
            self._register_state_callbacks(initial, current_state_id)

        self.add(initial)
        ##FIXME PUBSUB  We need to forward signals here so they get declared
        ##forward signals from initial state so they are declared here
        self._register_state_callbacks(initial, 0) # id param unused

    @contextmanager
    def locked_context(self):
        ''' Executor context is a shared memory object. All workers share this. 
            It needs a lock. Its used like this:

            with executor.context() as context:
                vsited = context['visited']
                visited.append(state.cpu.PC)
                context['visited'] = visited
        '''
        with self._lock:
            yield self._shared_context



    def _register_state_callbacks(self, state, state_id):
        '''
            Install forwarding callbacks in state so the events can go up. 
            Going up, we prepend state in the arguments.
        ''' 
        #Forward all state signals
        forward_signals(self, state, True)

    def add(self, state):
        '''
            Enqueue state.
            Save state on storage, assigns an id to it, then add it to the 
            priority queue
        '''
        #save the state to secondary storage
        state_id = self._workspace.save_state(state)
        self.will_store_state(state, state_id)
        self.put(state_id)
        return state_id

    def load_workspace(self):
        #Browse and load states in a workspace in case we are trying to 
        # continue from paused run
        loaded_state_ids = self._workspace.try_loading_workspace()
        if not loaded_state_ids:
            return False

        for id in loaded_state_ids:
            self._states.append(id)

        return True

    ###############################################
    # Synchronization helpers
    @sync
    def _start_run(self):
        #notify siblings we are about to start a run()
        self._running.value+=1

    @sync
    def _stop_run(self):
        #notify siblings we are about to stop this run()
        self._running.value-=1
        assert self._running.value >=0
        self._lock.notify_all()


    ################################################
    #Public API
    @property
    def running(self):
        ''' Report an estimate  of how many workers are currently running '''
        return self._running.value

    def shutdown(self):
        ''' This will stop all workers '''
        self._shutdown.set()

    def is_shutdown(self):
        ''' Returns True if shutdown was requested '''
        return self._shutdown.is_set()


    ###############################################
    # Priority queue 
    @sync
    def put(self, state_id):
        ''' Enqueue it for processing '''
        self._states.append(state_id)
        self._lock.notify_all()
        return state_id

    @sync
    def get(self):
        ''' Dequeue a state with the max priority '''

        #A shutdown has been requested
        if self.is_shutdown():
            return None

        #if not more states in the queue lets wait for some forks
        while len(self._states) == 0:
            #if no worker is running bail out
            if self.running == 0:
                return None
            #if a shutdown has been requested bail out
            if self.is_shutdown():
                return None
            #if there is actually some workers running wait for state forks
            logger.debug("Waiting for available states")
            self._lock.wait()
            
        state_id = random.choice(self._states)
        del  self._states[self._states.index(state_id)]
        return state_id

    ###############################################################
    # File Storage 

    def list(self):
        ''' Returns the list of states ids currently queued '''
        return list(self._states)

    def generate_testcase(self, state, message='Testcase generated'):
        '''
        Simply announce that we're going to generate a testcase. Actual generation
        should be handled by the driver class (such as :class:`~manticore.Manticore`)

        :param state: The state to generate information about
        :param message: Accompanying message
        '''

        #broadcast test generation. This is the time for other modules
        #to output whatever helps to understand this testcase
        self.will_generate_testcase(state, message)


    def fork(self, state, expression, policy='ALL', setstate=None):
        '''
        Fork state on expression concretizations.
        Using policy build a list of solutions for expression.
        For the state on each solution setting the new state with setstate 

        For example if expression is a Bool it may have 2 solutions. True or False.
    
                                 Parent  
                            (expression = ??)
       
                   Child1                         Child2
            (expression = True)             (expression = True)
               setstate(True)                   setstate(False)

        The optional setstate() function is supposed to set the concrete value 
        in the child state.
        
        '''
        assert isinstance(expression, Expression)

        if setstate is None:
            setstate = lambda x,y: None

        #Find a set of solutions for expression
        solutions = state.concretize(expression, policy)

        #We are about to fork current_state
        with self._lock:
            self.will_fork_state(state, expression, solutions, policy)

        #Build and enqueue a state for each solution 
        children = []
        for new_value in solutions:
            with state as new_state:
                new_state.constrain(expression == new_value) #We already know it's sat
                #and set the PC of the new state to the concrete pc-dest
                #(or other register or memory address to concrete)
                setstate(new_state, new_value)
                #enqueue new_state 
                state_id = self.add(new_state)
                #maintain a list of childres for logging purpose
                children.append(state_id)
        
        logger.debug("Forking current state into states %r",children)
        return None

    def run(self):
        '''
        Entry point of the Executor; called by workers to start analysis.
        '''
        #policy_order=self.policy_order
        #policy=self.policy
        current_state = None
        current_state_id = None

        with WithKeyboardInterruptAs(self.shutdown):
            #notify siblings we are about to start a run
            self._start_run()

            logger.debug("Starting Manticore Symbolic Emulator Worker (pid %d).",os.getpid())


            while not self.is_shutdown():
                try:
                    #select a suitable state to analyze
                    if current_state is None:

                        with self._lock:
                            #notify siblings we are about to stop this run
                            self._stop_run()
                            #Select a single state_id
                            current_state_id = self.get()
                            #load selected state from secondary storage
                            if current_state_id is not None:
                                current_state = self._workspace.load_state(current_state_id)
                                self.will_load_state(current_state, current_state_id)
                                #notify siblings we have a state to play with
                            self._start_run()

                        #If current_state is still None. We are done.
                        if current_state is None:
                            logger.debug("No more states in the queue, byte bye!")
                            break

                        assert current_state is not None

                    try:

                        # Allows to terminate manticore worker on user request
                        while not self.is_shutdown():
                            if not current_state.execute():
                                break
                        else:
                            #Notify this worker is done
                            self.will_terminate_state(current_state, current_state_id, 'Shutdown')
                            current_state = None


                    #Handling Forking and terminating exceptions
                    except Concretize as e:
                        #expression
                        #policy
                        #setstate()

                        logger.debug("Generic state fork on condition")
                        self.fork(current_state, e.expression, e.policy, e.setstate)
                        current_state = None

                    except TerminateState as e:
                        #Notify this worker is done
                        self.will_terminate_state(current_state, current_state_id, e)

                        logger.debug("Generic terminate state")
                        if e.testcase:
                            self.generate_testcase(current_state, str(e))
                        current_state = None

                    except SolverException as e:
                        import traceback
                        print "*** print_exc:"
                        traceback.print_exc()

                        #Notify this state is done
                        self.will_terminate_state(current_state, current_state_id, e)

                        if solver.check(current_state.constraints):
                            self.generate_testcase(current_state, "Solver failed" + str(e))
                        current_state = None

                except (Exception, AssertionError) as e:
                    import traceback
                    trace = traceback.format_exc()
                    logger.error("Exception: %s\n%s", str(e), trace)
                    #Notify this worker is done
                    self.will_terminate_state(current_state, current_state_id, 'Exception')
                    current_state = None
                    logger.setState(None)
    
            assert current_state is None

            #notify siblings we are about to stop this run
            self._stop_run()

            #Notify this worker is done (not sure it's needed)
            self.will_finish_run()