auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Class<?> toInternalConversionClass(LogicalType type) { switch (type.getTypeRoot()) { case CHAR: case VARCHAR: return StringData.class; case BOOLEAN: return Boolean.class; case BINARY: case VARBINARY: return byte[].class; case DECIMAL: return DecimalData.class; case TINYINT: return Byte.class; case SMALLINT: return Short.class; case INTEGER: case DATE: case TIME_WITHOUT_TIME_ZONE: case INTERVAL_YEAR_MONTH: return Integer.class; case BIGINT: case INTERVAL_DAY_TIME: return Long.class; case FLOAT: return Float.class; case DOUBLE: return Double.class; case TIMESTAMP_WITHOUT_TIME_ZONE: case TIMESTAMP_WITH_LOCAL_TIME_ZONE: return TimestampData.class; case TIMESTAMP_WITH_TIME_ZONE: throw new UnsupportedOperationException(); case ARRAY: return ArrayData.class; case MULTISET: case MAP: return MapData.class; case ROW: case STRUCTURED_TYPE: return RowData.class; case DISTINCT_TYPE: return toInternalConversionClass(((DistinctType) type).getSourceType()); case RAW: return RawValueData.class; case NULL: case SYMBOL: case UNRESOLVED: default: throw new IllegalArgumentException(); } }

Target:
public static Class<?> toInternalConversionClass(LogicalType type) { switch (type.getTypeRoot()) { case CHAR: case VARCHAR: return StringData.class; case BOOLEAN: return Boolean.class; case BINARY: case VARBINARY: return byte[].class; case DECIMAL: return DecimalData.class; case TINYINT: return Byte.class; case SMALLINT: return Short.class; case INTEGER: case DATE: case TIME_WITHOUT_TIME_ZONE: case INTERVAL_YEAR_MONTH: return Integer.class; case BIGINT: case INTERVAL_DAY_TIME: return Long.class; case FLOAT: return Float.class; case DOUBLE: return Double.class; case TIMESTAMP_WITHOUT_TIME_ZONE: case TIMESTAMP_WITH_LOCAL_TIME_ZONE: return TimestampData.class; case TIMESTAMP_WITH_TIME_ZONE: throw new UnsupportedOperationException("Unsupported type: " + type); case ARRAY: return ArrayData.class; case MULTISET: case MAP: return MapData.class; case ROW: case STRUCTURED_TYPE: return RowData.class; case DISTINCT_TYPE: return toInternalConversionClass(((DistinctType) type).getSourceType()); case RAW: return RawValueData.class; case NULL: case SYMBOL: case UNRESOLVED: default: throw new IllegalArgumentException("Illegal type: " + type); } }
Source:
private ProduceWindowResults() { pageBuilder = new PageBuilder(outputTypes); }

Target:
ProduceWindowResults() { pageBuilder = new PageBuilder(outputTypes); }
Source:
public int hashCode() { return Objects.hash(chainId, matchForwardFlow, matchReturnFlow, portGroup, invPortGroup, ipAddrGroupSrc, invIpAddrGroupSrc, ipAddrGroupDst, invIpAddrGroupDst, traversedDevice, invTraversedDevice, dlType, invDlType, dlSrc, dlSrcMask, invDlSrc, dlDst, dlDstMask, invDlDst, nwTos, invNwTos, nwProto, invNwProto, nwSrcAddress, nwSrcLength, invNwSrc, nwDstAddress, nwDstLength, invNwDst, fragmentPolicy, tpSrc, invTpSrc, tpDst, invTpDst, type, jumpChainName, jumpChainId, flowAction, natTargets, meterName, vlan, noVlan, popVlan, pushVlan, targetPortId, ingress, failOpen); }

Target:
public int hashCode() { return Objects.hash(chainId, condInvert, matchForwardFlow, matchReturnFlow, portGroup, invPortGroup, ipAddrGroupSrc, invIpAddrGroupSrc, ipAddrGroupDst, invIpAddrGroupDst, traversedDevice, invTraversedDevice, dlType, invDlType, dlSrc, dlSrcMask, invDlSrc, dlDst, dlDstMask, invDlDst, nwTos, invNwTos, nwProto, invNwProto, nwSrcAddress, nwSrcLength, invNwSrc, nwDstAddress, nwDstLength, invNwDst, fragmentPolicy, tpSrc, invTpSrc, tpDst, invTpDst, type, jumpChainName, jumpChainId, flowAction, natTargets, meterName, vlan, noVlan, popVlan, pushVlan, targetPortId, ingress, failOpen); }
Source:
public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId) { ArrayList<ReplicaId> replicaIdsToReturn = new ArrayList<>(); for (PartitionId partitionId : partitions.values()) { List<? extends ReplicaId> replicaIds = partitionId.getReplicaIds(); for (ReplicaId replicaId : replicaIds) { if (replicaId.getDataNodeId().getHostname().equals(dataNodeId.getHostname()) && replicaId.getDataNodeId().getPort() == dataNodeId.getPort()) { replicaIdsToReturn.add(replicaId); } } } return replicaIdsToReturn; }

Target:
public List<ReplicaId> getReplicaIds(DataNodeId dataNodeId) { ArrayList<ReplicaId> replicaIdsToReturn = new ArrayList<>(); for (PartitionId partitionId : partitions.values()) { List<? extends ReplicaId> replicaIds = partitionId.getReplicaIds(); for (ReplicaId replicaId : replicaIds) { if (replicaId.getDataNodeId().compareTo(dataNodeId) == 0) { replicaIdsToReturn.add(replicaId); } } } return replicaIdsToReturn; }
Source:
protected void processBlockContent(String line) { if (!line.trim().isEmpty()) { if (colsAttribute.isEmpty() || cellsCount % colsAttribute.size() == 0) { TableRowAttributes tableRowAttributes = new TableRowAttributes(); builder.beginBlock(BlockType.TABLE_ROW, tableRowAttributes); } for (String cell : ROW_CELL_SPLITTER.split(line)) { String cellContent = cell.trim(); if (!cellContent.isEmpty()) { String blockContent = cellContent.replaceAll("\\\\\\|", "|"); TableCellAttributes attributes; if (colsAttribute.isEmpty()) { attributes = new TableCellAttributes(); } else { attributes = colsAttribute.get(cellsCount % colsAttribute.size()); } builder.beginBlock(BlockType.TABLE_CELL_NORMAL, attributes); builder.characters(blockContent); builder.endBlock(); cellsCount = cellsCount + 1; } } if (colsAttribute.isEmpty() || cellsCount % colsAttribute.size() == 0) { builder.endBlock(); } } }

Target:
protected void processBlockContent(String line) { if (!line.trim().isEmpty()) { if (colsAttribute.isEmpty() || cellsCount % colsAttribute.size() == 0) { TableRowAttributes tableRowAttributes = new TableRowAttributes(); builder.beginBlock(BlockType.TABLE_ROW, tableRowAttributes); } for (String cell : ROW_CELL_SPLITTER.split(line)) { String cellContent = cell.trim(); if (!cellContent.isEmpty()) { String blockContent = cellContent.replaceAll("\\\\\\|", "|"); TableCellAttributes attributes; if (colsAttribute.isEmpty()) { attributes = new TableCellAttributes(); } else { attributes = colsAttribute.get(cellsCount % colsAttribute.size()); } builder.beginBlock(BlockType.TABLE_CELL_NORMAL, attributes); builder.characters(blockContent); builder.endBlock(); cellsCount = cellsCount + 1; } } if (colsAttribute.isEmpty()) { builder.endBlock(); colsAttribute = LanguageSupport.createDefaultColumnsAttributeList(cellsCount); } else if (cellsCount % colsAttribute.size() == 0) { builder.endBlock(); } } }
Source:
Table getTable(Class<? extends RealmModel> clazz) { Table table = classToTable.get(clazz); if (table == null) { Class<? extends RealmModel> originalClass = Util.getOriginalModelClass(clazz); if (originalClass != clazz) { table = classToTable.get(originalClass); } if (table == null) { table = transaction.getTable(realm.configuration.getSchemaMediator().getTableName(originalClass)); classToTable.put(originalClass, table); } if (originalClass != clazz) { classToTable.put(clazz, table); } } return table; }

Target:
Table getTable(Class<? extends RealmModel> clazz) { Table table = classToTable.get(clazz); if (table == null) { Class<? extends RealmModel> originalClass = Util.getOriginalModelClass(clazz); if (isProxyClass(originalClass, clazz)) { table = classToTable.get(originalClass); } if (table == null) { table = transaction.getTable(realm.configuration.getSchemaMediator().getTableName(originalClass)); classToTable.put(originalClass, table); } if (isProxyClass(originalClass, clazz)) { classToTable.put(clazz, table); } } return table; }
Source:
public String getVersion() { if (mIsValid) { return toString(); } else { return "0.0.0"; } }

Target:
public String getVersion() { if (mIsValid) { return toString(); } else { return INVALID_ZERO_VERSION; } }
Source:
public ReleaseRemovalRequest( final String repositoryId, final int numberOfVersionsToKeep, final String targetId ) { this.repositoryId = repositoryId; this.numberOfVersionsToKeep = numberOfVersionsToKeep; this.targetId = targetId; }

Target:
public ReleaseRemovalRequest( final String repositoryId, final int numberOfVersionsToKeep, final String targetId ) { this.repositoryId = checkNotNull(repositoryId); this.numberOfVersionsToKeep = checkNotNull(numberOfVersionsToKeep); this.targetId = targetId; }
Source:
public static void main(String[] args) { MonitoringService obj = new MonitoringService(); CircuitBreaker circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); long serverStartTime = System.nanoTime(); while (true) { LOGGER.info(obj.localResourceResponse()); LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); LOGGER.info(circuitBreaker.getState()); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }

Target:
public static void main(String[] args) { var obj = new MonitoringService(); var circuitBreaker = new CircuitBreaker(3000, 1, 2000 * 1000 * 1000); var serverStartTime = System.nanoTime(); while (true) { LOGGER.info(obj.localResourceResponse()); LOGGER.info(obj.remoteResourceResponse(circuitBreaker, serverStartTime)); LOGGER.info(circuitBreaker.getState()); try { Thread.sleep(5 * 1000); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); } } }
Source:
private static List<Object> deserializeList(JsonParser jp) throws IOException { ImmutableList.Builder<Object> builder = ImmutableList.builder(); JsonToken token; while ((token = jp.nextToken()) != JsonToken.END_ARRAY) { Object obj = deserializeRecursive(jp, token); if (obj != null) { builder.add(obj); } else { StringBuilder message = new StringBuilder(); message.append("null value can't be added to ["); for (Object element: builder.build()) { message.append("'").append(element).append("'").append(", "); } message.append("]"); throw new JsonParseException(null, message.toString()); } } if (token != JsonToken.END_ARRAY) { throw new JsonParseException(jp, "Missing expected END_ARRAY"); } return builder.build(); }

Target:
private static List<Object> deserializeList(JsonParser jp) throws IOException { ImmutableList.Builder<Object> builder = ImmutableList.builder(); JsonToken token; while ((token = jp.nextToken()) != JsonToken.END_ARRAY) { Object obj = deserializeRecursive(jp, token); if (obj != null) { builder.add(obj); } else { StringBuilder message = new StringBuilder(); message.append("null value can't be added to ["); for (Object element: builder.build()) { message.append("'").append(element).append("'").append(", "); } message.append("]"); throw new IllegalArgumentException(message.toString()); } } if (token != JsonToken.END_ARRAY) { throw new JsonParseException(jp, "Missing expected END_ARRAY"); } return builder.build(); }
Source:
private Discover findDiscoveryMode(Resource beansResource) { if (beansResource == null) { return Discover.none; } Document document = readXMLResource(beansResource); if (!document.hasAttributes() && !document.hasChildNodes()) { return Discover.all; } try { Object versionResult = versionExpression.evaluate(document, XPathConstants.STRING); Version version = Version.valueOf(versionResult.toString()); if ((version.equals(Version.LOWEST)) || CDIAnnotationReader.CDI_ARCHIVE_VERSION.compareTo(version) <= 0) { try { Object beanDiscoveryMode = discoveryModeExpression.evaluate(document, XPathConstants.STRING); return Discover.parse(beanDiscoveryMode.toString()); } catch (NullPointerException | XPathExpressionException e) { return Discover.annotated; } } return Discover.all; } catch (NullPointerException | XPathExpressionException e) { return Discover.all; } }

Target:
private Discover findDiscoveryMode(Resource beansResource) { if (beansResource == null) { return Discover.none; } Document document = readXMLResource(beansResource); if (!document.hasAttributes() && !document.hasChildNodes()) { return Discover.all; } try { Object versionResult = versionExpression.evaluate(document, XPathConstants.STRING); Version version = Version.valueOf(versionResult.toString()); if ((version.equals(Version.LOWEST)) || CDIAnnotationReader.CDI_ARCHIVE_VERSION.compareTo(version) <= 0) { try { Object beanDiscoveryMode = discoveryModeExpression.evaluate(document, XPathConstants.STRING); return Discover.parse(beanDiscoveryMode.toString()); } catch (IllegalArgumentException | NullPointerException | XPathExpressionException e) { return Discover.annotated; } } return Discover.all; } catch (NullPointerException | XPathExpressionException e) { return Discover.all; } }
Source:
public void makeBucket(String bucketName, String region) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> headerMap = new HashMap<>(); String configString; if (region == null || US_EAST_1.equals(region)) { configString = ""; } else { CreateBucketConfiguration config = new CreateBucketConfiguration(region); configString = config.toString(); } execute(Method.PUT, US_EAST_1, bucketName, null, headerMap, null, "application/octet-stream", configString, 0); }

Target:
public void makeBucket(String bucketName, String region) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { String configString; if (region == null || US_EAST_1.equals(region)) { configString = ""; } else { CreateBucketConfiguration config = new CreateBucketConfiguration(region); configString = config.toString(); } executePut(bucketName, null, null, null, US_EAST_1, configString, 0); }
Source:
private void performPaymentWorksApprovalProcessingForVendor(VendorDetail vendorDetail, String kfsDocumentNumber, String maintenanceAction) { if (isExistingPaymentWorksVendor(kfsDocumentNumber) && isMaintenanceActionNewOrNewWithExisting(maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: isExistingPaymentWorksVendor"); this.saveBusinessObject(); processExistingPaymentWorksVendorApproval(kfsDocumentNumber, vendorDetail); } else if (isMaintenanceActionNewOrNewWithExisting(maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: new action resulting from AVf or hand keying"); this.saveBusinessObject(); processKfsVendorNewActionApproval(kfsDocumentNumber, vendorDetail); } else if (StringUtils.equals(KRADConstants.MAINTENANCE_EDIT_ACTION, maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: edit action"); processKfsVendorEditActionApproval(kfsDocumentNumber, vendorDetail); } }

Target:
private void performPaymentWorksApprovalProcessingForVendor(VendorDetail vendorDetail, String kfsDocumentNumber, String maintenanceAction) { if (isExistingPaymentWorksVendor(kfsDocumentNumber) && isMaintenanceActionNewOrNewWithExisting(maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: isExistingPaymentWorksVendor"); this.saveBusinessObject(); processExistingPaymentWorksVendorApproval(kfsDocumentNumber, vendorDetail); } else if (isMaintenanceActionNewOrNewWithExisting(maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: new action resulting from AVf or hand keying"); this.saveBusinessObject(); processKfsVendorNewActionApproval(kfsDocumentNumber, vendorDetail); } else if (StringUtils.equals(KRADConstants.MAINTENANCE_EDIT_ACTION, maintenanceAction)) { LOG.debug("performPaymentWorksApprovalProcessingForVendor: edit action"); processKfsVendorEditActionApproval(kfsDocumentNumber, vendorDetail); } else { LOG.info("performPaymentWorksApprovalProcessingForVendor: No PVEN Approval processing performed for PMW because not existing PMW vendor -OR- KFS PVEN maintenance action not currently being tracked for PMW."); } }
Source:
BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) { Assert.notNull(registry, "Registry must not be null"); Assert.notEmpty(sources, "Sources must not be empty"); this.sources = sources; this.annotatedReader = new AnnotatedBeanDefinitionReader(registry); if (IS_XML_ENABLED) { this.xmlReader = new XmlBeanDefinitionReader(registry); this.groovyReader = isGroovyPresent() ? new GroovyBeanDefinitionReader(registry) : null; } else { this.xmlReader = null; this.groovyReader = null; } this.scanner = new ClassPathBeanDefinitionScanner(registry); this.scanner.addExcludeFilter(new ClassExcludeFilter(sources)); }

Target:
BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) { Assert.notNull(registry, "Registry must not be null"); Assert.notEmpty(sources, "Sources must not be empty"); this.sources = sources; this.annotatedReader = new AnnotatedBeanDefinitionReader(registry); this.xmlReader = (IS_XML_ENABLED ? new XmlBeanDefinitionReader(registry) : null); this.groovyReader = (isGroovyPresent() ? new GroovyBeanDefinitionReader(registry) : null); this.scanner = new ClassPathBeanDefinitionScanner(registry); this.scanner.addExcludeFilter(new ClassExcludeFilter(sources)); }
Source:
protected void setup(Context context) throws IOException, InterruptedException { config = HadoopDruidIndexerConfig.fromConfiguration(context.getConfiguration()); List<AggregatorFactory> combiningAggsList = Lists.newArrayList(); for (AggregatorFactory factory : config.getSchema().getDataSchema().getAggregators()) { combiningAggsList.add(factory.getCombiningFactory()); } combiningAggs = combiningAggsList.toArray(new AggregatorFactory[0]); }

Target:
protected void setup(Context context) throws IOException, InterruptedException { config = HadoopDruidIndexerConfig.fromConfiguration(context.getConfiguration()); aggregators = config.getSchema().getDataSchema().getAggregators(); combiningAggs = new AggregatorFactory[aggregators.length]; for (int i = 0; i < aggregators.length; ++i) { combiningAggs[i] = aggregators[i].getCombiningFactory(); } }
Source:
public SessionManagementMethod loadMethodFromSession(Session session, int contextId) throws DatabaseException { ScriptBasedSessionManagementMethod method = new ScriptBasedSessionManagementMethod(); this.loadMethod( method, session.getContextDataStrings(contextId, RecordContext.TYPE_AUTH_METHOD_FIELD_1) .get(0), session.getContextDataStrings(contextId, RecordContext.TYPE_AUTH_METHOD_FIELD_2)); return method; }

Target:
public SessionManagementMethod loadMethodFromSession(Session session, int contextId) throws DatabaseException { ScriptBasedSessionManagementMethod method = new ScriptBasedSessionManagementMethod(); List<String> scripts = session.getContextDataStrings( contextId, RecordContext.TYPE_SESSION_MANAGEMENT_FIELD_1); if (scripts.size() > 0) { this.loadMethod( method, scripts.get(0), session.getContextDataStrings( contextId, RecordContext.TYPE_SESSION_MANAGEMENT_FIELD_2)); } return method; }
Source:
public void forEachPixel( final T action ) { Objects.requireNonNull( action ); if ( Intervals.numElements( dimensions ) == 0 ) return; if ( allAreNativeImages() ) runUsingCursors( action ); else runUsingRandomAccesses( action ); }

Target:
public void forEachPixel( final T action ) { Objects.requireNonNull( action ); if ( Intervals.numElements( dimensions ) == 0 ) return; List< IterableInterval< ? > > iterableIntervals = imagesAsIterableIntervals(); if ( allCursorsAreFast( iterableIntervals ) ) runUsingCursors( iterableIntervals, action ); else runUsingRandomAccesses( action ); }
Source:
@Override public Call<Void> accept(List<Span> spans) { Call<Void> call = delegate.accept(spans); if (isSpanReporterThread()) return call; return new TracedCall<>(tracer, delegate.accept(spans), "accept-spans"); }

Target:
@Override public Call<Void> accept(List<Span> spans) { return new TracedCall<>(tracer, delegate.accept(spans), "accept-spans"); }
Source:
protected Warning createWarning(final Matcher matcher) { String fileName = matcher.group(1); int lineNumber = getLineNumber(matcher.group(2)); String message = matcher.group(7); Priority priority; StringBuilder category = new StringBuilder(); if (matcher.group(4).equalsIgnoreCase("err")) { priority = Priority.HIGH; category.append("ERROR"); } else { priority = Priority.NORMAL; category.append("Warning"); } Warning warning = createWarning(fileName, lineNumber, category.toString(), message, priority); return warning; }

Target:
protected Warning createWarning(final Matcher matcher) { String fileName = matcher.group(1); int lineNumber = getLineNumber(matcher.group(2)); String message = matcher.group(7); Priority priority; String category; if ("err".equalsIgnoreCase(matcher.group(4))) { priority = Priority.HIGH; category = "ERROR"; } else { priority = Priority.NORMAL; category = "Warning"; } return createWarning(fileName, lineNumber, category, message, priority); }
Source:
protected void warn(String message, Exception ex) { if(logger.isDebugEnabled()) { logger.warn(message, ex); } else { logger.warn(message); } }

Target:
protected void warn(String message, Exception ex) { logger.warn(message); if (logger.isDebugEnabled()) { logger.debug("Stacktrace for: " + message, ex); } }
Source:
private List<CrewMember> getDirectors(Element directionElement) { Elements directorElements = directionElement.getChildElements("director"); List<CrewMember> actors = Lists.newArrayList(); for (int i = 0; i < directorElements.size(); i++) { Element directorElement = directorElements.get(i); String role = directorElement.getFirstChildElement("role").getValue(); role = role.trim().replace(" ", "_").toLowerCase(); String name = name(directorElement); if (name != null) { if (CrewMember.Role.fromPossibleKey(role).isNothing()) { log.record(new AdapterLogEntry( AdapterLogEntry.Severity.WARN ).withSource(getClass()).withDescription( "Ignoring crew member with unrecognised role: " + role) ); } else { actors.add(CrewMember.crewMemberWithoutId(name, role, Publisher.RADIO_TIMES)); } } } return actors; }

Target:
private List<CrewMember> getDirectors(Element directionElement) { Elements directorElements = directionElement.getChildElements(DIRECTOR); List<CrewMember> actors = Lists.newArrayList(); for (int i = 0; i < directorElements.size(); i++) { Element directorElement = directorElements.get(i); String role = directorElement.getFirstChildElement(ROLE).getValue(); role = role.trim().replace(" ", "_").toLowerCase(); Optional<String> optionalName = makeName(directorElement); if (optionalName.isPresent()) { if (CrewMember.Role.fromPossibleKey(role).isNothing()) { log.record(new AdapterLogEntry( AdapterLogEntry.Severity.WARN ).withSource(getClass()).withDescription(String.format( "Ignoring crew member with unrecognised role: %s", role )) ); } else { actors.add(CrewMember.crewMemberWithoutId( optionalName.get(), role, Publisher.RADIO_TIMES )); } } } return actors; }
Source:
public Type getType() { String name = name(clazz, fieldIfPresent); Type.Repetition repetition = (clazz.isPrimitive()) ? Type.Repetition.REQUIRED : Type.Repetition.OPTIONAL; if (clazz == boolean.class || clazz == Boolean.class) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.BOOLEAN, name); } else if (clazz == char.class || clazz == Character.class || clazz == byte.class || clazz == Byte.class || clazz == short.class || clazz == Short.class || clazz == int.class || clazz == Integer.class) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.INT32, name); } else if (clazz == long.class || clazz == Long.class) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.INT64, name); } else if (clazz == float.class || clazz == Float.class) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.FLOAT, name); } else if (clazz == double.class || clazz == Double.class) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.DOUBLE, name); } else if (clazz.isEnum()) { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.BINARY, name); } else { return new PrimitiveType(repetition, PrimitiveType.PrimitiveTypeName.BINARY, name); } }

Target:
public Type getType() { String name = name(clazz, fieldIfPresent); Type.Repetition repetition = (clazz.isPrimitive()) ? Type.Repetition.REQUIRED : Type.Repetition.OPTIONAL; PrimitiveType.PrimitiveTypeName typeName; if(clazz.isEnum()) { typeName = PrimitiveType.PrimitiveTypeName.BINARY; } else { typeName = typesToTypeNames.get(clazz); } return new PrimitiveType(repetition, typeName, name); }
Source:
public AtomicFileWriter(@Nonnull Path destinationPath, @Nonnull Charset charset, boolean integrityOnFlush, boolean integrityOnClose) throws IOException { if (charset == null) { throw new IllegalArgumentException("charset is null"); } this.destPath = destinationPath; Path dir = this.destPath.getParent(); if (Files.exists(dir) && !Files.isDirectory(dir)) { throw new IOException(dir + " exists and is neither a directory nor a symlink to a directory"); } else { if (Files.isSymbolicLink(dir)) { LOGGER.log(Level.CONFIG, "{0} is a symlink to a directory", dir); } else { Files.createDirectories(dir); } } try { tmpPath = Files.createTempFile(dir, "atomic", "tmp"); } catch (IOException e) { throw new IOException("Failed to create a temporary file in "+ dir,e); } if (LOSE_INTEGRITY) { LOGGER.log(Level.FINE, "WARNING: YOU SET A FLAG THAT COULD LEAD TO DATA LOSS."); integrityOnFlush = false; integrityOnClose = false; } core = new FileChannelWriter(tmpPath, charset, integrityOnFlush, integrityOnClose, StandardOpenOption.WRITE); }

Target:
public AtomicFileWriter(@Nonnull Path destinationPath, @Nonnull Charset charset, boolean integrityOnFlush, boolean integrityOnClose) throws IOException { if (charset == null) { throw new IllegalArgumentException("charset is null"); } this.destPath = destinationPath; Path dir = this.destPath.getParent(); if (Files.exists(dir) && !Files.isDirectory(dir)) { throw new IOException(dir + " exists and is neither a directory nor a symlink to a directory"); } else { if (Files.isSymbolicLink(dir)) { LOGGER.log(Level.CONFIG, "{0} is a symlink to a directory", dir); } else { Files.createDirectories(dir); } } try { tmpPath = Files.createTempFile(dir, "atomic", "tmp"); } catch (IOException e) { throw new IOException("Failed to create a temporary file in "+ dir,e); } if (DISABLE_FORCED_FLUSH) { integrityOnFlush = false; integrityOnClose = false; } core = new FileChannelWriter(tmpPath, charset, integrityOnFlush, integrityOnClose, StandardOpenOption.WRITE); }
Source:
protected void executeVmCommand() { if (diskShouldBeUnPlugged()) { performPlugCommand(VDSCommandType.HotUnPlugDisk, disk, vmDevice); } getVmDeviceDao().remove(vmDevice.getId()); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { getImageDao().updateImageVmSnapshotId(((DiskImage) disk).getImageId(), Guid.Empty); } VmHandler.updateDisksFromDb(getVm()); VmDeviceUtils.updateBootOrderInVmDeviceAndStoreToDB(getVm().getStaticData()); setSucceeded(true); }

Target:
protected void executeVmCommand() { if (diskShouldBeUnPlugged()) { performPlugCommand(VDSCommandType.HotUnPlugDisk, disk, vmDevice); } getVmDeviceDao().remove(vmDevice.getId()); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { getImageDao().updateImageVmSnapshotId(((DiskImage) disk).getImageId(), null); } VmHandler.updateDisksFromDb(getVm()); VmDeviceUtils.updateBootOrderInVmDeviceAndStoreToDB(getVm().getStaticData()); setSucceeded(true); }
Source:
public HelixClusterManager getClusterMap() throws IOException { if (helixClusterManager == null) { ZkClient zkClient = new ZkClient(helixPropertyStoreConfig.zkClientConnectString, helixPropertyStoreConfig.zkClientSessionTimeoutMs, helixPropertyStoreConfig.zkClientConnectionTimeoutMs, new ZNRecordSerializer()); List<String> subscribedPaths = Collections.singletonList(helixPropertyStoreConfig.rootPath); helixPropertyStore = new ZkHelixPropertyStore<>(new ZkBaseDataAccessor<>(zkClient), helixPropertyStoreConfig.rootPath, subscribedPaths); helixClusterManager = new HelixClusterManager(clusterMapConfig, helixPropertyStore, instanceName, helixFactory, metricRegistry); } return helixClusterManager; }

Target:
public HelixClusterManager getClusterMap() throws IOException { if (helixClusterManager == null) { helixClusterManager = new HelixClusterManager(clusterMapConfig, instanceName, helixFactory, metricRegistry); } return helixClusterManager; }
Source:
protected void fillLocalToolBar(IToolBarManager manager) { manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new CollapseAction(Messages.CollapseButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new ExpandAction(Messages.ExpandButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new FilterAction(Messages.FilterButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getResetScaleAction()); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getPreviousEventAction()); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getNextEventAction()); }

Target:
protected void fillLocalToolBar(IToolBarManager manager) { manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new CollapseAction(Messages.CollapseButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new ExpandAction(Messages.ExpandButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new FilterAction(Messages.FilterButton)); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, new Separator()); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getResetScaleAction()); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getPreviousEventAction()); manager.appendToGroup(IWorkbenchActionConstants.MB_ADDITIONS, getTimeGraphViewer().getNextEventAction()); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewHolder = new ViewHolder(view, isViewingOwnProfile, new Runnable() { @Override public void run() { router.showUserProfileEditor(getActivity(), username); } }); viewHolder.setUsername(username); viewHolder.setAccount(account); }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewHolder = new UserProfileViewHolder(view); viewHolder.editProfileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { router.showUserProfileEditor(getActivity(), username); } }); viewHolder.usernameText.setText(username); setAccount(account); if (null == getAccountTask) { getAccountTask = new GetAccountTask(getActivity(), username) { @Override protected void onSuccess(Account account) throws Exception { setAccount(account); } @Override protected void onException(Exception e) throws RuntimeException { logger.error(e); showErrorMessage(e); } }; getAccountTask.setProgressDialog(viewHolder.loadingIndicator); getAccountTask.execute(); } }
Source:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); int columnIndex = 0; for (TmfEventTableColumn column : columns) { ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || !isVisibleEventColumn(fTable.getColumns()[columnIndex])) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } columnIndex++; } return itemStrings.toArray(new String[0]); } }

Target:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); int columnIndex = 0; for (TmfEventTableColumn column : columns) { ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } TableColumn viewColumn = fTable.getColumns()[columnIndex]; if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } columnIndex++; } return itemStrings.toArray(new String[0]); } }
Source:
public void report( SortedMap<String,Gauge> gauges, SortedMap<String,Counter> counters, SortedMap<String,Histogram> histograms, SortedMap<String,Meter> meters, SortedMap<String,Timer> timers ) { String metricKey = gauges.firstKey(); if ( !registeredEvents.containsKey( metricKey ) ) { registry.register( metricKey, (Gauge) () -> registeredEvents.get( metricKey ) ); } registeredEvents.put( metricKey, gauges.get( metricKey ).getValue() ); }

Target:
public void report( SortedMap<String,Gauge> gauges, SortedMap<String,Counter> counters, SortedMap<String,Histogram> histograms, SortedMap<String,Meter> meters, SortedMap<String,Timer> timers ) { String metricKey = gauges.firstKey(); if ( !registeredEvents.containsKey( metricKey ) ) { eventRegistry.register( metricKey, (Gauge) () -> registeredEvents.get( metricKey ) ); } registeredEvents.put( metricKey, gauges.get( metricKey ).getValue() ); }
Source:
@Test public void getSupportedPerformanceDataTypesTest() { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); assert(supportedPerformanceDataTypes.size() == 4); }

Target:
@Test public void getSupportedPerformanceDataTypesTest() { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> dataTypes = new ArrayList<String>(); dataTypes.add("cpuinfo"); dataTypes.add("memoryinfo"); dataTypes.add("batteryinfo"); dataTypes.add("networkinfo"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); assertEquals(4, supportedPerformanceDataTypes.size()); for ( int i = 0 ; i < supportedPerformanceDataTypes.size() ; ++i) { assertEquals(dataTypes.get(i), supportedPerformanceDataTypes.get(i)); } }
Source:
public void setFlying(boolean value) { if (flying != (flying = value && canFly)) { EventFactory.getInstance().callEvent( new PlayerToggleFlightEvent(this, flying)); } sendAbilities(); }

Target:
public void setFlying(boolean value) { flying = value && canFly; getServer().sendPlayerAbilities(this); }
Source:
public void sync(ServoControl sc) { this.addServoEventListener(this); subscribe(sc.getName(), "publishServoEvent", getName(), "moveTo"); }

Target:
public void sync(ServoControl sc) { this.addServoEventListener(this); ((Servo) sc).addServoEventListener((NameProvider) sc); subscribe(sc.getName(), "publishServoEvent", getName(), "moveTo"); }
Source:
public void saveSentMessage_shouldReturnTheSavedMessage() { Message m = new Message(); m.setId(17); m.setSubject("for test"); m.setContent("content for testing"); User sender = new User(); sender.setId(27); SentMessage sm = sentMessageService.saveSentMessage(new SentMessage(m, sender.getUserId(), null)); Assert.assertNotNull(sm); Assert.assertEquals(m.getId(), sm.getMessageId()); Assert.assertEquals(sender.getUserId(), sm.getSenderId()); }

Target:
public void saveSentMessage_shouldReturnTheSavedMessage() { Message m = new Message(); m.setId(17); m.setSubject("for test"); m.setContent("content for testing"); User sender = new User(); sender.setId(27); SentMessage sm = sentMessageService.saveSentMessage(new SentMessage(m, sender, null)); Assert.assertNotNull(sm); Assert.assertEquals(m.getId(), sm.getMessageId()); Assert.assertEquals(sender.getUserId(), sm.getSender().getUserId()); }
Source:
boolean exists(K key, String name) { if (key == null) { return false; } List<V> list = getDataMap().get(key); if (list == null) { return false; } for (V data : list) { if (getDataName(data).equals(name)) { return true; } } return false; }

Target:
boolean exists(K key, String name) { return find(key, name) != null; }
Source:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) .setSoTimeout(socketTimeout > 0 ? socketTimeout : TIMEOUT_THREE_HOURS) .build(); }

Target:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) .setSoTimeout(socketTimeout) .build(); }
Source:
private int daysWithoutPasswordChange(MotechUser user) { return Days.daysBetween(user.getLastPasswordChange(), DateTime.now()).getDays(); }

Target:
private int daysWithoutPasswordChange(MotechUser user) { return Days.daysBetween(user.getLastPasswordChange(), DateUtil.now()).getDays(); }
Source:
public synchronized void report(int seqnum, long time) { cache.put(seqnum, time); assert(cache.size() <= cache.maxSize); }

Target:
public synchronized void report(int seqnum, long time) { cache.put(seqnum, time); }
Source:
public void run() { long delayMS = pollPeriodinMS; try { final long pollStartTime = System.nanoTime(); poll(); final long pollEndTime = System.nanoTime(); final long pollTimeNS = pollEndTime - pollStartTime; final long pollTimeMS = TimeUnit.NANOSECONDS.toMillis(pollTimeNS); delayMS = Math.max(pollPeriodinMS - pollTimeMS, 0); } catch (Exception e) { log.makeAlert(e, "Problem polling Coordinator.").emit(); } scheduledExec.schedule(new PollTask(), delayMS, TimeUnit.MILLISECONDS); }

Target:
public void run() { long delayMS = pollPeriodInMS; try { final long pollStartTime = System.nanoTime(); poll(); final long pollEndTime = System.nanoTime(); final long pollTimeNS = pollEndTime - pollStartTime; final long pollTimeMS = TimeUnit.NANOSECONDS.toMillis(pollTimeNS); delayMS = Math.max(pollPeriodInMS - pollTimeMS, 0); } catch (Exception e) { log.makeAlert(e, "Problem polling Coordinator.").emit(); } finally { if (!Thread.currentThread().isInterrupted()) { scheduledExec.schedule(new PollTask(), delayMS, TimeUnit.MILLISECONDS); } } }
Source:
public Integer getNumberOfPrograms() { return numberOfPrograms; }

Target:
public int getNumberOfPrograms() { return results.size(); }
Source:
private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { LogUtil.w(be, "Binding error, sleep 1 second ..."); if (firstException == null) { firstException = be; } sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }

Target:
private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms..."); if (firstException == null) { firstException = be; } Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }
Source:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); Patient patientToAddThenRemove = new Patient(4); assertFalse(service.getCohort(2).contains(patientToAddThenRemove.getPatientId())); try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }

Target:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); Patient patientToAddThenRemove = new Patient(4); assertFalse(service.getCohort(2).contains(patientToAddThenRemove)); try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }
Source:
private void writeStatistics(final Region region, boolean delete, List<Mutation> mutations, long currentTime, Scan scan) throws IOException { Set<ImmutableBytesPtr> fams = guidePostsInfoWriterMap.keySet(); if (cachedGuidePosts == null) { boolean collectingForLocalIndex = scan != null && !scan.getFamilyMap().isEmpty() && MetaDataUtil.isLocalIndexFamily(scan.getFamilyMap().keySet().iterator().next()); for (Store store : region.getStores()) { ImmutableBytesPtr cfKey = new ImmutableBytesPtr(store.getFamily().getName()); boolean isLocalIndexStore = MetaDataUtil.isLocalIndexFamily(cfKey); if (isLocalIndexStore != collectingForLocalIndex) { continue; } if (!guidePostsInfoWriterMap.containsKey(cfKey)) { Pair<Long, GuidePostsInfoBuilder> emptyGps = new Pair<Long, GuidePostsInfoBuilder>(0l, new GuidePostsInfoBuilder()); guidePostsInfoWriterMap.put(cfKey, emptyGps); } } } for (ImmutableBytesPtr fam : fams) { if (delete) { statsWriter.deleteStatsForRegion(region, this, fam, mutations); LOG.info("Generated " + mutations.size() + " mutations to delete existing stats"); } if (this.guidePostDepth > 0) { int oldSize = mutations.size(); statsWriter.addStats(this, fam, mutations); LOG.info("Generated " + (mutations.size() - oldSize) + " mutations for new stats"); } } }

Target:
private void writeStatistics(final Region region, boolean delete, List<Mutation> mutations, long currentTime, Scan scan) throws IOException { Set<ImmutableBytesPtr> fams = guidePostsInfoWriterMap.keySet(); if (cachedGuidePosts == null) { boolean collectingForLocalIndex = scan != null && !scan.getFamilyMap().isEmpty() && MetaDataUtil.isLocalIndexFamily(scan.getFamilyMap().keySet().iterator().next()); for (Store store : region.getStores()) { ImmutableBytesPtr cfKey = new ImmutableBytesPtr(store.getFamily().getName()); boolean isLocalIndexStore = MetaDataUtil.isLocalIndexFamily(cfKey); if (isLocalIndexStore != collectingForLocalIndex) { continue; } if (!guidePostsInfoWriterMap.containsKey(cfKey)) { Pair<Long, GuidePostsInfoBuilder> emptyGps = new Pair<Long, GuidePostsInfoBuilder>(0l, new GuidePostsInfoBuilder()); guidePostsInfoWriterMap.put(cfKey, emptyGps); } } } for (ImmutableBytesPtr fam : fams) { if (delete) { statsWriter.deleteStatsForRegion(region, this, fam, mutations); LOG.info("Generated " + mutations.size() + " mutations to delete existing stats"); } if (this.guidePostDepth > 0) { int oldSize = mutations.size(); statsWriter.addStats(this, fam, mutations, guidePostDepth); LOG.info("Generated " + (mutations.size() - oldSize) + " mutations for new stats"); } } }
Source:
public long acceptWay(ReaderWay way) { String highwayValue = way.getTag("highway"); if (highwayValue == null) { long acceptPotentially = 0; if (way.hasTag("route", ferries)) { String footTag = way.getTag("foot"); if (footTag == null || "yes".equals(footTag)) acceptPotentially = acceptBit | ferryBit; } if (way.hasTag("railway", "platform")) acceptPotentially = acceptBit; if (way.hasTag("man_made", "pier")) acceptPotentially = acceptBit; if (acceptPotentially != 0) { if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; return acceptBit; } return 0; } String sacScale = way.getTag("sac_scale"); if (sacScale != null) { if (!"hiking".equals(sacScale) && !"mountain_hiking".equals(sacScale) && !"demanding_mountain_hiking".equals(sacScale) && !"alpine_hiking".equals(sacScale)) return 0; } if (way.hasTag("foot", intendedValues)) return acceptBit; if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; if (way.hasTag("sidewalk", sidewalkValues)) return acceptBit; if (!allowedHighwayTags.contains(highwayValue)) return 0; if (way.hasTag("motorroad", "yes")) return 0; if (isBlockFords() && (way.hasTag("highway", "ford") || way.hasTag("ford"))) return 0; if (getConditionalTagInspector().isPermittedWayConditionallyRestricted(way)) return 0; return acceptBit; }

Target:
public long acceptWay(ReaderWay way) { String highwayValue = way.getTag("highway"); if (highwayValue == null) { long acceptPotentially = 0; if (way.hasTag("route", ferries)) { String footTag = way.getTag("foot"); if (footTag == null || "yes".equals(footTag)) acceptPotentially = acceptBit | ferryBit; } if (way.hasTag("railway", "platform")) acceptPotentially = acceptBit; if (way.hasTag("man_made", "pier")) acceptPotentially = acceptBit; if (acceptPotentially != 0) { if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; return acceptPotentially; } return 0; } String sacScale = way.getTag("sac_scale"); if (sacScale != null) { if (!"hiking".equals(sacScale) && !"mountain_hiking".equals(sacScale) && !"demanding_mountain_hiking".equals(sacScale) && !"alpine_hiking".equals(sacScale)) return 0; } if (way.hasTag("foot", intendedValues)) return acceptBit; if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; if (way.hasTag("sidewalk", sidewalkValues)) return acceptBit; if (!allowedHighwayTags.contains(highwayValue)) return 0; if (way.hasTag("motorroad", "yes")) return 0; if (isBlockFords() && (way.hasTag("highway", "ford") || way.hasTag("ford"))) return 0; if (getConditionalTagInspector().isPermittedWayConditionallyRestricted(way)) return 0; return acceptBit; }
Source:
public String putIfAbsent(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); String result = value; Query query = new Query(Criteria.where("key").is(key)); if (template.exists(query, collectionName)) { result = null; } else { template.save(new Datastore(key, value), collectionName); } return result; }

Target:
public String putIfAbsent(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BasicDBObject result = (BasicDBObject) operations.call(PUT_IF_ABSENT, key, value); return (result == null) ? null : (String) result.get(VALUE); }
Source:
final static <T> int getFirstKeyframeIndexAtTime (final Array<NodeKeyframe<T>> arr, final float time) { final int lastIndex = arr.size - 1; if (lastIndex < 0 || time < arr.get(0).keytime || time > arr.get(lastIndex).keytime) { return 0; } int minIndex = 0; int maxIndex = lastIndex; for (;;) { final float minTime = arr.get(minIndex).keytime; final float maxTime = arr.get(maxIndex).keytime; if (time < minTime) { return Math.max(0, minIndex - 1); } if (time > maxTime) { return Math.min(lastIndex - 1, maxIndex); } if (minTime == maxTime) { return minIndex; } float t = (time - minTime) / (maxTime - minTime); int index = (int)(minIndex + t * (maxIndex - minIndex)); if (time < arr.get(index).keytime) { maxIndex = index - 1; } else if (time > arr.get(index).keytime) { minIndex = index + 1; } else { return Math.min(lastIndex - 1, index); } } }

Target:
final static <T> int getFirstKeyframeIndexAtTime (final Array<NodeKeyframe<T>> arr, final float time) { final int lastIndex = arr.size - 1; if (lastIndex <= 0 || time < arr.get(0).keytime || time > arr.get(lastIndex).keytime) { return 0; } int minIndex = 0; int maxIndex = lastIndex; while (minIndex < maxIndex) { int i = (minIndex + maxIndex) / 2; if (time > arr.get(i + 1).keytime) { minIndex = i + 1; } else if (time < arr.get(i).keytime) { maxIndex = i - 1; } else { return i; } } return minIndex; }