Try to inject python code into current thread.

    Args:
      codestring: Python snippet to execute in inferior. (may contain newlines)
      wait_for_completion: Block until execution of snippet has completed.
481568
def InjectString(self, codestring, wait_for_completion=True):
    
    if self.inferior.is_running and self.inferior.gdb.IsAttached():
      try:
        self.inferior.gdb.InjectString(
            self.inferior.position,
            codestring,
            wait_for_completion=wait_for_completion)
      except RuntimeError:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback)
    else:
      logging.error('Not attached to any process.')
534718
def execute_code_block(compiler, block, example_globals,
                       script_vars, gallery_conf):
    """"""
    blabel, bcontent, lineno = block
    # If example is not suitable to run, skip executing its blocks
    if not script_vars['execute_script'] or blabel == 'text':
        script_vars['memory_delta'].append(0)
        return ''

    cwd = os.getcwd()
    # Redirect output to stdout and
    orig_stdout = sys.stdout
    src_file = script_vars['src_file']

    # First cd in the original example dir, so that any file
    # created by the example get created in this directory

    my_stdout = MixedEncodingStringIO()
    os.chdir(os.path.dirname(src_file))

    sys_path = copy.deepcopy(sys.path)
    sys.path.append(os.getcwd())
    sys.stdout = LoggingTee(my_stdout, logger, src_file)

    try:
        dont_inherit = 1
        code_ast = compile(bcontent, src_file, 'exec',
                           ast.PyCF_ONLY_AST | compiler.flags, dont_inherit)
        ast.increment_lineno(code_ast, lineno - 1)
        # don't use unicode_literals at the top of this file or you get
        # nasty errors here on Py2.7
        _, mem = _memory_usage(_exec_once(
            compiler(code_ast, src_file, 'exec'), example_globals),
            gallery_conf)
    except Exception:
        sys.stdout.flush()
        sys.stdout = orig_stdout
        except_rst = handle_exception(sys.exc_info(), src_file, script_vars,
                                      gallery_conf)
        # python2.7: Code was read in bytes needs decoding to utf-8
        # unless future unicode_literals is imported in source which
        # make ast output unicode strings
        if hasattr(except_rst, 'decode') and not \
                isinstance(except_rst, unicode):
            except_rst = except_rst.decode('utf-8')

        code_output = u"\n{0}\n\n\n\n".format(except_rst)
        # still call this even though we won't use the images so that
        # figures are closed
        save_figures(block, script_vars, gallery_conf)
        mem = 0
    else:
        sys.stdout.flush()
        sys.stdout = orig_stdout
        sys.path = sys_path
        os.chdir(cwd)

        my_stdout = my_stdout.getvalue().strip().expandtabs()
        if my_stdout:
            stdout = CODE_OUTPUT.format(indent(my_stdout, u' ' * 4))
        else:
            stdout = ''
        images_rst = save_figures(block, script_vars, gallery_conf)
        code_output = u"\n{0}\n\n{1}\n\n".format(images_rst, stdout)

    finally:
        os.chdir(cwd)
        sys.path = sys_path
        sys.stdout = orig_stdout
    script_vars['memory_delta'].append(mem)

    return code_output
1167683
def _execute(self, code):
        
        self.globals['example'] = self.example
        eval(code, self.globals)
253902
def snippet=(v)
      case v
      when String
        @snippet = Snippet.new(v)
      when Snippet
        @snippet = v
      else
        raise ArgumentError, "Snippet must be a String or a Snippet"
      end
    end
598798
private boolean insertCodeBodyHook(TestMethod method, CtMethod ctMethod,
            String classQualifiedName, String methodSimpleName, String methodArgClassesStr) throws CannotCompileException {
        String hookClassName = HookMethodDef.class.getCanonicalName();
        String initializeSrc = hookInitializeSrc();
        boolean transformed = false;

        // iterate code body in the inverse order,
        // so that beforeHook is always inserted after the afterHook of the previous line
        // even if target line of these two hooks are the same
        for (int i = method.getCodeBody().size() - 1; i >= 0; i--) {
            int hookedLine = method.getCodeBody().get(i).getStartLine();

            // insert afterHook first and beforeHook second in each iteration,
            // so that beforeHook is always inserted before the afterHook
            // even if actual inserted lines for these two hooks are the same

            int afterHookInsertedLine = afterHookInsertLine(method, i);
            if (afterHookInsertedLine != -1) {
                int actualAfterHookInsertedLine = ctMethod.insertAt(afterHookInsertedLine, false, null);
                ctMethod.insertAt(afterHookInsertedLine,
                        String.format("%s%s.afterCodeLineHook(\"%s\",\"%s\",\"%s\",\"%s\",%d, %d);",
                                initializeSrc, hookClassName, classQualifiedName,
                                methodSimpleName, methodSimpleName,
                                methodArgClassesStr, hookedLine, actualAfterHookInsertedLine));
                transformed = true;
            }

            int beforeHookInsertedLine = beforeHookInsertLine(method, i);
            if (beforeHookInsertedLine != -1) {
                int actualBeforeHookInsertedLine = ctMethod.insertAt(beforeHookInsertedLine, false, null);
                ctMethod.insertAt(beforeHookInsertedLine,
                        String.format("%s%s.beforeCodeLineHook(\"%s\",\"%s\",\"%s\",\"%s\",%d, %d);",
                                initializeSrc, hookClassName, classQualifiedName,
                                methodSimpleName, methodSimpleName,
                                methodArgClassesStr, hookedLine, actualBeforeHookInsertedLine));
                transformed = true;
            }
        }

        return transformed;
    }
643586
def insert(text)
      raise "must be passed string" unless text.is_a?(String)

      snippet = Snippet.new_text(core, text)
      snippet.snippet_tags.each do |tag_info|
        visit tag_info[:tag]
      end

      context = Context.new(nil)
      insert_func(snippet, context).join($/)
    end
134358
def wait_for_string(self, expected_string, timeout=60):
        """"""
        ADMIN_USERNAME_PROMPT = re.compile("Admin Username:")
        ADMIN_PASSWORD_PROMPT = re.compile("Password:")

        # Big thanks to calvados developers for make this FSM such complex ;-)
        #                    0                         1                        2                        3
        events = [self.syntax_error_re, self.connection_closed_re, self.authentication_error_re, expected_string,
                  #        4                  5                 6             7               8
                  self.press_return_re, self.more_re, pexpect.TIMEOUT, pexpect.EOF, self.calvados_re,
                  #     9                             10                  11                     12
                  self.calvados_connect_re, self.calvados_term_length, ADMIN_USERNAME_PROMPT, ADMIN_PASSWORD_PROMPT]

        # add detected prompts chain
        events += self.device.get_previous_prompts()  # without target prompt

        self.log("Expecting: {}".format(pattern_to_str(expected_string)))
        self.log("Calvados prompt: {}".format(pattern_to_str(self.calvados_re)))

        transitions = [
            (ADMIN_USERNAME_PROMPT, [0], 6, partial(a_send_username, self.device.node_info.username), 5),
            (ADMIN_PASSWORD_PROMPT, [0, 6], 0, partial(a_send_password, self.device.node_info.password), 5),
            (self.authentication_error_re, [0], -1,
             ConnectionAuthenticationError("Admin plane authentication failed", self.device.hostname), 0),
            (self.syntax_error_re, [0], -1, CommandSyntaxError("Command unknown", self.device.hostname), 0),
            (self.connection_closed_re, [0], 1, a_connection_closed, 10),
            (pexpect.TIMEOUT, [0, 2], -1, CommandTimeoutError("Timeout waiting for prompt", self.device.hostname), 0),
            (pexpect.EOF, [0, 1], -1, ConnectionError("Unexpected device disconnect", self.device.hostname), 0),
            (self.more_re, [0], 0, partial(a_send, " "), 10),
            (expected_string, [0, 1], -1, a_expected_prompt, 0),
            (self.calvados_re, [0], -1, a_expected_prompt, 0),
            (self.press_return_re, [0], -1, a_stays_connected, 0),
            (self.calvados_connect_re, [0], 2, None, 0),
            # admin command to switch to calvados
            (self.calvados_re, [2], 3, None, _C['calvados_term_wait_time']),
            # getting the prompt only
            (pexpect.TIMEOUT, [3], 0, partial(a_send, "\r\r"), timeout),
            # term len
            (self.calvados_term_length, [3], 4, None, 0),
            # ignore for command start
            (self.calvados_re, [4], 5, None, 0),
            # ignore for command start
            (self.calvados_re, [5], 0, a_store_cmd_result, 0),
        ]

        for prompt in self.device.get_previous_prompts():
            transitions.append((prompt, [0, 1], 0, a_unexpected_prompt, 0))

        fsm = FSM("WAIT-4-STRING", self.device, events, transitions, timeout=timeout)
        return fsm.run()
340000
def completed?(str)
    str, @prelude = @prelude + str, "" unless @prelude.empty?
    add_lines(str)
    return unless @state == :body && @body.bytesize >= @content_length
    @prelude = bslice(@body, @content_length..-1)
    @body = bslice(@body, 0..@content_length)
    @state = :init
  end
606146
def apply_and_get_result(self, string):
        
        if self.is_multiline:
            compiled_pattern = re.compile(self.pattern, re.MULTILINE)
        else:
            compiled_pattern = re.compile(self.pattern)

        result = re.sub(compiled_pattern, self.repl, string)
        return result
821911
def fetch(code) :
		
		ret = {}

		code = KeywordFetcher._remove_strings(code)
		result = KeywordFetcher.prog.findall(code)

		for keyword in result :
			if len(keyword) <= 1: continue # Ignore single-length word
			if keyword.isdigit(): continue # Ignore number

			if keyword[0] == '-' or keyword[0] == '*' : keyword = keyword[1:] # Remove first char if string is starting by '-' or '*' (Pointer or Negative numbers)
			if keyword[-1] == '-' or keyword[-1] == '*' : keyword = keyword[0:-1] # Remove last char if string is finished by '-' or '*'

			if len(keyword) <= 1: continue

			ret[ keyword ] = ret.get(keyword, 0) + 1 # `ret[ keyword ] += 1` with initial value

		return ret
1263590
def run(self):
        
        # Set a stream to replace stdout, and get results in it
        stdoutBak = sys.stdout
        streamResult = StringIO()
        sys.stdout = streamResult
        try:
            pycodestyle.Checker.check_all(self)
        finally:
            sys.stdout = stdoutBak
1315283
def execute_interactive_code(elem, doc):
    
    code_lines = [l[4:] for l in elem.text.split('\n')]

    code_blocks = [[code_lines[0]]]
    for line in code_lines[1:]:
        if line.startswith(' ') or line == '':
            code_blocks[-1].append(line)
        else:
            code_blocks.append([line])

    final_code = []
    try:
        child = replwrap.REPLWrapper("python", ">>> ", None)
    except NameError:
        pf.debug('Can not run interactive session. No output produced ' +
                 '(Code was:\n{!s}\n)'
                 .format(elem))
        pf.debug('Please pip install pexpect.')
        return ''
    for code_block in code_blocks:
        result = child.run_command('\n'.join(code_block) + '\n').rstrip('\r\n')
        final_code += [('>>> ' if i == 0 else '... ') + l for i, l in
                       enumerate(code_block)]
        if result:
            final_code += [r for r in result.split('\n')
                           if r.strip() not in code_block]
    return '\n'.join(final_code)
909662
def inject_python_code2(fpath, patch_code, tag):
    
    import utool as ut
    text = ut.readfrom(fpath)
    start_tag = '# <%s>' % tag
    end_tag = '# </%s>' % tag
    new_text = ut.replace_between_tags(text, patch_code, start_tag, end_tag)
    ut.writeto(fpath, new_text)
569474
def execute(self):
        
        if self.skip:
            return None

        result = self.pre_execute()
        if result is None:
            try:
                result = self.do_execute()
            except Exception as e:
                result = traceback.format_exc()
                print(self.full_name + "\n" + result)
        if result is None:
            result = self.post_execute()
        return result
859895
def do_execute(self, code, silent, store_history=True,
                   user_expressions=None, allow_stdin=False):
        
        self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions)

        # Split lines and remove empty lines & comments
        code_noc = [line.strip() for line in code.split('\n')
                    if line and line[0] != '#']
        if not code_noc:
            return self._send(None)

        # Process
        try:
            # Detect if we've got magics
            magic_lines = []
            for line in code_noc:
                if line[0] != '%':
                    break
                magic_lines.append(line)

            # Process magics. Once done, remove them from the query buffer
            if magic_lines:
                out = [self._k.magic(line) for line in magic_lines]
                self._send(out, 'multi', silent=silent)
                code = '\n'.join(code_noc[len(magic_lines):])

            # If we have a regular SPARQL query, process it now
            result = self._k.query(code, num=self.execution_count) if code else None

            # Return the result
            return self._send(result, 'raw', silent=silent)

        except Exception as e:
            return self._send(e, 'error', silent=silent)
1025753
public static void waitUntilTextPresent(final String searchString) {
        logger.entering(searchString);
        Preconditions.checkArgument(StringUtils.isNotEmpty(searchString), "Search string cannot be null (or) empty.");
        ExpectedCondition<Boolean> conditionToCheck = new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                return getTextFromBody().contains(searchString);
            }
        };
        waitForCondition(conditionToCheck);
        logger.exiting();
    }
812778
def execute(self, string, max_tacts=None):
        """"""
        self.init_tape(string)
        counter = 0

        while True:
            self.execute_once()
            if self.state == self.TERM_STATE:
                break
            counter += 1
            if max_tacts is not None and counter >= max_tacts:
                raise TimeoutError("algorithm hasn't been stopped")

        return self.get_tape()