bug_id
stringlengths
5
19
func_before
stringlengths
49
25.9k
func_after
stringlengths
45
26k
Math-27
public double percentageValue() { return multiply(100).doubleValue(); }
public double percentageValue() { return 100 * doubleValue(); }
Closure-36
private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); }
private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } if (convention.getSingletonGetterClassName(callNode) != null) { return false; } } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); }
Jsoup-13
public boolean hasAttr(String attributeKey) { Validate.notNull(attributeKey); return attributes.hasKey(attributeKey); }
public boolean hasAttr(String attributeKey) { Validate.notNull(attributeKey); if (attributeKey.toLowerCase().startsWith("abs:")) { String key = attributeKey.substring("abs:".length()); if (attributes.hasKey(key) && !absUrl(key).equals("")) return true; } return attributes.hasKey(attributeKey); }
Compress-14
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } boolean allNUL = true; for (int i = start; i < end; i++){ if (buffer[i] != 0){ allNUL = false; break; } } if (allNUL) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
JacksonDatabind-83
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String text = p.getValueAsString(); if (text != null) { if (text.length() == 0 || (text = text.trim()).length() == 0) { return _deserializeFromEmptyString(); } Exception cause = null; try { if (_deserialize(text, ctxt) != null) { return _deserialize(text, ctxt); } } catch (IllegalArgumentException iae) { cause = iae; } catch (MalformedURLException me) { cause = me; } String msg = "not a valid textual representation"; if (cause != null) { String m2 = cause.getMessage(); if (m2 != null) { msg = msg + ", problem: "+m2; } } JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg); if (cause != null) { e.initCause(cause); } throw e; } JsonToken t = p.getCurrentToken(); if (t == JsonToken.START_ARRAY) { return _deserializeFromArray(p, ctxt); } if (t == JsonToken.VALUE_EMBEDDED_OBJECT) { Object ob = p.getEmbeddedObject(); if (ob == null) { return null; } if (_valueClass.isAssignableFrom(ob.getClass())) { return (T) ob; } return _deserializeEmbedded(ob, ctxt); } return (T) ctxt.handleUnexpectedToken(_valueClass, p); }
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String text = p.getValueAsString(); if (text != null) { if (text.length() == 0 || (text = text.trim()).length() == 0) { return _deserializeFromEmptyString(); } Exception cause = null; try { return _deserialize(text, ctxt); } catch (IllegalArgumentException iae) { cause = iae; } catch (MalformedURLException me) { cause = me; } String msg = "not a valid textual representation"; if (cause != null) { String m2 = cause.getMessage(); if (m2 != null) { msg = msg + ", problem: "+m2; } } JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg); if (cause != null) { e.initCause(cause); } throw e; } JsonToken t = p.getCurrentToken(); if (t == JsonToken.START_ARRAY) { return _deserializeFromArray(p, ctxt); } if (t == JsonToken.VALUE_EMBEDDED_OBJECT) { Object ob = p.getEmbeddedObject(); if (ob == null) { return null; } if (_valueClass.isAssignableFrom(ob.getClass())) { return (T) ob; } return _deserializeEmbedded(ob, ctxt); } return (T) ctxt.handleUnexpectedToken(_valueClass, p); }
Closure-24
private void findAliases(NodeTraversal t) { Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { Node n = v.getNode(); int type = n.getType(); Node parent = n.getParent(); if (parent.isVar()) { if (n.hasChildren() && n.getFirstChild().isQualifiedName()) { String name = n.getString(); Var aliasVar = scope.getVar(name); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); } else { report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } } }
private void findAliases(NodeTraversal t) { Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { Node n = v.getNode(); int type = n.getType(); Node parent = n.getParent(); if (parent.isVar() && n.hasChildren() && n.getFirstChild().isQualifiedName()) { String name = n.getString(); Var aliasVar = scope.getVar(name); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); } else if (v.isBleedingFunction()) { } else if (parent.getType() == Token.LP) { } else { report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } }
Math-57
private static <T extends Clusterable<T>> List<Cluster<T>> chooseInitialCenters(final Collection<T> points, final int k, final Random random) { final List<T> pointSet = new ArrayList<T>(points); final List<Cluster<T>> resultSet = new ArrayList<Cluster<T>>(); final T firstPoint = pointSet.remove(random.nextInt(pointSet.size())); resultSet.add(new Cluster<T>(firstPoint)); final double[] dx2 = new double[pointSet.size()]; while (resultSet.size() < k) { int sum = 0; for (int i = 0; i < pointSet.size(); i++) { final T p = pointSet.get(i); final Cluster<T> nearest = getNearestCluster(resultSet, p); final double d = p.distanceFrom(nearest.getCenter()); sum += d * d; dx2[i] = sum; } final double r = random.nextDouble() * sum; for (int i = 0 ; i < dx2.length; i++) { if (dx2[i] >= r) { final T p = pointSet.remove(i); resultSet.add(new Cluster<T>(p)); break; } } } return resultSet; }
private static <T extends Clusterable<T>> List<Cluster<T>> chooseInitialCenters(final Collection<T> points, final int k, final Random random) { final List<T> pointSet = new ArrayList<T>(points); final List<Cluster<T>> resultSet = new ArrayList<Cluster<T>>(); final T firstPoint = pointSet.remove(random.nextInt(pointSet.size())); resultSet.add(new Cluster<T>(firstPoint)); final double[] dx2 = new double[pointSet.size()]; while (resultSet.size() < k) { double sum = 0; for (int i = 0; i < pointSet.size(); i++) { final T p = pointSet.get(i); final Cluster<T> nearest = getNearestCluster(resultSet, p); final double d = p.distanceFrom(nearest.getCenter()); sum += d * d; dx2[i] = sum; } final double r = random.nextDouble() * sum; for (int i = 0 ; i < dx2.length; i++) { if (dx2[i] >= r) { final T p = pointSet.remove(i); resultSet.add(new Cluster<T>(p)); break; } } } return resultSet; }
Closure-57
private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null) { className = target.getString(); } } } } return className; }
private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null && target.getType() == Token.STRING) { className = target.getString(); } } } } return className; }
Jsoup-1
private void normalise(Element element) { List<Node> toMove = new ArrayList<Node>(); for (Node node: element.childNodes) { if (node instanceof TextNode) { TextNode tn = (TextNode) node; if (!tn.isBlank()) toMove.add(tn); } } for (Node node: toMove) { element.removeChild(node); body().appendChild(new TextNode(" ", "")); body().appendChild(node); } }
private void normalise(Element element) { List<Node> toMove = new ArrayList<Node>(); for (Node node: element.childNodes) { if (node instanceof TextNode) { TextNode tn = (TextNode) node; if (!tn.isBlank()) toMove.add(tn); } } for (Node node: toMove) { element.removeChild(node); body().prependChild(node); body().prependChild(new TextNode(" ", "")); } }
Math-32
protected void computeGeometricalProperties() { final Vector2D[][] v = getVertices(); if (v.length == 0) { final BSPTree<Euclidean2D> tree = getTree(false); if ((Boolean) tree.getAttribute()) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { setSize(0); setBarycenter(new Vector2D(0, 0)); } } else if (v[0][0] == null) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { double sum = 0; double sumX = 0; double sumY = 0; for (Vector2D[] loop : v) { double x1 = loop[loop.length - 1].getX(); double y1 = loop[loop.length - 1].getY(); for (final Vector2D point : loop) { final double x0 = x1; final double y0 = y1; x1 = point.getX(); y1 = point.getY(); final double factor = x0 * y1 - y0 * x1; sum += factor; sumX += factor * (x0 + x1); sumY += factor * (y0 + y1); } } if (sum < 0) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { setSize(sum / 2); setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum))); } } }
protected void computeGeometricalProperties() { final Vector2D[][] v = getVertices(); if (v.length == 0) { final BSPTree<Euclidean2D> tree = getTree(false); if (tree.getCut() == null && (Boolean) tree.getAttribute()) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { setSize(0); setBarycenter(new Vector2D(0, 0)); } } else if (v[0][0] == null) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { double sum = 0; double sumX = 0; double sumY = 0; for (Vector2D[] loop : v) { double x1 = loop[loop.length - 1].getX(); double y1 = loop[loop.length - 1].getY(); for (final Vector2D point : loop) { final double x0 = x1; final double y0 = y1; x1 = point.getX(); y1 = point.getY(); final double factor = x0 * y1 - y0 * x1; sum += factor; sumX += factor * (x0 + x1); sumY += factor * (y0 + y1); } } if (sum < 0) { setSize(Double.POSITIVE_INFINITY); setBarycenter(Vector2D.NaN); } else { setSize(sum / 2); setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum))); } } }
Math-72
public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifySequence(min, initial, max); double yInitial = f.value(initial); if (Math.abs(yInitial) <= functionValueAccuracy) { setResult(initial, 0); return result; } double yMin = f.value(min); if (Math.abs(yMin) <= functionValueAccuracy) { setResult(yMin, 0); return result; } if (yInitial * yMin < 0) { return solve(f, min, yMin, initial, yInitial, min, yMin); } double yMax = f.value(max); if (Math.abs(yMax) <= functionValueAccuracy) { setResult(yMax, 0); return result; } if (yInitial * yMax < 0) { return solve(f, initial, yInitial, max, yMax, initial, yInitial); } if (yMin * yMax > 0) { throw MathRuntimeException.createIllegalArgumentException( NON_BRACKETING_MESSAGE, min, max, yMin, yMax); } return solve(f, min, yMin, max, yMax, initial, yInitial); }
public double solve(final UnivariateRealFunction f, final double min, final double max, final double initial) throws MaxIterationsExceededException, FunctionEvaluationException { clearResult(); verifySequence(min, initial, max); double yInitial = f.value(initial); if (Math.abs(yInitial) <= functionValueAccuracy) { setResult(initial, 0); return result; } double yMin = f.value(min); if (Math.abs(yMin) <= functionValueAccuracy) { setResult(min, 0); return result; } if (yInitial * yMin < 0) { return solve(f, min, yMin, initial, yInitial, min, yMin); } double yMax = f.value(max); if (Math.abs(yMax) <= functionValueAccuracy) { setResult(max, 0); return result; } if (yInitial * yMax < 0) { return solve(f, initial, yInitial, max, yMax, initial, yInitial); } if (yMin * yMax > 0) { throw MathRuntimeException.createIllegalArgumentException( NON_BRACKETING_MESSAGE, min, max, yMin, yMax); } return solve(f, min, yMin, max, yMax, initial, yInitial); }
JacksonCore-6
private final static int _parseIndex(String str) { final int len = str.length(); if (len == 0 || len > 10) { return -1; } for (int i = 0; i < len; ++i) { char c = str.charAt(i); if (c > '9' || c < '0') { return -1; } } if (len == 10) { long l = NumberInput.parseLong(str); if (l > Integer.MAX_VALUE) { return -1; } } return NumberInput.parseInt(str); }
private final static int _parseIndex(String str) { final int len = str.length(); if (len == 0 || len > 10) { return -1; } char c = str.charAt(0); if (c <= '0') { return (len == 1 && c == '0') ? 0 : -1; } if (c > '9') { return -1; } for (int i = 1; i < len; ++i) { c = str.charAt(i); if (c > '9' || c < '0') { return -1; } } if (len == 10) { long l = NumberInput.parseLong(str); if (l > Integer.MAX_VALUE) { return -1; } } return NumberInput.parseInt(str); }
Closure-172
private boolean isQualifiedNameInferred( String qName, Node n, JSDocInfo info, Node rhsValue, JSType valueType) { if (valueType == null) { return true; } if (qName != null && qName.endsWith(".prototype")) { return false; } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (isConstantSymbol(info, n) && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { if (info != null) { return false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { for (Node current = n.getParent(); !(current.isScript() || current.isFunction()); current = current.getParent()) { if (NodeUtil.isControlStructure(current)) { return true; } } AstFunctionContents contents = getFunctionAnalysisResults(scope.getRootNode()); if (contents == null || !contents.getEscapedQualifiedNames().contains(qName)) { return false; } } } return inferred; }
private boolean isQualifiedNameInferred( String qName, Node n, JSDocInfo info, Node rhsValue, JSType valueType) { if (valueType == null) { return true; } if (qName != null && qName.endsWith(".prototype")) { String className = qName.substring(0, qName.lastIndexOf(".prototype")); Var slot = scope.getSlot(className); JSType classType = slot == null ? null : slot.getType(); if (classType != null && (classType.isConstructor() || classType.isInterface())) { return false; } } boolean inferred = true; if (info != null) { inferred = !(info.hasType() || info.hasEnumParameterType() || (isConstantSymbol(info, n) && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { if (info != null) { return false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { for (Node current = n.getParent(); !(current.isScript() || current.isFunction()); current = current.getParent()) { if (NodeUtil.isControlStructure(current)) { return true; } } AstFunctionContents contents = getFunctionAnalysisResults(scope.getRootNode()); if (contents == null || !contents.getEscapedQualifiedNames().contains(qName)) { return false; } } } return inferred; }
Closure-150
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (n == scope.getRootNode()) return; if (n.getType() == Token.LP && parent == scope.getRootNode()) { handleFunctionInputs(parent); return; } attachLiteralTypes(n); switch (n.getType()) { case Token.FUNCTION: if (parent.getType() == Token.NAME) { return; } defineDeclaredFunction(n, parent); break; case Token.CATCH: defineCatch(n, parent); break; case Token.VAR: defineVar(n, parent); break; } }
@Override public void visit(NodeTraversal t, Node n, Node parent) { if (n == scope.getRootNode()) return; if (n.getType() == Token.LP && parent == scope.getRootNode()) { handleFunctionInputs(parent); return; } super.visit(t, n, parent); }
Jsoup-45
void resetInsertionMode() { boolean last = false; for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (pos == 0) { last = true; node = contextElement; } String name = node.nodeName(); if ("select".equals(name)) { transition(HtmlTreeBuilderState.InSelect); break; } else if (("td".equals(name) || "td".equals(name) && !last)) { transition(HtmlTreeBuilderState.InCell); break; } else if ("tr".equals(name)) { transition(HtmlTreeBuilderState.InRow); break; } else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) { transition(HtmlTreeBuilderState.InTableBody); break; } else if ("caption".equals(name)) { transition(HtmlTreeBuilderState.InCaption); break; } else if ("colgroup".equals(name)) { transition(HtmlTreeBuilderState.InColumnGroup); break; } else if ("table".equals(name)) { transition(HtmlTreeBuilderState.InTable); break; } else if ("head".equals(name)) { transition(HtmlTreeBuilderState.InBody); break; } else if ("body".equals(name)) { transition(HtmlTreeBuilderState.InBody); break; } else if ("frameset".equals(name)) { transition(HtmlTreeBuilderState.InFrameset); break; } else if ("html".equals(name)) { transition(HtmlTreeBuilderState.BeforeHead); break; } else if (last) { transition(HtmlTreeBuilderState.InBody); break; } } }
void resetInsertionMode() { boolean last = false; for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (pos == 0) { last = true; node = contextElement; } String name = node.nodeName(); if ("select".equals(name)) { transition(HtmlTreeBuilderState.InSelect); break; } else if (("td".equals(name) || "th".equals(name) && !last)) { transition(HtmlTreeBuilderState.InCell); break; } else if ("tr".equals(name)) { transition(HtmlTreeBuilderState.InRow); break; } else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) { transition(HtmlTreeBuilderState.InTableBody); break; } else if ("caption".equals(name)) { transition(HtmlTreeBuilderState.InCaption); break; } else if ("colgroup".equals(name)) { transition(HtmlTreeBuilderState.InColumnGroup); break; } else if ("table".equals(name)) { transition(HtmlTreeBuilderState.InTable); break; } else if ("head".equals(name)) { transition(HtmlTreeBuilderState.InBody); break; } else if ("body".equals(name)) { transition(HtmlTreeBuilderState.InBody); break; } else if ("frameset".equals(name)) { transition(HtmlTreeBuilderState.InFrameset); break; } else if ("html".equals(name)) { transition(HtmlTreeBuilderState.BeforeHead); break; } else if (last) { transition(HtmlTreeBuilderState.InBody); break; } } }
Compress-40
public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count) { final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsCached |= (nextByte << bitsCachedSize); } else { bitsCached <<= 8; bitsCached |= nextByte; } bitsCachedSize += 8; } final long bitsOut; if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsOut = (bitsCached & MASKS[count]); bitsCached >>>= count; } else { bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count]; } bitsCachedSize -= count; return bitsOut; }
public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count && bitsCachedSize < 57) { final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsCached |= (nextByte << bitsCachedSize); } else { bitsCached <<= 8; bitsCached |= nextByte; } bitsCachedSize += 8; } int overflowBits = 0; long overflow = 0l; if (bitsCachedSize < count) { int bitsToAddCount = count - bitsCachedSize; overflowBits = 8 - bitsToAddCount; final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { long bitsToAdd = nextByte & MASKS[bitsToAddCount]; bitsCached |= (bitsToAdd << bitsCachedSize); overflow = (nextByte >>> bitsToAddCount) & MASKS[overflowBits]; } else { bitsCached <<= bitsToAddCount; long bitsToAdd = (nextByte >>> (overflowBits)) & MASKS[bitsToAddCount]; bitsCached |= bitsToAdd; overflow = nextByte & MASKS[overflowBits]; } bitsCachedSize = count; } final long bitsOut; if (overflowBits == 0) { if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsOut = (bitsCached & MASKS[count]); bitsCached >>>= count; } else { bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count]; } bitsCachedSize -= count; } else { bitsOut = bitsCached & MASKS[count]; bitsCached = overflow; bitsCachedSize = overflowBits; } return bitsOut; }
JacksonDatabind-39
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { p.skipChildren(); return null; }
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { if (p.hasToken(JsonToken.FIELD_NAME)) { while (true) { JsonToken t = p.nextToken(); if ((t == null) || (t == JsonToken.END_OBJECT)) { break; } p.skipChildren(); } } else { p.skipChildren(); } return null; }
Closure-117
String getReadableJSTypeName(Node n, boolean dereference) { if (n.isGetProp()) { ObjectType objectType = getJSType(n.getFirstChild()).dereference(); if (objectType != null) { String propName = n.getLastChild().getString(); if (objectType.getConstructor() != null && objectType.getConstructor().isInterface()) { objectType = FunctionType.getTopDefiningInterface( objectType, propName); } else { while (objectType != null && !objectType.hasOwnProperty(propName)) { objectType = objectType.getImplicitPrototype(); } } if (objectType != null && (objectType.getConstructor() != null || objectType.isFunctionPrototypeType())) { return objectType.toString() + "." + propName; } } } JSType type = getJSType(n); if (dereference) { ObjectType dereferenced = type.dereference(); if (dereferenced != null) { type = dereferenced; } } if (type.isFunctionPrototypeType() || (type.toObjectType() != null && type.toObjectType().getConstructor() != null)) { return type.toString(); } String qualifiedName = n.getQualifiedName(); if (qualifiedName != null) { return qualifiedName; } else if (type.isFunctionType()) { return "function"; } else { return type.toString(); } }
String getReadableJSTypeName(Node n, boolean dereference) { JSType type = getJSType(n); if (dereference) { ObjectType dereferenced = type.dereference(); if (dereferenced != null) { type = dereferenced; } } if (type.isFunctionPrototypeType() || (type.toObjectType() != null && type.toObjectType().getConstructor() != null)) { return type.toString(); } if (n.isGetProp()) { ObjectType objectType = getJSType(n.getFirstChild()).dereference(); if (objectType != null) { String propName = n.getLastChild().getString(); if (objectType.getConstructor() != null && objectType.getConstructor().isInterface()) { objectType = FunctionType.getTopDefiningInterface( objectType, propName); } else { while (objectType != null && !objectType.hasOwnProperty(propName)) { objectType = objectType.getImplicitPrototype(); } } if (objectType != null && (objectType.getConstructor() != null || objectType.isFunctionPrototypeType())) { return objectType.toString() + "." + propName; } } } String qualifiedName = n.getQualifiedName(); if (qualifiedName != null) { return qualifiedName; } else if (type.isFunctionType()) { return "function"; } else { return type.toString(); } }
Closure-130
private void inlineAliases(GlobalNamespace namespace) { Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest()); while (!workList.isEmpty()) { Name name = workList.pop(); if (name.type == Name.Type.GET || name.type == Name.Type.SET) { continue; } if (name.globalSets == 1 && name.localSets == 0 && name.aliasingGets > 0) { List<Ref> refs = Lists.newArrayList(name.getRefs()); for (Ref ref : refs) { if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) { if (inlineAliasIfPossible(ref, namespace)) { name.removeRef(ref); } } } } if ((name.type == Name.Type.OBJECTLIT || name.type == Name.Type.FUNCTION) && name.aliasingGets == 0 && name.props != null) { workList.addAll(name.props); } } }
private void inlineAliases(GlobalNamespace namespace) { Deque<Name> workList = new ArrayDeque<Name>(namespace.getNameForest()); while (!workList.isEmpty()) { Name name = workList.pop(); if (name.type == Name.Type.GET || name.type == Name.Type.SET) { continue; } if (!name.inExterns && name.globalSets == 1 && name.localSets == 0 && name.aliasingGets > 0) { List<Ref> refs = Lists.newArrayList(name.getRefs()); for (Ref ref : refs) { if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) { if (inlineAliasIfPossible(ref, namespace)) { name.removeRef(ref); } } } } if ((name.type == Name.Type.OBJECTLIT || name.type == Name.Type.FUNCTION) && name.aliasingGets == 0 && name.props != null) { workList.addAll(name.props); } } }
Gson-5
public static Date parse(String date, ParsePosition pos) throws ParseException { Exception fail = null; try { int offset = pos.getIndex(); int year = parseInt(date, offset, offset += 4); if (checkOffset(date, offset, '-')) { offset += 1; } int month = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, '-')) { offset += 1; } int day = parseInt(date, offset, offset += 2); int hour = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; boolean hasT = checkOffset(date, offset, 'T'); if (!hasT && (date.length() <= offset)) { Calendar calendar = new GregorianCalendar(year, month - 1, day); pos.setIndex(offset); return calendar.getTime(); } if (hasT) { hour = parseInt(date, offset += 1, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } minutes = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } if (date.length() > offset) { char c = date.charAt(offset); if (c != 'Z' && c != '+' && c != '-') { seconds = parseInt(date, offset, offset += 2); if (seconds > 59 && seconds < 63) seconds = 59; if (checkOffset(date, offset, '.')) { offset += 1; int endOffset = indexOfNonDigit(date, offset + 1); int parseEndOffset = Math.min(endOffset, offset + 3); int fraction = parseInt(date, offset, parseEndOffset); switch (parseEndOffset - offset) { case 2: milliseconds = fraction * 10; break; case 1: milliseconds = fraction * 100; break; default: milliseconds = fraction; } offset = endOffset; } } } } if (date.length() <= offset) { throw new IllegalArgumentException("No time zone indicator"); } TimeZone timezone = null; char timezoneIndicator = date.charAt(offset); if (timezoneIndicator == 'Z') { timezone = TIMEZONE_UTC; offset += 1; } else if (timezoneIndicator == '+' || timezoneIndicator == '-') { String timezoneOffset = date.substring(offset); offset += timezoneOffset.length(); if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) { timezone = TIMEZONE_UTC; } else { String timezoneId = "GMT" + timezoneOffset; timezone = TimeZone.getTimeZone(timezoneId); String act = timezone.getID(); if (!act.equals(timezoneId)) { String cleaned = act.replace(":", ""); if (!cleaned.equals(timezoneId)) { throw new IndexOutOfBoundsException("Mismatching time zone indicator: "+timezoneId+" given, resolves to " +timezone.getID()); } } } } else { throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator+"'"); } Calendar calendar = new GregorianCalendar(timezone); calendar.setLenient(false); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, milliseconds); pos.setIndex(offset); return calendar.getTime(); } catch (IndexOutOfBoundsException e) { fail = e; } catch (NumberFormatException e) { fail = e; } catch (IllegalArgumentException e) { fail = e; } String input = (date == null) ? null : ('"' + date + "'"); String msg = fail.getMessage(); if (msg == null || msg.isEmpty()) { msg = "("+fail.getClass().getName()+")"; } ParseException ex = new ParseException("Failed to parse date [" + input + "]: " + msg, pos.getIndex()); ex.initCause(fail); throw ex; }
public static Date parse(String date, ParsePosition pos) throws ParseException { Exception fail = null; try { int offset = pos.getIndex(); int year = parseInt(date, offset, offset += 4); if (checkOffset(date, offset, '-')) { offset += 1; } int month = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, '-')) { offset += 1; } int day = parseInt(date, offset, offset += 2); int hour = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; boolean hasT = checkOffset(date, offset, 'T'); if (!hasT && (date.length() <= offset)) { Calendar calendar = new GregorianCalendar(year, month - 1, day); pos.setIndex(offset); return calendar.getTime(); } if (hasT) { hour = parseInt(date, offset += 1, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } minutes = parseInt(date, offset, offset += 2); if (checkOffset(date, offset, ':')) { offset += 1; } if (date.length() > offset) { char c = date.charAt(offset); if (c != 'Z' && c != '+' && c != '-') { seconds = parseInt(date, offset, offset += 2); if (seconds > 59 && seconds < 63) seconds = 59; if (checkOffset(date, offset, '.')) { offset += 1; int endOffset = indexOfNonDigit(date, offset + 1); int parseEndOffset = Math.min(endOffset, offset + 3); int fraction = parseInt(date, offset, parseEndOffset); switch (parseEndOffset - offset) { case 2: milliseconds = fraction * 10; break; case 1: milliseconds = fraction * 100; break; default: milliseconds = fraction; } offset = endOffset; } } } } if (date.length() <= offset) { throw new IllegalArgumentException("No time zone indicator"); } TimeZone timezone = null; char timezoneIndicator = date.charAt(offset); if (timezoneIndicator == 'Z') { timezone = TIMEZONE_UTC; offset += 1; } else if (timezoneIndicator == '+' || timezoneIndicator == '-') { String timezoneOffset = date.substring(offset); timezoneOffset = timezoneOffset.length() >= 5 ? timezoneOffset : timezoneOffset + "00"; offset += timezoneOffset.length(); if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) { timezone = TIMEZONE_UTC; } else { String timezoneId = "GMT" + timezoneOffset; timezone = TimeZone.getTimeZone(timezoneId); String act = timezone.getID(); if (!act.equals(timezoneId)) { String cleaned = act.replace(":", ""); if (!cleaned.equals(timezoneId)) { throw new IndexOutOfBoundsException("Mismatching time zone indicator: "+timezoneId+" given, resolves to " +timezone.getID()); } } } } else { throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator+"'"); } Calendar calendar = new GregorianCalendar(timezone); calendar.setLenient(false); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, seconds); calendar.set(Calendar.MILLISECOND, milliseconds); pos.setIndex(offset); return calendar.getTime(); } catch (IndexOutOfBoundsException e) { fail = e; } catch (NumberFormatException e) { fail = e; } catch (IllegalArgumentException e) { fail = e; } String input = (date == null) ? null : ('"' + date + "'"); String msg = fail.getMessage(); if (msg == null || msg.isEmpty()) { msg = "("+fail.getClass().getName()+")"; } ParseException ex = new ParseException("Failed to parse date [" + input + "]: " + msg, pos.getIndex()); ex.initCause(fail); throw ex; }
Closure-131
public static boolean isJSIdentifier(String s) { int length = s.length(); if (length == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < length; i++) { if ( !Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; }
public static boolean isJSIdentifier(String s) { int length = s.length(); if (length == 0 || Character.isIdentifierIgnorable(s.charAt(0)) || !Character.isJavaIdentifierStart(s.charAt(0))) { return false; } for (int i = 1; i < length; i++) { if (Character.isIdentifierIgnorable(s.charAt(i)) || !Character.isJavaIdentifierPart(s.charAt(i))) { return false; } } return true; }
Closure-95
void defineSlot(Node n, Node parent, JSType type, boolean inferred) { Preconditions.checkArgument(inferred || type != null); boolean shouldDeclareOnGlobalThis = false; if (n.getType() == Token.NAME) { Preconditions.checkArgument( parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR || parent.getType() == Token.LP || parent.getType() == Token.CATCH); shouldDeclareOnGlobalThis = scope.isGlobal() && (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION); } else { Preconditions.checkArgument( n.getType() == Token.GETPROP && (parent.getType() == Token.ASSIGN || parent.getType() == Token.EXPR_RESULT)); } String variableName = n.getQualifiedName(); Preconditions.checkArgument(!variableName.isEmpty()); Scope scopeToDeclareIn = scope; if (scopeToDeclareIn.isDeclared(variableName, false)) { Var oldVar = scopeToDeclareIn.getVar(variableName); validator.expectUndeclaredVariable( sourceName, n, parent, oldVar, variableName, type); } else { if (!inferred) { setDeferredType(n, type); } CompilerInput input = compiler.getInput(sourceName); scopeToDeclareIn.declare(variableName, n, type, input, inferred); if (shouldDeclareOnGlobalThis) { ObjectType globalThis = typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS); boolean isExtern = input.isExtern(); if (inferred) { globalThis.defineInferredProperty(variableName, type == null ? getNativeType(JSTypeNative.NO_TYPE) : type, isExtern); } else { globalThis.defineDeclaredProperty(variableName, type, isExtern); } } if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; if (fnType.isConstructor() || fnType.isInterface()) { FunctionType superClassCtor = fnType.getSuperClassConstructor(); scopeToDeclareIn.declare(variableName + ".prototype", n, fnType.getPrototype(), compiler.getInput(sourceName), superClassCtor == null || superClassCtor.getInstanceType().equals( getNativeType(OBJECT_TYPE))); } } } }
void defineSlot(Node n, Node parent, JSType type, boolean inferred) { Preconditions.checkArgument(inferred || type != null); boolean shouldDeclareOnGlobalThis = false; if (n.getType() == Token.NAME) { Preconditions.checkArgument( parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR || parent.getType() == Token.LP || parent.getType() == Token.CATCH); shouldDeclareOnGlobalThis = scope.isGlobal() && (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION); } else { Preconditions.checkArgument( n.getType() == Token.GETPROP && (parent.getType() == Token.ASSIGN || parent.getType() == Token.EXPR_RESULT)); } String variableName = n.getQualifiedName(); Preconditions.checkArgument(!variableName.isEmpty()); Scope scopeToDeclareIn = scope; if (n.getType() == Token.GETPROP && !scope.isGlobal() && isQnameRootedInGlobalScope(n)) { Scope globalScope = scope.getGlobalScope(); if (!globalScope.isDeclared(variableName, false)) { scopeToDeclareIn = scope.getGlobalScope(); } } if (scopeToDeclareIn.isDeclared(variableName, false)) { Var oldVar = scopeToDeclareIn.getVar(variableName); validator.expectUndeclaredVariable( sourceName, n, parent, oldVar, variableName, type); } else { if (!inferred) { setDeferredType(n, type); } CompilerInput input = compiler.getInput(sourceName); scopeToDeclareIn.declare(variableName, n, type, input, inferred); if (shouldDeclareOnGlobalThis) { ObjectType globalThis = typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS); boolean isExtern = input.isExtern(); if (inferred) { globalThis.defineInferredProperty(variableName, type == null ? getNativeType(JSTypeNative.NO_TYPE) : type, isExtern); } else { globalThis.defineDeclaredProperty(variableName, type, isExtern); } } if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; if (fnType.isConstructor() || fnType.isInterface()) { FunctionType superClassCtor = fnType.getSuperClassConstructor(); scopeToDeclareIn.declare(variableName + ".prototype", n, fnType.getPrototype(), compiler.getInput(sourceName), superClassCtor == null || superClassCtor.getInstanceType().equals( getNativeType(OBJECT_TYPE))); } } } }
Closure-78
private Node performArithmeticOp(int opType, Node left, Node right) { if (opType == Token.ADD && (NodeUtil.mayBeString(left, false) || NodeUtil.mayBeString(right, false))) { return null; } double result; Double lValObj = NodeUtil.getNumberValue(left); if (lValObj == null) { return null; } Double rValObj = NodeUtil.getNumberValue(right); if (rValObj == null) { return null; } double lval = lValObj; double rval = rValObj; switch (opType) { case Token.BITAND: result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval); break; case Token.BITOR: result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval); break; case Token.BITXOR: result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval); break; case Token.ADD: result = lval + rval; break; case Token.SUB: result = lval - rval; break; case Token.MUL: result = lval * rval; break; case Token.MOD: if (rval == 0) { error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right); return null; } result = lval % rval; break; case Token.DIV: if (rval == 0) { error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right); return null; } result = lval / rval; break; default: throw new Error("Unexpected arithmetic operator"); } if (String.valueOf(result).length() <= String.valueOf(lval).length() + String.valueOf(rval).length() + 1 && Math.abs(result) <= MAX_FOLD_NUMBER) { Node newNumber = Node.newNumber(result); return newNumber; } else if (Double.isNaN(result)) { return Node.newString(Token.NAME, "NaN"); } else if (result == Double.POSITIVE_INFINITY) { return Node.newString(Token.NAME, "Infinity"); } else if (result == Double.NEGATIVE_INFINITY) { return new Node(Token.NEG, Node.newString(Token.NAME, "Infinity")); } return null; }
private Node performArithmeticOp(int opType, Node left, Node right) { if (opType == Token.ADD && (NodeUtil.mayBeString(left, false) || NodeUtil.mayBeString(right, false))) { return null; } double result; Double lValObj = NodeUtil.getNumberValue(left); if (lValObj == null) { return null; } Double rValObj = NodeUtil.getNumberValue(right); if (rValObj == null) { return null; } double lval = lValObj; double rval = rValObj; switch (opType) { case Token.BITAND: result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval); break; case Token.BITOR: result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval); break; case Token.BITXOR: result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval); break; case Token.ADD: result = lval + rval; break; case Token.SUB: result = lval - rval; break; case Token.MUL: result = lval * rval; break; case Token.MOD: if (rval == 0) { return null; } result = lval % rval; break; case Token.DIV: if (rval == 0) { return null; } result = lval / rval; break; default: throw new Error("Unexpected arithmetic operator"); } if (String.valueOf(result).length() <= String.valueOf(lval).length() + String.valueOf(rval).length() + 1 && Math.abs(result) <= MAX_FOLD_NUMBER) { Node newNumber = Node.newNumber(result); return newNumber; } else if (Double.isNaN(result)) { return Node.newString(Token.NAME, "NaN"); } else if (result == Double.POSITIVE_INFINITY) { return Node.newString(Token.NAME, "Infinity"); } else if (result == Double.NEGATIVE_INFINITY) { return new Node(Token.NEG, Node.newString(Token.NAME, "Infinity")); } return null; }
JacksonDatabind-27
protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt) throws IOException { final ExternalTypeHandler ext = _externalTypeIdHandler.start(); final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader); TokenBuffer tokens = new TokenBuffer(p); tokens.writeStartObject(); JsonToken t = p.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) { String propName = p.getCurrentName(); p.nextToken(); SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { if (ext.handlePropertyValue(p, ctxt, propName, buffer)) { ; } else { if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) { t = p.nextToken(); Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; } while (t == JsonToken.FIELD_NAME) { p.nextToken(); tokens.copyCurrentStructure(p); t = p.nextToken(); } if (bean.getClass() != _beanType.getRawClass()) { throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values"); } return ext.complete(p, ctxt, bean); } } continue; } if (buffer.readIdProperty(propName)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(p, ctxt)); continue; } if (ext.handlePropertyValue(p, ctxt, propName, null)) { continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt)); } } try { return ext.complete(p, ctxt, buffer, creator); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; } }
protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt) throws IOException { final ExternalTypeHandler ext = _externalTypeIdHandler.start(); final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader); TokenBuffer tokens = new TokenBuffer(p); tokens.writeStartObject(); JsonToken t = p.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) { String propName = p.getCurrentName(); p.nextToken(); SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { if (ext.handlePropertyValue(p, ctxt, propName, null)) { ; } else { if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) { t = p.nextToken(); Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; } while (t == JsonToken.FIELD_NAME) { p.nextToken(); tokens.copyCurrentStructure(p); t = p.nextToken(); } if (bean.getClass() != _beanType.getRawClass()) { throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values"); } return ext.complete(p, ctxt, bean); } } continue; } if (buffer.readIdProperty(propName)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(p, ctxt)); continue; } if (ext.handlePropertyValue(p, ctxt, propName, null)) { continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt)); } } try { return ext.complete(p, ctxt, buffer, creator); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; } }
Math-31
public double evaluate(double x, double epsilon, int maxIterations) { final double small = 1e-50; double hPrev = getA(0, x); if (Precision.equals(hPrev, 0.0, small)) { hPrev = small; } int n = 1; double dPrev = 0.0; double p0 = 1.0; double q1 = 1.0; double cPrev = hPrev; double hN = hPrev; while (n < maxIterations) { final double a = getA(n, x); final double b = getB(n, x); double cN = a * hPrev + b * p0; double q2 = a * q1 + b * dPrev; if (Double.isInfinite(cN) || Double.isInfinite(q2)) { double scaleFactor = 1d; double lastScaleFactor = 1d; final int maxPower = 5; final double scale = FastMath.max(a,b); if (scale <= 0) { throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x); } for (int i = 0; i < maxPower; i++) { lastScaleFactor = scaleFactor; scaleFactor *= scale; if (a != 0.0 && a > b) { cN = hPrev / lastScaleFactor + (b / scaleFactor * p0); q2 = q1 / lastScaleFactor + (b / scaleFactor * dPrev); } else if (b != 0) { cN = (a / scaleFactor * hPrev) + p0 / lastScaleFactor; q2 = (a / scaleFactor * q1) + dPrev / lastScaleFactor; } if (!(Double.isInfinite(cN) || Double.isInfinite(q2))) { break; } } } final double deltaN = cN / q2 / cPrev; hN = cPrev * deltaN; if (Double.isInfinite(hN)) { throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x); } if (Double.isNaN(hN)) { throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE, x); } if (FastMath.abs(deltaN - 1.0) < epsilon) { break; } dPrev = q1; cPrev = cN / q2; p0 = hPrev; hPrev = cN; q1 = q2; n++; } if (n >= maxIterations) { throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION, maxIterations, x); } return hN; }
public double evaluate(double x, double epsilon, int maxIterations) { final double small = 1e-50; double hPrev = getA(0, x); if (Precision.equals(hPrev, 0.0, small)) { hPrev = small; } int n = 1; double dPrev = 0.0; double cPrev = hPrev; double hN = hPrev; while (n < maxIterations) { final double a = getA(n, x); final double b = getB(n, x); double dN = a + b * dPrev; if (Precision.equals(dN, 0.0, small)) { dN = small; } double cN = a + b / cPrev; if (Precision.equals(cN, 0.0, small)) { cN = small; } dN = 1 / dN; final double deltaN = cN * dN; hN = hPrev * deltaN; if (Double.isInfinite(hN)) { throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x); } if (Double.isNaN(hN)) { throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE, x); } if (FastMath.abs(deltaN - 1.0) < epsilon) { break; } dPrev = dN; cPrev = cN; hPrev = hN; n++; } if (n >= maxIterations) { throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION, maxIterations, x); } return hN; }
Chart-13
protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { double[] w = new double[5]; double[] h = new double[5]; w[0] = constraint.getWidth(); if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight()), LengthConstraintType.RANGE); Size2D size = this.topBlock.arrange(g2, c1); h[0] = size.height; } w[1] = w[0]; if (this.bottomBlock != null) { RectangleConstraint c2 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight() - h[0]), LengthConstraintType.RANGE); Size2D size = this.bottomBlock.arrange(g2, c2); h[1] = size.height; } h[2] = constraint.getHeight() - h[1] - h[0]; if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth()), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; } h[3] = h[2]; if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth() - w[2]), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; } h[4] = h[2]; w[4] = constraint.getWidth() - w[3] - w[2]; RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]); if (this.centerBlock != null) { this.centerBlock.arrange(g2, c5); } if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0], h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2], w[1], h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4], h[4])); } return new Size2D(constraint.getWidth(), constraint.getHeight()); }
protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint) { double[] w = new double[5]; double[] h = new double[5]; w[0] = constraint.getWidth(); if (this.topBlock != null) { RectangleConstraint c1 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight()), LengthConstraintType.RANGE); Size2D size = this.topBlock.arrange(g2, c1); h[0] = size.height; } w[1] = w[0]; if (this.bottomBlock != null) { RectangleConstraint c2 = new RectangleConstraint(w[0], null, LengthConstraintType.FIXED, 0.0, new Range(0.0, constraint.getHeight() - h[0]), LengthConstraintType.RANGE); Size2D size = this.bottomBlock.arrange(g2, c2); h[1] = size.height; } h[2] = constraint.getHeight() - h[1] - h[0]; if (this.leftBlock != null) { RectangleConstraint c3 = new RectangleConstraint(0.0, new Range(0.0, constraint.getWidth()), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.leftBlock.arrange(g2, c3); w[2] = size.width; } h[3] = h[2]; if (this.rightBlock != null) { RectangleConstraint c4 = new RectangleConstraint(0.0, new Range(0.0, Math.max(constraint.getWidth() - w[2], 0.0)), LengthConstraintType.RANGE, h[2], null, LengthConstraintType.FIXED); Size2D size = this.rightBlock.arrange(g2, c4); w[3] = size.width; } h[4] = h[2]; w[4] = constraint.getWidth() - w[3] - w[2]; RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]); if (this.centerBlock != null) { this.centerBlock.arrange(g2, c5); } if (this.topBlock != null) { this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0], h[0])); } if (this.bottomBlock != null) { this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2], w[1], h[1])); } if (this.leftBlock != null) { this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2], h[2])); } if (this.rightBlock != null) { this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0], w[3], h[3])); } if (this.centerBlock != null) { this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4], h[4])); } return new Size2D(constraint.getWidth(), constraint.getHeight()); }
Math-106
public Fraction parse(String source, ParsePosition pos) { Fraction ret = super.parse(source, pos); if (ret != null) { return ret; } int initialIndex = pos.getIndex(); parseAndIgnoreWhitespace(source, pos); Number whole = getWholeFormat().parse(source, pos); if (whole == null) { pos.setIndex(initialIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number num = getNumeratorFormat().parse(source, pos); if (num == null) { pos.setIndex(initialIndex); return null; } int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); switch (c) { case 0 : return new Fraction(num.intValue(), 1); case '/' : break; default : pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number den = getDenominatorFormat().parse(source, pos); if (den == null) { pos.setIndex(initialIndex); return null; } int w = whole.intValue(); int n = num.intValue(); int d = den.intValue(); return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d); }
public Fraction parse(String source, ParsePosition pos) { Fraction ret = super.parse(source, pos); if (ret != null) { return ret; } int initialIndex = pos.getIndex(); parseAndIgnoreWhitespace(source, pos); Number whole = getWholeFormat().parse(source, pos); if (whole == null) { pos.setIndex(initialIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number num = getNumeratorFormat().parse(source, pos); if (num == null) { pos.setIndex(initialIndex); return null; } if (num.intValue() < 0) { pos.setIndex(initialIndex); return null; } int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); switch (c) { case 0 : return new Fraction(num.intValue(), 1); case '/' : break; default : pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } parseAndIgnoreWhitespace(source, pos); Number den = getDenominatorFormat().parse(source, pos); if (den == null) { pos.setIndex(initialIndex); return null; } if (den.intValue() < 0) { pos.setIndex(initialIndex); return null; } int w = whole.intValue(); int n = num.intValue(); int d = den.intValue(); return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d); }
Compress-41
public ZipArchiveEntry getNextZipEntry() throws IOException { boolean firstEntry = true; if (closed || hitCentralDirectory) { return null; } if (current != null) { closeEntry(); firstEntry = false; } try { if (firstEntry) { readFirstLocalFileHeader(LFH_BUF); } else { readFully(LFH_BUF); } } catch (final EOFException e) { return null; } final ZipLong sig = new ZipLong(LFH_BUF); if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) { hitCentralDirectory = true; skipRemainderOfArchive(); } if (!sig.equals(ZipLong.LFH_SIG)) { return null; } int off = WORD; current = new CurrentEntry(); final int versionMadeBy = ZipShort.getValue(LFH_BUF, off); off += SHORT; current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off); final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; current.hasDataDescriptor = gpFlag.usesDataDescriptor(); current.entry.setGeneralPurposeBit(gpFlag); off += SHORT; current.entry.setMethod(ZipShort.getValue(LFH_BUF, off)); off += SHORT; final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off)); current.entry.setTime(time); off += WORD; ZipLong size = null, cSize = null; if (!current.hasDataDescriptor) { current.entry.setCrc(ZipLong.getValue(LFH_BUF, off)); off += WORD; cSize = new ZipLong(LFH_BUF, off); off += WORD; size = new ZipLong(LFH_BUF, off); off += WORD; } else { off += 3 * WORD; } final int fileNameLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final int extraLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final byte[] fileName = new byte[fileNameLen]; readFully(fileName); current.entry.setName(entryEncoding.decode(fileName), fileName); final byte[] extraData = new byte[extraLen]; readFully(extraData); current.entry.setExtra(extraData); if (!hasUTF8Flag && useUnicodeExtraFields) { ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); } processZip64Extra(size, cSize); if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) { current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) { current.in = new ExplodingInputStream( current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) { current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } } entriesRead++; return current.entry; }
public ZipArchiveEntry getNextZipEntry() throws IOException { boolean firstEntry = true; if (closed || hitCentralDirectory) { return null; } if (current != null) { closeEntry(); firstEntry = false; } try { if (firstEntry) { readFirstLocalFileHeader(LFH_BUF); } else { readFully(LFH_BUF); } } catch (final EOFException e) { return null; } final ZipLong sig = new ZipLong(LFH_BUF); if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) { hitCentralDirectory = true; skipRemainderOfArchive(); return null; } if (!sig.equals(ZipLong.LFH_SIG)) { throw new ZipException(String.format("Unexpected record signature: 0X%X", sig.getValue())); } int off = WORD; current = new CurrentEntry(); final int versionMadeBy = ZipShort.getValue(LFH_BUF, off); off += SHORT; current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off); final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; current.hasDataDescriptor = gpFlag.usesDataDescriptor(); current.entry.setGeneralPurposeBit(gpFlag); off += SHORT; current.entry.setMethod(ZipShort.getValue(LFH_BUF, off)); off += SHORT; final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off)); current.entry.setTime(time); off += WORD; ZipLong size = null, cSize = null; if (!current.hasDataDescriptor) { current.entry.setCrc(ZipLong.getValue(LFH_BUF, off)); off += WORD; cSize = new ZipLong(LFH_BUF, off); off += WORD; size = new ZipLong(LFH_BUF, off); off += WORD; } else { off += 3 * WORD; } final int fileNameLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final int extraLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final byte[] fileName = new byte[fileNameLen]; readFully(fileName); current.entry.setName(entryEncoding.decode(fileName), fileName); final byte[] extraData = new byte[extraLen]; readFully(extraData); current.entry.setExtra(extraData); if (!hasUTF8Flag && useUnicodeExtraFields) { ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); } processZip64Extra(size, cSize); if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) { current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) { current.in = new ExplodingInputStream( current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) { current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } } entriesRead++; return current.entry; }
Closure-59
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; }
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn() && !options.disables(DiagnosticGroups.GLOBAL_THIS)) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; }
Lang-3
public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { final int hexDigits = str.length() - pfxLen; if (hexDigits > 16) { return createBigInteger(str); } if (hexDigits > 8) { return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; int numDecimals = 0; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (final NumberFormatException nfe) { } case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (final NumberFormatException nfe) { } try { return createLong(str); } catch (final NumberFormatException nfe) { } return createBigInteger(str); } final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (final NumberFormatException nfe) { } try { final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { } return createBigDecimal(str); }
public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { final int hexDigits = str.length() - pfxLen; if (hexDigits > 16) { return createBigInteger(str); } if (hexDigits > 8) { return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; int numDecimals = 0; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (final NumberFormatException nfe) { } case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { } default : throw new NumberFormatException(str + " is not a valid number."); } } if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(str); } catch (final NumberFormatException nfe) { } try { return createLong(str); } catch (final NumberFormatException nfe) { } return createBigInteger(str); } final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { if(numDecimals <= 7){ final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } } catch (final NumberFormatException nfe) { } try { if(numDecimals <= 16){ final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } } catch (final NumberFormatException nfe) { } return createBigDecimal(str); }
Closure-152
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope); typeOfThis = (ObjectType) safeResolve(typeOfThis, t, scope); boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope)); } } return super.resolveInternal(t, scope); }
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope); JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope); if (maybeTypeOfThis instanceof ObjectType) { typeOfThis = (ObjectType) maybeTypeOfThis; } boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope)); } } return super.resolveInternal(t, scope); }
JacksonDatabind-58
protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt, BeanDescription beanDesc, BeanPropertyDefinition propDef, JavaType propType0) throws JsonMappingException { AnnotatedMember mutator = propDef.getNonConstructorMutator(); if (ctxt.canOverrideAccessModifiers()) { mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(), propType0, propDef.getWrapperName(), beanDesc.getClassAnnotations(), mutator, propDef.getMetadata()); JavaType type = resolveType(ctxt, beanDesc, propType0, mutator); if (type != propType0) { property = property.withType(type); } JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator); type = modifyTypeByAnnotation(ctxt, mutator, type); TypeDeserializer typeDeser = type.getTypeHandler(); SettableBeanProperty prop; if (mutator instanceof AnnotatedMethod) { prop = new MethodProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator); } else { prop = new FieldProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedField) mutator); } if (propDeser != null) { prop = prop.withValueDeserializer(propDeser); } AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType(); if (ref != null && ref.isManagedReference()) { prop.setManagedReferenceName(ref.getName()); } ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo(); if(objectIdInfo != null){ prop.setObjectIdInfo(objectIdInfo); } return prop; }
protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt, BeanDescription beanDesc, BeanPropertyDefinition propDef, JavaType propType0) throws JsonMappingException { AnnotatedMember mutator = propDef.getNonConstructorMutator(); if (ctxt.canOverrideAccessModifiers()) { if ((mutator instanceof AnnotatedField) && "cause".equals(mutator.getName())) { ; } else { mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } } BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(), propType0, propDef.getWrapperName(), beanDesc.getClassAnnotations(), mutator, propDef.getMetadata()); JavaType type = resolveType(ctxt, beanDesc, propType0, mutator); if (type != propType0) { property = property.withType(type); } JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator); type = modifyTypeByAnnotation(ctxt, mutator, type); TypeDeserializer typeDeser = type.getTypeHandler(); SettableBeanProperty prop; if (mutator instanceof AnnotatedMethod) { prop = new MethodProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator); } else { prop = new FieldProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedField) mutator); } if (propDeser != null) { prop = prop.withValueDeserializer(propDeser); } AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType(); if (ref != null && ref.isManagedReference()) { prop.setManagedReferenceName(ref.getName()); } ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo(); if(objectIdInfo != null){ prop.setObjectIdInfo(objectIdInfo); } return prop; }
Math-3
public static double linearCombination(final double[] a, final double[] b) throws DimensionMismatchException { final int len = a.length; if (len != b.length) { throw new DimensionMismatchException(len, b.length); } final double[] prodHigh = new double[len]; double prodLowSum = 0; for (int i = 0; i < len; i++) { final double ai = a[i]; final double ca = SPLIT_FACTOR * ai; final double aHigh = ca - (ca - ai); final double aLow = ai - aHigh; final double bi = b[i]; final double cb = SPLIT_FACTOR * bi; final double bHigh = cb - (cb - bi); final double bLow = bi - bHigh; prodHigh[i] = ai * bi; final double prodLow = aLow * bLow - (((prodHigh[i] - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow); prodLowSum += prodLow; } final double prodHighCur = prodHigh[0]; double prodHighNext = prodHigh[1]; double sHighPrev = prodHighCur + prodHighNext; double sPrime = sHighPrev - prodHighNext; double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime); final int lenMinusOne = len - 1; for (int i = 1; i < lenMinusOne; i++) { prodHighNext = prodHigh[i + 1]; final double sHighCur = sHighPrev + prodHighNext; sPrime = sHighCur - prodHighNext; sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime); sHighPrev = sHighCur; } double result = sHighPrev + (prodLowSum + sLowSum); if (Double.isNaN(result)) { result = 0; for (int i = 0; i < len; ++i) { result += a[i] * b[i]; } } return result; }
public static double linearCombination(final double[] a, final double[] b) throws DimensionMismatchException { final int len = a.length; if (len != b.length) { throw new DimensionMismatchException(len, b.length); } if (len == 1) { return a[0] * b[0]; } final double[] prodHigh = new double[len]; double prodLowSum = 0; for (int i = 0; i < len; i++) { final double ai = a[i]; final double ca = SPLIT_FACTOR * ai; final double aHigh = ca - (ca - ai); final double aLow = ai - aHigh; final double bi = b[i]; final double cb = SPLIT_FACTOR * bi; final double bHigh = cb - (cb - bi); final double bLow = bi - bHigh; prodHigh[i] = ai * bi; final double prodLow = aLow * bLow - (((prodHigh[i] - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow); prodLowSum += prodLow; } final double prodHighCur = prodHigh[0]; double prodHighNext = prodHigh[1]; double sHighPrev = prodHighCur + prodHighNext; double sPrime = sHighPrev - prodHighNext; double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime); final int lenMinusOne = len - 1; for (int i = 1; i < lenMinusOne; i++) { prodHighNext = prodHigh[i + 1]; final double sHighCur = sHighPrev + prodHighNext; sPrime = sHighCur - prodHighNext; sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime); sHighPrev = sHighCur; } double result = sHighPrev + (prodLowSum + sLowSum); if (Double.isNaN(result)) { result = 0; for (int i = 0; i < len; ++i) { result += a[i] * b[i]; } } return result; }
JacksonCore-3
public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, features); _inputStream = in; _objectCodec = codec; _symbols = sym; _inputBuffer = inputBuffer; _inputPtr = start; _inputEnd = end; _bufferRecyclable = bufferRecyclable; }
public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, features); _inputStream = in; _objectCodec = codec; _symbols = sym; _inputBuffer = inputBuffer; _inputPtr = start; _inputEnd = end; _currInputRowStart = start; _currInputProcessed = -start; _bufferRecyclable = bufferRecyclable; }
Lang-39
private static String replaceEach(String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) { return text; } if (timeToLive < 0) { throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text); } int searchLength = searchList.length; int replacementLength = replacementList.length; if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; int textIndex = -1; int replaceIndex = -1; int tempIndex = -1; for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } if (textIndex == -1) { return text; } int start = 0; int increase = 0; for (int i = 0; i < searchList.length; i++) { int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; } } increase = Math.min(increase, text.length() / 5); StringBuilder buf = new StringBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; tempIndex = -1; for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } String result = buf.toString(); if (!repeat) { return result; } return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); }
private static String replaceEach(String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) { return text; } if (timeToLive < 0) { throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text); } int searchLength = searchList.length; int replacementLength = replacementList.length; if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; int textIndex = -1; int replaceIndex = -1; int tempIndex = -1; for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } if (textIndex == -1) { return text; } int start = 0; int increase = 0; for (int i = 0; i < searchList.length; i++) { if (searchList[i] == null || replacementList[i] == null) { continue; } int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; } } increase = Math.min(increase, text.length() / 5); StringBuilder buf = new StringBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; tempIndex = -1; for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } String result = buf.toString(); if (!repeat) { return result; } return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); }
Compress-13
protected void setName(String name) { this.name = name; }
protected void setName(String name) { if (name != null && getPlatform() == PLATFORM_FAT && name.indexOf("/") == -1) { name = name.replace('\\', '/'); } this.name = name; }
Gson-13
private int peekNumber() throws IOException { char[] buffer = this.buffer; int p = pos; int l = limit; long value = 0; boolean negative = false; boolean fitsInLong = true; int last = NUMBER_CHAR_NONE; int i = 0; charactersOfNumber: for (; true; i++) { if (p + i == l) { if (i == buffer.length) { return PEEKED_NONE; } if (!fillBuffer(i + 1)) { break; } p = pos; l = limit; } char c = buffer[p + i]; switch (c) { case '-': if (last == NUMBER_CHAR_NONE) { negative = true; last = NUMBER_CHAR_SIGN; continue; } else if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case '+': if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case 'e': case 'E': if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) { last = NUMBER_CHAR_EXP_E; continue; } return PEEKED_NONE; case '.': if (last == NUMBER_CHAR_DIGIT) { last = NUMBER_CHAR_DECIMAL; continue; } return PEEKED_NONE; default: if (c < '0' || c > '9') { if (!isLiteral(c)) { break charactersOfNumber; } return PEEKED_NONE; } if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) { value = -(c - '0'); last = NUMBER_CHAR_DIGIT; } else if (last == NUMBER_CHAR_DIGIT) { if (value == 0) { return PEEKED_NONE; } long newValue = value * 10 - (c - '0'); fitsInLong &= value > MIN_INCOMPLETE_INTEGER || (value == MIN_INCOMPLETE_INTEGER && newValue < value); value = newValue; } else if (last == NUMBER_CHAR_DECIMAL) { last = NUMBER_CHAR_FRACTION_DIGIT; } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) { last = NUMBER_CHAR_EXP_DIGIT; } } } if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) { peekedLong = negative ? value : -value; pos += i; return peeked = PEEKED_LONG; } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) { peekedNumberLength = i; return peeked = PEEKED_NUMBER; } else { return PEEKED_NONE; } }
private int peekNumber() throws IOException { char[] buffer = this.buffer; int p = pos; int l = limit; long value = 0; boolean negative = false; boolean fitsInLong = true; int last = NUMBER_CHAR_NONE; int i = 0; charactersOfNumber: for (; true; i++) { if (p + i == l) { if (i == buffer.length) { return PEEKED_NONE; } if (!fillBuffer(i + 1)) { break; } p = pos; l = limit; } char c = buffer[p + i]; switch (c) { case '-': if (last == NUMBER_CHAR_NONE) { negative = true; last = NUMBER_CHAR_SIGN; continue; } else if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case '+': if (last == NUMBER_CHAR_EXP_E) { last = NUMBER_CHAR_EXP_SIGN; continue; } return PEEKED_NONE; case 'e': case 'E': if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) { last = NUMBER_CHAR_EXP_E; continue; } return PEEKED_NONE; case '.': if (last == NUMBER_CHAR_DIGIT) { last = NUMBER_CHAR_DECIMAL; continue; } return PEEKED_NONE; default: if (c < '0' || c > '9') { if (!isLiteral(c)) { break charactersOfNumber; } return PEEKED_NONE; } if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) { value = -(c - '0'); last = NUMBER_CHAR_DIGIT; } else if (last == NUMBER_CHAR_DIGIT) { if (value == 0) { return PEEKED_NONE; } long newValue = value * 10 - (c - '0'); fitsInLong &= value > MIN_INCOMPLETE_INTEGER || (value == MIN_INCOMPLETE_INTEGER && newValue < value); value = newValue; } else if (last == NUMBER_CHAR_DECIMAL) { last = NUMBER_CHAR_FRACTION_DIGIT; } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) { last = NUMBER_CHAR_EXP_DIGIT; } } } if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value!=0 || false==negative)) { peekedLong = negative ? value : -value; pos += i; return peeked = PEEKED_LONG; } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT || last == NUMBER_CHAR_EXP_DIGIT) { peekedNumberLength = i; return peeked = PEEKED_NUMBER; } else { return PEEKED_NONE; } }
JacksonDatabind-112
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { JsonDeserializer<Object> delegate = null; if (_valueInstantiator != null) { AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator(); if (delegateCreator != null) { JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig()); delegate = findDeserializer(ctxt, delegateType, property); } } JsonDeserializer<?> valueDeser = _valueDeserializer; final JavaType valueType = _containerType.getContentType(); if (valueDeser == null) { valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser); if (valueDeser == null) { valueDeser = ctxt.findContextualValueDeserializer(valueType, property); } } else { valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType); } Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class, JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser); if (isDefaultDeserializer(valueDeser)) { valueDeser = null; } return withResolved(delegate, valueDeser, nuller, unwrapSingle); }
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { JsonDeserializer<Object> delegate = null; if (_valueInstantiator != null) { AnnotatedWithParams delegateCreator = _valueInstantiator.getArrayDelegateCreator(); if (delegateCreator != null) { JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig()); delegate = findDeserializer(ctxt, delegateType, property); } else if ((delegateCreator = _valueInstantiator.getDelegateCreator()) != null) { JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig()); delegate = findDeserializer(ctxt, delegateType, property); } } JsonDeserializer<?> valueDeser = _valueDeserializer; final JavaType valueType = _containerType.getContentType(); if (valueDeser == null) { valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser); if (valueDeser == null) { valueDeser = ctxt.findContextualValueDeserializer(valueType, property); } } else { valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType); } Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class, JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser); if (isDefaultDeserializer(valueDeser)) { valueDeser = null; } return withResolved(delegate, valueDeser, nuller, unwrapSingle); }
Closure-65
static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\0"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': final String END_SCRIPT = "/script"; final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { appendHexJavaScriptRepresentation(sb, c); } } else { if (c > 0x1f && c < 0x7f) { sb.append(c); } else { appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); }
static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\000"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': final String END_SCRIPT = "/script"; final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { appendHexJavaScriptRepresentation(sb, c); } } else { if (c > 0x1f && c < 0x7f) { sb.append(c); } else { appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); }
Math-26
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) throws FractionConversionException { long overflow = Integer.MAX_VALUE; double r0 = value; long a0 = (long)FastMath.floor(r0); if (a0 > overflow) { throw new FractionConversionException(value, a0, 1l); } if (FastMath.abs(a0 - value) < epsilon) { this.numerator = (int) a0; this.denominator = 1; return; } long p0 = 1; long q0 = 0; long p1 = a0; long q1 = 1; long p2 = 0; long q2 = 1; int n = 0; boolean stop = false; do { ++n; double r1 = 1.0 / (r0 - a0); long a1 = (long)FastMath.floor(r1); p2 = (a1 * p1) + p0; q2 = (a1 * q1) + q0; if ((p2 > overflow) || (q2 > overflow)) { throw new FractionConversionException(value, p2, q2); } double convergent = (double)p2 / (double)q2; if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) { p0 = p1; p1 = p2; q0 = q1; q1 = q2; a0 = a1; r0 = r1; } else { stop = true; } } while (!stop); if (n >= maxIterations) { throw new FractionConversionException(value, maxIterations); } if (q2 < maxDenominator) { this.numerator = (int) p2; this.denominator = (int) q2; } else { this.numerator = (int) p1; this.denominator = (int) q1; } }
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) throws FractionConversionException { long overflow = Integer.MAX_VALUE; double r0 = value; long a0 = (long)FastMath.floor(r0); if (FastMath.abs(a0) > overflow) { throw new FractionConversionException(value, a0, 1l); } if (FastMath.abs(a0 - value) < epsilon) { this.numerator = (int) a0; this.denominator = 1; return; } long p0 = 1; long q0 = 0; long p1 = a0; long q1 = 1; long p2 = 0; long q2 = 1; int n = 0; boolean stop = false; do { ++n; double r1 = 1.0 / (r0 - a0); long a1 = (long)FastMath.floor(r1); p2 = (a1 * p1) + p0; q2 = (a1 * q1) + q0; if ((FastMath.abs(p2) > overflow) || (FastMath.abs(q2) > overflow)) { throw new FractionConversionException(value, p2, q2); } double convergent = (double)p2 / (double)q2; if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) { p0 = p1; p1 = p2; q0 = q1; q1 = q2; a0 = a1; r0 = r1; } else { stop = true; } } while (!stop); if (n >= maxIterations) { throw new FractionConversionException(value, maxIterations); } if (q2 < maxDenominator) { this.numerator = (int) p2; this.denominator = (int) q2; } else { this.numerator = (int) p1; this.denominator = (int) q1; } }
Jsoup-77
private void popStackToClose(Token.EndTag endTag) { String elName = endTag.name(); Element firstFound = null; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (next.nodeName().equals(elName)) { firstFound = next; break; } } if (firstFound == null) return; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); stack.remove(pos); if (next == firstFound) break; } }
private void popStackToClose(Token.EndTag endTag) { String elName = endTag.normalName(); Element firstFound = null; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (next.nodeName().equals(elName)) { firstFound = next; break; } } if (firstFound == null) return; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); stack.remove(pos); if (next == firstFound) break; } }
Jsoup-26
public Document clean(Document dirtyDocument) { Validate.notNull(dirtyDocument); Document clean = Document.createShell(dirtyDocument.baseUri()); copySafeNodes(dirtyDocument.body(), clean.body()); return clean; }
public Document clean(Document dirtyDocument) { Validate.notNull(dirtyDocument); Document clean = Document.createShell(dirtyDocument.baseUri()); if (dirtyDocument.body() != null) copySafeNodes(dirtyDocument.body(), clean.body()); return clean; }
JxPath-8
private boolean compute(Object left, Object right) { left = reduce(left); right = reduce(right); if (left instanceof InitialContext) { ((InitialContext) left).reset(); } if (right instanceof InitialContext) { ((InitialContext) right).reset(); } if (left instanceof Iterator && right instanceof Iterator) { return findMatch((Iterator) left, (Iterator) right); } if (left instanceof Iterator) { return containsMatch((Iterator) left, right); } if (right instanceof Iterator) { return containsMatch((Iterator) right, left); } double ld = InfoSetUtil.doubleValue(left); double rd = InfoSetUtil.doubleValue(right); return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1); }
private boolean compute(Object left, Object right) { left = reduce(left); right = reduce(right); if (left instanceof InitialContext) { ((InitialContext) left).reset(); } if (right instanceof InitialContext) { ((InitialContext) right).reset(); } if (left instanceof Iterator && right instanceof Iterator) { return findMatch((Iterator) left, (Iterator) right); } if (left instanceof Iterator) { return containsMatch((Iterator) left, right); } if (right instanceof Iterator) { return containsMatch((Iterator) right, left); } double ld = InfoSetUtil.doubleValue(left); if (Double.isNaN(ld)) { return false; } double rd = InfoSetUtil.doubleValue(right); if (Double.isNaN(rd)) { return false; } return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1); }
Math-30
private double calculateAsymptoticPValue(final double Umin, final int n1, final int n2) throws ConvergenceException, MaxCountExceededException { final int n1n2prod = n1 * n2; final double EU = n1n2prod / 2.0; final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0; final double z = (Umin - EU) / FastMath.sqrt(VarU); final NormalDistribution standardNormal = new NormalDistribution(0, 1); return 2 * standardNormal.cumulativeProbability(z); }
private double calculateAsymptoticPValue(final double Umin, final int n1, final int n2) throws ConvergenceException, MaxCountExceededException { final double n1n2prod = n1 * n2; final double EU = n1n2prod / 2.0; final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0; final double z = (Umin - EU) / FastMath.sqrt(VarU); final NormalDistribution standardNormal = new NormalDistribution(0, 1); return 2 * standardNormal.cumulativeProbability(z); }
JacksonDatabind-99
protected String buildCanonicalName() { StringBuilder sb = new StringBuilder(); sb.append(_class.getName()); sb.append('<'); sb.append(_referencedType.toCanonical()); return sb.toString(); }
protected String buildCanonicalName() { StringBuilder sb = new StringBuilder(); sb.append(_class.getName()); sb.append('<'); sb.append(_referencedType.toCanonical()); sb.append('>'); return sb.toString(); }
Math-40
protected double doSolve() { final double[] x = new double[maximalOrder + 1]; final double[] y = new double[maximalOrder + 1]; x[0] = getMin(); x[1] = getStartValue(); x[2] = getMax(); verifySequence(x[0], x[1], x[2]); y[1] = computeObjectiveValue(x[1]); if (Precision.equals(y[1], 0.0, 1)) { return x[1]; } y[0] = computeObjectiveValue(x[0]); if (Precision.equals(y[0], 0.0, 1)) { return x[0]; } int nbPoints; int signChangeIndex; if (y[0] * y[1] < 0) { nbPoints = 2; signChangeIndex = 1; } else { y[2] = computeObjectiveValue(x[2]); if (Precision.equals(y[2], 0.0, 1)) { return x[2]; } if (y[1] * y[2] < 0) { nbPoints = 3; signChangeIndex = 2; } else { throw new NoBracketingException(x[0], x[2], y[0], y[2]); } } final double[] tmpX = new double[x.length]; double xA = x[signChangeIndex - 1]; double yA = y[signChangeIndex - 1]; double absYA = FastMath.abs(yA); int agingA = 0; double xB = x[signChangeIndex]; double yB = y[signChangeIndex]; double absYB = FastMath.abs(yB); int agingB = 0; while (true) { final double xTol = getAbsoluteAccuracy() + getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB)); if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) { switch (allowed) { case ANY_SIDE : return absYA < absYB ? xA : xB; case LEFT_SIDE : return xA; case RIGHT_SIDE : return xB; case BELOW_SIDE : return (yA <= 0) ? xA : xB; case ABOVE_SIDE : return (yA < 0) ? xB : xA; default : throw new MathInternalError(null); } } double targetY; if (agingA >= MAXIMAL_AGING) { targetY = -REDUCTION_FACTOR * yB; } else if (agingB >= MAXIMAL_AGING) { targetY = -REDUCTION_FACTOR * yA; } else { targetY = 0; } double nextX; int start = 0; int end = nbPoints; do { System.arraycopy(x, start, tmpX, start, end - start); nextX = guessX(targetY, tmpX, y, start, end); if (!((nextX > xA) && (nextX < xB))) { if (signChangeIndex - start >= end - signChangeIndex) { ++start; } else { --end; } nextX = Double.NaN; } } while (Double.isNaN(nextX) && (end - start > 1)); if (Double.isNaN(nextX)) { nextX = xA + 0.5 * (xB - xA); start = signChangeIndex - 1; end = signChangeIndex; } final double nextY = computeObjectiveValue(nextX); if (Precision.equals(nextY, 0.0, 1)) { return nextX; } if ((nbPoints > 2) && (end - start != nbPoints)) { nbPoints = end - start; System.arraycopy(x, start, x, 0, nbPoints); System.arraycopy(y, start, y, 0, nbPoints); signChangeIndex -= start; } else if (nbPoints == x.length) { nbPoints--; if (signChangeIndex >= (x.length + 1) / 2) { System.arraycopy(x, 1, x, 0, nbPoints); System.arraycopy(y, 1, y, 0, nbPoints); --signChangeIndex; } } System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex); x[signChangeIndex] = nextX; System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex); y[signChangeIndex] = nextY; ++nbPoints; if (nextY * yA <= 0) { xB = nextX; yB = nextY; absYB = FastMath.abs(yB); ++agingA; agingB = 0; } else { xA = nextX; yA = nextY; absYA = FastMath.abs(yA); agingA = 0; ++agingB; signChangeIndex++; } } }
protected double doSolve() { final double[] x = new double[maximalOrder + 1]; final double[] y = new double[maximalOrder + 1]; x[0] = getMin(); x[1] = getStartValue(); x[2] = getMax(); verifySequence(x[0], x[1], x[2]); y[1] = computeObjectiveValue(x[1]); if (Precision.equals(y[1], 0.0, 1)) { return x[1]; } y[0] = computeObjectiveValue(x[0]); if (Precision.equals(y[0], 0.0, 1)) { return x[0]; } int nbPoints; int signChangeIndex; if (y[0] * y[1] < 0) { nbPoints = 2; signChangeIndex = 1; } else { y[2] = computeObjectiveValue(x[2]); if (Precision.equals(y[2], 0.0, 1)) { return x[2]; } if (y[1] * y[2] < 0) { nbPoints = 3; signChangeIndex = 2; } else { throw new NoBracketingException(x[0], x[2], y[0], y[2]); } } final double[] tmpX = new double[x.length]; double xA = x[signChangeIndex - 1]; double yA = y[signChangeIndex - 1]; double absYA = FastMath.abs(yA); int agingA = 0; double xB = x[signChangeIndex]; double yB = y[signChangeIndex]; double absYB = FastMath.abs(yB); int agingB = 0; while (true) { final double xTol = getAbsoluteAccuracy() + getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB)); if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) { switch (allowed) { case ANY_SIDE : return absYA < absYB ? xA : xB; case LEFT_SIDE : return xA; case RIGHT_SIDE : return xB; case BELOW_SIDE : return (yA <= 0) ? xA : xB; case ABOVE_SIDE : return (yA < 0) ? xB : xA; default : throw new MathInternalError(null); } } double targetY; if (agingA >= MAXIMAL_AGING) { final int p = agingA - MAXIMAL_AGING; final double weightA = (1 << p) - 1; final double weightB = p + 1; targetY = (weightA * yA - weightB * REDUCTION_FACTOR * yB) / (weightA + weightB); } else if (agingB >= MAXIMAL_AGING) { final int p = agingB - MAXIMAL_AGING; final double weightA = p + 1; final double weightB = (1 << p) - 1; targetY = (weightB * yB - weightA * REDUCTION_FACTOR * yA) / (weightA + weightB); } else { targetY = 0; } double nextX; int start = 0; int end = nbPoints; do { System.arraycopy(x, start, tmpX, start, end - start); nextX = guessX(targetY, tmpX, y, start, end); if (!((nextX > xA) && (nextX < xB))) { if (signChangeIndex - start >= end - signChangeIndex) { ++start; } else { --end; } nextX = Double.NaN; } } while (Double.isNaN(nextX) && (end - start > 1)); if (Double.isNaN(nextX)) { nextX = xA + 0.5 * (xB - xA); start = signChangeIndex - 1; end = signChangeIndex; } final double nextY = computeObjectiveValue(nextX); if (Precision.equals(nextY, 0.0, 1)) { return nextX; } if ((nbPoints > 2) && (end - start != nbPoints)) { nbPoints = end - start; System.arraycopy(x, start, x, 0, nbPoints); System.arraycopy(y, start, y, 0, nbPoints); signChangeIndex -= start; } else if (nbPoints == x.length) { nbPoints--; if (signChangeIndex >= (x.length + 1) / 2) { System.arraycopy(x, 1, x, 0, nbPoints); System.arraycopy(y, 1, y, 0, nbPoints); --signChangeIndex; } } System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex); x[signChangeIndex] = nextX; System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex); y[signChangeIndex] = nextY; ++nbPoints; if (nextY * yA <= 0) { xB = nextX; yB = nextY; absYB = FastMath.abs(yB); ++agingA; agingB = 0; } else { xA = nextX; yA = nextY; absYA = FastMath.abs(yA); agingA = 0; ++agingB; signChangeIndex++; } } }
Jsoup-37
public String html() { StringBuilder accum = new StringBuilder(); html(accum); return accum.toString().trim(); }
public String html() { StringBuilder accum = new StringBuilder(); html(accum); return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString(); }
Cli-15
public List getValues(final Option option, List defaultValues) { List valueList = (List) values.get(option); if ((valueList == null) || valueList.isEmpty()) { valueList = defaultValues; } if ((valueList == null) || valueList.isEmpty()) { valueList = (List) this.defaultValues.get(option); } return valueList == null ? Collections.EMPTY_LIST : valueList; }
public List getValues(final Option option, List defaultValues) { List valueList = (List) values.get(option); if (defaultValues == null || defaultValues.isEmpty()) { defaultValues = (List) this.defaultValues.get(option); } if (defaultValues != null && !defaultValues.isEmpty()) { if (valueList == null || valueList.isEmpty()) { valueList = defaultValues; } else { if (defaultValues.size() > valueList.size()) { valueList = new ArrayList(valueList); for (int i=valueList.size(); i<defaultValues.size(); i++) { valueList.add(defaultValues.get(i)); } } } } return valueList == null ? Collections.EMPTY_LIST : valueList; }
Cli-8
protected StringBuffer renderWrappedText(StringBuffer sb, int width, int nextLineTabStop, String text) { int pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(rtrim(text)); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, nextLineTabStop); if (pos == -1) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
protected StringBuffer renderWrappedText(StringBuffer sb, int width, int nextLineTabStop, String text) { int pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(rtrim(text)); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
Closure-146
public TypePair getTypesUnderInequality(JSType that) { if (that instanceof UnionType) { TypePair p = that.getTypesUnderInequality(this); return new TypePair(p.typeB, p.typeA); } switch (this.testForEquality(that)) { case TRUE: return new TypePair(null, null); case FALSE: case UNKNOWN: return new TypePair(this, that); } throw new IllegalStateException(); }
public TypePair getTypesUnderInequality(JSType that) { if (that instanceof UnionType) { TypePair p = that.getTypesUnderInequality(this); return new TypePair(p.typeB, p.typeA); } switch (this.testForEquality(that)) { case TRUE: JSType noType = getNativeType(JSTypeNative.NO_TYPE); return new TypePair(noType, noType); case FALSE: case UNKNOWN: return new TypePair(this, that); } throw new IllegalStateException(); }
Compress-26
public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } return available - numToSkip; }
public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } if (numToSkip > 0) { byte[] skipBuf = new byte[SKIP_BUF_SIZE]; while (numToSkip > 0) { int read = readFully(input, skipBuf, 0, (int) Math.min(numToSkip, SKIP_BUF_SIZE)); if (read < 1) { break; } numToSkip -= read; } } return available - numToSkip; }
Compress-31
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte == 0) { break; } if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
Lang-12
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (start == 0 && end == 0) { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); }
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); }
Compress-44
public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { this.checksum = checksum; this.in = in; }
public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { if ( checksum == null ){ throw new NullPointerException("Parameter checksum must not be null"); } if ( in == null ){ throw new NullPointerException("Parameter in must not be null"); } this.checksum = checksum; this.in = in; }
Time-8
public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException { if (hoursOffset == 0 && minutesOffset == 0) { return DateTimeZone.UTC; } if (hoursOffset < -23 || hoursOffset > 23) { throw new IllegalArgumentException("Hours out of range: " + hoursOffset); } if (minutesOffset < 0 || minutesOffset > 59) { throw new IllegalArgumentException("Minutes out of range: " + minutesOffset); } int offset = 0; try { int hoursInMinutes = hoursOffset * 60; if (hoursInMinutes < 0) { minutesOffset = hoursInMinutes - minutesOffset; } else { minutesOffset = hoursInMinutes + minutesOffset; } offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE); } catch (ArithmeticException ex) { throw new IllegalArgumentException("Offset is too large"); } return forOffsetMillis(offset); }
public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException { if (hoursOffset == 0 && minutesOffset == 0) { return DateTimeZone.UTC; } if (hoursOffset < -23 || hoursOffset > 23) { throw new IllegalArgumentException("Hours out of range: " + hoursOffset); } if (minutesOffset < -59 || minutesOffset > 59) { throw new IllegalArgumentException("Minutes out of range: " + minutesOffset); } if (hoursOffset > 0 && minutesOffset < 0) { throw new IllegalArgumentException("Positive hours must not have negative minutes: " + minutesOffset); } int offset = 0; try { int hoursInMinutes = hoursOffset * 60; if (hoursInMinutes < 0) { minutesOffset = hoursInMinutes - Math.abs(minutesOffset); } else { minutesOffset = hoursInMinutes + minutesOffset; } offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE); } catch (ArithmeticException ex) { throw new IllegalArgumentException("Offset is too large"); } return forOffsetMillis(offset); }
Math-2
public double getNumericalMean() { return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize(); }
public double getNumericalMean() { return getSampleSize() * (getNumberOfSuccesses() / (double) getPopulationSize()); }
Csv-14
private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { if (newRecord) { quote = true; } } else { char c = value.charAt(pos); if (newRecord && (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')) { quote = true; } else if (c <= COMMENT) { quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); if (c <= SP) { quote = true; } } } } if (!quote) { out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { out.append(value, start, end); return; } out.append(quoteChar); while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { out.append(value, start, pos + 1); start = pos; } pos++; } out.append(value, start, pos); out.append(quoteChar); }
private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { if (newRecord) { quote = true; } } else { char c = value.charAt(pos); if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) { quote = true; } else if (c <= COMMENT) { quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); if (c <= SP) { quote = true; } } } } if (!quote) { out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { out.append(value, start, end); return; } out.append(quoteChar); while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { out.append(value, start, pos + 1); start = pos; } pos++; } out.append(value, start, pos); out.append(quoteChar); }
JacksonDatabind-85
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property == null) { return this; } JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (format == null) { return this; } JsonFormat.Shape shape = format.getShape(); if (shape.isNumeric()) { return withFormat(Boolean.TRUE, null); } if ((shape == JsonFormat.Shape.STRING) || format.hasPattern() || format.hasLocale() || format.hasTimeZone()) { TimeZone tz = format.getTimeZone(); final String pattern = format.hasPattern() ? format.getPattern() : StdDateFormat.DATE_FORMAT_STR_ISO8601; final Locale loc = format.hasLocale() ? format.getLocale() : serializers.getLocale(); SimpleDateFormat df = new SimpleDateFormat(pattern, loc); if (tz == null) { tz = serializers.getTimeZone(); } df.setTimeZone(tz); return withFormat(Boolean.FALSE, df); } return this; }
public JsonSerializer<?> createContextual(SerializerProvider serializers, BeanProperty property) throws JsonMappingException { if (property == null) { return this; } JsonFormat.Value format = findFormatOverrides(serializers, property, handledType()); if (format == null) { return this; } JsonFormat.Shape shape = format.getShape(); if (shape.isNumeric()) { return withFormat(Boolean.TRUE, null); } if (format.hasPattern()) { final Locale loc = format.hasLocale() ? format.getLocale() : serializers.getLocale(); SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc); TimeZone tz = format.hasTimeZone() ? format.getTimeZone() : serializers.getTimeZone(); df.setTimeZone(tz); return withFormat(Boolean.FALSE, df); } final boolean hasLocale = format.hasLocale(); final boolean hasTZ = format.hasTimeZone(); final boolean asString = (shape == JsonFormat.Shape.STRING); if (!hasLocale && !hasTZ && !asString) { return this; } DateFormat df0 = serializers.getConfig().getDateFormat(); if (df0 instanceof StdDateFormat) { StdDateFormat std = (StdDateFormat) df0; if (format.hasLocale()) { std = std.withLocale(format.getLocale()); } if (format.hasTimeZone()) { std = std.withTimeZone(format.getTimeZone()); } return withFormat(Boolean.FALSE, std); } if (!(df0 instanceof SimpleDateFormat)) { serializers.reportMappingProblem( "Configured `DateFormat` (%s) not a `SimpleDateFormat`; can not configure `Locale` or `TimeZone`", df0.getClass().getName()); } SimpleDateFormat df = (SimpleDateFormat) df0; if (hasLocale) { df = new SimpleDateFormat(df.toPattern(), format.getLocale()); } else { df = (SimpleDateFormat) df.clone(); } TimeZone newTz = format.getTimeZone(); boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone()); if (changeTZ) { df.setTimeZone(newTz); } return withFormat(Boolean.FALSE, df); }
Compress-17
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } trailer = buffer[end - 1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } trailer = buffer[end - 1]; while (start < end - 1 && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); } return result; }
Math-88
protected RealPointValuePair getSolution() { double[] coefficients = new double[getOriginalNumDecisionVariables()]; Integer basicRow = getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables()); double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset()); for (int i = 0; i < coefficients.length; i++) { basicRow = getBasicRow(getNumObjectiveFunctions() + i); coefficients[i] = (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - (restrictToNonNegative ? 0 : mostNegative); if (basicRow != null) { for (int j = getNumObjectiveFunctions(); j < getNumObjectiveFunctions() + i; j++) { if (tableau.getEntry(basicRow, j) == 1) { coefficients[i] = 0; } } } } return new RealPointValuePair(coefficients, f.getValue(coefficients)); }
protected RealPointValuePair getSolution() { double[] coefficients = new double[getOriginalNumDecisionVariables()]; Integer basicRow = getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables()); double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset()); Set<Integer> basicRows = new HashSet<Integer>(); for (int i = 0; i < coefficients.length; i++) { basicRow = getBasicRow(getNumObjectiveFunctions() + i); if (basicRows.contains(basicRow)) { coefficients[i] = 0; } else { basicRows.add(basicRow); coefficients[i] = (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - (restrictToNonNegative ? 0 : mostNegative); } } return new RealPointValuePair(coefficients, f.getValue(coefficients)); }
Closure-91
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || pType == Token.STRING || pType == Token.NUMBER)) { return false; } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { if (assignLhsChild == null) { assignLhsChild = lhs; } } else { if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || pType == Token.STRING || pType == Token.NUMBER)) { return false; } Node gramps = parent.getParent(); if (NodeUtil.isObjectLitKey(parent, gramps)) { JSDocInfo maybeLends = gramps.getJSDocInfo(); if (maybeLends != null && maybeLends.getLendsName() != null && maybeLends.getLendsName().endsWith(".prototype")) { return false; } } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { if (assignLhsChild == null) { assignLhsChild = lhs; } } else { if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
Closure-113
private void processRequireCall(NodeTraversal t, Node n, Node parent) { Node left = n.getFirstChild(); Node arg = left.getNext(); if (verifyLastArgumentIsString(t, left, arg)) { String ns = arg.getString(); ProvidedName provided = providedNames.get(ns); if (provided == null || !provided.isExplicitlyProvided()) { unrecognizedRequires.add( new UnrecognizedRequire(n, ns, t.getSourceName())); } else { JSModule providedModule = provided.explicitModule; Preconditions.checkNotNull(providedModule); JSModule module = t.getModule(); if (moduleGraph != null && module != providedModule && !moduleGraph.dependsOn(module, providedModule)) { compiler.report( t.makeError(n, XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } maybeAddToSymbolTable(left); maybeAddStringNodeToSymbolTable(arg); if (provided != null) { parent.detachFromParent(); compiler.reportCodeChange(); } } }
private void processRequireCall(NodeTraversal t, Node n, Node parent) { Node left = n.getFirstChild(); Node arg = left.getNext(); if (verifyLastArgumentIsString(t, left, arg)) { String ns = arg.getString(); ProvidedName provided = providedNames.get(ns); if (provided == null || !provided.isExplicitlyProvided()) { unrecognizedRequires.add( new UnrecognizedRequire(n, ns, t.getSourceName())); } else { JSModule providedModule = provided.explicitModule; Preconditions.checkNotNull(providedModule); JSModule module = t.getModule(); if (moduleGraph != null && module != providedModule && !moduleGraph.dependsOn(module, providedModule)) { compiler.report( t.makeError(n, XMODULE_REQUIRE_ERROR, ns, providedModule.getName(), module.getName())); } } maybeAddToSymbolTable(left); maybeAddStringNodeToSymbolTable(arg); if (provided != null || requiresLevel.isOn()) { parent.detachFromParent(); compiler.reportCodeChange(); } } }
Closure-111
protected JSType caseTopType(JSType topType) { return topType; }
protected JSType caseTopType(JSType topType) { return topType.isAllType() ? getNativeType(ARRAY_TYPE) : topType; }
Closure-12
private boolean hasExceptionHandler(Node cfgNode) { return false; }
private boolean hasExceptionHandler(Node cfgNode) { List<DiGraphEdge<Node, Branch>> branchEdges = getCfg().getOutEdges(cfgNode); for (DiGraphEdge<Node, Branch> edge : branchEdges) { if (edge.getValue() == Branch.ON_EX) { return true; } } return false; }
Jsoup-70
static boolean preserveWhitespace(Node node) { if (node != null && node instanceof Element) { Element el = (Element) node; if (el.tag.preserveWhitespace()) return true; else return el.parent() != null && el.parent().tag.preserveWhitespace(); } return false; }
static boolean preserveWhitespace(Node node) { if (node != null && node instanceof Element) { Element el = (Element) node; int i = 0; do { if (el.tag.preserveWhitespace()) return true; el = el.parent(); i++; } while (i < 6 && el != null); } return false; }
Closure-66
public void visit(NodeTraversal t, Node n, Node parent) { JSType childType; JSType leftType, rightType; Node left, right; boolean typeable = true; switch (n.getType()) { case Token.NAME: typeable = visitName(t, n, parent); break; case Token.LP: if (parent.getType() != Token.FUNCTION) { ensureTyped(t, n, getJSType(n.getFirstChild())); } else { typeable = false; } break; case Token.COMMA: ensureTyped(t, n, getJSType(n.getLastChild())); break; case Token.TRUE: case Token.FALSE: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.THIS: ensureTyped(t, n, t.getScope().getTypeOfThis()); break; case Token.REF_SPECIAL: ensureTyped(t, n); break; case Token.GET_REF: ensureTyped(t, n, getJSType(n.getFirstChild())); break; case Token.NULL: ensureTyped(t, n, NULL_TYPE); break; case Token.NUMBER: ensureTyped(t, n, NUMBER_TYPE); break; case Token.STRING: if (!NodeUtil.isObjectLitKey(n, n.getParent())) { ensureTyped(t, n, STRING_TYPE); } break; case Token.GET: case Token.SET: break; case Token.ARRAYLIT: ensureTyped(t, n, ARRAY_TYPE); break; case Token.REGEXP: ensureTyped(t, n, REGEXP_TYPE); break; case Token.GETPROP: visitGetProp(t, n, parent); typeable = !(parent.getType() == Token.ASSIGN && parent.getFirstChild() == n); break; case Token.GETELEM: visitGetElem(t, n); typeable = false; break; case Token.VAR: visitVar(t, n); typeable = false; break; case Token.NEW: visitNew(t, n); typeable = true; break; case Token.CALL: visitCall(t, n); typeable = !NodeUtil.isExpressionNode(parent); break; case Token.RETURN: visitReturn(t, n); typeable = false; break; case Token.DEC: case Token.INC: left = n.getFirstChild(); validator.expectNumber( t, left, getJSType(left), "increment/decrement"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.NOT: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.VOID: ensureTyped(t, n, VOID_TYPE); break; case Token.TYPEOF: ensureTyped(t, n, STRING_TYPE); break; case Token.BITNOT: childType = getJSType(n.getFirstChild()); if (!childType.matchesInt32Context()) { report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()), childType.toString()); } ensureTyped(t, n, NUMBER_TYPE); break; case Token.POS: case Token.NEG: left = n.getFirstChild(); validator.expectNumber(t, left, getJSType(left), "sign operator"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.EQ: case Token.NE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); TernaryValue result = leftTypeRestricted.testForEquality(rightTypeRestricted); if (result != TernaryValue.UNKNOWN) { if (n.getType() == Token.NE) { result = result.not(); } report(t, n, DETERMINISTIC_TEST, leftType.toString(), rightType.toString(), result.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.SHEQ: case Token.SHNE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); if (!leftTypeRestricted.canTestForShallowEqualityWith( rightTypeRestricted)) { report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(), rightType.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.LT: case Token.LE: case Token.GT: case Token.GE: leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); if (rightType.isNumber()) { validator.expectNumber( t, n, leftType, "left side of numeric comparison"); } else if (leftType.isNumber()) { validator.expectNumber( t, n, rightType, "right side of numeric comparison"); } else if (leftType.matchesNumberContext() && rightType.matchesNumberContext()) { } else { String message = "left side of comparison"; validator.expectString(t, n, leftType, message); validator.expectNotNullOrUndefined( t, n, leftType, message, getNativeType(STRING_TYPE)); message = "right side of comparison"; validator.expectString(t, n, rightType, message); validator.expectNotNullOrUndefined( t, n, rightType, message, getNativeType(STRING_TYPE)); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.IN: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right); validator.expectObject(t, n, rightType, "'in' requires an object"); validator.expectString(t, left, leftType, "left side of 'in'"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.INSTANCEOF: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right).restrictByNotNullOrUndefined(); validator.expectAnyObject( t, left, leftType, "deterministic instanceof yields false"); validator.expectActualObject( t, right, rightType, "instanceof requires an object"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.ASSIGN: visitAssign(t, n); typeable = false; break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_SUB: case Token.ASSIGN_ADD: case Token.ASSIGN_MUL: case Token.LSH: case Token.RSH: case Token.URSH: case Token.DIV: case Token.MOD: case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.SUB: case Token.ADD: case Token.MUL: visitBinaryOperator(n.getType(), t, n); break; case Token.DELPROP: if (!isReference(n.getFirstChild())) { report(t, n, BAD_DELETE); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.CASE: JSType switchType = getJSType(parent.getFirstChild()); JSType caseType = getJSType(n.getFirstChild()); validator.expectSwitchMatchesCase(t, n, switchType, caseType); typeable = false; break; case Token.WITH: { Node child = n.getFirstChild(); childType = getJSType(child); validator.expectObject( t, child, childType, "with requires an object"); typeable = false; break; } case Token.FUNCTION: visitFunction(t, n); break; case Token.LABEL: case Token.LABEL_NAME: case Token.SWITCH: case Token.BREAK: case Token.CATCH: case Token.TRY: case Token.SCRIPT: case Token.EXPR_RESULT: case Token.BLOCK: case Token.EMPTY: case Token.DEFAULT: case Token.CONTINUE: case Token.DEBUGGER: case Token.THROW: typeable = false; break; case Token.DO: case Token.FOR: case Token.IF: case Token.WHILE: typeable = false; break; case Token.AND: case Token.HOOK: case Token.OBJECTLIT: case Token.OR: if (n.getJSType() != null) { ensureTyped(t, n); } else { if ((n.getType() == Token.OBJECTLIT) && (parent.getJSType() instanceof EnumType)) { ensureTyped(t, n, parent.getJSType()); } else { ensureTyped(t, n); } } if (n.getType() == Token.OBJECTLIT) { for (Node key : n.children()) { visitObjLitKey(t, key, n); } } break; default: report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType())); ensureTyped(t, n); break; } typeable = typeable && !inExterns; if (typeable) { doPercentTypedAccounting(t, n); } checkNoTypeCheckSection(n, false); }
public void visit(NodeTraversal t, Node n, Node parent) { JSType childType; JSType leftType, rightType; Node left, right; boolean typeable = true; switch (n.getType()) { case Token.NAME: typeable = visitName(t, n, parent); break; case Token.LP: if (parent.getType() != Token.FUNCTION) { ensureTyped(t, n, getJSType(n.getFirstChild())); } else { typeable = false; } break; case Token.COMMA: ensureTyped(t, n, getJSType(n.getLastChild())); break; case Token.TRUE: case Token.FALSE: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.THIS: ensureTyped(t, n, t.getScope().getTypeOfThis()); break; case Token.REF_SPECIAL: ensureTyped(t, n); break; case Token.GET_REF: ensureTyped(t, n, getJSType(n.getFirstChild())); break; case Token.NULL: ensureTyped(t, n, NULL_TYPE); break; case Token.NUMBER: ensureTyped(t, n, NUMBER_TYPE); break; case Token.STRING: if (!NodeUtil.isObjectLitKey(n, n.getParent())) { ensureTyped(t, n, STRING_TYPE); } else { typeable = false; } break; case Token.GET: case Token.SET: break; case Token.ARRAYLIT: ensureTyped(t, n, ARRAY_TYPE); break; case Token.REGEXP: ensureTyped(t, n, REGEXP_TYPE); break; case Token.GETPROP: visitGetProp(t, n, parent); typeable = !(parent.getType() == Token.ASSIGN && parent.getFirstChild() == n); break; case Token.GETELEM: visitGetElem(t, n); typeable = false; break; case Token.VAR: visitVar(t, n); typeable = false; break; case Token.NEW: visitNew(t, n); typeable = true; break; case Token.CALL: visitCall(t, n); typeable = !NodeUtil.isExpressionNode(parent); break; case Token.RETURN: visitReturn(t, n); typeable = false; break; case Token.DEC: case Token.INC: left = n.getFirstChild(); validator.expectNumber( t, left, getJSType(left), "increment/decrement"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.NOT: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.VOID: ensureTyped(t, n, VOID_TYPE); break; case Token.TYPEOF: ensureTyped(t, n, STRING_TYPE); break; case Token.BITNOT: childType = getJSType(n.getFirstChild()); if (!childType.matchesInt32Context()) { report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()), childType.toString()); } ensureTyped(t, n, NUMBER_TYPE); break; case Token.POS: case Token.NEG: left = n.getFirstChild(); validator.expectNumber(t, left, getJSType(left), "sign operator"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.EQ: case Token.NE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); TernaryValue result = leftTypeRestricted.testForEquality(rightTypeRestricted); if (result != TernaryValue.UNKNOWN) { if (n.getType() == Token.NE) { result = result.not(); } report(t, n, DETERMINISTIC_TEST, leftType.toString(), rightType.toString(), result.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.SHEQ: case Token.SHNE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); if (!leftTypeRestricted.canTestForShallowEqualityWith( rightTypeRestricted)) { report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(), rightType.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.LT: case Token.LE: case Token.GT: case Token.GE: leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); if (rightType.isNumber()) { validator.expectNumber( t, n, leftType, "left side of numeric comparison"); } else if (leftType.isNumber()) { validator.expectNumber( t, n, rightType, "right side of numeric comparison"); } else if (leftType.matchesNumberContext() && rightType.matchesNumberContext()) { } else { String message = "left side of comparison"; validator.expectString(t, n, leftType, message); validator.expectNotNullOrUndefined( t, n, leftType, message, getNativeType(STRING_TYPE)); message = "right side of comparison"; validator.expectString(t, n, rightType, message); validator.expectNotNullOrUndefined( t, n, rightType, message, getNativeType(STRING_TYPE)); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.IN: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right); validator.expectObject(t, n, rightType, "'in' requires an object"); validator.expectString(t, left, leftType, "left side of 'in'"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.INSTANCEOF: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right).restrictByNotNullOrUndefined(); validator.expectAnyObject( t, left, leftType, "deterministic instanceof yields false"); validator.expectActualObject( t, right, rightType, "instanceof requires an object"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.ASSIGN: visitAssign(t, n); typeable = false; break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_SUB: case Token.ASSIGN_ADD: case Token.ASSIGN_MUL: case Token.LSH: case Token.RSH: case Token.URSH: case Token.DIV: case Token.MOD: case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.SUB: case Token.ADD: case Token.MUL: visitBinaryOperator(n.getType(), t, n); break; case Token.DELPROP: if (!isReference(n.getFirstChild())) { report(t, n, BAD_DELETE); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.CASE: JSType switchType = getJSType(parent.getFirstChild()); JSType caseType = getJSType(n.getFirstChild()); validator.expectSwitchMatchesCase(t, n, switchType, caseType); typeable = false; break; case Token.WITH: { Node child = n.getFirstChild(); childType = getJSType(child); validator.expectObject( t, child, childType, "with requires an object"); typeable = false; break; } case Token.FUNCTION: visitFunction(t, n); break; case Token.LABEL: case Token.LABEL_NAME: case Token.SWITCH: case Token.BREAK: case Token.CATCH: case Token.TRY: case Token.SCRIPT: case Token.EXPR_RESULT: case Token.BLOCK: case Token.EMPTY: case Token.DEFAULT: case Token.CONTINUE: case Token.DEBUGGER: case Token.THROW: typeable = false; break; case Token.DO: case Token.FOR: case Token.IF: case Token.WHILE: typeable = false; break; case Token.AND: case Token.HOOK: case Token.OBJECTLIT: case Token.OR: if (n.getJSType() != null) { ensureTyped(t, n); } else { if ((n.getType() == Token.OBJECTLIT) && (parent.getJSType() instanceof EnumType)) { ensureTyped(t, n, parent.getJSType()); } else { ensureTyped(t, n); } } if (n.getType() == Token.OBJECTLIT) { for (Node key : n.children()) { visitObjLitKey(t, key, n); } } break; default: report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType())); ensureTyped(t, n); break; } typeable = typeable && !inExterns; if (typeable) { doPercentTypedAccounting(t, n); } checkNoTypeCheckSection(n, false); }
Closure-23
private Node tryFoldArrayAccess(Node n, Node left, Node right) { Node parent = n.getParent(); if (isAssignmentTarget(n)) { return n; } if (!right.isNumber()) { return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node current = left.getFirstChild(); Node elem = null; for (int i = 0; current != null && i < intIndex; i++) { elem = current; current = current.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.isEmpty()) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
private Node tryFoldArrayAccess(Node n, Node left, Node right) { Node parent = n.getParent(); if (isAssignmentTarget(n)) { return n; } if (!right.isNumber()) { return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node current = left.getFirstChild(); Node elem = null; for (int i = 0; current != null; i++) { if (i != intIndex) { if (mayHaveSideEffects(current)) { return n; } } else { elem = current; } current = current.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.isEmpty()) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }