auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testAUserCannotCreateAMeetingIfHasConflictsWithAnotherMeeting() { String organizer = meetingData.get(2).get("Organizer"); String subject = meetingData.get(2).get("Subject"); String startTime = meetingData.get(2).get("Start time"); String endTime = meetingData.get(2).get("End time"); String attendee = meetingData.get(2).get("Attendee"); String body = meetingData.get(2).get("Body"); String password = meetingData.get(2).get("Password"); HomeTabletPage home = new HomeTabletPage(); home .clickScheduleBtn() .setOrganizerTxtBox(organizer) .setSubjectTxtBox(subject) <START> .setStartTimeDate(startTime) <END> .setEndTimeDate(endTime) .setAttendeeTxtBoxPressingEnter(attendee) .setBodyTxtBox(body) .clickCreateBtn() .setPasswordTxtBox(password) .clickOkButton(); SchedulePage schedule = new SchedulePage(); schedule.clickCancelButton(); Assert.assertTrue(schedule.isMessageErrorCreationMeetingPopUpDisplayed()); }</code><technical_language>method schedulePage.createMeeting (,.....,.., ) do of this steps here..</technical_language>

Target:
public void testAUserCannotCreateAMeetingIfHasConflictsWithAnotherMeeting() { String organizer = meetingData.get(2).get("Organizer"); String subject = meetingData.get(2).get("Subject"); String startTime = meetingData.get(2).get("Start time"); String endTime = meetingData.get(2).get("End time"); String attendee = meetingData.get(2).get("Attendee"); String body = meetingData.get(2).get("Body"); String password = meetingData.get(2).get("Password"); HomeTabletPage homePage = new HomeTabletPage(); SchedulePage schedulePage = homePage .clickScheduleBtn() .createMeeting(organizer, subject, startTime, endTime, attendee, body, password) .clickCancelButton(); Assert.assertTrue(schedulePage.isMessageErrorCreationMeetingPopUpDisplayed()); }
Source:
<code>private static io.fabric8.kubernetes.client.Config getKubeConfigFromPath(String path) { <START> try{ <END> final Path kubeConfigPath = Paths.get(path); final String kubeConfigContents = new String(Files.readAllBytes(kubeConfigPath), Charset.forName("UTF-8")); return io.fabric8.kubernetes.client.Config.fromKubeconfig(kubeConfigContents); }catch (java.io.IOException e) { throw new ConfigException("Could not read kubeConfig, check out kube_config_path."); } }</code><technical_language>nitpick: try {</technical_language>

Target:
static io.fabric8.kubernetes.client.Config getKubeConfigFromPath(String path) { try { final Path kubeConfigPath = Paths.get(path); final String kubeConfigContents = new String(Files.readAllBytes(kubeConfigPath), Charset.forName("UTF-8")); return io.fabric8.kubernetes.client.Config.fromKubeconfig(kubeConfigContents); } catch (java.io.IOException e) { throw new ConfigException("Could not read kubeConfig, check kube_config_path."); } }
Source:
<code>public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { <START> String fieldName; <END> Node node; NodeList nodeList; try { InputSource source = new InputSource(new StringReader((String) input.get(config.inputField))); source.setEncoding(config.encoding); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : outSchema.getFields()) { fieldName = field.getName(); nodeList = (NodeList) xpath.compile(xPathMapping.get(fieldName)).evaluate(document, XPathConstants.NODESET); if (nodeList.getLength() > 1) { throw new IllegalArgumentException("Cannot specify XPath that are arrays"); } node = nodeList.item(0); builder.set(fieldName, parseValues(getValue(node, field.getSchema().getNonNullable().getType(), fieldName), field)); } emitter.emit(builder.build()); } catch (Exception e) { switch (mapErrorProcessing.get(config.processOnError)) { case 2: throw new IllegalStateException("Terminating process in error : " + e.getMessage()); case 3: emitter.emitError(new InvalidEntry<>(31, e.getStackTrace()[0].toString() + " : " + e.getMessage(), input)); break; default: break; } } }</code><technical_language>I helps variable declarations separate assignments</technical_language>

Target:
public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { try { InputSource source = new InputSource(new StringReader((String) input.get(config.inputField))); source.setEncoding(config.encoding); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); StructuredRecord.Builder builder = StructuredRecord.builder(outSchema); for (Schema.Field field : outSchema.getFields()) { String fieldName = field.getName(); NodeList nodeList = (NodeList) xpath.compile(xPathMapping.get(fieldName)).evaluate(document, XPathConstants.NODESET); if (nodeList.getLength() > 1) { throw new IllegalArgumentException("Cannot specify an XPath that is an array"); } Node node = nodeList.item(0); Schema.Type type = field.getSchema().getNonNullable().getType(); String value = getValue(node, type, fieldName); if (value == null) { builder.set(fieldName, null); } else { builder.set(fieldName, TypeConvertor.get(value, type)); } } emitter.emit(builder.build()); } catch (Exception e) { switch (config.processOnError) { case EXIT_ON_ERROR: throw new IllegalStateException("Terminating process on error: " + e.getMessage()); case WRITE_ERROR_DATASET: emitter.emitError(new InvalidEntry<>(31, e.getStackTrace()[0].toString() + " : " + e.getMessage(), input)); break; default: break; } } }
Source:
<code><START> protected void processRequest() throws Exception { <END> }</code><technical_language>Instead of empty implementation, this abstract method subclasses need implement</technical_language>

Target:
protected abstract void processRequest() throws Exception; @Override protected void mayProceed() throws InsufficientPermissionException { if (ub.isSysAdmin() || ub.isTechAdmin()) { return; } addPageMessage(respage.getString("no_have_correct_privilege_current_study") + respage.getString("change_study_contact_sysadmin")); throw new InsufficientPermissionException(Page.MENU_SERVLET, resexception.getString("not_allowed_access_extract_data_servlet"), "1"); }
Source:
<code>public Context putAll(Context other) { <START> if ( readonly ) <END> throw new ARQException("Context is readonly") ; if ( other != null ) other.context.forEach(this::put); return this; }</code><technical_language>operation for fluent inconsistent. Context manipulation (shouldn't) common operation. Context.mergeCopy</technical_language>

Target:
public void putAll(Context other) { if ( readonly ) throw new ARQException("Context is readonly") ; if ( other != null ) other.context.forEach(this::put); }
Source:
<code>public <O> Expression<O> createExecutableExpression(String expression, Class<?> returnType) { <START> return createExecutableExpression(expression, returnType, false); <END> }</code><technical_language>pass true parameter? definition of createExecutableExpression conveys</technical_language>

Target:
public <O> Expression<O> createExecutableExpression(String expression, Class<?> returnType) { return createExecutableCode(expression, returnType, false); }
Source:
<code>Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, <START> shardPrioritization, Optional.empty(), Optional.empty(), DEFAULT_WORKER_STATE_CHANGE_LISTENER, new ShardSyncer(new KinesisLeaseCleanupValidator())); <END> }</code><technical_language>ShardSyncer is created multiple times. create once. Worker 1 ShardSyncer</technical_language>

Target:
Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, shardPrioritization, Optional.empty(), Optional.empty(), DEFAULT_WORKER_STATE_CHANGE_LISTENER, DEFAULT_LEASE_CLEANUP_VALIDATOR ); }
Source:
<code>public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); <START> for (String key : headers.keySet()) { <END> String value = headers.get(key); String[] values = StringUtils.commaDelimitedListToStringArray(value); for (String v : values) { httpHeaders.add(key, v); } } setHeaders(httpHeaders); }</code><technical_language>entrySet()</technical_language>

Target:
public void setHeadersMap(Map<String, String> headers) { Assert.notNull(headers); HttpHeaders httpHeaders = new HttpHeaders(); for (Map.Entry<String, String> entry : headers.entrySet()) { String[] values = StringUtils.commaDelimitedListToStringArray(entry.getValue()); for (String v : values) { httpHeaders.add(entry.getKey(), v); } } setHeaders(httpHeaders); }
Source:
<code>public void validConnection() throws WaarpDatabaseNoConnectionException { try { dbModel.validConnection(getSession()); } catch (WaarpDatabaseNoConnectionException e) { getSession().setDisActive(true); setActive(false); throw e; } getSession().setDisActive(false); <START> setActive(true); <END> }</code><technical_language>@deprecated removed? remain deprecated next major version! Especially this method is a "noop"</technical_language>

Target:
public void validConnection() throws WaarpDatabaseNoConnectionException { try { dbModel.validConnection(getSession()); } catch (WaarpDatabaseNoConnectionException e) { getSession().setDisActive(true); throw e; } getSession().setDisActive(false); }
Source:
<code>public void validateJBIDE22704() { <START> new NewOpenShift3ApplicationWizard().openWizardFromExplorer(); <END> BuilderImageApplicationWizardHandlingTest.nextToBuildConfigurationWizardPage(); applicationName = new LabeledText("Name: ").getText(); assertNotNull(applicationName); assertTrue(applicationName.length() > 0); new WaitUntil(new WidgetIsEnabled(new NextButton())); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberofEnvironmentVariables = new DefaultTable().rowCount(); assertTrue(numberofEnvironmentVariables > 0); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberOfServicePorts = new DefaultTable().rowCount(); assertTrue(numberOfServicePorts > 0); new CancelButton().click(); }</code><technical_language>JBIDE-22704 is opening Central/shell menu. Working wizard opened OpenShift explorer view is places working. 2 tests. new new NewOpenShift3ApplicationWizard().openWizardFromShellMenu(); new NewOpenShift3ApplicationWizard().openWizardFromCentral();</technical_language>

Target:
private void validateJBIDE22704() { BuilderImageApplicationWizardHandlingTest.nextToBuildConfigurationWizardPage(); applicationName = new LabeledText("Name: ").getText(); assertNotNull(applicationName); assertTrue(applicationName.length() > 0); new WaitUntil(new WidgetIsEnabled(new NextButton())); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberofEnvironmentVariables = new DefaultTable().rowCount(); assertTrue(numberofEnvironmentVariables > 0); new NextButton().click(); new WaitUntil(new WidgetIsEnabled(new BackButton())); int numberOfServicePorts = new DefaultTable().rowCount(); assertTrue(numberOfServicePorts > 0); new CancelButton().click(); new WaitWhile(new JobIsRunning(), TimePeriod.getCustom(120)); }
Source:
<code>protected void writeAlignment(final SAMRecord alignment) { if (shouldFlushContainer(alignment)) { try { flushContainer(); <START> } catch (final Exception e) { <END> throw new RuntimeException(e); } } updateReferenceContext(alignment.getReferenceIndex()); samRecords.add(alignment); }</code><technical_language>replace this more explicit exception rewrapping? try { flushContainer(); } catch (IOException e) { throw new RuntimeIOException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); }</technical_language>

Target:
protected void writeAlignment(final SAMRecord alignment) { if (shouldFlushContainer(alignment)) { try { flushContainer(); } catch (IOException e) { throw new RuntimeIOException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } updateReferenceContext(alignment.getReferenceIndex()); samRecords.add(alignment); }
Source:
<code>public static synchronized void forceShutdown() { if (instance != null) { try { <START> instance.shutdownGracefully(100, 3000, TimeUnit.MILLISECONDS).await(); <END> } catch (InterruptedException ignored) { } instance.channelFactoryCount.set(0); instance = null; } }</code><technical_language>Possibly. need run tests a determination</technical_language>

Target:
public static synchronized void forceShutdown() { if (instance != null) { instance.forEach(executor -> executor.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS)); instance.channelFactoryCount.set(0); instance = null; } }
Source:
<code>private Query createQuery(List<PriorityQueue<Object[]>> q) { int length = fieldsContext.size(); if ( length == 0 ) { throw new AssertionFailure( "Querying MoreLikeThis on 0 field." ); } else if ( length == 1 ) { return createQuery( q.get( 0 ), fieldsContext.getFirst() ); } else { <START> BooleanQuery.Builder builder = new BooleanQuery.Builder(); <END> Iterator<FieldContext> fieldsContextIterator = fieldsContext.iterator(); for ( PriorityQueue<Object[]> queue : q ) { try { builder.add( createQuery( queue, fieldsContextIterator.next() ), BooleanClause.Occur.SHOULD ); } catch (BooleanQuery.TooManyClauses ignore) { break; } } return builder.build(); } }</code><technical_language>here, queryBuilder better</technical_language>

Target:
private Query createQuery(List<PriorityQueue<Object[]>> q) { int length = fieldsContext.size(); if ( length == 0 ) { throw new AssertionFailure( "Querying MoreLikeThis on 0 field." ); } else if ( length == 1 ) { return createQuery( q.get( 0 ), fieldsContext.getFirst() ); } else { BooleanQuery.Builder queryBuilder = new BooleanQuery.Builder(); Iterator<FieldContext> fieldsContextIterator = fieldsContext.iterator(); for ( PriorityQueue<Object[]> queue : q ) { try { queryBuilder.add( createQuery( queue, fieldsContextIterator.next() ), BooleanClause.Occur.SHOULD ); } catch (BooleanQuery.TooManyClauses ignore) { break; } } return queryBuilder.build(); } }
Source:
<code>default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { <START> return null; <END> }</code><technical_language>return getRetryAnalyzer() check null call previous getRetryAnalyzer in business code (where expect call new method only)</technical_language>

Target:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return getRetryAnalyzer(); }
Source:
<code>public void getYouViewVersionCridJson(HttpServletResponse response, @RequestParam(value = "pid", required = true) String pid) throws IOException { <START> response.setContentType("application/json"); <END> serializeJSON(response, outputForPid(pid)); }</code><technical_language>com.metabroadcast.common.media.MimeType</technical_language>

Target:
public void getYouViewVersionCridJson(HttpServletResponse response, @RequestParam(value = "pid", required = true) String pid) throws IOException { response.setContentType(MimeType.APPLICATION_JSON.toString()); serializeJson(response, outputForPid(pid)); }
Source:
<code><START> protected Span takeLocalSpanWithError(String errorTag) <END> throws InterruptedException { Span result = takeSpanWithError(errorTag); assertLocalSpan(result); return result; }</code><technical_language>I if this results in permutations. thinking of adding BraveAssertions allow java assertThat(takeSpan()).isLocal().hasError("failed"); do :) wondering of idea</technical_language>

Target:
protected Span takeLocalSpanWithError(String errorTag) throws InterruptedException { Span result = doTakeSpan(errorTag, false); assertLocalSpan(result); return result; }
Source:
<code>public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { <START> Map<String, ClockService> monitors = Maps.toMap( <END> remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); return new ClockSkewMonitor( monitors, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("clock-skew-monitor", true)), new ClockServiceImpl()); }</code><technical_language>[nit] rename this clocksByServer consistency</technical_language>

Target:
public static ClockSkewMonitor create(Set<String> remoteServers, Optional<SSLSocketFactory> optionalSecurity) { Map<String, ClockService> clocksByServer = Maps.toMap( remoteServers, (remoteServer) -> AtlasDbHttpClients.createProxy(optionalSecurity, remoteServer, ClockService.class)); return new ClockSkewMonitor( clocksByServer, new ClockSkewEvents(AtlasDbMetrics.getMetricRegistry()), Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("clock-skew-monitor", true)), new ClockServiceImpl()); }
Source:
<code>public void testAbstractQueueDecoratorRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().remove(); fail("Queue.remove should throw NoSuchElementException"); <START> } catch (final NoSuchElementException e) { <END> } resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().remove(); final boolean success = getConfirmed().remove(element); assertTrue("remove should return correct element", success); verify(); } try { getCollection().element(); fail("Queue.remove should throw NoSuchElementException"); } catch (final NoSuchElementException e) { } }</code><technical_language>Please JUnit 5's assertThrows() in new tests</technical_language>

Target:
public void testAbstractQueueDecoratorRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().remove(); }); assertNull(exception.getMessage()); resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().remove(); final boolean success = getConfirmed().remove(element); assertTrue("remove should return correct element", success); verify(); } Exception noSuchElementException = assertThrows(NoSuchElementException.class, () -> { getCollection().element(); }); assertNull(noSuchElementException.getMessage()); }
Source:
<code>public String generateForm(Schema<?> schema) { Map<String, Schema> properties = schema.getProperties(); if (properties != null) { <START> String value = ""; <END> for (Map.Entry<String, Schema> property : properties.entrySet()) { value += property.getKey(); value += FORMSYNTAX.get(Element.INNER_SEPARATOR); value += dataGenerator.generateValue(property.getKey(), property.getValue(), true); value += FORMSYNTAX.get(Element.OUTER_SEPARATOR); } return value.substring(0, value.length() - 1); } return ""; }</code><technical_language>a StringBuilder</technical_language>

Target:
public String generateForm(Schema<?> schema) { Map<String, Schema> properties = schema.getProperties(); if (properties != null) { StringBuilder formData = new StringBuilder(); for (Map.Entry<String, Schema> property : properties.entrySet()) { formData.append(urlEncode(property.getKey())); formData.append(FORMSYNTAX.get(Element.INNER_SEPARATOR)); formData.append( urlEncode( dataGenerator.generateValue( property.getKey(), property.getValue(), true))); formData.append(FORMSYNTAX.get(Element.OUTER_SEPARATOR)); } return formData.substring(0, formData.length() - 1); } return ""; }
Source:
<code>public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); <START> Exec.getReporter(Reporters.Type.EVENT_LOG).report(Reporters.ReportLevel.INFO, ImmutableMap.<String, Object>of("foo", "bar")); <END> List<String> files = listFiles(task); log.info("Loading files {}", files); task.setFiles(files); int taskCount = task.getFiles().size(); return resume(task.dump(), taskCount, control); }</code><technical_language>Is this a testing statement</technical_language>

Target:
public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); List<String> files = listFiles(task); log.info("Loading files {}", files); task.setFiles(files); int taskCount = task.getFiles().size(); return resume(task.dump(), taskCount, control); }
Source:
<code>public void testPrepareStub() throws IOException { <START> System.out.println("prepareStub"); <END> File originProject = new File("src/test/resources/arith_funcs/"); File targetFolder = createTemporaryCopyOf(originProject); ExerciseBuilder instance = new ExerciseBuilder(); instance.prepareStub(targetFolder.toPath()); File expectedFolder = new File("src/test/resources/arith_funcs_stub/src"); File outputFolder = new File(targetFolder.getAbsolutePath() + "/src"); Map<String, File> expectedFiles = getFileMap(expectedFolder); Map<String, File> actualFiles = getFileMap(outputFolder); for(String fileName : expectedFiles.keySet()) { File expected = expectedFiles.get(fileName); File actual = actualFiles.get(fileName); List<String> expectedLines = FileUtils.readLines(expected); List<String> actualLines = FileUtils.readLines(actual); for (int i = 0 ; i < expectedLines.size() ; ++i) { String expectedLine = expectedLines.get(i); String actualLine = actualLines.get(i); assertEquals("Line in file " + fileName + " did not match ", expectedLine, actualLine); } } }</code><technical_language>remove</technical_language>

Target:
public void testPrepareStub() throws IOException { System.out.println("prepareStub"); File originProject = new File("src/test/resources/arith_funcs/"); File targetFolder = createTemporaryCopyOf(originProject); ExerciseBuilder instance = new ExerciseBuilder(); File expectedFolder = new File("src/test/resources/arith_funcs_stub/src"); File outputFolder = new File(targetFolder.getAbsolutePath() + "/src"); instance.prepareStub(targetFolder.toPath()); assertFileLines(expectedFolder, outputFolder); }
Source:
<code>private int nextCorrelationId() { <START> if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; <END> return correlationId++; }</code><technical_language>before, this if-then-else increment for if case</technical_language>

Target:
int nextCorrelationId() { if (!isReserved(correlationId)) correlationId = MIN_RESERVED_CORRELATION_ID; return correlationId++; }
Source:
<code>protected void onHandleIntent(Intent intent) { try { <START> handler = new SwrveGcmHandler(this); <END> handler.onHandleIntent(intent); } finally { SwrveGcmBroadcastReceiver.completeWakefulIntent(intent); } }</code><technical_language>create handler onCreate instead of intent</technical_language>

Target:
protected void onHandleIntent(Intent intent) { try { handler.onHandleIntent(intent, GoogleCloudMessaging.getInstance(this)); } finally { SwrveGcmBroadcastReceiver.completeWakefulIntent(intent); } }
Source:
<code>public void onPushBlock(StreamBlockId streamBlockId, ArrayBuffer<?> dataBuffer) { store(dataBuffer); LinkedList<MessageHeaders> headersListToAck = new LinkedList<MessageHeaders>(); for (int i = 0; i < dataBuffer.size(); i++) { try { headersListToAck.add(headersList.take()); } <START> catch (InterruptedException ie) { <END> logger.error("Interrupted exception while getting message headers from the local blocking queue."); } } ((MessageBusSupport) messageBus).doManualAck(headersListToAck); }</code><technical_language>catch InterruptedException invoke Thread.currentThread().interrupt()</technical_language>

Target:
public void onPushBlock(StreamBlockId streamBlockId, ArrayBuffer<?> dataBuffer) { store(dataBuffer); LinkedList<MessageHeaders> headersListToAck = new LinkedList<MessageHeaders>(); for (int i = 0; i < dataBuffer.size(); i++) { try { headersListToAck.add(headersList.take()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } ((MessageBusSupport) messageBus).doManualAck(headersListToAck); }
Source:
<code>public void getEnabledSendingEndPointByAddress_returnEndpoint_whenNetmaskIsUsed() throws DotDataException { PublishingEndPoint endPoint = createPublishingEndPoint("10", "G03", "Netmask Endpoint", "192.168.1.0/24", "90", "http", true, "123456", true); api.saveEndPoint(endPoint); <START> assertNotNull(api.findEnabledSendingEndPointByAddress("192.168.1.60")); <END> api.deleteEndPointById(endPoint.getId()); }</code><technical_language>assert a bit more, check if ids of endpoints</technical_language>

Target:
public void getEnabledSendingEndPointByAddress_returnEndpoint_whenNetmaskIsUsed() throws DotDataException { PublishingEndPoint endPoint, endPointResult; endPoint = createPublishingEndPoint("10", "G03", "Netmask Endpoint", "192.168.1.0/24", "90", "http", true, "123456", true); api.saveEndPoint(endPoint); validateEndPoint(endPoint, "192.168.1.60"); }
Source:
<code>static List<Class<?>> getClassNamesInJarPackage(ClassLoader loader, String jarName, String packageName) throws MalformedURLException { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); packageName = packageName.replaceAll("\\.", "/"); JarInputStream jarFileInputStream = null; try { jarFileInputStream = new JarInputStream(new FileInputStream(jarName)); JarEntry jarEntry; while (true) { jarEntry = jarFileInputStream.getNextJarEntry(); if (jarEntry == null) break; if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) { classes.add(loader.loadClass(jarEntry.getName().replaceAll("/", "\\.").replace(".class", ""))); } <START> } <END> jarFileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(jarFileInputStream != null) { jarFileInputStream.close(); } } catch (IOException e) { } } return classes; }</code><technical_language>in finally</technical_language>

Target:
static List<Class<?>> getClassNamesInJarPackage(ClassLoader loader, String jarName, String packageName) throws MalformedURLException { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); packageName = packageName.replaceAll("\\.", "/"); JarInputStream jarFileInputStream = null; try { jarFileInputStream = new JarInputStream(new FileInputStream(jarName)); JarEntry jarEntry; while (true) { jarEntry = jarFileInputStream.getNextJarEntry(); if (jarEntry == null) break; if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) { classes.add(loader.loadClass(jarEntry.getName().replaceAll("/", "\\.").replace(".class", ""))); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if(jarFileInputStream != null) { jarFileInputStream.close(); } } catch (IOException e) { } } return classes; }
Source:
<code><START> public void testFileIsEmpty() throws Exception { <END> params = new String[1]; params[0] = "/Users/zeinebzhioua/Downloads/a.xml"; new SubmitJobCommand(params).execute(currentContextMock); assertThat(stack.get(0).getMessage(), is("'" + params[0] + "' is empty.")); Mockito.verify(schedulerRestClientMock, times(0)).submitJobArchive(anyString(), anyObject(), anyObject()); throw stack.get(0); }</code><technical_language>improve naming well</technical_language>

Target:
public void testFileIsEmpty() throws Exception { params = new String[1]; params[0] = System.getProperty("user.dir") + "/src/test/java/config/empty.xml"; new SubmitJobCommand(params).execute(currentContextMock); assertThat(stack.get(0).getMessage(), is("'" + params[0] + "' is empty.")); Mockito.verify(schedulerRestClientMock, times(0)) .submitJobArchive(anyString(), convertObjectToInputStream(anyObject()), anyMap()); throw stack.get(0); }
Source:
<code>@VisibleForTesting Call<MwQueryResponse<LangLinks>> request(@NonNull Service service, @NonNull PageTitle title, @NonNull final Callback cb) { Call<MwQueryResponse<LangLinks>> call = service.langLinks(title.getPrefixedText()); call.enqueue(new retrofit2.Callback<MwQueryResponse<LangLinks>>() { @Override public void onResponse(Call<MwQueryResponse<LangLinks>> call, Response<MwQueryResponse<LangLinks>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, response.body().query().langLinks()); } else if (response.body().hasError()) { String errorTitle = response.body().getError().getTitle(); cb.failure(call, new MwApiException(response.body().getError())); L.e("API error fetching langlinks: " + errorTitle); <START> } <END> } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<LangLinks>> call, Throwable t) { cb.failure(call, t); } }); return call; }</code><technical_language>Consider a else case a callback is invoked! :] Consider frustration of callbacks invoked for Fresco bug difficulty of performing a client test knowing assert</technical_language>

Target:
@VisibleForTesting Call<MwQueryResponse<LangLinks>> request(@NonNull Service service, @NonNull PageTitle title, @NonNull final Callback cb) { Call<MwQueryResponse<LangLinks>> call = service.langLinks(title.getPrefixedText()); call.enqueue(new retrofit2.Callback<MwQueryResponse<LangLinks>>() { @Override public void onResponse(Call<MwQueryResponse<LangLinks>> call, Response<MwQueryResponse<LangLinks>> response) { if (response.isSuccessful()) { if (response.body().success()) { cb.success(call, response.body().query().langLinks()); } else if (response.body().hasError()) { String errorTitle = response.body().getError().getTitle(); cb.failure(call, new MwApiException(response.body().getError())); L.e("API error fetching langlinks: " + errorTitle); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } } @Override public void onFailure(Call<MwQueryResponse<LangLinks>> call, Throwable t) { cb.failure(call, t); } }); return call; }
Source:
<code><START> protected String render (Object item) { <END> return null; }</code><technical_language>Experimental this well</technical_language>

Target:
protected String render (Object item) throws InterruptedException { return null; }
Source:
<code>private void mayTriggerRefresh(RepositoryEvent e) { synchronized (repositoriesChanged) { repositoriesChanged.add(e.getRepository()); } <START> if (!isRefreshOnlyWhenActive() || isActive()) { <END> triggerRefresh(); } }</code><technical_language>Nit: this is a completely unrelated change done in a separate commit</technical_language>

Target:
private void mayTriggerRefresh(RepositoryEvent e) { synchronized (repositoriesChanged) { repositoriesChanged.add(e.getRepository()); } if (!Activator.getDefault().getPreferenceStore() .getBoolean(UIPreferences.REFESH_ONLY_WHEN_ACTIVE) || isActive()) { triggerRefresh(); } }
Source:
<code>public final void updateEntity() { <START> if (Config.allowExternalTickSpeedup || worldObj == null || worldObj.getTotalWorldTime() != lastUpdate) { <END> lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }</code><technical_language>if worldObj == null? This means this is called if world object is null..... I guess want ANDs here</technical_language>

Target:
public final void updateEntity() { if (Config.allowExternalTickSpeedup || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }
Source:
<code>private static final void transferStreams(InputStream source, OutputStream destination, long length, String path, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, length >= 0 ? 1 + (int) (length / buffer.length) : 1000); try { synchronized (buffer) { while (true) { int bytesRead = -1; try { bytesRead = source.read(buffer); } catch (IOException e) { String msg = NLS.bind(Messages.failedReadDuringWrite, path); Policy.error(EFS.ERROR_READ, msg, e); } try { if (bytesRead == -1) { destination.close(); break; } destination.write(buffer, 0, bytesRead); } catch (IOException e) { String msg = NLS.bind(Messages.couldNotWrite, path); Policy.error(EFS.ERROR_WRITE, msg, e); } <START> subMonitor.worked(1); <END> } } } finally { Policy.safeClose(source); Policy.safeClose(destination); } }</code><technical_language>Reporting progress while holding a lock is potentially deadlock-prone, IProgressMonitor is overridable interface acquire more locks. I this broken prior this patch, consider - - adding a TODO</technical_language>

Target:
private static final void transferStreams(InputStream source, OutputStream destination, long length, String path, IProgressMonitor monitor) throws CoreException { byte[] buffer = new byte[8192]; SubMonitor subMonitor = SubMonitor.convert(monitor, length >= 0 ? 1 + (int) (length / buffer.length) : 1000); try { while (true) { int bytesRead = -1; try { bytesRead = source.read(buffer); } catch (IOException e) { String msg = NLS.bind(Messages.failedReadDuringWrite, path); Policy.error(EFS.ERROR_READ, msg, e); } try { if (bytesRead == -1) { destination.close(); break; } destination.write(buffer, 0, bytesRead); } catch (IOException e) { String msg = NLS.bind(Messages.couldNotWrite, path); Policy.error(EFS.ERROR_WRITE, msg, e); } subMonitor.worked(1); } } finally { Policy.safeClose(source); Policy.safeClose(destination); } }
Source:
<code>public PutMember create(final GroupResource parent, final String id) throws RestApiException { <START> return put.get(); <END> }</code><technical_language>trick create is need convert String Account.Id in create embed view instance return caller. :-(</technical_language>

Target:
public PutMember create(final GroupResource parent, final String id) throws RestApiException { return new PutMember(put, Url.decode(id)); }
Source:
<code>private void checkWhetherToDisplayUserProjectRegistrationWizard() { ProjectPreferenceSetting projectSetting = preferences .getOrCreateProjectSetting(workspaceName); AbstractHandler newUserWizardHandler = new UserRegistrationWizardDialogHandler(); try { int statusCode = (int) newUserWizardHandler .execute(new ExecutionEvent()); savePreferenceStoreIfNeeded(); <START> if (statusCode == Window.CANCEL && preferences.getUserId() == null) { <END> boolean shouldRegisterAnonymously = MessageDialog.openQuestion( null, "WatchDog not active!", WATCHDOG_UNREGISTERED_WARNING); if (shouldRegisterAnonymously) { makeSilentRegistration(); } else { userProjectRegistrationCancelled = true; preferences.registerProjectUse( WatchDogUtils.getWorkspaceName(), false); } } } catch (ExecutionException exception) { WatchDogLogger.getInstance().logSevere(exception); } }</code><technical_language>check for UID (also) PID</technical_language>

Target:
private void checkWhetherToDisplayUserProjectRegistrationWizard() { ProjectPreferenceSetting projectSetting = preferences .getOrCreateProjectSetting(workspaceName); if (!WatchDogUtils.isEmpty(preferences.getUserId()) || (projectSetting.startupQuestionAsked && !projectSetting.enableWatchdog)) return; AbstractHandler newUserWizardHandler = new UserRegistrationWizardDialogHandler(); try { int statusCode = (int) newUserWizardHandler .execute(new ExecutionEvent()); savePreferenceStoreIfNeeded(); if (statusCode == Window.CANCEL) { userProjectRegistrationCancelled = true; if (preferences.getUserId() == null || preferences.getOrCreateProjectSetting(workspaceName).projectId == null) { boolean shouldRegisterAnonymously = MessageDialog.openQuestion( null, "WatchDog not active!", WATCHDOG_UNREGISTERED_WARNING); if (shouldRegisterAnonymously) { makeSilentRegistration(); } else { preferences.registerProjectUse( WatchDogUtils.getWorkspaceName(), false); } } } } catch (ExecutionException exception) { WatchDogLogger.getInstance().logSevere(exception); } }
Source:
<code>private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTaskCount(); totalRunningTaskCount += runningTaskCount; <START> if (enqueueQueryWhenTaskLimitExceeded && totalRunningTaskCount > maxTotalRunningTaskCount) { resourceGroupManager.setTaskLimitExceeded(true); } if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } if (enqueueQueryWhenTaskLimitExceeded && totalRunningTaskCount <= maxTotalRunningTaskCount) { <END> resourceGroupManager.setTaskLimitExceeded(false); } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCount && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Query killed because the cluster is overloaded with too many tasks (%s) and this query was running with the highest number of tasks (%s). %s Otherwise, please try again later.", totalRunningTaskCount, highestRunningTaskCount, TOO_MANY_STAGES_MESSAGE))); queriesKilledDueToTooManyTask.incrementAndGet(); } }</code><technical_language>this logic simplified? like: if (enqueueQueryWhenTaskLimitExceeded) { resourceGroupManager.setTaskLimitExceeded(totalRunningTaskCount <= maxTotalRunningTaskCount); }</technical_language>

Target:
private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTaskCount(); totalRunningTaskCount += runningTaskCount; if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCountToKillQuery && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Query killed because the cluster is overloaded with too many tasks (%s) and this query was running with the highest number of tasks (%s). %s Otherwise, please try again later.", totalRunningTaskCount, highestRunningTaskCount, TOO_MANY_STAGES_MESSAGE))); queriesKilledDueToTooManyTask.incrementAndGet(); } }
Source:
<code>void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); <START> PlayerDomain domain1 = new PlayerDomain(domain); <END> Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, domain1, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaFreewheelManager fwManager = new OoyalaFreewheelManager(this, skinLayout.getAdView(), player); if (player.setEmbedCode(embedCode)) { } } }</code><technical_language>rename playerDomain</technical_language>

Target:
void completePlayerSetup(boolean asked) { if (asked) { skinLayout = (OoyalaSkinLayout) findViewById(R.id.ooyalaPlayer); PlayerDomain playerDomain = new PlayerDomain(domain); Options options = new Options.Builder().setShowNativeLearnMoreButton(false).setShowPromoImage(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(pcode, playerDomain, options); SkinOptions skinOptions = new SkinOptions.Builder().build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); playerLayoutController.addObserver(this); player.addObserver(this); @SuppressWarnings("unused") OoyalaFreewheelManager fwManager = new OoyalaFreewheelManager(this, skinLayout.getAdView(), player); if (player.setEmbedCode(embedCode)) { } } }
Source:
<code>public void startBackgroundTasks() { try { scheduler.schedule( itunesFileUpdater().withName("iTunes File Updater"), FOUR_AM ); <START> if (!Strings.isNullOrEmpty(localFilesPath)) { <END> scheduler.schedule( new ItunesEpfUpdateTask( new LatestEpfDataSetSupplier(new File(localFilesPath)), contentDeactivator(), contentWriter, log ).withName("iTunes EPF Updater"), FIVE_AM); log.record(infoEntry() .withDescription("iTunes EPF update task installed (%s)", localFilesPath) .withSource(getClass()) ); } else { log.record(infoEntry() .withDescription("iTunes EPF update task not installed", localFilesPath) .withSource(getClass()) ); } } catch (Exception e) { log.record(infoEntry() .withDescription("iTunes EPF update task installed failed") .withSource(getClass()) .withCause(e)); } }</code><technical_language>Is case legitimate for start Atlas a null localFilesPath? If is good reason for this remove checkArgument(!Strings.isNullOrEmpty(localFilesPath)); instead</technical_language>

Target:
public void startBackgroundTasks() { checkArgument(!Strings.isNullOrEmpty(localFilesPath)); try { scheduler.schedule( itunesFileUpdater().withName("iTunes File Updater"), ITUNES_FILE_UPDATER ); log.record(infoEntry() .withDescription("iTunes File update task installed (%s)", localFilesPath) .withSource(getClass()) ); scheduler.schedule( new ItunesEpfUpdateTask( new LatestEpfDataSetSupplier(new File(localFilesPath)), contentDeactivator(), contentWriter, log ).withName("iTunes EPF Updater"), ITUNES_EPF_UPDATER ); log.record(infoEntry() .withDescription("iTunes EPF update task installed (%s)", localFilesPath) .withSource(getClass()) ); } catch (Exception e) { log.record(infoEntry() .withDescription("iTunes EPF update task installed failed") .withSource(getClass()) .withCause(e)); } }
Source:
<code>public Builder addPortRange(Integer start, Integer end) { <START> checkState(checkNotNull(start, "start") < checkNotNull(end, "end"), <END> "start of range must be lower than end of range"); this.ports.add(closed(start, end)); return this; }</code><technical_language>checkArgument? This a case for IllegalStateException</technical_language>

Target:
public Builder addPortRange(Integer start, Integer end) { checkArgument(checkNotNull(start, "start") < checkNotNull(end, "end"), "start of range must be lower than end of range but was [%d, %d]", start, end); this.ports.add(closed(start, end)); return this; }
Source:
<code>private void cancelGeoTagging() { Context context = getContext(); Intent intent = new Intent(context, GeoTagImagesService.class); intent.setAction(GeoTagImagesService.ACTION_CANCEL_GEOTAGGING); <START> getContext().startService(intent); <END> }</code><technical_language>@chaviw ensure getContext() is null, reuse context variable defined beginning of method</technical_language>

Target:
private void cancelGeoTagging() { Context context = getContext(); if (context != null) { Intent intent = new Intent(context, GeoTagImagesService.class); intent.setAction(GeoTagImagesService.ACTION_CANCEL_GEOTAGGING); context.startService(intent); } }
Source:
<code>private void <START> enforceAnyPermissionOf(String... <END> permissions) { for (String permission : permissions) { if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) { return; } } throw new SecurityException( "requires one of the " + String.join(", ", permissions) + " permissions"); }</code><technical_language>Weak suggestion rename this "enforceAtLeastOnePermissionOf". eliminate interpretation "enforce (any permission)" sounds code chooses some permission in list enforces held. pretty silly a relevant concern</technical_language>

Target:
private void enforceAnyPermissionOf(String... permissions) { for (String permission : permissions) { if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) { return; } } throw new SecurityException( "Requires one of the following permissions: " + String.join(", ", permissions) + "."); }