bug_id
stringlengths
5
19
func_before
stringlengths
49
25.9k
func_after
stringlengths
45
26k
Closure-170
private void getNumUseInUseCfgNode(final Node cfgNode) { numUsesWithinCfgNode = 0; AbstractCfgNodeTraversalCallback gatherCb = new AbstractCfgNodeTraversalCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName() && n.getString().equals(varName) && !(parent.isAssign() && (parent.getFirstChild() == n))) { numUsesWithinCfgNode++; } } }; NodeTraversal.traverse(compiler, cfgNode, gatherCb); }
private void getNumUseInUseCfgNode(final Node cfgNode) { numUsesWithinCfgNode = 0; AbstractCfgNodeTraversalCallback gatherCb = new AbstractCfgNodeTraversalCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isName() && n.getString().equals(varName)) { if (parent.isAssign() && (parent.getFirstChild() == n) && isAssignChain(parent, cfgNode)) { return; } else { numUsesWithinCfgNode++; } } } private boolean isAssignChain(Node child, Node ancestor) { for (Node n = child; n != ancestor; n = n.getParent()) { if (!n.isAssign()) { return false; } } return true; } }; NodeTraversal.traverse(compiler, cfgNode, gatherCb); }
Lang-18
protected List<Rule> parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List<Rule> rules = new ArrayList<Rule>(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': rule = new TextField(Calendar.ERA, ERAs); break; case 'y': if (tokenLen >= 4) { rule = selectNumberRule(Calendar.YEAR, tokenLen); } else { rule = TwoDigitYearField.INSTANCE; } break; case 'M': if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); } break; case 'Z': if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; }
protected List<Rule> parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List<Rule> rules = new ArrayList<Rule>(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': rule = new TextField(Calendar.ERA, ERAs); break; case 'y': if (tokenLen == 2) { rule = TwoDigitYearField.INSTANCE; } else { rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); } break; case 'M': if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); } break; case 'Z': if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; }
Closure-115
private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); boolean hasSideEffects = false; if (block.hasChildren()) { Preconditions.checkState(block.hasOneChild()); Node stmt = block.getFirstChild(); if (stmt.isReturn()) { hasSideEffects = NodeUtil.mayHaveSideEffects(stmt.getFirstChild(), compiler); } } Node cArg = callNode.getFirstChild().getNext(); if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { if (fnParam != null) { if (cArg != null) { if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) { return CanInlineResult.NO; } if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } fnParam = fnParam.getNext(); } if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; }
private CanInlineResult canInlineReferenceDirectly( Node callNode, Node fnNode) { if (!isDirectCallNodeReplacementPossible(fnNode)) { return CanInlineResult.NO; } Node block = fnNode.getLastChild(); Node cArg = callNode.getFirstChild().getNext(); if (!callNode.getFirstChild().isName()) { if (NodeUtil.isFunctionObjectCall(callNode)) { if (cArg == null || !cArg.isThis()) { return CanInlineResult.NO; } cArg = cArg.getNext(); } else { Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode)); } } Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); while (cArg != null || fnParam != null) { if (fnParam != null) { if (cArg != null) { if (NodeUtil.mayEffectMutableState(cArg, compiler) && NodeUtil.getNameReferenceCount( block, fnParam.getString()) > 1) { return CanInlineResult.NO; } } fnParam = fnParam.getNext(); } if (cArg != null) { if (NodeUtil.mayHaveSideEffects(cArg, compiler)) { return CanInlineResult.NO; } cArg = cArg.getNext(); } } return CanInlineResult.YES; }
Closure-159
private void findCalledFunctions( Node node, Set<String> changed) { Preconditions.checkArgument(changed != null); if (node.getType() == Token.CALL) { Node child = node.getFirstChild(); if (child.getType() == Token.NAME) { changed.add(child.getString()); } } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { findCalledFunctions(c, changed); } }
private void findCalledFunctions( Node node, Set<String> changed) { Preconditions.checkArgument(changed != null); if (node.getType() == Token.NAME) { if (isCandidateUsage(node)) { changed.add(node.getString()); } } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { findCalledFunctions(c, changed); } }
Chart-7
private void updateBounds(TimePeriod period, int index) { long start = period.getStart().getTime(); long end = period.getEnd().getTime(); long middle = start + ((end - start) / 2); if (this.minStartIndex >= 0) { long minStart = getDataItem(this.minStartIndex).getPeriod() .getStart().getTime(); if (start < minStart) { this.minStartIndex = index; } } else { this.minStartIndex = index; } if (this.maxStartIndex >= 0) { long maxStart = getDataItem(this.maxStartIndex).getPeriod() .getStart().getTime(); if (start > maxStart) { this.maxStartIndex = index; } } else { this.maxStartIndex = index; } if (this.minMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long minMiddle = s + (e - s) / 2; if (middle < minMiddle) { this.minMiddleIndex = index; } } else { this.minMiddleIndex = index; } if (this.maxMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long maxMiddle = s + (e - s) / 2; if (middle > maxMiddle) { this.maxMiddleIndex = index; } } else { this.maxMiddleIndex = index; } if (this.minEndIndex >= 0) { long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd() .getTime(); if (end < minEnd) { this.minEndIndex = index; } } else { this.minEndIndex = index; } if (this.maxEndIndex >= 0) { long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd() .getTime(); if (end > maxEnd) { this.maxEndIndex = index; } } else { this.maxEndIndex = index; } }
private void updateBounds(TimePeriod period, int index) { long start = period.getStart().getTime(); long end = period.getEnd().getTime(); long middle = start + ((end - start) / 2); if (this.minStartIndex >= 0) { long minStart = getDataItem(this.minStartIndex).getPeriod() .getStart().getTime(); if (start < minStart) { this.minStartIndex = index; } } else { this.minStartIndex = index; } if (this.maxStartIndex >= 0) { long maxStart = getDataItem(this.maxStartIndex).getPeriod() .getStart().getTime(); if (start > maxStart) { this.maxStartIndex = index; } } else { this.maxStartIndex = index; } if (this.minMiddleIndex >= 0) { long s = getDataItem(this.minMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd() .getTime(); long minMiddle = s + (e - s) / 2; if (middle < minMiddle) { this.minMiddleIndex = index; } } else { this.minMiddleIndex = index; } if (this.maxMiddleIndex >= 0) { long s = getDataItem(this.maxMiddleIndex).getPeriod().getStart() .getTime(); long e = getDataItem(this.maxMiddleIndex).getPeriod().getEnd() .getTime(); long maxMiddle = s + (e - s) / 2; if (middle > maxMiddle) { this.maxMiddleIndex = index; } } else { this.maxMiddleIndex = index; } if (this.minEndIndex >= 0) { long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd() .getTime(); if (end < minEnd) { this.minEndIndex = index; } } else { this.minEndIndex = index; } if (this.maxEndIndex >= 0) { long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd() .getTime(); if (end > maxEnd) { this.maxEndIndex = index; } } else { this.maxEndIndex = index; } }
Jsoup-48
void processResponseHeaders(Map<String, List<String>> resHeaders) { for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { if (!values.isEmpty()) header(name, values.get(0)); } } }
void processResponseHeaders(Map<String, List<String>> resHeaders) { for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { if (values.size() == 1) header(name, values.get(0)); else if (values.size() > 1) { StringBuilder accum = new StringBuilder(); for (int i = 0; i < values.size(); i++) { final String val = values.get(i); if (i != 0) accum.append(", "); accum.append(val); } header(name, accum.toString()); } } } }
Closure-109
private Node parseContextTypeExpression(JsDocToken token) { return parseTypeName(token); }
private Node parseContextTypeExpression(JsDocToken token) { if (token == JsDocToken.QMARK) { return newNode(Token.QMARK); } else { return parseBasicTypeExpression(token); } }
Closure-70
private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), true); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } }
private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), false); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } }
Closure-129
private void annotateCalls(Node n) { Preconditions.checkState(n.isCall()); Node first = n.getFirstChild(); if (!NodeUtil.isGet(first)) { n.putBooleanProp(Node.FREE_CALL, true); } if (first.isName() && "eval".equals(first.getString())) { first.putBooleanProp(Node.DIRECT_EVAL, true); } }
private void annotateCalls(Node n) { Preconditions.checkState(n.isCall()); Node first = n.getFirstChild(); while (first.isCast()) { first = first.getFirstChild(); } if (!NodeUtil.isGet(first)) { n.putBooleanProp(Node.FREE_CALL, true); } if (first.isName() && "eval".equals(first.getString())) { first.putBooleanProp(Node.DIRECT_EVAL, true); } }
Gson-17
public Date read(JsonReader in) throws IOException { if (in.peek() != JsonToken.STRING) { throw new JsonParseException("The date should be a string value"); } Date date = deserializeToDate(in.nextString()); if (dateType == Date.class) { return date; } else if (dateType == Timestamp.class) { return new Timestamp(date.getTime()); } else if (dateType == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } else { throw new AssertionError(); } }
public Date read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } Date date = deserializeToDate(in.nextString()); if (dateType == Date.class) { return date; } else if (dateType == Timestamp.class) { return new Timestamp(date.getTime()); } else if (dateType == java.sql.Date.class) { return new java.sql.Date(date.getTime()); } else { throw new AssertionError(); } }
Compress-32
private void applyPaxHeadersToCurrentEntry(Map<String, String> headers) { for (Entry<String, String> ent : headers.entrySet()){ String key = ent.getKey(); String val = ent.getValue(); if ("path".equals(key)){ currEntry.setName(val); } else if ("linkpath".equals(key)){ currEntry.setLinkName(val); } else if ("gid".equals(key)){ currEntry.setGroupId(Integer.parseInt(val)); } else if ("gname".equals(key)){ currEntry.setGroupName(val); } else if ("uid".equals(key)){ currEntry.setUserId(Integer.parseInt(val)); } else if ("uname".equals(key)){ currEntry.setUserName(val); } else if ("size".equals(key)){ currEntry.setSize(Long.parseLong(val)); } else if ("mtime".equals(key)){ currEntry.setModTime((long) (Double.parseDouble(val) * 1000)); } else if ("SCHILY.devminor".equals(key)){ currEntry.setDevMinor(Integer.parseInt(val)); } else if ("SCHILY.devmajor".equals(key)){ currEntry.setDevMajor(Integer.parseInt(val)); } } }
private void applyPaxHeadersToCurrentEntry(Map<String, String> headers) { for (Entry<String, String> ent : headers.entrySet()){ String key = ent.getKey(); String val = ent.getValue(); if ("path".equals(key)){ currEntry.setName(val); } else if ("linkpath".equals(key)){ currEntry.setLinkName(val); } else if ("gid".equals(key)){ currEntry.setGroupId(Long.parseLong(val)); } else if ("gname".equals(key)){ currEntry.setGroupName(val); } else if ("uid".equals(key)){ currEntry.setUserId(Long.parseLong(val)); } else if ("uname".equals(key)){ currEntry.setUserName(val); } else if ("size".equals(key)){ currEntry.setSize(Long.parseLong(val)); } else if ("mtime".equals(key)){ currEntry.setModTime((long) (Double.parseDouble(val) * 1000)); } else if ("SCHILY.devminor".equals(key)){ currEntry.setDevMinor(Integer.parseInt(val)); } else if ("SCHILY.devmajor".equals(key)){ currEntry.setDevMajor(Integer.parseInt(val)); } } }
JacksonDatabind-51
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { JavaType type = _idResolver.typeFromId(ctxt, typeId); if (type == null) { deser = _findDefaultImplDeserializer(ctxt); if (deser == null) { JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType); if (actual == null) { return null; } deser = ctxt.findContextualValueDeserializer(actual, _property); } } else { if ((_baseType != null) && _baseType.getClass() == type.getClass()) { type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass()); } deser = ctxt.findContextualValueDeserializer(type, _property); } _deserializers.put(typeId, deser); } return deser; }
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { JavaType type = _idResolver.typeFromId(ctxt, typeId); if (type == null) { deser = _findDefaultImplDeserializer(ctxt); if (deser == null) { JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType); if (actual == null) { return null; } deser = ctxt.findContextualValueDeserializer(actual, _property); } } else { if ((_baseType != null) && _baseType.getClass() == type.getClass()) { if (!type.hasGenericTypes()) { type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass()); } } deser = ctxt.findContextualValueDeserializer(type, _property); } _deserializers.put(typeId, deser); } return deser; }
Jsoup-5
private Attribute parseAttribute() { tq.consumeWhitespace(); String key = tq.consumeAttributeKey(); String value = ""; tq.consumeWhitespace(); if (tq.matchChomp("=")) { tq.consumeWhitespace(); if (tq.matchChomp(SQ)) { value = tq.chompTo(SQ); } else if (tq.matchChomp(DQ)) { value = tq.chompTo(DQ); } else { StringBuilder valueAccum = new StringBuilder(); while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) { valueAccum.append(tq.consume()); } value = valueAccum.toString(); } tq.consumeWhitespace(); } if (key.length() != 0) return Attribute.createFromEncoded(key, value); else { tq.consume(); return null; } }
private Attribute parseAttribute() { tq.consumeWhitespace(); String key = tq.consumeAttributeKey(); String value = ""; tq.consumeWhitespace(); if (tq.matchChomp("=")) { tq.consumeWhitespace(); if (tq.matchChomp(SQ)) { value = tq.chompTo(SQ); } else if (tq.matchChomp(DQ)) { value = tq.chompTo(DQ); } else { StringBuilder valueAccum = new StringBuilder(); while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) { valueAccum.append(tq.consume()); } value = valueAccum.toString(); } tq.consumeWhitespace(); } if (key.length() != 0) return Attribute.createFromEncoded(key, value); else { if (value.length() == 0) tq.advance(); return null; } }
Jsoup-47
static void escape(StringBuilder accum, String string, Document.OutputSettings out, boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) { boolean lastWasWhite = false; boolean reachedNonWhite = false; final EscapeMode escapeMode = out.escapeMode(); final CharsetEncoder encoder = out.encoder(); final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name()); final Map<Character, String> map = escapeMode.getMap(); final int length = string.length(); int codePoint; for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) { codePoint = string.codePointAt(offset); if (normaliseWhite) { if (StringUtil.isWhitespace(codePoint)) { if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) continue; accum.append(' '); lastWasWhite = true; continue; } else { lastWasWhite = false; reachedNonWhite = true; } } if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) { final char c = (char) codePoint; switch (c) { case '&': accum.append("&amp;"); break; case 0xA0: if (escapeMode != EscapeMode.xhtml) accum.append("&nbsp;"); else accum.append("&#xa0;"); break; case '<': if (!inAttribute) accum.append("&lt;"); else accum.append(c); break; case '>': if (!inAttribute) accum.append("&gt;"); else accum.append(c); break; case '"': if (inAttribute) accum.append("&quot;"); else accum.append(c); break; default: if (canEncode(coreCharset, c, encoder)) accum.append(c); else if (map.containsKey(c)) accum.append('&').append(map.get(c)).append(';'); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } else { final String c = new String(Character.toChars(codePoint)); if (encoder.canEncode(c)) accum.append(c); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } }
static void escape(StringBuilder accum, String string, Document.OutputSettings out, boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) { boolean lastWasWhite = false; boolean reachedNonWhite = false; final EscapeMode escapeMode = out.escapeMode(); final CharsetEncoder encoder = out.encoder(); final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name()); final Map<Character, String> map = escapeMode.getMap(); final int length = string.length(); int codePoint; for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) { codePoint = string.codePointAt(offset); if (normaliseWhite) { if (StringUtil.isWhitespace(codePoint)) { if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) continue; accum.append(' '); lastWasWhite = true; continue; } else { lastWasWhite = false; reachedNonWhite = true; } } if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) { final char c = (char) codePoint; switch (c) { case '&': accum.append("&amp;"); break; case 0xA0: if (escapeMode != EscapeMode.xhtml) accum.append("&nbsp;"); else accum.append("&#xa0;"); break; case '<': if (!inAttribute || escapeMode == EscapeMode.xhtml) accum.append("&lt;"); else accum.append(c); break; case '>': if (!inAttribute) accum.append("&gt;"); else accum.append(c); break; case '"': if (inAttribute) accum.append("&quot;"); else accum.append(c); break; default: if (canEncode(coreCharset, c, encoder)) accum.append(c); else if (map.containsKey(c)) accum.append('&').append(map.get(c)).append(';'); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } else { final String c = new String(Character.toChars(codePoint)); if (encoder.canEncode(c)) accum.append(c); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } }
JacksonDatabind-71
public static StdKeyDeserializer forType(Class<?> raw) { int kind; if (raw == String.class || raw == Object.class) { return StringKD.forType(raw); } else if (raw == UUID.class) { kind = TYPE_UUID; } else if (raw == Integer.class) { kind = TYPE_INT; } else if (raw == Long.class) { kind = TYPE_LONG; } else if (raw == Date.class) { kind = TYPE_DATE; } else if (raw == Calendar.class) { kind = TYPE_CALENDAR; } else if (raw == Boolean.class) { kind = TYPE_BOOLEAN; } else if (raw == Byte.class) { kind = TYPE_BYTE; } else if (raw == Character.class) { kind = TYPE_CHAR; } else if (raw == Short.class) { kind = TYPE_SHORT; } else if (raw == Float.class) { kind = TYPE_FLOAT; } else if (raw == Double.class) { kind = TYPE_DOUBLE; } else if (raw == URI.class) { kind = TYPE_URI; } else if (raw == URL.class) { kind = TYPE_URL; } else if (raw == Class.class) { kind = TYPE_CLASS; } else if (raw == Locale.class) { FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Locale.class); return new StdKeyDeserializer(TYPE_LOCALE, raw, deser); } else if (raw == Currency.class) { FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Currency.class); return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser); } else { return null; } return new StdKeyDeserializer(kind, raw); }
public static StdKeyDeserializer forType(Class<?> raw) { int kind; if (raw == String.class || raw == Object.class || raw == CharSequence.class) { return StringKD.forType(raw); } else if (raw == UUID.class) { kind = TYPE_UUID; } else if (raw == Integer.class) { kind = TYPE_INT; } else if (raw == Long.class) { kind = TYPE_LONG; } else if (raw == Date.class) { kind = TYPE_DATE; } else if (raw == Calendar.class) { kind = TYPE_CALENDAR; } else if (raw == Boolean.class) { kind = TYPE_BOOLEAN; } else if (raw == Byte.class) { kind = TYPE_BYTE; } else if (raw == Character.class) { kind = TYPE_CHAR; } else if (raw == Short.class) { kind = TYPE_SHORT; } else if (raw == Float.class) { kind = TYPE_FLOAT; } else if (raw == Double.class) { kind = TYPE_DOUBLE; } else if (raw == URI.class) { kind = TYPE_URI; } else if (raw == URL.class) { kind = TYPE_URL; } else if (raw == Class.class) { kind = TYPE_CLASS; } else if (raw == Locale.class) { FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Locale.class); return new StdKeyDeserializer(TYPE_LOCALE, raw, deser); } else if (raw == Currency.class) { FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Currency.class); return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser); } else { return null; } return new StdKeyDeserializer(kind, raw); }
Closure-124
private boolean isSafeReplacement(Node node, Node replacement) { if (node.isName()) { return true; } Preconditions.checkArgument(node.isGetProp()); node = node.getFirstChild(); if (node.isName() && isNameAssignedTo(node.getString(), replacement)) { return false; } return true; }
private boolean isSafeReplacement(Node node, Node replacement) { if (node.isName()) { return true; } Preconditions.checkArgument(node.isGetProp()); while (node.isGetProp()) { node = node.getFirstChild(); } if (node.isName() && isNameAssignedTo(node.getString(), replacement)) { return false; } return true; }
Jsoup-41
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Element element = (Element) o; return this == o; }
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Element element = (Element) o; return tag.equals(element.tag); }
Mockito-8
protected void registerTypeVariablesOn(Type classType) { if (!(classType instanceof ParameterizedType)) { return; } ParameterizedType parameterizedType = (ParameterizedType) classType; TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < actualTypeArguments.length; i++) { TypeVariable typeParameter = typeParameters[i]; Type actualTypeArgument = actualTypeArguments[i]; if (actualTypeArgument instanceof WildcardType) { contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument)); } else { contextualActualTypeParameters.put(typeParameter, actualTypeArgument); } } }
protected void registerTypeVariablesOn(Type classType) { if (!(classType instanceof ParameterizedType)) { return; } ParameterizedType parameterizedType = (ParameterizedType) classType; TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < actualTypeArguments.length; i++) { TypeVariable typeParameter = typeParameters[i]; Type actualTypeArgument = actualTypeArguments[i]; if (actualTypeArgument instanceof WildcardType) { contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument)); } else if (typeParameter != actualTypeArgument) { contextualActualTypeParameters.put(typeParameter, actualTypeArgument); } } }
JacksonCore-8
public char[] getTextBuffer() { if (_inputStart >= 0) return _inputBuffer; if (_resultArray != null) return _resultArray; if (_resultString != null) { return (_resultArray = _resultString.toCharArray()); } if (!_hasSegments) return _currentSegment; return contentsAsArray(); }
public char[] getTextBuffer() { if (_inputStart >= 0) return _inputBuffer; if (_resultArray != null) return _resultArray; if (_resultString != null) { return (_resultArray = _resultString.toCharArray()); } if (!_hasSegments && _currentSegment != null) return _currentSegment; return contentsAsArray(); }
Cli-17
protected void burstToken(String token, boolean stopAtNonOption) { for (int i = 1; i < token.length(); i++) { String ch = String.valueOf(token.charAt(i)); if (options.hasOption(ch)) { tokens.add("-" + ch); currentOption = options.getOption(ch); if (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); } else { tokens.add(token); break; } } }
protected void burstToken(String token, boolean stopAtNonOption) { for (int i = 1; i < token.length(); i++) { String ch = String.valueOf(token.charAt(i)); if (options.hasOption(ch)) { tokens.add("-" + ch); currentOption = options.getOption(ch); if (currentOption.hasArg() && (token.length() != (i + 1))) { tokens.add(token.substring(i + 1)); break; } } else if (stopAtNonOption) { process(token.substring(i)); break; } else { tokens.add(token); break; } } }
Math-86
public CholeskyDecompositionImpl(final RealMatrix matrix, final double relativeSymmetryThreshold, final double absolutePositivityThreshold) throws NonSquareMatrixException, NotSymmetricMatrixException, NotPositiveDefiniteMatrixException { if (!matrix.isSquare()) { throw new NonSquareMatrixException(matrix.getRowDimension(), matrix.getColumnDimension()); } final int order = matrix.getRowDimension(); lTData = matrix.getData(); cachedL = null; cachedLT = null; for (int i = 0; i < order; ++i) { final double[] lI = lTData[i]; if (lTData[i][i] < absolutePositivityThreshold) { throw new NotPositiveDefiniteMatrixException(); } for (int j = i + 1; j < order; ++j) { final double[] lJ = lTData[j]; final double lIJ = lI[j]; final double lJI = lJ[i]; final double maxDelta = relativeSymmetryThreshold * Math.max(Math.abs(lIJ), Math.abs(lJI)); if (Math.abs(lIJ - lJI) > maxDelta) { throw new NotSymmetricMatrixException(); } lJ[i] = 0; } } for (int i = 0; i < order; ++i) { final double[] ltI = lTData[i]; ltI[i] = Math.sqrt(ltI[i]); final double inverse = 1.0 / ltI[i]; for (int q = order - 1; q > i; --q) { ltI[q] *= inverse; final double[] ltQ = lTData[q]; for (int p = q; p < order; ++p) { ltQ[p] -= ltI[q] * ltI[p]; } } } }
public CholeskyDecompositionImpl(final RealMatrix matrix, final double relativeSymmetryThreshold, final double absolutePositivityThreshold) throws NonSquareMatrixException, NotSymmetricMatrixException, NotPositiveDefiniteMatrixException { if (!matrix.isSquare()) { throw new NonSquareMatrixException(matrix.getRowDimension(), matrix.getColumnDimension()); } final int order = matrix.getRowDimension(); lTData = matrix.getData(); cachedL = null; cachedLT = null; for (int i = 0; i < order; ++i) { final double[] lI = lTData[i]; for (int j = i + 1; j < order; ++j) { final double[] lJ = lTData[j]; final double lIJ = lI[j]; final double lJI = lJ[i]; final double maxDelta = relativeSymmetryThreshold * Math.max(Math.abs(lIJ), Math.abs(lJI)); if (Math.abs(lIJ - lJI) > maxDelta) { throw new NotSymmetricMatrixException(); } lJ[i] = 0; } } for (int i = 0; i < order; ++i) { final double[] ltI = lTData[i]; if (ltI[i] < absolutePositivityThreshold) { throw new NotPositiveDefiniteMatrixException(); } ltI[i] = Math.sqrt(ltI[i]); final double inverse = 1.0 / ltI[i]; for (int q = order - 1; q > i; --q) { ltI[q] *= inverse; final double[] ltQ = lTData[q]; for (int p = q; p < order; ++p) { ltQ[p] -= ltI[q] * ltI[p]; } } } }
Closure-83
public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } }
public int parseArguments(Parameters params) throws CmdLineException { String param = null; try { param = params.getParameter(0); } catch (CmdLineException e) {} if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } }
Jsoup-61
public boolean hasClass(String className) { final String classAttr = attributes.get("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } if (len == wantLen) { return className.equalsIgnoreCase(classAttr); } boolean inClass = false; int start = 0; for (int i = 0; i < len; i++) { if (Character.isWhitespace(classAttr.charAt(i))) { if (inClass) { if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) { return true; } inClass = false; } } else { if (!inClass) { inClass = true; start = i; } } } if (inClass && len - start == wantLen) { return classAttr.regionMatches(true, start, className, 0, wantLen); } return false; }
public boolean hasClass(String className) { final String classAttr = attributes.getIgnoreCase("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } if (len == wantLen) { return className.equalsIgnoreCase(classAttr); } boolean inClass = false; int start = 0; for (int i = 0; i < len; i++) { if (Character.isWhitespace(classAttr.charAt(i))) { if (inClass) { if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) { return true; } inClass = false; } } else { if (!inClass) { inClass = true; start = i; } } } if (inClass && len - start == wantLen) { return classAttr.regionMatches(true, start, className, 0, wantLen); } return false; }
Closure-32
private ExtractionInfo extractMultilineTextualBlock(JsDocToken token, WhitespaceOption option) { if (token == JsDocToken.EOC || token == JsDocToken.EOL || token == JsDocToken.EOF) { return new ExtractionInfo("", token); } stream.update(); int startLineno = stream.getLineno(); int startCharno = stream.getCharno() + 1; String line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = line.trim(); } StringBuilder builder = new StringBuilder(); builder.append(line); state = State.SEARCHING_ANNOTATION; token = next(); boolean ignoreStar = false; do { switch (token) { case STAR: if (ignoreStar) { } else { if (builder.length() > 0) { builder.append(' '); } builder.append('*'); } token = next(); continue; case EOL: if (option != WhitespaceOption.SINGLE_LINE) { builder.append("\n"); } ignoreStar = true; token = next(); continue; default: ignoreStar = false; state = State.SEARCHING_ANNOTATION; if (token == JsDocToken.EOC || token == JsDocToken.EOF || (token == JsDocToken.ANNOTATION && option != WhitespaceOption.PRESERVE)) { String multilineText = builder.toString(); if (option != WhitespaceOption.PRESERVE) { multilineText = multilineText.trim(); } int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); if (multilineText.length() > 0) { jsdocBuilder.markText(multilineText, startLineno, startCharno, endLineno, endCharno); } return new ExtractionInfo(multilineText, token); } if (builder.length() > 0) { builder.append(' '); } builder.append(toString(token)); line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = trimEnd(line); } builder.append(line); token = next(); } } while (true); }
private ExtractionInfo extractMultilineTextualBlock(JsDocToken token, WhitespaceOption option) { if (token == JsDocToken.EOC || token == JsDocToken.EOL || token == JsDocToken.EOF) { return new ExtractionInfo("", token); } stream.update(); int startLineno = stream.getLineno(); int startCharno = stream.getCharno() + 1; String line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = line.trim(); } StringBuilder builder = new StringBuilder(); builder.append(line); state = State.SEARCHING_ANNOTATION; token = next(); boolean ignoreStar = false; int lineStartChar = -1; do { switch (token) { case STAR: if (ignoreStar) { lineStartChar = stream.getCharno() + 1; } else { if (builder.length() > 0) { builder.append(' '); } builder.append('*'); } token = next(); continue; case EOL: if (option != WhitespaceOption.SINGLE_LINE) { builder.append("\n"); } ignoreStar = true; lineStartChar = 0; token = next(); continue; default: ignoreStar = false; state = State.SEARCHING_ANNOTATION; boolean isEOC = token == JsDocToken.EOC; if (!isEOC) { if (lineStartChar != -1 && option == WhitespaceOption.PRESERVE) { int numSpaces = stream.getCharno() - lineStartChar; for (int i = 0; i < numSpaces; i++) { builder.append(' '); } lineStartChar = -1; } else if (builder.length() > 0) { builder.append(' '); } } if (token == JsDocToken.EOC || token == JsDocToken.EOF || (token == JsDocToken.ANNOTATION && option != WhitespaceOption.PRESERVE)) { String multilineText = builder.toString(); if (option != WhitespaceOption.PRESERVE) { multilineText = multilineText.trim(); } int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); if (multilineText.length() > 0) { jsdocBuilder.markText(multilineText, startLineno, startCharno, endLineno, endCharno); } return new ExtractionInfo(multilineText, token); } builder.append(toString(token)); line = stream.getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = trimEnd(line); } builder.append(line); token = next(); } } while (true); }
Math-53
public Complex add(Complex rhs) throws NullArgumentException { MathUtils.checkNotNull(rhs); return createComplex(real + rhs.getReal(), imaginary + rhs.getImaginary()); }
public Complex add(Complex rhs) throws NullArgumentException { MathUtils.checkNotNull(rhs); if (isNaN || rhs.isNaN) { return NaN; } return createComplex(real + rhs.getReal(), imaginary + rhs.getImaginary()); }
Math-28
private Integer getPivotRow(SimplexTableau tableau, final int col) { List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && minRow != row; i++) { if (row == tableau.getBasicRow(i)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } return minRatioPositions.get(0); }
private Integer getPivotRow(SimplexTableau tableau, final int col) { List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && minRow != row; i++) { if (row == tableau.getBasicRow(i)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
Closure-128
static boolean isSimpleNumber(String s) { int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len > 0 && s.charAt(0) != '0'; }
static boolean isSimpleNumber(String s) { int len = s.length(); if (len == 0) { return false; } for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len == 1 || s.charAt(0) != '0'; }
Compress-37
Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); while(true){ int ch; int len = 0; int read = 0; while((ch = i.read()) != -1) { read++; if (ch == ' '){ final ByteArrayOutputStream coll = new ByteArrayOutputStream(); while((ch = i.read()) != -1) { read++; if (ch == '='){ final String keyword = coll.toString(CharsetNames.UTF_8); final int restLen = len - read; if (restLen == 1) { headers.remove(keyword); } else { final byte[] rest = new byte[restLen]; final int got = IOUtils.readFully(i, rest); if (got != restLen) { throw new IOException("Failed to read " + "Paxheader. Expected " + restLen + " bytes, read " + got); } final String value = new String(rest, 0, restLen - 1, CharsetNames.UTF_8); headers.put(keyword, value); } break; } coll.write((byte) ch); } break; } len *= 10; len += ch - '0'; } if (ch == -1){ break; } } return headers; }
Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); while(true){ int ch; int len = 0; int read = 0; while((ch = i.read()) != -1) { read++; if (ch == '\n') { break; } else if (ch == ' '){ final ByteArrayOutputStream coll = new ByteArrayOutputStream(); while((ch = i.read()) != -1) { read++; if (ch == '='){ final String keyword = coll.toString(CharsetNames.UTF_8); final int restLen = len - read; if (restLen == 1) { headers.remove(keyword); } else { final byte[] rest = new byte[restLen]; final int got = IOUtils.readFully(i, rest); if (got != restLen) { throw new IOException("Failed to read " + "Paxheader. Expected " + restLen + " bytes, read " + got); } final String value = new String(rest, 0, restLen - 1, CharsetNames.UTF_8); headers.put(keyword, value); } break; } coll.write((byte) ch); } break; } len *= 10; len += ch - '0'; } if (ch == -1){ break; } } return headers; }
Compress-7
public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { if (buffer[i] == 0) { break; } result.append((char) buffer[i]); } return result.toString(); }
public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { byte b = buffer[i]; if (b == 0) { break; } result.append((char) (b & 0xFF)); } return result.toString(); }
Cli-4
private void checkRequiredOptions() throws MissingOptionException { if (requiredOptions.size() > 0) { Iterator iter = requiredOptions.iterator(); StringBuffer buff = new StringBuffer(); while (iter.hasNext()) { buff.append(iter.next()); } throw new MissingOptionException(buff.toString()); } }
private void checkRequiredOptions() throws MissingOptionException { if (requiredOptions.size() > 0) { Iterator iter = requiredOptions.iterator(); StringBuffer buff = new StringBuffer("Missing required option"); buff.append(requiredOptions.size() == 1 ? "" : "s"); buff.append(": "); while (iter.hasNext()) { buff.append(iter.next()); } throw new MissingOptionException(buff.toString()); } }
Time-16
public int parseInto(ReadWritableInstant instant, String text, int position) { DateTimeParser parser = requireParser(); if (instant == null) { throw new IllegalArgumentException("Instant must not be null"); } long instantMillis = instant.getMillis(); Chronology chrono = instant.getChronology(); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, position); instant.setMillis(bucket.computeMillis(false, text)); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } instant.setChronology(chrono); if (iZone != null) { instant.setZone(iZone); } return newPos; }
public int parseInto(ReadWritableInstant instant, String text, int position) { DateTimeParser parser = requireParser(); if (instant == null) { throw new IllegalArgumentException("Instant must not be null"); } long instantMillis = instant.getMillis(); Chronology chrono = instant.getChronology(); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, chrono.year().get(instantLocal)); int newPos = parser.parseInto(bucket, text, position); instant.setMillis(bucket.computeMillis(false, text)); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } instant.setChronology(chrono); if (iZone != null) { instant.setZone(iZone); } return newPos; }
Jsoup-42
public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>(); for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if ("select".equals(el.tagName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option: options) { data.add(HttpConnection.KeyVal.create(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) data.add(HttpConnection.KeyVal.create(name, option.val())); } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { if (el.hasAttr("checked")) { final String val = el.val(); data.add(HttpConnection.KeyVal.create(name, val)); } } else { data.add(HttpConnection.KeyVal.create(name, el.val())); } } return data; }
public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>(); for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; if (el.hasAttr("disabled")) continue; String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if ("select".equals(el.tagName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option: options) { data.add(HttpConnection.KeyVal.create(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) data.add(HttpConnection.KeyVal.create(name, option.val())); } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { if (el.hasAttr("checked")) { final String val = el.val().length() > 0 ? el.val() : "on"; data.add(HttpConnection.KeyVal.create(name, val)); } } else { data.add(HttpConnection.KeyVal.create(name, el.val())); } } return data; }
Closure-166
public void matchConstraint(JSType constraint) { if (hasReferenceName()) { return; } if (constraint.isRecordType()) { matchRecordTypeConstraint(constraint.toObjectType()); } }
public void matchConstraint(JSType constraint) { if (hasReferenceName()) { return; } if (constraint.isRecordType()) { matchRecordTypeConstraint(constraint.toObjectType()); } else if (constraint.isUnionType()) { for (JSType alt : constraint.toMaybeUnionType().getAlternates()) { if (alt.isRecordType()) { matchRecordTypeConstraint(alt.toObjectType()); } } } }
Closure-87
private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); return NodeUtil.isExpressionNode(maybeExpr); } } return false; }
private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); if (maybeExpr.getType() == Token.EXPR_RESULT) { if (maybeExpr.getFirstChild().getType() == Token.CALL) { Node calledFn = maybeExpr.getFirstChild().getFirstChild(); if (calledFn.getType() == Token.GETELEM) { return false; } else if (calledFn.getType() == Token.GETPROP && calledFn.getLastChild().getString().startsWith("on")) { return false; } } return true; } return false; } } return false; }
JacksonDatabind-107
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { JavaType type = _idResolver.typeFromId(ctxt, typeId); if (type == null) { deser = _findDefaultImplDeserializer(ctxt); if (deser == null) { JavaType actual = _handleUnknownTypeId(ctxt, typeId); if (actual == null) { return null; } deser = ctxt.findContextualValueDeserializer(actual, _property); } } else { if ((_baseType != null) && _baseType.getClass() == type.getClass()) { if (!type.hasGenericTypes()) { type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass()); } } deser = ctxt.findContextualValueDeserializer(type, _property); } _deserializers.put(typeId, deser); } return deser; }
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt, String typeId) throws IOException { JsonDeserializer<Object> deser = _deserializers.get(typeId); if (deser == null) { JavaType type = _idResolver.typeFromId(ctxt, typeId); if (type == null) { deser = _findDefaultImplDeserializer(ctxt); if (deser == null) { JavaType actual = _handleUnknownTypeId(ctxt, typeId); if (actual == null) { return NullifyingDeserializer.instance; } deser = ctxt.findContextualValueDeserializer(actual, _property); } } else { if ((_baseType != null) && _baseType.getClass() == type.getClass()) { if (!type.hasGenericTypes()) { type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass()); } } deser = ctxt.findContextualValueDeserializer(type, _property); } _deserializers.put(typeId, deser); } return deser; }
Jsoup-62
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) { String name = t.asEndTag().normalName(); ArrayList<Element> stack = tb.getStack(); for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; }
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) { String name = t.asEndTag().name(); ArrayList<Element> stack = tb.getStack(); for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; }
JacksonDatabind-37
protected JavaType _narrow(Class<?> subclass) { if (_class == subclass) { return this; } return new SimpleType(subclass, _bindings, _superClass, _superInterfaces, _valueHandler, _typeHandler, _asStatic); }
protected JavaType _narrow(Class<?> subclass) { if (_class == subclass) { return this; } return new SimpleType(subclass, _bindings, this, _superInterfaces, _valueHandler, _typeHandler, _asStatic); }
Math-51
protected final double doSolve() { double x0 = getMin(); double x1 = getMax(); double f0 = computeObjectiveValue(x0); double f1 = computeObjectiveValue(x1); if (f0 == 0.0) { return x0; } if (f1 == 0.0) { return x1; } verifyBracketing(x0, x1); final double ftol = getFunctionValueAccuracy(); final double atol = getAbsoluteAccuracy(); final double rtol = getRelativeAccuracy(); boolean inverted = false; while (true) { final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); final double fx = computeObjectiveValue(x); if (fx == 0.0) { return x; } if (f1 * fx < 0) { x0 = x1; f0 = f1; inverted = !inverted; } else { switch (method) { case ILLINOIS: f0 *= 0.5; break; case PEGASUS: f0 *= f1 / (f1 + fx); break; default: } } x1 = x; f1 = fx; if (FastMath.abs(f1) <= ftol) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: if (inverted) { return x1; } break; case RIGHT_SIDE: if (!inverted) { return x1; } break; case BELOW_SIDE: if (f1 <= 0) { return x1; } break; case ABOVE_SIDE: if (f1 >= 0) { return x1; } break; default: throw new MathInternalError(); } } if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol)) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: return inverted ? x1 : x0; case RIGHT_SIDE: return inverted ? x0 : x1; case BELOW_SIDE: return (f1 <= 0) ? x1 : x0; case ABOVE_SIDE: return (f1 >= 0) ? x1 : x0; default: throw new MathInternalError(); } } } }
protected final double doSolve() { double x0 = getMin(); double x1 = getMax(); double f0 = computeObjectiveValue(x0); double f1 = computeObjectiveValue(x1); if (f0 == 0.0) { return x0; } if (f1 == 0.0) { return x1; } verifyBracketing(x0, x1); final double ftol = getFunctionValueAccuracy(); final double atol = getAbsoluteAccuracy(); final double rtol = getRelativeAccuracy(); boolean inverted = false; while (true) { final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); final double fx = computeObjectiveValue(x); if (fx == 0.0) { return x; } if (f1 * fx < 0) { x0 = x1; f0 = f1; inverted = !inverted; } else { switch (method) { case ILLINOIS: f0 *= 0.5; break; case PEGASUS: f0 *= f1 / (f1 + fx); break; case REGULA_FALSI: if (x == x1) { final double delta = FastMath.max(rtol * FastMath.abs(x1), atol); x0 = 0.5 * (x0 + x1 - delta); f0 = computeObjectiveValue(x0); } break; default: throw new MathInternalError(); } } x1 = x; f1 = fx; if (FastMath.abs(f1) <= ftol) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: if (inverted) { return x1; } break; case RIGHT_SIDE: if (!inverted) { return x1; } break; case BELOW_SIDE: if (f1 <= 0) { return x1; } break; case ABOVE_SIDE: if (f1 >= 0) { return x1; } break; default: throw new MathInternalError(); } } if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1), atol)) { switch (allowed) { case ANY_SIDE: return x1; case LEFT_SIDE: return inverted ? x1 : x0; case RIGHT_SIDE: return inverted ? x0 : x1; case BELOW_SIDE: return (f1 <= 0) ? x1 : x0; case ABOVE_SIDE: return (f1 >= 0) ? x1 : x0; default: throw new MathInternalError(); } } } }
JacksonDatabind-100
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { JsonNode n = currentNode(); if (n != null) { byte[] data = n.binaryValue(); if (data != null) { return data; } if (n.isPojo()) { Object ob = ((POJONode) n).getPojo(); if (ob instanceof byte[]) { return (byte[]) ob; } } } return null; }
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { JsonNode n = currentNode(); if (n != null) { if (n instanceof TextNode) { return ((TextNode) n).getBinaryValue(b64variant); } return n.binaryValue(); } return null; }
Time-20
public int parseInto(DateTimeParserBucket bucket, String text, int position) { String str = text.substring(position); for (String id : ALL_IDS) { if (str.startsWith(id)) { bucket.setZone(DateTimeZone.forID(id)); return position + id.length(); } } return ~position; }
public int parseInto(DateTimeParserBucket bucket, String text, int position) { String str = text.substring(position); String best = null; for (String id : ALL_IDS) { if (str.startsWith(id)) { if (best == null || id.length() > best.length()) { best = id; } } } if (best != null) { bucket.setZone(DateTimeZone.forID(best)); return position + best.length(); } return ~position; }
Jsoup-68
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) { int bottom = stack.size() -1; if (bottom > MaxScopeSearchDepth) { bottom = MaxScopeSearchDepth; } final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0; for (int pos = bottom; pos >= top; pos--) { final String elName = stack.get(pos).nodeName(); if (inSorted(elName, targetNames)) return true; if (inSorted(elName, baseTypes)) return false; if (extraTypes != null && inSorted(elName, extraTypes)) return false; } return false; }
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) { final int bottom = stack.size() -1; final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0; for (int pos = bottom; pos >= top; pos--) { final String elName = stack.get(pos).nodeName(); if (inSorted(elName, targetNames)) return true; if (inSorted(elName, baseTypes)) return false; if (extraTypes != null && inSorted(elName, extraTypes)) return false; } return false; }
Jsoup-51
boolean matchesLetter() { if (isEmpty()) return false; char c = input[pos]; return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
boolean matchesLetter() { if (isEmpty()) return false; char c = input[pos]; return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c); }
Gson-18
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { checkArgument(supertype.isAssignableFrom(contextRawType)); return resolve(context, contextRawType, $Gson$Types.getGenericSupertype(context, contextRawType, supertype)); }
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) { if (context instanceof WildcardType) { context = ((WildcardType)context).getUpperBounds()[0]; } checkArgument(supertype.isAssignableFrom(contextRawType)); return resolve(context, contextRawType, $Gson$Types.getGenericSupertype(context, contextRawType, supertype)); }
Closure-88
private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; }
private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { Preconditions.checkState(n.getParent().getType() == Token.ASSIGN); Node rhs = n.getNext(); VariableLiveness state = isVariableReadBeforeKill(rhs, variable); if (state == VariableLiveness.READ) { return state; } return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; }
Closure-123
void add(Node n, Context context) { if (!cc.continueProcessing()) { return; } int type = n.getType(); String opstr = NodeUtil.opToStr(type); int childCount = n.getChildCount(); Node first = n.getFirstChild(); Node last = n.getLastChild(); if (opstr != null && first != last) { Preconditions.checkState( childCount == 2, "Bad binary operator \"%s\": expected 2 arguments but got %s", opstr, childCount); int p = NodeUtil.precedence(type); Context rhsContext = getContextForNoInOperator(context); if (last.getType() == type && NodeUtil.isAssociative(type)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else { unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1); } return; } cc.startSourceMapping(n); switch (type) { case Token.TRY: { Preconditions.checkState(first.getNext().isBlock() && !first.getNext().hasMoreThanOneChild()); Preconditions.checkState(childCount >= 2 && childCount <= 3); add("try"); add(first, Context.PRESERVE_BLOCK); Node catchblock = first.getNext().getFirstChild(); if (catchblock != null) { add(catchblock); } if (childCount == 3) { add("finally"); add(last, Context.PRESERVE_BLOCK); } break; } case Token.CATCH: Preconditions.checkState(childCount == 2); add("catch("); add(first); add(")"); add(last, Context.PRESERVE_BLOCK); break; case Token.THROW: Preconditions.checkState(childCount == 1); add("throw"); add(first); cc.endStatement(true); break; case Token.RETURN: add("return"); if (childCount == 1) { add(first); } else { Preconditions.checkState(childCount == 0); } cc.endStatement(); break; case Token.VAR: if (first != null) { add("var "); addList(first, false, getContextForNoInOperator(context)); } break; case Token.LABEL_NAME: Preconditions.checkState(!n.getString().isEmpty()); addIdentifier(n.getString()); break; case Token.NAME: if (first == null || first.isEmpty()) { addIdentifier(n.getString()); } else { Preconditions.checkState(childCount == 1); addIdentifier(n.getString()); cc.addOp("=", true); if (first.isComma()) { addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER); } else { addExpr(first, 0, getContextForNoInOperator(context)); } } break; case Token.ARRAYLIT: add("["); addArrayList(first); add("]"); break; case Token.PARAM_LIST: add("("); addList(first); add(")"); break; case Token.COMMA: Preconditions.checkState(childCount == 2); unrollBinaryOperator(n, Token.COMMA, ",", context, getContextForNoInOperator(context), 0, 0); break; case Token.NUMBER: Preconditions.checkState(childCount == 0); cc.addNumber(n.getDouble()); break; case Token.TYPEOF: case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.POS: { Preconditions.checkState(childCount == 1); cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); break; } case Token.NEG: { Preconditions.checkState(childCount == 1); if (n.getFirstChild().isNumber()) { cc.addNumber(-n.getFirstChild().getDouble()); } else { cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); } break; } case Token.HOOK: { Preconditions.checkState(childCount == 3); int p = NodeUtil.precedence(type); Context rhsContext = Context.OTHER; addExpr(first, p + 1, context); cc.addOp("?", true); addExpr(first.getNext(), 1, rhsContext); cc.addOp(":", true); addExpr(last, 1, rhsContext); break; } case Token.REGEXP: if (!first.isString() || !last.isString()) { throw new Error("Expected children to be strings"); } String regexp = regexpEscape(first.getString(), outputCharsetEncoder); if (childCount == 2) { add(regexp + last.getString()); } else { Preconditions.checkState(childCount == 1); add(regexp); } break; case Token.FUNCTION: if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } Preconditions.checkState(childCount == 3); boolean funcNeedsParens = (context == Context.START_OF_EXPR); if (funcNeedsParens) { add("("); } add("function"); add(first); add(first.getNext()); add(last, Context.PRESERVE_BLOCK); cc.endFunction(context == Context.STATEMENT); if (funcNeedsParens) { add(")"); } break; case Token.GETTER_DEF: case Token.SETTER_DEF: Preconditions.checkState(n.getParent().isObjectLit()); Preconditions.checkState(childCount == 1); Preconditions.checkState(first.isFunction()); Preconditions.checkState(first.getFirstChild().getString().isEmpty()); if (type == Token.GETTER_DEF) { Preconditions.checkState(!first.getChildAtIndex(1).hasChildren()); add("get "); } else { Preconditions.checkState(first.getChildAtIndex(1).hasOneChild()); add("set "); } String name = n.getString(); Node fn = first; Node parameters = fn.getChildAtIndex(1); Node body = fn.getLastChild(); if (!n.isQuotedString() && TokenStream.isJSIdentifier(name) && NodeUtil.isLatin(name)) { add(name); } else { double d = getSimpleNumber(name); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addJsString(n); } } add(parameters); add(body, Context.PRESERVE_BLOCK); break; case Token.SCRIPT: case Token.BLOCK: { if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } boolean preserveBlock = context == Context.PRESERVE_BLOCK; if (preserveBlock) { cc.beginBlock(); } boolean preferLineBreaks = type == Token.SCRIPT || (type == Token.BLOCK && !preserveBlock && n.getParent() != null && n.getParent().isScript()); for (Node c = first; c != null; c = c.getNext()) { add(c, Context.STATEMENT); if (c.isVar()) { cc.endStatement(); } if (c.isFunction()) { cc.maybeLineBreak(); } if (preferLineBreaks) { cc.notePreferredLineBreak(); } } if (preserveBlock) { cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT)); } break; } case Token.FOR: if (childCount == 4) { add("for("); if (first.isVar()) { add(first, Context.IN_FOR_INIT_CLAUSE); } else { addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE); } add(";"); add(first.getNext()); add(";"); add(first.getNext().getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { Preconditions.checkState(childCount == 3); add("for("); add(first); add("in"); add(first.getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } break; case Token.DO: Preconditions.checkState(childCount == 2); add("do"); addNonEmptyStatement(first, Context.OTHER, false); add("while("); add(last); add(")"); cc.endStatement(); break; case Token.WHILE: Preconditions.checkState(childCount == 2); add("while("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.EMPTY: Preconditions.checkState(childCount == 0); break; case Token.GETPROP: { Preconditions.checkState( childCount == 2, "Bad GETPROP: expected 2 children, but got %s", childCount); Preconditions.checkState( last.isString(), "Bad GETPROP: RHS should be STRING"); boolean needsParens = (first.isNumber()); if (needsParens) { add("("); } addExpr(first, NodeUtil.precedence(type), context); if (needsParens) { add(")"); } if (this.languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(last.getString())) { add("["); add(last); add("]"); } else { add("."); addIdentifier(last.getString()); } break; } case Token.GETELEM: Preconditions.checkState( childCount == 2, "Bad GETELEM: expected 2 children but got %s", childCount); addExpr(first, NodeUtil.precedence(type), context); add("["); add(first.getNext()); add("]"); break; case Token.WITH: Preconditions.checkState(childCount == 2); add("with("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.INC: case Token.DEC: { Preconditions.checkState(childCount == 1); String o = type == Token.INC ? "++" : "--"; int postProp = n.getIntProp(Node.INCRDECR_PROP); if (postProp != 0) { addExpr(first, NodeUtil.precedence(type), context); cc.addOp(o, false); } else { cc.addOp(o, false); add(first); } break; } case Token.CALL: if (isIndirectEval(first) || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) { add("(0,"); addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER); add(")"); } else { addExpr(first, NodeUtil.precedence(type), context); } add("("); addList(first.getNext()); add(")"); break; case Token.IF: boolean hasElse = childCount == 3; boolean ambiguousElseClause = context == Context.BEFORE_DANGLING_ELSE && !hasElse; if (ambiguousElseClause) { cc.beginBlock(); } add("if("); add(first); add(")"); if (hasElse) { addNonEmptyStatement( first.getNext(), Context.BEFORE_DANGLING_ELSE, false); add("else"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { addNonEmptyStatement(first.getNext(), Context.OTHER, false); Preconditions.checkState(childCount == 2); } if (ambiguousElseClause) { cc.endBlock(); } break; case Token.NULL: Preconditions.checkState(childCount == 0); cc.addConstant("null"); break; case Token.THIS: Preconditions.checkState(childCount == 0); add("this"); break; case Token.FALSE: Preconditions.checkState(childCount == 0); cc.addConstant("false"); break; case Token.TRUE: Preconditions.checkState(childCount == 0); cc.addConstant("true"); break; case Token.CONTINUE: Preconditions.checkState(childCount <= 1); add("continue"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.DEBUGGER: Preconditions.checkState(childCount == 0); add("debugger"); cc.endStatement(); break; case Token.BREAK: Preconditions.checkState(childCount <= 1); add("break"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.EXPR_RESULT: Preconditions.checkState(childCount == 1); add(first, Context.START_OF_EXPR); cc.endStatement(); break; case Token.NEW: add("new "); int precedence = NodeUtil.precedence(type); if (NodeUtil.containsType( first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) { precedence = NodeUtil.precedence(first.getType()) + 1; } addExpr(first, precedence, Context.OTHER); Node next = first.getNext(); if (next != null) { add("("); addList(next); add(")"); } break; case Token.STRING_KEY: Preconditions.checkState( childCount == 1, "Object lit key must have 1 child"); addJsString(n); break; case Token.STRING: Preconditions.checkState( childCount == 0, "A string may not have children"); addJsString(n); break; case Token.DELPROP: Preconditions.checkState(childCount == 1); add("delete "); add(first); break; case Token.OBJECTLIT: { boolean needsParens = (context == Context.START_OF_EXPR); if (needsParens) { add("("); } add("{"); for (Node c = first; c != null; c = c.getNext()) { if (c != first) { cc.listSeparator(); } if (c.isGetterDef() || c.isSetterDef()) { add(c); } else { Preconditions.checkState(c.isStringKey()); String key = c.getString(); if (!c.isQuotedString() && !(languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(key)) && TokenStream.isJSIdentifier(key) && NodeUtil.isLatin(key)) { add(key); } else { double d = getSimpleNumber(key); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addExpr(c, 1, Context.OTHER); } } add(":"); addExpr(c.getFirstChild(), 1, Context.OTHER); } } add("}"); if (needsParens) { add(")"); } break; } case Token.SWITCH: add("switch("); add(first); add(")"); cc.beginBlock(); addAllSiblings(first.getNext()); cc.endBlock(context == Context.STATEMENT); break; case Token.CASE: Preconditions.checkState(childCount == 2); add("case "); add(first); addCaseBody(last); break; case Token.DEFAULT_CASE: Preconditions.checkState(childCount == 1); add("default"); addCaseBody(first); break; case Token.LABEL: Preconditions.checkState(childCount == 2); if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(first); add(":"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), true); break; case Token.CAST: add("("); add(first); add(")"); break; default: throw new Error("Unknown type " + type + "\n" + n.toStringTree()); } cc.endSourceMapping(n); }
void add(Node n, Context context) { if (!cc.continueProcessing()) { return; } int type = n.getType(); String opstr = NodeUtil.opToStr(type); int childCount = n.getChildCount(); Node first = n.getFirstChild(); Node last = n.getLastChild(); if (opstr != null && first != last) { Preconditions.checkState( childCount == 2, "Bad binary operator \"%s\": expected 2 arguments but got %s", opstr, childCount); int p = NodeUtil.precedence(type); Context rhsContext = getContextForNoInOperator(context); if (last.getType() == type && NodeUtil.isAssociative(type)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) { addExpr(first, p, context); cc.addOp(opstr, true); addExpr(last, p, rhsContext); } else { unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1); } return; } cc.startSourceMapping(n); switch (type) { case Token.TRY: { Preconditions.checkState(first.getNext().isBlock() && !first.getNext().hasMoreThanOneChild()); Preconditions.checkState(childCount >= 2 && childCount <= 3); add("try"); add(first, Context.PRESERVE_BLOCK); Node catchblock = first.getNext().getFirstChild(); if (catchblock != null) { add(catchblock); } if (childCount == 3) { add("finally"); add(last, Context.PRESERVE_BLOCK); } break; } case Token.CATCH: Preconditions.checkState(childCount == 2); add("catch("); add(first); add(")"); add(last, Context.PRESERVE_BLOCK); break; case Token.THROW: Preconditions.checkState(childCount == 1); add("throw"); add(first); cc.endStatement(true); break; case Token.RETURN: add("return"); if (childCount == 1) { add(first); } else { Preconditions.checkState(childCount == 0); } cc.endStatement(); break; case Token.VAR: if (first != null) { add("var "); addList(first, false, getContextForNoInOperator(context)); } break; case Token.LABEL_NAME: Preconditions.checkState(!n.getString().isEmpty()); addIdentifier(n.getString()); break; case Token.NAME: if (first == null || first.isEmpty()) { addIdentifier(n.getString()); } else { Preconditions.checkState(childCount == 1); addIdentifier(n.getString()); cc.addOp("=", true); if (first.isComma()) { addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER); } else { addExpr(first, 0, getContextForNoInOperator(context)); } } break; case Token.ARRAYLIT: add("["); addArrayList(first); add("]"); break; case Token.PARAM_LIST: add("("); addList(first); add(")"); break; case Token.COMMA: Preconditions.checkState(childCount == 2); unrollBinaryOperator(n, Token.COMMA, ",", context, getContextForNoInOperator(context), 0, 0); break; case Token.NUMBER: Preconditions.checkState(childCount == 0); cc.addNumber(n.getDouble()); break; case Token.TYPEOF: case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.POS: { Preconditions.checkState(childCount == 1); cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); break; } case Token.NEG: { Preconditions.checkState(childCount == 1); if (n.getFirstChild().isNumber()) { cc.addNumber(-n.getFirstChild().getDouble()); } else { cc.addOp(NodeUtil.opToStrNoFail(type), false); addExpr(first, NodeUtil.precedence(type), Context.OTHER); } break; } case Token.HOOK: { Preconditions.checkState(childCount == 3); int p = NodeUtil.precedence(type); Context rhsContext = getContextForNoInOperator(context); addExpr(first, p + 1, context); cc.addOp("?", true); addExpr(first.getNext(), 1, rhsContext); cc.addOp(":", true); addExpr(last, 1, rhsContext); break; } case Token.REGEXP: if (!first.isString() || !last.isString()) { throw new Error("Expected children to be strings"); } String regexp = regexpEscape(first.getString(), outputCharsetEncoder); if (childCount == 2) { add(regexp + last.getString()); } else { Preconditions.checkState(childCount == 1); add(regexp); } break; case Token.FUNCTION: if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } Preconditions.checkState(childCount == 3); boolean funcNeedsParens = (context == Context.START_OF_EXPR); if (funcNeedsParens) { add("("); } add("function"); add(first); add(first.getNext()); add(last, Context.PRESERVE_BLOCK); cc.endFunction(context == Context.STATEMENT); if (funcNeedsParens) { add(")"); } break; case Token.GETTER_DEF: case Token.SETTER_DEF: Preconditions.checkState(n.getParent().isObjectLit()); Preconditions.checkState(childCount == 1); Preconditions.checkState(first.isFunction()); Preconditions.checkState(first.getFirstChild().getString().isEmpty()); if (type == Token.GETTER_DEF) { Preconditions.checkState(!first.getChildAtIndex(1).hasChildren()); add("get "); } else { Preconditions.checkState(first.getChildAtIndex(1).hasOneChild()); add("set "); } String name = n.getString(); Node fn = first; Node parameters = fn.getChildAtIndex(1); Node body = fn.getLastChild(); if (!n.isQuotedString() && TokenStream.isJSIdentifier(name) && NodeUtil.isLatin(name)) { add(name); } else { double d = getSimpleNumber(name); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addJsString(n); } } add(parameters); add(body, Context.PRESERVE_BLOCK); break; case Token.SCRIPT: case Token.BLOCK: { if (n.getClass() != Node.class) { throw new Error("Unexpected Node subclass."); } boolean preserveBlock = context == Context.PRESERVE_BLOCK; if (preserveBlock) { cc.beginBlock(); } boolean preferLineBreaks = type == Token.SCRIPT || (type == Token.BLOCK && !preserveBlock && n.getParent() != null && n.getParent().isScript()); for (Node c = first; c != null; c = c.getNext()) { add(c, Context.STATEMENT); if (c.isVar()) { cc.endStatement(); } if (c.isFunction()) { cc.maybeLineBreak(); } if (preferLineBreaks) { cc.notePreferredLineBreak(); } } if (preserveBlock) { cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT)); } break; } case Token.FOR: if (childCount == 4) { add("for("); if (first.isVar()) { add(first, Context.IN_FOR_INIT_CLAUSE); } else { addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE); } add(";"); add(first.getNext()); add(";"); add(first.getNext().getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { Preconditions.checkState(childCount == 3); add("for("); add(first); add("in"); add(first.getNext()); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } break; case Token.DO: Preconditions.checkState(childCount == 2); add("do"); addNonEmptyStatement(first, Context.OTHER, false); add("while("); add(last); add(")"); cc.endStatement(); break; case Token.WHILE: Preconditions.checkState(childCount == 2); add("while("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.EMPTY: Preconditions.checkState(childCount == 0); break; case Token.GETPROP: { Preconditions.checkState( childCount == 2, "Bad GETPROP: expected 2 children, but got %s", childCount); Preconditions.checkState( last.isString(), "Bad GETPROP: RHS should be STRING"); boolean needsParens = (first.isNumber()); if (needsParens) { add("("); } addExpr(first, NodeUtil.precedence(type), context); if (needsParens) { add(")"); } if (this.languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(last.getString())) { add("["); add(last); add("]"); } else { add("."); addIdentifier(last.getString()); } break; } case Token.GETELEM: Preconditions.checkState( childCount == 2, "Bad GETELEM: expected 2 children but got %s", childCount); addExpr(first, NodeUtil.precedence(type), context); add("["); add(first.getNext()); add("]"); break; case Token.WITH: Preconditions.checkState(childCount == 2); add("with("); add(first); add(")"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); break; case Token.INC: case Token.DEC: { Preconditions.checkState(childCount == 1); String o = type == Token.INC ? "++" : "--"; int postProp = n.getIntProp(Node.INCRDECR_PROP); if (postProp != 0) { addExpr(first, NodeUtil.precedence(type), context); cc.addOp(o, false); } else { cc.addOp(o, false); add(first); } break; } case Token.CALL: if (isIndirectEval(first) || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) { add("(0,"); addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER); add(")"); } else { addExpr(first, NodeUtil.precedence(type), context); } add("("); addList(first.getNext()); add(")"); break; case Token.IF: boolean hasElse = childCount == 3; boolean ambiguousElseClause = context == Context.BEFORE_DANGLING_ELSE && !hasElse; if (ambiguousElseClause) { cc.beginBlock(); } add("if("); add(first); add(")"); if (hasElse) { addNonEmptyStatement( first.getNext(), Context.BEFORE_DANGLING_ELSE, false); add("else"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), false); } else { addNonEmptyStatement(first.getNext(), Context.OTHER, false); Preconditions.checkState(childCount == 2); } if (ambiguousElseClause) { cc.endBlock(); } break; case Token.NULL: Preconditions.checkState(childCount == 0); cc.addConstant("null"); break; case Token.THIS: Preconditions.checkState(childCount == 0); add("this"); break; case Token.FALSE: Preconditions.checkState(childCount == 0); cc.addConstant("false"); break; case Token.TRUE: Preconditions.checkState(childCount == 0); cc.addConstant("true"); break; case Token.CONTINUE: Preconditions.checkState(childCount <= 1); add("continue"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.DEBUGGER: Preconditions.checkState(childCount == 0); add("debugger"); cc.endStatement(); break; case Token.BREAK: Preconditions.checkState(childCount <= 1); add("break"); if (childCount == 1) { if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(" "); add(first); } cc.endStatement(); break; case Token.EXPR_RESULT: Preconditions.checkState(childCount == 1); add(first, Context.START_OF_EXPR); cc.endStatement(); break; case Token.NEW: add("new "); int precedence = NodeUtil.precedence(type); if (NodeUtil.containsType( first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) { precedence = NodeUtil.precedence(first.getType()) + 1; } addExpr(first, precedence, Context.OTHER); Node next = first.getNext(); if (next != null) { add("("); addList(next); add(")"); } break; case Token.STRING_KEY: Preconditions.checkState( childCount == 1, "Object lit key must have 1 child"); addJsString(n); break; case Token.STRING: Preconditions.checkState( childCount == 0, "A string may not have children"); addJsString(n); break; case Token.DELPROP: Preconditions.checkState(childCount == 1); add("delete "); add(first); break; case Token.OBJECTLIT: { boolean needsParens = (context == Context.START_OF_EXPR); if (needsParens) { add("("); } add("{"); for (Node c = first; c != null; c = c.getNext()) { if (c != first) { cc.listSeparator(); } if (c.isGetterDef() || c.isSetterDef()) { add(c); } else { Preconditions.checkState(c.isStringKey()); String key = c.getString(); if (!c.isQuotedString() && !(languageMode == LanguageMode.ECMASCRIPT3 && TokenStream.isKeyword(key)) && TokenStream.isJSIdentifier(key) && NodeUtil.isLatin(key)) { add(key); } else { double d = getSimpleNumber(key); if (!Double.isNaN(d)) { cc.addNumber(d); } else { addExpr(c, 1, Context.OTHER); } } add(":"); addExpr(c.getFirstChild(), 1, Context.OTHER); } } add("}"); if (needsParens) { add(")"); } break; } case Token.SWITCH: add("switch("); add(first); add(")"); cc.beginBlock(); addAllSiblings(first.getNext()); cc.endBlock(context == Context.STATEMENT); break; case Token.CASE: Preconditions.checkState(childCount == 2); add("case "); add(first); addCaseBody(last); break; case Token.DEFAULT_CASE: Preconditions.checkState(childCount == 1); add("default"); addCaseBody(first); break; case Token.LABEL: Preconditions.checkState(childCount == 2); if (!first.isLabelName()) { throw new Error("Unexpected token type. Should be LABEL_NAME."); } add(first); add(":"); addNonEmptyStatement( last, getContextForNonEmptyExpression(context), true); break; case Token.CAST: add("("); add(first); add(")"); break; default: throw new Error("Unknown type " + type + "\n" + n.toStringTree()); } cc.endSourceMapping(n); }
Math-42
protected RealPointValuePair getSolution() { int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL); Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null; double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset()); Set<Integer> basicRows = new HashSet<Integer>(); double[] coefficients = new double[getOriginalNumDecisionVariables()]; for (int i = 0; i < coefficients.length; i++) { int colIndex = columnLabels.indexOf("x" + i); if (colIndex < 0) { coefficients[i] = 0; continue; } Integer basicRow = getBasicRow(colIndex); if (basicRows.contains(basicRow)) { coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative); } else { basicRows.add(basicRow); coefficients[i] = (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - (restrictToNonNegative ? 0 : mostNegative); } } return new RealPointValuePair(coefficients, f.getValue(coefficients)); }
protected RealPointValuePair getSolution() { int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL); Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null; double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset()); Set<Integer> basicRows = new HashSet<Integer>(); double[] coefficients = new double[getOriginalNumDecisionVariables()]; for (int i = 0; i < coefficients.length; i++) { int colIndex = columnLabels.indexOf("x" + i); if (colIndex < 0) { coefficients[i] = 0; continue; } Integer basicRow = getBasicRow(colIndex); if (basicRow != null && basicRow == 0) { coefficients[i] = 0; } else if (basicRows.contains(basicRow)) { coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative); } else { basicRows.add(basicRow); coefficients[i] = (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) - (restrictToNonNegative ? 0 : mostNegative); } } return new RealPointValuePair(coefficients, f.getValue(coefficients)); }
Math-89
public void addValue(Object v) { addValue((Comparable<?>) v); }
public void addValue(Object v) { if (v instanceof Comparable<?>){ addValue((Comparable<?>) v); } else { throw new IllegalArgumentException("Object must implement Comparable"); } }
Math-78
public boolean evaluateStep(final StepInterpolator interpolator) throws DerivativeException, EventException, ConvergenceException { try { forward = interpolator.isForward(); final double t1 = interpolator.getCurrentTime(); final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval)); final double h = (t1 - t0) / n; double ta = t0; double ga = g0; double tb = t0 + (interpolator.isForward() ? convergence : -convergence); for (int i = 0; i < n; ++i) { tb += h; interpolator.setInterpolatedTime(tb); final double gb = handler.g(tb, interpolator.getInterpolatedState()); if (g0Positive ^ (gb >= 0)) { increasing = gb >= ga; final UnivariateRealFunction f = new UnivariateRealFunction() { public double value(final double t) throws FunctionEvaluationException { try { interpolator.setInterpolatedTime(t); return handler.g(t, interpolator.getInterpolatedState()); } catch (DerivativeException e) { throw new FunctionEvaluationException(e, t); } catch (EventException e) { throw new FunctionEvaluationException(e, t); } } }; final BrentSolver solver = new BrentSolver(); solver.setAbsoluteAccuracy(convergence); solver.setMaximalIterationCount(maxIterationCount); final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); if ((Math.abs(root - ta) <= convergence) && (Math.abs(root - previousEventTime) <= convergence)) { ta = tb; ga = gb; } else if (Double.isNaN(previousEventTime) || (Math.abs(previousEventTime - root) > convergence)) { pendingEventTime = root; if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) { return false; } pendingEvent = true; return true; } } else { ta = tb; ga = gb; } } pendingEvent = false; pendingEventTime = Double.NaN; return false; } catch (FunctionEvaluationException e) { final Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof DerivativeException)) { throw (DerivativeException) cause; } else if ((cause != null) && (cause instanceof EventException)) { throw (EventException) cause; } throw new EventException(e); } }
public boolean evaluateStep(final StepInterpolator interpolator) throws DerivativeException, EventException, ConvergenceException { try { forward = interpolator.isForward(); final double t1 = interpolator.getCurrentTime(); final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval)); final double h = (t1 - t0) / n; double ta = t0; double ga = g0; double tb = t0 + (interpolator.isForward() ? convergence : -convergence); for (int i = 0; i < n; ++i) { tb += h; interpolator.setInterpolatedTime(tb); final double gb = handler.g(tb, interpolator.getInterpolatedState()); if (g0Positive ^ (gb >= 0)) { if (ga * gb > 0) { final double epsilon = (forward ? 0.25 : -0.25) * convergence; for (int k = 0; (k < 4) && (ga * gb > 0); ++k) { ta += epsilon; interpolator.setInterpolatedTime(ta); ga = handler.g(ta, interpolator.getInterpolatedState()); } if (ga * gb > 0) { throw MathRuntimeException.createInternalError(null); } } increasing = gb >= ga; final UnivariateRealFunction f = new UnivariateRealFunction() { public double value(final double t) throws FunctionEvaluationException { try { interpolator.setInterpolatedTime(t); return handler.g(t, interpolator.getInterpolatedState()); } catch (DerivativeException e) { throw new FunctionEvaluationException(e, t); } catch (EventException e) { throw new FunctionEvaluationException(e, t); } } }; final BrentSolver solver = new BrentSolver(); solver.setAbsoluteAccuracy(convergence); solver.setMaximalIterationCount(maxIterationCount); final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta); if ((Math.abs(root - ta) <= convergence) && (Math.abs(root - previousEventTime) <= convergence)) { ta = tb; ga = gb; } else if (Double.isNaN(previousEventTime) || (Math.abs(previousEventTime - root) > convergence)) { pendingEventTime = root; if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) { return false; } pendingEvent = true; return true; } } else { ta = tb; ga = gb; } } pendingEvent = false; pendingEventTime = Double.NaN; return false; } catch (FunctionEvaluationException e) { final Throwable cause = e.getCause(); if ((cause != null) && (cause instanceof DerivativeException)) { throw (DerivativeException) cause; } else if ((cause != null) && (cause instanceof EventException)) { throw (EventException) cause; } throw new EventException(e); } }
Time-27
private static PeriodFormatter toFormatter(List<Object> elementPairs, boolean notPrinter, boolean notParser) { if (notPrinter && notParser) { throw new IllegalStateException("Builder has created neither a printer nor a parser"); } int size = elementPairs.size(); if (size >= 2 && elementPairs.get(0) instanceof Separator) { Separator sep = (Separator) elementPairs.get(0); PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser); sep = sep.finish(f.getPrinter(), f.getParser()); return new PeriodFormatter(sep, sep); } Object[] comp = createComposite(elementPairs); if (notPrinter) { return new PeriodFormatter(null, (PeriodParser) comp[1]); } else if (notParser) { return new PeriodFormatter((PeriodPrinter) comp[0], null); } else { return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]); } }
private static PeriodFormatter toFormatter(List<Object> elementPairs, boolean notPrinter, boolean notParser) { if (notPrinter && notParser) { throw new IllegalStateException("Builder has created neither a printer nor a parser"); } int size = elementPairs.size(); if (size >= 2 && elementPairs.get(0) instanceof Separator) { Separator sep = (Separator) elementPairs.get(0); if (sep.iAfterParser == null && sep.iAfterPrinter == null) { PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser); sep = sep.finish(f.getPrinter(), f.getParser()); return new PeriodFormatter(sep, sep); } } Object[] comp = createComposite(elementPairs); if (notPrinter) { return new PeriodFormatter(null, (PeriodParser) comp[1]); } else if (notParser) { return new PeriodFormatter((PeriodPrinter) comp[0], null); } else { return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]); } }
Time-14
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) { if (valueToAdd == 0) { return values; } if (DateTimeUtils.isContiguous(partial)) { long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]); } instant = add(instant, valueToAdd); return iChronology.get(partial, instant); } else { return super.add(partial, fieldIndex, values, valueToAdd); } }
public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) { if (valueToAdd == 0) { return values; } if (partial.size() > 0 && partial.getFieldType(0).equals(DateTimeFieldType.monthOfYear()) && fieldIndex == 0) { int curMonth0 = partial.getValue(0) - 1; int newMonth = ((curMonth0 + (valueToAdd % 12) + 12) % 12) + 1; return set(partial, 0, values, newMonth); } if (DateTimeUtils.isContiguous(partial)) { long instant = 0L; for (int i = 0, isize = partial.size(); i < isize; i++) { instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]); } instant = add(instant, valueToAdd); return iChronology.get(partial, instant); } else { return super.add(partial, fieldIndex, values, valueToAdd); } }
Chart-23
null
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MinMaxCategoryRenderer)) { return false; } MinMaxCategoryRenderer that = (MinMaxCategoryRenderer) obj; if (this.plotLines != that.plotLines) { return false; } if (!PaintUtilities.equal(this.groupPaint, that.groupPaint)) { return false; } if (!this.groupStroke.equals(that.groupStroke)) { return false; } return super.equals(obj); }
Mockito-33
public boolean hasSameMethod(Invocation candidate) { Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); return m1.equals(m2); }
public boolean hasSameMethod(Invocation candidate) { Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); if (m1.getName() != null && m1.getName().equals(m2.getName())) { Class[] params1 = m1.getParameterTypes(); Class[] params2 = m2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } } return false; }
Closure-101
protected CompilerOptions createOptions() { CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new ClosureCodingConvention()); CompilationLevel level = flags.compilation_level; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } WarningLevel wLevel = flags.warning_level; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } if (flags.process_closure_primitives) { options.closurePass = true; } initOptionsFromFlags(options); return options; }
protected CompilerOptions createOptions() { CompilerOptions options = new CompilerOptions(); options.setCodingConvention(new ClosureCodingConvention()); CompilationLevel level = flags.compilation_level; level.setOptionsForCompilationLevel(options); if (flags.debug) { level.setDebugOptionsForCompilationLevel(options); } WarningLevel wLevel = flags.warning_level; wLevel.setOptionsForWarningLevel(options); for (FormattingOption formattingOption : flags.formatting) { formattingOption.applyToOptions(options); } options.closurePass = flags.process_closure_primitives; initOptionsFromFlags(options); return options; }
Closure-38
void addNumber(double x) { char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
void addNumber(double x) { char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if ((x < 0 || negativeZero) && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
JacksonDatabind-70
public void remove(SettableBeanProperty propToRm) { ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size); String key = getPropertyName(propToRm); boolean found = false; for (int i = 1, end = _hashArea.length; i < end; i += 2) { SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i]; if (prop == null) { continue; } if (!found) { found = key.equals(prop.getName()); if (found) { _propsInOrder[_findFromOrdered(prop)] = null; continue; } } props.add(prop); } if (!found) { throw new NoSuchElementException("No entry '"+propToRm.getName()+"' found, can't remove"); } init(props); }
public void remove(SettableBeanProperty propToRm) { ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size); String key = getPropertyName(propToRm); boolean found = false; for (int i = 1, end = _hashArea.length; i < end; i += 2) { SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i]; if (prop == null) { continue; } if (!found) { found = key.equals(_hashArea[i-1]); if (found) { _propsInOrder[_findFromOrdered(prop)] = null; continue; } } props.add(prop); } if (!found) { throw new NoSuchElementException("No entry '"+propToRm.getName()+"' found, can't remove"); } init(props); }
JacksonDatabind-6
protected Date parseAsISO8601(String dateStr, ParsePosition pos) { int len = dateStr.length(); char c = dateStr.charAt(len-1); DateFormat df; if (len <= 10 && Character.isDigit(c)) { df = _formatPlain; if (df == null) { df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale); } } else if (c == 'Z') { df = _formatISO8601_z; if (df == null) { df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale); } if (dateStr.charAt(len-4) == ':') { StringBuilder sb = new StringBuilder(dateStr); sb.insert(len-1, ".000"); dateStr = sb.toString(); } } else { if (hasTimeZone(dateStr)) { c = dateStr.charAt(len-3); if (c == ':') { StringBuilder sb = new StringBuilder(dateStr); sb.delete(len-3, len-2); dateStr = sb.toString(); } else if (c == '+' || c == '-') { dateStr += "00"; } len = dateStr.length(); c = dateStr.charAt(len-9); if (Character.isDigit(c)) { StringBuilder sb = new StringBuilder(dateStr); sb.insert(len-5, ".000"); dateStr = sb.toString(); } df = _formatISO8601; if (_formatISO8601 == null) { df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale); } } else { StringBuilder sb = new StringBuilder(dateStr); int timeLen = len - dateStr.lastIndexOf('T') - 1; if (timeLen <= 8) { sb.append(".000"); } sb.append('Z'); dateStr = sb.toString(); df = _formatISO8601_z; if (df == null) { df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale); } } } return df.parse(dateStr, pos); }
protected Date parseAsISO8601(String dateStr, ParsePosition pos) { int len = dateStr.length(); char c = dateStr.charAt(len-1); DateFormat df; if (len <= 10 && Character.isDigit(c)) { df = _formatPlain; if (df == null) { df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale); } } else if (c == 'Z') { df = _formatISO8601_z; if (df == null) { df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale); } if (dateStr.charAt(len-4) == ':') { StringBuilder sb = new StringBuilder(dateStr); sb.insert(len-1, ".000"); dateStr = sb.toString(); } } else { if (hasTimeZone(dateStr)) { c = dateStr.charAt(len-3); if (c == ':') { StringBuilder sb = new StringBuilder(dateStr); sb.delete(len-3, len-2); dateStr = sb.toString(); } else if (c == '+' || c == '-') { dateStr += "00"; } len = dateStr.length(); int timeLen = len - dateStr.lastIndexOf('T') - 6; if (timeLen < 12) { int offset = len - 5; StringBuilder sb = new StringBuilder(dateStr); switch (timeLen) { case 11: sb.insert(offset, '0'); break; case 10: sb.insert(offset, "00"); break; case 9: sb.insert(offset, "000"); break; case 8: sb.insert(offset, ".000"); break; case 7: break; case 6: sb.insert(offset, "00.000"); case 5: sb.insert(offset, ":00.000"); } dateStr = sb.toString(); } df = _formatISO8601; if (_formatISO8601 == null) { df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale); } } else { StringBuilder sb = new StringBuilder(dateStr); int timeLen = len - dateStr.lastIndexOf('T') - 1; if (timeLen < 12) { switch (timeLen) { case 11: sb.append('0'); case 10: sb.append('0'); case 9: sb.append('0'); break; default: sb.append(".000"); } } sb.append('Z'); dateStr = sb.toString(); df = _formatISO8601_z; if (df == null) { df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale); } } } return df.parse(dateStr, pos); }
JacksonDatabind-101
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader); TokenBuffer tokens = new TokenBuffer(p, ctxt); 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 (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) { t = p.nextToken(); Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { bean = wrapInstantiationProblem(e, ctxt); } p.setCurrentValue(bean); while (t == JsonToken.FIELD_NAME) { p.nextToken(); tokens.copyCurrentStructure(p); t = p.nextToken(); } tokens.writeEndObject(); if (bean.getClass() != _beanType.getRawClass()) { ctxt.reportInputMismatch(creatorProp, "Cannot create polymorphic instances with unwrapped values"); return null; } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); } continue; } if (buffer.readIdProperty(propName)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop)); continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } if (_anySetter == null) { tokens.writeFieldName(propName); tokens.copyCurrentStructure(p); } else { TokenBuffer b2 = TokenBuffer.asCopyOfValue(p); tokens.writeFieldName(propName); tokens.append(b2); try { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt)); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); } continue; } } Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); }
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException { final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader); TokenBuffer tokens = new TokenBuffer(p, ctxt); 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 (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) { t = p.nextToken(); Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { bean = wrapInstantiationProblem(e, ctxt); } p.setCurrentValue(bean); while (t == JsonToken.FIELD_NAME) { tokens.copyCurrentStructure(p); t = p.nextToken(); } if (t != JsonToken.END_OBJECT) { ctxt.reportWrongTokenException(this, JsonToken.END_OBJECT, "Attempted to unwrap '%s' value", handledType().getName()); } tokens.writeEndObject(); if (bean.getClass() != _beanType.getRawClass()) { ctxt.reportInputMismatch(creatorProp, "Cannot create polymorphic instances with unwrapped values"); return null; } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); } continue; } if (buffer.readIdProperty(propName)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop)); continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } if (_anySetter == null) { tokens.writeFieldName(propName); tokens.copyCurrentStructure(p); } else { TokenBuffer b2 = TokenBuffer.asCopyOfValue(p); tokens.writeFieldName(propName); tokens.append(b2); try { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt)); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); } continue; } } Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); }
Time-23
private static synchronized String getConvertedId(String id) { Map<String, String> map = cZoneIdConversion; if (map == null) { map = new HashMap<String, String>(); map.put("GMT", "UTC"); map.put("MIT", "Pacific/Apia"); map.put("HST", "Pacific/Honolulu"); map.put("AST", "America/Anchorage"); map.put("PST", "America/Los_Angeles"); map.put("MST", "America/Denver"); map.put("PNT", "America/Phoenix"); map.put("CST", "America/Chicago"); map.put("EST", "America/New_York"); map.put("IET", "America/Indianapolis"); map.put("PRT", "America/Puerto_Rico"); map.put("CNT", "America/St_Johns"); map.put("AGT", "America/Buenos_Aires"); map.put("BET", "America/Sao_Paulo"); map.put("WET", "Europe/London"); map.put("ECT", "Europe/Paris"); map.put("ART", "Africa/Cairo"); map.put("CAT", "Africa/Harare"); map.put("EET", "Europe/Bucharest"); map.put("EAT", "Africa/Addis_Ababa"); map.put("MET", "Asia/Tehran"); map.put("NET", "Asia/Yerevan"); map.put("PLT", "Asia/Karachi"); map.put("IST", "Asia/Calcutta"); map.put("BST", "Asia/Dhaka"); map.put("VST", "Asia/Saigon"); map.put("CTT", "Asia/Shanghai"); map.put("JST", "Asia/Tokyo"); map.put("ACT", "Australia/Darwin"); map.put("AET", "Australia/Sydney"); map.put("SST", "Pacific/Guadalcanal"); map.put("NST", "Pacific/Auckland"); cZoneIdConversion = map; } return map.get(id); }
private static synchronized String getConvertedId(String id) { Map<String, String> map = cZoneIdConversion; if (map == null) { map = new HashMap<String, String>(); map.put("GMT", "UTC"); map.put("WET", "WET"); map.put("CET", "CET"); map.put("MET", "CET"); map.put("ECT", "CET"); map.put("EET", "EET"); map.put("MIT", "Pacific/Apia"); map.put("HST", "Pacific/Honolulu"); map.put("AST", "America/Anchorage"); map.put("PST", "America/Los_Angeles"); map.put("MST", "America/Denver"); map.put("PNT", "America/Phoenix"); map.put("CST", "America/Chicago"); map.put("EST", "America/New_York"); map.put("IET", "America/Indiana/Indianapolis"); map.put("PRT", "America/Puerto_Rico"); map.put("CNT", "America/St_Johns"); map.put("AGT", "America/Argentina/Buenos_Aires"); map.put("BET", "America/Sao_Paulo"); map.put("ART", "Africa/Cairo"); map.put("CAT", "Africa/Harare"); map.put("EAT", "Africa/Addis_Ababa"); map.put("NET", "Asia/Yerevan"); map.put("PLT", "Asia/Karachi"); map.put("IST", "Asia/Kolkata"); map.put("BST", "Asia/Dhaka"); map.put("VST", "Asia/Ho_Chi_Minh"); map.put("CTT", "Asia/Shanghai"); map.put("JST", "Asia/Tokyo"); map.put("ACT", "Australia/Darwin"); map.put("AET", "Australia/Sydney"); map.put("SST", "Pacific/Guadalcanal"); map.put("NST", "Pacific/Auckland"); cZoneIdConversion = map; } return map.get(id); }
Csv-2
public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); return index != null ? values[index.intValue()] : null; }
public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); try { return index != null ? values[index.intValue()] : null; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException( String.format( "Index for header '%s' is %d but CSVRecord only has %d values!", name, index.intValue(), values.length)); } }
Closure-20
private Node tryFoldSimpleFunctionCall(Node n) { Preconditions.checkState(n.isCall()); Node callTarget = n.getFirstChild(); if (callTarget != null && callTarget.isName() && callTarget.getString().equals("String")) { Node value = callTarget.getNext(); if (value != null) { Node addition = IR.add( IR.string("").srcref(callTarget), value.detachFromParent()); n.getParent().replaceChild(n, addition); reportCodeChange(); return addition; } } return n; }
private Node tryFoldSimpleFunctionCall(Node n) { Preconditions.checkState(n.isCall()); Node callTarget = n.getFirstChild(); if (callTarget != null && callTarget.isName() && callTarget.getString().equals("String")) { Node value = callTarget.getNext(); if (value != null && value.getNext() == null && NodeUtil.isImmutableValue(value)) { Node addition = IR.add( IR.string("").srcref(callTarget), value.detachFromParent()); n.getParent().replaceChild(n, addition); reportCodeChange(); return addition; } } return n; }
Compress-45
public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean negative = value < 0; if (!negative && value <= maxAsOctalChar) { return formatLongOctalBytes(value, buf, offset, length); } if (length < 9) { formatLongBinary(value, buf, offset, length, negative); } formatBigIntegerBinary(value, buf, offset, length, negative); buf[offset] = (byte) (negative ? 0xff : 0x80); return offset + length; }
public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean negative = value < 0; if (!negative && value <= maxAsOctalChar) { return formatLongOctalBytes(value, buf, offset, length); } if (length < 9) { formatLongBinary(value, buf, offset, length, negative); } else { formatBigIntegerBinary(value, buf, offset, length, negative); } buf[offset] = (byte) (negative ? 0xff : 0x80); return offset + length; }
Jsoup-54
private void copyAttributes(org.jsoup.nodes.Node source, Element el) { for (Attribute attribute : source.attributes()) { String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", ""); el.setAttribute(key, attribute.getValue()); } }
private void copyAttributes(org.jsoup.nodes.Node source, Element el) { for (Attribute attribute : source.attributes()) { String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", ""); if (key.matches("[a-zA-Z_:]{1}[-a-zA-Z0-9_:.]*")) el.setAttribute(key, attribute.getValue()); } }
Compress-11
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); tais.getNextEntry(); return new TarArchiveInputStream(in); } catch (Exception e) { } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); }
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } if (signatureLength >= 512) { try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); tais.getNextEntry(); return new TarArchiveInputStream(in); } catch (Exception e) { } } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); }
JacksonXml-5
protected XmlSerializerProvider(XmlSerializerProvider src) { super(src); _rootNameLookup = src._rootNameLookup; }
protected XmlSerializerProvider(XmlSerializerProvider src) { super(src); _rootNameLookup = new XmlRootNameLookup(); }
Csv-15
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: case ALL_NON_NULL: 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); }
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: case ALL_NON_NULL: 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 (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); }
Chart-6
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ShapeList)) { return false; } return super.equals(obj); }
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ShapeList)) { return false; } ShapeList that = (ShapeList) obj; int listSize = size(); for (int i = 0; i < listSize; i++) { if (!ShapeUtilities.equal((Shape) get(i), (Shape) that.get(i))) { return false; } } return true; }
Mockito-34
public void captureArgumentsFrom(Invocation i) { int k = 0; for (Matcher m : matchers) { if (m instanceof CapturesArguments) { ((CapturesArguments) m).captureFrom(i.getArguments()[k]); } k++; } }
public void captureArgumentsFrom(Invocation i) { int k = 0; for (Matcher m : matchers) { if (m instanceof CapturesArguments && i.getArguments().length > k) { ((CapturesArguments) m).captureFrom(i.getArguments()[k]); } k++; } }
Math-34
public Iterator<Chromosome> iterator() { return chromosomes.iterator(); }
public Iterator<Chromosome> iterator() { return getChromosomes().iterator(); }
Closure-44
void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { append(" "); } append(newcode); }
void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { append(" "); } else if (c == '/' && getLastChar() == '/') { append(" "); } append(newcode); }
Compress-25
public ZipArchiveInputStream(InputStream inputStream, String encoding, boolean useUnicodeExtraFields, boolean allowStoredEntriesWithDataDescriptor) { zipEncoding = ZipEncodingHelper.getZipEncoding(encoding); this.useUnicodeExtraFields = useUnicodeExtraFields; in = new PushbackInputStream(inputStream, buf.capacity()); this.allowStoredEntriesWithDataDescriptor = allowStoredEntriesWithDataDescriptor; }
public ZipArchiveInputStream(InputStream inputStream, String encoding, boolean useUnicodeExtraFields, boolean allowStoredEntriesWithDataDescriptor) { zipEncoding = ZipEncodingHelper.getZipEncoding(encoding); this.useUnicodeExtraFields = useUnicodeExtraFields; in = new PushbackInputStream(inputStream, buf.capacity()); this.allowStoredEntriesWithDataDescriptor = allowStoredEntriesWithDataDescriptor; buf.limit(0); }
Closure-52
static boolean isSimpleNumber(String s) { int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len > 0; }
static boolean isSimpleNumber(String s) { int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len > 0 && s.charAt(0) != '0'; }
Closure-14
private static Node computeFollowNode( Node fromNode, Node node, ControlFlowAnalysis cfa) { Node parent = node.getParent(); if (parent == null || parent.isFunction() || (cfa != null && node == cfa.root)) { return null; } switch (parent.getType()) { case Token.IF: return computeFollowNode(fromNode, parent, cfa); case Token.CASE: case Token.DEFAULT_CASE: if (parent.getNext() != null) { if (parent.getNext().isCase()) { return parent.getNext().getFirstChild().getNext(); } else if (parent.getNext().isDefaultCase()) { return parent.getNext().getFirstChild(); } else { Preconditions.checkState(false, "Not reachable"); } } else { return computeFollowNode(fromNode, parent, cfa); } break; case Token.FOR: if (NodeUtil.isForIn(parent)) { return parent; } else { return parent.getFirstChild().getNext().getNext(); } case Token.WHILE: case Token.DO: return parent; case Token.TRY: if (parent.getFirstChild() == node) { if (NodeUtil.hasFinally(parent)) { return computeFallThrough(parent.getLastChild()); } else { return computeFollowNode(fromNode, parent, cfa); } } else if (NodeUtil.getCatchBlock(parent) == node){ if (NodeUtil.hasFinally(parent)) { return computeFallThrough(node.getNext()); } else { return computeFollowNode(fromNode, parent, cfa); } } else if (parent.getLastChild() == node){ if (cfa != null) { for (Node finallyNode : cfa.finallyMap.get(parent)) { cfa.createEdge(fromNode, Branch.UNCOND, finallyNode); } } return computeFollowNode(fromNode, parent, cfa); } } Node nextSibling = node.getNext(); while (nextSibling != null && nextSibling.isFunction()) { nextSibling = nextSibling.getNext(); } if (nextSibling != null) { return computeFallThrough(nextSibling); } else { return computeFollowNode(fromNode, parent, cfa); } }
private static Node computeFollowNode( Node fromNode, Node node, ControlFlowAnalysis cfa) { Node parent = node.getParent(); if (parent == null || parent.isFunction() || (cfa != null && node == cfa.root)) { return null; } switch (parent.getType()) { case Token.IF: return computeFollowNode(fromNode, parent, cfa); case Token.CASE: case Token.DEFAULT_CASE: if (parent.getNext() != null) { if (parent.getNext().isCase()) { return parent.getNext().getFirstChild().getNext(); } else if (parent.getNext().isDefaultCase()) { return parent.getNext().getFirstChild(); } else { Preconditions.checkState(false, "Not reachable"); } } else { return computeFollowNode(fromNode, parent, cfa); } break; case Token.FOR: if (NodeUtil.isForIn(parent)) { return parent; } else { return parent.getFirstChild().getNext().getNext(); } case Token.WHILE: case Token.DO: return parent; case Token.TRY: if (parent.getFirstChild() == node) { if (NodeUtil.hasFinally(parent)) { return computeFallThrough(parent.getLastChild()); } else { return computeFollowNode(fromNode, parent, cfa); } } else if (NodeUtil.getCatchBlock(parent) == node){ if (NodeUtil.hasFinally(parent)) { return computeFallThrough(node.getNext()); } else { return computeFollowNode(fromNode, parent, cfa); } } else if (parent.getLastChild() == node){ if (cfa != null) { for (Node finallyNode : cfa.finallyMap.get(parent)) { cfa.createEdge(fromNode, Branch.ON_EX, finallyNode); } } return computeFollowNode(fromNode, parent, cfa); } } Node nextSibling = node.getNext(); while (nextSibling != null && nextSibling.isFunction()) { nextSibling = nextSibling.getNext(); } if (nextSibling != null) { return computeFallThrough(nextSibling); } else { return computeFollowNode(fromNode, parent, cfa); } }
Math-56
public int[] getCounts(int index) { if (index < 0 || index >= totalSize) { throw new OutOfRangeException(index, 0, totalSize); } final int[] indices = new int[dimension]; int count = 0; for (int i = 0; i < last; i++) { int idx = 0; final int offset = uniCounterOffset[i]; while (count <= index) { count += offset; ++idx; } --idx; count -= offset; indices[i] = idx; } int idx = 1; while (count < index) { count += idx; ++idx; } --idx; indices[last] = idx; return indices; }
public int[] getCounts(int index) { if (index < 0 || index >= totalSize) { throw new OutOfRangeException(index, 0, totalSize); } final int[] indices = new int[dimension]; int count = 0; for (int i = 0; i < last; i++) { int idx = 0; final int offset = uniCounterOffset[i]; while (count <= index) { count += offset; ++idx; } --idx; count -= offset; indices[i] = idx; } indices[last] = index - count; return indices; }
Math-79
public static double distance(int[] p1, int[] p2) { int sum = 0; for (int i = 0; i < p1.length; i++) { final int dp = p1[i] - p2[i]; sum += dp * dp; } return Math.sqrt(sum); }
public static double distance(int[] p1, int[] p2) { double sum = 0; for (int i = 0; i < p1.length; i++) { final double dp = p1[i] - p2[i]; sum += dp * dp; } return Math.sqrt(sum); }
Jsoup-53
public String chompBalanced(char open, char close) { int start = -1; int end = -1; int depth = 0; char last = 0; do { if (isEmpty()) break; Character c = consume(); if (last == 0 || last != ESC) { if (c.equals(open)) { depth++; if (start == -1) start = pos; } else if (c.equals(close)) depth--; } if (depth > 0 && last != 0) end = pos; last = c; } while (depth > 0); return (end >= 0) ? queue.substring(start, end) : ""; }
public String chompBalanced(char open, char close) { int start = -1; int end = -1; int depth = 0; char last = 0; boolean inQuote = false; do { if (isEmpty()) break; Character c = consume(); if (last == 0 || last != ESC) { if (c.equals('\'') || c.equals('"') && c != open) inQuote = !inQuote; if (inQuote) continue; if (c.equals(open)) { depth++; if (start == -1) start = pos; } else if (c.equals(close)) depth--; } if (depth > 0 && last != 0) end = pos; last = c; } while (depth > 0); return (end >= 0) ? queue.substring(start, end) : ""; }
Closure-92
void replace() { if (firstNode == null) { replacementNode = candidateDefinition; return; } if (candidateDefinition != null && explicitNode != null) { explicitNode.detachFromParent(); compiler.reportCodeChange(); replacementNode = candidateDefinition; if (NodeUtil.isExpressionNode(candidateDefinition)) { candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true); Node assignNode = candidateDefinition.getFirstChild(); Node nameNode = assignNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { Node valueNode = nameNode.getNext(); assignNode.removeChild(nameNode); assignNode.removeChild(valueNode); nameNode.addChildToFront(valueNode); Node varNode = new Node(Token.VAR, nameNode); varNode.copyInformationFrom(candidateDefinition); candidateDefinition.getParent().replaceChild( candidateDefinition, varNode); nameNode.setJSDocInfo(assignNode.getJSDocInfo()); compiler.reportCodeChange(); replacementNode = varNode; } } } else { replacementNode = createDeclarationNode(); if (firstModule == minimumModule) { firstNode.getParent().addChildBefore(replacementNode, firstNode); } else { int indexOfDot = namespace.indexOf('.'); if (indexOfDot == -1) { compiler.getNodeForCodeInsertion(minimumModule) .addChildToBack(replacementNode); } else { ProvidedName parentName = providedNames.get(namespace.substring(0, indexOfDot)); Preconditions.checkNotNull(parentName); Preconditions.checkNotNull(parentName.replacementNode); parentName.replacementNode.getParent().addChildAfter( replacementNode, parentName.replacementNode); } } if (explicitNode != null) { explicitNode.detachFromParent(); } compiler.reportCodeChange(); } }
void replace() { if (firstNode == null) { replacementNode = candidateDefinition; return; } if (candidateDefinition != null && explicitNode != null) { explicitNode.detachFromParent(); compiler.reportCodeChange(); replacementNode = candidateDefinition; if (NodeUtil.isExpressionNode(candidateDefinition)) { candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true); Node assignNode = candidateDefinition.getFirstChild(); Node nameNode = assignNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { Node valueNode = nameNode.getNext(); assignNode.removeChild(nameNode); assignNode.removeChild(valueNode); nameNode.addChildToFront(valueNode); Node varNode = new Node(Token.VAR, nameNode); varNode.copyInformationFrom(candidateDefinition); candidateDefinition.getParent().replaceChild( candidateDefinition, varNode); nameNode.setJSDocInfo(assignNode.getJSDocInfo()); compiler.reportCodeChange(); replacementNode = varNode; } } } else { replacementNode = createDeclarationNode(); if (firstModule == minimumModule) { firstNode.getParent().addChildBefore(replacementNode, firstNode); } else { int indexOfDot = namespace.lastIndexOf('.'); if (indexOfDot == -1) { compiler.getNodeForCodeInsertion(minimumModule) .addChildToBack(replacementNode); } else { ProvidedName parentName = providedNames.get(namespace.substring(0, indexOfDot)); Preconditions.checkNotNull(parentName); Preconditions.checkNotNull(parentName.replacementNode); parentName.replacementNode.getParent().addChildAfter( replacementNode, parentName.replacementNode); } } if (explicitNode != null) { explicitNode.detachFromParent(); } compiler.reportCodeChange(); } }
Compress-10
private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { for (ZipArchiveEntry ze : entries.keySet()) { OffsetEntry offsetEntry = entries.get(ze); long offset = offsetEntry.headerOffset; archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH); byte[] b = new byte[SHORT]; archive.readFully(b); int fileNameLen = ZipShort.getValue(b); archive.readFully(b); int extraFieldLen = ZipShort.getValue(b); int lenToSkip = fileNameLen; while (lenToSkip > 0) { int skipped = archive.skipBytes(lenToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip file name in" + " local file header"); } lenToSkip -= skipped; } byte[] localExtraData = new byte[extraFieldLen]; archive.readFully(localExtraData); ze.setExtra(localExtraData); offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH + SHORT + SHORT + fileNameLen + extraFieldLen; if (entriesWithoutUTF8Flag.containsKey(ze)) { String orig = ze.getName(); NameAndComment nc = entriesWithoutUTF8Flag.get(ze); ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment); if (!orig.equals(ze.getName())) { nameMap.remove(orig); nameMap.put(ze.getName(), ze); } } } }
private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { Map<ZipArchiveEntry, OffsetEntry> origMap = new LinkedHashMap<ZipArchiveEntry, OffsetEntry>(entries); entries.clear(); for (ZipArchiveEntry ze : origMap.keySet()) { OffsetEntry offsetEntry = origMap.get(ze); long offset = offsetEntry.headerOffset; archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH); byte[] b = new byte[SHORT]; archive.readFully(b); int fileNameLen = ZipShort.getValue(b); archive.readFully(b); int extraFieldLen = ZipShort.getValue(b); int lenToSkip = fileNameLen; while (lenToSkip > 0) { int skipped = archive.skipBytes(lenToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip file name in" + " local file header"); } lenToSkip -= skipped; } byte[] localExtraData = new byte[extraFieldLen]; archive.readFully(localExtraData); ze.setExtra(localExtraData); offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH + SHORT + SHORT + fileNameLen + extraFieldLen; if (entriesWithoutUTF8Flag.containsKey(ze)) { String orig = ze.getName(); NameAndComment nc = entriesWithoutUTF8Flag.get(ze); ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment); if (!orig.equals(ze.getName())) { nameMap.remove(orig); nameMap.put(ze.getName(), ze); } } entries.put(ze, offsetEntry); } }
Closure-121
private void inlineNonConstants( Var v, ReferenceCollection referenceInfo, boolean maybeModifiedArguments) { int refCount = referenceInfo.references.size(); Reference declaration = referenceInfo.references.get(0); Reference init = referenceInfo.getInitializingReference(); int firstRefAfterInit = (declaration == init) ? 2 : 3; if (refCount > 1 && isImmutableAndWellDefinedVariable(v, referenceInfo)) { Node value; if (init != null) { value = init.getAssignedValue(); } else { Node srcLocation = declaration.getNode(); value = NodeUtil.newUndefinedNode(srcLocation); } Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } else if (refCount == firstRefAfterInit) { Reference reference = referenceInfo.references.get( firstRefAfterInit - 1); if (canInline(declaration, init, reference)) { inline(v, declaration, init, reference); staleVars.add(v); } } else if (declaration != init && refCount == 2) { if (isValidDeclaration(declaration) && isValidInitialization(init)) { Node value = init.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } } if (!maybeModifiedArguments && !staleVars.contains(v) && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime()) { List<Reference> refs = referenceInfo.references; for (int i = 1 ; i < refs.size(); i++) { Node nameNode = refs.get(i).getNode(); if (aliasCandidates.containsKey(nameNode)) { AliasCandidate candidate = aliasCandidates.get(nameNode); if (!staleVars.contains(candidate.alias) && !isVarInlineForbidden(candidate.alias)) { Reference aliasInit; aliasInit = candidate.refInfo.getInitializingReference(); Node value = aliasInit.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(candidate.alias, value, candidate.refInfo.references); staleVars.add(candidate.alias); } } } } }
private void inlineNonConstants( Var v, ReferenceCollection referenceInfo, boolean maybeModifiedArguments) { int refCount = referenceInfo.references.size(); Reference declaration = referenceInfo.references.get(0); Reference init = referenceInfo.getInitializingReference(); int firstRefAfterInit = (declaration == init) ? 2 : 3; if (refCount > 1 && isImmutableAndWellDefinedVariable(v, referenceInfo)) { Node value; if (init != null) { value = init.getAssignedValue(); } else { Node srcLocation = declaration.getNode(); value = NodeUtil.newUndefinedNode(srcLocation); } Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } else if (refCount == firstRefAfterInit) { Reference reference = referenceInfo.references.get( firstRefAfterInit - 1); if (canInline(declaration, init, reference)) { inline(v, declaration, init, reference); staleVars.add(v); } } else if (declaration != init && refCount == 2) { if (isValidDeclaration(declaration) && isValidInitialization(init)) { Node value = init.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(v, value, referenceInfo.references); staleVars.add(v); } } if (!maybeModifiedArguments && !staleVars.contains(v) && referenceInfo.isWellDefined() && referenceInfo.isAssignedOnceInLifetime() && (isInlineableDeclaredConstant(v, referenceInfo) || referenceInfo.isOnlyAssignmentSameScopeAsDeclaration())) { List<Reference> refs = referenceInfo.references; for (int i = 1 ; i < refs.size(); i++) { Node nameNode = refs.get(i).getNode(); if (aliasCandidates.containsKey(nameNode)) { AliasCandidate candidate = aliasCandidates.get(nameNode); if (!staleVars.contains(candidate.alias) && !isVarInlineForbidden(candidate.alias)) { Reference aliasInit; aliasInit = candidate.refInfo.getInitializingReference(); Node value = aliasInit.getAssignedValue(); Preconditions.checkNotNull(value); inlineWellDefinedVariable(candidate.alias, value, candidate.refInfo.references); staleVars.add(candidate.alias); } } } } }
Jsoup-59
final void newAttribute() { if (attributes == null) attributes = new Attributes(); if (pendingAttributeName != null) { pendingAttributeName = pendingAttributeName.trim(); Attribute attribute; if (hasPendingAttributeValue) attribute = new Attribute(pendingAttributeName, pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS); else if (hasEmptyAttributeValue) attribute = new Attribute(pendingAttributeName, ""); else attribute = new BooleanAttribute(pendingAttributeName); attributes.put(attribute); } pendingAttributeName = null; hasEmptyAttributeValue = false; hasPendingAttributeValue = false; reset(pendingAttributeValue); pendingAttributeValueS = null; }
final void newAttribute() { if (attributes == null) attributes = new Attributes(); if (pendingAttributeName != null) { pendingAttributeName = pendingAttributeName.trim(); if (pendingAttributeName.length() > 0) { Attribute attribute; if (hasPendingAttributeValue) attribute = new Attribute(pendingAttributeName, pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS); else if (hasEmptyAttributeValue) attribute = new Attribute(pendingAttributeName, ""); else attribute = new BooleanAttribute(pendingAttributeName); attributes.put(attribute); } } pendingAttributeName = null; hasEmptyAttributeValue = false; hasPendingAttributeValue = false; reset(pendingAttributeValue); pendingAttributeValueS = null; }
Lang-28
public int translate(CharSequence input, int index, Writer out) throws IOException { if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; } int end = start; while(input.charAt(end) != ';') { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { return 0; } out.write(entityValue); return 2 + (end - start) + (isHex ? 1 : 0) + 1; } return 0; }
public int translate(CharSequence input, int index, Writer out) throws IOException { if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; } int end = start; while(input.charAt(end) != ';') { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { return 0; } if(entityValue > 0xFFFF) { char[] chrs = Character.toChars(entityValue); out.write(chrs[0]); out.write(chrs[1]); } else { out.write(entityValue); } return 2 + (end - start) + (isHex ? 1 : 0) + 1; } return 0; }
Math-87
private Integer getBasicRow(final int col) { Integer row = null; for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) { if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) { if (row == null) { row = i; } else { return null; } } } return row; }
private Integer getBasicRow(final int col) { Integer row = null; for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) { if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) { row = i; } else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) { return null; } } return row; }
JacksonCore-23
public DefaultPrettyPrinter createInstance() { return new DefaultPrettyPrinter(this); }
public DefaultPrettyPrinter createInstance() { if (getClass() != DefaultPrettyPrinter.class) { throw new IllegalStateException("Failed `createInstance()`: "+getClass().getName() +" does not override method; it has to"); } return new DefaultPrettyPrinter(this); }
Closure-122
private void handleBlockComment(Comment comment) { if (comment.getValue().indexOf("/* @") != -1 || comment.getValue().indexOf("\n * @") != -1) { errorReporter.warning( SUSPICIOUS_COMMENT_WARNING, sourceName, comment.getLineno(), "", 0); } }
private void handleBlockComment(Comment comment) { Pattern p = Pattern.compile("(/|(\n[ \t]*))\\*[ \t]*@[a-zA-Z]"); if (p.matcher(comment.getValue()).find()) { errorReporter.warning( SUSPICIOUS_COMMENT_WARNING, sourceName, comment.getLineno(), "", 0); } }
JacksonDatabind-8
protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit) { final int mask = (1 << typeIndex); _hasNonDefaultCreator = true; AnnotatedWithParams oldOne = _creators[typeIndex]; if (oldOne != null) { if ((_explicitCreators & mask) != 0) { if (!explicit) { return; } } if (oldOne.getClass() == newOne.getClass()) { throw new IllegalArgumentException("Conflicting "+TYPE_DESCS[typeIndex] +" creators: already had explicitly marked "+oldOne+", encountered "+newOne); } } if (explicit) { _explicitCreators |= mask; } _creators[typeIndex] = _fixAccess(newOne); }
protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit) { final int mask = (1 << typeIndex); _hasNonDefaultCreator = true; AnnotatedWithParams oldOne = _creators[typeIndex]; if (oldOne != null) { boolean verify; if ((_explicitCreators & mask) != 0) { if (!explicit) { return; } verify = true; } else { verify = !explicit; } if (verify && (oldOne.getClass() == newOne.getClass())) { Class<?> oldType = oldOne.getRawParameterType(0); Class<?> newType = newOne.getRawParameterType(0); if (oldType == newType) { throw new IllegalArgumentException("Conflicting "+TYPE_DESCS[typeIndex] +" creators: already had explicitly marked "+oldOne+", encountered "+newOne); } if (newType.isAssignableFrom(oldType)) { return; } } } if (explicit) { _explicitCreators |= mask; } _creators[typeIndex] = _fixAccess(newOne); }
JacksonDatabind-49
public Object generateId(Object forPojo) { id = generator.generateId(forPojo); return id; }
public Object generateId(Object forPojo) { if (id == null) { id = generator.generateId(forPojo); } return id; }
Jsoup-6
static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); StringBuffer accum = new StringBuffer(string.length()); while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); } } m.appendTail(accum); return accum.toString(); }
static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); StringBuffer accum = new StringBuffer(string.length()); while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { String c = Character.toString((char) charval); m.appendReplacement(accum, Matcher.quoteReplacement(c)); } else { m.appendReplacement(accum, Matcher.quoteReplacement(m.group(0))); } } m.appendTail(accum); return accum.toString(); }
Cli-12
protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = Util.stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { if (options.hasOption(arg.substring(0, 2))) { tokens.add(arg.substring(0, 2)); tokens.add(arg.substring(2)); } else { eatTheRest = stopAtNonOption; tokens.add(arg); } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); }
protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { List tokens = new ArrayList(); boolean eatTheRest = false; for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if ("--".equals(arg)) { eatTheRest = true; tokens.add("--"); } else if ("-".equals(arg)) { tokens.add("-"); } else if (arg.startsWith("-")) { String opt = Util.stripLeadingHyphens(arg); if (options.hasOption(opt)) { tokens.add(arg); } else { if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) { tokens.add(arg.substring(0, arg.indexOf('='))); tokens.add(arg.substring(arg.indexOf('=') + 1)); } else if (options.hasOption(arg.substring(0, 2))) { tokens.add(arg.substring(0, 2)); tokens.add(arg.substring(2)); } else { eatTheRest = stopAtNonOption; tokens.add(arg); } } } else { tokens.add(arg); } if (eatTheRest) { for (i++; i < arguments.length; i++) { tokens.add(arguments[i]); } } } return (String[]) tokens.toArray(new String[tokens.size()]); }
Codec-5
void decode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; } for (int i = 0; i < inAvail; i++) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } byte b = in[inPos++]; if (b == PAD) { eof = true; break; } else { if (b >= 0 && b < DECODE_TABLE.length) { int result = DECODE_TABLE[b]; if (result >= 0) { modulus = (++modulus) % 4; x = (x << 6) + result; if (modulus == 0) { buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); buffer[pos++] = (byte) (x & MASK_8BITS); } } } } } if (eof && modulus != 0) { x = x << 6; switch (modulus) { case 2 : x = x << 6; buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); break; case 3 : buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); break; } } }
void decode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; } for (int i = 0; i < inAvail; i++) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } byte b = in[inPos++]; if (b == PAD) { eof = true; break; } else { if (b >= 0 && b < DECODE_TABLE.length) { int result = DECODE_TABLE[b]; if (result >= 0) { modulus = (++modulus) % 4; x = (x << 6) + result; if (modulus == 0) { buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); buffer[pos++] = (byte) (x & MASK_8BITS); } } } } } if (eof && modulus != 0) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } x = x << 6; switch (modulus) { case 2 : x = x << 6; buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); break; case 3 : buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); break; } } }
Chart-26
protected AxisState drawLabel(String label, Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { if (state == null) { throw new IllegalArgumentException("Null 'state' argument."); } if ((label == null) || (label.equals(""))) { return state; } Font font = getLabelFont(); RectangleInsets insets = getLabelInsets(); g2.setFont(font); g2.setPaint(getLabelPaint()); FontMetrics fm = g2.getFontMetrics(); Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm); Shape hotspot = null; if (edge == RectangleEdge.TOP) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() - insets.getBottom() - h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorUp(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.BOTTOM) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() + insets.getTop() + h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorDown(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.LEFT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() - insets.getRight() - w / 2.0); float labely = (float) dataArea.getCenterY(); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorLeft(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } else if (edge == RectangleEdge.RIGHT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() + Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() + insets.getLeft() + w / 2.0); float labely = (float) (dataArea.getY() + dataArea.getHeight() / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorRight(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } if (plotState != null && hotspot != null) { ChartRenderingInfo owner = plotState.getOwner(); EntityCollection entities = owner.getEntityCollection(); if (entities != null) { entities.add(new AxisLabelEntity(this, hotspot, this.labelToolTip, this.labelURL)); } } return state; }
protected AxisState drawLabel(String label, Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { if (state == null) { throw new IllegalArgumentException("Null 'state' argument."); } if ((label == null) || (label.equals(""))) { return state; } Font font = getLabelFont(); RectangleInsets insets = getLabelInsets(); g2.setFont(font); g2.setPaint(getLabelPaint()); FontMetrics fm = g2.getFontMetrics(); Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm); Shape hotspot = null; if (edge == RectangleEdge.TOP) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() - insets.getBottom() - h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorUp(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.BOTTOM) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle(), labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) dataArea.getCenterX(); float labely = (float) (state.getCursor() + insets.getTop() + h / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorDown(insets.getTop() + labelBounds.getHeight() + insets.getBottom()); } else if (edge == RectangleEdge.LEFT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() - insets.getRight() - w / 2.0); float labely = (float) dataArea.getCenterY(); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorLeft(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } else if (edge == RectangleEdge.RIGHT) { AffineTransform t = AffineTransform.getRotateInstance( getLabelAngle() + Math.PI / 2.0, labelBounds.getCenterX(), labelBounds.getCenterY()); Shape rotatedLabelBounds = t.createTransformedShape(labelBounds); labelBounds = rotatedLabelBounds.getBounds2D(); float w = (float) labelBounds.getWidth(); float h = (float) labelBounds.getHeight(); float labelx = (float) (state.getCursor() + insets.getLeft() + w / 2.0); float labely = (float) (dataArea.getY() + dataArea.getHeight() / 2.0); TextUtilities.drawRotatedString(label, g2, labelx, labely, TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, TextAnchor.CENTER); hotspot = new Rectangle2D.Float(labelx - w / 2.0f, labely - h / 2.0f, w, h); state.cursorRight(insets.getLeft() + labelBounds.getWidth() + insets.getRight()); } if (plotState != null && hotspot != null) { ChartRenderingInfo owner = plotState.getOwner(); if (owner != null) { EntityCollection entities = owner.getEntityCollection(); if (entities != null) { entities.add(new AxisLabelEntity(this, hotspot, this.labelToolTip, this.labelURL)); } } } return state; }
Math-105
public double getSumSquaredErrors() { return sumYY - sumXY * sumXY / sumXX; }
public double getSumSquaredErrors() { return Math.max(0d, sumYY - sumXY * sumXY / sumXX); }
Time-18
public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } long instant; instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant < iCutoverMillis) { instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant >= iCutoverMillis) { throw new IllegalArgumentException("Specified date does not exist"); } } return instant; }
public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } long instant; try { instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } catch (IllegalFieldValueException ex) { if (monthOfYear != 2 || dayOfMonth != 29) { throw ex; } instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, 28, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant >= iCutoverMillis) { throw ex; } } if (instant < iCutoverMillis) { instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); if (instant >= iCutoverMillis) { throw new IllegalArgumentException("Specified date does not exist"); } } return instant; }
JacksonDatabind-34
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (_isInt) { visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER); } else { Class<?> h = handledType(); if (h == BigDecimal.class) { visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER); } else { visitor.expectNumberFormat(typeHint); } } }
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { if (_isInt) { visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER); } else { Class<?> h = handledType(); if (h == BigDecimal.class) { visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_DECIMAL); } else { visitor.expectNumberFormat(typeHint); } } }
Mockito-28
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) { for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) { mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject(); } }
private void injectMockCandidate(Class<?> awaitingInjectionClazz, Set<Object> mocks, Object fieldInstance) { for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) { Object injected = mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject(); mocks.remove(injected); } }
Mockito-29
public void describeTo(Description description) { description.appendText("same("); appendQuoting(description); description.appendText(wanted.toString()); appendQuoting(description); description.appendText(")"); }
public void describeTo(Description description) { description.appendText("same("); appendQuoting(description); description.appendText(wanted == null ? "null" : wanted.toString()); appendQuoting(description); description.appendText(")"); }
Lang-52
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'': if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"': out.write('\\'); out.write('"'); break; case '\\': out.write('\\'); out.write('\\'); break; default : out.write(ch); break; } } } }
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'': if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"': out.write('\\'); out.write('"'); break; case '\\': out.write('\\'); out.write('\\'); break; case '/': out.write('\\'); out.write('/'); break; default : out.write(ch); break; } } } }
Jsoup-34
int nextIndexOf(CharSequence seq) { char startChar = seq.charAt(0); for (int offset = pos; offset < length; offset++) { if (startChar != input[offset]) while(++offset < length && startChar != input[offset]); int i = offset + 1; int last = i + seq.length()-1; if (offset < length) { for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++); if (i == last) return offset - pos; } } return -1; }
int nextIndexOf(CharSequence seq) { char startChar = seq.charAt(0); for (int offset = pos; offset < length; offset++) { if (startChar != input[offset]) while(++offset < length && startChar != input[offset]); int i = offset + 1; int last = i + seq.length()-1; if (offset < length && last <= length) { for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++); if (i == last) return offset - pos; } } return -1; }
Closure-86
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: return true; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: return true; case Token.IN: return true; default: if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } }
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: return false; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: return true; case Token.IN: return true; default: if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } }
Jsoup-32
public Element clone() { Element clone = (Element) super.clone(); clone.classNames(); return clone; }
public Element clone() { Element clone = (Element) super.clone(); clone.classNames = null; return clone; }
Jsoup-64
private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rawtext); tb.markInsertionMode(); tb.transition(Text); }
private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) { tb.tokeniser.transition(TokeniserState.Rawtext); tb.markInsertionMode(); tb.transition(Text); tb.insert(startTag); }
Lang-11
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); }
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 = ' '; } } } else { if (end <= start) { throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + 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); }