bug_id
stringlengths
5
19
func_before
stringlengths
49
25.9k
func_after
stringlengths
45
26k
Compress-35
public static boolean verifyCheckSum(byte[] header) { long storedSum = 0; long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) { if ('0' <= b && b <= '7' && digits++ < 6) { storedSum = storedSum * 8 + b - '0'; } else if (digits > 0) { digits = 6; } b = ' '; } unsignedSum += 0xff & b; signedSum += b; } return storedSum == unsignedSum || storedSum == signedSum; }
public static boolean verifyCheckSum(byte[] header) { long storedSum = parseOctal(header, CHKSUM_OFFSET, CHKSUMLEN); long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) { b = ' '; } unsignedSum += 0xff & b; signedSum += b; } return storedSum == unsignedSum || storedSum == signedSum; }
JacksonCore-21
public JsonToken nextToken() throws IOException { if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) { if (_currToken.isStructEnd()) { if (_headContext.isStartHandled()) { return (_currToken = null); } } else if (_currToken.isScalarValue()) { if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) { return (_currToken = null); } } } TokenFilterContext ctxt = _exposedContext; if (ctxt != null) { while (true) { JsonToken t = ctxt.nextTokenToRead(); if (t != null) { _currToken = t; return t; } if (ctxt == _headContext) { _exposedContext = null; if (ctxt.inArray()) { t = delegate.getCurrentToken(); _currToken = t; return t; } break; } ctxt = _headContext.findChildOf(ctxt); _exposedContext = ctxt; if (ctxt == null) { throw _constructError("Unexpected problem: chain of filtered context broken"); } } } JsonToken t = delegate.nextToken(); if (t == null) { _currToken = t; return t; } TokenFilter f; switch (t.id()) { case ID_START_ARRAY: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildArrayContext(f, true); return (_currToken = t); } if (f == null) { delegate.skipChildren(); break; } f = _headContext.checkValue(f); if (f == null) { delegate.skipChildren(); break; } if (f != TokenFilter.INCLUDE_ALL) { f = f.filterStartArray(); } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildArrayContext(f, true); return (_currToken = t); } _headContext = _headContext.createChildArrayContext(f, false); if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; case ID_START_OBJECT: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildObjectContext(f, true); return (_currToken = t); } if (f == null) { delegate.skipChildren(); break; } f = _headContext.checkValue(f); if (f == null) { delegate.skipChildren(); break; } if (f != TokenFilter.INCLUDE_ALL) { f = f.filterStartObject(); } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildObjectContext(f, true); return (_currToken = t); } _headContext = _headContext.createChildObjectContext(f, false); if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; case ID_END_ARRAY: case ID_END_OBJECT: { boolean returnEnd = _headContext.isStartHandled(); f = _headContext.getFilter(); if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) { f.filterFinishArray(); } _headContext = _headContext.getParent(); _itemFilter = _headContext.getFilter(); if (returnEnd) { return (_currToken = t); } } break; case ID_FIELD_NAME: { final String name = delegate.getCurrentName(); f = _headContext.setFieldName(name); if (f == TokenFilter.INCLUDE_ALL) { _itemFilter = f; if (!_includePath) { if (_includeImmediateParent && !_headContext.isStartHandled()) { t = _headContext.nextTokenToRead(); _exposedContext = _headContext; } } return (_currToken = t); } if (f == null) { delegate.nextToken(); delegate.skipChildren(); break; } f = f.includeProperty(name); if (f == null) { delegate.nextToken(); delegate.skipChildren(); break; } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { if (_includePath) { return (_currToken = t); } } if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; } default: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { return (_currToken = t); } if (f != null) { f = _headContext.checkValue(f); if ((f == TokenFilter.INCLUDE_ALL) || ((f != null) && f.includeValue(delegate))) { return (_currToken = t); } } break; } return _nextToken2(); }
public JsonToken nextToken() throws IOException { if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) { if (!_includePath) { if (_currToken.isStructEnd()) { if (_headContext.isStartHandled()) { return (_currToken = null); } } else if (_currToken.isScalarValue()) { if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) { return (_currToken = null); } } } } TokenFilterContext ctxt = _exposedContext; if (ctxt != null) { while (true) { JsonToken t = ctxt.nextTokenToRead(); if (t != null) { _currToken = t; return t; } if (ctxt == _headContext) { _exposedContext = null; if (ctxt.inArray()) { t = delegate.getCurrentToken(); _currToken = t; return t; } break; } ctxt = _headContext.findChildOf(ctxt); _exposedContext = ctxt; if (ctxt == null) { throw _constructError("Unexpected problem: chain of filtered context broken"); } } } JsonToken t = delegate.nextToken(); if (t == null) { _currToken = t; return t; } TokenFilter f; switch (t.id()) { case ID_START_ARRAY: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildArrayContext(f, true); return (_currToken = t); } if (f == null) { delegate.skipChildren(); break; } f = _headContext.checkValue(f); if (f == null) { delegate.skipChildren(); break; } if (f != TokenFilter.INCLUDE_ALL) { f = f.filterStartArray(); } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildArrayContext(f, true); return (_currToken = t); } _headContext = _headContext.createChildArrayContext(f, false); if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; case ID_START_OBJECT: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildObjectContext(f, true); return (_currToken = t); } if (f == null) { delegate.skipChildren(); break; } f = _headContext.checkValue(f); if (f == null) { delegate.skipChildren(); break; } if (f != TokenFilter.INCLUDE_ALL) { f = f.filterStartObject(); } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { _headContext = _headContext.createChildObjectContext(f, true); return (_currToken = t); } _headContext = _headContext.createChildObjectContext(f, false); if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; case ID_END_ARRAY: case ID_END_OBJECT: { boolean returnEnd = _headContext.isStartHandled(); f = _headContext.getFilter(); if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) { f.filterFinishArray(); } _headContext = _headContext.getParent(); _itemFilter = _headContext.getFilter(); if (returnEnd) { return (_currToken = t); } } break; case ID_FIELD_NAME: { final String name = delegate.getCurrentName(); f = _headContext.setFieldName(name); if (f == TokenFilter.INCLUDE_ALL) { _itemFilter = f; if (!_includePath) { if (_includeImmediateParent && !_headContext.isStartHandled()) { t = _headContext.nextTokenToRead(); _exposedContext = _headContext; } } return (_currToken = t); } if (f == null) { delegate.nextToken(); delegate.skipChildren(); break; } f = f.includeProperty(name); if (f == null) { delegate.nextToken(); delegate.skipChildren(); break; } _itemFilter = f; if (f == TokenFilter.INCLUDE_ALL) { if (_includePath) { return (_currToken = t); } } if (_includePath) { t = _nextTokenWithBuffering(_headContext); if (t != null) { _currToken = t; return t; } } break; } default: f = _itemFilter; if (f == TokenFilter.INCLUDE_ALL) { return (_currToken = t); } if (f != null) { f = _headContext.checkValue(f); if ((f == TokenFilter.INCLUDE_ALL) || ((f != null) && f.includeValue(delegate))) { return (_currToken = t); } } break; } return _nextToken2(); }
Lang-5
public static Locale toLocale(final String str) { if (str == null) { return null; } final int len = str.length(); if (len < 2) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } final char ch4 = str.charAt(4); if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } if (len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); }
public static Locale toLocale(final String str) { if (str == null) { return null; } final int len = str.length(); if (len < 2) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch0 = str.charAt(0); if (ch0 == '_') { if (len < 3) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch1 = str.charAt(1); final char ch2 = str.charAt(2); if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 3) { return new Locale("", str.substring(1, 3)); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(3) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale("", str.substring(1, 3), str.substring(4)); } else { final char ch1 = str.charAt(1); if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } final char ch4 = str.charAt(4); if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } if (len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } }
Codec-17
public static String newStringIso8859_1(final byte[] bytes) { return new String(bytes, Charsets.ISO_8859_1); }
public static String newStringIso8859_1(final byte[] bytes) { return newString(bytes, Charsets.ISO_8859_1); }
Compress-12
public TarArchiveEntry getNextTarEntry() throws IOException { if (hasHitEOF) { return null; } if (currEntry != null) { long numToSkip = entrySize - entryOffset; while (numToSkip > 0) { long skipped = skip(numToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip current tar entry"); } numToSkip -= skipped; } readBuf = null; } byte[] headerBuf = getRecord(); if (hasHitEOF) { currEntry = null; return null; } currEntry = new TarArchiveEntry(headerBuf); entryOffset = 0; entrySize = currEntry.getSize(); if (currEntry.isGNULongNameEntry()) { StringBuffer longName = new StringBuffer(); byte[] buf = new byte[SMALL_BUFFER_SIZE]; int length = 0; while ((length = read(buf)) >= 0) { longName.append(new String(buf, 0, length)); } getNextEntry(); if (currEntry == null) { return null; } if (longName.length() > 0 && longName.charAt(longName.length() - 1) == 0) { longName.deleteCharAt(longName.length() - 1); } currEntry.setName(longName.toString()); } if (currEntry.isPaxHeader()){ paxHeaders(); } if (currEntry.isGNUSparse()){ readGNUSparse(); } entrySize = currEntry.getSize(); return currEntry; }
public TarArchiveEntry getNextTarEntry() throws IOException { if (hasHitEOF) { return null; } if (currEntry != null) { long numToSkip = entrySize - entryOffset; while (numToSkip > 0) { long skipped = skip(numToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip current tar entry"); } numToSkip -= skipped; } readBuf = null; } byte[] headerBuf = getRecord(); if (hasHitEOF) { currEntry = null; return null; } try { currEntry = new TarArchiveEntry(headerBuf); } catch (IllegalArgumentException e) { IOException ioe = new IOException("Error detected parsing the header"); ioe.initCause(e); throw ioe; } entryOffset = 0; entrySize = currEntry.getSize(); if (currEntry.isGNULongNameEntry()) { StringBuffer longName = new StringBuffer(); byte[] buf = new byte[SMALL_BUFFER_SIZE]; int length = 0; while ((length = read(buf)) >= 0) { longName.append(new String(buf, 0, length)); } getNextEntry(); if (currEntry == null) { return null; } if (longName.length() > 0 && longName.charAt(longName.length() - 1) == 0) { longName.deleteCharAt(longName.length() - 1); } currEntry.setName(longName.toString()); } if (currEntry.isPaxHeader()){ paxHeaders(); } if (currEntry.isGNUSparse()){ readGNUSparse(); } entrySize = currEntry.getSize(); return currEntry; }
Lang-31
public static boolean containsAny(CharSequence cs, char[] searchChars) { if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = cs.length(); int searchLength = searchChars.length; for (int i = 0; i < csLength; i++) { char ch = cs.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { return true; } } } return false; }
public static boolean containsAny(CharSequence cs, char[] searchChars) { if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = cs.length(); int searchLength = searchChars.length; int csLastIndex = csLength - 1; int searchLastIndex = searchLength - 1; for (int i = 0; i < csLength; i++) { char ch = cs.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { if (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) { if (searchChars[j + 1] == cs.charAt(i + 1)) { return true; } } else { return true; } } } } return false; }
Closure-116
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; }
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; }
Mockito-18
Object returnValueFor(Class<?> type) { if (Primitives.isPrimitiveOrWrapper(type)) { return Primitives.defaultValueForPrimitiveOrWrapper(type); } else if (type == Collection.class) { return new LinkedList<Object>(); } else if (type == Set.class) { return new HashSet<Object>(); } else if (type == HashSet.class) { return new HashSet<Object>(); } else if (type == SortedSet.class) { return new TreeSet<Object>(); } else if (type == TreeSet.class) { return new TreeSet<Object>(); } else if (type == LinkedHashSet.class) { return new LinkedHashSet<Object>(); } else if (type == List.class) { return new LinkedList<Object>(); } else if (type == LinkedList.class) { return new LinkedList<Object>(); } else if (type == ArrayList.class) { return new ArrayList<Object>(); } else if (type == Map.class) { return new HashMap<Object, Object>(); } else if (type == HashMap.class) { return new HashMap<Object, Object>(); } else if (type == SortedMap.class) { return new TreeMap<Object, Object>(); } else if (type == TreeMap.class) { return new TreeMap<Object, Object>(); } else if (type == LinkedHashMap.class) { return new LinkedHashMap<Object, Object>(); } return null; }
Object returnValueFor(Class<?> type) { if (Primitives.isPrimitiveOrWrapper(type)) { return Primitives.defaultValueForPrimitiveOrWrapper(type); } else if (type == Iterable.class) { return new ArrayList<Object>(0); } else if (type == Collection.class) { return new LinkedList<Object>(); } else if (type == Set.class) { return new HashSet<Object>(); } else if (type == HashSet.class) { return new HashSet<Object>(); } else if (type == SortedSet.class) { return new TreeSet<Object>(); } else if (type == TreeSet.class) { return new TreeSet<Object>(); } else if (type == LinkedHashSet.class) { return new LinkedHashSet<Object>(); } else if (type == List.class) { return new LinkedList<Object>(); } else if (type == LinkedList.class) { return new LinkedList<Object>(); } else if (type == ArrayList.class) { return new ArrayList<Object>(); } else if (type == Map.class) { return new HashMap<Object, Object>(); } else if (type == HashMap.class) { return new HashMap<Object, Object>(); } else if (type == SortedMap.class) { return new TreeMap<Object, Object>(); } else if (type == TreeMap.class) { return new TreeMap<Object, Object>(); } else if (type == LinkedHashMap.class) { return new LinkedHashMap<Object, Object>(); } return null; }
Time-7
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); int defaultYear = chrono.year().get(instantLocal); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, defaultYear); 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(); int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, defaultYear); 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; }
Closure-18
Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } hoistExterns(externsRoot); boolean staleInputs = false; if (options.dependencyOptions.needsManagement() && options.closurePass) { for (CompilerInput input : inputs) { for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); if (hasErrors()) { return null; } } } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } }
Node parseInputs() { boolean devMode = options.devMode != DevMode.OFF; if (externsRoot != null) { externsRoot.detachChildren(); } if (jsRoot != null) { jsRoot.detachChildren(); } jsRoot = IR.block(); jsRoot.setIsSyntheticBlock(true); externsRoot = IR.block(); externsRoot.setIsSyntheticBlock(true); externAndJsRoot = IR.block(externsRoot, jsRoot); externAndJsRoot.setIsSyntheticBlock(true); if (options.tracer.isOn()) { tracker = new PerformanceTracker(jsRoot, options.tracer); addChangeHandler(tracker.getCodeChangeHandler()); } Tracer tracer = newTracer("parseInputs"); try { for (CompilerInput input : externs) { Node n = input.getAstRoot(this); if (hasErrors()) { return null; } externsRoot.addChildToBack(n); } if (options.transformAMDToCJSModules || options.processCommonJSModules) { processAMDAndCommonJSModules(); } hoistExterns(externsRoot); boolean staleInputs = false; if (options.dependencyOptions.needsManagement()) { for (CompilerInput input : inputs) { for (String provide : input.getProvides()) { getTypeRegistry().forwardDeclareType(provide); } } try { inputs = (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph) .manageDependencies(options.dependencyOptions, inputs); staleInputs = true; } catch (CircularDependencyException e) { report(JSError.make( JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage())); if (hasErrors()) { return null; } } catch (MissingProvideException e) { report(JSError.make( MISSING_ENTRY_ERROR, e.getMessage())); if (hasErrors()) { return null; } } } hoistNoCompileFiles(); if (staleInputs) { repartitionInputs(); } for (CompilerInput input : inputs) { Node n = input.getAstRoot(this); if (n == null) { continue; } if (devMode) { runSanityCheck(); if (hasErrors()) { return null; } } if (options.sourceMapOutputPath != null || options.nameReferenceReportPath != null) { SourceInformationAnnotator sia = new SourceInformationAnnotator( input.getName(), options.devMode != DevMode.OFF); NodeTraversal.traverse(this, n, sia); } jsRoot.addChildToBack(n); } if (hasErrors()) { return null; } return externAndJsRoot; } finally { stopTracer(tracer, "parseInputs"); } }
JacksonDatabind-17
public boolean useForType(JavaType t) { switch (_appliesFor) { case NON_CONCRETE_AND_ARRAYS: while (t.isArrayType()) { t = t.getContentType(); } case OBJECT_AND_NON_CONCRETE: return (t.getRawClass() == Object.class) || (!t.isConcrete() || TreeNode.class.isAssignableFrom(t.getRawClass())); case NON_FINAL: while (t.isArrayType()) { t = t.getContentType(); } return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass()); default: return (t.getRawClass() == Object.class); } }
public boolean useForType(JavaType t) { switch (_appliesFor) { case NON_CONCRETE_AND_ARRAYS: while (t.isArrayType()) { t = t.getContentType(); } case OBJECT_AND_NON_CONCRETE: return (t.getRawClass() == Object.class) || (!t.isConcrete() && !TreeNode.class.isAssignableFrom(t.getRawClass())); case NON_FINAL: while (t.isArrayType()) { t = t.getContentType(); } return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass()); default: return (t.getRawClass() == Object.class); } }
Math-52
public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) { double u1u1 = u1.getNormSq(); double u2u2 = u2.getNormSq(); double v1v1 = v1.getNormSq(); double v2v2 = v2.getNormSq(); if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) { throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR); } v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1); double u1u2 = u1.dotProduct(u2); double v1v2 = v1.dotProduct(v2); double coeffU = u1u2 / u1u1; double coeffV = v1v2 / u1u1; double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV)); double alpha = coeffU - beta * coeffV; v2 = new Vector3D(alpha, v1, beta, v2); Vector3D uRef = u1; Vector3D vRef = v1; Vector3D v1Su1 = v1.subtract(u1); Vector3D v2Su2 = v2.subtract(u2); Vector3D k = v1Su1.crossProduct(v2Su2); Vector3D u3 = u1.crossProduct(u2); double c = k.dotProduct(u3); if (c == 0) { Vector3D v3 = Vector3D.crossProduct(v1, v2); Vector3D v3Su3 = v3.subtract(u3); k = v1Su1.crossProduct(v3Su3); Vector3D u2Prime = u1.crossProduct(u3); c = k.dotProduct(u2Prime); if (c == 0) { k = v2Su2.crossProduct(v3Su3);; c = k.dotProduct(u2.crossProduct(u3));; if (c == 0) { q0 = 1.0; q1 = 0.0; q2 = 0.0; q3 = 0.0; return; } uRef = u2; vRef = v2; } } c = FastMath.sqrt(c); double inv = 1.0 / (c + c); q1 = inv * k.getX(); q2 = inv * k.getY(); q3 = inv * k.getZ(); k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2, uRef.getZ() * q1 - uRef.getX() * q3, uRef.getX() * q2 - uRef.getY() * q1); q0 = vRef.dotProduct(k) / (2 * k.getNormSq()); }
public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) { double u1u1 = u1.getNormSq(); double u2u2 = u2.getNormSq(); double v1v1 = v1.getNormSq(); double v2v2 = v2.getNormSq(); if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) { throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR); } v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1); double u1u2 = u1.dotProduct(u2); double v1v2 = v1.dotProduct(v2); double coeffU = u1u2 / u1u1; double coeffV = v1v2 / u1u1; double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV)); double alpha = coeffU - beta * coeffV; v2 = new Vector3D(alpha, v1, beta, v2); Vector3D uRef = u1; Vector3D vRef = v1; Vector3D v1Su1 = v1.subtract(u1); Vector3D v2Su2 = v2.subtract(u2); Vector3D k = v1Su1.crossProduct(v2Su2); Vector3D u3 = u1.crossProduct(u2); double c = k.dotProduct(u3); final double inPlaneThreshold = 0.001; if (c <= inPlaneThreshold * k.getNorm() * u3.getNorm()) { Vector3D v3 = Vector3D.crossProduct(v1, v2); Vector3D v3Su3 = v3.subtract(u3); k = v1Su1.crossProduct(v3Su3); Vector3D u2Prime = u1.crossProduct(u3); c = k.dotProduct(u2Prime); if (c <= inPlaneThreshold * k.getNorm() * u2Prime.getNorm()) { k = v2Su2.crossProduct(v3Su3);; c = k.dotProduct(u2.crossProduct(u3));; if (c <= 0) { q0 = 1.0; q1 = 0.0; q2 = 0.0; q3 = 0.0; return; } uRef = u2; vRef = v2; } } c = FastMath.sqrt(c); double inv = 1.0 / (c + c); q1 = inv * k.getX(); q2 = inv * k.getY(); q3 = inv * k.getZ(); k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2, uRef.getZ() * q1 - uRef.getX() * q3, uRef.getX() * q2 - uRef.getY() * q1); q0 = vRef.dotProduct(k) / (2 * k.getNormSq()); }
Chart-8
public Week(Date time, TimeZone zone) { this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault()); }
public Week(Date time, TimeZone zone) { this(time, zone, Locale.getDefault()); }
Chart-11
public static boolean equal(GeneralPath p1, GeneralPath p2) { if (p1 == null) { return (p2 == null); } if (p2 == null) { return false; } if (p1.getWindingRule() != p2.getWindingRule()) { return false; } PathIterator iterator1 = p1.getPathIterator(null); PathIterator iterator2 = p1.getPathIterator(null); double[] d1 = new double[6]; double[] d2 = new double[6]; boolean done = iterator1.isDone() && iterator2.isDone(); while (!done) { if (iterator1.isDone() != iterator2.isDone()) { return false; } int seg1 = iterator1.currentSegment(d1); int seg2 = iterator2.currentSegment(d2); if (seg1 != seg2) { return false; } if (!Arrays.equals(d1, d2)) { return false; } iterator1.next(); iterator2.next(); done = iterator1.isDone() && iterator2.isDone(); } return true; }
public static boolean equal(GeneralPath p1, GeneralPath p2) { if (p1 == null) { return (p2 == null); } if (p2 == null) { return false; } if (p1.getWindingRule() != p2.getWindingRule()) { return false; } PathIterator iterator1 = p1.getPathIterator(null); PathIterator iterator2 = p2.getPathIterator(null); double[] d1 = new double[6]; double[] d2 = new double[6]; boolean done = iterator1.isDone() && iterator2.isDone(); while (!done) { if (iterator1.isDone() != iterator2.isDone()) { return false; } int seg1 = iterator1.currentSegment(d1); int seg2 = iterator2.currentSegment(d2); if (seg1 != seg2) { return false; } if (!Arrays.equals(d1, d2)) { return false; } iterator1.next(); iterator2.next(); done = iterator1.isDone() && iterator2.isDone(); } return true; }
Closure-10
static boolean mayBeString(Node n, boolean recurse) { if (recurse) { return allResultsMatch(n, MAY_BE_STRING_PREDICATE); } else { return mayBeStringHelper(n); } }
static boolean mayBeString(Node n, boolean recurse) { if (recurse) { return anyResultsMatch(n, MAY_BE_STRING_PREDICATE); } else { return mayBeStringHelper(n); } }
Jsoup-40
public DocumentType(String name, String publicId, String systemId, String baseUri) { super(baseUri); Validate.notEmpty(name); attr("name", name); attr("publicId", publicId); attr("systemId", systemId); }
public DocumentType(String name, String publicId, String systemId, String baseUri) { super(baseUri); attr("name", name); attr("publicId", publicId); attr("systemId", systemId); }
Time-24
public long computeMillis(boolean resetFields, String text) { SavedField[] savedFields = iSavedFields; int count = iSavedFieldsCount; if (iSavedFieldsShared) { iSavedFields = savedFields = (SavedField[])iSavedFields.clone(); iSavedFieldsShared = false; } sort(savedFields, count); if (count > 0) { DurationField months = DurationFieldType.months().getField(iChrono); DurationField days = DurationFieldType.days().getField(iChrono); DurationField first = savedFields[0].iField.getDurationField(); if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) { saveField(DateTimeFieldType.year(), iDefaultYear); return computeMillis(resetFields, text); } } long millis = iMillis; try { for (int i = 0; i < count; i++) { millis = savedFields[i].set(millis, resetFields); } } catch (IllegalFieldValueException e) { if (text != null) { e.prependMessage("Cannot parse \"" + text + '"'); } throw e; } if (iZone == null) { millis -= iOffset; } else { int offset = iZone.getOffsetFromLocal(millis); millis -= offset; if (offset != iZone.getOffset(millis)) { String message = "Illegal instant due to time zone offset transition (" + iZone + ')'; if (text != null) { message = "Cannot parse \"" + text + "\": " + message; } throw new IllegalArgumentException(message); } } return millis; }
public long computeMillis(boolean resetFields, String text) { SavedField[] savedFields = iSavedFields; int count = iSavedFieldsCount; if (iSavedFieldsShared) { iSavedFields = savedFields = (SavedField[])iSavedFields.clone(); iSavedFieldsShared = false; } sort(savedFields, count); if (count > 0) { DurationField months = DurationFieldType.months().getField(iChrono); DurationField days = DurationFieldType.days().getField(iChrono); DurationField first = savedFields[0].iField.getDurationField(); if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) { saveField(DateTimeFieldType.year(), iDefaultYear); return computeMillis(resetFields, text); } } long millis = iMillis; try { for (int i = 0; i < count; i++) { millis = savedFields[i].set(millis, resetFields); } if (resetFields) { for (int i = 0; i < count; i++) { millis = savedFields[i].set(millis, i == (count - 1)); } } } catch (IllegalFieldValueException e) { if (text != null) { e.prependMessage("Cannot parse \"" + text + '"'); } throw e; } if (iZone == null) { millis -= iOffset; } else { int offset = iZone.getOffsetFromLocal(millis); millis -= offset; if (offset != iZone.getOffset(millis)) { String message = "Illegal instant due to time zone offset transition (" + iZone + ')'; if (text != null) { message = "Cannot parse \"" + text + "\": " + message; } throw new IllegalArgumentException(message); } } return millis; }
Cli-26
public static Option create(String opt) throws IllegalArgumentException { Option option = new Option(opt, description); option.setLongOpt(longopt); option.setRequired(required); option.setOptionalArg(optionalArg); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); OptionBuilder.reset(); return option; }
public static Option create(String opt) throws IllegalArgumentException { Option option = null; try { option = new Option(opt, description); option.setLongOpt(longopt); option.setRequired(required); option.setOptionalArg(optionalArg); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); } finally { OptionBuilder.reset(); } return option; }
Math-82
private Integer getPivotRow(final int col, final SimplexTableau tableau) { double minRatio = Double.MAX_VALUE; Integer minRatioPos = null; 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 (MathUtils.compareTo(entry, 0, epsilon) >= 0) { final double ratio = rhs / entry; if (ratio < minRatio) { minRatio = ratio; minRatioPos = i; } } } return minRatioPos; }
private Integer getPivotRow(final int col, final SimplexTableau tableau) { double minRatio = Double.MAX_VALUE; Integer minRatioPos = null; 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 (MathUtils.compareTo(entry, 0, epsilon) > 0) { final double ratio = rhs / entry; if (ratio < minRatio) { minRatio = ratio; minRatioPos = i; } } } return minRatioPos; }
JacksonDatabind-82
protected void addBeanProps(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { final boolean isConcrete = !beanDesc.getType().isAbstract(); final SettableBeanProperty[] creatorProps = isConcrete ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig()) : null; final boolean hasCreatorProps = (creatorProps != null); JsonIgnoreProperties.Value ignorals = ctxt.getConfig() .getDefaultPropertyIgnorals(beanDesc.getBeanClass(), beanDesc.getClassInfo()); Set<String> ignored; if (ignorals != null) { boolean ignoreAny = ignorals.getIgnoreUnknown(); builder.setIgnoreUnknownProperties(ignoreAny); ignored = ignorals.getIgnored(); for (String propName : ignored) { builder.addIgnorable(propName); } } else { ignored = Collections.emptySet(); } AnnotatedMethod anySetterMethod = beanDesc.findAnySetter(); AnnotatedMember anySetterField = null; if (anySetterMethod != null) { builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod)); } else { anySetterField = beanDesc.findAnySetterField(); if(anySetterField != null) { builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField)); } } if (anySetterMethod == null && anySetterField == null) { Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames(); if (ignored2 != null) { for (String propName : ignored2) { builder.addIgnorable(propName); } } } final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS) && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS); List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt, beanDesc, builder, beanDesc.findProperties(), ignored); if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs); } } for (BeanPropertyDefinition propDef : propDefs) { SettableBeanProperty prop = null; if (propDef.hasSetter()) { JavaType propertyType = propDef.getSetter().getParameterType(0); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (propDef.hasField()) { JavaType propertyType = propDef.getField().getType(); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (useGettersAsSetters && propDef.hasGetter()) { AnnotatedMethod getter = propDef.getGetter(); Class<?> rawPropertyType = getter.getRawType(); if (Collection.class.isAssignableFrom(rawPropertyType) || Map.class.isAssignableFrom(rawPropertyType)) { prop = constructSetterlessProperty(ctxt, beanDesc, propDef); } } if (hasCreatorProps && propDef.hasConstructorParameter()) { final String name = propDef.getName(); CreatorProperty cprop = null; if (creatorProps != null) { for (SettableBeanProperty cp : creatorProps) { if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) { cprop = (CreatorProperty) cp; break; } } } if (cprop == null) { List<String> n = new ArrayList<>(); for (SettableBeanProperty cp : creatorProps) { n.add(cp.getName()); } ctxt.reportBadPropertyDefinition(beanDesc, propDef, "Could not find creator property with name '%s' (known Creator properties: %s)", name, n); continue; } if (prop != null) { cprop.setFallbackSetter(prop); } prop = cprop; builder.addCreatorProperty(cprop); continue; } if (prop != null) { Class<?>[] views = propDef.findViews(); if (views == null) { if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) { views = NO_VIEWS; } } prop.setViews(views); builder.addProperty(prop); } } }
protected void addBeanProps(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { final boolean isConcrete = !beanDesc.getType().isAbstract(); final SettableBeanProperty[] creatorProps = isConcrete ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig()) : null; final boolean hasCreatorProps = (creatorProps != null); JsonIgnoreProperties.Value ignorals = ctxt.getConfig() .getDefaultPropertyIgnorals(beanDesc.getBeanClass(), beanDesc.getClassInfo()); Set<String> ignored; if (ignorals != null) { boolean ignoreAny = ignorals.getIgnoreUnknown(); builder.setIgnoreUnknownProperties(ignoreAny); ignored = ignorals.findIgnoredForDeserialization(); for (String propName : ignored) { builder.addIgnorable(propName); } } else { ignored = Collections.emptySet(); } AnnotatedMethod anySetterMethod = beanDesc.findAnySetter(); AnnotatedMember anySetterField = null; if (anySetterMethod != null) { builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod)); } else { anySetterField = beanDesc.findAnySetterField(); if(anySetterField != null) { builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField)); } } if (anySetterMethod == null && anySetterField == null) { Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames(); if (ignored2 != null) { for (String propName : ignored2) { builder.addIgnorable(propName); } } } final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS) && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS); List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt, beanDesc, builder, beanDesc.findProperties(), ignored); if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs); } } for (BeanPropertyDefinition propDef : propDefs) { SettableBeanProperty prop = null; if (propDef.hasSetter()) { JavaType propertyType = propDef.getSetter().getParameterType(0); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (propDef.hasField()) { JavaType propertyType = propDef.getField().getType(); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (useGettersAsSetters && propDef.hasGetter()) { AnnotatedMethod getter = propDef.getGetter(); Class<?> rawPropertyType = getter.getRawType(); if (Collection.class.isAssignableFrom(rawPropertyType) || Map.class.isAssignableFrom(rawPropertyType)) { prop = constructSetterlessProperty(ctxt, beanDesc, propDef); } } if (hasCreatorProps && propDef.hasConstructorParameter()) { final String name = propDef.getName(); CreatorProperty cprop = null; if (creatorProps != null) { for (SettableBeanProperty cp : creatorProps) { if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) { cprop = (CreatorProperty) cp; break; } } } if (cprop == null) { List<String> n = new ArrayList<>(); for (SettableBeanProperty cp : creatorProps) { n.add(cp.getName()); } ctxt.reportBadPropertyDefinition(beanDesc, propDef, "Could not find creator property with name '%s' (known Creator properties: %s)", name, n); continue; } if (prop != null) { cprop.setFallbackSetter(prop); } prop = cprop; builder.addCreatorProperty(cprop); continue; } if (prop != null) { Class<?>[] views = propDef.findViews(); if (views == null) { if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) { views = NO_VIEWS; } } prop.setViews(views); builder.addProperty(prop); } } }
Jsoup-35
boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else if (isWhitespace(c)) { tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else if (!tb.framesetOk()) { return false; } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, "pre", "listing")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertForm(startTag, true); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "dd", "dt")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), "dd", "dt")) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, "applet", "marquee", "object")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, "param", "source", "track")) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { startTag.name("img"); return tb.process(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), "name", "action", "prompt")) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); HtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in("optgroup", "option")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in("rp", "rt")) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "dd", "dt")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6"); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) { OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); for (int si = 0; si < stack.size() && si < 64; si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(formatEl.tag(), tb.getBaseUri()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, "applet", "marquee", "object")) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: break; } return true; }
boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else if (isWhitespace(c)) { tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else if (!tb.framesetOk()) { return false; } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, "pre", "listing")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertForm(startTag, true); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "dd", "dt")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), "dd", "dt")) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, "applet", "marquee", "object")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, "param", "source", "track")) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { startTag.name("img"); return tb.process(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), "name", "action", "prompt")) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); HtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in("optgroup", "option")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in("rp", "rt")) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "dd", "dt")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6"); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) { OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); for (int si = 0; si < stack.size() && si < 64; si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(formatEl.tag(), tb.getBaseUri()); adopter.attributes().addAll(formatEl.attributes()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, "applet", "marquee", "object")) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: break; } return true; }
Lang-48
public EqualsBuilder append(Object lhs, Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { isEquals = lhs.equals(rhs); } else if (lhs.getClass() != rhs.getClass()) { this.setEquals(false); } else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { append((Object[]) lhs, (Object[]) rhs); } return this; }
public EqualsBuilder append(Object lhs, Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { if (lhs instanceof java.math.BigDecimal) { isEquals = (((java.math.BigDecimal)lhs).compareTo(rhs) == 0); } else { isEquals = lhs.equals(rhs); } } else if (lhs.getClass() != rhs.getClass()) { this.setEquals(false); } else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { append((Object[]) lhs, (Object[]) rhs); } return this; }
Chart-20
public ValueMarker(double value, Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha) { super(paint, stroke, paint, stroke, alpha); this.value = value; }
public ValueMarker(double value, Paint paint, Stroke stroke, Paint outlinePaint, Stroke outlineStroke, float alpha) { super(paint, stroke, outlinePaint, outlineStroke, alpha); this.value = value; }
Lang-45
public static String abbreviate(String str, int lower, int upper, String appendToEnd) { if (str == null) { return null; } if (str.length() == 0) { return StringUtils.EMPTY; } if (upper == -1 || upper > str.length()) { upper = str.length(); } if (upper < lower) { upper = lower; } StringBuffer result = new StringBuffer(); int index = StringUtils.indexOf(str, " ", lower); if (index == -1) { result.append(str.substring(0, upper)); if (upper != str.length()) { result.append(StringUtils.defaultString(appendToEnd)); } } else if (index > upper) { result.append(str.substring(0, upper)); result.append(StringUtils.defaultString(appendToEnd)); } else { result.append(str.substring(0, index)); result.append(StringUtils.defaultString(appendToEnd)); } return result.toString(); }
public static String abbreviate(String str, int lower, int upper, String appendToEnd) { if (str == null) { return null; } if (str.length() == 0) { return StringUtils.EMPTY; } if (lower > str.length()) { lower = str.length(); } if (upper == -1 || upper > str.length()) { upper = str.length(); } if (upper < lower) { upper = lower; } StringBuffer result = new StringBuffer(); int index = StringUtils.indexOf(str, " ", lower); if (index == -1) { result.append(str.substring(0, upper)); if (upper != str.length()) { result.append(StringUtils.defaultString(appendToEnd)); } } else if (index > upper) { result.append(str.substring(0, upper)); result.append(StringUtils.defaultString(appendToEnd)); } else { result.append(str.substring(0, index)); result.append(StringUtils.defaultString(appendToEnd)); } return result.toString(); }
Codec-7
public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, true)); }
public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); }
Gson-2
public static <T1> TypeAdapterFactory newTypeHierarchyFactory( final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) { final Class<? super T2> requestedType = typeToken.getRawType(); if (!clazz.isAssignableFrom(requestedType)) { return null; } return (TypeAdapter<T2>) typeAdapter; } @Override public String toString() { return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]"; } }; }
public static <T1> TypeAdapterFactory newTypeHierarchyFactory( final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) { return new TypeAdapterFactory() { @SuppressWarnings("unchecked") public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) { final Class<? super T2> requestedType = typeToken.getRawType(); if (!clazz.isAssignableFrom(requestedType)) { return null; } return (TypeAdapter<T2>) new TypeAdapter<T1>() { @Override public void write(JsonWriter out, T1 value) throws IOException { typeAdapter.write(out, value); } @Override public T1 read(JsonReader in) throws IOException { T1 result = typeAdapter.read(in); if (result != null && !requestedType.isInstance(result)) { throw new JsonSyntaxException("Expected a " + requestedType.getName() + " but was " + result.getClass().getName()); } return result; } }; } @Override public String toString() { return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]"; } }; }
Chart-5
public XYDataItem addOrUpdate(Number x, Number y) { if (x == null) { throw new IllegalArgumentException("Null 'x' argument."); } XYDataItem overwritten = null; int index = indexOf(x); if (index >= 0 && !this.allowDuplicateXValues) { XYDataItem existing = (XYDataItem) this.data.get(index); try { overwritten = (XYDataItem) existing.clone(); } catch (CloneNotSupportedException e) { throw new SeriesException("Couldn't clone XYDataItem!"); } existing.setY(y); } else { if (this.autoSort) { this.data.add(-index - 1, new XYDataItem(x, y)); } else { this.data.add(new XYDataItem(x, y)); } if (getItemCount() > this.maximumItemCount) { this.data.remove(0); } } fireSeriesChanged(); return overwritten; }
public XYDataItem addOrUpdate(Number x, Number y) { if (x == null) { throw new IllegalArgumentException("Null 'x' argument."); } if (this.allowDuplicateXValues) { add(x, y); return null; } XYDataItem overwritten = null; int index = indexOf(x); if (index >= 0) { XYDataItem existing = (XYDataItem) this.data.get(index); try { overwritten = (XYDataItem) existing.clone(); } catch (CloneNotSupportedException e) { throw new SeriesException("Couldn't clone XYDataItem!"); } existing.setY(y); } else { if (this.autoSort) { this.data.add(-index - 1, new XYDataItem(x, y)); } else { this.data.add(new XYDataItem(x, y)); } if (getItemCount() > this.maximumItemCount) { this.data.remove(0); } } fireSeriesChanged(); return overwritten; }
Closure-5
private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; Set<String> validProperties = Sets.newHashSet(); for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } String propName = parent.getLastChild().getString(); if (!validProperties.contains(propName)) { if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) { validProperties.add(propName); } else { return false; } } continue; } if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { continue; } if (!val.isObjectLit()) { return false; } for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { return false; } validProperties.add(child.getString()); Node childVal = child.getFirstChild(); for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { return false; } refNode = refNode.getParent(); } } } ret = true; } return ret; }
private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; Set<String> validProperties = Sets.newHashSet(); for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } if (gramps.isDelProp()) { return false; } String propName = parent.getLastChild().getString(); if (!validProperties.contains(propName)) { if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) { validProperties.add(propName); } else { return false; } } continue; } if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { continue; } if (!val.isObjectLit()) { return false; } for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { return false; } validProperties.add(child.getString()); Node childVal = child.getFirstChild(); for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { return false; } refNode = refNode.getParent(); } } } ret = true; } return ret; }
Math-64
protected VectorialPointValuePair doOptimize() throws FunctionEvaluationException, OptimizationException, IllegalArgumentException { solvedCols = Math.min(rows, cols); diagR = new double[cols]; jacNorm = new double[cols]; beta = new double[cols]; permutation = new int[cols]; lmDir = new double[cols]; double delta = 0; double xNorm = 0; double[] diag = new double[cols]; double[] oldX = new double[cols]; double[] oldRes = new double[rows]; double[] work1 = new double[cols]; double[] work2 = new double[cols]; double[] work3 = new double[cols]; updateResidualsAndCost(); lmPar = 0; boolean firstIteration = true; VectorialPointValuePair current = new VectorialPointValuePair(point, objective); while (true) { incrementIterationsCounter(); VectorialPointValuePair previous = current; updateJacobian(); qrDecomposition(); qTy(residuals); for (int k = 0; k < solvedCols; ++k) { int pk = permutation[k]; jacobian[k][pk] = diagR[pk]; } if (firstIteration) { xNorm = 0; for (int k = 0; k < cols; ++k) { double dk = jacNorm[k]; if (dk == 0) { dk = 1.0; } double xk = dk * point[k]; xNorm += xk * xk; diag[k] = dk; } xNorm = Math.sqrt(xNorm); delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm); } double maxCosine = 0; if (cost != 0) { for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; double s = jacNorm[pj]; if (s != 0) { double sum = 0; for (int i = 0; i <= j; ++i) { sum += jacobian[i][pj] * residuals[i]; } maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost)); } } } if (maxCosine <= orthoTolerance) { return current; } for (int j = 0; j < cols; ++j) { diag[j] = Math.max(diag[j], jacNorm[j]); } for (double ratio = 0; ratio < 1.0e-4;) { for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; oldX[pj] = point[pj]; } double previousCost = cost; double[] tmpVec = residuals; residuals = oldRes; oldRes = tmpVec; determineLMParameter(oldRes, delta, diag, work1, work2, work3); double lmNorm = 0; for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; lmDir[pj] = -lmDir[pj]; point[pj] = oldX[pj] + lmDir[pj]; double s = diag[pj] * lmDir[pj]; lmNorm += s * s; } lmNorm = Math.sqrt(lmNorm); if (firstIteration) { delta = Math.min(delta, lmNorm); } updateResidualsAndCost(); current = new VectorialPointValuePair(point, objective); double actRed = -1.0; if (0.1 * cost < previousCost) { double r = cost / previousCost; actRed = 1.0 - r * r; } for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; double dirJ = lmDir[pj]; work1[j] = 0; for (int i = 0; i <= j; ++i) { work1[i] += jacobian[i][pj] * dirJ; } } double coeff1 = 0; for (int j = 0; j < solvedCols; ++j) { coeff1 += work1[j] * work1[j]; } double pc2 = previousCost * previousCost; coeff1 = coeff1 / pc2; double coeff2 = lmPar * lmNorm * lmNorm / pc2; double preRed = coeff1 + 2 * coeff2; double dirDer = -(coeff1 + coeff2); ratio = (preRed == 0) ? 0 : (actRed / preRed); if (ratio <= 0.25) { double tmp = (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5; if ((0.1 * cost >= previousCost) || (tmp < 0.1)) { tmp = 0.1; } delta = tmp * Math.min(delta, 10.0 * lmNorm); lmPar /= tmp; } else if ((lmPar == 0) || (ratio >= 0.75)) { delta = 2 * lmNorm; lmPar *= 0.5; } if (ratio >= 1.0e-4) { firstIteration = false; xNorm = 0; for (int k = 0; k < cols; ++k) { double xK = diag[k] * point[k]; xNorm += xK * xK; } xNorm = Math.sqrt(xNorm); } else { cost = previousCost; for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; point[pj] = oldX[pj]; } tmpVec = residuals; residuals = oldRes; oldRes = tmpVec; } if (checker==null) { if (((Math.abs(actRed) <= costRelativeTolerance) && (preRed <= costRelativeTolerance) && (ratio <= 2.0)) || (delta <= parRelativeTolerance * xNorm)) { return current; } } else { if (checker.converged(getIterations(), previous, current)) { return current; } } if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE, costRelativeTolerance); } else if (delta <= 2.2204e-16 * xNorm) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE, parRelativeTolerance); } else if (maxCosine <= 2.2204e-16) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE, orthoTolerance); } } } }
protected VectorialPointValuePair doOptimize() throws FunctionEvaluationException, OptimizationException, IllegalArgumentException { solvedCols = Math.min(rows, cols); diagR = new double[cols]; jacNorm = new double[cols]; beta = new double[cols]; permutation = new int[cols]; lmDir = new double[cols]; double delta = 0; double xNorm = 0; double[] diag = new double[cols]; double[] oldX = new double[cols]; double[] oldRes = new double[rows]; double[] oldObj = new double[rows]; double[] qtf = new double[rows]; double[] work1 = new double[cols]; double[] work2 = new double[cols]; double[] work3 = new double[cols]; updateResidualsAndCost(); lmPar = 0; boolean firstIteration = true; VectorialPointValuePair current = new VectorialPointValuePair(point, objective); while (true) { for (int i=0;i<rows;i++) { qtf[i]=residuals[i]; } incrementIterationsCounter(); VectorialPointValuePair previous = current; updateJacobian(); qrDecomposition(); qTy(qtf); for (int k = 0; k < solvedCols; ++k) { int pk = permutation[k]; jacobian[k][pk] = diagR[pk]; } if (firstIteration) { xNorm = 0; for (int k = 0; k < cols; ++k) { double dk = jacNorm[k]; if (dk == 0) { dk = 1.0; } double xk = dk * point[k]; xNorm += xk * xk; diag[k] = dk; } xNorm = Math.sqrt(xNorm); delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm); } double maxCosine = 0; if (cost != 0) { for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; double s = jacNorm[pj]; if (s != 0) { double sum = 0; for (int i = 0; i <= j; ++i) { sum += jacobian[i][pj] * qtf[i]; } maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost)); } } } if (maxCosine <= orthoTolerance) { updateResidualsAndCost(); current = new VectorialPointValuePair(point, objective); return current; } for (int j = 0; j < cols; ++j) { diag[j] = Math.max(diag[j], jacNorm[j]); } for (double ratio = 0; ratio < 1.0e-4;) { for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; oldX[pj] = point[pj]; } double previousCost = cost; double[] tmpVec = residuals; residuals = oldRes; oldRes = tmpVec; tmpVec = objective; objective = oldObj; oldObj = tmpVec; determineLMParameter(qtf, delta, diag, work1, work2, work3); double lmNorm = 0; for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; lmDir[pj] = -lmDir[pj]; point[pj] = oldX[pj] + lmDir[pj]; double s = diag[pj] * lmDir[pj]; lmNorm += s * s; } lmNorm = Math.sqrt(lmNorm); if (firstIteration) { delta = Math.min(delta, lmNorm); } updateResidualsAndCost(); double actRed = -1.0; if (0.1 * cost < previousCost) { double r = cost / previousCost; actRed = 1.0 - r * r; } for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; double dirJ = lmDir[pj]; work1[j] = 0; for (int i = 0; i <= j; ++i) { work1[i] += jacobian[i][pj] * dirJ; } } double coeff1 = 0; for (int j = 0; j < solvedCols; ++j) { coeff1 += work1[j] * work1[j]; } double pc2 = previousCost * previousCost; coeff1 = coeff1 / pc2; double coeff2 = lmPar * lmNorm * lmNorm / pc2; double preRed = coeff1 + 2 * coeff2; double dirDer = -(coeff1 + coeff2); ratio = (preRed == 0) ? 0 : (actRed / preRed); if (ratio <= 0.25) { double tmp = (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5; if ((0.1 * cost >= previousCost) || (tmp < 0.1)) { tmp = 0.1; } delta = tmp * Math.min(delta, 10.0 * lmNorm); lmPar /= tmp; } else if ((lmPar == 0) || (ratio >= 0.75)) { delta = 2 * lmNorm; lmPar *= 0.5; } if (ratio >= 1.0e-4) { firstIteration = false; xNorm = 0; for (int k = 0; k < cols; ++k) { double xK = diag[k] * point[k]; xNorm += xK * xK; } xNorm = Math.sqrt(xNorm); current = new VectorialPointValuePair(point, objective); if (checker != null) { if (checker.converged(getIterations(), previous, current)) { return current; } } } else { cost = previousCost; for (int j = 0; j < solvedCols; ++j) { int pj = permutation[j]; point[pj] = oldX[pj]; } tmpVec = residuals; residuals = oldRes; oldRes = tmpVec; tmpVec = objective; objective = oldObj; oldObj = tmpVec; } if (checker==null) { if (((Math.abs(actRed) <= costRelativeTolerance) && (preRed <= costRelativeTolerance) && (ratio <= 2.0)) || (delta <= parRelativeTolerance * xNorm)) { return current; } } if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE, costRelativeTolerance); } else if (delta <= 2.2204e-16 * xNorm) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE, parRelativeTolerance); } else if (maxCosine <= 2.2204e-16) { throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE, orthoTolerance); } } } }
Mockito-22
public static boolean areEqual(Object o1, Object o2) { if (o1 == null || o2 == null) { return o1 == null && o2 == null; } else if (isArray(o1)) { return isArray(o2) && areArraysEqual(o1, o2); } else { return o1.equals(o2); } }
public static boolean areEqual(Object o1, Object o2) { if (o1 == o2 ) { return true; } else if (o1 == null || o2 == null) { return o1 == null && o2 == null; } else if (isArray(o1)) { return isArray(o2) && areArraysEqual(o1, o2); } else { return o1.equals(o2); } }
JacksonXml-1
public JsonToken nextToken() throws IOException { _binaryValue = null; if (_nextToken != null) { JsonToken t = _nextToken; _currToken = t; _nextToken = null; switch (t) { case START_OBJECT: _parsingContext = _parsingContext.createChildObjectContext(-1, -1); break; case START_ARRAY: _parsingContext = _parsingContext.createChildArrayContext(-1, -1); break; case END_OBJECT: case END_ARRAY: _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); break; case FIELD_NAME: _parsingContext.setCurrentName(_xmlTokens.getLocalName()); break; default: } return t; } int token = _xmlTokens.next(); while (token == XmlTokenStream.XML_START_ELEMENT) { if (_mayBeLeaf) { _nextToken = JsonToken.FIELD_NAME; _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } if (_parsingContext.inArray()) { token = _xmlTokens.next(); _mayBeLeaf = true; continue; } String name = _xmlTokens.getLocalName(); _parsingContext.setCurrentName(name); if (_namesToWrap != null && _namesToWrap.contains(name)) { _xmlTokens.repeatStartElement(); } _mayBeLeaf = true; return (_currToken = JsonToken.FIELD_NAME); } switch (token) { case XmlTokenStream.XML_END_ELEMENT: if (_mayBeLeaf) { _mayBeLeaf = false; return (_currToken = JsonToken.VALUE_NULL); } _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT; _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); return _currToken; case XmlTokenStream.XML_ATTRIBUTE_NAME: if (_mayBeLeaf) { _mayBeLeaf = false; _nextToken = JsonToken.FIELD_NAME; _currText = _xmlTokens.getText(); _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } _parsingContext.setCurrentName(_xmlTokens.getLocalName()); return (_currToken = JsonToken.FIELD_NAME); case XmlTokenStream.XML_ATTRIBUTE_VALUE: _currText = _xmlTokens.getText(); return (_currToken = JsonToken.VALUE_STRING); case XmlTokenStream.XML_TEXT: _currText = _xmlTokens.getText(); if (_mayBeLeaf) { _mayBeLeaf = false; _xmlTokens.skipEndElement(); if (_parsingContext.inArray()) { if (_isEmpty(_currText)) { _currToken = JsonToken.END_ARRAY; _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); return _currToken; } } return (_currToken = JsonToken.VALUE_STRING); } else { if (_parsingContext.inObject() && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) { _currToken = JsonToken.END_OBJECT; _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); return _currToken; } } _parsingContext.setCurrentName(_cfgNameForTextElement); _nextToken = JsonToken.VALUE_STRING; return (_currToken = JsonToken.FIELD_NAME); case XmlTokenStream.XML_END: return (_currToken = null); } _throwInternal(); return null; }
public JsonToken nextToken() throws IOException { _binaryValue = null; if (_nextToken != null) { JsonToken t = _nextToken; _currToken = t; _nextToken = null; switch (t) { case START_OBJECT: _parsingContext = _parsingContext.createChildObjectContext(-1, -1); break; case START_ARRAY: _parsingContext = _parsingContext.createChildArrayContext(-1, -1); break; case END_OBJECT: case END_ARRAY: _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); break; case FIELD_NAME: _parsingContext.setCurrentName(_xmlTokens.getLocalName()); break; default: } return t; } int token = _xmlTokens.next(); while (token == XmlTokenStream.XML_START_ELEMENT) { if (_mayBeLeaf) { _nextToken = JsonToken.FIELD_NAME; _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } if (_parsingContext.inArray()) { token = _xmlTokens.next(); _mayBeLeaf = true; continue; } String name = _xmlTokens.getLocalName(); _parsingContext.setCurrentName(name); if (_namesToWrap != null && _namesToWrap.contains(name)) { _xmlTokens.repeatStartElement(); } _mayBeLeaf = true; return (_currToken = JsonToken.FIELD_NAME); } switch (token) { case XmlTokenStream.XML_END_ELEMENT: if (_mayBeLeaf) { _mayBeLeaf = false; if (_parsingContext.inArray()) { _nextToken = JsonToken.END_OBJECT; _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } return (_currToken = JsonToken.VALUE_NULL); } _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT; _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); return _currToken; case XmlTokenStream.XML_ATTRIBUTE_NAME: if (_mayBeLeaf) { _mayBeLeaf = false; _nextToken = JsonToken.FIELD_NAME; _currText = _xmlTokens.getText(); _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } _parsingContext.setCurrentName(_xmlTokens.getLocalName()); return (_currToken = JsonToken.FIELD_NAME); case XmlTokenStream.XML_ATTRIBUTE_VALUE: _currText = _xmlTokens.getText(); return (_currToken = JsonToken.VALUE_STRING); case XmlTokenStream.XML_TEXT: _currText = _xmlTokens.getText(); if (_mayBeLeaf) { _mayBeLeaf = false; _xmlTokens.skipEndElement(); if (_parsingContext.inArray()) { if (_isEmpty(_currText)) { _nextToken = JsonToken.END_OBJECT; _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); } } return (_currToken = JsonToken.VALUE_STRING); } else { if (_parsingContext.inObject() && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) { _currToken = JsonToken.END_OBJECT; _parsingContext = _parsingContext.getParent(); _namesToWrap = _parsingContext.getNamesToWrap(); return _currToken; } } _parsingContext.setCurrentName(_cfgNameForTextElement); _nextToken = JsonToken.VALUE_STRING; return (_currToken = JsonToken.FIELD_NAME); case XmlTokenStream.XML_END: return (_currToken = null); } _throwInternal(); return null; }
Gson-15
public JsonWriter value(double value) throws IOException { writeDeferredName(); if (Double.isNaN(value) || Double.isInfinite(value)) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Double.toString(value)); return this; }
public JsonWriter value(double value) throws IOException { writeDeferredName(); if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) { throw new IllegalArgumentException("Numeric values must be finite, but was " + value); } beforeValue(); out.append(Double.toString(value)); return this; }
Math-74
public double integrate(final FirstOrderDifferentialEquations equations, final double t0, final double[] y0, final double t, final double[] y) throws DerivativeException, IntegratorException { sanityChecks(equations, t0, y0, t, y); setEquations(equations); resetEvaluations(); final boolean forward = t > t0; final int stages = c.length + 1; if (y != y0) { System.arraycopy(y0, 0, y, 0, y0.length); } final double[][] yDotK = new double[stages][y0.length]; final double[] yTmp = new double[y0.length]; AbstractStepInterpolator interpolator; if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) { final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy(); rki.reinitialize(this, yTmp, yDotK, forward); interpolator = rki; } else { interpolator = new DummyStepInterpolator(yTmp, forward); } interpolator.storeTime(t0); stepStart = t0; double hNew = 0; boolean firstTime = true; for (StepHandler handler : stepHandlers) { handler.reset(); } CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager); boolean lastStep = false; while (!lastStep) { interpolator.shift(); double error = 0; for (boolean loop = true; loop;) { if (firstTime || !fsal) { computeDerivatives(stepStart, y, yDotK[0]); } if (firstTime) { final double[] scale; if (vecAbsoluteTolerance == null) { scale = new double[y0.length]; java.util.Arrays.fill(scale, scalAbsoluteTolerance); } else { scale = vecAbsoluteTolerance; } hNew = initializeStep(equations, forward, getOrder(), scale, stepStart, y, yDotK[0], yTmp, yDotK[1]); firstTime = false; } stepSize = hNew; for (int k = 1; k < stages; ++k) { for (int j = 0; j < y0.length; ++j) { double sum = a[k-1][0] * yDotK[0][j]; for (int l = 1; l < k; ++l) { sum += a[k-1][l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]); } for (int j = 0; j < y0.length; ++j) { double sum = b[0] * yDotK[0][j]; for (int l = 1; l < stages; ++l) { sum += b[l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } error = estimateError(yDotK, y, yTmp, stepSize); if (error <= 1.0) { interpolator.storeTime(stepStart + stepSize); if (manager.evaluateStep(interpolator)) { final double dt = manager.getEventTime() - stepStart; if (Math.abs(dt) <= Math.ulp(stepStart)) { loop = false; } else { hNew = dt; } } else { loop = false; } } else { final double factor = Math.min(maxGrowth, Math.max(minReduction, safety * Math.pow(error, exp))); hNew = filterStep(stepSize * factor, forward, false); } } final double nextStep = stepStart + stepSize; System.arraycopy(yTmp, 0, y, 0, y0.length); manager.stepAccepted(nextStep, y); lastStep = manager.stop(); interpolator.storeTime(nextStep); for (StepHandler handler : stepHandlers) { handler.handleStep(interpolator, lastStep); } stepStart = nextStep; if (fsal) { System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length); } if (manager.reset(stepStart, y) && ! lastStep) { computeDerivatives(stepStart, y, yDotK[0]); } if (! lastStep) { stepSize = filterStep(stepSize, forward, true); final double factor = Math.min(maxGrowth, Math.max(minReduction, safety * Math.pow(error, exp))); final double scaledH = stepSize * factor; final double nextT = stepStart + scaledH; final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t); hNew = filterStep(scaledH, forward, nextIsLast); } } final double stopTime = stepStart; resetInternalState(); return stopTime; }
public double integrate(final FirstOrderDifferentialEquations equations, final double t0, final double[] y0, final double t, final double[] y) throws DerivativeException, IntegratorException { sanityChecks(equations, t0, y0, t, y); setEquations(equations); resetEvaluations(); final boolean forward = t > t0; final int stages = c.length + 1; if (y != y0) { System.arraycopy(y0, 0, y, 0, y0.length); } final double[][] yDotK = new double[stages][y0.length]; final double[] yTmp = new double[y0.length]; AbstractStepInterpolator interpolator; if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) { final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy(); rki.reinitialize(this, yTmp, yDotK, forward); interpolator = rki; } else { interpolator = new DummyStepInterpolator(yTmp, forward); } interpolator.storeTime(t0); stepStart = t0; double hNew = 0; boolean firstTime = true; for (StepHandler handler : stepHandlers) { handler.reset(); } CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager); boolean lastStep = false; while (!lastStep) { interpolator.shift(); double error = 0; for (boolean loop = true; loop;) { if (firstTime || !fsal) { computeDerivatives(stepStart, y, yDotK[0]); } if (firstTime) { final double[] scale = new double[y0.length]; if (vecAbsoluteTolerance == null) { for (int i = 0; i < scale.length; ++i) { scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * Math.abs(y[i]); } } else { for (int i = 0; i < scale.length; ++i) { scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * Math.abs(y[i]); } } hNew = initializeStep(equations, forward, getOrder(), scale, stepStart, y, yDotK[0], yTmp, yDotK[1]); firstTime = false; } stepSize = hNew; for (int k = 1; k < stages; ++k) { for (int j = 0; j < y0.length; ++j) { double sum = a[k-1][0] * yDotK[0][j]; for (int l = 1; l < k; ++l) { sum += a[k-1][l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]); } for (int j = 0; j < y0.length; ++j) { double sum = b[0] * yDotK[0][j]; for (int l = 1; l < stages; ++l) { sum += b[l] * yDotK[l][j]; } yTmp[j] = y[j] + stepSize * sum; } error = estimateError(yDotK, y, yTmp, stepSize); if (error <= 1.0) { interpolator.storeTime(stepStart + stepSize); if (manager.evaluateStep(interpolator)) { final double dt = manager.getEventTime() - stepStart; if (Math.abs(dt) <= Math.ulp(stepStart)) { loop = false; } else { hNew = dt; } } else { loop = false; } } else { final double factor = Math.min(maxGrowth, Math.max(minReduction, safety * Math.pow(error, exp))); hNew = filterStep(stepSize * factor, forward, false); } } final double nextStep = stepStart + stepSize; System.arraycopy(yTmp, 0, y, 0, y0.length); manager.stepAccepted(nextStep, y); lastStep = manager.stop(); interpolator.storeTime(nextStep); for (StepHandler handler : stepHandlers) { handler.handleStep(interpolator, lastStep); } stepStart = nextStep; if (fsal) { System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length); } if (manager.reset(stepStart, y) && ! lastStep) { computeDerivatives(stepStart, y, yDotK[0]); } if (! lastStep) { stepSize = filterStep(stepSize, forward, true); final double factor = Math.min(maxGrowth, Math.max(minReduction, safety * Math.pow(error, exp))); final double scaledH = stepSize * factor; final double nextT = stepStart + scaledH; final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t); hNew = filterStep(scaledH, forward, nextIsLast); } } final double stopTime = stepStart; resetInternalState(); return stopTime; }
Gson-11
public Number read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); switch (jsonToken) { case NULL: in.nextNull(); return null; case NUMBER: return new LazilyParsedNumber(in.nextString()); default: throw new JsonSyntaxException("Expecting number, got: " + jsonToken); } }
public Number read(JsonReader in) throws IOException { JsonToken jsonToken = in.peek(); switch (jsonToken) { case NULL: in.nextNull(); return null; case NUMBER: case STRING: return new LazilyParsedNumber(in.nextString()); default: throw new JsonSyntaxException("Expecting number, got: " + jsonToken); } }
Jsoup-15
boolean process(Token t, TreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else if (isWhitespace(c)) { tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "style", "title")) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else if (!tb.framesetOk()) { return false; } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, "pre", "listing")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } Element form = tb.insert(startTag); tb.setFormElement(form); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "dd", "dt")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), "dd", "dt")) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, "applet", "marquee", "object")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, "param", "source", "track")) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { startTag.name("img"); return tb.process(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), "name", "action", "prompt")) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); TreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in("optgroup", "option")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in("rp", "rt")) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "dd", "dt")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6"); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) { OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); for (int si = 0; si < stack.size(); si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, "applet", "marquee", "object")) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: break; } return true; }
boolean process(Token t, TreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { tb.error(this); return false; } else if (isWhitespace(c)) { tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); String name = startTag.name(); if (name.equals("html")) { tb.error(this); Element html = tb.getStack().getFirst(); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); LinkedList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { return false; } else if (!tb.framesetOk()) { return false; } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); while (stack.size() > 1) stack.removeLast(); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.in(name, "pre", "listing")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } Element form = tb.insert(startTag); tb.setFormElement(form); } else if (name.equals("li")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.process(new Token.EndTag("li")); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (StringUtil.in(name, "dd", "dt")) { tb.framesetOk(false); LinkedList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.in(el.nodeName(), "dd", "dt")) { tb.process(new Token.EndTag(el.nodeName())); break; } if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p")) break; } if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); } else if (name.equals("button")) { if (tb.inButtonScope("button")) { tb.error(this); tb.process(new Token.EndTag("button")); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.process(new Token.EndTag("a")); Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.in(name, "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.process(new Token.EndTag("nobr")); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.in(name, "applet", "marquee", "object")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.in(name, "param", "source", "track")) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { startTag.name("img"); return tb.process(startTag); } else if (name.equals("isindex")) { tb.error(this); if (tb.getFormElement() != null) return false; tb.tokeniser.acknowledgeSelfClosingFlag(); tb.process(new Token.StartTag("form")); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.process(new Token.StartTag("hr")); tb.process(new Token.StartTag("label")); String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character(prompt)); Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.in(attr.getKey(), "name", "action", "prompt")) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.process(new Token.StartTag("input", inputAttribs)); tb.process(new Token.EndTag("label")); tb.process(new Token.StartTag("hr")); tb.process(new Token.EndTag("form")); } else if (name.equals("textarea")) { tb.insert(startTag); tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.process(new Token.EndTag("p")); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); TreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.in("optgroup", "option")) { if (tb.currentElement().nodeName().equals("option")) tb.process(new Token.EndTag("option")); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.in("rp", "rt")) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.tokeniser.acknowledgeSelfClosingFlag(); } else if (StringUtil.in(name, "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.name(); if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.process(new Token.EndTag("body")); if (notIgnored) return tb.process(endTag); } else if (StringUtil.in(name, "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.process(new Token.StartTag(name)); return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "dd", "dt")) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) { if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6"); } } else if (name.equals("sarcasm")) { return anyOtherEndTag(t, tb); } else if (StringUtil.in(name, "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) { OUTER: for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; LinkedList<Element> stack = tb.getStack(); for (int si = 0; si < stack.size(); si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } Element node = furthestBlock; Element lastNode = furthestBlock; INNER: for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { tb.removeFromStack(node); continue INNER; } else if (node == formatEl) break INNER; Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri()); tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.in(name, "applet", "marquee", "object")) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.process(new Token.StartTag("br")); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: break; } return true; }
JacksonDatabind-98
public Object complete(JsonParser p, DeserializationContext ctxt, PropertyValueBuffer buffer, PropertyBasedCreator creator) throws IOException { final int len = _properties.length; Object[] values = new Object[len]; for (int i = 0; i < len; ++i) { String typeId = _typeIds[i]; final ExtTypedProperty extProp = _properties[i]; if (typeId == null) { if (_tokens[i] == null) { continue; } if (!extProp.hasDefaultType()) { ctxt.reportInputMismatch(_beanType, "Missing external type id property '%s'", extProp.getTypePropertyName()); } else { typeId = extProp.getDefaultTypeId(); } } else if (_tokens[i] == null) { SettableBeanProperty prop = extProp.getProperty(); ctxt.reportInputMismatch(_beanType, "Missing property '%s' for external type id '%s'", prop.getName(), _properties[i].getTypePropertyName()); } values[i] = _deserialize(p, ctxt, i, typeId); final SettableBeanProperty prop = extProp.getProperty(); if (prop.getCreatorIndex() >= 0) { buffer.assignParameter(prop, values[i]); SettableBeanProperty typeProp = extProp.getTypeProperty(); if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) { buffer.assignParameter(typeProp, typeId); } } } Object bean = creator.build(ctxt, buffer); for (int i = 0; i < len; ++i) { SettableBeanProperty prop = _properties[i].getProperty(); if (prop.getCreatorIndex() < 0) { prop.set(bean, values[i]); } } return bean; }
public Object complete(JsonParser p, DeserializationContext ctxt, PropertyValueBuffer buffer, PropertyBasedCreator creator) throws IOException { final int len = _properties.length; Object[] values = new Object[len]; for (int i = 0; i < len; ++i) { String typeId = _typeIds[i]; final ExtTypedProperty extProp = _properties[i]; if (typeId == null) { if (_tokens[i] == null) { continue; } if (!extProp.hasDefaultType()) { ctxt.reportInputMismatch(_beanType, "Missing external type id property '%s'", extProp.getTypePropertyName()); } else { typeId = extProp.getDefaultTypeId(); } } else if (_tokens[i] == null) { SettableBeanProperty prop = extProp.getProperty(); ctxt.reportInputMismatch(_beanType, "Missing property '%s' for external type id '%s'", prop.getName(), _properties[i].getTypePropertyName()); } values[i] = _deserialize(p, ctxt, i, typeId); final SettableBeanProperty prop = extProp.getProperty(); if (prop.getCreatorIndex() >= 0) { buffer.assignParameter(prop, values[i]); SettableBeanProperty typeProp = extProp.getTypeProperty(); if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) { final Object v; if (typeProp.getType().hasRawClass(String.class)) { v = typeId; } else { TokenBuffer tb = new TokenBuffer(p, ctxt); tb.writeString(typeId); v = typeProp.getValueDeserializer().deserialize(tb.asParserOnFirstToken(), ctxt); tb.close(); } buffer.assignParameter(typeProp, v); } } } Object bean = creator.build(ctxt, buffer); for (int i = 0; i < len; ++i) { SettableBeanProperty prop = _properties[i].getProperty(); if (prop.getCreatorIndex() < 0) { prop.set(bean, values[i]); } } return bean; }
Math-69
public RealMatrix getCorrelationPValues() throws MathException { TDistribution tDistribution = new TDistributionImpl(nObs - 2); int nVars = correlationMatrix.getColumnDimension(); double[][] out = new double[nVars][nVars]; for (int i = 0; i < nVars; i++) { for (int j = 0; j < nVars; j++) { if (i == j) { out[i][j] = 0d; } else { double r = correlationMatrix.getEntry(i, j); double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r))); out[i][j] = 2 * (1 - tDistribution.cumulativeProbability(t)); } } } return new BlockRealMatrix(out); }
public RealMatrix getCorrelationPValues() throws MathException { TDistribution tDistribution = new TDistributionImpl(nObs - 2); int nVars = correlationMatrix.getColumnDimension(); double[][] out = new double[nVars][nVars]; for (int i = 0; i < nVars; i++) { for (int j = 0; j < nVars; j++) { if (i == j) { out[i][j] = 0d; } else { double r = correlationMatrix.getEntry(i, j); double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r))); out[i][j] = 2 * tDistribution.cumulativeProbability(-t); } } } return new BlockRealMatrix(out); }
Csv-11
private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] headerRecord = null; if (formatHeader.length == 0) { final CSVRecord nextRecord = this.nextRecord(); if (nextRecord != null) { headerRecord = nextRecord.values(); } } else { if (this.format.getSkipHeaderRecord()) { this.nextRecord(); } headerRecord = formatHeader; } if (headerRecord != null) { for (int i = 0; i < headerRecord.length; i++) { final String header = headerRecord[i]; final boolean containsHeader = hdrMap.containsKey(header); final boolean emptyHeader = header.trim().isEmpty(); if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) { throw new IllegalArgumentException("The header contains a duplicate name: \"" + header + "\" in " + Arrays.toString(headerRecord)); } hdrMap.put(header, Integer.valueOf(i)); } } } return hdrMap; }
private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] headerRecord = null; if (formatHeader.length == 0) { final CSVRecord nextRecord = this.nextRecord(); if (nextRecord != null) { headerRecord = nextRecord.values(); } } else { if (this.format.getSkipHeaderRecord()) { this.nextRecord(); } headerRecord = formatHeader; } if (headerRecord != null) { for (int i = 0; i < headerRecord.length; i++) { final String header = headerRecord[i]; final boolean containsHeader = hdrMap.containsKey(header); final boolean emptyHeader = header == null || header.trim().isEmpty(); if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) { throw new IllegalArgumentException("The header contains a duplicate name: \"" + header + "\" in " + Arrays.toString(headerRecord)); } hdrMap.put(header, Integer.valueOf(i)); } } } return hdrMap; }
Closure-97
private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) { error(BITWISE_OPERAND_OUT_OF_RANGE, left); return n; } if (!(rval >= 0 && rval < 32)) { error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right); return n; } int lvalInt = (int) lval; if (lvalInt != lval) { error(FRACTIONAL_BITWISE_OPERAND, left); return n; } int rvalInt = (int) rval; if (rvalInt != rval) { error(FRACTIONAL_BITWISE_OPERAND, right); return n; } switch (n.getType()) { case Token.LSH: result = lvalInt << rvalInt; break; case Token.RSH: result = lvalInt >> rvalInt; break; case Token.URSH: result = lvalInt >>> rvalInt; break; default: throw new AssertionError("Unknown shift operator: " + Node.tokenToName(n.getType())); } Node newNumber = Node.newNumber(result); n.getParent().replaceChild(n, newNumber); reportCodeChange(); return newNumber; } return n; }
private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) { error(BITWISE_OPERAND_OUT_OF_RANGE, left); return n; } if (!(rval >= 0 && rval < 32)) { error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right); return n; } int lvalInt = (int) lval; if (lvalInt != lval) { error(FRACTIONAL_BITWISE_OPERAND, left); return n; } int rvalInt = (int) rval; if (rvalInt != rval) { error(FRACTIONAL_BITWISE_OPERAND, right); return n; } switch (n.getType()) { case Token.LSH: result = lvalInt << rvalInt; break; case Token.RSH: result = lvalInt >> rvalInt; break; case Token.URSH: long lvalLong = lvalInt & 0xffffffffL; result = lvalLong >>> rvalInt; break; default: throw new AssertionError("Unknown shift operator: " + Node.tokenToName(n.getType())); } Node newNumber = Node.newNumber(result); n.getParent().replaceChild(n, newNumber); reportCodeChange(); return newNumber; } return n; }
Jsoup-2
private void parseStartTag() { tq.consume("<"); String tagName = tq.consumeWord(); if (tagName.length() == 0) { tq.addFirst("&lt;"); parseTextNode(); return; } Attributes attributes = new Attributes(); while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); Element child = new Element(tag, baseUri, attributes); boolean isEmptyElement = tag.isEmpty(); if (tq.matchChomp("/>")) { isEmptyElement = true; } else { tq.matchChomp(">"); } addChildToParent(child, isEmptyElement); if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); Node dataNode; if (tag.equals(titleTag) || tag.equals(textareaTag)) dataNode = TextNode.createFromEncoded(data, baseUri); else dataNode = new DataNode(data, baseUri); child.appendChild(dataNode); } if (child.tagName().equals("base")) { String href = child.absUrl("href"); if (href.length() != 0) { baseUri = href; doc.setBaseUri(href); } } }
private void parseStartTag() { tq.consume("<"); String tagName = tq.consumeWord(); if (tagName.length() == 0) { tq.addFirst("&lt;"); parseTextNode(); return; } Attributes attributes = new Attributes(); while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); Element child = new Element(tag, baseUri, attributes); boolean isEmptyElement = tag.isEmpty(); if (tq.matchChomp("/>")) { isEmptyElement = true; } else { tq.matchChomp(">"); } addChildToParent(child, isEmptyElement); if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); popStackToClose(tag); Node dataNode; if (tag.equals(titleTag) || tag.equals(textareaTag)) dataNode = TextNode.createFromEncoded(data, baseUri); else dataNode = new DataNode(data, baseUri); child.appendChild(dataNode); } if (child.tagName().equals("base")) { String href = child.absUrl("href"); if (href.length() != 0) { baseUri = href; doc.setBaseUri(href); } } }
Jsoup-88
public String getValue() { return val; }
public String getValue() { return Attributes.checkNotNull(val); }
Jsoup-86
public XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.childNodeSize() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; }
public XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.children().size() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; }
Closure-105
void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right, Node parent) { if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) { return; } Node arrayNode = left.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return; } String joinString = NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = new StringBuilder(); int foldedSize = 0; Node elem = arrayNode.getFirstChild(); while (elem != null) { if (NodeUtil.isImmutableValue(elem)) { if (sb.length() > 0) { sb.append(joinString); } sb.append(NodeUtil.getStringValue(elem)); } else { if (sb.length() > 0) { foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); sb = new StringBuilder(); } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } elem = elem.getNext(); } if (sb.length() > 0) { foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); } foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); parent.replaceChild(n, emptyStringNode); break; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { Node replacement = new Node(Token.ADD, Node.newString(""), foldedStringNode); foldedStringNode = replacement; } parent.replaceChild(n, foldedStringNode); break; default: if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += InlineCostEstimator.getCost(right); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } break; } t.getCompiler().reportCodeChange(); }
void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right, Node parent) { if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) { return; } Node arrayNode = left.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return; } String joinString = NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node elem = arrayNode.getFirstChild(); while (elem != null) { if (NodeUtil.isImmutableValue(elem)) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getStringValue(elem)); } else { if (sb != null) { foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } elem = elem.getNext(); } if (sb != null) { foldedSize += sb.length() + 2; arrayFoldedChildren.add(Node.newString(sb.toString())); } foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); parent.replaceChild(n, emptyStringNode); break; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { Node replacement = new Node(Token.ADD, Node.newString(""), foldedStringNode); foldedStringNode = replacement; } parent.replaceChild(n, foldedStringNode); break; default: if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += InlineCostEstimator.getCost(right); if (foldedSize > originalSize) { return; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } break; } t.getCompiler().reportCodeChange(); }
Compress-21
private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); --shift; if (shift == 0) { header.write(cache); shift = 7; cache = 0; } } if (length > 0 && shift > 0) { header.write(cache); } }
private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); if (--shift < 0) { header.write(cache); shift = 7; cache = 0; } } if (shift != 7) { header.write(cache); } }
Codec-2
void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } switch (modulus) { case 1: buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 4) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; buf[pos++] = PAD; } break; case 2: buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 2) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; } break; } if (lineLength > 0) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } modulus = (++modulus) % 3; int b = in[inPos++]; if (b < 0) { b += 256; } x = (x << 8) + b; if (0 == modulus) { buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS]; buf[pos++] = encodeTable[x & MASK_6BITS]; currentLinePos += 4; if (lineLength > 0 && lineLength <= currentLinePos) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; currentLinePos = 0; } } } } }
void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } switch (modulus) { case 1: buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 4) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; buf[pos++] = PAD; } break; case 2: buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 2) & MASK_6BITS]; if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; } break; } if (lineLength > 0 && pos > 0) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } modulus = (++modulus) % 3; int b = in[inPos++]; if (b < 0) { b += 256; } x = (x << 8) + b; if (0 == modulus) { buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS]; buf[pos++] = encodeTable[x & MASK_6BITS]; currentLinePos += 4; if (lineLength > 0 && lineLength <= currentLinePos) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; currentLinePos = 0; } } } } }
JacksonDatabind-76
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { 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, creatorProp.deserialize(p, ctxt))) { t = p.nextToken(); Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; } while (t == JsonToken.FIELD_NAME) { p.nextToken(); tokens.copyCurrentStructure(p); t = p.nextToken(); } tokens.writeEndObject(); if (bean.getClass() != _beanType.getRawClass()) { ctxt.reportMappingException("Can not 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, prop.deserialize(p, ctxt)); continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } tokens.writeFieldName(propName); tokens.copyCurrentStructure(p); if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt)); } } Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { return wrapInstantiationProblem(e, ctxt); } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); }
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { 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) { buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt)); continue; } if (buffer.readIdProperty(propName)) { continue; } SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(p, ctxt)); continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { handleIgnoredProperty(p, ctxt, handledType(), propName); continue; } tokens.writeFieldName(propName); tokens.copyCurrentStructure(p); if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt)); } } Object bean; try { bean = creator.build(ctxt, buffer); } catch (Exception e) { return wrapInstantiationProblem(e, ctxt); } return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens); }
Mockito-20
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) { throw new MockitoException("Serialization across classloaders not yet supported with ByteBuddyMockMaker"); } Class<? extends T> mockedProxyType = cachingMockBytecodeGenerator.get( settings.getTypeToMock(), settings.getExtraInterfaces() ); T mockInstance = null; try { mockInstance = classInstantiator.instantiate(mockedProxyType); MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance; mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings)); return ensureMockIsAssignableToMockedType(settings, mockInstance); } catch (ClassCastException cce) { throw new MockitoException(join( "ClassCastException occurred while creating the mockito mock :", " class to mock : " + describeClass(mockedProxyType), " created class : " + describeClass(settings.getTypeToMock()), " proxy instance class : " + describeClass(mockInstance), " instance creation by : " + classInstantiator.getClass().getSimpleName(), "", "You might experience classloading issues, please ask the mockito mailing-list.", "" ),cce); } catch (org.mockito.internal.creation.instance.InstantiationException e) { throw new MockitoException("Unable to create mock instance of type '" + mockedProxyType.getSuperclass().getSimpleName() + "'", e); } }
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) { throw new MockitoException("Serialization across classloaders not yet supported with ByteBuddyMockMaker"); } Class<? extends T> mockedProxyType = cachingMockBytecodeGenerator.get( settings.getTypeToMock(), settings.getExtraInterfaces() ); Instantiator instantiator = new InstantiatorProvider().getInstantiator(settings); T mockInstance = null; try { mockInstance = instantiator.newInstance(mockedProxyType); MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance; mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings)); return ensureMockIsAssignableToMockedType(settings, mockInstance); } catch (ClassCastException cce) { throw new MockitoException(join( "ClassCastException occurred while creating the mockito mock :", " class to mock : " + describeClass(mockedProxyType), " created class : " + describeClass(settings.getTypeToMock()), " proxy instance class : " + describeClass(mockInstance), " instance creation by : " + instantiator.getClass().getSimpleName(), "", "You might experience classloading issues, please ask the mockito mailing-list.", "" ),cce); } catch (org.mockito.internal.creation.instance.InstantiationException e) { throw new MockitoException("Unable to create mock instance of type '" + mockedProxyType.getSuperclass().getSimpleName() + "'", e); } }
Jsoup-39
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } } else { foundCharset = meta.attr("charset"); } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (docData.length() > 0 && docData.charAt(0) == 65279) { byteData.rewind(); docData = Charset.forName(defaultCharset).decode(byteData).toString(); docData = docData.substring(1); charsetName = defaultCharset; } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } } else { foundCharset = meta.attr("charset"); } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (docData.length() > 0 && docData.charAt(0) == 65279) { byteData.rewind(); docData = Charset.forName(defaultCharset).decode(byteData).toString(); docData = docData.substring(1); charsetName = defaultCharset; doc = null; } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
Jsoup-90
private static boolean looksLikeUtf8(byte[] input) { int i = 0; if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int end; for (int j = input.length; i < j; ++i) { int o = input[i]; if ((o & 0x80) == 0) { continue; } if ((o & 0xE0) == 0xC0) { end = i + 1; } else if ((o & 0xF0) == 0xE0) { end = i + 2; } else if ((o & 0xF8) == 0xF0) { end = i + 3; } else { return false; } while (i < end) { i++; o = input[i]; if ((o & 0xC0) != 0x80) { return false; } } } return true; }
private static boolean looksLikeUtf8(byte[] input) { int i = 0; if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int end; for (int j = input.length; i < j; ++i) { int o = input[i]; if ((o & 0x80) == 0) { continue; } if ((o & 0xE0) == 0xC0) { end = i + 1; } else if ((o & 0xF0) == 0xE0) { end = i + 2; } else if ((o & 0xF8) == 0xF0) { end = i + 3; } else { return false; } if (end >= input.length) return false; while (i < end) { i++; o = input[i]; if ((o & 0xC0) != 0x80) { return false; } } } return true; }
Time-5
public Period normalizedStandard(PeriodType type) { type = DateTimeUtils.getPeriodType(type); long millis = getMillis(); millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND)); millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE)); millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR)); millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY)); millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK)); Period result = new Period(millis, type, ISOChronology.getInstanceUTC()); int years = getYears(); int months = getMonths(); if (years != 0 || months != 0) { years = FieldUtils.safeAdd(years, months / 12); months = months % 12; if (years != 0) { result = result.withYears(years); } if (months != 0) { result = result.withMonths(months); } } return result; }
public Period normalizedStandard(PeriodType type) { type = DateTimeUtils.getPeriodType(type); long millis = getMillis(); millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND)); millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE)); millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR)); millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY)); millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK)); Period result = new Period(millis, type, ISOChronology.getInstanceUTC()); int years = getYears(); int months = getMonths(); if (years != 0 || months != 0) { long totalMonths = years * 12L + months; if (type.isSupported(DurationFieldType.YEARS_TYPE)) { int normalizedYears = FieldUtils.safeToInt(totalMonths / 12); result = result.withYears(normalizedYears); totalMonths = totalMonths - (normalizedYears * 12); } if (type.isSupported(DurationFieldType.MONTHS_TYPE)) { int normalizedMonths = FieldUtils.safeToInt(totalMonths); result = result.withMonths(normalizedMonths); totalMonths = totalMonths - normalizedMonths; } if (totalMonths != 0) { throw new UnsupportedOperationException("Unable to normalize as PeriodType is missing either years or months but period has a month/year amount: " + toString()); } } return result; }
Mockito-5
public void verify(VerificationData data) { AssertionError error = null; timer.start(); while (timer.isCounting()) { try { delegate.verify(data); if (returnOnSuccess) { return; } else { error = null; } } catch (MockitoAssertionError e) { error = handleVerifyException(e); } catch (org.mockito.exceptions.verification.junit.ArgumentsAreDifferent e) { error = handleVerifyException(e); } } if (error != null) { throw error; } }
public void verify(VerificationData data) { AssertionError error = null; timer.start(); while (timer.isCounting()) { try { delegate.verify(data); if (returnOnSuccess) { return; } else { error = null; } } catch (MockitoAssertionError e) { error = handleVerifyException(e); } catch (AssertionError e) { error = handleVerifyException(e); } } if (error != null) { throw error; } }
Lang-17
public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = Character.codePointCount(input, 0, input.length()); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); } else { for (int pt = 0; pt < consumed; pt++) { if (pos < len - 2) { pos += Character.charCount(Character.codePointAt(input, pos)); } else { pos++; } } pos--; } pos++; } }
public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = input.length(); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); pos+= c.length; continue; } for (int pt = 0; pt < consumed; pt++) { pos += Character.charCount(Character.codePointAt(input, pos)); } } }
Compress-1
public void close() throws IOException { if (!this.closed) { super.close(); this.closed = true; } }
public void close() throws IOException { if (!this.closed) { this.finish(); super.close(); this.closed = true; } }
Closure-22
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } if (parent.getType() == Token.COMMA) { Node gramps = parent.getParent(); if (gramps.isCall() && parent == gramps.getFirstChild()) { if (n == parent.getFirstChild() && parent.getChildCount() == 2 && n.getNext().isName() && "eval".equals(n.getNext().getString())) { return; } } if (n == parent.getLastChild()) { for (Node an : parent.getAncestors()) { int ancestorType = an.getType(); if (ancestorType == Token.COMMA) continue; if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return; else break; } } } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) { if (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext())) { } else { return; } } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (!isResultUsed && (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } else if (n.isExprResult()) { return; } String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } }
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isEmpty() || n.isComma()) { return; } if (parent == null) { return; } if (n.isExprResult() || n.isBlock()) { return; } if (n.isQualifiedName() && n.getJSDocInfo() != null) { return; } boolean isResultUsed = NodeUtil.isExpressionResultUsed(n); boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType()); if (!isResultUsed && (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) { String msg = "This code lacks side-effects. Is there a bug?"; if (n.isString()) { msg = "Is there a missing '+' on the previous line?"; } else if (isSimpleOp) { msg = "The result of the '" + Token.name(n.getType()).toLowerCase() + "' operator is not being used."; } t.getCompiler().report( t.makeError(n, level, USELESS_CODE_ERROR, msg)); if (!NodeUtil.isStatement(n)) { problemNodes.add(n); } } }
JacksonCore-25
private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException { _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); char[] outBuf = _textBuffer.getCurrentSegment(); int outPtr = _textBuffer.getCurrentSegmentSize(); final int maxCode = codes.length; while (true) { if (_inputPtr >= _inputEnd) { if (!_loadMore()) { break; } } char c = _inputBuffer[_inputPtr]; int i = (int) c; if (i <= maxCode) { if (codes[i] != 0) { break; } } else if (!Character.isJavaIdentifierPart(c)) { break; } ++_inputPtr; hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i; outBuf[outPtr++] = c; if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } } _textBuffer.setCurrentLength(outPtr); { TextBuffer tb = _textBuffer; char[] buf = tb.getTextBuffer(); int start = tb.getTextOffset(); int len = tb.size(); return _symbols.findSymbol(buf, start, len, hash); } }
private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException { _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); char[] outBuf = _textBuffer.getCurrentSegment(); int outPtr = _textBuffer.getCurrentSegmentSize(); final int maxCode = codes.length; while (true) { if (_inputPtr >= _inputEnd) { if (!_loadMore()) { break; } } char c = _inputBuffer[_inputPtr]; int i = (int) c; if (i < maxCode) { if (codes[i] != 0) { break; } } else if (!Character.isJavaIdentifierPart(c)) { break; } ++_inputPtr; hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i; outBuf[outPtr++] = c; if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } } _textBuffer.setCurrentLength(outPtr); { TextBuffer tb = _textBuffer; char[] buf = tb.getTextBuffer(); int start = tb.getTextOffset(); int len = tb.size(); return _symbols.findSymbol(buf, start, len, hash); } }
Lang-44
public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } if (val.startsWith("--")) { return null; } if (val.startsWith("0x") || val.startsWith("-0x")) { return createInteger(val); } char lastChar = val.charAt(val.length() - 1); String mant; String dec; String exp; int decPos = val.indexOf('.'); int expPos = val.indexOf('e') + val.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } String numeric = val.substring(0, val.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(val + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException e) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(val + " is not a valid number."); } } else { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(val); } catch (NumberFormatException nfe) { } try { return createLong(val); } catch (NumberFormatException nfe) { } return createBigInteger(val); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(val); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(val); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(val); } } }
public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } if (val.length() == 1 && !Character.isDigit(val.charAt(0))) { throw new NumberFormatException(val + " is not a valid number."); } if (val.startsWith("--")) { return null; } if (val.startsWith("0x") || val.startsWith("-0x")) { return createInteger(val); } char lastChar = val.charAt(val.length() - 1); String mant; String dec; String exp; int decPos = val.indexOf('.'); int expPos = val.indexOf('e') + val.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } String numeric = val.substring(0, val.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { } return createBigInteger(numeric); } throw new NumberFormatException(val + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException e) { } case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { } default : throw new NumberFormatException(val + " is not a valid number."); } } else { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { try { return createInteger(val); } catch (NumberFormatException nfe) { } try { return createLong(val); } catch (NumberFormatException nfe) { } return createBigInteger(val); } else { boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(val); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { } try { Double d = createDouble(val); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { } return createBigDecimal(val); } } }
Chart-9
public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException { if (start == null) { throw new IllegalArgumentException("Null 'start' argument."); } if (end == null) { throw new IllegalArgumentException("Null 'end' argument."); } if (start.compareTo(end) > 0) { throw new IllegalArgumentException( "Requires start on or before end."); } boolean emptyRange = false; int startIndex = getIndex(start); if (startIndex < 0) { startIndex = -(startIndex + 1); if (startIndex == this.data.size()) { emptyRange = true; } } int endIndex = getIndex(end); if (endIndex < 0) { endIndex = -(endIndex + 1); endIndex = endIndex - 1; } if (endIndex < 0) { emptyRange = true; } if (emptyRange) { TimeSeries copy = (TimeSeries) super.clone(); copy.data = new java.util.ArrayList(); return copy; } else { return createCopy(startIndex, endIndex); } }
public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end) throws CloneNotSupportedException { if (start == null) { throw new IllegalArgumentException("Null 'start' argument."); } if (end == null) { throw new IllegalArgumentException("Null 'end' argument."); } if (start.compareTo(end) > 0) { throw new IllegalArgumentException( "Requires start on or before end."); } boolean emptyRange = false; int startIndex = getIndex(start); if (startIndex < 0) { startIndex = -(startIndex + 1); if (startIndex == this.data.size()) { emptyRange = true; } } int endIndex = getIndex(end); if (endIndex < 0) { endIndex = -(endIndex + 1); endIndex = endIndex - 1; } if ((endIndex < 0) || (endIndex < startIndex)) { emptyRange = true; } if (emptyRange) { TimeSeries copy = (TimeSeries) super.clone(); copy.data = new java.util.ArrayList(); return copy; } else { return createCopy(startIndex, endIndex); } }
Closure-81
Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { newName.setLineno(functionNode.getLineno()); int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; }
Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { int functionType = functionNode.getFunctionType(); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { errorReporter.error( "unnamed function statement", sourceName, functionNode.getLineno(), "", 0); } name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { newName.setLineno(functionNode.getLineno()); int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; }
Jsoup-50
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset = null; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); } if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (docData.length() > 0 && docData.charAt(0) == UNICODE_BOM) { byteData.rewind(); docData = Charset.forName(defaultCharset).decode(byteData).toString(); docData = docData.substring(1); charsetName = defaultCharset; doc = null; } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; byteData.mark(); byte[] bom = new byte[4]; byteData.get(bom); byteData.rewind(); if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF || bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { charsetName = "UTF-32"; } else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF || bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) { charsetName = "UTF-16"; } else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) { charsetName = "UTF-8"; byteData.position(3); } if (charsetName == null) { docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { String foundCharset = null; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); } if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
Jsoup-55
void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.tagPending.selfClosing = true; t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); t.transition(BeforeAttributeName); } }
void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.tagPending.selfClosing = true; t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); r.unconsume(); t.transition(BeforeAttributeName); } }
Jsoup-49
protected void addChildren(int index, Node... children) { Validate.noNullElements(children); ensureChildNodes(); for (int i = children.length - 1; i >= 0; i--) { Node in = children[i]; reparentChild(in); childNodes.add(index, in); } reindexChildren(index); }
protected void addChildren(int index, Node... children) { Validate.noNullElements(children); ensureChildNodes(); for (int i = children.length - 1; i >= 0; i--) { Node in = children[i]; reparentChild(in); childNodes.add(index, in); reindexChildren(index); } }
Lang-21
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass()); }
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass()); }
Jsoup-43
private static <E extends Element> Integer indexInList(Element search, List<E> elements) { Validate.notNull(search); Validate.notNull(elements); for (int i = 0; i < elements.size(); i++) { E element = elements.get(i); if (element.equals(search)) return i; } return null; }
private static <E extends Element> Integer indexInList(Element search, List<E> elements) { Validate.notNull(search); Validate.notNull(elements); for (int i = 0; i < elements.size(); i++) { E element = elements.get(i); if (element == search) return i; } return null; }
Cli-25
protected StringBuffer renderWrappedText(StringBuffer sb, int width, int nextLineTabStop, String text) { int pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(rtrim(text)); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); if (nextLineTabStop >= width) { nextLineTabStop = width - 1; } final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
protected StringBuffer renderWrappedText(StringBuffer sb, int width, int nextLineTabStop, String text) { int pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(rtrim(text)); return sb; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); if (nextLineTabStop >= width) { nextLineTabStop = 1; } final String padding = createPadding(nextLineTabStop); while (true) { text = padding + text.substring(pos).trim(); pos = findWrapPos(text, width, 0); if (pos == -1) { sb.append(text); return sb; } if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) { pos = width; } sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine); } }
Lang-59
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); int strLen = str.length(); if (strLen >= width) { str.getChars(0, strLen, buffer, size); } else { int padLen = width - strLen; str.getChars(0, strLen, buffer, size); for (int i = 0; i < padLen; i++) { buffer[size + strLen + i] = padChar; } } size += width; } return this; }
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); int strLen = str.length(); if (strLen >= width) { str.getChars(0, width, buffer, size); } else { int padLen = width - strLen; str.getChars(0, strLen, buffer, size); for (int i = 0; i < padLen; i++) { buffer[size + strLen + i] = padChar; } } size += width; } return this; }
Closure-118
private void handleObjectLit(NodeTraversal t, Node n) { for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { String name = child.getString(); T type = typeSystem.getType(getScope(), n, name); Property prop = getProperty(name); if (!prop.scheduleRenaming(child, processProperty(t, prop, type, null))) { if (propertiesToErrorFor.containsKey(name)) { compiler.report(JSError.make( t.getSourceName(), child, propertiesToErrorFor.get(name), Warnings.INVALIDATION, name, (type == null ? "null" : type.toString()), n.toString(), "")); } } } }
private void handleObjectLit(NodeTraversal t, Node n) { for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (child.isQuotedString()) { continue; } String name = child.getString(); T type = typeSystem.getType(getScope(), n, name); Property prop = getProperty(name); if (!prop.scheduleRenaming(child, processProperty(t, prop, type, null))) { if (propertiesToErrorFor.containsKey(name)) { compiler.report(JSError.make( t.getSourceName(), child, propertiesToErrorFor.get(name), Warnings.INVALIDATION, name, (type == null ? "null" : type.toString()), n.toString(), "")); } } } }
JacksonCore-4
public char[] expandCurrentSegment() { final char[] curr = _currentSegment; final int len = curr.length; int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1)); return (_currentSegment = Arrays.copyOf(curr, newLen)); }
public char[] expandCurrentSegment() { final char[] curr = _currentSegment; final int len = curr.length; int newLen = len + (len >> 1); if (newLen > MAX_SEGMENT_LEN) { newLen = len + (len >> 2); } return (_currentSegment = Arrays.copyOf(curr, newLen)); }
Closure-133
private String getRemainingJSDocLine() { String result = stream.getRemainingJSDocLine(); return result; }
private String getRemainingJSDocLine() { String result = stream.getRemainingJSDocLine(); unreadToken = NO_UNREAD_TOKEN; return result; }
Jsoup-80
void insert(Token.Comment commentToken) { Comment comment = new Comment(commentToken.getData()); Node insert = comment; if (commentToken.bogus) { String data = comment.getData(); if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) { Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser()); Element el = doc.child(0); insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!")); insert.attributes().addAll(el.attributes()); } } insertNode(insert); }
void insert(Token.Comment commentToken) { Comment comment = new Comment(commentToken.getData()); Node insert = comment; if (commentToken.bogus) { String data = comment.getData(); if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) { Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser()); if (doc.childNodeSize() > 0) { Element el = doc.child(0); insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!")); insert.attributes().addAll(el.attributes()); } } } insertNode(insert); }
Math-48
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: 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(); } } } }
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) { throw new ConvergenceException(); } 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(); } } } }
Closure-25
private FlowScope traverseNew(Node n, FlowScope scope) { Node constructor = n.getFirstChild(); scope = traverse(constructor, scope); JSType constructorType = constructor.getJSType(); JSType type = null; if (constructorType != null) { constructorType = constructorType.restrictByNotNullOrUndefined(); if (constructorType.isUnknownType()) { type = getNativeType(UNKNOWN_TYPE); } else { FunctionType ct = constructorType.toMaybeFunctionType(); if (ct == null && constructorType instanceof FunctionType) { ct = (FunctionType) constructorType; } if (ct != null && ct.isConstructor()) { type = ct.getInstanceType(); } } } n.setJSType(type); for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) { scope = traverse(arg, scope); } return scope; }
private FlowScope traverseNew(Node n, FlowScope scope) { scope = traverseChildren(n, scope); Node constructor = n.getFirstChild(); JSType constructorType = constructor.getJSType(); JSType type = null; if (constructorType != null) { constructorType = constructorType.restrictByNotNullOrUndefined(); if (constructorType.isUnknownType()) { type = getNativeType(UNKNOWN_TYPE); } else { FunctionType ct = constructorType.toMaybeFunctionType(); if (ct == null && constructorType instanceof FunctionType) { ct = (FunctionType) constructorType; } if (ct != null && ct.isConstructor()) { type = ct.getInstanceType(); backwardsInferenceFromCallSite(n, ct); } } } n.setJSType(type); return scope; }
Time-4
public Partial with(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("The field type must not be null"); } int index = indexOf(fieldType); if (index == -1) { DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1]; int[] newValues = new int[newTypes.length]; int i = 0; DurationField unitField = fieldType.getDurationType().getField(iChronology); if (unitField.isSupported()) { for (; i < iTypes.length; i++) { DateTimeFieldType loopType = iTypes[i]; DurationField loopUnitField = loopType.getDurationType().getField(iChronology); if (loopUnitField.isSupported()) { int compare = unitField.compareTo(loopUnitField); if (compare > 0) { break; } else if (compare == 0) { DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology); DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); if (rangeField.compareTo(loopRangeField) > 0) { break; } } } } } System.arraycopy(iTypes, 0, newTypes, 0, i); System.arraycopy(iValues, 0, newValues, 0, i); newTypes[i] = fieldType; newValues[i] = value; System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1); System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1); Partial newPartial = new Partial(iChronology, newTypes, newValues); iChronology.validate(newPartial, newValues); return newPartial; } if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new Partial(this, newValues); }
public Partial with(DateTimeFieldType fieldType, int value) { if (fieldType == null) { throw new IllegalArgumentException("The field type must not be null"); } int index = indexOf(fieldType); if (index == -1) { DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1]; int[] newValues = new int[newTypes.length]; int i = 0; DurationField unitField = fieldType.getDurationType().getField(iChronology); if (unitField.isSupported()) { for (; i < iTypes.length; i++) { DateTimeFieldType loopType = iTypes[i]; DurationField loopUnitField = loopType.getDurationType().getField(iChronology); if (loopUnitField.isSupported()) { int compare = unitField.compareTo(loopUnitField); if (compare > 0) { break; } else if (compare == 0) { DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology); DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); if (rangeField.compareTo(loopRangeField) > 0) { break; } } } } } System.arraycopy(iTypes, 0, newTypes, 0, i); System.arraycopy(iValues, 0, newValues, 0, i); newTypes[i] = fieldType; newValues[i] = value; System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1); System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1); Partial newPartial = new Partial(newTypes, newValues, iChronology); iChronology.validate(newPartial, newValues); return newPartial; } if (value == getValue(index)) { return this; } int[] newValues = getValues(); newValues = getField(index).set(this, index, newValues, value); return new Partial(this, newValues); }
Math-85
public static double[] bracket(UnivariateRealFunction function, double initial, double lowerBound, double upperBound, int maximumIterations) throws ConvergenceException, FunctionEvaluationException { if (function == null) { throw MathRuntimeException.createIllegalArgumentException("function is null"); } if (maximumIterations <= 0) { throw MathRuntimeException.createIllegalArgumentException( "bad value for maximum iterations number: {0}", maximumIterations); } if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) { throw MathRuntimeException.createIllegalArgumentException( "invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}", lowerBound, initial, upperBound); } double a = initial; double b = initial; double fa; double fb; int numIterations = 0 ; do { a = Math.max(a - 1.0, lowerBound); b = Math.min(b + 1.0, upperBound); fa = function.value(a); fb = function.value(b); numIterations++ ; } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && ((a > lowerBound) || (b < upperBound))); if (fa * fb >= 0.0 ) { throw new ConvergenceException( "number of iterations={0}, maximum iterations={1}, " + "initial={2}, lower bound={3}, upper bound={4}, final a value={5}, " + "final b value={6}, f(a)={7}, f(b)={8}", numIterations, maximumIterations, initial, lowerBound, upperBound, a, b, fa, fb); } return new double[]{a, b}; }
public static double[] bracket(UnivariateRealFunction function, double initial, double lowerBound, double upperBound, int maximumIterations) throws ConvergenceException, FunctionEvaluationException { if (function == null) { throw MathRuntimeException.createIllegalArgumentException("function is null"); } if (maximumIterations <= 0) { throw MathRuntimeException.createIllegalArgumentException( "bad value for maximum iterations number: {0}", maximumIterations); } if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) { throw MathRuntimeException.createIllegalArgumentException( "invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}", lowerBound, initial, upperBound); } double a = initial; double b = initial; double fa; double fb; int numIterations = 0 ; do { a = Math.max(a - 1.0, lowerBound); b = Math.min(b + 1.0, upperBound); fa = function.value(a); fb = function.value(b); numIterations++ ; } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && ((a > lowerBound) || (b < upperBound))); if (fa * fb > 0.0 ) { throw new ConvergenceException( "number of iterations={0}, maximum iterations={1}, " + "initial={2}, lower bound={3}, upper bound={4}, final a value={5}, " + "final b value={6}, f(a)={7}, f(b)={8}", numIterations, maximumIterations, initial, lowerBound, upperBound, a, b, fa, fb); } return new double[]{a, b}; }
Lang-10
private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) { boolean wasWhite= false; for(int i= 0; i<value.length(); ++i) { char c= value.charAt(i); if(Character.isWhitespace(c)) { if(!wasWhite) { wasWhite= true; regex.append("\\s*+"); } continue; } wasWhite= false; switch(c) { case '\'': if(unquote) { if(++i==value.length()) { return regex; } c= value.charAt(i); } break; case '?': case '[': case ']': case '(': case ')': case '{': case '}': case '\\': case '|': case '*': case '+': case '^': case '$': case '.': regex.append('\\'); } regex.append(c); } return regex; }
private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) { for(int i= 0; i<value.length(); ++i) { char c= value.charAt(i); switch(c) { case '\'': if(unquote) { if(++i==value.length()) { return regex; } c= value.charAt(i); } break; case '?': case '[': case ']': case '(': case ')': case '{': case '}': case '\\': case '|': case '*': case '+': case '^': case '$': case '.': regex.append('\\'); } regex.append(c); } return regex; }
Lang-65
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { val.add(fields[i][0], 1); } } return; } } int offset = 0; boolean offsetSet = false; switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { offset = val.get(Calendar.DATE) - 1; if (offset >= 15) { offset -= 15; } roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); offset = val.get(fields[i][0]) - min; roundUp = offset > ((max - min) / 2); } val.set(fields[i][0], val.get(fields[i][0]) - offset); } throw new IllegalArgumentException("The field " + field + " is not supported"); }
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } Date date = val.getTime(); long time = date.getTime(); boolean done = false; int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; if (field == Calendar.SECOND) { done = true; } } int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); if (field == Calendar.MINUTE) { done = true; } } int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } if (date.getTime() != time) { date.setTime(time); val.setTime(date); } boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { val.add(fields[i][0], 1); } } return; } } int offset = 0; boolean offsetSet = false; switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { offset = val.get(Calendar.DATE) - 1; if (offset >= 15) { offset -= 15; } roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); offset = val.get(fields[i][0]) - min; roundUp = offset > ((max - min) / 2); } if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
JacksonCore-20
public void writeEmbeddedObject(Object object) throws IOException { throw new JsonGenerationException("No native support for writing embedded objects", this); }
public void writeEmbeddedObject(Object object) throws IOException { if (object == null) { writeNull(); return; } if (object instanceof byte[]) { writeBinary((byte[]) object); return; } throw new JsonGenerationException("No native support for writing embedded objects of type " +object.getClass().getName(), this); }
Closure-61
static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; }
static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } if (nameNode.getFirstChild().getType() == Token.NAME) { String namespaceName = nameNode.getFirstChild().getString(); if (namespaceName.equals("Math")) { return false; } } if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; }
Closure-161
private Node tryFoldArrayAccess(Node n, Node left, Node right) { Node parent = n.getParent(); if (right.getType() != Token.NUMBER) { return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node elem = left.getFirstChild(); for (int i = 0; elem != null && i < intIndex; i++) { elem = elem.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.getType() == Token.EMPTY) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
private Node tryFoldArrayAccess(Node n, Node left, Node right) { Node parent = n.getParent(); if (isAssignmentTarget(n)) { return n; } if (right.getType() != Token.NUMBER) { return n; } double index = right.getDouble(); int intIndex = (int) index; if (intIndex != index) { error(INVALID_GETELEM_INDEX_ERROR, right); return n; } if (intIndex < 0) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } Node elem = left.getFirstChild(); for (int i = 0; elem != null && i < intIndex; i++) { elem = elem.getNext(); } if (elem == null) { error(INDEX_OUT_OF_BOUNDS_ERROR, right); return n; } if (elem.getType() == Token.EMPTY) { elem = NodeUtil.newUndefinedNode(elem); } else { left.removeChild(elem); } n.getParent().replaceChild(n, elem); reportCodeChange(); return elem; }
Lang-49
public Fraction reduce() { int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); if (gcd == 1) { return this; } return Fraction.getFraction(numerator / gcd, denominator / gcd); }
public Fraction reduce() { if (numerator == 0) { return equals(ZERO) ? this : ZERO; } int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); if (gcd == 1) { return this; } return Fraction.getFraction(numerator / gcd, denominator / gcd); }
Lang-55
public void stop() { if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } stopTime = System.currentTimeMillis(); this.runningState = STATE_STOPPED; }
public void stop() { if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } if(this.runningState == STATE_RUNNING) { stopTime = System.currentTimeMillis(); } this.runningState = STATE_STOPPED; }
Closure-53
private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; nodes.add(new Node(Token.TRUE)); nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } }
private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; if (nodes.isEmpty()) { replacement = new Node(Token.TRUE); } else { nodes.add(new Node(Token.TRUE)); nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); } Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } }
Chart-4
public Range getDataRange(ValueAxis axis) { Range result = null; List mappedDatasets = new ArrayList(); List includedAnnotations = new ArrayList(); boolean isDomainAxis = true; int domainIndex = getDomainAxisIndex(axis); if (domainIndex >= 0) { isDomainAxis = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis( new Integer(domainIndex))); if (domainIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis( new Integer(rangeIndex))); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } Iterator iterator = mappedDatasets.iterator(); while (iterator.hasNext()) { XYDataset d = (XYDataset) iterator.next(); if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } Collection c = r.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; }
public Range getDataRange(ValueAxis axis) { Range result = null; List mappedDatasets = new ArrayList(); List includedAnnotations = new ArrayList(); boolean isDomainAxis = true; int domainIndex = getDomainAxisIndex(axis); if (domainIndex >= 0) { isDomainAxis = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis( new Integer(domainIndex))); if (domainIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis( new Integer(rangeIndex))); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } Iterator iterator = mappedDatasets.iterator(); while (iterator.hasNext()) { XYDataset d = (XYDataset) iterator.next(); if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } if (r != null) { Collection c = r.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; }
Closure-40
public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, false); if (name != null) { refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } } }
public void visit(NodeTraversal t, Node n, Node parent) { if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, true); refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } }
JacksonDatabind-24
public BaseSettings withDateFormat(DateFormat df) { if (_dateFormat == df) { return this; } TimeZone tz = (df == null) ? _timeZone : df.getTimeZone(); return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory, _typeResolverBuilder, df, _handlerInstantiator, _locale, tz, _defaultBase64); }
public BaseSettings withDateFormat(DateFormat df) { if (_dateFormat == df) { return this; } return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory, _typeResolverBuilder, df, _handlerInstantiator, _locale, _timeZone, _defaultBase64); }
Math-13
private RealMatrix squareRoot(RealMatrix m) { final EigenDecomposition dec = new EigenDecomposition(m); return dec.getSquareRoot(); }
private RealMatrix squareRoot(RealMatrix m) { if (m instanceof DiagonalMatrix) { final int dim = m.getRowDimension(); final RealMatrix sqrtM = new DiagonalMatrix(dim); for (int i = 0; i < dim; i++) { sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i))); } return sqrtM; } else { final EigenDecomposition dec = new EigenDecomposition(m); return dec.getSquareRoot(); } }
Codec-18
public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length())); }
public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return cs1.length() == cs2.length() && CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()); }
JacksonDatabind-93
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException { final Class<?> raw = type.getRawClass(); String full = raw.getName(); main_check: do { if (_cfgIllegalClassNames.contains(full)) { break; } if (full.startsWith(PREFIX_STRING)) { for (Class<?> cls = raw; cls != Object.class; cls = cls.getSuperclass()) { String name = cls.getSimpleName(); if ("AbstractPointcutAdvisor".equals(name) || "AbstractApplicationContext".equals(name)) { break main_check; } } } return; } while (false); throw JsonMappingException.from(ctxt, String.format("Illegal type (%s) to deserialize: prevented for security reasons", full)); }
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException { final Class<?> raw = type.getRawClass(); String full = raw.getName(); main_check: do { if (_cfgIllegalClassNames.contains(full)) { break; } if (!raw.isInterface() && full.startsWith(PREFIX_STRING)) { for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()) { String name = cls.getSimpleName(); if ("AbstractPointcutAdvisor".equals(name) || "AbstractApplicationContext".equals(name)) { break main_check; } } } return; } while (false); throw JsonMappingException.from(ctxt, String.format("Illegal type (%s) to deserialize: prevented for security reasons", full)); }
Closure-145
private boolean isOneExactlyFunctionOrDo(Node n) { return (n.getType() == Token.FUNCTION || n.getType() == Token.DO); }
private boolean isOneExactlyFunctionOrDo(Node n) { if (n.getType() == Token.LABEL) { Node labeledStatement = n.getLastChild(); if (labeledStatement.getType() != Token.BLOCK) { return isOneExactlyFunctionOrDo(labeledStatement); } else { if (getNonEmptyChildCount(n, 2) == 1) { return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n)); } else { return false; } } } else { return (n.getType() == Token.FUNCTION || n.getType() == Token.DO); } }
Closure-176
private void updateScopeForTypeChange( FlowScope scope, Node left, JSType leftType, JSType resultType) { Preconditions.checkNotNull(resultType); switch (left.getType()) { case Token.NAME: String varName = left.getString(); Var var = syntacticScope.getVar(varName); boolean isVarDeclaration = left.hasChildren(); boolean isVarTypeBetter = !isVarDeclaration || var == null || var.isTypeInferred(); if (isVarTypeBetter) { redeclareSimpleVar(scope, left, resultType); } left.setJSType(isVarDeclaration || leftType == null ? resultType : null); if (var != null && var.isTypeInferred()) { JSType oldType = var.getType(); var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType)); } break; case Token.GETPROP: String qualifiedName = left.getQualifiedName(); if (qualifiedName != null) { scope.inferQualifiedSlot(left, qualifiedName, leftType == null ? unknownType : leftType, resultType); } left.setJSType(resultType); ensurePropertyDefined(left, resultType); break; } }
private void updateScopeForTypeChange( FlowScope scope, Node left, JSType leftType, JSType resultType) { Preconditions.checkNotNull(resultType); switch (left.getType()) { case Token.NAME: String varName = left.getString(); Var var = syntacticScope.getVar(varName); JSType varType = var == null ? null : var.getType(); boolean isVarDeclaration = left.hasChildren() && varType != null && !var.isTypeInferred(); boolean isVarTypeBetter = isVarDeclaration && !resultType.isNullType() && !resultType.isVoidType(); if (isVarTypeBetter) { redeclareSimpleVar(scope, left, varType); } else { redeclareSimpleVar(scope, left, resultType); } left.setJSType(resultType); if (var != null && var.isTypeInferred()) { JSType oldType = var.getType(); var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType)); } break; case Token.GETPROP: String qualifiedName = left.getQualifiedName(); if (qualifiedName != null) { scope.inferQualifiedSlot(left, qualifiedName, leftType == null ? unknownType : leftType, resultType); } left.setJSType(resultType); ensurePropertyDefined(left, resultType); break; } }
Cli-35
public List<String> getMatchingOptions(String opt) { opt = Util.stripLeadingHyphens(opt); List<String> matchingOpts = new ArrayList<String>(); for (String longOpt : longOpts.keySet()) { if (longOpt.startsWith(opt)) { matchingOpts.add(longOpt); } } return matchingOpts; }
public List<String> getMatchingOptions(String opt) { opt = Util.stripLeadingHyphens(opt); List<String> matchingOpts = new ArrayList<String>(); if(longOpts.keySet().contains(opt)) { return Collections.singletonList(opt); } for (String longOpt : longOpts.keySet()) { if (longOpt.startsWith(opt)) { matchingOpts.add(longOpt); } } return matchingOpts; }
Closure-119
public void collect(JSModule module, Scope scope, Node n) { Node parent = n.getParent(); String name; boolean isSet = false; Name.Type type = Name.Type.OTHER; boolean isPropAssign = false; switch (n.getType()) { case Token.GETTER_DEF: case Token.SETTER_DEF: case Token.STRING_KEY: name = null; if (parent != null && parent.isObjectLit()) { name = getNameForObjLitKey(n); } if (name == null) { return; } isSet = true; switch (n.getType()) { case Token.STRING_KEY: type = getValueType(n.getFirstChild()); break; case Token.GETTER_DEF: type = Name.Type.GET; break; case Token.SETTER_DEF: type = Name.Type.SET; break; default: throw new IllegalStateException("unexpected:" + n); } break; case Token.NAME: if (parent != null) { switch (parent.getType()) { case Token.VAR: isSet = true; Node rvalue = n.getFirstChild(); type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue); break; case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); } break; case Token.GETPROP: return; case Token.FUNCTION: Node gramps = parent.getParent(); if (gramps == null || NodeUtil.isFunctionExpression(parent)) { return; } isSet = true; type = Name.Type.FUNCTION; break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getString(); break; case Token.GETPROP: if (parent != null) { switch (parent.getType()) { case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); isPropAssign = true; } break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; case Token.GETPROP: return; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getQualifiedName(); if (name == null) { return; } break; default: return; } if (!isGlobalNameReference(name, scope)) { return; } if (isSet) { if (isGlobalScope(scope)) { handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type); } else { handleSetFromLocal(module, scope, n, parent, name); } } else { handleGet(module, scope, n, parent, name); } }
public void collect(JSModule module, Scope scope, Node n) { Node parent = n.getParent(); String name; boolean isSet = false; Name.Type type = Name.Type.OTHER; boolean isPropAssign = false; switch (n.getType()) { case Token.GETTER_DEF: case Token.SETTER_DEF: case Token.STRING_KEY: name = null; if (parent != null && parent.isObjectLit()) { name = getNameForObjLitKey(n); } if (name == null) { return; } isSet = true; switch (n.getType()) { case Token.STRING_KEY: type = getValueType(n.getFirstChild()); break; case Token.GETTER_DEF: type = Name.Type.GET; break; case Token.SETTER_DEF: type = Name.Type.SET; break; default: throw new IllegalStateException("unexpected:" + n); } break; case Token.NAME: if (parent != null) { switch (parent.getType()) { case Token.VAR: isSet = true; Node rvalue = n.getFirstChild(); type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue); break; case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); } break; case Token.GETPROP: return; case Token.FUNCTION: Node gramps = parent.getParent(); if (gramps == null || NodeUtil.isFunctionExpression(parent)) { return; } isSet = true; type = Name.Type.FUNCTION; break; case Token.CATCH: case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getString(); break; case Token.GETPROP: if (parent != null) { switch (parent.getType()) { case Token.ASSIGN: if (parent.getFirstChild() == n) { isSet = true; type = getValueType(n.getNext()); isPropAssign = true; } break; case Token.INC: case Token.DEC: isSet = true; type = Name.Type.OTHER; break; case Token.GETPROP: return; default: if (NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n) { isSet = true; type = Name.Type.OTHER; } } } name = n.getQualifiedName(); if (name == null) { return; } break; default: return; } if (!isGlobalNameReference(name, scope)) { return; } if (isSet) { if (isGlobalScope(scope)) { handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type); } else { handleSetFromLocal(module, scope, n, parent, name); } } else { handleGet(module, scope, n, parent, name); } }
JacksonDatabind-19
private JavaType _mapType(Class<?> rawClass) { JavaType[] typeParams = findTypeParameters(rawClass, Map.class); if (typeParams == null) { return MapType.construct(rawClass, _unknownType(), _unknownType()); } if (typeParams.length != 2) { throw new IllegalArgumentException("Strange Map type "+rawClass.getName()+": can not determine type parameters"); } return MapType.construct(rawClass, typeParams[0], typeParams[1]); }
private JavaType _mapType(Class<?> rawClass) { if (rawClass == Properties.class) { return MapType.construct(rawClass, CORE_TYPE_STRING, CORE_TYPE_STRING); } JavaType[] typeParams = findTypeParameters(rawClass, Map.class); if (typeParams == null) { return MapType.construct(rawClass, _unknownType(), _unknownType()); } if (typeParams.length != 2) { throw new IllegalArgumentException("Strange Map type "+rawClass.getName()+": can not determine type parameters"); } return MapType.construct(rawClass, typeParams[0], typeParams[1]); }
Closure-56
public String getLine(int lineNumber) { String js = ""; try { js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = 1; if (lineNumber >= lastLine) { pos = lastOffset; startLine = lastLine; } for (int n = startLine; n < lineNumber; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { return null; } pos = nextpos + 1; } lastOffset = pos; lastLine = lineNumber; if (js.indexOf('\n', pos) == -1) { return null; } else { return js.substring(pos, js.indexOf('\n', pos)); } }
public String getLine(int lineNumber) { String js = ""; try { js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = 1; if (lineNumber >= lastLine) { pos = lastOffset; startLine = lastLine; } for (int n = startLine; n < lineNumber; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { return null; } pos = nextpos + 1; } lastOffset = pos; lastLine = lineNumber; if (js.indexOf('\n', pos) == -1) { if (pos >= js.length()) { return null; } else { return js.substring(pos, js.length()); } } else { return js.substring(pos, js.indexOf('\n', pos)); } }
Math-103
public double cumulativeProbability(double x) throws MathException { return 0.5 * (1.0 + Erf.erf((x - mean) / (standardDeviation * Math.sqrt(2.0)))); }
public double cumulativeProbability(double x) throws MathException { try { return 0.5 * (1.0 + Erf.erf((x - mean) / (standardDeviation * Math.sqrt(2.0)))); } catch (MaxIterationsExceededException ex) { if (x < (mean - 20 * standardDeviation)) { return 0.0d; } else if (x > (mean + 20 * standardDeviation)) { return 1.0d; } else { throw ex; } } }
Math-80
private boolean flipIfWarranted(final int n, final int step) { if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) { int j = 4 * n - 1; for (int i = 0; i < j; i += 4) { for (int k = 0; k < 4; k += step) { final double tmp = work[i + k]; work[i + k] = work[j - k]; work[j - k] = tmp; } j -= 4; } return true; } return false; }
private boolean flipIfWarranted(final int n, final int step) { if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) { int j = 4 * (n - 1); for (int i = 0; i < j; i += 4) { for (int k = 0; k < 4; k += step) { final double tmp = work[i + k]; work[i + k] = work[j - k]; work[j - k] = tmp; } j -= 4; } return true; } return false; }
Math-41
public double evaluate(final double[] values, final double[] weights, final double mean, final int begin, final int length) { double var = Double.NaN; if (test(values, weights, begin, length)) { if (length == 1) { var = 0.0; } else if (length > 1) { double accum = 0.0; double dev = 0.0; double accum2 = 0.0; for (int i = begin; i < begin + length; i++) { dev = values[i] - mean; accum += weights[i] * (dev * dev); accum2 += weights[i] * dev; } double sumWts = 0; for (int i = 0; i < weights.length; i++) { sumWts += weights[i]; } if (isBiasCorrected) { var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0); } else { var = (accum - (accum2 * accum2 / sumWts)) / sumWts; } } } return var; }
public double evaluate(final double[] values, final double[] weights, final double mean, final int begin, final int length) { double var = Double.NaN; if (test(values, weights, begin, length)) { if (length == 1) { var = 0.0; } else if (length > 1) { double accum = 0.0; double dev = 0.0; double accum2 = 0.0; for (int i = begin; i < begin + length; i++) { dev = values[i] - mean; accum += weights[i] * (dev * dev); accum2 += weights[i] * dev; } double sumWts = 0; for (int i = begin; i < begin + length; i++) { sumWts += weights[i]; } if (isBiasCorrected) { var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0); } else { var = (accum - (accum2 * accum2 / sumWts)) / sumWts; } } } return var; }
Math-17
public Dfp multiply(final int x) { return multiplyFast(x); }
public Dfp multiply(final int x) { if (x >= 0 && x < RADIX) { return multiplyFast(x); } else { return multiply(newInstance(x)); } }
Math-38
private void prelim(double[] lowerBound, double[] upperBound) { printMethod(); final int n = currentBest.getDimension(); final int npt = numberOfInterpolationPoints; final int ndim = bMatrix.getRowDimension(); final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius; final double recip = 1d / rhosq; final int np = n + 1; for (int j = 0; j < n; j++) { originShift.setEntry(j, currentBest.getEntry(j)); for (int k = 0; k < npt; k++) { interpolationPoints.setEntry(k, j, ZERO); } for (int i = 0; i < ndim; i++) { bMatrix.setEntry(i, j, ZERO); } } for (int i = 0, max = n * np / 2; i < max; i++) { modelSecondDerivativesValues.setEntry(i, ZERO); } for (int k = 0; k < npt; k++) { modelSecondDerivativesParameters.setEntry(k, ZERO); for (int j = 0, max = npt - np; j < max; j++) { zMatrix.setEntry(k, j, ZERO); } } int ipt = 0; int jpt = 0; double fbeg = Double.NaN; do { final int nfm = getEvaluations(); final int nfx = nfm - n; final int nfmm = nfm - 1; final int nfxm = nfx - 1; double stepa = 0; double stepb = 0; if (nfm <= 2 * n) { if (nfm >= 1 && nfm <= n) { stepa = initialTrustRegionRadius; if (upperDifference.getEntry(nfmm) == ZERO) { stepa = -stepa; throw new PathIsExploredException(); } interpolationPoints.setEntry(nfm, nfmm, stepa); } else if (nfm > n) { stepa = interpolationPoints.getEntry(nfx, nfxm); stepb = -initialTrustRegionRadius; if (lowerDifference.getEntry(nfxm) == ZERO) { stepb = Math.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm)); throw new PathIsExploredException(); } if (upperDifference.getEntry(nfxm) == ZERO) { stepb = Math.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm)); throw new PathIsExploredException(); } interpolationPoints.setEntry(nfm, nfxm, stepb); } } else { final int tmp1 = (nfm - np) / n; jpt = nfm - tmp1 * n - n; ipt = jpt + tmp1; if (ipt > n) { final int tmp2 = jpt; jpt = ipt - n; ipt = tmp2; throw new PathIsExploredException(); } final int iptMinus1 = ipt; final int jptMinus1 = jpt; interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1)); interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1)); } for (int j = 0; j < n; j++) { currentBest.setEntry(j, Math.min(Math.max(lowerBound[j], originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)), upperBound[j])); if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) { currentBest.setEntry(j, lowerBound[j]); } if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) { currentBest.setEntry(j, upperBound[j]); } } final double objectiveValue = computeObjectiveValue(currentBest.toArray()); final double f = isMinimize ? objectiveValue : -objectiveValue; final int numEval = getEvaluations(); fAtInterpolationPoints.setEntry(nfm, f); if (numEval == 1) { fbeg = f; trustRegionCenterInterpolationPointIndex = 0; } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) { trustRegionCenterInterpolationPointIndex = nfm; } if (numEval <= 2 * n + 1) { if (numEval >= 2 && numEval <= n + 1) { gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa); if (npt < numEval + n) { final double oneOverStepA = ONE / stepa; bMatrix.setEntry(0, nfmm, -oneOverStepA); bMatrix.setEntry(nfm, nfmm, oneOverStepA); bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq); throw new PathIsExploredException(); } } else if (numEval >= n + 2) { final int ih = nfx * (nfx + 1) / 2 - 1; final double tmp = (f - fbeg) / stepb; final double diff = stepb - stepa; modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff); gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff); if (stepa * stepb < ZERO) { if (f < fAtInterpolationPoints.getEntry(nfm - n)) { fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n)); fAtInterpolationPoints.setEntry(nfm - n, f); if (trustRegionCenterInterpolationPointIndex == nfm) { trustRegionCenterInterpolationPointIndex = nfm - n; } interpolationPoints.setEntry(nfm - n, nfxm, stepb); interpolationPoints.setEntry(nfm, nfxm, stepa); } } bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb)); bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm)); bMatrix.setEntry(nfm - n, nfxm, -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm)); zMatrix.setEntry(0, nfxm, Math.sqrt(TWO) / (stepa * stepb)); zMatrix.setEntry(nfm, nfxm, Math.sqrt(HALF) / rhosq); zMatrix.setEntry(nfm - n, nfxm, -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm)); } } else { zMatrix.setEntry(0, nfxm, recip); zMatrix.setEntry(nfm, nfxm, recip); zMatrix.setEntry(ipt, nfxm, -recip); zMatrix.setEntry(jpt, nfxm, -recip); final int ih = ipt * (ipt - 1) / 2 + jpt - 1; final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1); modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp); throw new PathIsExploredException(); } } while (getEvaluations() < npt); }
private void prelim(double[] lowerBound, double[] upperBound) { printMethod(); final int n = currentBest.getDimension(); final int npt = numberOfInterpolationPoints; final int ndim = bMatrix.getRowDimension(); final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius; final double recip = 1d / rhosq; final int np = n + 1; for (int j = 0; j < n; j++) { originShift.setEntry(j, currentBest.getEntry(j)); for (int k = 0; k < npt; k++) { interpolationPoints.setEntry(k, j, ZERO); } for (int i = 0; i < ndim; i++) { bMatrix.setEntry(i, j, ZERO); } } for (int i = 0, max = n * np / 2; i < max; i++) { modelSecondDerivativesValues.setEntry(i, ZERO); } for (int k = 0; k < npt; k++) { modelSecondDerivativesParameters.setEntry(k, ZERO); for (int j = 0, max = npt - np; j < max; j++) { zMatrix.setEntry(k, j, ZERO); } } int ipt = 0; int jpt = 0; double fbeg = Double.NaN; do { final int nfm = getEvaluations(); final int nfx = nfm - n; final int nfmm = nfm - 1; final int nfxm = nfx - 1; double stepa = 0; double stepb = 0; if (nfm <= 2 * n) { if (nfm >= 1 && nfm <= n) { stepa = initialTrustRegionRadius; if (upperDifference.getEntry(nfmm) == ZERO) { stepa = -stepa; throw new PathIsExploredException(); } interpolationPoints.setEntry(nfm, nfmm, stepa); } else if (nfm > n) { stepa = interpolationPoints.getEntry(nfx, nfxm); stepb = -initialTrustRegionRadius; if (lowerDifference.getEntry(nfxm) == ZERO) { stepb = Math.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm)); throw new PathIsExploredException(); } if (upperDifference.getEntry(nfxm) == ZERO) { stepb = Math.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm)); throw new PathIsExploredException(); } interpolationPoints.setEntry(nfm, nfxm, stepb); } } else { final int tmp1 = (nfm - np) / n; jpt = nfm - tmp1 * n - n; ipt = jpt + tmp1; if (ipt > n) { final int tmp2 = jpt; jpt = ipt - n; ipt = tmp2; } final int iptMinus1 = ipt - 1; final int jptMinus1 = jpt - 1; interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1)); interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1)); } for (int j = 0; j < n; j++) { currentBest.setEntry(j, Math.min(Math.max(lowerBound[j], originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)), upperBound[j])); if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) { currentBest.setEntry(j, lowerBound[j]); } if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) { currentBest.setEntry(j, upperBound[j]); } } final double objectiveValue = computeObjectiveValue(currentBest.toArray()); final double f = isMinimize ? objectiveValue : -objectiveValue; final int numEval = getEvaluations(); fAtInterpolationPoints.setEntry(nfm, f); if (numEval == 1) { fbeg = f; trustRegionCenterInterpolationPointIndex = 0; } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) { trustRegionCenterInterpolationPointIndex = nfm; } if (numEval <= 2 * n + 1) { if (numEval >= 2 && numEval <= n + 1) { gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa); if (npt < numEval + n) { final double oneOverStepA = ONE / stepa; bMatrix.setEntry(0, nfmm, -oneOverStepA); bMatrix.setEntry(nfm, nfmm, oneOverStepA); bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq); throw new PathIsExploredException(); } } else if (numEval >= n + 2) { final int ih = nfx * (nfx + 1) / 2 - 1; final double tmp = (f - fbeg) / stepb; final double diff = stepb - stepa; modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff); gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff); if (stepa * stepb < ZERO) { if (f < fAtInterpolationPoints.getEntry(nfm - n)) { fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n)); fAtInterpolationPoints.setEntry(nfm - n, f); if (trustRegionCenterInterpolationPointIndex == nfm) { trustRegionCenterInterpolationPointIndex = nfm - n; } interpolationPoints.setEntry(nfm - n, nfxm, stepb); interpolationPoints.setEntry(nfm, nfxm, stepa); } } bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb)); bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm)); bMatrix.setEntry(nfm - n, nfxm, -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm)); zMatrix.setEntry(0, nfxm, Math.sqrt(TWO) / (stepa * stepb)); zMatrix.setEntry(nfm, nfxm, Math.sqrt(HALF) / rhosq); zMatrix.setEntry(nfm - n, nfxm, -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm)); } } else { zMatrix.setEntry(0, nfxm, recip); zMatrix.setEntry(nfm, nfxm, recip); zMatrix.setEntry(ipt, nfxm, -recip); zMatrix.setEntry(jpt, nfxm, -recip); final int ih = ipt * (ipt - 1) / 2 + jpt - 1; final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1); modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp); } } while (getEvaluations() < npt); }
Lang-37
public static <T> T[] addAll(T[] array1, T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; }
public static <T> T[] addAll(T[] array1, T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (ArrayStoreException ase) { final Class<?> type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)){ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName()); } throw ase; } return joinedArray; }
Closure-132
private Node tryMinimizeIf(Node n) { Node parent = n.getParent(); Node cond = n.getFirstChild(); if (NodeUtil.isLiteralValue(cond, true)) { return n; } Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); if (elseBranch == null) { if (isFoldableExpressBlock(thenBranch)) { Node expr = getBlockExpression(thenBranch); if (!late && isPropertyAssignmentInExpression(expr)) { return n; } if (cond.isNot()) { if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), OR_PRECEDENCE)) { return n; } Node or = IR.or( cond.removeFirstChild(), expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(or); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), AND_PRECEDENCE)) { return n; } n.removeChild(cond); Node and = IR.and(cond, expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(and); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } else { if (NodeUtil.isStatementBlock(thenBranch) && thenBranch.hasOneChild()) { Node innerIf = thenBranch.getFirstChild(); if (innerIf.isIf()) { Node innerCond = innerIf.getFirstChild(); Node innerThenBranch = innerCond.getNext(); Node innerElseBranch = innerThenBranch.getNext(); if (innerElseBranch == null && !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) { n.detachChildren(); n.addChildToBack( IR.and( cond, innerCond.detachFromParent()) .srcref(cond)); n.addChildrenToBack(innerThenBranch.detachFromParent()); reportCodeChange(); return n; } } } } return n; } tryRemoveRepeatedStatements(n); if (cond.isNot() && !consumesDanglingElse(elseBranch)) { n.replaceChild(cond, cond.removeFirstChild()); n.removeChild(thenBranch); n.addChildToBack(thenBranch); reportCodeChange(); return n; } if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) { Node thenExpr = getBlockReturnExpression(thenBranch); Node elseExpr = getBlockReturnExpression(elseBranch); n.removeChild(cond); thenExpr.detachFromParent(); elseExpr.detachFromParent(); Node returnNode = IR.returnNode( IR.hook(cond, thenExpr, elseExpr) .srcref(n)); parent.replaceChild(n, returnNode); reportCodeChange(); return returnNode; } boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch); boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch); if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) { Node thenOp = getBlockExpression(thenBranch).getFirstChild(); Node elseOp = getBlockExpression(elseBranch).getFirstChild(); if (thenOp.getType() == elseOp.getType()) { if (NodeUtil.isAssignmentOp(thenOp)) { Node lhs = thenOp.getFirstChild(); if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) && !mayEffectMutableState(lhs)) { n.removeChild(cond); Node assignName = thenOp.removeFirstChild(); Node thenExpr = thenOp.removeFirstChild(); Node elseExpr = elseOp.getLastChild(); elseOp.removeChild(elseExpr); Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n); Node assign = new Node(thenOp.getType(), assignName, hookNode) .srcref(thenOp); Node expr = NodeUtil.newExpr(assign); parent.replaceChild(n, expr); reportCodeChange(); return expr; } } } n.removeChild(cond); thenOp.detachFromParent(); elseOp.detachFromParent(); Node expr = IR.exprResult( IR.hook(cond, thenOp, elseOp).srcref(n)); parent.replaceChild(n, expr); reportCodeChange(); return expr; } boolean thenBranchIsVar = isVarBlock(thenBranch); boolean elseBranchIsVar = isVarBlock(elseBranch); if (thenBranchIsVar && elseBranchIsExpressionBlock && getBlockExpression(elseBranch).getFirstChild().isAssign()) { Node var = getBlockVar(thenBranch); Node elseAssign = getBlockExpression(elseBranch).getFirstChild(); Node name1 = var.getFirstChild(); Node maybeName2 = elseAssign.getFirstChild(); if (name1.hasChildren() && maybeName2.isName() && name1.getString().equals(maybeName2.getString())) { Node thenExpr = name1.removeChildren(); Node elseExpr = elseAssign.getLastChild().detachFromParent(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name1.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } else if (elseBranchIsVar && thenBranchIsExpressionBlock && getBlockExpression(thenBranch).getFirstChild().isAssign()) { Node var = getBlockVar(elseBranch); Node thenAssign = getBlockExpression(thenBranch).getFirstChild(); Node maybeName1 = thenAssign.getFirstChild(); Node name2 = var.getFirstChild(); if (name2.hasChildren() && maybeName1.isName() && maybeName1.getString().equals(name2.getString())) { Node thenExpr = thenAssign.getLastChild().detachFromParent(); Node elseExpr = name2.removeChildren(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name2.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } return n; }
private Node tryMinimizeIf(Node n) { Node parent = n.getParent(); Node cond = n.getFirstChild(); if (NodeUtil.isLiteralValue(cond, true)) { return n; } Node thenBranch = cond.getNext(); Node elseBranch = thenBranch.getNext(); if (elseBranch == null) { if (isFoldableExpressBlock(thenBranch)) { Node expr = getBlockExpression(thenBranch); if (!late && isPropertyAssignmentInExpression(expr)) { return n; } if (cond.isNot()) { if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), OR_PRECEDENCE)) { return n; } Node or = IR.or( cond.removeFirstChild(), expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(or); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(expr.getFirstChild(), AND_PRECEDENCE)) { return n; } n.removeChild(cond); Node and = IR.and(cond, expr.removeFirstChild()).srcref(n); Node newExpr = NodeUtil.newExpr(and); parent.replaceChild(n, newExpr); reportCodeChange(); return newExpr; } else { if (NodeUtil.isStatementBlock(thenBranch) && thenBranch.hasOneChild()) { Node innerIf = thenBranch.getFirstChild(); if (innerIf.isIf()) { Node innerCond = innerIf.getFirstChild(); Node innerThenBranch = innerCond.getNext(); Node innerElseBranch = innerThenBranch.getNext(); if (innerElseBranch == null && !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) && isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) { n.detachChildren(); n.addChildToBack( IR.and( cond, innerCond.detachFromParent()) .srcref(cond)); n.addChildrenToBack(innerThenBranch.detachFromParent()); reportCodeChange(); return n; } } } } return n; } tryRemoveRepeatedStatements(n); if (cond.isNot() && !consumesDanglingElse(elseBranch)) { n.replaceChild(cond, cond.removeFirstChild()); n.removeChild(thenBranch); n.addChildToBack(thenBranch); reportCodeChange(); return n; } if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) { Node thenExpr = getBlockReturnExpression(thenBranch); Node elseExpr = getBlockReturnExpression(elseBranch); n.removeChild(cond); thenExpr.detachFromParent(); elseExpr.detachFromParent(); Node returnNode = IR.returnNode( IR.hook(cond, thenExpr, elseExpr) .srcref(n)); parent.replaceChild(n, returnNode); reportCodeChange(); return returnNode; } boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch); boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch); if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) { Node thenOp = getBlockExpression(thenBranch).getFirstChild(); Node elseOp = getBlockExpression(elseBranch).getFirstChild(); if (thenOp.getType() == elseOp.getType()) { if (NodeUtil.isAssignmentOp(thenOp)) { Node lhs = thenOp.getFirstChild(); if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) && !mayEffectMutableState(lhs) && (!mayHaveSideEffects(cond) || (thenOp.isAssign() && thenOp.getFirstChild().isName()))) { n.removeChild(cond); Node assignName = thenOp.removeFirstChild(); Node thenExpr = thenOp.removeFirstChild(); Node elseExpr = elseOp.getLastChild(); elseOp.removeChild(elseExpr); Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n); Node assign = new Node(thenOp.getType(), assignName, hookNode) .srcref(thenOp); Node expr = NodeUtil.newExpr(assign); parent.replaceChild(n, expr); reportCodeChange(); return expr; } } } n.removeChild(cond); thenOp.detachFromParent(); elseOp.detachFromParent(); Node expr = IR.exprResult( IR.hook(cond, thenOp, elseOp).srcref(n)); parent.replaceChild(n, expr); reportCodeChange(); return expr; } boolean thenBranchIsVar = isVarBlock(thenBranch); boolean elseBranchIsVar = isVarBlock(elseBranch); if (thenBranchIsVar && elseBranchIsExpressionBlock && getBlockExpression(elseBranch).getFirstChild().isAssign()) { Node var = getBlockVar(thenBranch); Node elseAssign = getBlockExpression(elseBranch).getFirstChild(); Node name1 = var.getFirstChild(); Node maybeName2 = elseAssign.getFirstChild(); if (name1.hasChildren() && maybeName2.isName() && name1.getString().equals(maybeName2.getString())) { Node thenExpr = name1.removeChildren(); Node elseExpr = elseAssign.getLastChild().detachFromParent(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name1.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } else if (elseBranchIsVar && thenBranchIsExpressionBlock && getBlockExpression(thenBranch).getFirstChild().isAssign()) { Node var = getBlockVar(elseBranch); Node thenAssign = getBlockExpression(thenBranch).getFirstChild(); Node maybeName1 = thenAssign.getFirstChild(); Node name2 = var.getFirstChild(); if (name2.hasChildren() && maybeName1.isName() && maybeName1.getString().equals(name2.getString())) { Node thenExpr = thenAssign.getLastChild().detachFromParent(); Node elseExpr = name2.removeChildren(); cond.detachFromParent(); Node hookNode = IR.hook(cond, thenExpr, elseExpr) .srcref(n); var.detachFromParent(); name2.addChildrenToBack(hookNode); parent.replaceChild(n, var); reportCodeChange(); return var; } } return n; }