auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void displayText() { String name = getIntent().getExtras().getString("name"); String[] firstName = name.split(" "); <START> if (firstName.length > 1) { <END> requestReceiver.setText("Hi " + firstName[1] + " I'd like you to help me buy this items"); } requestReceiver.setText("Hi " + name + " I'd like you to help me buy this items"); }</code><technical_language>check length of firstName? if I registered name? I (in case have) fields for name name in DB</technical_language>

Target:
public void displayText() { requestReceiver.setVisibility(View.VISIBLE); String receiversName = getIntent().getExtras().getString("name"); String[] receiversFullName = receiversName.split(" "); if (receiversFullName.length > 1) { requestReceiver.setText("Hi " + receiversFullName[0] + " I'd like you to help me buy this item(s)"); } else { requestReceiver.setText("Hi " + receiversName + " I'd like you to help me buy this item(s)"); } }
Source:
<code>public static String gensalt(int log_rounds, SecureRandom random) { StringBuffer rs = new StringBuffer(); byte rnd[] = new byte[BCRYPT_SALT_LEN]; random.nextBytes(rnd); rs.append("$2a$"); if (log_rounds < 10) { rs.append("0"); } if (log_rounds > 30) { throw new IllegalArgumentException( "log_rounds exceeds maximum (30)"); } <START> rs.append(Integer.toString(log_rounds)).append("$") <END> .append(encode_base64(rnd, rnd.length)); return rs.toString(); }</code><technical_language>bad: StringBuilder.append(int) exists is optimized</technical_language>

Target:
public static String gensalt(int log_rounds, SecureRandom random) { StringBuffer rs = new StringBuffer(); byte rnd[] = new byte[BCRYPT_SALT_LEN]; random.nextBytes(rnd); rs.append("$2a$"); if (log_rounds < 10) { rs.append("0"); } if (log_rounds > 30) { throw new IllegalArgumentException( "log_rounds exceeds maximum (30)"); } rs.append(log_rounds).append("$") .append(encode_base64(rnd, rnd.length)); return rs.toString(); }
Source:
<code>public void savePluginXml() throws CoreException { <START> try (InputStream stream = XmlDocumentHelper.saveDocument(document)) { <END> if (pluginXml.exists()) { pluginXml.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); pluginXml.setContents(stream, false, true, new NullProgressMonitor()); } else { pluginXml.create(stream, false, new NullProgressMonitor()); } } catch (TransformerException e) { throw wrapException(e); } catch (IOException e) { wrapException(e); } }</code><technical_language>This is unrelated this change</technical_language>

Target:
public void savePluginXml() throws CoreException { try { InputStream stream = XmlDocumentHelper.saveDocument(document); if (pluginXml.exists()) { pluginXml.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); pluginXml.setContents(stream, false, true, new NullProgressMonitor()); } else { pluginXml.create(stream, false, new NullProgressMonitor()); } } catch (TransformerException e) { throw wrapException(e); } catch (IOException e) { wrapException(e); } }
Source:
<code>static void cleanup(){ <START> <END> final String ver = org.sqlite.SQLiteJDBCLoader.getVersion(); String tempFolder = new java.io.File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); java.io.File dir = new java.io.File(tempFolder); java.io.File files = dir.listFiles(new java.io.FilenameFilter() { @Override public boolean accept(java.io.File dir, String name) { return name.startsWith("sqlite-" + ver); } }); for (java.io.File tempFile : files) { if(tempFile.getName().indexOf(".lck") > 0) { continue; } java.io.File lckFile = new java.io.File(tempFile.getName() + ".lck"); if(!lckFile.exists()) { try{ tempFile.delete(); } catch(SecurityException ex){ } } } }</code><technical_language>remove this line</technical_language>

Target:
static void cleanup() { String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); File dir = new File(tempFolder); File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(searchPattern); } }); if(files != null) { for (File tempFile : files) { if(tempFile.getName().indexOf(".lck") > 0) { continue; } File lckFile = new File(tempFile.getName() + ".lck"); if(!lckFile.exists()) { try { tempFile.delete(); } catch (SecurityException e) { System.err.println("Fail deleting old native lib" + e.getMessage()); } } } } }
Source:
<code>public UpdateStack build() { UpdateStack result = new AutoValue_UpdateStack( this.template != null ? template : null, <START> this.templateUrl != null ? templateUrl : null, <END> parameters != null ? ImmutableMap.copyOf(this.parameters) : null); return result; }</code><technical_language>Remove redundant null checks</technical_language>

Target:
public UpdateStack build() { UpdateStack result = new AutoValue_UpdateStack( this.template, this.templateUrl, parameters != null ? ImmutableMap.copyOf(this.parameters) : null); return result; }
Source:
<code>public void initialize(IPath containerPath, IJavaProject project) throws CoreException { String[] jars = Util.getJavaClassLibs(); IClasspathEntry[] entries = new IClasspathEntry[jars.length]; IClasspathAttribute[] extraAttributes; if (jars.length == 1 && (jars[0].endsWith("jrt-fs.jar") || JavaModelManager.isJrtInstallation(jars[0]))) { <START> extraAttributes = <END> ClasspathEntry.NO_EXTRA_ATTRIBUTES; entries[0] = JavaCore.newJrtEntry((new Path(jars[0])).removeLastSegments(2), null, null, ClasspathEntry.NO_ACCESS_RULES, extraAttributes, false ); } else { for (int i = 0; i < jars.length; i++) { if (RT_JAR_ANNOTATION_PATH != null && jars[i].endsWith("rt.jar")) { extraAttributes = externalAnnotationExtraAttributes(RT_JAR_ANNOTATION_PATH); } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } entries[i] = JavaCore.newLibraryEntry(new Path(jars[i]), null, null, ClasspathEntry.NO_ACCESS_RULES, extraAttributes, false ); } } JavaCore.setClasspathContainer( new Path(TEST_CONTAINER_NAME), new IJavaProject[]{ project }, new IClasspathContainer[] { new TestContainer(new Path(TEST_CONTAINER_NAME), entries) }, null); }</code><technical_language>external annotation path, here</technical_language>

Target:
public void initialize(IPath containerPath, IJavaProject project) throws CoreException { String[] jars = Util.getJavaClassLibs(); IClasspathEntry[] entries = new IClasspathEntry[jars.length]; IClasspathAttribute[] extraAttributes; if (jars.length == 1 && (jars[0].endsWith("jrt-fs.jar") || JavaModelManager.isJrtInstallation(jars[0]))) { if (RT_JAR_ANNOTATION_PATH != null) { extraAttributes = externalAnnotationExtraAttributes(RT_JAR_ANNOTATION_PATH); } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } extraAttributes = externalAnnotationExtraAttributes(RT_JAR_ANNOTATION_PATH); entries[0] = JavaCore.newJrtEntry((new Path(jars[0])).removeLastSegments(2), null, null, ClasspathEntry.NO_ACCESS_RULES, extraAttributes, false ); } else { for (int i = 0; i < jars.length; i++) { if (RT_JAR_ANNOTATION_PATH != null && jars[i].endsWith("rt.jar")) { extraAttributes = externalAnnotationExtraAttributes(RT_JAR_ANNOTATION_PATH); } else { extraAttributes = ClasspathEntry.NO_EXTRA_ATTRIBUTES; } entries[i] = JavaCore.newLibraryEntry(new Path(jars[i]), null, null, ClasspathEntry.NO_ACCESS_RULES, extraAttributes, false ); } } JavaCore.setClasspathContainer( new Path(TEST_CONTAINER_NAME), new IJavaProject[]{ project }, new IClasspathContainer[] { new TestContainer(new Path(TEST_CONTAINER_NAME), entries) }, null); }
Source:
<code>public String cadenceToString(int cadence) { numberFormat.setMaximumFractionDigits(0); <START> return numberFormat.format(cadence) + " r|spm"; <END> }</code><technical_language>unit name "r|spm" is geeky - programmer or-sign. typical user. I prefer unit name "rpm / spm". in diagram axis labels above</technical_language>

Target:
public String cadenceToString(int cadence) { numberFormat.setMaximumFractionDigits(0); return numberFormat.format(cadence) + " rpm / spm"; }
Source:
<code>public void testAddLabelAndAlias() throws JsonProcessingException { ItemDocument currentDocument = ItemDocumentBuilder.forItemId(Q1).build(); MonolingualTextValue label = Datamodel.makeMonolingualTextValue("strudel aux pommes", "fr"); MonolingualTextValue alias = Datamodel.makeMonolingualTextValue("Apfelstrudel", "fr"); TermStatementUpdate su = makeUpdate(currentDocument, Collections.singletonList(label), Collections.<MonolingualTextValue> emptyList(), Collections.singletonList(alias), Collections.<MonolingualTextValue> emptyList()); assertEquals(Collections.singleton("fr"), su.getLabelUpdates().keySet()); assertEquals(label.getText(), su.getLabelUpdates().get("fr").getText()); assertEquals(Collections.singleton("fr"), su.getAliasUpdates().keySet()); assertEquals(alias.getText(), su.getAliasUpdates().get("fr").get(0).getText()); assertTrue(su.getDescriptionUpdates().isEmpty()); <START> assertTrue(!su.isNull()); <END> }</code><technical_language>assertFalse more readable</technical_language>

Target:
public void testAddLabelAndAlias() throws JsonProcessingException { ItemDocument currentDocument = ItemDocumentBuilder.forItemId(Q1).build(); MonolingualTextValue label = Datamodel.makeMonolingualTextValue("strudel aux pommes", "fr"); MonolingualTextValue alias = Datamodel.makeMonolingualTextValue("Apfelstrudel", "fr"); TermStatementUpdate su = makeUpdate(currentDocument, Collections.singletonList(label), Collections.<MonolingualTextValue> emptyList(), Collections.singletonList(alias), Collections.<MonolingualTextValue> emptyList()); assertEquals(Collections.singleton("fr"), su.getLabelUpdates().keySet()); assertEquals(label.getText(), su.getLabelUpdates().get("fr").getText()); assertEquals(Collections.singleton("fr"), su.getAliasUpdates().keySet()); assertEquals(alias.getText(), su.getAliasUpdates().get("fr").get(0).getText()); assertTrue(su.getDescriptionUpdates().isEmpty()); assertFalse(su.isEmptyEdit()); }
Source:
<code>Set<SinkRecordField> missingFields(Collection<SinkRecordField> fields, Set<String> dbColumnNames) { final Set<SinkRecordField> missingFields = new HashSet<>(); for (SinkRecordField field : fields) { if (!dbColumnNames.contains(field.name())) { missingFields.add(field); } } Set<String> columnNamesLowerCase = new HashSet<>(); for (String columnName: dbColumnNames) { columnNamesLowerCase.add(columnName.toLowerCase()); } if (columnNamesLowerCase.size() != dbColumnNames.size()) { log.warn("Table has column names which differ only with case sensitivity. Original " <START> + "columns={}", dbColumnNames); <END> } final Set<SinkRecordField> missingFieldsIgnoreCase = new HashSet<>(); for (SinkRecordField missing: missingFields) { if (!columnNamesLowerCase.contains(missing.name().toLowerCase())) { missingFieldsIgnoreCase.add(missing); } } if (missingFieldsIgnoreCase.size() > 0) { log.info( "Unable to find fields among column names {}", missingFieldsIgnoreCase, dbColumnNames ); } return missingFieldsIgnoreCase; }</code><technical_language>wording: Table column names differ field names case. Original ..</technical_language>

Target:
Set<SinkRecordField> missingFields(Collection<SinkRecordField> fields, Set<String> dbColumnNames) { final Set<SinkRecordField> missingFields = new HashSet<>(); for (SinkRecordField field : fields) { if (!dbColumnNames.contains(field.name())) { missingFields.add(field); } } if (missingFields.isEmpty()) { return missingFields; } Set<String> columnNamesLowerCase = new HashSet<>(); for (String columnName: dbColumnNames) { columnNamesLowerCase.add(columnName.toLowerCase()); } if (columnNamesLowerCase.size() != dbColumnNames.size()) { log.warn( "Table has column names that differ only by case. Original columns={}", dbColumnNames ); } final Set<SinkRecordField> missingFieldsIgnoreCase = new HashSet<>(); for (SinkRecordField missing: missingFields) { if (!columnNamesLowerCase.contains(missing.name().toLowerCase())) { missingFieldsIgnoreCase.add(missing); } } if (missingFieldsIgnoreCase.size() > 0) { log.info( "Unable to find fields among column names {}", missingFieldsIgnoreCase, dbColumnNames ); } return missingFieldsIgnoreCase; }
Source:
<code>private String getBranch(final String jobName, final StaplerRequest req) { final String json = req.getParameter("json"); final JSONObject formData = JSONObject.fromObject(json); final TeamBuildPayload payload = EndpointHelper.MAPPER.convertValue(formData, TeamBuildPayload.class); String sourceBranch = payload.BuildVariables.get(QUEUEJOBTASK_MULTIBRANCH_JOB_BRANCH); if (sourceBranch == null || sourceBranch.trim().isEmpty()) { if (jobName.indexOf('/') > 0) { sourceBranch = jobName.substring(jobName.indexOf('/') + 1); } else { sourceBranch = payload.BuildVariables.get(BUILD_SOURCE_BRANCH); <START> } <END> } if (sourceBranch == null || sourceBranch.trim().isEmpty()) { throw new IllegalArgumentException("Could not find branch from job name. If building a multibranch" + "pipeline job, the job name should be in the format of '${multibranch pipeline name}/${branch}.'"); } try { return URLEncoder.encode(sourceBranch.replace("refs/heads/", ""), "UTF-8"); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode branch: " + sourceBranch, e); } }</code><technical_language>important, consider saving result of jobName.indexOf('/') instead of calling twice</technical_language>

Target:
private String getBranch(final String jobName, final StaplerRequest req) { final String json = req.getParameter("json"); final JSONObject formData = JSONObject.fromObject(json); final TeamBuildPayload payload = EndpointHelper.MAPPER.convertValue(formData, TeamBuildPayload.class); String sourceBranch = payload.BuildVariables.get(QUEUEJOBTASK_MULTIBRANCH_JOB_BRANCH); if (sourceBranch == null || sourceBranch.trim().isEmpty()) { final int idx = jobName.indexOf('/'); if (idx > 0) { sourceBranch = jobName.substring(idx + 1); } else { sourceBranch = payload.BuildVariables.get(BUILD_SOURCE_BRANCH); } } if (sourceBranch == null || sourceBranch.trim().isEmpty()) { throw new IllegalArgumentException("Could not find branch from job name. If building a multibranch" + "pipeline job, the job name should be in the format of '${multibranch pipeline name}/${branch}.'"); } try { return URLEncoder.encode(sourceBranch.replace("refs/heads/", ""), "UTF-8"); } catch (final UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode branch: " + sourceBranch, e); } }
Source:
<code>public void queueListeningTestCase() { try { jmsQueueTransportListener.start(queueListeningParameters); logger.info("JMS Transport Listener is starting to listen to the queue " + JMSTestConstants.QUEUE_NAME); jmsServer.publishMessagesToQueue(JMSTestConstants.QUEUE_NAME); Assert.assertEquals(queueTestMessageProcessor.getCount(), 10, "Expected message count is not received when " + "listening to queue " + JMSTestConstants.QUEUE_NAME); jmsQueueTransportListener.stop(); } catch (Exception e) { <START> Assert.fail("Error while listening to queue"); <END> } }</code><technical_language>Simply throwing error test case fail it. catch Assert fail</technical_language>

Target:
public void queueListeningTestCase() throws ServerConnectorException, InterruptedException, JMSException { jmsQueueTransportListener.start(queueListeningParameters); logger.info("JMS Transport Listener is starting to listen to the queue " + JMSTestConstants.QUEUE_NAME); jmsServer.publishMessagesToQueue(JMSTestConstants.QUEUE_NAME); Assert.assertEquals(queueTestMessageProcessor.getCount(), 10, "Expected message count is not received when " + "listening to queue " + JMSTestConstants.QUEUE_NAME); jmsQueueTransportListener.stop(); }
Source:
<code>public <TM> MessageStream<TM> flatMap(FlatMapFunction<? super M, ? extends TM> flatMapFn) { <START> StreamOperatorSpec<M, TM> op = OperatorSpecs.createFlatMapOperatorSpec(flatMapFn, this.graph.getNextOpId(OpCode.FLAT_MAP)); <END> this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }</code><technical_language>< 120 chars? Prefer older formatting (i.e. opId get call line) for consistency</technical_language>

Target:
public <TM> MessageStream<TM> flatMap(FlatMapFunction<? super M, ? extends TM> flatMapFn) { String opId = this.graph.getNextOpId(OpCode.FLAT_MAP); StreamOperatorSpec<M, TM> op = OperatorSpecs.createFlatMapOperatorSpec(flatMapFn, opId); this.operatorSpec.registerNextOperatorSpec(op); return new MessageStreamImpl<>(this.graph, op); }
Source:
<code>public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { TidAnalysisModule module = fModule.get(); if (module == null) { return null; } int count = 0; while (!module.isQueryable(time) && count < <START> 5) { <END> try { Thread.sleep(100); count++; } catch (InterruptedException e) { break; } } return module.getThreadOnCpuAtTime(cpu, time); }</code><technical_language>count = 5? msElapsed < 5 * wait Thread.sleep(wait); msElapsed += wait;</technical_language>

Target:
public @Nullable Integer getThreadOnCpuAtTime(int cpu, long time) { TidAnalysisModule module = fModule.get(); if (module == null) { return null; } int wait = 0; while (!module.isQueryable(time) && wait < WAIT_TIMEOUT) { try { Thread.sleep(100); wait += 100; } catch (InterruptedException e) { break; } } return module.getThreadOnCpuAtTime(cpu, time); }
Source:
<code>public void exec(final MainRemote.Script script) throws Exception { final File file = File.createTempFile("takes-", ".txt"); file.delete(); final Method method = this.app.getDeclaredMethod( "main", String[].class ); final String[] passed = new String[1 + this.args.length]; passed[0] = String.format("--port=%s", file.getAbsoluteFile()); for (int idx = 0; idx < this.args.length; ++idx) { passed[idx + 1] = this.args[idx]; } final Thread thread = new Thread( new MainRemoteRunnable(method, passed) ); thread.start(); try { script.exec( URI.create( String.format( "http://localhost:%d", MainRemote.port(file) ) ) ); } finally { if (!file.delete()) { <START> throw new HttpException( <END> HttpURLConnection.HTTP_BAD_REQUEST, "Can not delete file" ); } thread.interrupt(); } }</code><technical_language>@sebing I throw IOException</technical_language>

Target:
public void exec(final MainRemote.Script script) throws Exception { final File file = File.createTempFile("takes-", ".txt"); file.delete(); final Method method = this.app.getDeclaredMethod( "main", String[].class ); final String[] passed = new String[1 + this.args.length]; passed[0] = String.format("--port=%s", file.getAbsoluteFile()); for (int idx = 0; idx < this.args.length; ++idx) { passed[idx + 1] = this.args[idx]; } final Thread thread = new Thread( new Runnable() { @Override public void run() { try { method.invoke(null, (Object) passed); } catch (final InvocationTargetException ex) { throw new IllegalStateException(ex); } catch (final IllegalAccessException ex) { throw new IllegalStateException(ex); } } } ); thread.start(); try { script.exec( URI.create( String.format( "http://localhost:%d", MainRemote.port(file) ) ) ); } finally { file.delete(); thread.interrupt(); } }
Source:
<code>public void rollback(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { <START> LOG.trace("DummyXAResource.rollback(xid=" + xid + ")"); <END> } }</code><technical_language>info</technical_language>

Target:
public void rollback(Xid xid) throws XAException { LOG.info("DummyXAResource.rollback(xid=" + xid + ")"); }
Source:
<code>public DeviceInactivePage getInactiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("after") final Long afterTimestamp, @QueryParam("before") final Long beforeTimestamp, @QueryParam("limit") final Integer limit) { InactiveDevicesPaginator redisPaginator; <START> if (limit == null) { <END> redisPaginator = new InactiveDevicesPaginator(jedisPool, afterTimestamp, beforeTimestamp, ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY); } else { redisPaginator = new InactiveDevicesPaginator(jedisPool, afterTimestamp, beforeTimestamp, ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, limit); } return redisPaginator.generatePage(); }</code><technical_language>max for limit</technical_language>

Target:
public DeviceInactivePage getInactiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("after") final Long afterTimestamp, @QueryParam("before") final Long beforeTimestamp, @QueryParam("limit") final Integer limit) { return new InactiveDevicesPaginator(jedisPool, afterTimestamp, beforeTimestamp, ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, limit) .generatePage(); }
Source:
<code><START> public StoredConfig getSystemConfig() { <END> if (systemConfig.isOutdated()) { try { LOG.debug("loading system config {}", systemConfig); systemConfig.load(); } catch (IOException e) { throw new RuntimeException(e); } catch (ConfigInvalidException e) { throw new RuntimeException( MessageFormat.format( JGitText.get().systemConfigFileInvalid, systemConfig.getFile().getAbsolutePath(), e), e); } } return systemConfig; }</code><technical_language>Propagate IOE ConfigInvalidException instead of translating RuntimeException? happy this translation -- unclear effects be. If propagate checked exceptions, caller do it. callers catch IOE ConfigInvalidException load()</technical_language>

Target:
public StoredConfig getSystemConfig() throws IOException, ConfigInvalidException { if (systemConfig.isOutdated()) { try { LOG.debug("loading system config {}", systemConfig); systemConfig.load(); } catch (ConfigInvalidException e) { LOG.error(MessageFormat.format( JGitText.get().systemConfigFileInvalid, systemConfig.getFile().getAbsolutePath()), e); throw e; } } return systemConfig; }
Source:
<code>private String getColumnString(boolean uppercase, ImmutableList.Builder<String> columnNames, ImmutableList.Builder<Type> columnTypes, ColumnMetadata column) { String columnName = column.getName(); if (uppercase) { columnName = columnName.toUpperCase(ENGLISH); } columnNames.add(columnName); columnTypes.add(column.getType()); StringBuilder sb = new StringBuilder() .append(quoted(columnName)) .append(" ") .append(toSqlType(column.getType())); if (!column.isNullable()) { <START> sb.append(" ").append("NOT NULL"); <END> } if (column.getDefaultValue() != null) { sb.append(" DEFAULT ").append(objectToValue(column.getType(), column.getDefaultValue())); } return sb.toString(); }</code><technical_language>nit:sb.append(" NULL")</technical_language>

Target:
private String getColumnString(boolean uppercase, ImmutableList.Builder<String> columnNames, ImmutableList.Builder<Type> columnTypes, ColumnMetadata column) { String columnName = column.getName(); if (uppercase) { columnName = columnName.toUpperCase(ENGLISH); } columnNames.add(columnName); columnTypes.add(column.getType()); StringBuilder sb = new StringBuilder() .append(quoted(columnName)) .append(" ") .append(toSqlType(column.getType())); if (!column.isNullable()) { sb.append(" NOT NULL"); } if (column.getDefaultValue() != null) { sb.append(" DEFAULT ").append(toLiteral(column.getType(), column.getDefaultValue())); } return sb.toString(); }
Source:
<code>protected void onInitUI() { super.onInitUI(); setPageTitle(Util.C.groupListTitle()); groups = new GroupTable(true , PageLinks.ADMIN_GROUPS); add(groups); final VerticalPanel fp = new VerticalPanel(); fp.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); fp.add(new SmallHeading(Util.C.headingCreateGroup())); addTxt = new NpTextBox(); addTxt.setVisibleLength(60); addTxt.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doCreateGroup(); } } }); <START> addTxt.addKeyUpHandler(new KeyUpHandler() { <END> @Override public void onKeyUp(KeyUpEvent event) { addNew.setEnabled(!addTxt.getText().trim().isEmpty()); } }); fp.add(addTxt); addNew = new Button(Util.C.buttonCreateGroup()); addNew.setEnabled(false); addNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doCreateGroup(); } }); fp.add(addNew); add(fp); }</code><technical_language>This OnEditEnabler class. fix cherry-pick</technical_language>

Target:
protected void onInitUI() { super.onInitUI(); setPageTitle(Util.C.groupListTitle()); groups = new GroupTable(true , PageLinks.ADMIN_GROUPS); add(groups); final VerticalPanel fp = new VerticalPanel(); fp.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); fp.add(new SmallHeading(Util.C.headingCreateGroup())); addTxt = new NpTextBox(); addTxt.setVisibleLength(60); addTxt.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(KeyPressEvent event) { if (event.getCharCode() == KeyCodes.KEY_ENTER) { doCreateGroup(); } } }); fp.add(addTxt); addNew = new Button(Util.C.buttonCreateGroup()); addNew.setEnabled(false); addNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doCreateGroup(); } }); fp.add(addNew); add(fp); new OnEditEnabler(addNew, addTxt); }
Source:
<code>public static void trySkipCache(int fd, long offset, long len) { if (!initialized || !fadvisePossible || fd < 0) { return; } try { posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); } catch (UnsupportedOperationException uoe) { LOG.warn("posix_fadvise is not supported : ", uoe); fadvisePossible = false; } catch (UnsatisfiedLinkError ule) { LOG.warn("Unsatisfied Link error: posix_fadvise failed on file descriptor {}, offset : ", <START> new Object[] {fd, offset, ule}); <END> fadvisePossible = false; } catch (Exception e) { LOG.warn("Unknown exception: posix_fadvise failed on file descriptor {}, offset : ", new Object[] {fd, offset, e}); } }</code><technical_language>logging changes un-do this part</technical_language>

Target:
public static void trySkipCache(int fd, long offset, long len) { if (!initialized || !fadvisePossible || fd < 0) { return; } try { posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED); } catch (UnsupportedOperationException uoe) { log.warn(uoe, "posix_fadvise is not supported"); fadvisePossible = false; } catch (UnsatisfiedLinkError ule) { log.warn(ule, "Unsatisfied Link error: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); fadvisePossible = false; } catch (Exception e) { log.warn(e, "Unknown exception: posix_fadvise failed on file descriptor [%d], offset [%d]", fd, offset); } }
Source:
<code>final void fail(long now, Throwable throwable) { if (aborted) { tries++; failWithTimeout(now, throwable); return; } if ((throwable instanceof UnsupportedVersionException) && handleUnsupportedVersionException((UnsupportedVersionException) throwable)) { log.debug("{} attempting protocol downgrade and then retry.", this); runnable.enqueue(this, now); return; } tries++; nextAllowedTryMs = now + retryBackoffMs; if (calcTimeoutMsRemainingAsInt(now, deadlineMs) < 0) { <START> failWithTimeout(now, throwable); <END> return; } if (!(throwable instanceof RetriableException)) { if (log.isDebugEnabled()) { log.debug("{} failed with non-retriable exception after attempt(s)", this, tries, new Exception(prettyPrintException(throwable))); } handleFailure(throwable); return; } if (tries > maxRetries) { if (log.isDebugEnabled()) { log.debug("{} failed after attempt(s)", this, tries, new Exception(prettyPrintException(throwable))); } handleFailure(throwable); return; } if (log.isDebugEnabled()) { log.debug("{} failed: {}. Beginning retry #{}", this, prettyPrintException(throwable), tries); } runnable.enqueue(this, now); }</code><technical_language>Below, a case throw underlying exception if run out of retries. Is intentional</technical_language>

Target:
final void fail(long now, Throwable throwable) { if (aborted) { tries++; failWithTimeout(now, throwable); return; } if ((throwable instanceof UnsupportedVersionException) && handleUnsupportedVersionException((UnsupportedVersionException) throwable)) { log.debug("{} attempting protocol downgrade and then retry.", this); runnable.enqueue(this, now); return; } tries++; nextAllowedTryMs = now + retryBackoffMs; if (calcTimeoutMsRemainingAsInt(now, deadlineMs) < 0) { failWithTimeout(now, throwable); return; } if (!(throwable instanceof RetriableException)) { if (log.isDebugEnabled()) { log.debug("{} failed with non-retriable exception after attempt(s)", this, tries, new Exception(prettyPrintException(throwable))); } handleFailure(throwable); return; } if (tries > maxRetries) { failWithTimeout(now, throwable); return; } if (log.isDebugEnabled()) { log.debug("{} failed: {}. Beginning retry #{}", this, prettyPrintException(throwable), tries); } runnable.enqueue(this, now); }
Source:
<code>LedgerMetadataBuilder withEnsembleSize(int ensembleSize) { <START> checkState(ensembles.size() == 0, "Can only set ensemble size when ensembles is empty"); <END> this.ensembleSize = ensembleSize; return this; }</code><technical_language>this statement sounds making this class a "Mutator" a "Builder". clarify more here</technical_language>

Target:
LedgerMetadataBuilder withEnsembleSize(int ensembleSize) { checkState(ensembles.size() == 0, "Can only set ensemble size before adding ensembles to the builder"); this.ensembleSize = ensembleSize; return this; }
Source:
<code>public ProductProjectionQueryBuilder plusLocaleProjection(@Nullable final String localeProjection) { <START> if (this.localeProjection == null) { this.localeProjection = new ArrayList<>(); } <END> this.localeProjection.add(localeProjection); return this; }</code><technical_language>needed localProjection is initialized arraylist</technical_language>

Target:
public ProductProjectionQueryBuilder plusLocaleProjection(@Nullable final String localeProjection) { this.localeProjection.add(localeProjection); return this; }
Source:
<code>public abstract @Nullable PcapPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException; public abstract void skipNextPacket() throws IOException, BadPcapFileException; public abstract void seekPacket(long rank) throws IOException, BadPcapFileException; public abstract PcapTimestampScale getTimestampPrecision(); public abstract long getTimeAccuracy(); public abstract long getTimeZoneCorrection(); public abstract long getSnapShotLength(); <START> public abstract long getDataLinkType(); <END> public synchronized long getTotalNbPackets() throws IOException, BadPcapFileException { if (fTotalNumberPackets == -1) { long rank = fCurrentRank; fCurrentRank = fFileIndex.floorKey(rank); while (hasNextPacket()) { skipNextPacket(); } fTotalNumberPackets = fCurrentRank; fCurrentRank = rank; seekPacket(rank); } return fTotalNumberPackets; }</code><technical_language>methods in PcapOldFile. For PcapTrace.getProperties(), called instanceof PcapOldFile check. For PcapEventFactory.createEvent() needs link type, I suggest add a method PcapPacket.getDataLinkType(). For PcapOldPacket PcapOldFile, for PcapNgPacket interfaceId (could stored in PcapNgPacket)</technical_language>

Target:
public abstract @Nullable PcapPacket parseNextPacket() throws IOException, BadPcapFileException, BadPacketException; public abstract boolean skipNextPacket() throws IOException, BadPcapFileException; public void seekPacket(long rank) throws IOException, BadPcapFileException { if (rank < 0) { throw new IllegalArgumentException(); } TreeMap<Long, Long> fileIndex = getFileIndex(); Long positionInBytes = fileIndex.get(rank); if (positionInBytes != null) { getFileChannel().position(positionInBytes.longValue()); setCurrentRank(rank); } else { long floorRank = fileIndex.floorKey(rank); setCurrentRank(floorRank); positionInBytes = fileIndex.get(floorRank); if (positionInBytes != null) { getFileChannel().position(positionInBytes); while (getCurrentRank() < rank && skipNextPacket()) { } } } }
Source:
<code>public void query(final Query query, final int chunkSize, final Consumer<QueryResult> consumer) { if (version().startsWith("0.") || version().startsWith("1.0")) { throw new UnsupportedOperationException("chunking not supported"); } Call<ResponseBody> call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) { try { if (response.isSuccessful()) { BufferedSource source = response.body().source(); <START> QueryResult result = InfluxDBImpl.this.adapter.fromJson(source); <END> while (result != null) { consumer.accept(result); result = InfluxDBImpl.this.adapter.fromJson(source); } } try (ResponseBody errorBody = response.errorBody()) { throw new InfluxDBException(errorBody.string()); } } catch (EOFException e) { QueryResult queryResult = new QueryResult(); queryResult.setError("DONE"); consumer.accept(queryResult); } catch (IOException e) { QueryResult queryResult = new QueryResult(); queryResult.setError(e.toString()); consumer.accept(queryResult); } } @Override public void onFailure(final Call<ResponseBody> call, final Throwable t) { throw new InfluxDBException(t); } }); }</code><technical_language>is this implementation changed, unrelated want achieve</technical_language>

Target:
public void query(final Query query, final int chunkSize, final Consumer<QueryResult> consumer) { if (version().startsWith("0.") || version().startsWith("1.0")) { throw new UnsupportedOperationException("chunking not supported"); } Call<ResponseBody> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize, boundParameterQuery.getParameterJsonWithUrlEncoded()); } else { call = this.influxDBService.query(this.username, this.password, query.getDatabase(), query.getCommandWithUrlEncoded(), chunkSize); } call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) { try { if (response.isSuccessful()) { BufferedSource source = response.body().source(); while (true) { QueryResult result = InfluxDBImpl.this.adapter.fromJson(source); if (result != null) { consumer.accept(result); } } } try (ResponseBody errorBody = response.errorBody()) { throw new InfluxDBException(errorBody.string()); } } catch (EOFException e) { QueryResult queryResult = new QueryResult(); queryResult.setError("DONE"); consumer.accept(queryResult); } catch (IOException e) { QueryResult queryResult = new QueryResult(); queryResult.setError(e.toString()); consumer.accept(queryResult); } } @Override public void onFailure(final Call<ResponseBody> call, final Throwable t) { throw new InfluxDBException(t); } }); }
Source:
<code>private static void pushMethod(JoinPoint joinPoint) { CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); Class<?> clazz = codeSignature.getDeclaringType(); String methodName = codeSignature.getName(); String[] parameterNames = codeSignature.getParameterNames(); Object[] parameterValues = joinPoint.getArgs(); StringBuilder builder = new StringBuilder("⇢ "); builder.append(methodName).append('('); for (int i = 0; i < parameterValues.length; i++) { if (i > 0) { builder.append(", "); } builder.append(parameterNames[i]).append('='); appendObject(builder, parameterValues[i]); } builder.append(')'); <START> builder.append(" @Thread:").append(Thread.currentThread().getName()); <END> Log.d(asTag(clazz), builder.toString()); }</code><technical_language>show this if main thread? leaning no</technical_language>

Target:
private static void pushMethod(JoinPoint joinPoint) { CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); Class<?> clazz = codeSignature.getDeclaringType(); String methodName = codeSignature.getName(); String[] parameterNames = codeSignature.getParameterNames(); Object[] parameterValues = joinPoint.getArgs(); StringBuilder builder = new StringBuilder("⇢ "); builder.append(methodName).append('('); for (int i = 0; i < parameterValues.length; i++) { if (i > 0) { builder.append(", "); } builder.append(parameterNames[i]).append('='); appendObject(builder, parameterValues[i]); } builder.append(')'); if (!isMainThread()) { builder.append(" @Thread:").append(Thread.currentThread().getName()); } Log.d(asTag(clazz), builder.toString()); }
Source:
<code>private static Boolean loadContacts(Context context) { if (context == null) { return false; } if (MainApplication.contacts != null) { return true; } String jsonData = PreferenceUtils.getString(context, PreferenceUtils.KEY_CONTACTS); if (jsonData.isEmpty()) { return false; } try { MainApplication.contacts = JSONModel.createFromJson(jsonData, MainApplication.Contacts.class); } catch (IOException e) { MainApplication.contacts = new MainApplication.Contacts(); <START> e.printStackTrace(); <END> return false; } return true; }</code><technical_language>good log exception</technical_language>

Target:
private static Boolean loadContacts(Context context) { if (context == null) { return false; } if (MainApplication.contacts != null) { return true; } String jsonData = PreferenceUtils.getString(context, PreferenceUtils.KEY_CONTACTS); if (jsonData.isEmpty()) { return false; } try { MainApplication.contacts = JSONModel.createFromJson(jsonData, MainApplication.Contacts.class); } catch (IOException e) { MainApplication.contacts = new MainApplication.Contacts(); Log.e(TAG, "Reading contacts from JSON failed. Empty contacts created."); e.printStackTrace(); return false; } return true; }
Source:
<code>public Object getPropertyValue(Object id) { <START> if (id.equals(ID_FILE_NAME) && fSourceLookup.getCallsite().getFileName() != null) { <END> return fSourceLookup.getCallsite().getFileName(); } else if (id.equals(ID_FUNCTION_NAME)) { return fSourceLookup.getCallsite().getFunctionName(); } else if (id.equals(ID_LINE_NUMBER)) { return Long.valueOf(fSourceLookup.getCallsite().getLineNumber()); } return null; }</code><technical_language>useless null check (not supposed null, ok return null)</technical_language>

Target:
public Object getPropertyValue(Object id) { if (id.equals(ID_FILE_NAME)) { return fSourceLookup.getCallsite().getFileName(); } else if (id.equals(ID_FUNCTION_NAME)) { return fSourceLookup.getCallsite().getFunctionName(); } else if (id.equals(ID_LINE_NUMBER)) { return Long.valueOf(fSourceLookup.getCallsite().getLineNumber()); } return null; }
Source:
<code>TransportAmazonS3(final Repository local, final URIish uri) throws NotSupportedException { super(local, uri); Properties props = null; File propsFile = new File(local.getDirectory(), uri.getUser()); if (!propsFile.isFile()) <START> propsFile = new File(FS.DETECTED.userHome(), uri.getUser()); <END> if (propsFile.isFile()) { try { props = AmazonS3.properties(propsFile); } catch (IOException e) { throw new NotSupportedException("cannot read " + propsFile, e); } } else { props = new Properties(); props.setProperty("accesskey", uri.getUser()); props.setProperty("secretkey", uri.getPass()); } s3 = new AmazonS3(props); bucket = uri.getHost(); String p = uri.getPath(); if (p.startsWith("/")) p = p.substring(1); if (p.endsWith("/")) p = p.substring(0, p.length() - 1); keyPrefix = p; }</code><technical_language>this Repository's FS instance? in case detected Cygwin, application wants msysgit behavior? user's home directory Amazon S3 property files stored match home directory SSH configuration is stored in, is determined FS type</technical_language>

Target:
TransportAmazonS3(final Repository local, final URIish uri) throws NotSupportedException { super(local, uri); Properties props = null; File propsFile = new File(local.getDirectory(), uri.getUser()); if (!propsFile.isFile()) propsFile = new File(local.getFS().userHome(), uri.getUser()); if (propsFile.isFile()) { try { props = AmazonS3.properties(propsFile); } catch (IOException e) { throw new NotSupportedException("cannot read " + propsFile, e); } } else { props = new Properties(); props.setProperty("accesskey", uri.getUser()); props.setProperty("secretkey", uri.getPass()); } s3 = new AmazonS3(props); bucket = uri.getHost(); String p = uri.getPath(); if (p.startsWith("/")) p = p.substring(1); if (p.endsWith("/")) p = p.substring(0, p.length() - 1); keyPrefix = p; }
Source:
<code>public static void registerTags() { PropertyParser.<MaterialBamboo>registerTag("leaf_size", (attribute, material) -> { <START> return new ElementTag(String.valueOf(material.getBamboo().getLeaves())); <END> }); }</code><technical_language>name() stringify enum</technical_language>

Target:
public static void registerTags() { PropertyParser.<MaterialBamboo>registerTag("leaf_size", (attribute, material) -> { return new ElementTag(material.getBamboo().getLeaves().name()); }); }
Source:
<code>private void updateOffset(List<Update> updates) { OptionalLong ol = updates.stream().mapToLong(Update::getUpdateId).max(); if (ol.isPresent()) { this.offset = ol.getAsLong() + 1; <START> log.debug("Next Telegram offset will be " + this.offset); <END> } }</code><technical_language>{} placeholders in logger</technical_language>

Target:
private void updateOffset(List<Update> updates) { OptionalLong ol = updates.stream().mapToLong(Update::getUpdateId).max(); if (ol.isPresent()) { this.offset = ol.getAsLong() + 1; log.debug("Next Telegram offset will be {}", this.offset); } }
Source:
<code><START> List<TopicPartition> closeRevokedStandbyTasks(final Map<TaskId, Set<TopicPartition>> revokedTasks) { <END> final List<TopicPartition> revokedChangelogs = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> entry : revokedTasks.entrySet()) { final TaskId taskId = entry.getKey(); final Task task; if (running.containsKey(taskId)) { task = running.get(taskId); } else if (created.containsKey(taskId)) { task = created.get(taskId); } else { log.error("Could not find the standby task while closing it", taskId); continue; } try { task.close(true, false); } catch (final RuntimeException e) { log.error("Closing the failed due to the following error:", taskTypeName, task.id(), e); } finally { running.remove(taskId); revokedChangelogs.addAll(task.changelogPartitions()); } } return revokedChangelogs; }</code><technical_language>NVM I done :)</technical_language>

Target:
List<TopicPartition> closeRevokedStandbyTasks(final Map<TaskId, Set<TopicPartition>> revokedTasks) { log.debug("Closing revoked standby tasks {}", revokedTasks); final List<TopicPartition> revokedChangelogs = new ArrayList<>(); for (final Map.Entry<TaskId, Set<TopicPartition>> entry : revokedTasks.entrySet()) { final TaskId taskId = entry.getKey(); final Task task; if (running.containsKey(taskId)) { task = running.get(taskId); } else if (created.containsKey(taskId)) { task = created.get(taskId); } else { log.error("Could not find the standby task while closing it", taskId); continue; } try { task.close(true, false); } catch (final RuntimeException e) { log.error("Closing the failed due to the following error:", taskTypeName, task.id(), e); } finally { running.remove(taskId); revokedChangelogs.addAll(task.changelogPartitions()); } } return revokedChangelogs; }
Source:
<code>public void testEvaluationOrder() throws TransformationException { String evaluationorder = "scale/evaluationorder.scale"; String source = "12"; String transformedResponse = processor.transform(evaluationorder, source); Assert.assertEquals("first", transformedResponse); <START> <END> }</code><technical_language>leave out this newline, note is a notice in (upcoming) release of static code analysis</technical_language>

Target:
public void testEvaluationOrder() throws TransformationException { String evaluationOrder = "scale/evaluationorder.scale"; String source = "12"; String transformedResponse = processor.transform(evaluationOrder, source); Assert.assertEquals("first", transformedResponse); }
Source:
<code>public void testWithFilledSet() { final AlarmType alarmType = AlarmType.CLOCK_INVALID; final Set<AlarmType> alarmTypeSet = new TreeSet<>(); alarmTypeSet.add(alarmType); final AlarmRegister original = new AlarmRegister(alarmTypeSet); final com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister mapped = this.mapperFactory .getMapperFacade().map(original, com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister.class); assertNotNull(mapped); <START> assertEquals(original.getAlarmTypes().size(), mapped.getAlarmTypes().size()); <END> assertEquals(alarmType.name(), mapped.getAlarmTypes().get(0).name()); }</code><technical_language>add: - assertNotNull(mapped.getAlarmTypes()); - assertNotNull(mapped.getAlarmTypes().get(0));</technical_language>

Target:
public void testWithFilledSet() { final Set<AlarmType> alarmTypeSet = new TreeSet<>(); alarmTypeSet.add(ALARMTYPE); final AlarmRegister original = new AlarmRegister(alarmTypeSet); final com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister mapped = this.monitoringMapper .map(original, com.alliander.osgp.adapter.ws.schema.smartmetering.monitoring.AlarmRegister.class); assertNotNull(mapped); assertNotNull(mapped.getAlarmTypes()); assertNotNull(mapped.getAlarmTypes().get(0)); assertEquals(original.getAlarmTypes().size(), mapped.getAlarmTypes().size()); assertEquals(ALARMTYPE.name(), mapped.getAlarmTypes().get(0).name()); }
Source:
<code>public void moveAction(int oldIndex, int newIndex) { <START> var newActions = new ArrayList<ScriptGeneratorAction>(); <END> newActions.addAll(actions); if (newIndex < 0) { newIndex = 0; } else if (newIndex >= this.actions.size()) { newIndex = this.actions.size() - 1; } Collections.swap(newActions, oldIndex, newIndex); firePropertyChange("actions", actions, actions = newActions); }</code><technical_language>wrapped in a check if index is valid</technical_language>

Target:
public void moveAction(int oldIndex, int newIndex) { if (isValidIndex(oldIndex)) { var newActions = new ArrayList<ScriptGeneratorAction>(); newActions.addAll(actions); if (newIndex < 0) { newIndex = 0; } else if (newIndex >= this.actions.size()) { newIndex = this.actions.size() - 1; } Collections.swap(newActions, oldIndex, newIndex); firePropertyChange("actions", actions, actions = newActions); } }
Source:
<code>private void publishFallback(RecordMetadata md, Exception e) { KafkaCallback cb = new KafkaCallback(cc, position, key, json, succeededMessageCount, failedMessageCount, succeededMessageMeter, failedMessageMeter, null, context, producer); try { <START> producer.sendFallbackAsync(fallbackTopic, key, cb, e); <END> } catch (Exception fallbackEx) { cb.onCompletion(md, fallbackEx); } }</code><technical_language>i logic is fractured this call point sendFallbackAsync -- splitting duties a bit much. call producer.fallback(this, e) rest of work of creating a new callback etc? another rev, trouble tendrils of logic here</technical_language>

Target:
private void publishFallback(RecordMetadata md, Exception e) { KafkaCallback cb = new KafkaCallback(cc, position, key, json, succeededMessageCount, failedMessageCount, succeededMessageMeter, failedMessageMeter, null, context, producer); producer.sendFallbackAsync(fallbackTopic, key, cb, md, e); }