auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DetailledItem getResultById(String id, String homebranch) throws IOException, OpacErrorException { final String html = httpGet(opac_url + "/search?view=detail&id=" + id, getDefaultEncoding()); final Document doc = Jsoup.parse(html); final Element detailData = doc.select(".detailData").first(); final Element detailTable = detailData.select("table.titel").first(); final Element availabilityTable = doc.select(".bibliothek table").first(); final DetailledItem result = new DetailledItem(); final HashMap<String, String> copy = new HashMap<>(); result.addCopy(copy); result.setId(id); result.setCover(getCover(doc)); result.setTitle(detailData.select("h3").first().text()); result.setMediaType(MEDIA_TYPES.get(getCellContent(detailTable, "Medienart|Type of media"))); copy.put(DetailledItem.KEY_COPY_STATUS, getCellContent(availabilityTable, "Verfügbar|Available")); copy.put(DetailledItem.KEY_COPY_RESERVATIONS, getCellContent(availabilityTable, "Reservierungen|Reservations")); for (final Element tr : detailTable.select("tr")) { final String desc = tr.child(0).text(); final String content = tr.child(1).text(); if (desc != null && !desc.trim().isEmpty()) { result.addDetail(new Detail(desc, content)); } else if (!result.getDetails().isEmpty()) { final Detail lastDetail = result.getDetails().get(result.getDetails().size() - 1); lastDetail.setHtml(true); lastDetail.setContent(lastDetail.getContent() + "<br>" + content); } } return result; }

Target:
public DetailledItem getResultById(String id, String homebranch) throws IOException, OpacErrorException { if (!initialised) { start(); } final String html = httpGet(getApiUrl() + "&view=detail&id=" + id, getDefaultEncoding()); final Document doc = Jsoup.parse(html); final Element detailData = doc.select(".detailData").first(); final Element detailTable = detailData.select("table.titel").first(); final Element availabilityTable = doc.select(".bibliothek table").first(); final DetailledItem result = new DetailledItem(); final HashMap<String, String> copy = new HashMap<>(); result.addCopy(copy); result.setId(id); result.setCover(getCover(doc)); result.setTitle(detailData.select("h3").first().text()); result.setMediaType(MEDIA_TYPES.get(getCellContent(detailTable, "Medienart|Type of media"))); copy.put(DetailledItem.KEY_COPY_STATUS, getCellContent(availabilityTable, "Verfügbar|Available")); copy.put(DetailledItem.KEY_COPY_RESERVATIONS, getCellContent(availabilityTable, "Reservierungen|Reservations")); for (final Element tr : detailTable.select("tr")) { final String desc = tr.child(0).text(); final String content = tr.child(1).text(); if (desc != null && !desc.trim().isEmpty()) { result.addDetail(new Detail(desc, content)); } else if (!result.getDetails().isEmpty()) { final Detail lastDetail = result.getDetails().get(result.getDetails().size() - 1); lastDetail.setHtml(true); lastDetail.setContent(lastDetail.getContent() + "<br>" + content); } } return result; }
Source:
public void test() throws Throwable { ExecutorService pool = Executors.newFixedThreadPool(32); for (int i = 0; i < 32; i++) { final String connStr = "jdbc:sqlite:sample-" + i + ".db"; final int sleepMillis = i; pool.execute(new Runnable() { public void run() { try { Thread.sleep(sleepMillis * 10); } catch (InterruptedException e) { } try { Connection conn = DriverManager.getConnection(connStr); System.out.println("Connected!"); } catch (SQLException e) { e.printStackTrace(); Assert.fail(e.getLocalizedMessage()); } } }); } pool.awaitTermination(3, TimeUnit.SECONDS); }

Target:
public void test() throws Throwable { ExecutorService pool = Executors.newFixedThreadPool(32); for (int i = 0; i < 32; i++) { final String connStr = "jdbc:sqlite:target/sample-" + i + ".db"; final int sleepMillis = i; pool.execute(new Runnable() { public void run() { try { Thread.sleep(sleepMillis * 10); } catch (InterruptedException e) { } try { Connection conn = DriverManager.getConnection(connStr); } catch (SQLException e) { e.printStackTrace(); Assert.fail(e.getLocalizedMessage()); } } }); } pool.awaitTermination(3, TimeUnit.SECONDS); }
Source:
protected RestHighLevelClient makeClient(IndexWriterParams parameters) throws IOException { hosts = parameters.getStrings(ElasticConstants.HOSTS); port = parameters.getInt(ElasticConstants.PORT, DEFAULT_PORT); user = parameters.get(ElasticConstants.USER, DEFAULT_USER); password = parameters.get(ElasticConstants.PASSWORD, ""); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); RestHighLevelClient client = null; if (hosts != null && port > 1) { HttpHost[] hostsList = new HttpHost[hosts.length]; int i = 0; for(String host: hosts) { hostsList[i++] = new HttpHost(host, port); } RestClientBuilder restClientBuilder = RestClient.builder(hostsList); if (StringUtils.isNotBlank(cluster)) { Header[] defaultHeaders = new Header[]{new BasicHeader("cluster.name", cluster)}; restClientBuilder.setDefaultHeaders(defaultHeaders); } else { LOG.debug("No cluster name provided so using default"); } if(StringUtils.isNotBlank(password)) { restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder arg0) { return arg0 .setDefaultCredentialsProvider(credentialsProvider); } }); } client = new RestHighLevelClient(restClientBuilder); } else { throw new IOException("ElasticRestClient initialization Failed!!!\\n\\nPlease Provide the hosts"); } return client; }

Target:
protected RestHighLevelClient makeClient(IndexWriterParams parameters) throws IOException { hosts = parameters.getStrings(ElasticConstants.HOSTS); port = parameters.getInt(ElasticConstants.PORT, DEFAULT_PORT); auth = parameters.getBoolean(ElasticConstants.USE_AUTH, false); user = parameters.get(ElasticConstants.USER, DEFAULT_USER); password = parameters.get(ElasticConstants.PASSWORD, ""); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); RestHighLevelClient client = null; if (hosts != null && port > 1) { HttpHost[] hostsList = new HttpHost[hosts.length]; int i = 0; for (String host : hosts) { hostsList[i++] = new HttpHost(host, port); } RestClientBuilder restClientBuilder = RestClient.builder(hostsList); if (auth) { restClientBuilder .setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder arg0) { return arg0.setDefaultCredentialsProvider(credentialsProvider); } }); } client = new RestHighLevelClient(restClientBuilder); } else { throw new IOException( "ElasticRestClient initialization Failed!!!\\n\\nPlease Provide the hosts"); } return client; }
Source:
public void onWritePossible() throws IOException { while (out.isReady()) { try { buffer.clear(); if (in.read(buffer) < 0) { buffer = null; } else { buffer.flip(); } } catch(Throwable t) { LOG.log(Level.SEVERE, t.getMessage(), t); buffer = null; } finally { if (buffer != null) { outChannel.write(buffer); } else { try { out.close(); } finally { context.complete(); return; } return; } } } }

Target:
public void onWritePossible() throws IOException { while (out.isReady()) { try { buffer.clear(); if (in.read(buffer) < 0) { buffer = null; } else { buffer.flip(); } } catch(Throwable t) { LOG.log(Level.SEVERE, t.getMessage(), t); buffer = null; } finally { if (buffer != null) { outChannel.write(buffer); } else { try { out.close(); } finally { context.complete(); } return; } } } }
Source:
public String normalize(String absoluteFieldPath, String value) { if ( value == null ) { return null; } return analyzerOrNormalizer != null ? analyzerOrNormalizer.normalize( absoluteFieldPath, value ).utf8ToString() : value; }

Target:
public BytesRef normalize(String absoluteFieldPath, String value) { if ( value == null ) { return null; } if ( analyzerOrNormalizer == null ) { return new BytesRef( value ); } return analyzerOrNormalizer.normalize( absoluteFieldPath, value ); }
Source:
private Guid findImageForSameDrive(Guid snapshotId, DiskImage diskImage) { List<DiskImage> imagesFromSnapshot = diskImageDao.getAllSnapshotsForVmSnapshot(snapshotId); for (DiskImage currDiskImage : imagesFromSnapshot) { if (diskImage.getId().equals(currDiskImage.getId())) { return currDiskImage.getImageId(); } } return null; }

Target:
private Guid findImageForSameDrive(Guid snapshotId, DiskImage diskImage) { List<DiskImage> imagesFromSnapshot = diskImageDao.getAllSnapshotsForVmSnapshot(snapshotId); return imagesFromSnapshot.stream() .filter(currDiskImage -> diskImage.getId().equals(currDiskImage.getId())) .findFirst() .map(DiskImage::getImageId) .orElse(null); }
Source:
public void handleSetDataResponse(final EmptyResponseDto emptyResponseDto, final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType responseMessageResultType, final OsgpException osgpException) { LOGGER.info("handleResponse for MessageType: {}", messageType); ResponseMessageResultType result = ResponseMessageResultType.OK; EmptyResponse emptyResponse = null; OsgpException exception = null; try { if (responseMessageResultType == ResponseMessageResultType.NOT_OK || osgpException != null) { LOGGER.error("Device Response not ok.", osgpException); throw osgpException; } this.handleResponseMessageReceived(deviceIdentification); emptyResponse = this.mapper.map(emptyResponseDto, EmptyResponse.class); } catch (final Exception e) { LOGGER.error("Unexpected Exception", e); result = ResponseMessageResultType.NOT_OK; exception = this.ensureOsgpException(e, "Exception occurred while setting data"); } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(exception) .withDataObject(emptyResponse).build(), messageType); }

Target:
public void handleSetDataResponse(final EmptyResponseDto emptyResponseDto, final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType responseMessageResultType, final OsgpException osgpException) { LOGGER.info("handleResponse for MessageType: {}", messageType); ResponseMessageResultType result = ResponseMessageResultType.OK; EmptyResponse emptyResponse = null; OsgpException exception = null; try { if (responseMessageResultType == ResponseMessageResultType.NOT_OK || osgpException != null) { LOGGER.error("Device Response not ok.", osgpException); throw osgpException; } this.handleResponseMessageReceived(deviceIdentification); emptyResponse = this.mapper.map(emptyResponseDto, EmptyResponse.class); } catch (final Exception e) { LOGGER.error("Unexpected Exception", e); result = ResponseMessageResultType.NOT_OK; exception = this.ensureOsgpException(e, "Exception occurred while setting data"); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(exception) .withDataObject(emptyResponse).build(); this.webServiceResponseMessageSender.send(responseMessage, messageType); }
Source:
public void testExecuteQuery() { Guid storagePoolID = new Guid(UUID.randomUUID()); storage_pool expectedResult = mock(storage_pool.class); StoragePoolQueryParametersBase paramsMock = getQueryParameters(); when(paramsMock.getStoragePoolId()).thenReturn(storagePoolID); StoragePoolDAO storagePoolDAOMock = mock(StoragePoolDAO.class); when(storagePoolDAOMock.get(storagePoolID, getUser().getUserId(), paramsMock.isFiltered())).thenReturn(expectedResult); DbFacade dbFacadeMock = getDbFacadeMockInstance(); when(dbFacadeMock.getStoragePoolDAO()).thenReturn(storagePoolDAOMock); getQuery().executeQueryCommand(); storage_pool result = (storage_pool) getQuery().getQueryReturnValue().getReturnValue(); assertEquals("Wrong storage pool returned", expectedResult, result); verify(storagePoolDAOMock, times(1)).get(storagePoolID, getUser().getUserId(), paramsMock.isFiltered()); verifyNoMoreInteractions(storagePoolDAOMock); }

Target:
public void testExecuteQuery() { Guid storagePoolID = new Guid(UUID.randomUUID()); storage_pool expectedResult = mock(storage_pool.class); StoragePoolQueryParametersBase paramsMock = getQueryParameters(); when(paramsMock.getStoragePoolId()).thenReturn(storagePoolID); StoragePoolDAO storagePoolDAOMock = mock(StoragePoolDAO.class); when(storagePoolDAOMock.get(storagePoolID, getUser().getUserId(), paramsMock.isFiltered())).thenReturn(expectedResult); DbFacade dbFacadeMock = getDbFacadeMockInstance(); when(dbFacadeMock.getStoragePoolDAO()).thenReturn(storagePoolDAOMock); getQuery().executeQueryCommand(); storage_pool result = (storage_pool) getQuery().getQueryReturnValue().getReturnValue(); assertEquals("Wrong storage pool returned", expectedResult, result); }
Source:
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request); String lookupPath = getUrlPathHelper().getLookupPathForRequest(request); String repositoryLookupPath = new BaseUri(configuration.getBaseUri()).getRepositoryLookupPath(lookupPath); if (StringUtils.hasText(repositoryLookupPath) && repositories != null) { CorsConfiguration repositoryConfiguration = new CorsConfigurationAccessor(mappings, repositories, embeddedValueResolver).findCorsConfiguration(lookupPath); if (repositoryConfiguration != null) { if (corsConfiguration != null) { return corsConfiguration.combine(repositoryConfiguration); } return repositoryConfiguration; } } return corsConfiguration; }

Target:
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) { CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request); String lookupPath = getUrlPathHelper().getLookupPathForRequest(request); String repositoryLookupPath = new BaseUri(configuration.getBaseUri()).getRepositoryLookupPath(lookupPath); if (!StringUtils.hasText(repositoryLookupPath) || repositories == null) { return corsConfiguration; } CorsConfiguration repositoryConfiguration = new CorsConfigurationAccessor(mappings, repositories, embeddedValueResolver).findCorsConfiguration(lookupPath); if (repositoryConfiguration != null) { return corsConfiguration != null ? corsConfiguration.combine(repositoryConfiguration) : repositoryConfiguration; } return corsConfiguration; }
Source:
private boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }

Target:
private static boolean isWithinTryHeader(Tree syntaxNode) { final Tree parent = syntaxNode.parent(); if (parent.is(Tree.Kind.VARIABLE)) { return isTryStatementResource((VariableTree) parent); } return false; }
Source:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable tvp1 = args[0]; ObjectPointable op; if (tvp1.getTag() == ValueTag.SEQUENCE_TAG) { List<TaggedValuePointable> pointables = new ArrayList<>(); TaggedValuePointable temptvp = ppool.takeOne(TaggedValuePointable.class); try { tvp1.getValue(sp1); int size1 = sp1.getEntryCount(); int size2; for (int i = 0; i < size1; i++) { sp1.getEntry(i, temptvp); if (temptvp.getTag() == ValueTag.OBJECT_TAG) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); temptvp.getValue(op); op.getKeys(temptvp); temptvp.getValue(sp2); size2 = sp2.getEntryCount(); for (int j = 0; j < size2; j++) { TaggedValuePointable tvp = (TaggedValuePointable) TaggedValuePointable.FACTORY .createPointable(); sp2.getEntry(j, tvp); pointables.add(tvp); } } } removeDuplicates(pointables); abvs.reset(); sb.reset(abvs); for (TaggedValuePointable tvp : pointables) { sb.addItem(tvp); } sb.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(temptvp); } } else if (tvp1.getTag() == ValueTag.OBJECT_TAG) { try { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); tvp1.getValue(op); op.getKeys(result); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } else { XDMConstants.setEmptySequence(result); } }

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable tvp1 = args[0]; ObjectPointable op; if (tvp1.getTag() == ValueTag.SEQUENCE_TAG) { pointables = new ArrayList<>(); TaggedValuePointable temptvp = ppool.takeOne(TaggedValuePointable.class); try { tvp1.getValue(sp1); int size1 = sp1.getEntryCount(); int size2; for (int i = 0; i < size1; i++) { sp1.getEntry(i, temptvp); if (temptvp.getTag() == ValueTag.OBJECT_TAG) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); temptvp.getValue(op); op.getKeys(temptvp); temptvp.getValue(sp2); size2 = sp2.getEntryCount(); for (int j = 0; j < size2; j++) { TaggedValuePointable tvp = (TaggedValuePointable) TaggedValuePointable.FACTORY .createPointable(); sp2.getEntry(j, tvp); pointables.add(tvp); } } } removeDuplicates(pointables); abvs.reset(); sb.reset(abvs); for (TaggedValuePointable tvp : pointables) { sb.addItem(tvp); } sb.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(temptvp); } } else if (tvp1.getTag() == ValueTag.OBJECT_TAG) { try { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); tvp1.getValue(op); op.getKeys(result); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } } else { XDMConstants.setEmptySequence(result); } }
Source:
private static boolean deepEqualsRowData( RowData should, RowData is, RowDataSerializer serializer1, RowDataSerializer serializer2, boolean checkClass) { if (should.getArity() != is.getArity()) { return false; } if (checkClass && should.getClass() != is.getClass()) { return false; } BinaryRowData row1 = serializer1.toBinaryRow(should); BinaryRowData row2 = serializer2.toBinaryRow(is); return Objects.equals(row1, row2); }

Target:
private static boolean deepEqualsRowData( RowData should, RowData is, RowDataSerializer serializer1, RowDataSerializer serializer2, boolean checkClass) { if (should.getArity() != is.getArity()) { return false; } if (checkClass && (should.getClass() != is.getClass() || !should.equals(is))) { return false; } BinaryRowData row1 = serializer1.toBinaryRow(should); BinaryRowData row2 = serializer2.toBinaryRow(is); return Objects.equals(row1, row2); }
Source:
public void setBlock(Block block) { this.columnarRow = ColumnarRow.toColumnarRow(block); this.position = 0; this.positionCount = block == null ? 0 : block.getPositionCount(); }

Target:
public void setBlock(Block block) { this.position = 0; this.nonNullPosition = 0; if (block == null) { this.columnarRow = null; this.positionCount = 0; } else { this.columnarRow = ColumnarRow.toColumnarRow(block); this.positionCount = block.getPositionCount(); } }
Source:
public PartitionId PartitionIdentifyCreate(ServletRequestDetails theRequestDetails) { String partitionName = theRequestDetails.getHeader("X-Partition-Name"); return PartitionId.fromPartitionName(partitionName); }

Target:
public RequestPartitionId PartitionIdentifyCreate(ServletRequestDetails theRequestDetails) { String partitionName = theRequestDetails.getHeader("X-Partition-Name"); return RequestPartitionId.fromPartitionName(partitionName); }
Source:
protected void fillEdgesToUsingFilter(EdgeFilter edgeFilter) { EdgeFilter tmpFilter = additionalEdgeFilter; additionalEdgeFilter = edgeFilter; finishedTo = !fillEdgesTo(); additionalEdgeFilter = tmpFilter; }

Target:
protected void fillEdgesToUsingFilter(EdgeFilter edgeFilter) { additionalEdgeFilter = edgeFilter; finishedTo = !fillEdgesTo(); additionalEdgeFilter = null; }
Source:
public int slotForBlockId(int partitionId, String streamName) { int offset = m_slotManager.slotForBlockId(partitionId, streamName); assert(offset != -1); return offset; }

Target:
public int slotForBlockId(int partitionId, String streamName) { int offset = m_slotMapper.slotForBlockId(partitionId, streamName); assert(offset != -1); return offset; }
Source:
public DataStore buildDataStore(EntityManagerFactory entityManagerFactory, QueryEngine queryEngine, ObjectProvider<ElideDynamicEntityCompiler> dynamicCompiler, ElideConfigProperties settings) throws ClassNotFoundException { AggregationDataStore aggregationDataStore = null; JpaDataStore.JpaTransactionCancel jpaTransactionCancel = null; if (isDynamicConfigEnabled(settings)) { ElideDynamicEntityCompiler compiler = dynamicCompiler.getIfAvailable(); Set<Class<?>> annotatedClass = compiler.findAnnotatedClasses(FromTable.class); annotatedClass.addAll(compiler.findAnnotatedClasses(FromSubquery.class)); aggregationDataStore = new AggregationDataStore( () -> { return entityManagerFactory.createEntityManager(); }, queryEngine, annotatedClass, (entityManager -> { entityManager.unwrap(Session.class).cancelQuery();})); } else { aggregationDataStore = new AggregationDataStore( () -> { return entityManagerFactory.createEntityManager(); }, queryEngine, (entityManager -> { entityManager.unwrap(Session.class).cancelQuery();})); } JpaDataStore jpaDataStore = new JpaDataStore( () -> { return entityManagerFactory.createEntityManager(); }, (em -> { return new NonJtaTransaction(em, em.unwrap(Session.class).cancelQuery()); }), (entityManager -> { entityManager.unwrap(Session.class).cancelQuery();})); return new MultiplexManager(jpaDataStore, queryEngine.getMetaDataStore(), aggregationDataStore); }

Target:
public DataStore buildDataStore(EntityManagerFactory entityManagerFactory, QueryEngine queryEngine, ObjectProvider<ElideDynamicEntityCompiler> dynamicCompiler, ElideConfigProperties settings) throws ClassNotFoundException { AggregationDataStore.AggregationDataStoreBuilder aggregationDataStoreBuilder = AggregationDataStore.builder() .queryEngine(queryEngine); if (isDynamicConfigEnabled(settings)) { ElideDynamicEntityCompiler compiler = dynamicCompiler.getIfAvailable(); Set<Class<?>> annotatedClass = compiler.findAnnotatedClasses(FromTable.class); annotatedClass.addAll(compiler.findAnnotatedClasses(FromSubquery.class)); aggregationDataStoreBuilder.dynamicCompiledClasses(annotatedClass); } AggregationDataStore aggregationDataStore = aggregationDataStoreBuilder.build(); JpaDataStore jpaDataStore = new JpaDataStore( () -> { return entityManagerFactory.createEntityManager(); }, (em) -> { return new NonJtaTransaction(em, txCancel); }); return new MultiplexManager(jpaDataStore, queryEngine.getMetaDataStore(), aggregationDataStore); }
Source:
public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); return new TimeWindowedCogroupedKStreamImpl<>(windows, builder, sourceNodes, name, keySerde, null, aggregateBuilder, streamsGraphNode, groupPatterns); }

Target:
public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); return new TimeWindowedCogroupedKStreamImpl<>( windows, builder, sourceNodes, name, aggregateBuilder, streamsGraphNode, groupPatterns); }
Source:
protected Vector<ChangeBasedEvent> getEventsFromDateRange(Date lowerDate) throws IOException { GerritServer server = PluginImpl.getInstance().getServer(serverName); IGerritHudsonTriggerConfig config = server.getConfig(); String events = getEventsFromEventsLogPlugin(config, buildEventsLogURL(config, lowerDate)); return createEventsFromString(events); }

Target:
protected List<GerritTriggeredEvent> getEventsFromDateRange(Date lowerDate) throws IOException { GerritServer server = PluginImpl.getServer_(serverName); if (server == null) { logger.error("Server for could not be found.", serverName); return Collections.synchronizedList(new ArrayList<GerritTriggeredEvent>()); } IGerritHudsonTriggerConfig config = server.getConfig(); String events = getEventsFromEventsLogPlugin(config, buildEventsLogURL(config, lowerDate)); return createEventsFromString(events); }
Source:
public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); }

Target:
public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); Assert.assertTrue(clusterVerifier.verifyByPolling()); }
Source:
public boolean equals(Object other) { if (other == null || !(other instanceof VdcParameter)) { return false; } return getGuid().equals(((VdcParameter) other).getGuid()); }

Target:
public boolean equals(Object other) { if (other == null || getClass() != other.getClass()) { return false; } return uuid.equals(((VdcParameter) other).uuid); }
Source:
private void handleSuccess() { LOG.info("Unlock of '{}' succeeded.", vault.getDisplayableName()); if (savePassword.get()) { savePasswordToSystemkeychain(); } switch (vault.getVaultSettings().actionAfterUnlock().get()) { case ASK -> Platform.runLater(() -> { window.setScene(successScene.get()); window.show(); }); case REVEAL -> { Platform.runLater(() -> { window.setScene(unlockScene.get()); window.close(); }); vaultService.reveal(vault); } case IGNORE -> { Platform.runLater(() -> { window.setScene(unlockScene.get()); window.close(); }); } } }

Target:
private void handleSuccess() { LOG.info("Unlock of '{}' succeeded.", vault.getDisplayableName()); if (savePassword.get()) { savePasswordToSystemkeychain(); } switch (vault.getVaultSettings().actionAfterUnlock().get()) { case ASK -> Platform.runLater(() -> { window.setScene(successScene.get()); window.show(); }); case REVEAL -> { Platform.runLater(window::close); vaultService.reveal(vault); } case IGNORE -> Platform.runLater(window::close); } }
Source:
public void setup(TestContext textConTx) { testContext = textConTx; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager( hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config.setName(basename); MutableConfiguration a; cacheManager.createCache(basename, config); }

Target:
public void setup(TestContext textConTx) { testContext = textConTx; targetInstance = testContext.getTargetInstance(); basename = testContext.getTestId(); if (TestUtils.isMemberNode(targetInstance)) { HazelcastServerCachingProvider hcp = new HazelcastServerCachingProvider(); cacheManager = new HazelcastServerCacheManager(hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } else { HazelcastClientCachingProvider hcp = new HazelcastClientCachingProvider(); cacheManager = new HazelcastClientCacheManager( hcp, targetInstance, hcp.getDefaultURI(), hcp.getDefaultClassLoader(), null); } config.setName(basename); cacheManager.createCache(basename, config); }
Source:
void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { getBytes(index, out, length); }

Target:
void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { UnsafeByteBufUtil.getBytes(this, addr(index), index, out, length); }
Source:
public synchronized void changeChannelEventLoopGroup(EventLoopGroup newGroup, Runnable callback) { if (newGroup.equals(channel.eventLoop())) { return; } channel.deregister().addListener((ChannelFutureListener) future -> { synchronized (channel) { if (!channel.isRegistered()) { newGroup.register(channel).sync(); } } callback.run(); }); }

Target:
public synchronized void changeChannelEventLoopGroup(EventLoopGroup newGroup, Runnable callback) { if (newGroup.equals(channel.eventLoop())) { callback.run(); return; } channel.deregister().addListener((ChannelFutureListener) future -> { synchronized (channel) { if (!channel.isRegistered()) { try { newGroup.register(channel).sync(); } catch (Exception e) { logger.warn("Unable to register new EventLoopGroup: {}", e.getMessage()); return; } } } callback.run(); }); }
Source:
public void shouldThrowExceptionIfTypeMismatchesInQueryForObject() { session.queryForObject(Restaurant.class, "MATCH (n:User) return count(n)", emptyMap()); }

Target:
public void shouldThrowExceptionIfTypeMismatchesInQueryForObject() { assertThatExceptionOfType(MappingException.class) .isThrownBy(() -> session.queryForObject(Restaurant.class, "MATCH (n:User) return count(n)", emptyMap())) .withMessage("Cannot map java.lang.Long to %s. This can be caused by missing registration of %1$s.", Restaurant.class.getName()); }
Source:
private ObjectStream getPrologRules() throws IOException{ Repository git = gitMgr.openRepository(getProject().getNameKey()); try { ObjectId config = getConfig().getRevision(); ObjectId rules = git.resolve(config.getName() + ":rules.pl"); if (rules == null) { return null; } ObjectLoader ldr = git.open(rules); if (ldr.getType() != Constants.OBJ_BLOB) { return null; } return ldr.openStream(); } finally { git.close(); } }

Target:
private String getPrologRules() throws RepositoryNotFoundException { Repository git = gitMgr.openRepository(getProject().getNameKey()); ProjectConfig config = getConfig(); if (config == null) { return null; } return config.getPrologRules(); }
Source:
public static void validateConfiguration(Configuration conf) throws IOException { ConfigurationUtil.getMandatoryConfig(conf, REQUIRED_KEYS); getJobProjectId(conf); getTableSchema(conf); getFileFormat(conf); getFileOutputFormat(conf); getGcsOutputPath(conf); }

Target:
public static void validateConfiguration(Configuration conf) throws IOException { ConfigurationUtil.getMandatoryConfig(conf, REQUIRED_KEYS); getProjectId(conf); getJobProjectId(conf); getTableSchema(conf); getFileFormat(conf); getFileOutputFormat(conf); getGcsOutputPath(conf); }
Source:
public GraphiteMetrics readMetrics(String... metrics) { try { GraphiteMetrics response = new GraphiteMetrics(); queryGraphite(metrics).stream().forEach(metric -> response.addMetricValue(metric.getTarget(), getFirstValue(metric))); return response; } catch (GraphiteConnectionException exception) { logger.warn("Unable to read from Graphite", exception.getMessage()); return GraphiteMetrics.unavailable(metrics); } }

Target:
public GraphiteMetrics readMetrics(String... metrics) { try { GraphiteMetrics response = new GraphiteMetrics(); queryGraphite(metrics).stream().forEach(metric -> response.addMetricValue(metric.getTarget(), getFirstValue(metric))); return response; } catch (Exception exception) { logger.warn("Unable to read from Graphite. {}", getRootCause(exception).getMessage()); return GraphiteMetrics.unavailable(metrics); } }
Source:
protected void done() { List<BlackboardArtifact> listOfArtifacts = new ArrayList<>(); if (!isCancelled()) { try { listOfArtifacts.addAll(get()); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for artifact type: " + artifactType.getDisplayName() + " and domain: " + domain, ex); } } DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.ArtifactListRetrievedEvent(artifactType, listOfArtifacts)); }

Target:
protected void done() { List<BlackboardArtifact> listOfArtifacts = new ArrayList<>(); if (!isCancelled()) { try { listOfArtifacts.addAll(get()); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for artifact type: " + artifactType.getDisplayName() + " and domain: " + domain, ex); } catch (CancellationException ignored) { } } DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.ArtifactSearchResultEvent(artifactType, listOfArtifacts)); }
Source:
public void testGetDDMFromLocationLat() { String ddm = UIUtils.getDDMFromLocation(getTargetContext(),24.15346, "lat"); assertEquals("N 24° 9.208", ddm); }

Target:
public void testGetDDMFromLocationLat() { String ddm = UIUtils.getDDMFromLocation(getTargetContext(),24.15346, "lat"); assertEquals("N\t\u200724° 09.208", ddm); }
Source:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (int i = 0; i < location_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, location_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }

Target:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < location_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, location_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }
Source:
private PerfData test(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = toCharArray(a); CharArray bc = toCharArray(b); long millis = System.currentTimeMillis(); MyersDiff myersDiff = new MyersDiff(ac, bc); millis = System.currentTimeMillis() - millis; ret.t = millis; ret.N = (ac.size() + bc.size()); ret.D = myersDiff.getEdits().size(); return (ret); }

Target:
private PerfData test(int characters) { PerfData ret = new PerfData(); String a = DiffTestDataGenerator.generateSequence(characters, 971, 3); String b = DiffTestDataGenerator.generateSequence(characters, 1621, 5); CharArray ac = new CharArray(a); CharArray bc = new CharArray(b); MyersDiff myersDiff = null; int cpuTimeChanges = 0; long lastReadout = 0; long interimTime = 0; int repetitions = 0; stopwatch.start(); while (cpuTimeChanges < minCPUTimerTicks && interimTime < longTaskBoundary) { myersDiff = new MyersDiff(ac, bc); repetitions++; interimTime = stopwatch.readout(); if (interimTime != lastReadout) { cpuTimeChanges++; lastReadout = interimTime; } } ret.runningTime = stopwatch.stop() / repetitions; ret.N = (ac.size() + bc.size()); ret.D = myersDiff.getEdits().size(); return ret; }
Source:
public static void addBiome(BiomeType type, BiomeEntry entry) { if (!isModded) isModded = true; getListOfType(type).add(entry); }

Target:
public static void addBiome(BiomeType type, BiomeEntry entry) { isModded = true; int idx = type.ordinal(); List<BiomeEntry> list = idx > biomes.length ? null : biomes[idx]; if (list != null) list.add(entry); }
Source:
public RqLengthAware(final Request req) { super( new RqOf( req::head, () -> RqLengthAware.cap(req) ) ); }

Target:
public RqLengthAware(final Request req) { super(new RequestOf(req::head, () -> RqLengthAware.cap(req))); }
Source:
public void grabEncodersFromRegistry(EncoderRegistry encoderRegistry, EncodingClasses encodingClasses) { this.keyEncoder = encoderRegistry.getEncoder(encodingClasses.getKeyEncoderClass()); this.valueEncoder = encoderRegistry.getEncoder(encodingClasses.getValueEncoderClass()); this.keyWrapper = encoderRegistry.getWrapper(encodingClasses.getKeyWrapperClass()); this.valueWrapper = encoderRegistry.getWrapper(encodingClasses.getValueWrapperClass()); }

Target:
public static CacheEncoders grabEncodersFromRegistry(EncoderRegistry encoderRegistry, EncodingClasses encodingClasses) { CacheEncoders cacheEncoders = new CacheEncoders(encoderRegistry.getEncoder(encodingClasses.getKeyEncoderClass()), encoderRegistry.getWrapper(encodingClasses.getKeyWrapperClass()), encoderRegistry.getEncoder(encodingClasses.getValueEncoderClass()), encoderRegistry.getWrapper(encodingClasses.getValueWrapperClass()) ); return cacheEncoders; }
Source:
public void subscribe(PropertyChangeListener listener) { if (subscribers == null) { subscribers = Lists.newArrayList(); } subscribers.add(listener); }

Target:
public boolean subscribe(PropertyChangeListener listener) { if (subscribers == null) { subscribers = Sets.newHashSet(); } if (listener == null) { LOGGER.warn(MessageFormat.format(this.warningFormatString, "A null subscriber cannot be added")); return false; } if (subscribers.contains(listener)) { LOGGER.warn(MessageFormat.format(this.warningFormatString, "The listener has already been subscribed")); return false; } subscribers.add(listener); return true; }
Source:
DistributedMember getOneMemberForRegion(InternalCache cache, String regionName) { String regionNameWithSeparator = regionName; if (!regionName.startsWith(SEPARATOR)) { regionNameWithSeparator = SEPARATOR + regionName; } return RebalanceOperationPerformer.getAssociatedMembers(regionNameWithSeparator, cache); }

Target:
private DistributedMember getOneMemberForRegion(InternalCache cache, String regionName) { String regionNameWithSeparator = regionName; if (!regionName.startsWith(SEPARATOR)) { regionNameWithSeparator = SEPARATOR + regionName; } return RebalanceOperationPerformer.getAssociatedMembers(regionNameWithSeparator, cache); }
Source:
public void updateAccountDetailsByUsername(User userToUpdate) { UserEntry user = findByUserName(userToUpdate.getUsername()); if (user == null) { throw new UsernameNotFoundException(userToUpdate.getUsername()); } if (!StringUtils.isBlank(userToUpdate.getPassword())) { user.setPassword(userToUpdate.getPassword()); } if (StringUtils.isNotBlank(userToUpdate.getSecurityTokenKey())) { user.setSecurityTokenKey(userToUpdate.getSecurityTokenKey()); } save(user); }

Target:
public void updateAccountDetailsByUsername(User userToUpdate) { UserEntry user = findByUsername(userToUpdate.getUsername()); if (user == null) { throw new UsernameNotFoundException(userToUpdate.getUsername()); } if (!StringUtils.isBlank(userToUpdate.getPassword())) { user.setPassword(userToUpdate.getPassword()); } if (StringUtils.isNotBlank(userToUpdate.getSecurityTokenKey())) { user.setSecurityTokenKey(userToUpdate.getSecurityTokenKey()); } save(user); }
Source:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); lagComputingConsumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Throwable e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); metricEmittingExec.scheduleAtFixedRate( computeAndEmitLag(taskClient), ioConfig.getStartDelay().getMillis() + 10000, 60 * 1000, TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], first run in [%s], with spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); } catch (Exception e) { if (consumer != null) { consumer.close(); } if (lagComputingConsumer != null) { lagComputingConsumer.close(); } log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } } }

Target:
public void start() { synchronized (stateChangeLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); try { consumer = getKafkaConsumer(); lagComputingConsumer = getKafkaConsumer(); exec.submit( new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { final Notice notice = notices.take(); try { notice.handle(); } catch (Throwable e) { log.makeAlert(e, "KafkaSupervisor[%s] failed to handle notice", dataSource) .addData("noticeClass", notice.getClass().getSimpleName()) .emit(); } } } catch (InterruptedException e) { log.info("KafkaSupervisor[%s] interrupted, exiting", dataSource); } } } ); firstRunTime = DateTime.now().plus(ioConfig.getStartDelay()); scheduledExec.scheduleAtFixedRate( buildRunTask(), ioConfig.getStartDelay().getMillis(), Math.max(ioConfig.getPeriod().getMillis(), MAX_RUN_FREQUENCY_MILLIS), TimeUnit.MILLISECONDS ); metricEmittingExec.scheduleAtFixedRate( computeAndEmitLag(taskClient), ioConfig.getStartDelay().getMillis() + 10000, Math.max(monitorSchedulerConfig.getEmitterPeriod().getMillis(), 60 * 1000), TimeUnit.MILLISECONDS ); started = true; log.info( "Started KafkaSupervisor[%s], first run in [%s], with spec: [%s]", dataSource, ioConfig.getStartDelay(), spec.toString() ); } catch (Exception e) { if (consumer != null) { consumer.close(); } if (lagComputingConsumer != null) { lagComputingConsumer.close(); } log.makeAlert(e, "Exception starting KafkaSupervisor[%s]", dataSource) .emit(); throw Throwables.propagate(e); } } }
Source:
public Long evaluate(TransactionContext txnCtx, Input<Object>... args) { Object fst = args[0].value(); Object snd = args[1].value(); if (fst == null || snd == null) { return null; } final Long timestamp; final Period period; if (fst instanceof Long && snd instanceof Period) { timestamp = (Long) args[0].value(); period = (Period) args[1].value(); } else { timestamp = (Long) args[1].value(); period = (Period) args[0].value(); } return operation.apply(new DateTime(timestamp, DateTimeZone.UTC), period).toInstant().getMillis(); }

Target:
public Long evaluate(TransactionContext txnCtx, Input<Object>... args) { final Long timestamp = (Long) args[timestampIdx].value(); final Period period = (Period) args[periodIdx].value(); if (period == null || timestamp == null) { return null; } return operation.apply(new DateTime(timestamp, DateTimeZone.UTC), period).toInstant().getMillis(); }
Source:
public static boolean isDynamicFilter(Expression expression) { if (!(expression instanceof ComparisonExpression)) { return false; } ComparisonExpression comparison = (ComparisonExpression) expression; checkState(!(comparison.getLeft() instanceof DeferredSymbolReference && comparison.getRight() instanceof DeferredSymbolReference), "Dynamic filter cannot have DeferredSymbolReferences"); return comparison.getLeft() instanceof DeferredSymbolReference || comparison.getRight() instanceof DeferredSymbolReference; }

Target:
public static boolean isDynamicFilter(Expression expression) { return expression instanceof DynamicFilterExpression; }