Create a line object skeleton with only code and indentation from a code string of an assignment definition string (see parseCode)
427940
function(codestring, widget) {
    this.widget = widget;
    this.code = "";
    this.indent = 0;
    this._toggles = [];
    if (codestring) {
      // Consecutive lines to be dragged as a single block of code have strings "\\n" to
      // represent newlines => replace them with actual new line characters "\n"
      this.code = codestring.replace(/#distractor\s*$/, "").replace(trimRegexp, "$1").replace(/\\n/g, "\n");
      this.indent = codestring.length - codestring.replace(/^\s+/, "").length;
    }
  }
653760
def find_insertion_line(self, code):
        """"""
        match = re.search(r'^(def|class)\s+', code)
        if match is not None:
            code = code[:match.start()]
        try:
            pymodule = libutils.get_string_module(self.project, code)
        except exceptions.ModuleSyntaxError:
            return 1
        testmodname = '__rope_testmodule_rope'
        importinfo = importutils.NormalImport(((testmodname, None),))
        module_imports = importutils.get_module_imports(self.project,
                                                        pymodule)
        module_imports.add_import(importinfo)
        code = module_imports.get_changed_source()
        offset = code.index(testmodname)
        lineno = code.count('\n', 0, offset) + 1
        return lineno
730046
def get_code(self, code):
        
        # code= [code] if isinstance(code,str) else
        return self.new(self.data.loc[(slice(None), code), :])
1181236
def _set_line_indent(src, line, indent):
    '''
    
    '''
    if not indent:
        return line

    idt = []
    for c in src:
        if c not in ['\t', ' ']:
            break
        idt.append(c)

    return ''.join(idt) + line.lstrip()
1336027
def visit_Assign(self, node):
        """"""
        line = self._code_lines[node.lineno - 1]
        if SIG_COMMENT in line:
            line = _RE_COMMENT_IN_STRING.sub("", line)

        if (SIG_COMMENT not in line) and (not self.generic):
            return

        if SIG_COMMENT in line:
            _, signature = line.split(SIG_COMMENT)
            _, return_type, requires = parse_signature(signature)
            self.required_types |= requires

        parent = self._parents[-1]
        for var in node.targets:
            if isinstance(var, ast.Name):
                name, p = var.id, parent
            elif (
                isinstance(var, ast.Attribute)
                and isinstance(var.value, ast.Name)
                and (var.value.id == "self")
            ):
                name, p = var.attr, parent.parent
            else:
                name, p = None, None

            if name is not None:
                if self.generic:
                    return_type = "Any"
                    self.required_types.add(return_type)
                stub_node = VariableNode(name, return_type)
                p.add_variable(stub_node)
453005
def from_string(cls, line, ignore_bad_cookies=False,
                    ignore_bad_attributes=True):
        ""
        cookie_dict = parse_one_response(
            line, ignore_bad_cookies=ignore_bad_cookies,
            ignore_bad_attributes=ignore_bad_attributes)
        if not cookie_dict:
            return None
        return cls.from_dict(
            cookie_dict, ignore_bad_attributes=ignore_bad_attributes)
804118
def _get_a_code_object_from( thing ) :
    '''
    
    '''
    # If we were passed a Method wrapper, get its function
    if isinstance( thing, types.MethodType ) :
        thing = thing.__func__
    # If we were passed a property object, get its getter function
    # (no direct support for the fdel or fset functions)
    if hasattr( thing, 'fget' ) :
        thing = thing.fget
    # If we were passed, or now have, a function, get its code object.
    if isinstance( thing, types.FunctionType ) :
        thing = thing.__code__
    # We should now have a code object, or will never have it.
    return thing
1309328
def parse(cls, line, ns={}):
        
        definitions = []
        parses  = [p for p in cls.compositor_spec.scanString(line)]
        if len(parses) != 1:
            raise SyntaxError("Invalid specification syntax.")
        else:
            e = parses[0][2]
            processed = line[:e]
            if (processed.strip() != line.strip()):
                raise SyntaxError("Failed to parse remainder of string: %r" % line[e:])

        opmap = {op.__name__:op for op in Compositor.operations}
        for group in cls.compositor_spec.parseString(line):

            if ('mode' not in group) or group['mode'] not in ['data', 'display']:
                raise SyntaxError("Either data or display mode must be specified.")
            mode = group['mode']

            kwargs = {}
            operation = opmap[group['op']]
            spec = ' '.join(group['spec'].asList()[0])

            if  group['op'] not in opmap:
                raise SyntaxError("Operation %s not available for use with compositors."
                                  % group['op'])
            if  'op_settings' in group:
                kwargs = cls.todict(group['op_settings'][0], 'brackets', ns=ns)

            definition = Compositor(str(spec), operation, str(group['value']), mode, **kwargs)
            definitions.append(definition)
        return definitions
409110
function(options) {
	 // Contains line objects of the user-draggable code.
	 // The order is not meaningful (unchanged from the initial state) but
	 // indent property for each line object is updated as the user moves
	 // codelines around. (see parseCode for line object description)
     this.modified_lines = [];
     // contains line objects of distractors (see parseCode for line object description)
     this.extra_lines = [];
     // contains line objects (see parseCode for line object description)
     this.model_solution = [];
     
     //To collect statistics, feedback should not be based on this
     this.user_actions = [];
     
     //State history for feedback purposes
     this.state_path = [];
     this.states = {};
     
     var defaults = {
       'incorrectSound': false,
       'x_indent': 50,
       'can_indent': true,
       'feedback_cb': false,
       'first_error_only': true,
       'max_wrong_lines': 10,
       'lang': 'en',
       'toggleSeparator': '::'
     };
     
     this.options = jQuery.extend({}, defaults, options);
     this.feedback_exists = false;
     this.id_prefix = options['sortableId'] + 'codeline';
     if (translations.hasOwnProperty(this.options.lang)) {
       this.translations = translations[this.options.lang];
     } else {
       this.translations = translations['en'];
     }

     // translate trash_label and solution_label
     if (!this.options.hasOwnProperty("trash_label")) {
         this.options.trash_label = this.translations.trash_label;
     }
     if (!this.options.hasOwnProperty("solution_label")) {
         this.options.solution_label = this.translations.solution_label;
     }
     this.FEEDBACK_STYLES = { 'correctPosition' : 'correctPosition',
                              'incorrectPosition' : 'incorrectPosition',
                              'correctIndent' : 'correctIndent',
                              'incorrectIndent' : 'incorrectIndent'};

    // use grader passed as an option if defined and is a function
    if (this.options.grader && _.isFunction(this.options.grader)) {
      this.grader = new this.options.grader(this);
    } else {
      // initialize the grader
      if (typeof(this.options.unittests) !== "undefined") { /// unittests are specified
        this.grader = new UnitTestGrader(this);
      } else if (typeof(this.options.vartests) !== "undefined") { /// tests for variable values
        this.grader = new VariableCheckGrader(this);
      } else { // "traditional" parson feedback
        this.grader = new LineBasedGrader(this);
      }
    }
   }
1342556
def _pys2code(self, line):
        """"""

        row, col, tab, code = self._split_tidy(line, maxsplit=3)
        key = self._get_key(row, col, tab)

        self.code_array.dict_grid[key] = unicode(code, encoding='utf-8')
952773
function stringifyObject(object, indent) {
  return Object.keys(object).reduce((string, key, index) => {
    const script = object[key]
    let value
    if (isPlainObject(script)) {
      value = `{${stringifyObject(script, `${indent}  `)}\n${indent}}`
    } else {
      value = `'${escapeSingleQuote(script)}'`
    }
    const comma = getComma(isLast(object, index))
    return `${string}\n${indent}${key}: ${value}${comma}`
  }, '')
}
213616
public String reindent(String code) {
    try {
      // Remove indention from each line.
      StringBuilder sb = new StringBuilder();
      LineReader lr = new LineReader(new StringReader(code));
      String line = lr.readLine();
      while (line != null) {
        sb.append(line.trim());
        line = lr.readLine();
        if (line != null) {
          sb.append('\n');
        }
      }
      String strippedCode = sb.toString();

      // Now indent it again.
      int indent = indention * DEFAULT_INDENTION;
      sb.setLength(0);  // reset buffer
      lr = new LineReader(new StringReader(strippedCode));
      line = lr.readLine();
      while (line != null) {
        if (line.startsWith("}")) {
          indent -= DEFAULT_INDENTION;
        }
        if (!line.startsWith("#line")) {
          sb.append(pad(indent));
        }
        sb.append(line);
        if (line.endsWith("{")) {
          indent += DEFAULT_INDENTION;
        }
        line = lr.readLine();
        if (line != null) {
          sb.append('\n');
        }
      }
      return sb.toString();
    } catch (IOException e) {
      // Should never happen with string readers.
      throw new AssertionError(e);
    }
  }
834803
function prettify (luaCode) {
  const lines = luaCode
    .split("\n")
    .map(line => line.trim());

  const { code } = lines.reduce((result, line) => {
    const { code, indentation } = result;
    let currentIndentation = indentation;
    let nextLineIndentation = indentation;

    if (indentIncrease.some(entry => entry(line))) {
      nextLineIndentation++;
    }

    if (indentDecrease.some(entry => entry(line))) {
      currentIndentation--;
      nextLineIndentation--;
    }

    code.push(line && line.padStart(line.length + currentIndentation * 2) || line);

    return {
      code,
      indentation: Math.max(0, nextLineIndentation)
    };
  }, {
    code: [],
    indentation: 0
  });

  return code.join("\n");
}
845868
def _code_line(self, line):
        """"""
        assert self._containers
        container = self._containers[-1]
        # Handle extra spaces.
        text = line
        while text:
            if text.startswith('  '):
                r = re.match(r'(^ +)', text)
                n = len(r.group(1))
                container.addElement(S(c=n))
                text = text[n:]
            elif '  ' in text:
                assert not text.startswith(' ')
                i = text.index('  ')
                container.addElement(Span(text=text[:i]))
                text = text[i:]
            else:
                container.addElement(Span(text=text))
                text = ''
645908
def from_string(line):
        
        result = StringValueMap()
        
        if line == None or len(line) == 0:
            return result

        tokens = str(line).split(';')
        for token in tokens:
            if len(token) == 0:
                continue
            index = token.find('=')
            key = token[0:index] if index >= 0 else token
            value = token[index + 1:] if index >= 0 else None
            result.put(key, value)

        return result
333783
def __edit_line(line, code, code_obj):  # pylint: disable=R0201
        """"""
        try:
            # pylint: disable=eval-used
            result = eval(code_obj, globals(), locals())
        except TypeError as ex:
            log.error("failed to execute %s: %s", code, ex)
            raise
        if result is None:
            log.error("cannot process line '%s' with %s", line, code)
            raise RuntimeError('failed to process line')
        elif isinstance(result, list) or isinstance(result, tuple):
            line = unicode(' '.join([unicode(res_element)
                                     for res_element in result]))
        else:
            line = unicode(result)
        return line
623312
function replaceDefine(code) {
    var defineList = getDefineBlock(code);
    var segments = [];
    var index = 0;
    defineList.forEach(function (block) {

        if (block.type === 'function') {
            segments.push(code.slice(index, block.defineRange[0]));
            index = block.factoryRange[0] + 1;

            block.returnRange.forEach(function (range) {
                segments.push(code.slice(index, range[0]));
                segments.push('module.exports =');
                segments.push(code.slice(range[0] + 6, range[1]));
                index = range[1];
            });
            segments.push(code.slice(index, block.factoryRange[1] - 1));

            index = block.defineRange[1];
        }
        else if (block.type === 'object') {
            segments.push(code.slice(index, block.defineRange[0]));
            segments.push('module.exports = ');
            segments.push(code.slice(block.factoryRange[0], block.factoryRange[1]) + ';');
            index = block.defineRange[1];
        }
    });

    segments.push(code.slice(index));

    code = segments.join('');

    return code;
}