auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public IStatus run(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, fTraceBoundsToUpdate.size()); TmfTraceElement tElement = null; while <START> (fTraceBoundsToUpdate.isEmpty()) { <END> tElement = fTraceBoundsToUpdate.remove(); subMonitor.setTaskName(getName()); if (subMonitor.isCanceled()) { return Status.CANCEL_STATUS; } ITmfTimestamp start = tElement.getStartTime(); ITmfTimestamp end = tElement.getEndTime(); if (start != null && end != null) { subMonitor.worked(1); continue; } IFolder folder = tElement.getTraceSupplementaryFolder(tElement.getSupplementaryFolderPath()); tElement.refreshSupplementaryFolder(); File f = folder.getFile(BOUNDS_FILE_NAME).getLocation().toFile(); tryReadBoundsFile(tElement, f); start = tElement.getStartTime(); end = tElement.getEndTime(); if (start == null || end == null) { extractBoundsFromTrace(tElement); tryWriteBoundsFile(subMonitor.newChild(1), tElement, folder, f); } else { subMonitor.worked(1); } } return Status.OK_STATUS; }</code><technical_language>add</technical_language>

Target:
public IStatus run(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, fTraceBoundsToUpdate.size()); TmfTraceElement tElement = null; while (!fTraceBoundsToUpdate.isEmpty()) { tElement = fTraceBoundsToUpdate.remove(); subMonitor.setTaskName(getName()); if (subMonitor.isCanceled()) { return Status.CANCEL_STATUS; } ITmfTimestamp start = tElement.getStartTime(); ITmfTimestamp end = tElement.getEndTime(); if (start != null && end != null) { subMonitor.worked(1); continue; } IFolder folder = tElement.getTraceSupplementaryFolder(tElement.getSupplementaryFolderPath()); tElement.refreshSupplementaryFolder(); File f = folder.getFile(BOUNDS_FILE_NAME).getLocation().toFile(); tryReadBoundsFile(tElement, f); start = tElement.getStartTime(); end = tElement.getEndTime(); if (start == null || end == null) { extractBoundsFromTrace(tElement); tryWriteBoundsFile(subMonitor.newChild(1), tElement, folder, f); } else { subMonitor.worked(1); } } return Status.OK_STATUS; }
Source:
<code>public void inflateSubmissionDate() { mfDatePicker = MFDatePicker.newInsance(this); tvSubmissionDate.setText(MFDatePicker.getDatePickedAsString()); setSubmissionDate(); <START> tvSubmissionDate.setOnClickListener(new View.OnClickListener() { <END> @Override public void onClick(View view) { mfDatePicker.show(getActivity().getSupportFragmentManager(), FragmentConstants .DFRAG_DATE_PICKER); } }); }</code><technical_language>Butterknife annonation for onClick</technical_language>

Target:
public void inflateSubmissionDate() { mfDatePicker = MFDatePicker.newInsance(this); tvSubmissionDate.setText(MFDatePicker.getDatePickedAsString()); setSubmissionDate(); }
Source:
<code><START> public BatchSelectTableSink(TableSchema tableSchema) { <END> this.tableSchema = SelectTableSinkSchemaConverter.convertTimeAttributeToRegularTimestamp( SelectTableSinkSchemaConverter.changeDefaultConversionClass(tableSchema)); TypeSerializer<Row> typeSerializer = (TypeSerializer<Row>) TypeInfoDataTypeConverter .fromDataTypeToTypeInfo(this.tableSchema.toRowDataType()) .createSerializer(new ExecutionConfig()); String accumulatorName = "tableResultCollect_" + UUID.randomUUID(); this.factory = new CollectSinkOperatorFactory<>(typeSerializer, accumulatorName); CollectSinkOperator<Row> operator = (CollectSinkOperator<Row>) factory.getOperator(); this.iterator = new CollectResultIterator<>(operator.getOperatorIdFuture(), typeSerializer, accumulatorName); }</code><technical_language>extract code of BatchSelectTableSink StreamSelectTableSink a base class (SelectTableSinkBase)</technical_language>

Target:
public BatchSelectTableSink(TableSchema tableSchema) { super(tableSchema); }
Source:
<code><START> public void registerJar(final URL url) { <END> }</code><technical_language>throw a RuntimeException if a method is supported</technical_language>

Target:
public void registerJar(final URL url) { throw new RuntimeException("Functionality not supported in this engine"); }
Source:
<code>public void testCreatePayload() { Injector injector = Guice.createInjector(new GsonModule()); CreateVolumeRequestBinder binder = injector.getInstance(CreateVolumeRequestBinder.class); Volume.Request.CreatePayload payload = Volume.Request.creatingBuilder() .dataCenterId("datacenter-id") .name("jclouds-volume") .size(3) <START> .type("HDD") <END> .licenceType(LicenceType.LINUX) .build(); String actual = binder.createPayload(payload); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), actual ); assertEquals(request.getEndpoint().getPath(), "/rest/datacenters/datacenter-id/volumes"); assertNotNull(actual, "Binder returned null payload"); Json json = injector.getInstance(Json.class); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("size", 3); properties.put("licenceType", "LINUX"); properties.put("type", "HDD"); properties.put("name", "jclouds-volume"); HashMap<String, Object> expectedPayload = new HashMap<String, Object>(); expectedPayload.put("properties", properties); assertEquals(actual, json.toJson(expectedPayload)); }</code><technical_language>enum work here, users a constrained set of options use</technical_language>

Target:
public void testCreatePayload() { CreateVolumeRequestBinder binder = injector.getInstance(CreateVolumeRequestBinder.class); Volume.Request.CreatePayload payload = Volume.Request.creatingBuilder() .dataCenterId("datacenter-id") .name("jclouds-volume") .size(3) .type(VolumeType.HDD) .licenceType(LicenceType.LINUX) .build(); String actual = binder.createPayload(payload); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), actual ); assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/volumes"); assertNotNull(actual, "Binder returned null payload"); Json json = injector.getInstance(Json.class); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("size", 3); properties.put("licenceType", "LINUX"); properties.put("type", "HDD"); properties.put("name", "jclouds-volume"); HashMap<String, Object> expectedPayload = new HashMap<String, Object>(); expectedPayload.put("properties", properties); assertEquals(actual, json.toJson(expectedPayload)); }
Source:
<code>protected void setLeader(boolean isLeader) { if (isLeader && leader.compareAndSet(false, isLeader)) { LOGGER.info("Leadership taken (map={}, key={}, val={})", lockMapName, lockKey, lockValue); startAllStoppedConsumers(); } else { <START> if (!leader.getAndSet(isLeader) && isLeader) { <END> LOGGER.info("Leadership lost (map={}, key={} val={})", lockMapName, lockKey, lockValue); } } }</code><technical_language>review this condition? I log is printed correctly. If I understand correctly, leader.getAndSet(isLeader) && !isLeader. leader true set false</technical_language>

Target:
protected void setLeader(boolean isLeader) { if (isLeader && leader.compareAndSet(false, isLeader)) { LOGGER.info("Leadership taken (map={}, key={}, val={})", lockMapName, lockKey, lockValue); startAllStoppedConsumers(); } else if (!isLeader && leader.getAndSet(isLeader)) { LOGGER.info("Leadership lost (map={}, key={} val={})", lockMapName, lockKey, lockValue); } if (!isLeader && this.route != null) { stopConsumer(route); } }
Source:
<code>public void copyLeftToRight(Diff target, Monitor monitor) { if (target.getState() != DifferenceState.UNRESOLVED) { return; } long start = System.currentTimeMillis(); target.setState(DifferenceState.MERGED); final Set<Diff> dependencies = getDirectMergeDependencies(target, false); boolean requiresMerging = requiresMerging(target, false); for (Diff mergeMe : dependencies) { mergeDiff(mergeMe, false, monitor); } for (Diff transitiveMerge : getDirectResultingMerges(target, false)) { transitiveMerge.setState(DifferenceState.MERGED); } if (requiresMerging) { if (target.getSource() == DifferenceSource.LEFT) { accept(target, false); } else { reject(target, false); } } if (isHandleSubDiffs()) { Set<Diff> subDiffs = Sets.newLinkedHashSet(ComparisonUtil.getDirectSubDiffs(true).apply(target)); for (Diff subDiff : subDiffs) { mergeDiff(subDiff, false, monitor); } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyLeftToRight(Diff, Monitor) - diff " + target.hashCode() + " merged in " <START> + duration + "s"); END> } }</code><technical_language>ms</technical_language>

Target:
public void copyLeftToRight(Diff target, Monitor monitor) { if (target.getState() != DifferenceState.UNRESOLVED) { return; } long start = System.currentTimeMillis(); target.setState(DifferenceState.MERGED); final Set<Diff> dependencies = getDirectMergeDependencies(target, false); boolean requiresMerging = requiresMerging(target, false); for (Diff mergeMe : dependencies) { mergeDiff(mergeMe, false, monitor); } for (Diff transitiveMerge : getDirectResultingMerges(target, false)) { transitiveMerge.setState(DifferenceState.MERGED); } if (requiresMerging) { if (target.getSource() == DifferenceSource.LEFT) { accept(target, false); } else { reject(target, false); } } if (isHandleSubDiffs()) { Set<Diff> subDiffs = Sets.newLinkedHashSet(ComparisonUtil.getDirectSubDiffs(true).apply(target)); for (Diff subDiff : subDiffs) { mergeDiff(subDiff, false, monitor); } } if (LOGGER.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; LOGGER.debug("copyLeftToRight(Diff, Monitor) - diff " + target.hashCode() + " merged in " + duration + "ms"); } }
Source:
<code>public InputSplit[] getSplits(final JobConf conf, int ignored) throws IOException { final String domainName = DomainBuilderProperties.getDomainName(conf); RunWithCoordinator.run(DomainBuilderProperties.getConfigurator(conf), new RunnableWithCoordinator() { @Override public void run(Coordinator coordinator) throws IOException { domain = DomainBuilderProperties.getDomain(coordinator, domainName); domainVersion = domain.getVersion(DomainBuilderProperties.getVersionNumber(domainName, conf)); } }); final int domainNumParts = domain.getNumParts(); final StorageEngine storageEngine = domain.getStorageEngine(); final InputSplit[] splits = new InputSplit[domainNumParts]; for (int partition = 0; partition < domainNumParts; ++partition) { Compactor compactor = storageEngine.getCompactor(null, partition); List<String> locations = new ArrayList<String>(); if (compactor instanceof IncrementalPartitionUpdater) { IncrementalPartitionUpdater updater = (IncrementalPartitionUpdater) compactor; IncrementalUpdatePlan updatePlan = updater.computeUpdatePlan(domainVersion); List<String> paths = updater.getRemotePartitionFilePaths(updatePlan); LOG.info("Determining locations for partition " + partition + " using: " + paths); <START> locations = computeOptimalHosts(conf, paths); <END> } splits[partition] = new HadoopDomainCompactorInputSplit(domainName, partition, locations.toArray(new String[locations.size()])); } return splits; }</code><technical_language>log optimal hosts a safeguard</technical_language>

Target:
public InputSplit[] getSplits(final JobConf conf, int ignored) throws IOException { final String domainName = DomainBuilderProperties.getDomainName(conf); RunWithCoordinator.run(DomainBuilderProperties.getConfigurator(conf), new RunnableWithCoordinator() { @Override public void run(Coordinator coordinator) throws IOException { domain = DomainBuilderProperties.getDomain(coordinator, domainName); domainVersion = domain.getVersion(DomainBuilderProperties.getVersionNumber(domainName, conf)); } }); final int domainNumParts = domain.getNumParts(); final StorageEngine storageEngine = domain.getStorageEngine(); final InputSplit[] splits = new InputSplit[domainNumParts]; for (int partition = 0; partition < domainNumParts; ++partition) { Compactor compactor = storageEngine.getCompactor(null, partition); List<String> locations = new ArrayList<String>(); if (compactor instanceof IncrementalPartitionUpdater) { IncrementalPartitionUpdater updater = (IncrementalPartitionUpdater) compactor; IncrementalUpdatePlan updatePlan = updater.computeUpdatePlan(domainVersion); List<String> paths = updater.getRemotePartitionFilePaths(updatePlan); LOG.info("Determining locations for partition " + partition + " using: " + paths); locations = computeOptimalHosts(conf, paths); LOG.info("Determining locations for partition " + partition + " : " + locations); } splits[partition] = new HadoopDomainCompactorInputSplit(domainName, partition, locations.toArray(new String[locations.size()])); } return splits; }
Source:
<code>public void syncPodsToDirectory(File deployFolder, MultiStatus status, final IServerConsoleWriter consoleWriter) { new OCBinaryOperation() { @Override protected void runOCBinary(MultiStatus multiStatus) { boolean shouldSync = true; if (shouldSync) { for (IPod pod : service.getPods()) { try { <START> if (pod.getStatus() == "Running") { <END> syncPodToDirectory(pod, podPath, deployFolder, consoleWriter); } } catch (IOException | OpenShiftException e) { status.add(new Status(IStatus.ERROR, OpenShiftCoreActivator.PLUGIN_ID, e.getMessage())); } } } } }.run(status); }</code><technical_language>osjc provide enums for pod states. file issue</technical_language>

Target:
public void syncPodsToDirectory(File deployFolder, MultiStatus status, final IServerConsoleWriter consoleWriter) { new OCBinaryOperation() { @Override protected void runOCBinary(MultiStatus multiStatus) { boolean shouldSync = true; if (shouldSync) { for (IPod pod : service.getPods()) { try { if ("Running".equals(pod.getStatus())) { syncPodToDirectory(pod, podPath, deployFolder, consoleWriter); } } catch (IOException | OpenShiftException e) { status.add(new Status(IStatus.ERROR, OpenShiftCoreActivator.PLUGIN_ID, e.getMessage())); } } } } }.run(status); }
Source:
<code>public static void main(String[] args) { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); IMap<String, String> customers = hazelcastInstance.getMap("customers"); <START> LocalMapStats mapStatistics = customers.getLocalMapStats(); <END> Map<String, LocalIndexStats> indexStats = mapStatistics.getIndexStats(); LocalIndexStats nameIndexStats = indexStats.get("name"); System.out.println("average name index hit selectivity on this member = " + nameIndexStats.getAverageHitSelectivity()); }</code><technical_language>customers.addIndex("name", true); nameIndexStats.getAverageHitSelectivity() result NPE</technical_language>

Target:
public static void main(String[] args) { HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(); IMap<String, String> customers = hazelcastInstance.getMap("customers"); customers.addIndex("name", true); LocalMapStats mapStatistics = customers.getLocalMapStats(); Map<String, LocalIndexStats> indexStats = mapStatistics.getIndexStats(); LocalIndexStats nameIndexStats = indexStats.get("name"); System.out.println("average name index hit selectivity on this member = " + nameIndexStats.getAverageHitSelectivity()); }
Source:
<code>public InventoryDataProviders() { <START> super("inventory"); <END> }</code><technical_language>of string constants, I want refer o.s.c.util.Constants</technical_language>

Target:
public InventoryDataProviders() { super(Constants.Sponge.Entity.DataRegistration.INVENTORY); }
Source:
<code>public void newCanHttpPost() throws IOException, InterruptedException, NoSuchAlgorithmException { server.setResponse(NanoHTTPD.Method.POST, defaultMd5Post); Map<String, String> params = new HashMap<>(); params.put("firstK", "firstV"); params.put("secondK", "secondV"); String result = HttpUtil.httpPost(URL_STRING, params); byte[] hash = MessageDigest.getInstance("MD5").digest(HttpUtil.getQuery(params).getBytes()); String expected = Arrays.toString(hash); <START> assertEquals(result, expected); <END> }</code><technical_language>Expected param result</technical_language>

Target:
public void newCanHttpPost() throws IOException, InterruptedException, NoSuchAlgorithmException { server.setResponse(NanoHTTPD.Method.POST, defaultMd5Post); Map<String, String> params = new HashMap<>(); params.put("firstK", "firstV"); params.put("secondK", "secondV"); String result = HttpUtil.httpPost(URL_STRING, params); byte[] hash = MessageDigest.getInstance("MD5").digest(HttpUtil.getQuery(params).getBytes()); String expected = Arrays.toString(hash); assertEquals(expected, result); }
Source:
<code>public Reader(Configuration conf, List<Path> paths) throws IOException { <START> mMap = new TreeMap<K, V>(); <END> for (Path path : paths) { FileSystem fs = path.getFileSystem(conf); SequenceFile.Reader seqReader = new SequenceFile.Reader(fs, path, conf); try { Class<? extends K> keyClass = (Class<? extends K>) seqReader.getKeyClass(); Class<? extends V> valClass = (Class<? extends V>) seqReader.getValueClass(); K key = ReflectionUtils.newInstance(keyClass, conf); V val = ReflectionUtils.newInstance(valClass, conf); key = (K) seqReader.next(key); while (key != null) { val = (V) seqReader.getCurrentValue(val); if (!mMap.containsKey(key)) { mMap.put(key, val); } key = ReflectionUtils.newInstance(keyClass, conf); val = ReflectionUtils.newInstance(valClass, conf); key = (K) seqReader.next(key); } } finally { seqReader.close(); } } }</code><technical_language>need TreeMap here</technical_language>

Target:
public Reader(Configuration conf, List<Path> paths) throws IOException { mMap = new HashMap<K, V>(); for (Path path : paths) { FileSystem fs = path.getFileSystem(conf); SequenceFile.Reader seqReader = new SequenceFile.Reader(fs, path, conf); try { Class<? extends K> keyClass = (Class<? extends K>) seqReader.getKeyClass(); Class<? extends V> valClass = (Class<? extends V>) seqReader.getValueClass(); K key = ReflectionUtils.newInstance(keyClass, conf); V val = ReflectionUtils.newInstance(valClass, conf); key = (K) seqReader.next(key); while (key != null) { val = (V) seqReader.getCurrentValue(val); if (!mMap.containsKey(key)) { mMap.put(key, val); } key = ReflectionUtils.newInstance(keyClass, conf); val = ReflectionUtils.newInstance(valClass, conf); key = (K) seqReader.next(key); } } finally { seqReader.close(); } } }
Source:
<code>public ShowBubbleActor createBubbleActor() throws InterpretationException { String textToDisplay = text == null ? "" : text.interpretString(sprite); <START> if (textToDisplay.equals("")) { <END> return null; } return new ShowBubbleActor(textToDisplay, sprite, type); }</code><technical_language>this replaced textToDisplay.isEmpty()</technical_language>

Target:
public ShowBubbleActor createBubbleActor() throws InterpretationException { String textToDisplay = text == null ? "" : text.interpretString(sprite); if (textToDisplay.isEmpty()) { return null; } return new ShowBubbleActor(textToDisplay, sprite, type); }
Source:
<code>private void recordEvent(String msg, int evtType) { GridKernalContext ctx = cctx.kernalContext(); Collection<ClusterNode> srvNodes = ctx.cluster().get().forServers().nodes(); <START> ArrayList baselineNodes = new ArrayList(srvNodes.size()); <END> for (ClusterNode clN : srvNodes) baselineNodes.add(clN); ctx.getSystemExecutorService().execute(new Runnable() { @Override public void run() { if (ctx.event().isRecordable(evtType)) { ClusterActivationEvent evt = new ClusterActivationEvent(ctx.discovery().localNode(), msg, evtType, baselineNodes); ctx.event().record(evt); } } }); }</code><technical_language>new ArrayList(srvNodes)? List<ClusterNode></technical_language>

Target:
private void recordEvent(String msg, int evtType) { GridKernalContext ctx = cctx.kernalContext(); Collection<ClusterNode> srvNodes = ctx.cluster().get().forServers().nodes(); Collection<BaselineNode> baselineNodes = new ArrayList<>(srvNodes); ctx.getStripedExecutorService().execute(CLUSTER_ACTIVATION_EVT_STRIPE_ID, new Runnable() { @Override public void run() { if (ctx.event().isRecordable(evtType)) { ClusterActivationEvent evt = new ClusterActivationEvent(ctx.discovery().localNode(), msg, evtType, baselineNodes); ctx.event().record(evt); } } }); }
Source:
<code>public void testSomeCommits() throws CorruptObjectException, UnmergedPathException, IOException { Git git = new Git(db); git.commit().setMessage("initial commit").run(); git.commit().setMessage("second commit").setCommitter(committer).run(); git.commit().setMessage("third commit").setAuthor(author).run(); git.commit().setMessage("fourth commit").setAuthor(author) .setCommitter(committer).run(); String defaultCommitter = new PersonIdent(db).getName(); String expectedAuthors[] = new String[] { defaultCommitter, committer.getName(), author.getName(), author.getName() }; String expectedCommitters[] = new String[] { defaultCommitter, committer.getName(), defaultCommitter, committer.getName() }; <START> String expectedMessages[] = new String[] { "initial", "second", <END> "third", "fourth" }; int l = expectedAuthors.length - 1; for (RevCommit c : git.log().run()) { assertEquals(expectedAuthors[l], c.getAuthorIdent().getName()); assertEquals(expectedCommitters[l], c.getCommitterIdent().getName()); assertTrue(c.getFullMessage().startsWith(expectedMessages[l])); l--; } assertTrue(l==-1); }</code><technical_language>set this commits above, setMessage(expectedMessages[0]) point message</technical_language>

Target:
public void testSomeCommits() throws CorruptObjectException, UnmergedPathException, IOException { final Git git = new Git(db); git.commit().setMessage("initial commit").call(); git.commit().setMessage("second commit").setCommitter(committer).call(); git.commit().setMessage("third commit").setAuthor(author).call(); git.commit().setMessage("fourth commit").setAuthor(author) .setCommitter(committer).call(); final Iterable<RevCommit> commits = git.log().call(); final PersonIdent defaultCommitter = new PersonIdent(db); final PersonIdent expectedAuthors[] = new PersonIdent[] { defaultCommitter, committer, author, author }; final PersonIdent expectedCommitters[] = new PersonIdent[] { defaultCommitter, committer, defaultCommitter, committer }; final String expectedMessages[] = new String[] { "initial commit", "second commit", "third commit", "fourth commit" }; int l = expectedAuthors.length - 1; for (final RevCommit c : commits) { assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent() .getName()); assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent() .getName()); assertEquals(c.getFullMessage(), expectedMessages[l]); l--; } assertEquals(l, -1); }
Source:
<code>public void postOnCreateSnapshot(VdcReturnValueBase returnValue, GlusterVolumeSnapshotEntity snapshot) { GlusterVolumeSnapshotModel model = (GlusterVolumeSnapshotModel) getWindow(); <START> model.stopProgress(); <END> if (returnValue != null && returnValue.getSucceeded()) { setWindow(null); } }</code><technical_language>is progress started</technical_language>

Target:
public void postOnCreateSnapshot(VdcReturnValueBase returnValue, GlusterVolumeSnapshotEntity snapshot) { GlusterVolumeSnapshotModel model = (GlusterVolumeSnapshotModel) getWindow(); if (returnValue != null && returnValue.getSucceeded()) { setWindow(null); } }
Source:
<code>public void testDiscoverDeviceNoDevice() throws Exception { String id = "id"; byte[] deviceTimeoutByteArray = new byte[]{0x01}; long deviceTimeout = ByteUtils.byteArrayToLong(deviceTimeoutByteArray) * 100; PowerMockito.when(deviceMock.getParameter("NT")).thenReturn(deviceTimeoutByteArray); long start = System.currentTimeMillis(); RemoteXBeeDevice remote = nd.discoverDevice(id); long end = System.currentTimeMillis(); assertThat("The 'discoverDevice' should block for " + deviceTimeout + " ms", end - start > deviceTimeout, is(equalTo(true))); assertThat("The discovered device should be null", remote, is(equalTo(null))); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(SEND_NODE_DISCOVERY_COMMAND_METHOD, Mockito.anyString()); Mockito.verify(deviceMock, Mockito.times(1)).addPacketListener(packetListener); Mockito.verify(deviceMock, Mockito.times(1)).removePacketListener(packetListener); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(DISCOVER_DEVICES_API_METHOD, null, id); <START> Mockito.verify(networkMock, Mockito.never()).addRemoteDevices(Mockito.anyListOf(RemoteXBeeDevice.class)); <END> }</code><technical_language>Add line: java Mockito.verify(networkMock, Mockito.never()).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class));</technical_language>

Target:
public void testDiscoverDeviceNoDevice() throws Exception { String id = "id"; byte[] deviceTimeoutByteArray = new byte[]{0x01}; long deviceTimeout = ByteUtils.byteArrayToLong(deviceTimeoutByteArray) * 100; PowerMockito.when(deviceMock.getParameter("NT")).thenReturn(deviceTimeoutByteArray); long start = System.currentTimeMillis(); RemoteXBeeDevice remote = nd.discoverDevice(id); long end = System.currentTimeMillis(); assertThat("The 'discoverDevice' should block for " + deviceTimeout + " ms", end - start > deviceTimeout, is(equalTo(true))); assertThat("The discovered device should be null", remote, is(equalTo(null))); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(SEND_NODE_DISCOVERY_COMMAND_METHOD, Mockito.anyString()); Mockito.verify(deviceMock, Mockito.times(1)).addPacketListener(packetListener); Mockito.verify(deviceMock, Mockito.times(1)).removePacketListener(packetListener); PowerMockito.verifyPrivate(nd, Mockito.times(1)).invoke(DISCOVER_DEVICES_API_METHOD, null, id); Mockito.verify(networkMock, Mockito.never()).addRemoteDevices(Mockito.anyListOf(RemoteXBeeDevice.class)); Mockito.verify(networkMock, Mockito.never()).addRemoteDevice(Mockito.any(RemoteXBeeDevice.class)); }
Source:
<code>public static void mongoGetExperiment(final DB dbs, final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { final Request.Builder requestBuilder = Request.newBuilder(); requestBuilder.setSessionInfo(sessionInfo); requestBuilder.setRequestType(MessageType.DATA_REQUEST); final ItemRequest.Builder build = ItemRequest.newBuilder(); build.setQuery(ItemQuery.EXPERIMENT); final DBRef myDbRef = new DBRef(dbs, EXPERIMENT_COLLECTION, new ObjectId(problemId)); final DBObject corsor = myDbRef.fetch(); if (corsor == null) { throw new DatabaseAccessException("The student has not submitted anything for this problem"); } final String sketchId = "" + corsor.get(userId); LOG.info("SketchId: ", sketchId); if ("null".equals(sketchId)) { throw new DatabaseAccessException("The student has not submitted anything for this problem"); } build.addItemId(sketchId); final DataRequest.Builder data = DataRequest.newBuilder(); data.addItems(build); requestBuilder.setOtherData(data.build().toByteString()); try { internalConnections.send(requestBuilder.build(), null, SubmissionClientWebSocket.class); } catch (ConnectionException e) { <START> LOG.info("Exception: {}", e); <END> throw new DatabaseAccessException("Failed to send request to submission server for experiment", e); } }</code><technical_language>error</technical_language>

Target:
public static void mongoGetExperiment(final DB dbs, final String userId, final String problemId, final String sessionInfo, final MultiConnectionManager internalConnections) throws DatabaseAccessException { final Request.Builder requestBuilder = Request.newBuilder(); requestBuilder.setSessionInfo(sessionInfo); requestBuilder.setRequestType(MessageType.DATA_REQUEST); final ItemRequest.Builder build = ItemRequest.newBuilder(); build.setQuery(ItemQuery.EXPERIMENT); final DBRef myDbRef = new DBRef(dbs, EXPERIMENT_COLLECTION, new ObjectId(problemId)); final DBObject corsor = myDbRef.fetch(); if (corsor == null) { throw new DatabaseAccessException("The student has not submitted anything for this problem"); } final String sketchId = "" + corsor.get(userId); LOG.info("SketchId: ", sketchId); if ("null".equals(sketchId)) { throw new DatabaseAccessException("The student has not submitted anything for this problem"); } build.addItemId(sketchId); final DataRequest.Builder data = DataRequest.newBuilder(); data.addItems(build); requestBuilder.setOtherData(data.build().toByteString()); try { internalConnections.send(requestBuilder.build(), null, SubmissionClientWebSocket.class); } catch (ConnectionException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); throw new DatabaseAccessException("Failed to send request to submission server for experiment", e); } }
Source:
<code>public String toString() { <START> return String.format("<SchemaPair: %s, %s>", keySchema.toString(), valueSchema.toString()); <END> }</code><technical_language>varargs parameter of String.format(...) is of type Object for toString() called if non-null, a bit safer do in case key schema schema null: suggestion return String.format("<SchemaPair: %s, %s>", keySchema, valueSchema);</technical_language>

Target:
public String toString() { return String.format("<SchemaPair: %s, %s>", keySchema, valueSchema); }
Source:
<code>public void onDestroyView() { super.onDestroyView(); <START> SharedVariables.isAlertsFragmentAvailable = false; <END> tearDownBindings(); }</code><technical_language>do consider keeping isAlertsFragmentAvailable instance variable work</technical_language>

Target:
public void onDestroyView() { super.onDestroyView(); isAlertsFragmentAvailable = false; tearDownBindings(); }
Source:
<code>public void testDisablingCrossReferencerWhileReloadingResource() throws Exception { genericSetUp(); initSemanticResource(); Resource fragmentedResource = <START> editingDomain.getResourceSet().getResources().get(2); <END> boolean found = false; for (Adapter adapter : fragmentedResource.eAdapters()) { if (adapter instanceof LazyCrossReferencer) { found = true; break; } } assertTrue("The LazyCrossReferencer adapter is not set on fragmented resource", found); File fragFile = ResourcesPlugin.getWorkspace().getRoot().getProject(TEMPORARY_PROJECT_NAME).getFile(fragmentFileName).getLocation().toFile(); fragFile.setLastModified(System.currentTimeMillis()); ResourceSetSync resourceSetSync = ResourceSetSync.getResourceSetSync(editingDomain).get(); resourceSetSync.statusChanged(fragmentedResource, ResourceSetSync.ResourceStatus.SYNC, ResourceSetSync.ResourceStatus.EXTERNAL_CHANGED); for (Iterator<IStatus> warning = warnings.values().iterator(); warning.hasNext();) { IStatus status = warning.next(); if (status.getCode() == EMFTransactionStatusCodes.RELOAD_DURING_UNLOAD) { fail("Resource is being reloaded during its unload."); } } }</code><technical_language>Do another select resource? In case index change in future test fail. ((DAnalysisSessionEObject) session).getControlledResources()</technical_language>

Target:
public void testDisablingCrossReferencerWhileReloadingResource() throws Exception { genericSetUp(); initSemanticResource(); Resource fragmentedResource = ((DAnalysisSessionEObject) session).getControlledResources().get(0); assertNotNull(FRAGMENT_FILE_NAME + " should be part of session controlled resource", fragmentedResource); boolean found = false; for (Adapter adapter : fragmentedResource.eAdapters()) { if (adapter instanceof LazyCrossReferencer) { found = true; break; } } assertTrue("The LazyCrossReferencer adapter is not set on fragmented resource", found); File fragFile = ResourcesPlugin.getWorkspace().getRoot().getProject(TEMPORARY_PROJECT_NAME).getFile(FRAGMENT_FILE_NAME).getLocation().toFile(); fragFile.setLastModified(System.currentTimeMillis()); ResourceSetSync resourceSetSync = ResourceSetSync.getResourceSetSync(editingDomain).get(); resourceSetSync.statusChanged(fragmentedResource, ResourceSetSync.ResourceStatus.SYNC, ResourceSetSync.ResourceStatus.EXTERNAL_CHANGED); for (Iterator<IStatus> warning = warnings.values().iterator(); warning.hasNext();) { IStatus status = warning.next(); if (status.getCode() == EMFTransactionStatusCodes.RELOAD_DURING_UNLOAD) { fail("Resource is being reloaded during its unload."); } } }
Source:
<code>public RelDataType rowType() { synchronized (lock) { Preconditions.checkState(plannerResult != null, <START> "must be call after sql has been planned"); <END> return plannerResult.rowType(); } }</code><technical_language>"Must called" (grammar)</technical_language>

Target:
public RelDataType rowType() { synchronized (lock) { Preconditions.checkState(plannerResult != null, "must be called after sql has been planned"); return plannerResult.rowType(); } }
Source:
<code>public void addContents(@NonNull Container result) { result.add( new PrefilteredPrintedContent("running-builds.txt") { @Override protected void printTo(PrintWriter out, ContentFilter filter) { Optional.ofNullable(Jenkins.getInstanceOrNull()) .ifPresent(jenkins -> Arrays.stream(jenkins.getComputers()) .flatMap(computer -> computer.getAllExecutors().stream()) .collect(Collectors.toList()) .forEach(executor -> Optional.ofNullable(executor.getCurrentExecutable()) <START> .filter(executable -> executable.getParent() == executable.getParent().getOwnerTask()) <END> .ifPresent(executable -> out.println(ContentFilter.filter(filter, executable.toString()))) ) ); } }); }</code><technical_language>Is correct filtering asking if executable is present</technical_language>

Target:
public void addContents(@NonNull Container result) { result.add( new PrefilteredPrintedContent("running-builds.txt") { @Override protected void printTo(PrintWriter out, ContentFilter filter) { Arrays.stream(Jenkins.get().getComputers()) .flatMap(computer -> computer.getAllExecutors().stream()) .collect(Collectors.toList()) .forEach(executor -> Optional.ofNullable(executor.getCurrentExecutable()) .filter(executable -> executable.getParent() == executable.getParent().getOwnerTask()) .ifPresent(executable -> out.println(ContentFilter.filter(filter, executable.toString()))) ); } }); }
Source:
<code>public Object[] <START> getChildren() <END> { Object[] result = new Object[0]; if (root) { ITargetPlatformService service = (ITargetPlatformService) PlatformUI.getWorkbench().getService(ITargetPlatformService.class); ITargetDefinition td = null; try { td = service.getWorkspaceTargetHandle().getTargetDefinition(); } catch (CoreException e) { } if (td != null) { WorkbenchProxyObject wpoTargetDefinition = new WorkbenchProxyObject(td, null); wpoTargetDefinition.setValidated(true); result = new Object[] { ResourcesPlugin.getWorkspace().getRoot(), wpoTargetDefinition }; } else { result = new Object[] { ResourcesPlugin.getWorkspace().getRoot() }; } } else if (containedObject instanceof ZipFile) { List<Object> children = new ArrayList<Object>(); Enumeration<? extends ZipEntry> entries = ((ZipFile) containedObject).entries(); ZipEntry zipEntry; while (entries.hasMoreElements()) { zipEntry = entries.nextElement(); if (!zipEntry.isDirectory()) { children.add(new WorkbenchProxyObject(zipEntry, getLabel())); } } result = children.toArray(); } return result; }</code><technical_language>bad indentation check workspace save actions</technical_language>

Target:
public Object[] getChildren() { Object[] result = new Object[0]; if (root) { ITargetPlatformService service = (ITargetPlatformService) PlatformUI.getWorkbench().getService(ITargetPlatformService.class); ITargetDefinition td = null; try { td = service.getWorkspaceTargetHandle().getTargetDefinition(); } catch (CoreException e) { } if (td != null) { WorkbenchProxyObject wpoTargetDefinition = new WorkbenchProxyObject(td, null); wpoTargetDefinition.setChecked(true); result = new Object[] { ResourcesPlugin.getWorkspace().getRoot(), wpoTargetDefinition }; } else { result = new Object[] { ResourcesPlugin.getWorkspace().getRoot() }; } } else if (containedObject instanceof ZipFile) { List<Object> children = new ArrayList<Object>(); Enumeration<? extends ZipEntry> entries = ((ZipFile) containedObject).entries(); ZipEntry zipEntry; while (entries.hasMoreElements()) { zipEntry = entries.nextElement(); if (!zipEntry.isDirectory()) { children.add(new WorkbenchProxyObject(zipEntry, getLabel())); } } result = children.toArray(); } return result; }
Source:
<code>public BulkByScrollResponse updateByQuery(String index, String type, int batchSize, Script script, int numberOfSlices, QueryBuilder query) throws IOException { <START> UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(new SearchRequest()); <END> updateByQueryRequest.getSearchRequest() .indices(index) .types(type) .source() .size(batchSize) .query(query); updateByQueryRequest .setScript(script) .setSlices(numberOfSlices); return clientExt.updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT); }</code><technical_language>zero-arg constructor starts out unpopulated SearchRequest: <LINK_0></technical_language>

Target:
public BulkByScrollResponse updateByQuery(String index, String type, int batchSize, Script script, int numberOfSlices, QueryBuilder query) throws IOException { UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(index) .setDocTypes(type) .setBatchSize(batchSize) .setQuery(query) .setScript(script) .setSlices(numberOfSlices); return client.updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT); }
Source:
<code>private String getUrl(SearchCriteria searchCriteria) throws UnsupportedEncodingException { Map<String, String> params = new HashMap<>(); params.put("format", "json"); params.put("addressdetails", "1"); String filterBBOX = PropertyUtil.getOptional(PROPERTY_BBOX); if(filterBBOX != null) { params.put("bounded", "1"); params.put("viewbox", filterBBOX); } else { log.debug("Search BBOX not configured. Add property with key", PROPERTY_BBOX); } params.put("accept-language", searchCriteria.getLocale()); int maxResults = getMaxResults(searchCriteria.getMaxResults()); if (maxResults > 0) { params.put("limit", Integer.toString(maxResults)); } <START> params.put("q", URLEncoder.encode(searchCriteria.getSearchString(),"UTF-8")); <END> return IOHelper.constructUrl(serviceURL, params); }</code><technical_language>constructUrl encoding need do here</technical_language>

Target:
private String getUrl(SearchCriteria searchCriteria) throws UnsupportedEncodingException { Map<String, String> params = new HashMap<>(); params.put("format", "json"); params.put("addressdetails", "1"); String filterBBOX = PropertyUtil.getOptional(PROPERTY_BBOX); if(filterBBOX != null) { params.put("bounded", "1"); params.put("viewbox", filterBBOX); } else { log.debug("Search BBOX not configured. Add property with key", PROPERTY_BBOX); } params.put("accept-language", searchCriteria.getLocale()); int maxResults = getMaxResults(searchCriteria.getMaxResults()); if (maxResults > 0) { params.put("limit", Integer.toString(maxResults)); } params.put("q", searchCriteria.getSearchString()); return IOHelper.constructUrl(serviceURL, params); }
Source:
<code>public void testWriteAndReadBCF() throws IOException { <START> final File fakeVCFFile = VariantBaseTest.createTempFile("testWriteAndReadVCFBody.", ".bcf"); <END> Tribble.indexFile(fakeVCFFile).deleteOnExit(); metaData = new HashSet<VCFHeaderLine>(); additionalColumns = new HashSet<String>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY)) .build()) { writer.writeHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } VariantContextTestProvider.VariantContextContainer container = VariantContextTestProvider .readAllVCs(fakeVCFFile, new BCF2Codec()); int counter = 0; final Iterator<VariantContext> it = container.getVCs().iterator(); while (it.hasNext()) { it.next(); counter++; } Assert.assertEquals(counter, 2); }</code><technical_language>helpful call variables "fakeBCFFile" BCF. "bcfOutputFile"</technical_language>

Target:
public void testWriteAndReadBCF() throws IOException { final File bcfOutputFile = File.createTempFile("testWriteAndReadVCF.", ".bcf", tempDir); bcfOutputFile.deleteOnExit(); final VCFHeader header = createFakeHeader(); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(bcfOutputFile).setReferenceDictionary(header.getSequenceDictionary()) .unsetOption(Options.INDEX_ON_THE_FLY) .build()) { writer.writeHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } VariantContextTestProvider.VariantContextContainer container = VariantContextTestProvider .readAllVCs(bcfOutputFile, new BCF2Codec()); int counter = 0; final Iterator<VariantContext> it = container.getVCs().iterator(); while (it.hasNext()) { it.next(); counter++; } Assert.assertEquals(counter, 2); }
Source:
<code>public Subscription schedulePeriodically(final Action0 action, long initialDelay, long period, TimeUnit unit) { final long periodInNanos = unit.toNanos(period); final long firstNowNanos = TimeUnit.MILLISECONDS.toNanos(now()); final long firstStartInNanos = firstNowNanos + unit.toNanos(initialDelay); final MultipleAssignmentSubscription mas = new MultipleAssignmentSubscription(); final Action0 recursiveAction = new Action0() { long count; long lastNowNanos = firstNowNanos; long startInNanos = firstStartInNanos; @Override public void call() { if (!mas.isUnsubscribed()) { action.call(); long nextTick; long nowNanos = TimeUnit.MILLISECONDS.toNanos(now()); if (nowNanos + CLOCK_DRIFT_TOLERANCE_NANOS < lastNowNanos || nowNanos >= lastNowNanos + periodInNanos + CLOCK_DRIFT_TOLERANCE_NANOS) { nextTick = nowNanos + periodInNanos; <START> startInNanos -= (lastNowNanos - nowNanos) + periodInNanos; <END> ++count; } else { nextTick = startInNanos + (++count * periodInNanos); } lastNowNanos = nowNanos; long delay = nextTick - nowNanos; mas.set(schedule(this, delay, TimeUnit.NANOSECONDS)); } } }; MultipleAssignmentSubscription s = new MultipleAssignmentSubscription(); mas.set(s); s.set(schedule(recursiveAction, initialDelay, unit)); return mas; }</code><technical_language>I a problem if lastNowNanos - nowNanos > 2 * periodInNanos. schedule nextTick for right time rebased next nextTick result in scheduling action previous action. I suggest replacing lines 147 148 java startInNanos = nextTick - (periodInNanos * ++count);</technical_language>

Target:
public Subscription schedulePeriodically(final Action0 action, long initialDelay, long period, TimeUnit unit) { final long periodInNanos = unit.toNanos(period); final long firstNowNanos = TimeUnit.MILLISECONDS.toNanos(now()); final long firstStartInNanos = firstNowNanos + unit.toNanos(initialDelay); final MultipleAssignmentSubscription mas = new MultipleAssignmentSubscription(); final Action0 recursiveAction = new Action0() { long count; long lastNowNanos = firstNowNanos; long startInNanos = firstStartInNanos; @Override public void call() { if (!mas.isUnsubscribed()) { action.call(); long nextTick; long nowNanos = TimeUnit.MILLISECONDS.toNanos(now()); if (nowNanos + CLOCK_DRIFT_TOLERANCE_NANOS < lastNowNanos || nowNanos >= lastNowNanos + periodInNanos + CLOCK_DRIFT_TOLERANCE_NANOS) { nextTick = nowNanos + periodInNanos; startInNanos = nextTick - (periodInNanos * (++count)); } else { nextTick = startInNanos + (++count * periodInNanos); } lastNowNanos = nowNanos; long delay = nextTick - nowNanos; mas.set(schedule(this, delay, TimeUnit.NANOSECONDS)); } } }; MultipleAssignmentSubscription s = new MultipleAssignmentSubscription(); mas.set(s); s.set(schedule(recursiveAction, initialDelay, unit)); return mas; }
Source:
<code>public void queryWithNumericParameter_shouldReturnResults() { String projectId = spanner.getOptions().getProjectId(); DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId)); client.write( <START> ImmutableList.of( <END> Mutation.newInsertOrUpdateBuilder("SingerRevenues") .set("SingerId") .to(1L) .set("Revenue") .to(new BigDecimal("35000")) .build(), Mutation.newInsertOrUpdateBuilder("SingerRevenues") .set("SingerId") .to(6L) .set("Revenue") .to(new BigDecimal("104500")) .build(), Mutation.newInsertOrUpdateBuilder("SingerRevenues") .set("SingerId") .to(14L) .set("Revenue") .to(new BigDecimal("99999999999999999999999999999.99")) .build())); String out = runExample(() -> QueryWithNumericParameterSample.queryWithNumericParameter(client)); assertThat(out).contains("1 35000"); }</code><technical_language>table this entries previous test</technical_language>

Target:
public void queryWithNumericParameter_shouldReturnResults() { String projectId = spanner.getOptions().getProjectId(); DatabaseClient client = spanner.getDatabaseClient(DatabaseId.of(projectId, instanceId, databaseId)); client.write( ImmutableList.of( Mutation.newInsertOrUpdateBuilder("Venues") .set("VenueId") .to(4L) .set("Revenue") .to(new BigDecimal("35000")) .build(), Mutation.newInsertOrUpdateBuilder("Venues") .set("VenueId") .to(19L) .set("Revenue") .to(new BigDecimal("104500")) .build(), Mutation.newInsertOrUpdateBuilder("Venues") .set("VenueId") .to(42L) .set("Revenue") .to(new BigDecimal("99999999999999999999999999999.99")) .build())); String out = runExample(() -> QueryWithNumericParameterSample.queryWithNumericParameter(client)); assertThat(out).contains("4 35000"); }
Source:
<code>public boolean userIsBlocked() throws TooManyLoginAttemptsException { UserSecret userSecret = getSecret(); <START> if (userSecret.getFailedLoginAttempts() >= 3) <END> { if (userSecret.getLastFailedAuthentication() != null && (Instant.now().toEpochMilli() < userSecret.getLastFailedAuthentication().plus(Duration.ofSeconds(30)).toEpochMilli())) { throw new TooManyLoginAttemptsException( "You entered the wrong verification code 3 times, please wait 30 seconds before you try again"); } } return false; }</code><technical_language>private static final for magic numbers</technical_language>

Target:
public boolean userIsBlocked() throws TooManyLoginAttemptsException { UserSecret userSecret = getSecret(); if (userSecret.getFailedLoginAttempts() >= MAX_FAILED_LOGIN_ATTEMPTS) { if (userSecret.getLastFailedAuthentication() != null && (Instant.now().toEpochMilli() < userSecret.getLastFailedAuthentication() .plus(Duration.ofSeconds(BLOCKED_USER_INTERVAL)) .toEpochMilli())) { throw new TooManyLoginAttemptsException( format("You entered the wrong verification code %d times, please wait for %d seconds before you try again", MAX_FAILED_LOGIN_ATTEMPTS, BLOCKED_USER_INTERVAL)); } } return false; }