Create action to run a program
435141
def create_program_action(parent, text, name, icon=None, nt_name=None):
    """"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if os.name == 'nt' and nt_name is not None:
        name = nt_name
    path = programs.find_program(name)
    if path is not None:
        return create_action(parent, text, icon=icon,
                             triggered=lambda: programs.run_program(name))
361117
def run_program(self, command, working_directory=os.getcwd(),
                    environment=None, cleanup_files=True,
                    native_spec="-l cputype=intel"):
        
        try:
            s = drmaa.Session()
            s.initialize()
            jt = s.createJobTemplate()
            jt.remoteCommand = os.path.dirname(
                os.path.abspath(__file__)) + '/run_program.sh'
            jt.args = [command]

            if environment is not None:
                jt.jobEnvironment = environment

            jt.workingDirectory = working_directory
            jt.nativeSpecification = native_spec
            output_filename = os.path.join(working_directory, 'output.txt')
            jt.outputPath = ':' + output_filename
            jt.joinFiles = True

            jobid = s.runJob(jt)

            s.wait(jobid, drmaa.Session.TIMEOUT_WAIT_FOREVER)

            with open(output_filename, 'r') as output:
                stdout = output.read()

            # Clean up
            if cleanup_files:
                os.remove(output_filename)

        finally:
            try:
                s.control(drmaa.JOB_IDS_SESSION_ALL,
                          drmaa.JobControlAction.TERMINATE)
                s.synchronize([drmaa.JOB_IDS_SESSION_ALL], dispose=True)
                s.exit()
            except(drmaa.errors.NoActiveSessionException):
                pass

        return stdout
267010
def run(entry_point, drivers, loop = None):
    ''' 
    '''
    program = setup(entry_point, drivers)
    dispose = program.run()
    if loop == None:
        loop = asyncio.get_event_loop()

    loop.run_forever()
    dispose()
348087
def run(cmd, input=None, capture_output=False, check=False, quiet=False, **kwargs):
    """"""
    if input is not None:
        kwargs['stdin'] = subprocess.PIPE
    if capture_output:
        kwargs['stdout'] = kwargs['stderr'] = subprocess.PIPE

    try:
        proc = subprocess.Popen(cmd, startupinfo=get_startupinfo(), **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise ExecutableNotFound(cmd)
        else:
            raise

    out, err = proc.communicate(input)

    if not quiet and err:
        stderr_write_bytes(err, flush=True)
    if check and proc.returncode:
        raise CalledProcessError(proc.returncode, cmd, output=out, stderr=err)

    return out, err
367805
def main():
    
    logging.basicConfig(level=logging.DEBUG)
    # create the application and the main window
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()

    # setup ui
    ui = example_ui.Ui_MainWindow()
    ui.setupUi(window)
    ui.bt_delay_popup.addActions([
        ui.actionAction,
        ui.actionAction_C
    ])
    ui.bt_instant_popup.addActions([
        ui.actionAction,
        ui.actionAction_C
    ])
    ui.bt_menu_button_popup.addActions([
        ui.actionAction,
        ui.actionAction_C
    ])
    item = QtWidgets.QTableWidgetItem("Test")
    item.setCheckState(QtCore.Qt.Checked)
    ui.tableWidget.setItem(0, 0, item)
    window.setWindowTitle("QDarkStyle example")

    # tabify dock widgets to show bug #6
    window.tabifyDockWidget(ui.dockWidget1, ui.dockWidget2)

    # setup stylesheet
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

    # auto quit after 2s when testing on travis-ci
    if "--travis" in sys.argv:
        QtCore.QTimer.singleShot(2000, app.exit)

    # run
    window.show()
    app.exec_()
883453
def run(self, name, *args):
        """"""
        assert isinstance(name, string_types)
        # Resolve the alias if it is an alias.
        name = self._aliases.get(name, name)
        # Get the action.
        action = self._actions_dict.get(name, None)
        if not action:
            raise ValueError("Action `{}` doesn't exist.".format(name))
        if not name.startswith('_'):
            logger.debug("Execute action `%s`.", name)
        return action.callback(*args)
397460
def run_action(self, unit_sentry, action,
                   _check_output=subprocess.check_output,
                   params=None):
        
        self.log.warn('charmhelpers.contrib.amulet.utils.run_action has been '
                      'deprecated for amulet.run_action')
        return unit_sentry.run_action(action, action_args=params)
1290510
def run(**kwargs):
    """"""
    paths = kwargs.pop('paths', ())
    action = kwargs.pop('action')
    plugin = kwargs.pop('plugin')
    junit_xml = kwargs.pop('junit_xml')
    use_tracked_files = kwargs.pop('use_tracked_files')
    quiet = kwargs.pop('quiet')

    colorama.init(strip=kwargs.pop('no_color'))

    git_dir = current_git_dir()

    if git_dir is None:
        output(NOT_GIT_REPO_MSG)
        exit(1)

    repo_root = os.path.dirname(git_dir)

    files = []
    if paths:
        # We want to look at files in their current state if paths are passed through
        kwargs['include_unstaged_changes'] = True

        # If paths were provided get all the files for each path
        for path in paths:
            for f in list_files(path):
                f = os.path.relpath(f, repo_root)
                if not f.startswith('..'):  # Don't include files outside the repo root.
                    files.append(f)
    elif use_tracked_files:
        # If the use tracked files flag was passed, get a list of all the tracked files
        out, err, code = git.ls_files()
        files = out.splitlines()

        if kwargs.get('include_untracked'):
            out, err, code = git.ls_files(o=True, exclude_standard=True)
            files += out.splitlines()

    if files or paths:
        kwargs['files'] = files

    config = get_config(repo_root)
    runner = Runner(config.cwd, **kwargs)
    results = ResultCollection()

    if runner.unstaged_changes and not quiet:
        output(UNSTAGED_CHANGES_MSG, end='\n\n')

    processes = list(config.actions) + list(config.plugins)
    processes.sort(key=lambda x: x.name)  # Sort the list of processes for consistent results

    if plugin:
        try:
            processes = [config.plugins.get(plugin)]
        except config.plugins.DoesNotExist as e:
            output('{}\nAvailable plugins:'.format(e.message))

            for p in config.plugins:
                output(p.name)
            exit(1)

    if action:
        try:
            processes = [config.actions.get(action)]
        except config.actions.DoesNotExist as e:
            output('{}\nAvailable actions:'.format(e.message))

            for a in config.actions:
                output(a.name)
            exit(1)

    for process in processes:
        result, message = runner.run_process(process)
        results.append(result)

        if not quiet:
            output(message)

    if junit_xml:
        with open(junit_xml, 'w+') as f:
            f.write('{}'.format(results.dump_junit()))

    if not quiet:
        output(results.dump())
        output('#{{bright}}{}\nCompleted in: {}s'.format(''.ljust(79, '-'), round(results.execution_time, 2)))

    if results.has_error:
        exit(1)
    elif results.has_failure:
        exit(2)
1023138
def create_python_script_action(parent, text, icon, package, module, args=[]):
    """"""
    if is_text_string(icon):
        icon = get_icon(icon)
    if programs.python_script_exists(package, module):
        return create_action(parent, text, icon=icon,
                             triggered=lambda:
                             programs.run_python_script(package, module, args))
220840
def action(name, altname=nil, &block) 
      Runner.instance.add_action name, altname, &block
    end
1272125
public function run()
    {
        // Creates the current controller instance
        $this->controller = new $this->controller($this->twig);

        // Calls the action method on the controller
        $response = call_user_func([$this->controller, $this->action]);

        // Shows the response
        echo $response;
    }
990162
def run(self):
        """"""
        if len(self._argv) > 1 and len(self._argv[1]) > 0:
            oper = self._argv[1]
        else:
            oper = 'fetch'
        if oper == 'fetch':
            ret = self.fetch()
        elif oper == 'config':
            ret = self.config()
            if ret and self._dirtyConfig:
                ret = self.fetch()
        elif oper == 'autoconf':
            ret = self.autoconf()
            if ret:
                print "yes"
            else:
                print "no"
            ret = True
        elif oper == 'suggest':
            ret = self.suggest()
        else:
            raise AttributeError("Invalid command argument: %s" % oper)
        return ret
1171405
def execute_action_list(obj, target, kw):
    """"""
    env = obj.get_build_env()
    kw = obj.get_kw(kw)
    status = 0
    for act in obj.get_action_list():
        args = ([], [], env)
        status = act(*args, **kw)
        if isinstance(status, SCons.Errors.BuildError):
            status.executor = obj
            raise status
        elif status:
            msg = "Error %s" % status
            raise SCons.Errors.BuildError(
                errstr=msg, 
                node=obj.batches[0].targets,
                executor=obj, 
                action=act)
    return status
600258
def action_add(self):
        

        # prepare values for new shortcut
        path = self.args['--workdir'] or os.getcwd()
        name = self.args['<name>']
        cmd = self.args['<command>']

        overwrite = self.args['--force']

        # check for conflicts in DB
        if not overwrite and self.shortcut_exists(name):
            print_err('The shortcut "%s" already exists.' % name)
            return

        # if cmd has arguments, extract the command only
        cmd_parts = [x.strip() for x in cmd.split(' ')]
        cmd_real = cmd_parts[0]
        cmd_tail = ' '.join(cmd_parts[1:])

        # if cmd_real starts with ./, remove that
        if cmd_real.startswith('./'):
            cmd_real = cmd_real[2:]

        # path to the file (if it's in the folder)
        localfile = os.path.abspath(os.path.join(path, cmd_real))

        # check if the file is present at the path given
        if os.path.isfile(localfile):

            # file extension
            ext = os.path.splitext(cmd_real)[1]

            # check for exacutable bit
            # jar is executable, but cannot be run directly
            if os.access(localfile, os.X_OK) and not ext == '.jar':
                # file is executable
                cmd = ''

                if not cmd_real.startswith('/'):
                    cmd = './'

                cmd = cmd + cmd_real + ' ' + cmd_tail

            else:
                # not executable
                # try to find interpreter for the file

                interpreter = {
                    '.py': 'python',
                    '.rb': 'ruby',
                    '.js': 'node',
                    '.pl': 'perl',
                    '.sh': 'sh',
                    '.php': 'php',
                    '.jar': 'java -jar',
                }.get(ext, None)

                # check if interpreter was found
                if interpreter is None:

                    msg = ('Could not make a shortcut to "%s":'
                           + '\n - not executable & unknown extension.') % localfile

                    print_err(msg)
                    return

                cmd = str(interpreter) + ' ' + \
                    str(cmd_real) + ' ' + str(cmd_tail)
        else:
            # use cmd, as given.
            pass

        if overwrite:
            self.db_exec('''
                    DELETE FROM shortcuts WHERE name=?
                    ''', (name,))
        # save to DB
        self.db_exec('''
            INSERT INTO shortcuts (name, path, command)
            VALUES (?, ?, ?)
            ''', (str(name), str(path), str(cmd)))

        # show OK message
        msg = ('Shortcut "%s" has been created.\n'
               + self.shortcut_str(path, cmd)) % name

        print_msg(msg)
942186
public void runAction(ActionType action) {

        m_mode = action;
        setActionFlags();
        setCommonParameters();
        m_checkinBean.clearModules();
        for (String moduleName : getSelectedModules()) {
            m_checkinBean.addModuleToExport(moduleName);
        }
        int result = m_checkinBean.checkIn();
        String log = m_checkinBean.getLogText();
        String message = null;
        boolean error = false;
        switch (action) {
            case checkIn:
                String messageToSave = m_checkinBean.getCommitMessage();
                String emailToSave = m_checkinBean.getGitUserEmail();
                String userToSave = m_checkinBean.getGitUserName();
                CmsObject cms = m_checkinBean.getCmsObject();
                CmsUser user = cms.getRequestContext().getCurrentUser();
                setUserInfo(user, ADDINFO_USER, userToSave);
                setUserInfo(user, ADDINFO_EMAIL, emailToSave);
                setUserInfo(user, ADDINFO_MESSAGE, messageToSave);
                try {
                    cms.writeUser(user);
                } catch (CmsException e) {
                    LOG.error(e.getLocalizedMessage(), e);
                }

                List<Button> resetButtons = new ArrayList<Button>();

                Button resetHead = new Button(CmsVaadinUtils.getMessageText(Messages.GUI_GIT_BUTTON_RESET_HEAD_0));
                resetHead.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_GIT_BUTTON_RESET_HEAD_DESC_0));
                resetHead.addClickListener(new ClickListener() {

                    private static final long serialVersionUID = 1L;

                    public void buttonClick(ClickEvent event) {

                        runAction(ActionType.resetHead);
                    }
                });

                Button resetRemoteHead = new Button(
                    CmsVaadinUtils.getMessageText(Messages.GUI_GIT_BUTTON_RESET_REMOTE_HEAD_0));
                resetRemoteHead.setDescription(
                    CmsVaadinUtils.getMessageText(Messages.GUI_GIT_BUTTON_RESET_REMOTE_HEAD_DESC_0));
                resetRemoteHead.addClickListener(new ClickListener() {

                    private static final long serialVersionUID = 1L;

                    public void buttonClick(ClickEvent event) {

                        runAction(ActionType.resetRemoteHead);
                    }
                });

                if (result == 0) {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CHECKIN_SUCCESSFUL_0);
                } else if (result == 10) {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CHECKIN_FAILED_0);
                    error = true;
                    resetButtons.add(resetRemoteHead);
                    resetButtons.add(resetHead);
                } else {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_CHECKIN_FAILED_0);
                    error = true;
                    resetButtons.add(resetRemoteHead);
                }
                CmsGitActionResultPanel panel = new CmsGitActionResultPanel(message, log, error, resetButtons);
                addAsWindow(panel);
                break;
            case checkOut:
                if (result == 0) {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_IMPORT_SUCCESSFUL_0);
                } else {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_IMPORT_FAILED_0);
                }
                CmsGitActionResultPanel checkoutResult = new CmsGitActionResultPanel(
                    message,
                    log,
                    error,
                    new ArrayList<Button>());
                addAsWindow(checkoutResult);
                break;
            case resetHead:
                if (result == 0) {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_RESET_SUCCESSFUL_0);
                } else {
                    error = true;
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_RESET_FAILED_0);
                }
                CmsGitActionResultPanel resetResult = new CmsGitActionResultPanel(
                    message,
                    log,
                    error,
                    new ArrayList<Button>());
                addAsWindow(resetResult);
                break;
            case resetRemoteHead:
                if (result == 0) {
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_RESET_SUCCESSFUL_0);
                } else {
                    error = true;
                    message = CmsVaadinUtils.getMessageText(Messages.GUI_GIT_RESET_FAILED_0);
                }
                CmsGitActionResultPanel resetRemoteResult = new CmsGitActionResultPanel(
                    message,
                    log,
                    error,
                    new ArrayList<Button>());
                addAsWindow(resetRemoteResult);
                break;
            default:
                // Should never happen
        }
    }
1309501
function launch($action) {

        global $CFG;

        // Get the action path and invoke it
        $actionsroot = "$CFG->dirroot/$CFG->admin/tool/xmldb/actions";
        $actionclass = $action . '.class.php';
        $actionpath = "$actionsroot/$action/$actionclass";

        // Load and invoke the proper action
        $result = false;
        if (file_exists($actionpath) && is_readable($actionpath)) {
            require_once($actionpath);
            if ($xmldb_action = new $action) {
                $result = $xmldb_action->invoke();
                if ($result) {
                    if ($xmldb_action->does_generate != ACTION_NONE &&
                        $xmldb_action->getOutput()) {
                        $this->does_generate = $xmldb_action->does_generate;
                        $this->title = $xmldb_action->title;
                        $this->str = $xmldb_action->str;
                        $this->output .= $xmldb_action->getOutput();
                    }
                } else {
                    $this->errormsg = $xmldb_action->getError();
                }
            } else {
                $this->errormsg = "Error: cannot instantiate class (actions/$action/$actionclass)";
            }
        } else {
            $this->errormsg = "Error: wrong action specified ($action)";
        }
        return $result;
    }
1190320
def run(self, name, replace=None, actions=None):
        
        self.actions = actions # incase we use group

        action = actions.get(name)
        if not action:
            self.die("Action not found: {}", name)
        action['name'] = name
        action_type = action.get('type', "none")
        try:
            func = getattr(self, '_run__' + action_type)
        except AttributeError:
            self.die("Unsupported action type " + action_type)
        try:
            return func(action, replace)
        except Exception as err: # pylint: disable=broad-except
            if self._debug:
                self.debug(traceback.format_exc())
            self.die("Error running action name={} type={} error={}",
                     name, action_type, err)