TODO: refactor this code
545964
private void read(SelectionKey key) throws IOException {
        PerfMonMetricGetter getter = null;
        ByteBuffer buf = ByteBuffer.allocateDirect(1024);
        if (key.channel() instanceof SocketChannel) {
            SocketChannel channel = (SocketChannel) key.channel();
            if (channel.read(buf) < 0) {
                log.info("Closing TCP connection");
                channel.close();
                notifyDisonnected();
                return;
            }
            getter = (PerfMonMetricGetter) key.attachment();
        } else if (key.channel() instanceof DatagramChannel) {
            DatagramChannel channel = (DatagramChannel) key.channel();
            SocketAddress remoteAddr = channel.receive(buf);
            if (remoteAddr == null) {
                throw new IOException("Received null datagram");
            }

            synchronized (udpConnections) {
                if (!udpConnections.containsKey(remoteAddr)) {
                    connectUDPClient(remoteAddr, channel, new PerfMonMetricGetter(sigar, this, channel, remoteAddr));
                }
                getter = (PerfMonMetricGetter) udpConnections.get(remoteAddr);
            }
        }

        buf.flip();
        log.debug("Read: " + buf.toString());

        getter.addCommandString(byteBufferToString(buf));
        try {
            while (getter.processNextCommand()) {
                log.debug("Done executing command");
            }
        } catch (Exception e) {
            log.error("Error executing command", e);
        }
    }
95034
function () {
    var pattern = /\{(\d+)\}/g;
    //safer way to convert a pseudo array to an object array
    var args = Array.prototype.slice.call(arguments);
    var s = args.shift();
    return s.replace(pattern, function(c, d) {
      var replacement = args[d] ;
      if (lib.isNull(replacement)) {
        replacement = "";
      }
      return replacement;
    });
  }
1088163
@Override
    public void visitCode(final Code obj) {
        if (sourceLines == null) {
            return;
        }

        if (isAbstract) {
            return;
        }

        if (Values.STATIC_INITIALIZER.equals(methodName) || Values.CONSTRUCTOR.equals(methodName)) {
            return;
        }

        int methodStart = srcLineAnnotation.getStartLine() - 2;
        int methodLine = methodStart;
        String line;
        while ((methodLine >= 0) && (methodLine < sourceLines.length)) {
            line = sourceLines[methodLine];
            if (line.indexOf(methodName) >= 0) {
                break;
            }
            methodLine--;
        }

        if (methodLine < 0) {
            return;
        }

        for (int i = methodLine; i <= methodStart; i++) {
            if ((i < 0) || (i >= sourceLines.length)) {
                return;
            }
            line = sourceLines[i];
            if (line.indexOf("final") >= 0) {
                return;
            }
        }

        changedParms = new BitSet();
        super.visitCode(obj);

        BugInstance bi = null;
        for (int i = 0; i < firstLocalReg; i++) {
            if (changedParms.get(i)) {
                changedParms.clear(i);
                continue;
            }

            String parmName = getRegisterName(obj, i);
            if (bi == null) {
                bi = new BugInstance(this, BugType.FP_FINAL_PARAMETERS.name(), LOW_PRIORITY).addClass(this).addMethod(this).addSourceLine(this, 0);
                bugReporter.reportBug(bi);
            }
            bi.addString(parmName);
        }
        changedParms = null;
    }
802134
function mix(self, ref) {
	if (ref === undefined) return self;
	if ((typeof(ref) != 'object') || (typeof(self) != 'object') || isValueObject(self)) return ref;
	Object.keys(ref).forEach(function(key) { self[key] = mix(self[key], ref[key]) });
	return self;
}
837116
function() {
    var key = Array.prototype.shift.call(arguments);
    if (typeof Modifiers[key] != 'function') return Modifiers.error.call(this, {reason: 'no method', val: key});
    var ob = arguments[0];
    if (Modifiers.mappers[key] instanceof Array && (ob == null || (typeof ob != 'object') || (ob.constructor != Object))) {
      var context = {};
      Array.prototype.forEach.call(arguments, function(v, k) {
        var arg = Modifiers.mappers[key][k];
        if (arg) context[arg] = v;
      });
      return Modifiers[key].bind(context);
    }

    return Modifiers[key].bind(arguments[0] || {});
  }
207710
function refreshModel(o) {
  if (!(o instanceof Model)) {throw new TypeError('Model expected')}
  _.forEach(o.elements(), refreshElement)
}
936971
function handleExtractToVariable() {
        var editor = EditorManager.getActiveEditor();

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_MULTICURSORS);
            return;
        }

        initializeSession(editor);

        var selection = editor.getSelection(),
            doc       = editor.document,
            retObj    = RefactoringUtils.normalizeText(editor.getSelectedText(), editor.indexFromPos(selection.start),
                        editor.indexFromPos(selection.end), true),
            text      = retObj.text,
            start     = retObj.start,
            end       = retObj.end,
            ast,
            scopes,
            expns,
            inlineMenu;

        function callExtractToVariable(startPos, endPos, value) {
            RefactoringUtils.getScopeData(session, editor.posFromIndex(startPos))
                .done(function(expnscope) {
                    scopes = RefactoringUtils.getAllScopes(ast, expnscope, doc.getText());
                    extractToVariable(ast, startPos, endPos, value, scopes);
                }).fail(function() {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
                });
        }

        RefactoringUtils.getScopeData(session, editor.posFromIndex(start)).done(function(scope) {
            ast = RefactoringUtils.getAST(doc.getText());
            scopes = RefactoringUtils.getAllScopes(ast, scope, doc.getText());

            if (editor.hasSelection()) {
                extractToVariable(ast, start, end, text, scopes);
            } else {
                expns = getExpressions(ast, start, end);

                expns.forEach(function(expn, index) {
                    expn.value = doc.getText().substr(expn.start, expn.end - expn.start);
                });

                // Sort expressions by their length
                expns.sort(function(a, b) {
                    return a.value.length - b.value.length;
                });

                if (!expns || !expns.length) {
                    session.editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_VARIABLE_NOT_VALID);
                    return;
                }

                // Filter expns based on length of first surrounding expression
                var firstExpnLength = RefactoringUtils.numLines(expns[0].value);
                expns = expns.filter(function(expn) {
                    return RefactoringUtils.numLines(expn.value) === firstExpnLength;
                });

                // Add name for the expression based on its value
                expns.forEach(function(expn, index) {
                    // If expn name is multi-line, display only first line
                    if (RefactoringUtils.numLines(expn.value) > 1) {
                        expn.name = expn.value.substr(0, expn.value.indexOf("\n")) + "...";
                    } else {
                        expn.name = expn.value;
                    }
                });

                // If only one surround expression, extract
                if (expns.length === 1) {
                    callExtractToVariable(expns[0].start, expns[0].end, expns[0].value);
                    return;
                }

                expns.forEach(function(expn, index) {
                    expn.id = index;
                });

                // UI for extract to variable
                inlineMenu = new InlineMenu(session.editor, Strings.EXTRACTTO_VARIABLE_SELECT_EXPRESSION);

                inlineMenu.onHover(function (expnId) {
                    // Remove the scroll Handlers If already Attached.
                    editor.off("scroll.inlinemenu");
                    // Add a scroll handler If Selection Range is not View.
                    // This is Added for a Bug, where Menu used not to open for the first Time
                    if(!editor.isLineVisible(editor.posFromIndex(expns[expnId].end).line)) {
                        editor.on("scroll.inlinemenu", function() {
                            // Remove the Handlers so that If scroll event is triggerd again by any other operation
                            // Menu should not be reopened.
                            // Menu Should be reopened only if Scroll event is triggered by onHover.
                            editor.off("scroll.inlinemenu");
                            inlineMenu.openRemovedMenu();
                        });
                    }
                    editor.setSelection(editor.posFromIndex(expns[expnId].start), editor.posFromIndex(expns[expnId].end));
                });

                inlineMenu.open(expns);

                inlineMenu.onSelect(function (expnId) {
                    callExtractToVariable(expns[expnId].start, expns[expnId].end, expns[expnId].value);
                    inlineMenu.close();
                });

                inlineMenu.onClose(function () {
                    inlineMenu.close();
                });
            }
        }).fail(function() {
            editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
        });
    }
544560
private void convertTokenDefinitions() throws GrammarException,
	    TreeException {
	tokenVisibility.clear();
	Map<String, ParseTreeNode> helpers = getHelperTokens();
	Map<String, ParseTreeNode> tokens = getTokens();
	convertTokenDefinitions(helpers, tokens);
    }
895870
function refract(value) {
  if (value instanceof Element) {
    return value;
  }

  if (typeof value === 'string') {
    return new StringElement(value);
  }

  if (typeof value === 'number') {
    return new NumberElement(value);
  }

  if (typeof value === 'boolean') {
    return new BooleanElement(value);
  }

  if (value === null) {
    return new NullElement();
  }

  if (Array.isArray(value)) {
    return new ArrayElement(value.map(refract));
  }

  if (typeof value === 'object') {
    const element = new ObjectElement(value);
    return element;
  }

  return value;
}
1001776
function getReferenceExpression ( expression ) {
  	var members = [], refinement;

  	while ( expression.t === MEMBER && expression.r.t === REFINEMENT ) {
  		refinement = expression.r;

  		if ( refinement.x ) {
  			if ( refinement.x.t === REFERENCE ) {
  				members.unshift( refinement.x );
  			} else {
  				members.unshift( flattenExpression( refinement.x ) );
  			}
  		} else {
  			members.unshift( refinement.n );
  		}

  		expression = expression.x;
  	}

  	if ( expression.t !== REFERENCE ) {
  		return null;
  	}

  	return {
  		r: expression.n,
  		m: members
  	};
  }
333559
function makeStrProtoFn(method) {
		return function () {
			// Convert `arguments` into an array (usually empty or has 1 parameter)
			var args = slice.call(arguments, 0);
			// Add the current string as the first argument
			args.unshift(this);
			return ColorHelper[method].apply(ColorHelper, args);
		};
	}
1337226
function (source, data) {
                return source.replace(/\$\{([\w.]+)\}/g, function ($0, $1) {
                    var ref = $1.split('.');
                    var refObject = data;
                    var level;

                    while (refObject != null && (level = ref.shift())) {
                        refObject = refObject[level];
                    }

                    return refObject != null ?  refObject : '';
                });
            }
1132247
function (filter) {
    var obj = {}
    var val = this.__input

    this.each(function (property, key) {
      obj[key] = property.flatten ? property.flatten(filter) : property
    }, wrapFilter(filter))

    if (val !== void 0) {
      if (val instanceof Base) {
        val = {
          reference: val.path
        }
      }
      obj.val = val
    }

    // refactoring non standard keys
    var flattened = flatten(obj)
    for (var key in flattened) {
      if (key.indexOf('.val') > 0) {
        var newKey = key.split('.val')[0]
        flattened[newKey] = flattened[key]
        delete flattened[key]
      }
    }
    return flattened
  }
995174
public void buildReturnCode(MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) {
		if (returnType == TypeName.VOID) {

		} else if (isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode)
				methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise");
			else
				methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise");
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result!=0;\n");
		} else if (isTypeIncludedIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
			methodBuilder.addJavadoc("\n");
			if (updateMode) {
				methodBuilder.addJavadoc("@return number of updated records");
			} else {
				methodBuilder.addJavadoc("@return number of deleted records");
			}
			methodBuilder.addJavadoc("\n");

			methodBuilder.addCode("return result;\n");
		} else {
			// more than one listener found
			throw (new InvalidMethodSignException(method, "invalid return type"));
		}
	}
784620
function () {
        return function () {
          var args = Array.prototype.slice.call(arguments, 0);
          var sig = (function () {
            var ret = [];
            for (var i = 0, len = args.length; i < len; i++) {
              ret.push(toType(args[i]));
            }
            return ret;
          })().join('::');

          if (map[sig]) {
            if (map[sig].inject) args.unshift(input);
            return map[sig].fn.apply(ctx || null, args);
          }

          return input && input.apply(ctx || null, args);
        }
      }
440702
@Override
  protected void remapData(int[][] mapping) throws IOException {
    super.remapData(mapping);
    T1[][] originalFullValueList = fullValueList.clone();
    fullValueList = operations.createMatrix1(mapping.length);
    for (int i = 0; i < mapping.length; i++) {
      for (int j = 0; j < mapping[i].length; j++) {
        if (j == 0) {
          setValue(i, originalFullValueList[mapping[i][j]],
              originalFullValueList[mapping[i][j]].length, false);
        } else {
          setValue(i, originalFullValueList[mapping[i][j]],
              originalFullValueList[mapping[i][j]].length, true);
        }
      }
    }
    fullValueList = newFullValueList;
  }
619592
function()
	{
		if(this._collectionBinder)
		{
			this._collectionBinder.refreshIndexedBinders();
		}
		else
		{
			if(this._modelBindersMap)
			{
				this._modelBindersMap.refreshIndexedBinders();
			}
			if(this.subviews !== null)
			{
				for(var i = 0, l = this.subviews.length; i < l; i++) this.subviews[i].refreshIndexedBinders();
			}
		}
	}