auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void onHandleIntent(Intent intent) { final Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { if (GoogleCloudMessaging. MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging. MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); } else if (GoogleCloudMessaging. MESSAGE_TYPE_MESSAGE.equals(messageType)) { for (int i=0; i<5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); sendNotification("Received: " + extras.toString()); Log.i(TAG, "Received: " + extras.toString()); Handler h = new Handler(Looper.getMainLooper()); final Context c = this.getApplicationContext(); <START> h.post(new Runnable() { <END> public void run() { Toast.makeText(c, extras.toString(), Toast.LENGTH_SHORT).show(); } }); } } GcmBroadcastReceiver.completeWakefulIntent(intent); }</code><technical_language>do need a Handler here? I call Toast.makeText(c, extras.toString(), Toast.LENGTH_SHORT).show(); instead of making a toast, do this: <LINK_0> Create a notification instead content title set "new donation: " + extras.get("message") include feeding icon icon</technical_language>

Target:
protected void onHandleIntent(Intent intent) { final Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { if (GoogleCloudMessaging. MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging. MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); } else if (GoogleCloudMessaging. MESSAGE_TYPE_MESSAGE.equals(messageType)) { for (int i=0; i<5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); sendNotification("Received: " + extras.toString()); } } GcmBroadcastReceiver.completeWakefulIntent(intent); }
Source:
<code>private static void testSearchLoanTransactionsWithCustomFields(LoanTransaction loanTransaction) throws MambuApiException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); if(loanTransaction == null){ <START> System.out.println("WARN: " + methodName + " could not run transaction is null"); <END> } JSONFilterConstraints filterConstraints = getJsonFilterConstraintsForParentTransactionGreaterThanOne(loanTransaction); LoansService loanService = MambuAPIFactory.getLoanService(); List<LoanTransaction> transactions = loanService.getLoanTransactionsWithFullDetails(filterConstraints, "0", "100"); for (LoanTransaction transaction : transactions) { List<CustomFieldValue> customFieldValues = transaction.getCustomFieldValues(); logCustomFieldValues(customFieldValues, "LoanAccount", transaction.getParentAccountKey()); } }</code><technical_language>I add "because" "run" "transaction" -> run transaction is null</technical_language>

Target:
private static void testSearchLoanTransactionsWithCustomFields(LoanTransaction loanTransaction) throws MambuApiException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); if(loanTransaction == null){ System.out.println("WARN: " + methodName + " could not run because transaction is null"); } JSONFilterConstraints filterConstraints = getJsonFilterConstraintsForParentTransactionGreaterThanOne(loanTransaction); LoansService loanService = MambuAPIFactory.getLoanService(); List<LoanTransaction> transactions = loanService.getLoanTransactionsWithFullDetails(filterConstraints, "0", "100"); for (LoanTransaction transaction : transactions) { List<CustomFieldValue> customFieldValues = transaction.getCustomFieldValues(); logCustomFieldValues(customFieldValues, "LoanAccount", transaction.getParentAccountKey()); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); String printStyle = this.getIntent().getExtras().getString(KEY_TEMPLATE_STYLE); if(printStyle == null) { if(CompoundIntentList.isIntentCompound(this.getIntent())) { printStyle = TEMPLATE_STYLE_ZPL; } else { printStyle = TEMPLATE_STYLE_HTML; } } <START> if(printStyle == TEMPLATE_STYLE_ZPL) { <END> if(savedInstanceState != null) { return; } } if(TEMPLATE_STYLE_ZPL.equals(printStyle)) { doZebraPrint(); return; } String path = getPathOrThrowError(getIntent().getExtras()); if(path == null) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); return; } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; preparePrintDoc(path); }</code><technical_language>== -> .equals better, lift this logic place set printStyle TEMPLATE_STYLE_ZPL</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_template_printer); String printStyle = this.getIntent().getExtras().getString(KEY_TEMPLATE_STYLE); if(printStyle == null) { if(CompoundIntentList.isIntentCompound(this.getIntent())) { printStyle = TEMPLATE_STYLE_ZPL; } else { printStyle = TEMPLATE_STYLE_HTML; } } if(TEMPLATE_STYLE_ZPL.equals(printStyle)) { if(savedInstanceState != null) { return; } else { doZebraPrint(); return; } } String path = getPathOrThrowError(getIntent().getExtras()); if(path == null) { return; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { showErrorDialog(Localization.get("print.not.supported")); return; } this.outputPath = CommCareApplication._().getTempFilePath() + ".html"; preparePrintDoc(path); }
Source:
<code>public void getAddress( final double latitude, final double longitude, final ReverseGeocoderCallback callback) { if (cache != null) { String cachedAddress = cache.get(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude)); if (cachedAddress != null) { callback.onSuccess(cachedAddress); return; } } <START> Context.getAsyncHttpClient().prepareGet(String.format(Locale.US, url, latitude, longitude)) <END> .execute(new AsyncCompletionHandler() { @Override public Object onCompleted(Response response) throws Exception { try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { Address address = parseAddress(reader.readObject()); if (address != null) { String formattedAddress = addressFormat.format(address); if (cache != null) { cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress); } callback.onSuccess(formattedAddress); } else { callback.onFailure(new GeocoderException("Empty address")); } } return null; } @Override public void onThrowable(Throwable t) { callback.onFailure(t); } }); }</code><technical_language>set locale in Main class. I guess set for unit tests</technical_language>

Target:
public String getAddress( final double latitude, final double longitude, final ReverseGeocoderCallback callback) { if (cache != null) { String cachedAddress = cache.get(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude)); if (cachedAddress != null) { if (callback != null) { callback.onSuccess(cachedAddress); } return cachedAddress; } } if (callback != null) { Context.getAsyncHttpClient().prepareGet(String.format(url, latitude, longitude)) .execute(new AsyncCompletionHandler() { @Override public Object onCompleted(Response response) throws Exception { return handleResponse(latitude, longitude, response, callback); } @Override public void onThrowable(Throwable t) { callback.onFailure(t); } }); } else { try { Response response = Context.getAsyncHttpClient() .prepareGet(String.format(url, latitude, longitude)).execute().get(); return handleResponse(latitude, longitude, response, null); } catch (InterruptedException | ExecutionException | IOException error) { Log.warning("Geocoding failed", error); } } return null; }
Source:
<code>public void checkCodeCommentFeature() { editor.goToPosition(17, 1); <START> editor.typeTextIntoEditor(CONTROL.toString() + "/"); <END> editor.waitTextIntoEditor(" editor.typeTextIntoEditor(Keys.END.toString()); }</code><technical_language>test this? If works OK</technical_language>

Target:
public void checkCodeCommentFeature() { editor.goToPosition(17, 1); editor.launchCommentCodeFeature(); editor.waitTextIntoEditor(" editor.typeTextIntoEditor(Keys.END.toString()); }
Source:
<code>static String generateTaskShape(Integer taskOrdering, int xAxe) { StringBuilder taskBuilder = new StringBuilder(); <START> final int yAxe = 218; <END> taskBuilder.append(" <bpmndi:BPMNShape id=\"Task_"); taskBuilder.append(taskOrdering); taskBuilder.append("_di\" bpmnElement=\"Task_"); taskBuilder.append(taskOrdering); taskBuilder.append(END_LINE); generateBounds(taskBuilder, xAxe, yAxe, 100, 80); taskBuilder.append(CLOSE_SHAPE); taskBuilder.append(" <bpmndi:BPMNEdge id=\"SequenceFlow_"); taskBuilder.append(taskOrdering + 1); taskBuilder.append("_di\" bpmnElement=\"SequenceFlow_"); taskBuilder.append(taskOrdering + 1); taskBuilder.append(END_LINE); generateWayPoint(taskBuilder, xAxe + 100, yAxe + 40); generateWayPoint(taskBuilder, xAxe + 150, yAxe + 40); taskBuilder.append(OPEN_LABEL); generateBounds(taskBuilder, xAxe + 125, yAxe + 29, 0, 12); taskBuilder.append(CLOSE_LABEL); taskBuilder.append(" </bpmndi:BPMNEdge>\n"); return taskBuilder.toString(); }</code><technical_language>above. If constant needs defined for some reason, stick naming conventions for contants, e.g. call this Y_AXE that</technical_language>

Target:
static String generateTaskShape(Integer taskOrdering, int xAxe) { StringBuilder taskBuilder = new StringBuilder(); final int diagramHeight = 218; taskBuilder.append(" <bpmndi:BPMNShape id=\"Task_"); taskBuilder.append(taskOrdering); taskBuilder.append("_di\" bpmnElement=\"Task_"); taskBuilder.append(taskOrdering); taskBuilder.append(END_LINE); generateBounds(taskBuilder, xAxe, diagramHeight, 100, 80); taskBuilder.append(CLOSE_SHAPE); taskBuilder.append(" <bpmndi:BPMNEdge id=\"SequenceFlow_"); taskBuilder.append(taskOrdering + 1); taskBuilder.append("_di\" bpmnElement=\"SequenceFlow_"); taskBuilder.append(taskOrdering + 1); taskBuilder.append(END_LINE); generateWayPoint(taskBuilder, xAxe + 100, diagramHeight + 40); generateWayPoint(taskBuilder, xAxe + 150, diagramHeight + 40); taskBuilder.append(OPEN_LABEL); generateBounds(taskBuilder, xAxe + 125, diagramHeight + 29, 0, 12); taskBuilder.append(CLOSE_LABEL); taskBuilder.append(" </bpmndi:BPMNEdge>\n"); return taskBuilder.toString(); }
Source:
<code>public void testGetInstanceCountMultipleVerticles() throws Exception { AtomicInteger messageCount = new AtomicInteger(0); AtomicInteger totalReportedInstances = new AtomicInteger(0); vertx.eventBus().consumer("instanceCount", event -> { messageCount.incrementAndGet(); totalReportedInstances.addAndGet((int)event.body()); if(messageCount.intValue() == 3) { assertEquals(9, totalReportedInstances.get()); } }); vertx.deployVerticle(TestVerticle3.class.getCanonicalName(), new DeploymentOptions().setInstances(3), ar -> { <START> assertTrue(ar.succeeded()); <END> testComplete(); }); await(); Deployment deployment = ((VertxInternal) vertx).getDeployment(vertx.deploymentIDs().iterator().next()); vertx.undeploy(deployment.deploymentID()); }</code><technical_language>this test is valid deployment handler called message consumer instanceCount messages. put testComplete() in message handler</technical_language>

Target:
public void testGetInstanceCountMultipleVerticles() throws Exception { AtomicInteger messageCount = new AtomicInteger(0); AtomicInteger totalReportedInstances = new AtomicInteger(0); vertx.eventBus().consumer("instanceCount", event -> { messageCount.incrementAndGet(); totalReportedInstances.addAndGet((int)event.body()); if(messageCount.intValue() == 3) { assertEquals(9, totalReportedInstances.get()); testComplete(); } }); vertx.deployVerticle(TestVerticle3.class.getCanonicalName(), new DeploymentOptions().setInstances(3), ar -> { assertTrue(ar.succeeded()); }); await(); Deployment deployment = ((VertxInternal) vertx).getDeployment(vertx.deploymentIDs().iterator().next()); vertx.undeploy(deployment.deploymentID()); }
Source:
<code>public void testWithInvalidAuthorizationCode(String opHost, String redirectUrl, String userId, String userSecret) throws Exception{ final DevelopersApi client = Tester.api(); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String state = CoreUtils.secureRandomString(); final String authorizationStr = Tester.getAuthorization(site); <START> final String code = codeRequest(client, site.getOxdId(), userId, userSecret, state, CoreUtils.secureRandomString(), authorizationStr); <END> final String invalidCode = code.concat("blah"); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(site.getOxdId()); params.setCode(invalidCode); params.setState(state); try { client.getTokensByCode(authorizationStr, params); } catch (ApiException ex) { assertEquals(400, ex.getCode()); } }</code><technical_language>need obtain valid code if want call test method invalid code ? This line removed</technical_language>

Target:
public void testWithInvalidAuthorizationCode(String opHost, String redirectUrl, String userId, String userSecret) throws Exception{ final DevelopersApi client = Tester.api(); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String state = CoreUtils.secureRandomString(); final String authorizationStr = Tester.getAuthorization(site); final String code = codeRequest(client, site.getOxdId(), userId, userSecret, state, CoreUtils.secureRandomString(), authorizationStr); final String invalidCode = code.concat("blah"); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(site.getOxdId()); params.setCode(invalidCode); params.setState(state); try { client.getTokensByCode(authorizationStr, params); fail("Test should throw an exception"); } catch (ApiException ex) { assertEquals(400, ex.getCode()); } }
Source:
<code>protected final void setReliabilityAttributes(boolean lengthCheck, boolean acknowledge, String ackHost, int ackPort, int ackTimeout) { this.mapper.setLengthCheck(lengthCheck); this.waitForAck = acknowledge; this.mapper.setAcknowledge(acknowledge); this.mapper.setAckAddress(ackHost + ":" + ackPort); this.ackHost = ackHost; this.ackPort = ackPort; if (ackTimeout > 0) { this.ackTimeout = ackTimeout; } this.acknowledge = acknowledge; if (!this.acknowledge) { Assert.hasLength(ackHost); <START> Assert.state(StringUtils.isEmpty(socketExpression), "acknowledge cannot be used together with socketExpression"); <END> } }</code><technical_language>This is redundant well. if expression inverted</technical_language>

Target:
protected final void setReliabilityAttributes(boolean lengthCheck, boolean acknowledge, String ackHost, int ackPort, int ackTimeout) { this.mapper.setLengthCheck(lengthCheck); this.waitForAck = acknowledge; this.mapper.setAcknowledge(acknowledge); this.mapper.setAckAddress(ackHost + ":" + ackPort); this.ackHost = ackHost; this.ackPort = ackPort; if (ackTimeout > 0) { this.ackTimeout = ackTimeout; } this.acknowledge = acknowledge; if (this.acknowledge) { Assert.hasLength(ackHost); } }
Source:
<code>public ArrayOfDoublesSketchBuildAggregator( <START> final DimensionSelector keySelector, final List<BaseDoubleColumnValueSelector> valueSelectors, <END> final int nominalEntries) { this.keySelector = keySelector; this.valueSelectors = valueSelectors; sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(valueSelectors.size()).build(); }</code><technical_language>param a separate line. in this PR, in other classes</technical_language>

Target:
public ArrayOfDoublesSketchBuildAggregator( final DimensionSelector keySelector, final List<BaseDoubleColumnValueSelector> valueSelectors, final int nominalEntries ) { this.keySelector = keySelector; this.valueSelectors = valueSelectors.toArray(new BaseDoubleColumnValueSelector[0]); values = new double[valueSelectors.size()]; sketch = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(nominalEntries) .setNumberOfValues(valueSelectors.size()).build(); }
Source:
<code>public void accept(Frame frame) { FrameType frameType = frame.getType(); switch (frameType) { case RESERVED: break; case SETUP: this.setup.increment(); break; case LEASE: this.lease.increment(); break; case KEEPALIVE: this.keepalive.increment(); break; case REQUEST_RESPONSE: this.requestResponse.increment(); break; case REQUEST_FNF: this.requestFireAndForget.increment(); break; case REQUEST_STREAM: this.requestStream.increment(); break; case REQUEST_CHANNEL: this.requestChannel.increment(); break; case REQUEST_N: this.requestN.increment(); break; case CANCEL: this.cancel.increment(); break; case PAYLOAD: break; case ERROR: this.error.increment(); break; case METADATA_PUSH: this.metadataPush.increment(); break; case RESUME: this.resume.increment(); break; case RESUME_OK: this.resumeOk.increment(); break; case NEXT: this.next.increment(); break; case COMPLETE: this.complete.increment(); break; case NEXT_COMPLETE: <START> this.nextComplete.increment(); <END> break; case EXT: this.extension.increment(); break; default: this.logger.warn("Skipping count of unknown frame type: {}", frameType); } }</code><technical_language>a mistake track payload frames</technical_language>

Target:
public void accept(Frame frame) { FrameType frameType = frame.getType(); switch (frameType) { case SETUP: this.setup.increment(); break; case LEASE: this.lease.increment(); break; case KEEPALIVE: this.keepalive.increment(); break; case REQUEST_RESPONSE: this.requestResponse.increment(); break; case REQUEST_FNF: this.requestFireAndForget.increment(); break; case REQUEST_STREAM: this.requestStream.increment(); break; case REQUEST_CHANNEL: this.requestChannel.increment(); break; case REQUEST_N: this.requestN.increment(); break; case CANCEL: this.cancel.increment(); break; case PAYLOAD: this.payload.increment(); break; case ERROR: this.error.increment(); break; case METADATA_PUSH: this.metadataPush.increment(); break; case RESUME: this.resume.increment(); break; case RESUME_OK: this.resumeOk.increment(); break; case NEXT: this.next.increment(); break; case COMPLETE: this.complete.increment(); break; case NEXT_COMPLETE: this.nextComplete.increment(); break; case EXT: this.extension.increment(); break; default: this.logger.debug("Skipping count of unknown frame type: {}", frameType); this.unknown.increment(); } }
Source:
<code>@Test public void configRoundTrip() throws Exception { JUnitResultArchiver a = new JUnitResultArchiver("TEST-*.xml"); a.setKeepLongStdio(true); <START> a.setTestDataPublishers(Collections.singletonList((TestDataPublisher) new MockTestDataPublisher("testing"))); <END> a.setHealthScaleFactor(0.77); a = j.configRoundtrip(a); assertEquals("TEST-*.xml", a.getTestResults()); assertTrue(a.isKeepLongStdio()); List<? extends TestDataPublisher> testDataPublishers = a.getTestDataPublishers(); assertEquals(1, testDataPublishers.size()); assertEquals(MockTestDataPublisher.class, testDataPublishers.get(0).getClass()); assertEquals("testing", ((MockTestDataPublisher) testDataPublishers.get(0)).getName()); assertEquals(0.77, a.getHealthScaleFactor(), 0.01); }</code><technical_language>ant: java a.setTestDataPublishers(Collections.<TestDataPublisher>singletonList(new MockTestDataPublisher("testing")));</technical_language>

Target:
@Test public void configRoundTrip() throws Exception { JUnitResultArchiver a = new JUnitResultArchiver("TEST-*.xml"); a.setKeepLongStdio(true); a.setTestDataPublishers(Collections.<TestDataPublisher>singletonList(new MockTestDataPublisher("testing"))); a.setHealthScaleFactor(0.77); a = j.configRoundtrip(a); assertEquals("TEST-*.xml", a.getTestResults()); assertTrue(a.isKeepLongStdio()); List<? extends TestDataPublisher> testDataPublishers = a.getTestDataPublishers(); assertEquals(1, testDataPublishers.size()); assertEquals(MockTestDataPublisher.class, testDataPublishers.get(0).getClass()); assertEquals("testing", ((MockTestDataPublisher) testDataPublishers.get(0)).getName()); assertEquals(0.77, a.getHealthScaleFactor(), 0.01); }
Source:
<code>private Optional<byte[]> buildIndex(final List<String> accountIds) { final RoaringBitmap roaringBitmap = new RoaringBitmap(); <START> for(String accountId : accountIds) { <END> roaringBitmap.add(Integer.valueOf(accountId)); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(bos); try { roaringBitmap.serialize(dos); } catch (IOException e) { return Optional.absent(); } return Optional.of(bos.toByteArray()); }</code><technical_language>final :)</technical_language>

Target:
private Optional<byte[]> buildIndex(final List<String> accountIds) { final RoaringBitmap roaringBitmap = new RoaringBitmap(); for(String accountId : accountIds) { roaringBitmap.add(Integer.valueOf(accountId)); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(bos); try { roaringBitmap.serialize(dos); return Optional.of(bos.toByteArray()); } catch (IOException e) { LOGGER.error("Failed generating Bitmap index: {}", e.getMessage()); return Optional.absent(); } finally { try { bos.close(); dos.close(); } catch (IOException e) { LOGGER.error("{}", e.getMessage()); } } }
Source:
<code>public void doBuildQuietPeriodInSeconds() throws Exception { final int projectQuietPeriodInSeconds = 10; <START> final int projectQuietPeriodInMillis = projectQuietPeriodInSeconds * 1000; <END> final int timeToExecuteProject = 5000; final FreeStyleProject project = j.createFreeStyleProject(); project.setQuietPeriod(projectQuietPeriodInSeconds); final JenkinsRule.WebClient webClient = j.createWebClient(); webClient.goTo(project.getUrl() + "build", ""); Assert.assertEquals(0, project.getBuilds().size()); Thread.sleep(projectQuietPeriodInMillis / 2); Assert.assertEquals(0, project.getBuilds().size()); Thread.sleep(projectQuietPeriodInMillis / 2 + timeToExecuteProject); Assert.assertEquals(1, project.getBuilds().size()); }</code><technical_language>Ironically, of TimeUnit here</technical_language>

Target:
public void doBuildQuietPeriodInSeconds() throws Exception { final int projectQuietPeriodInSeconds = 50; final FreeStyleProject project = j.createFreeStyleProject(); project.setQuietPeriod(projectQuietPeriodInSeconds); final JenkinsRule.WebClient webClient = j.createWebClient(); webClient.goTo(project.getUrl() + "build", ""); long triggerTime = System.currentTimeMillis(); Queue.Item item = Jenkins.get().getQueue().getItem(1); Assert.assertTrue(item instanceof Queue.WaitingItem); Assert.assertTrue(item.task instanceof FreeStyleProject); Queue.WaitingItem waitingItem = (Queue.WaitingItem) item; Assert.assertTrue((waitingItem.timestamp.getTimeInMillis() - triggerTime) > 45000); Jenkins.get().getQueue().doCancelItem(1); }
Source:
<code>public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { List<Element> sourceElements = source.getAllElements(); sourceElements.stream() .filter(element -> SUPPORTED_ELEMENTS.contains(element.getName())) .filter(unsafeSubResource(msg.getRequestHeader().getHostName())) .forEach( element -> { Alert alert = new Alert( getPluginId(), Alert.RISK_MEDIUM, Alert.CONFIDENCE_HIGH, getName()); alert.setDetail( getString("desc"), msg.getRequestHeader().getURI().toString(), "", "", "", getString("soln"), getString("refs"), element.toString(), <START> 287, END> -1, msg); parent.raiseAlert(id, alert); }); }</code><technical_language>Is this wanted? right me</technical_language>

Target:
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) { List<Element> sourceElements = source.getAllElements(); sourceElements.stream() .filter(element -> SupportedElements.contains(element.getName())) .filter(unsafeSubResource(msg.getRequestHeader().getHostName())) .forEach( element -> { Alert alert = new Alert( getPluginId(), Alert.RISK_MEDIUM, Alert.CONFIDENCE_HIGH, getName()); alert.setDetail( getString("desc"), msg.getRequestHeader().getURI().toString(), "", "", "", getString("soln"), getString("refs"), element.toString(), 16, 15, msg); parent.raiseAlert(id, alert); }); }
Source:
<code>private int allocateResources(int workerNum) { int allocatedWorkerNum = 0; for (int i = 0; i < workerNum; ++i) { if (allocateResource(defaultSlotResourceProfile).isPresent()) { <START> ++allocatedWorkerNum; <END> } } return allocatedWorkerNum; }</code><technical_language>break for-loop early if condition is met</technical_language>

Target:
private int allocateResources(int workerNum) { int allocatedWorkerNum = 0; for (int i = 0; i < workerNum; ++i) { if (allocateResource(defaultSlotResourceProfile).isPresent()) { ++allocatedWorkerNum; } else { break; } } return allocatedWorkerNum; }
Source:
<code>private void send(String exchangeName, String routingKey, final Message<?> requestMessage, CorrelationData correlationData) { if (this.amqpTemplate instanceof RabbitTemplate) { MessageConverter converter = ((RabbitTemplate) this.amqpTemplate).getMessageConverter(); org.springframework.amqp.core.Message amqpMessage = MappingUtils.mapMessage(requestMessage, converter, <START> getHeaderMapper(), this.getDefaultDeliveryMode()); <END> ((RabbitTemplate) this.amqpTemplate).send(exchangeName, routingKey, amqpMessage, correlationData); } else { this.amqpTemplate.convertAndSend(exchangeName, routingKey, requestMessage.getPayload(), new MessagePostProcessor() { @Override public org.springframework.amqp.core.Message postProcessMessage( org.springframework.amqp.core.Message message) throws AmqpException { getHeaderMapper().fromHeadersToRequest(requestMessage.getHeaders(), message.getMessageProperties()); return message; } }); } }</code><technical_language>this. is overhead for methods. modify code :smile:</technical_language>

Target:
private void send(String exchangeName, String routingKey, final Message<?> requestMessage, CorrelationData correlationData) { if (this.amqpTemplate instanceof RabbitTemplate) { MessageConverter converter = ((RabbitTemplate) this.amqpTemplate).getMessageConverter(); org.springframework.amqp.core.Message amqpMessage = MappingUtils.mapMessage(requestMessage, converter, getHeaderMapper(), getDefaultDeliveryMode()); ((RabbitTemplate) this.amqpTemplate).send(exchangeName, routingKey, amqpMessage, correlationData); } else { this.amqpTemplate.convertAndSend(exchangeName, routingKey, requestMessage.getPayload(), new MessagePostProcessor() { @Override public org.springframework.amqp.core.Message postProcessMessage( org.springframework.amqp.core.Message message) throws AmqpException { getHeaderMapper().fromHeadersToRequest(requestMessage.getHeaders(), message.getMessageProperties()); return message; } }); } }
Source:
<code>public void validate () { LOG.info("Cacheing stops, trips, and routes..."); for (Stop stop : feed.stops) stopById.put(stop.stop_id, stop); <START> for (ShapePoint shape : feed.shapePoints.getAllOrdered()) shapeById.put(shape.shape_id, shape); <END> for (Trip trip: feed.trips) tripById.put(trip.trip_id, trip); for (Route route: feed.routes) routeById.put(route.route_id, route); LOG.info("Done."); List<StopTime> stopTimesForTrip = new ArrayList<>(); String previousTripId = null; for (StopTime stopTime : feed.stopTimes.getAllOrdered()) { if (stopTime.trip_id == null) continue; if (!stopTime.trip_id.equals(previousTripId) && !stopTimesForTrip.isEmpty()) { processTrip(stopTimesForTrip); stopTimesForTrip.clear(); } stopTimesForTrip.add(stopTime); previousTripId = stopTime.trip_id; } processTrip(stopTimesForTrip); }</code><technical_language>Shapes frequently of largest tables in a GTFS feed, par stop_times. hesitant cache this in memory. PatternFinderValidator.java this cache, building front passing TripValidator excessive. I suspect fetch shape points table pattern (within pattern creation validator pattern builder) prohibitively slow, tens hundreds of times patterns trips</technical_language>

Target:
public void validate () { LOG.info("Cacheing stops, trips, and routes..."); for (Stop stop : feed.stops) stopById.put(stop.stop_id, stop); for (Trip trip: feed.trips) tripById.put(trip.trip_id, trip); for (Route route: feed.routes) routeById.put(route.route_id, route); LOG.info("Done."); List<StopTime> stopTimesForTrip = new ArrayList<>(); String previousTripId = null; for (StopTime stopTime : feed.stopTimes.getAllOrdered()) { if (stopTime.trip_id == null) continue; if (!stopTime.trip_id.equals(previousTripId) && !stopTimesForTrip.isEmpty()) { processTrip(stopTimesForTrip); stopTimesForTrip.clear(); } stopTimesForTrip.add(stopTime); previousTripId = stopTime.trip_id; } processTrip(stopTimesForTrip); }
Source:
<code>private void DiskInterface_SelectedItemChanged() { boolean isLunDisk = getDiskStorageType().getEntity() == DiskStorageType.LUN; DiskInterface diskInterface = getDiskInterface().getSelectedItem(); getIsSgIoUnfiltered().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsScsiPassthrough().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsUsingScsiReservation().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); <START> getIsReadOnly().setIsAvailable(!DiskInterface.IDE.equals(diskInterface) && !DiskInterface.SATA.equals(diskInterface)); <END> updatePassDiscardAvailability(); updateScsiPassthroughChangeability(); updateScsiReservationChangeability(); updateReadOnlyChangeability(); updatePlugChangeability(); updatePassDiscardChangeability(); updateWipeAfterDeleteChangeability(); }</code><technical_language>changing syntax to: diskInterface != DiskInterface.IDE && diskInterface != DiskInterface.SATA limit of 120 characters</technical_language>

Target:
private void DiskInterface_SelectedItemChanged() { boolean isLunDisk = getDiskStorageType().getEntity() == DiskStorageType.LUN; DiskInterface diskInterface = getDiskInterface().getSelectedItem(); getIsSgIoUnfiltered().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsScsiPassthrough().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsUsingScsiReservation().setIsAvailable(isLunDisk && DiskInterface.VirtIO_SCSI.equals(diskInterface)); getIsReadOnly().setIsAvailable(diskInterface != DiskInterface.IDE && diskInterface != DiskInterface.SATA); updatePassDiscardAvailability(); updateScsiPassthroughChangeability(); updateScsiReservationChangeability(); updateReadOnlyChangeability(); updatePlugChangeability(); updatePassDiscardChangeability(); updateWipeAfterDeleteChangeability(); }
Source:
<code>public final void onFailure(Exchange exchange) { boolean connected = AccessController.doPrivileged((PrivilegedAction<Boolean>) asyncFileEntry::checkNetwork); if (!connected) { LOGGER.debug( "a network error occurred, The file failed to process", asyncFileEntry.getName()); } else if (exchange.getException() != null) { <START> LOGGER.debug( <END> "Exchange failed synchronization on exception: {}", exchange.getExchangeId(), exchange.getException()); } callback.accept(asyncFileEntry, false); }</code><technical_language>this higher debug? frequently this occur if considered noise</technical_language>

Target:
public final void onFailure(Exchange exchange) { boolean connected = AccessController.doPrivileged((PrivilegedAction<Boolean>) asyncFileEntry::checkNetwork); if (!connected) { LOGGER.debug( "a network error occurred, The file failed to process", asyncFileEntry.getName()); } else if (exchange != null && exchange.getException() != null) { LOGGER.debug( "Exchange failed synchronization on exception: {}", exchange.getExchangeId(), exchange.getException()); } callback.accept(asyncFileEntry, false); }
Source:
<code>protected E doBackward(Tuple<I> tuple) { final Message unpacked = unpack(tuple.getState() .getState()); final TypeUrl entityStateType = repository.getEntityStateType(); final S state = (S) FieldMasks.applyMask(fieldMask, unpacked, entityStateType); final E entity = repository.create(tuple.getId()); final EntityRecord record = tuple.getState(); if (entity != null) { if (entity instanceof AbstractVersionableEntity) { <START> AbstractVersionableEntity versionable = (AbstractVersionableEntity) entity; <END> versionable.setState(state, record.getVersion()); versionable.setVisibility(record.getVisibility()); } else { entity.injectState(state); } } return entity; }</code><technical_language>declared final. BTW, IDEA instanceof template edited :)</technical_language>

Target:
protected E doBackward(Tuple<I> tuple) { final Message unpacked = unpack(tuple.getState() .getState()); final TypeUrl entityStateType = repository.getEntityStateType(); final S state = (S) FieldMasks.applyMask(fieldMask, unpacked, entityStateType); final E entity = repository.create(tuple.getId()); final EntityRecord record = tuple.getState(); if (entity != null) { if (entity instanceof AbstractVersionableEntity) { final AbstractVersionableEntity versionable = (AbstractVersionableEntity) entity; versionable.setState(state, record.getVersion()); versionable.setVisibility(record.getVisibility()); } else { entity.injectState(state); } } return entity; }
Source:
<code>public Boolean getisValueTypeCorrect() { if (this.xmpNode.getChildren().size() != 3) { return Boolean.FALSE; } <START> VeraPDFXMPNode description = null; <END> VeraPDFXMPNode name = null; VeraPDFXMPNode valueType = null; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_FIELD.equals(child.getNamespaceURI())) { switch (child.getName()) { case "description": description = child; break; case "name": name = child; break; case "valueType": valueType = child; break; } } } return Boolean.valueOf(description != null && name != null && valueType != null); }</code><technical_language>boolean flag</technical_language>

Target:
public Boolean getisValueTypeCorrect() { boolean isValid = true; boolean isDescriptionPresent = false; boolean isNamePresent = false; boolean isValueTypePresent = false; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_FIELD.equals(child.getNamespaceURI())) { switch (child.getName()) { case "description": if (isDescriptionPresent) { isValid = false; } else { isDescriptionPresent = true; } break; case "name": if (isNamePresent) { isValid = false; } else { isNamePresent = true; } break; case "valueType": if (isValueTypePresent) { isValid = false; } else { isValueTypePresent = true; } break; default: isValid = false; } } else { isValid = false; } } return Boolean.valueOf(isValid); }
Source:
<code>protected TmfXYChartViewer createChartViewer(Composite parent) { TmfXYChartSettings settings = new TmfXYChartSettings(Messages.ScriptedXYTreeViewer_DefaultViewerTitle, Messages.ScriptedXYTreeViewer_DefaultXAxis, Messages.ScriptedXYTreeViewer_DefaultYAxis, 1); <START> String name = getSecondaryIdName(); <END> return new ScriptedXYViewer(parent, settings, name); }</code><technical_language>inline this in call</technical_language>

Target:
protected TmfXYChartViewer createChartViewer(Composite parent) { TmfXYChartSettings settings = new TmfXYChartSettings(Messages.ScriptedXYTreeViewer_DefaultViewerTitle, Messages.ScriptedXYTreeViewer_DefaultXAxis, Messages.ScriptedXYTreeViewer_DefaultYAxis, 1); return new TmfFilteredXYChartViewer(parent, settings, getViewSite().getSecondaryId().replace(ScriptedXYView.COLON, ":")); }
Source:
<code>public List<OntClass> listClasses() { <START> return ontology.listClasses().toList(); <END> }</code><technical_language>Yields results I replace OntModel schema = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM); OntModel schema = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RDFS_INF); in MetadataService</technical_language>

Target:
public Set<OntClass> listClasses() { return ontology.listClasses().toSet(); }
Source:
<code>public int hashCode() { <START> int result = leaderSessionID.hashCode(); <END> result = 31 * result + Objects.hashCode(leaderAddress); return result; }</code><technical_language>This throw NPE if leaderSessionID is null</technical_language>

Target:
public int hashCode() { int result = Objects.hashCode(leaderSessionID); result = 31 * result + Objects.hashCode(leaderAddress); return result; }
Source:
<code>public synchronized INavigatorContentService findService(String aViewerId) { if(aViewerId == null || aViewerId.length() == 0) { return null; } INavigatorContentService contentService; for (Iterator<WeakReference<INavigatorContentService>> iter = registeredContentServices.iterator(); iter.hasNext();) { WeakReference ref = iter.next(); <START> if(ref.get() == <END> null) { iter.remove(); } else { contentService = (INavigatorContentService)ref.get(); if (contentService != null && aViewerId.equals(contentService.getViewerId())) { return contentService; } } } return null; }</code><technical_language>Please call this time check time</technical_language>

Target:
public synchronized INavigatorContentService findService(String aViewerId) { if(aViewerId == null || aViewerId.length() == 0) { return null; } INavigatorContentService contentService; for (Iterator<WeakReference<INavigatorContentService>> iter = registeredContentServices.iterator(); iter.hasNext();) { WeakReference ref = iter.next(); contentService = (INavigatorContentService) ref.get(); if (contentService == null) { iter.remove(); } else if (aViewerId.equals(contentService.getViewerId())) { return contentService; } } return null; }
Source:
<code>public Syndication createSyndication(ArticleVersionIdentifier versionId, String target) { ArticleVersion articleVersion = articleCrudService.getArticleVersion(versionId); Syndication syndication = new Syndication(articleVersion, target); <START> syndication.setStatus(Syndication.STATUS_PENDING); <END> syndication.setSubmissionCount(0); hibernateTemplate.save(syndication); return syndication; }</code><technical_language>long touching status constants, consider pulling enum</technical_language>

Target:
public Syndication createSyndication(ArticleVersionIdentifier versionId, String target) { ArticleVersion articleVersion = articleCrudService.getArticleVersion(versionId); Syndication syndication = new Syndication(articleVersion, target); syndication.setStatus(SyndicationStatuses.PENDING.name()); syndication.setSubmissionCount(0); hibernateTemplate.save(syndication); return syndication; }
Source:
<code>private void initializeActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowCustomEnabled(true); <START> actionBar.setCustomView(R.layout.actionbar_custom); <END> actionBar.setDisplayHomeAsUpEnabled(true); }</code><technical_language>custom action bar before. need now</technical_language>

Target:
private void initializeActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); }
Source:
<code>public void refreshBuilds(final RefreshRequest request, final GetBuildsRequest buildRequest, final IOperationMonitor monitor) throws CoreException { final List<IBuild> result = BuildRunner.run(new BuildRunnableWithResult<List<IBuild>>() { @Override public List<IBuild> run() throws CoreException { <START> List<IBuild> builds = server.getBehaviour().getBuilds(buildRequest, monitor); <END> return builds; } }); if (result == null) { return; } final BuildServer original = server.getOriginal(); original.getLoader().getRealm().syncExec(new Runnable() { public void run() { Date refreshDate = new Date(); List<IBuildPlan> plans = new ArrayList<>(); plans.addAll(request.getModel().getPlans()); for (IBuildPlan modelPlan : plans) { if (modelPlan.getServer() == original && modelPlan.getId().equals(buildRequest.getPlan().getId())) { updateLastBuild(request, modelPlan, result.get(0), refreshDate); } } } }); }</code><technical_language>change this inline return</technical_language>

Target:
public void refreshBuilds(final RefreshRequest request, final GetBuildsRequest buildRequest, final IOperationMonitor monitor) throws CoreException { final List<IBuild> result = BuildRunner.run(new BuildRunnableWithResult<List<IBuild>>() { @Override public List<IBuild> run() throws CoreException { return server.getBehaviour().getBuilds(buildRequest, monitor); } }); if (result == null) { return; } final BuildServer original = server.getOriginal(); original.getLoader().getRealm().syncExec(new Runnable() { public void run() { Date refreshDate = new Date(); for (IBuildPlan modelPlan : request.getModel().getPlans()) { if (modelPlan.getServer() == original && modelPlan.getId().equals(buildRequest.getPlan().getId())) { updateLastBuild(request, modelPlan, result.get(0), refreshDate); } } } }); }
Source:
<code>private boolean shouldEnableWiktionaryDialog() { <START> return Prefs.useRestBase() && isWiktionaryDialogEnabledForArticleLanguage(); <END> }</code><technical_language>need add a beta check here. Another patch is changing Prefs.useRestBase() include production app well</technical_language>

Target:
private boolean shouldEnableWiktionaryDialog() { return Prefs.useRestBase() && WikipediaApp.getInstance().isPreProdRelease() && isWiktionaryDialogEnabledForArticleLanguage(); }
Source:
<code>public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { <START> mockMvc.contentType("application/json") <END> .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", CoreMatchers.equalTo("forbidden")); }</code><technical_language>MediaType.APPLICATION_JSON_VALUE instead of String constant? Thanks</technical_language>

Target:
public void unauthorizedUserShouldReceiveExpectedUnauthorizedResponse() { mockMvc.contentType("application/json") .accept(ContentType.JSON) .when() .get("/api/configuration/strongbox") .peek() .then() .statusCode(HttpStatus.FORBIDDEN.value()) .contentType("application/json") .body("error", equalTo("forbidden")); }
Source:
<code>public KeyPairProducer(int numberOfworkers) { this.numberOfWorkers = new AtomicInteger(numberOfworkers); <START> final ExecutorService executorService = Executors.newSingleThreadExecutor(); <END> future = executorService.submit(new Runnable() { @Override public void run() { while (!Thread.interrupted()) { try { int numberOfKeysToAdd = numberOfWorkers.get() - keyPairs.size(); if (numberOfKeysToAdd > 0) { for (int i = 0; i < numberOfKeysToAdd; ++i) { keyPairs.put(generateAndAddKeyPairs()); } } synchronized (keyPairs) { keyPairs.wait(loopTimeout); } } catch (InterruptedException e) { LOGGER.error("Thread was interrupted.", e); Thread.currentThread().interrupt(); } catch (Throwable e) { LOGGER.error(e); } } } }); }</code><technical_language>I discussed @jrochas, is need ExecutorService here, is once. other hand, Thread created named setDaemon</technical_language>

Target:
public KeyPairProducer(int numberOfworkers) { this.keyPairs = new LinkedBlockingQueue(numberOfworkers); final Thread thread = new Thread(new Runnable() { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { keyPairs.put(generateAndAddKeyPairs()); } } catch (InterruptedException e) { LOGGER.error(e); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER.error(e); } } }); thread.setDaemon(true); thread.start(); }
Source:
<code>public void execute(final Credentials credentials, final Callback callback) { <START> mCallback = callback; <END> insertedCredentials = credentials; mAuthenticationManager.hardcodedLogin(ServerAPIController.getServerUrl(), new IAuthenticationManager.Callback<UserAccount>() { @Override public void onSuccess(UserAccount userAccount) { mAsyncExecutor.run(new Runnable() { @Override public void run() { pullOrganisationCredentials(credentials, callback); } }); } @Override public void onError(Throwable throwable) { if (throwable instanceof MalformedURLException || throwable instanceof UnknownHostException) { notifyServerURLNotValid(); } else if (throwable instanceof InvalidCredentialsException) { notifyInvalidCredentials(); } else if (throwable instanceof NetworkException) { ICredentialsRepository credentialsLocalDataSource = new CredentialsLocalDataSource(); checkUserCredentialsWithOrgUnit( credentialsLocalDataSource.getOrganisationCredentials(), false); } } }); }</code><technical_language>@manuelplazaspalacio steps of login process executed AsyncExecutor step included. Review PushUseCase for view a example of execute in async mode</technical_language>

Target:
public void execute(final Credentials credentials, final Callback callback) { mCallback = callback; insertedCredentials = credentials; mAsyncExecutor.run(this); }
Source:
<code>protected JobId createJob(final String name, final String version, final String image, final List<String> command, final Map<String, String> env, final Map<String, PortMapping> ports, final Map<ServiceEndpoint, ServicePorts> registration, final Map<String, String> volumes) throws Exception { <START> return createJob(name, version, image, command, env, ports, registration, volumes, null); <END> }</code><technical_language>If EMPTY_EXPIRES, here</technical_language>

Target:
protected JobId createJob(final String name, final String version, final String image, final List<String> command, final Map<String, String> env, final Map<String, PortMapping> ports, final Map<ServiceEndpoint, ServicePorts> registration, final Map<String, String> volumes) throws Exception { return createJob(name, version, image, command, env, ports, registration, volumes, EMPTY_EXPIRES); }
Source:
<code>public boolean load(Element shared, Element perNode) throws JmriConfigureXmlException { getInstance(); <START> try { } catch (NullPointerException ex) { } try { <END> } catch (NullPointerException ex) { } loadCommon(shared, perNode, portController); register(); if (!portController.getDisabled()) { portController.configure(); try { portController.connect(); } catch (IOException ex) { log.error("Unable to start service: {}", ex.getMessage()); } } return true; }</code><technical_language>Is this code finished? checking forgotten it</technical_language>

Target:
public boolean load(Element shared, Element perNode) throws JmriConfigureXmlException { getInstance(); try { short port = (short)shared.getAttribute("port").getIntValue(); portController.setPort(port); } catch (org.jdom2.DataConversionException ex) { log.warn("Could not parse port attribute: {}", shared.getAttribute("port")); } catch (NullPointerException ex) { log.error("No port attribute availableCould not parse port attribute", ex); } loadCommon(shared, perNode, portController); register(); if (!portController.getDisabled()) { portController.configure(); try { portController.connect(); } catch (IOException ex) { log.error("Unable to start service: {}", ex.getMessage()); } } return true; }