runs the kernel once and checks the result against answer
165285
def check_kernel_output(self, func, gpu_args, instance, answer, atol, verify, verbose):
        """"""
        logging.debug('check_kernel_output')

        #if not using custom verify function, check if the length is the same
        if not verify and len(instance.arguments) != len(answer):
            raise TypeError("The length of argument list and provided results do not match.")

        #zero GPU memory for output arguments
        for i, arg in enumerate(instance.arguments):
            if verify or answer[i] is not None:
                if isinstance(arg, numpy.ndarray):
                    self.dev.memcpy_htod(gpu_args[i], arg)

        #run the kernel
        check = self.run_kernel(func, gpu_args, instance)
        if not check:
            return True #runtime failure occured that should be ignored, skip correctness check

        #retrieve gpu results to host memory
        result_host = []
        for i, arg in enumerate(instance.arguments):
            if verify or answer[i] is not None:
                if isinstance(arg, numpy.ndarray):
                    result_host.append(numpy.zeros_like(arg))
                    self.dev.memcpy_dtoh(result_host[-1], gpu_args[i])
            else:
                result_host.append(None)

        #if the user has specified a custom verify function, then call it, else use default based on numpy allclose
        if verify:
            try:
                return verify(answer, result_host, atol=atol)
            except TypeError:
                return verify(answer, result_host)
        else:
            return _default_verify_function(instance, answer, result_host, atol, verbose)
100649
def check_solution(self) -> bool:
        
        if self.solution is None:
            raise AssertionError("You need to `run` this algorithm first")
        assert_map = create_bv_bitmap(*self.solution)
        return all([assert_map[k] == v for k, v in self.input_bitmap.items()])
1261911
def startLoop():
    
    def _ipython_loop_asyncio(kernel):
        '''
        Use asyncio event loop for the given IPython kernel.
        '''
        loop = asyncio.get_event_loop()

        def kernel_handler():
            kernel.do_one_iteration()
            loop.call_later(kernel._poll_interval, kernel_handler)

        loop.call_soon(kernel_handler)
        try:
            if not loop.is_running():
                loop.run_forever()
        finally:
            if not loop.is_running():
                loop.run_until_complete(loop.shutdown_asyncgens())
                loop.close()

    patchAsyncio()
    loop = asyncio.get_event_loop()
    if not loop.is_running():
        from ipykernel.eventloops import register_integration, enable_gui
        register_integration('asyncio')(_ipython_loop_asyncio)
        enable_gui('asyncio')
1286541
def run_env_once(f: t.Callable) -> t.Callable:
    

    @wraps(f)
    def wrapper(*args, **kwargs):
        has_run = os.environ.get(wrapper.__name__)
        if has_run == '1':
            return
        result = f(*args, **kwargs)
        os.environ[wrapper.__name__] = '1'
        return result

    return wrapper
7944
def _loop_once(self, timeout=None):
        
        _vv and IOLOG.debug('%r._loop_once(%r, %r)',
                            self, timeout, self.poller)
        #IOLOG.debug('readers =\n%s', pformat(self.poller.readers))
        #IOLOG.debug('writers =\n%s', pformat(self.poller.writers))
        for side, func in self.poller.poll(timeout):
            self._call(side.stream, func)
1033501
def verify(num, filename=None, exit=True):
    """"""
    p = Problem(num)

    filename = filename or p.filename()

    if not os.path.isfile(filename):
        # Attempt to verify the first problem file matched by glob
        if p.glob:
            filename = str(p.file)
        else:
            click.secho('No file found for problem %i.' % p.num, fg='red')
            sys.exit(1)

    solution = p.solution
    click.echo('Checking "{}" against solution: '.format(filename), nl=False)

    cmd = (sys.executable or 'python', filename)
    start = clock()
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    stdout = proc.communicate()[0]
    end = clock()
    time_info = format_time(start, end)

    # Return value of anything other than 0 indicates an error
    if proc.poll() != 0:
        click.secho('Error calling "{}".'.format(filename), fg='red')
        click.secho(time_info, fg='cyan')

        # Return None if option is not --verify-all, otherwise exit
        return sys.exit(1) if exit else None

    # Decode output if returned as bytes (Python 3)
    if isinstance(stdout, bytes):
        output = stdout.decode('ascii')

    # Split output lines into array; make empty output more readable
    output_lines = output.splitlines() if output else ['[no output]']

    # If output is multi-lined, print the first line of the output on a
    # separate line from the "checking against solution" message, and
    # skip the solution check (multi-line solution won't be correct)
    if len(output_lines) > 1:
        is_correct = False
        click.echo()  # force output to start on next line
        click.secho('\n'.join(output_lines), bold=True, fg='red')
    else:
        is_correct = output_lines[0] == solution
        fg_colour = 'green' if is_correct else 'red'
        click.secho(output_lines[0], bold=True, fg=fg_colour)

    click.secho(time_info, fg='cyan')

    # Remove any suffix from the filename if its solution is correct
    if is_correct:
        p.file.change_suffix('')

    # Exit here if answer was incorrect, otherwise return is_correct value
    return sys.exit(1) if exit and not is_correct else is_correct
223260
def run(self):
    """"""
    self.count += 1
    print('FailTwicePlug: Run number %s' % (self.count))
    if self.count < 3:
      raise RuntimeError('Fails a couple times')

    return True
263345
def kernel_integrity(attrs=None, where=None):
    '''
    
    '''
    if __grains__['os_family'] in ['RedHat', 'Debian']:
        return _osquery_cmd(table='kernel_integrity', attrs=attrs, where=where)
    return {'result': False, 'comment': 'Only available on Red Hat or Debian based systems.'}
985909
def get_value(self, name):
        """"""
        code = u"get_ipython().kernel.get_value('%s')" % name
        if self._reading:
            method = self.kernel_client.input
            code = u'!' + code
        else:
            method = self.silent_execute

        # Wait until the kernel returns the value
        wait_loop = QEventLoop()
        self.sig_got_reply.connect(wait_loop.quit)
        method(code)
        wait_loop.exec_()

        # Remove loop connection and loop
        self.sig_got_reply.disconnect(wait_loop.quit)
        wait_loop = None

        # Handle exceptions
        if self._kernel_value is None:
            if self._kernel_reply:
                msg = self._kernel_reply[:]
                self._kernel_reply = None
                raise ValueError(msg)

        return self._kernel_value
738452
async def restart(self):
        '''
        
        '''
        params = {}
        if self.owner_access_key:
            params['owner_access_key'] = self.owner_access_key
        rqst = Request(self.session,
                       'PATCH', '/kernel/{}'.format(self.kernel_id),
                       params=params)
        async with rqst.fetch():
            pass
510247
def run_check(self, data):
        """"""
        if not data:
            sys.exit(1)
        data, sentences, chars, num_words = self.pre_check(data)
        w_dict = Counter(data)
        uniq_len, uncommon, uncom_len = self.gsl(w_dict)
        non_dchall_set = Counter({word: count for word, count in w_dict.items()
            if word and word not in self.dale_chall_words})
        diff_count = sum(non_dchall_set.values())
        dc_score = round(self.dale_chall(diff_count, num_words, sentences), 1)
        cli_score = round(self.coleman_liau(chars, num_words, sentences), 1)
        return uncommon, uncom_len, uniq_len, dc_score, cli_score
255838
def _mod_run_check(cmd_kwargs, onlyif, unless):
    '''
    
    '''
    if onlyif:
        if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
            return {'comment': 'onlyif condition is false',
                    'skip_watch': True,
                    'result': True}

    if unless:
        if __salt__['cmd.retcode'](unless, **cmd_kwargs) == 0:
            return {'comment': 'unless condition is true',
                    'skip_watch': True,
                    'result': True}

    # No reason to stop, return True
    return True
101757
def restart_kernel(self):
        """"""
        client = self.get_current_client()
        if client is not None:
            self.switch_to_plugin()
            client.restart_kernel()
1267579
def after_start_check(self):
        
        try:
            if self.url.scheme == 'http':
                conn = HTTPConnection(self.host, self.port)
            elif self.url.scheme == 'https':
                ssl_context = None
                if not self.verify_tls:
                    ssl_context = ssl._create_unverified_context()
                conn = HTTPSConnection(
                    self.host,
                    self.port,
                    context=ssl_context,
                )
            else:
                raise ValueError(f'Unsupported URL scheme: "{self.url.scheme}"')

            self._send_request(conn)
            response = conn.getresponse()
            status = str(response.status)

            if not self._validate_response(response):
                return False

            if status == self.status or self.status_re.match(status):
                conn.close()
                return True

        except (HTTPException, socket.timeout, socket.error) as ex:
            log.debug('Executor process not healthy yet', command=self.command, error=ex)
            time.sleep(.05)
            return False

        return False
438459
def _verify_one(self, rsock):
        
        poller = mitogen.core.Poller()
        poller.start_receive(rsock.fileno())
        try:
            while True:
                for fd in poller.poll():
                    return
        finally:
            poller.close()
453714
def kernels_status(self, kernel):
        
        if kernel is None:
            raise ValueError('A kernel must be specified')
        if '/' in kernel:
            self.validate_kernel_string(kernel)
            kernel_url_list = kernel.split('/')
            owner_slug = kernel_url_list[0]
            kernel_slug = kernel_url_list[1]
        else:
            owner_slug = self.get_config_value(self.CONFIG_NAME_USER)
            kernel_slug = kernel
        response = self.process_response(
            self.kernel_status_with_http_info(owner_slug, kernel_slug))
        return response
76644
def check(self):
        '''  '''
        if self.lastrun + self.interval < time.time():
            return True
        else:
            return False