/*
See https://github.com/facebook/graphql/pull/327/files#diff-fe406b08746616e2f5f00909488cce66R758
357012
public static String removeIndentation(String rawValue) {
        String[] lines = rawValue.split("\\n");
        Integer commonIndent = null;
        for (int i = 0; i < lines.length; i++) {
            if (i == 0) continue;
            String line = lines[i];
            int length = line.length();
            int indent = leadingWhitespace(line);
            if (indent < length) {
                if (commonIndent == null || indent < commonIndent) {
                    commonIndent = indent;
                }
            }
        }
        List<String> lineList = new ArrayList<>(Arrays.asList(lines));
        if (commonIndent != null) {
            for (int i = 0; i < lineList.size(); i++) {
                String line = lineList.get(i);
                if (i == 0) continue;
                if (line.length() > commonIndent) {
                    line = line.substring(commonIndent);
                    lineList.set(i, line);
                }
            }
        }
        while (!lineList.isEmpty()) {
            String line = lineList.get(0);
            if (containsOnlyWhiteSpace(line)) {
                lineList.remove(0);
            } else {
                break;
            }
        }
        while (!lineList.isEmpty()) {
            int endIndex = lineList.size() - 1;
            String line = lineList.get(endIndex);
            if (containsOnlyWhiteSpace(line)) {
                lineList.remove(endIndex);
            } else {
                break;
            }
        }
        StringBuilder formatted = new StringBuilder();
        for (int i = 0; i < lineList.size(); i++) {
            String line = lineList.get(i);
            if (i == 0) {
                formatted.append(line);
            } else {
                formatted.append("\n");
                formatted.append(line);
            }
        }
        return formatted.toString();
    }
502157
function diffContentItems(lhs, rhs) {
  var d = diff(lhs, rhs, function(key, value) {
    return value === 'visitors' || value === 'headers';
  });
  return d;
}
551844
function inlineDiff (actual, expected, formatAdd, formatRem) {
  var result = diff.diffWordsWithSpace(actual, expected)
    .map(function (line, idx) {
      if (line.added) { return formatLinesWith(formatAdd, line.value) }
      return line.removed
        ? formatLinesWith(formatRem, line.value)
        : line.value
    })
    .join('')

  var lines = result.split('\n')
  if (lines.length > 4) {
    result = lines
      .map(function (line, idx) {
        return lpad(idx + 1, String(lines.length).length) + ' | ' + line
      })
      .join('\n')
  }

  return formatRem('actual') + ' ' + formatAdd('expected') + '\n\n' + result
}
1038649
function compactGraphQLQuery (query) {
    let lexer = new Tokenizr()

    /*  configure lexical analysis  */
    lexer.rule(/#[^\r\n]*(?=\r?\n)/,                       (ctx, match) => { ctx.accept("comment") })
    lexer.rule(/"(?:\\"|[^"])*"/,                          (ctx, match) => { ctx.accept("string") })
    lexer.rule(/$[a-zA-Z_][a-zA-Z0-9_]*/,                  (ctx, match) => { ctx.accept("var") })
    lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/,                   (ctx, match) => { ctx.accept("id") })
    lexer.rule(/[+-]?[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/, (ctx, match) => { ctx.accept("number") })
    lexer.rule(/[ \t\r\n]+/,                               (ctx, match) => { ctx.accept("ws", " ") })
    lexer.rule(/[{}]/,                                     (ctx, match) => { ctx.accept("brace") })
    lexer.rule(/[[\]]/,                                    (ctx, match) => { ctx.accept("bracket") })
    lexer.rule(/[()]/,                                     (ctx, match) => { ctx.accept("parenthesis") })
    lexer.rule(/,/,                                        (ctx, match) => { ctx.accept("comma") })
    lexer.rule(/!/,                                        (ctx, match) => { ctx.accept("not") })
    lexer.rule(/\.\.\./,                                   (ctx, match) => { ctx.accept("ellipsis") })
    lexer.rule(/@/,                                        (ctx, match) => { ctx.accept("at") })
    lexer.rule(/:/,                                        (ctx, match) => { ctx.accept("colon") })
    lexer.rule(/./,                                        (ctx, match) => { ctx.accept("any") })
    lexer.input(query)
    lexer.debug(false)

    /*  fetch all parsed tokens  */
    let tokens = lexer.tokens()

    /*  remove whitespace tokens at harmless positions  */
    let output = ""
    let re = /^(?:brace|bracket|parenthesis|comma|colon)$/
    for (let i = 0; i < tokens.length; i++) {
        if (   tokens[i].type === "comment"
            || (   tokens[i].type === "ws"
                && (   (   i < tokens.length - 1
                        && tokens[i + 1].type.match(re))
                    || (    i > 0
                        && tokens[i - 1].type.match(re))))) {
            tokens.splice(i, 1)
            i--
        }
    }

    /*  assembly and return new query string  */
    tokens.forEach((token) => {
        output += token.value
    })
    return output
}
835350
function (req, res, next) {
    var graphApiUrl = 'https://graph.facebook.com/me';
    var accessToken = req.accessToken;

    request.get({ url: graphApiUrl, qs: accessToken, json: true }, function(err, response, profile) {
      if (response.statusCode !== 200) {
        res.status(500).send({ message: profile.error.message });
        return;
      }
      req.profile = profile;
      next();
    });
  }
421242
function errorDiff(err, type, escape) {
  return diff['diff' + type](err.actual, err.expected).map(function(str){
    if (escape) {
      str.value = str.value
        .replace(/\t/g, '<tab>')
        .replace(/\r/g, '<CR>')
        .replace(/\n/g, '<LF>\n');
    }
    if (str.added) return colorLines('diff added', str.value);
    if (str.removed) return colorLines('diff removed', str.value);
    return str.value;
  }).join('');
}
214269
function proxyConfig(path) {
  const config = {}

  const {endpointsExtension} = tryGetGraphQLProjectConfig()
  if (endpointsExtension) {
    const graphqlEndpoint = endpointsExtension.getEndpoint()

    const {url: target, headers} = graphqlEndpoint
    const changeOrigin = true

    const pathRewrite = {}
    pathRewrite[`^${path}`] = ''

    config[path] = {changeOrigin, headers, pathRewrite, target}
  }

  return config
}
961850
function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) {
  if (jsonSchemaType === "array") {
    if (graphQLObjectTypes[schemaName]) {
      return new GraphQLList(graphQLObjectTypes[schemaName]);
    } else {
      const translated = {
        pilots: "people",
        characters: "people",
        residents: "people"
      }[schemaName];

      if (! translated) {
        throw new Error(`no type ${schemaName}`);
      }

      const type = graphQLObjectTypes[translated];

      if (! type) {
        throw new Error(`no GraphQL type ${schemaName}`);
      }

      return new GraphQLList(type);
    }
  }

  return {
    string: GraphQLString,
    date: GraphQLString,
    integer: GraphQLInt,
  }[jsonSchemaType];
}
16556
@RequestMapping(value = "changelog/diff", method = RequestMethod.GET)
    public ResponseEntity<String> diff(FileDiffChangeLogRequest request) {
        // Gets the change log
        SVNChangeLog changeLog = changeLogService.changeLog(request);
        // Gets the files
        SVNChangeLogFiles changeLogFiles = changeLogService.getChangeLogFiles(changeLog);
        // Diff export
        String diff = scmService.diff(
                changeLogFiles.getList(),
                request.getPatterns(),
                changeLogFile -> changeLogService.getDiff(changeLog.getRepository(), changeLogFile)
        );
        // Content type
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        // Body and headers
        return new ResponseEntity<>(diff, responseHeaders, HttpStatus.OK);
    }
201739
function diffTrack( newArr, oldArr, keyOf  ){

  var olen = oldArr.length;
  var nlen = newArr.length;


  var steps = [];
  var ret = {
    isTrack: true,
    steps:steps
  }

  // 确保当存在无法被keyOf的item时，不会死循环
  // true 说明 不同
  // false 说明 引用相同
  if( !_.simpleDiff(newArr, oldArr) ) return ret;

  ret.dirty = true;

  if( olen && !nlen ) { // 直接删除所有
    createStep( steps, 0,0,olen );
    return ret
  }
  if(nlen && !olen){ //直接添加所有
    createStep(steps, 1,0,nlen);
    return ret
  }

  // 模拟被真实操作的groups获得真实的下标
  var substitute = _.slice( oldArr );
  var newTrack = getTrackInfo( newArr, keyOf );
  var oldTrack = getTrackInfo( oldArr, keyOf );

  var newTrackMap = newTrack.trackMap;
  var oldTrackMap = oldTrack.trackMap;

  var oldRemoved = {};

  // 使用替身数组完成对应操作，模拟DOM操作

  // i 老数据下标， 
  // j 新数组下标
  var untrackIndex = 0, 
    oldUntracked = oldTrack.untrack, 
    oldUntrackedLength = oldUntracked.length;

  // @FIXIT, 当数组对应的key发生改变，而缓存key其实是一种错误开销
  // 暂时将所有untraked的东西都进行删除，实际这是用户的一种错误使用, 可以引发性能开销
  if(oldUntrackedLength){
    while(oldUntrackedLength--){
      var oidx = oldUntracked[oldUntrackedLength];
      remove( substitute, steps, oldUntracked[ oldUntrackedLength ] );
    }
  }

  var len = substitute.length;
  for(var i =0; i<len ;i++){
    var oldItem = substitute[i];
    var oldKey = keyOf( oldItem);

    // 将所有其它不存在与
    if( !newTrackMap.hasOwnProperty(oldKey) ){
      oldRemoved[ oldKey ] = oldTrackMap[ oldKey ]
      remove( substitute, steps, i );
      i--;
      len--;
    }
    
  }


  var jlen = newArr.length;
  // i old index
  // j new index
  var i = 0, j = 0;

  while( j < jlen  ){

    //@TODO 大量重复key的计算
    if(i >= substitute.length){
      insert( substitute, steps, i, 1 );
      i++;
      j++;
      continue
    }
    var oldKey = keyOf( substitute[i] );


    var item = newArr[ j ];
    var key = keyOf( item );

    if( key === oldKey ){
      i++; j++;
      continue;
    }else{
      //先插入一个节点
      insert( substitute, steps, i, 1 );
      i++;
      j++;
      continue;
    }

  }
  // 说明还未完全处理完毕，因为j条件短了

  var slen = substitute.length;
  if( j < slen ){
    createStep(steps, 0, j, slen - j )
    for(var k = j; k < slen; k++ ){
      var oldKey = keyOf( substitute[k]);
      oldRemoved[oldKey] = oldTrackMap[oldKey];
    }
  }
  // 这些将在apply到前台时，被复用
  ret.oldKeyMap = oldRemoved;

  return ret;
}
24482
function(options) {
    options = options || {}
    var exclude = options.exclude || []
    var schema = []
    var query = []
    var mutation = []

    Object.keys(this.models).forEach(function(modelName) {
      var model = this.models[modelName]
      var definition = model.definition

      if (definition.graphqlHelper.hidden) return // via this.graphQLExclude()
      if (exclude.indexOf(modelName) !== -1) return

      schema.push(model.toGraphQLType())
      schema.push.apply(schema, definition.graphqlHelper.schema)

      query.push.apply(query, definition.graphqlHelper.query)
      mutation.push.apply(mutation, definition.graphqlHelper.mutation)
    }, this)

    if (query.length > 0) {
      schema.push(
        [
          'type Query{',
          query
            .map(function(str) {
              return '  ' + str
            })
            .join('\n'),
          '}'
        ].join('\n')
      )
    }

    if (mutation.length > 0) {
      schema.push(
        [
          'type Mutation{',
          mutation
            .map(function(str) {
              return '  ' + str
            })
            .join('\n'),
          '}'
        ].join('\n')
      )
    }

    return schema.join('\n\n')
  }
1268947
static function diff($traversable, $traversable2) 
    {
        return static::filter($traversable, function($value) use ($traversable2) {
            return ! Collection::contains($traversable2, $value);
        });
    }
198221
function removeDirIfOk(p) {
  return globP(path.join(p, '*' + consts.DIFF_PNG_SUFFIX))
    .then(function(res) {
      if (res.length === 0) {
        return rimrafP(p);
      }
      return Promise.resolve();
    });
}
482243
function convertDiff (diff) {
  var converted = []
  var index = 0

  for (var i = 0; i < diff.length; i += 1) {
    var change = diff[i]

    if (!change.added && !change.removed) {
      index += change.items.length
      continue
    }

    var next = diff[i + 1]
    if (next && change.removed && next.added) {
      var changeLen = change.items.length
      var nextLen = next.items.length
      var len = Math.min(changeLen, nextLen)
      converted.push({
        items: next.items.slice(0, len),
        index: index,
        added: true,
        removed: true
      })

      index += len

      if (changeLen < nextLen) {
        converted.push({
          items: next.items.slice(len),
          index: index,
          added: true,
          removed: false
        })
        index += nextLen - len
      } else if (nextLen < changeLen) {
        converted.push({
          items: change.items.slice(len),
          index: index,
          added: false,
          removed: true
        })
      }

      i += 1
      continue
    }

    converted.push({
      items: change.items.slice(),
      index: index,
      added: change.added,
      removed: change.removed
    })

    if (change.added) {
      index += change.items.length
    }
  }

  return converted
}
54311
def graph2item(graph_item)
      id = graph_item["id"]
      if id =~ /^notif_(.+)$/
        item = Item.new({
          id: id,
          info: :notification,
          data: {
            user: graph_item["from"]["name"],
            content: graph_item["title"],
          },
          date: graph_item["created_time"],
          link: graph_item["link"]
        })
      else
        content = 
          case graph_item["type"]
          when "status"
            if graph_item["message"].nil?
              graph_item["story"]
            else
              graph_item["message"]
            end
          when "photo"
            "share a photo: #{graph_item['message'] || graph_item['link']}"
          when "checkin"
            "checkin"
          when "video"
            "share a video: #{graph_item['message']}"
          when "link"
            "#{graph_item["message"]} #{graph_item["link"]} #{graph_item["name"]}"
          end
        
        link = 
          (graph_item["actions"] && graph_item["actions"].first["link"]) ||
          graph_item["link"]
        
        likes = graph_item["likes"] && graph_item["likes"]["data"] || []
        comments = graph_item["comments"] && graph_item["comments"]["data"] || []

        like_count = likes.size
        comment_count = comments.size

        item = Item.new({
          id: graph_item["id"],
          info: :feed,
          data: {
            type: graph_item["type"],
            user: graph_item["from"]["name"],
            content: content,
            picture: graph_item["picture"],
            link: link,
            like_count: like_count,
            likes: likes, 
            comment_count: comment_count,
            comments: comments,
            date: DateTime.parse(graph_item["created_time"]),
          },
          date: graph_item["created_time"],
        })
      end
      item.raw = graph_item
      return item
    end
1020824
function printDiff(diff) {
  diff.forEach(line => {
    if (line.added) {
      line.value.split('\n').forEach(l => l && console.log(chalk.green(' +++ ') + chalk.gray(l)));
    } else if (line.removed) {
      line.value.split('\n').forEach(l => l && console.log(chalk.red(' --- ') + chalk.gray(l)));
    }
  });
}
156051
static NodeDifference diff(ProductPartitionNode originalNode,
      ProductPartitionNode newNode, Comparator<ProductDimension> dimensionComparator) {
    NodeDifference nodeDifference;
    if (originalNode == null && newNode == null) {
      nodeDifference = NodeDifference.NONE;
    } else if (originalNode == null) {
      nodeDifference = NodeDifference.NEW_NODE;
    } else if (newNode == null) {
      nodeDifference = NodeDifference.REMOVED_NODE;
    } else if (dimensionComparator.compare(originalNode.getDimension(), newNode.getDimension())
        != 0) {
      throw new IllegalArgumentException(
          "Original node and new node are not for the same product dimension");
    } else if (originalNode.isUnit() != newNode.isUnit()) {
      nodeDifference = NodeDifference.PARTITION_TYPE_CHANGE;
    } else if (originalNode.isExcludedUnit() != newNode.isExcludedUnit()) {
      nodeDifference = NodeDifference.EXCLUDED_UNIT_CHANGE;
    } else if (!originalNode.isExcludedUnit() && originalNode.isUnit() && newNode.isUnit()) {
      // Both nodes are non-excluded units - the only possible differences
      // left are from the bid, tracking URL template, or custom parameters.
      nodeDifference = NodeDifference.NONE;
      if (!Objects.equals(originalNode.getBid(), newNode.getBid())) {
        nodeDifference = NodeDifference.BIDDABLE_UNIT_CHANGE;
      }
      if (!Objects.equals(
          originalNode.getTrackingUrlTemplate(), newNode.getTrackingUrlTemplate())) {
        nodeDifference = NodeDifference.BIDDABLE_UNIT_CHANGE;
      }
      if (!Objects.equals(originalNode.getCustomParameters(), newNode.getCustomParameters())) {
        nodeDifference = NodeDifference.BIDDABLE_UNIT_CHANGE;
      }
    } else {
      nodeDifference = NodeDifference.NONE;
    }
    return nodeDifference;
  }