A timed block to run tasks with titles and success/failure messages.

    Args:
        msg: The header message to print at the beginning of the timed block.
976902
def timed_display(msg):
    
    def print_header(msg, newline=True):
        """Print a header line.

        Args:
            msg: A message to be printed in the center of the header line.
            newline: Whether or not to print a newline at the end of the
                header. This can be convenient for allowing the line to
                overwrite another.
        """
        if sys.stdout.isatty():
            print('\r', end=Style.BRIGHT + Fore.BLUE)
        print(' {} '.format(msg).center(_ncols(), '='),
              end='\n{}'.format(Style.RESET_ALL)
              if newline else Style.RESET_ALL)
        sys.stdout.flush()

    def print_message(msg):
        """Print a task title message.

        Args:
            msg: The message to display before running the task.
        """
        if sys.stdout.isatty():
            print('\r', end='')
            msg = msg.ljust(_ncols())
        print(msg, end='')
        sys.stdout.flush()

    start = time.time()
    print_header(msg)
    with hidden_cursor():
        try:
            yield print_message
        finally:
            delta = time.time() - start
            print_header('completed in {:.2f}s'.format(delta), False)
968281
def _task_to_text(self, task):
        

        started = self._format_date(task.get('started_at', None))
        completed = self._format_date(task.get('completed_at', None))

        success = task.get('success', None)
        success_lu = {None: 'Not executed', True: 'Success',
                      False: 'Failed'}

        run_log = task.get('run_log', {})
        return '\n'.join(['Task: %s' % task.get('name', None),
                          'Command: %s' % task.get('command', None),
                          'Result: %s' % success_lu[success],
                          'Started at: %s' % started,
                          'Completed at: %s' % completed,
                          'Return Code: %s' % run_log.get('return_code', None),
                          'Stdout: %s' % run_log.get('stdout', None),
                          'Stderr: %s' % run_log.get('stderr', None)])
163387
def handle_message(self, msg):
        
        self._messages.append({
            'type': msg.category,
            'module': msg.module,
            'obj': msg.obj,
            'line': msg.line,
            'column': msg.column,
            'path': msg.path,
            'symbol': msg.symbol,
            'message': str(msg.msg) or '',
            'message-id': msg.msg_id,
        })
98865
def run_commands_from_slack_async(self, message_generator, fire_all, tag, control, interval=1):
        '''
        
        '''

        outstanding = {}  # set of job_id that we need to check for

        while True:
            log.trace('Sleeping for interval of %s', interval)
            time.sleep(interval)
            # Drain the slack messages, up to 10 messages at a clip
            count = 0
            for msg in message_generator:
                # The message_generator yields dicts.  Leave this loop
                # on a dict that looks like {'done': True} or when we've done it
                # 10 times without taking a break.
                log.trace('Got a message from the generator: %s', msg.keys())
                if count > 10:
                    log.warning('Breaking in getting messages because count is exceeded')
                    break
                if not msg:
                    count += 1
                    log.warning('Skipping an empty message.')
                    continue  # This one is a dud, get the next message
                if msg.get('done'):
                    log.trace('msg is done')
                    break
                if fire_all:
                    log.debug('Firing message to the bus with tag: %s', tag)
                    log.debug('%s %s', tag, msg)
                    self.fire('{0}/{1}'.format(tag, msg['message_data'].get('type')), msg)
                if control and (len(msg) > 1) and msg.get('cmdline'):
                    channel = self.sc.server.channels.find(msg['channel'])
                    jid = self.run_command_async(msg)
                    log.debug('Submitted a job and got jid: %s', jid)
                    outstanding[jid] = msg  # record so we can return messages to the caller
                    channel.send_message("@{}'s job is submitted as salt jid {}".format(msg['user_name'], jid))
                count += 1
            start_time = time.time()
            job_status = self.get_jobs_from_runner(outstanding.keys())  # dict of job_ids:results are returned
            log.trace('Getting %s jobs status took %s seconds', len(job_status), time.time() - start_time)
            for jid in job_status:
                result = job_status[jid]['data']
                function = job_status[jid]['function']
                if result:
                    log.debug('ret to send back is %s', result)
                    # formatting function?
                    this_job = outstanding[jid]
                    channel = self.sc.server.channels.find(this_job['channel'])
                    return_text = self.format_return_text(result, function)
                    return_prefix = "@{}'s job `{}` (id: {}) (target: {}) returned".format(
                        this_job['user_name'], this_job['cmdline'], jid, this_job['target'])
                    channel.send_message(return_prefix)
                    ts = time.time()
                    st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S%f')
                    filename = 'salt-results-{0}.yaml'.format(st)
                    r = self.sc.api_call(
                        'files.upload', channels=channel.id, filename=filename,
                        content=return_text)
                    # Handle unicode return
                    log.debug('Got back %s via the slack client', r)
                    resp = salt.utils.yaml.safe_load(salt.utils.json.dumps(r))
                    if 'ok' in resp and resp['ok'] is False:
                        this_job['channel'].send_message('Error: {0}'.format(resp['error']))
                    del outstanding[jid]
428076
def _process_message(self, msg):
        
        self._logger.info(
            'Processing Message(topic={}, partition={}, offset={}) ...'
            .format(msg.topic, msg.partition, msg.offset))
        try:
            job = self._deserializer(msg.value)
            job_repr = get_call_repr(job.func, *job.args, **job.kwargs)

        except Exception as err:
            self._logger.exception('Job was invalid: {}'.format(err))
            self._execute_callback('invalid', msg, None, None, None, None)
        else:
            self._logger.info('Executing job {}: {}'.format(job.id, job_repr))

            if job.timeout:
                timer = threading.Timer(job.timeout, _thread.interrupt_main)
                timer.start()
            else:
                timer = None
            try:
                res = job.func(*job.args, **job.kwargs)
            except KeyboardInterrupt:
                self._logger.error(
                    'Job {} timed out or was interrupted'.format(job.id))
                self._execute_callback('timeout', msg, job, None, None, None)
            except Exception as err:
                self._logger.exception(
                    'Job {} raised an exception:'.format(job.id))
                tb = traceback.format_exc()
                self._execute_callback('failure', msg, job, None, err, tb)
            else:
                self._logger.info('Job {} returned: {}'.format(job.id, res))
                self._execute_callback('success', msg, job, res, None, None)
            finally:
                if timer is not None:
                    timer.cancel()
193805
def toc(tt, return_msg=False, write_msg=True, verbose=None):
    
    if verbose is not None:
        write_msg = verbose
    (msg, start_time) = tt
    ellapsed = (default_timer() - start_time)
    if (not return_msg) and write_msg and msg is not None:
        sys.stdout.write('...toc(%.4fs, ' % ellapsed + '"' + str(msg) + '"' + ')\n')
    if return_msg:
        return msg
    else:
        return ellapsed
963228
def total_timer(msg):
    
    start = timer()
    yield
    t = timer() - start
    _TOTAL_TIMER_DATA[msg].feed(t)
509543
def msg(message):
    
    to_stdout(" --- {message}".format(message=message))
    if _logger:
        _logger.info(message)
160925
def show(self, msg, indent=0, style="", **kwargs):
        
        if self.enable_verbose:
            new_msg = self.MessageTemplate.with_style.format(
                indent=self.tab * indent,
                style=style,
                msg=msg,
            )
            print(new_msg, **kwargs)
38743
def print_time(self, message="Time is now: ", print_frame_info=True):
        
        if print_frame_info:
            frame_info = inspect.getouterframes(inspect.currentframe())[1]
            print(message, (datetime.now() - self.start_time), frame_info)
        else:
            print(message, (datetime.now() - self.start_time))
435379
def write(self, msg, level=logging.INFO):
        
        if msg is not None and len(msg.strip()) > 0:
            self.logger.log(level, msg)
1278490
def msg(self, level, s, *args):
        
        if s and level <= self.debug:
            print "%s%s %s" % ("  " * self.indent, s, ' '.join(map(repr, args)))
1210441
private synchronized void showMessage(final String msg)
	{
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				getMessages().setText(msg);
			}
		});
	}
488047
public void printRawLines(String msg) {
        PrintWriter noticeWriter = writers.get(WriterKind.NOTICE);
        printRawLines(noticeWriter, msg);
    }
706185
def printmp(msg):
    
    filler = (80 - len(msg)) * ' '
    print(msg + filler, end='\r')
    sys.stdout.flush()
471154
def _failed(self, msg):
        
        self.log(msg)
        self.result.passed = False
        self.result.add_error(msg)
        self.log(u"Failed")
1130182
def setError(self, msg=None, title=None):
        
        if msg is not None:
            self.messageLabel.setText(msg)

        if title is not None:
            self.titleLabel.setText(title)