auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void SaveM3U(final String filePath, final String fileName) { <START> Toast toast = Toast.makeText(context, context.getResources().getText(R.string.notify_save_playlist_now, filePath, fileName), Toast.LENGTH_LONG); <END> toast.show(); new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return SaveM3UInternal(filePath, fileName); } @Override protected void onPostExecute(Boolean result) { if (result.booleanValue()) { Log.i("SAVE", "OK"); Toast toast = Toast.makeText(context, context.getResources().getText(R.string.notify_save_playlist_ok, filePath, fileName), Toast.LENGTH_LONG); toast.show(); } else { Log.i("SAVE", "NOK"); Toast toast = Toast.makeText(context, context.getResources().getText(R.string.notify_save_playlist_nok, filePath, fileName), Toast.LENGTH_LONG); toast.show(); } super.onPostExecute(result); } }.execute(); }</code><technical_language>getString instead of getText in cases. text is styled. getText support format arguments. this change works languages</technical_language>

Target:
public void SaveM3U(final String filePath, final String fileName) { Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_now, filePath, fileName), Toast.LENGTH_LONG); toast.show(); new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return SaveM3UInternal(filePath, fileName); } @Override protected void onPostExecute(Boolean result) { if (result.booleanValue()) { Log.i("SAVE", "OK"); Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_ok, filePath, fileName), Toast.LENGTH_LONG); toast.show(); } else { Log.i("SAVE", "NOK"); Toast toast = Toast.makeText(context, context.getResources().getString(R.string.notify_save_playlist_nok, filePath, fileName), Toast.LENGTH_LONG); toast.show(); } super.onPostExecute(result); } }.execute(); }
Source:
<code>public static Vector<String> extractEntityOwners(UserSandbox sandbox) { Vector<String> owners = new Vector<String>(); Vector<String> users = new Vector<String>(); for (IStorageIterator<User> userIterator = sandbox.getUserStorage().iterate(); userIterator.hasMore(); ) { String id = userIterator.nextRecord().getUniqueId(); owners.addElement(id); users.addElement(id); } for (String userId : users) { DataInstance instance = loadFixture(sandbox, "user-groups", userId); if (instance == null) { continue; } EvaluationContext ec = new EvaluationContext(instance); for (TreeReference ref : ec.expandReference(XPathReference.getPathExpr("/groups/group/@id").getReference())) { <START> AbstractTreeElement<AbstractTreeElement> idelement = ec.resolveReference(ref); <END> if (idelement.getValue() != null) { owners.addElement(idelement.getValue().uncast().getString()); } } } return owners; }</code><technical_language>remove <AbstractTreeElement> type annotation, presence creates a cast lint warning</technical_language>

Target:
public static Vector<String> extractEntityOwners(UserSandbox sandbox) { Vector<String> owners = new Vector<String>(); Vector<String> users = new Vector<String>(); for (IStorageIterator<User> userIterator = sandbox.getUserStorage().iterate(); userIterator.hasMore(); ) { String id = userIterator.nextRecord().getUniqueId(); owners.addElement(id); users.addElement(id); } for (String userId : users) { DataInstance instance = loadFixture(sandbox, "user-groups", userId); if (instance == null) { continue; } EvaluationContext ec = new EvaluationContext(instance); for (TreeReference ref : ec.expandReference(XPathReference.getPathExpr("/groups/group/@id").getReference())) { AbstractTreeElement idElement = ec.resolveReference(ref); if (idElement.getValue() != null) { owners.addElement(idElement.getValue().uncast().getString()); } } } return owners; }
Source:
<code>public void returnsProperResponseCodeOnNoContentLength() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText("411 Test")).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "", <START> BkBasicTest.HELLO_WORLD <END> ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString("HTTP/1.1 411 Length Required") ); }</code><technical_language>@dalifreire change this string else is specific this test</technical_language>

Target:
public void returnsProperResponseCodeOnNoContentLength() throws Exception { final ByteArrayOutputStream output = new ByteArrayOutputStream(); final ServerSocket server = new ServerSocket(0); final String text = "Say hello!"; try { new Thread( new Runnable() { @Override public void run() { try { new BkBasic(new TkText("411 Test")).accept( server.accept() ); } catch (final IOException exception) { throw new IllegalStateException(exception); } } } ).start(); final Socket socket = new Socket( server.getInetAddress(), server.getLocalPort() ); try { socket.getOutputStream().write( Joiner.on(BkBasicTest.CRLF).join( BkBasicTest.POST, BkBasicTest.HOST, "", text ).getBytes() ); final InputStream input = socket.getInputStream(); final byte[] buffer = new byte[4096]; for (int count = input.read(buffer); count != -1; count = input.read(buffer)) { output.write(buffer, 0, count); } } finally { socket.close(); } } finally { server.close(); } MatcherAssert.assertThat( output.toString(), Matchers.containsString("HTTP/1.1 411 Length Required") ); }
Source:
<code><START> public String getDescriptorFile() { <END> return _descriptorFile; }</code><technical_language>URI instead of File</technical_language>

Target:
public URI getDescriptorFile() { return _descriptorFile; }
Source:
<code>public static void setLogDelegateFactory(LogDelegateFactory factory) { LogDelegateFactory current = delegateFactory; if (current != null) { try { <START> getLogger(LoggerFactory.class).info("Replacing LogDelegateFactory " + current + " by " + factory); <END> } catch (Throwable t) { t.printStackTrace(); } loggers.clear(); } delegateFactory = factory; }</code><technical_language>of info, this a debug message</technical_language>

Target:
public static synchronized void setLogDelegateFactory(LogDelegateFactory factory) { requireNonNull(factory, "factory == null"); LogDelegateFactory current = delegateFactory; if (current != null) { try { getLogger(LoggerFactory.class).debug("Replacing LogDelegateFactory " + current + " by " + factory); } catch (Throwable t) { factory.createDelegate(LoggerFactory.class.getCanonicalName()) .error("Failed to log LogDelegateFactory replacement on previous implementation", t); } loggers.clear(); } delegateFactory = factory; }
Source:
<code>public ThriftIndexHandle( SchemaTableName schemaTableName, TupleDomain<ColumnHandle> tupleDomain, ConnectorSession session) { this.schemaTableName = requireNonNull(schemaTableName, "schemaTableName is null"); this.tupleDomain = requireNonNull(tupleDomain, "tupleDomain is null"); <START> this.session = Optional.of(requireNonNull(session, "session is null")); <END> }</code><technical_language>clever trick</technical_language>

Target:
public ThriftIndexHandle( SchemaTableName schemaTableName, TupleDomain<ColumnHandle> tupleDomain, ConnectorSession session) { this(schemaTableName, tupleDomain, Optional.of(requireNonNull(session, "session is null"))); }
Source:
<code>public void generatesPersistenceXml() throws Exception { Path path = new PersistTestModuleBuilder().setDriver("org.h2.Driver") .addEntityClass(MyEntity1.class) <START> .addEntityClass(MyEntity2.class) <END> .setUrl("jdbc:h2:mem:test") .setUser("username") .setPassword("secret") .setLogLevel("FINE") .setPersistenceUnit("test-unit") .setExceptionHandler(MyExceptionHandler.class) .setProperty("custom-property", "value") .build() .savePersistenceXml(); URL url = Thread.currentThread().getContextClassLoader().getResource("org/eclipse/che/commons/test/db/test-persistence-1.xml"); assertNotNull(url); assertEquals(new String(Files.readAllBytes(path), UTF_8), Resources.toString(url, UTF_8)); }</code><technical_language>replace addEntityClass consumes class consumes fqn</technical_language>

Target:
public void generatesPersistenceXml() throws Exception { Path path = new PersistTestModuleBuilder().setDriver("org.h2.Driver") .addEntityClass(MyEntity1.class) .addEntityClass("org.eclipse.che.commons.test.db.PersistTestModuleBuilderTest$MyEntity2") .setUrl("jdbc:h2:mem:test") .setUser("username") .setPassword("secret") .setLogLevel("FINE") .setPersistenceUnit("test-unit") .setExceptionHandler(MyExceptionHandler.class) .setProperty("custom-property", "value") .savePersistenceXml(); URL url = Thread.currentThread().getContextClassLoader().getResource("org/eclipse/che/commons/test/db/test-persistence-1.xml"); assertNotNull(url); assertEquals(new String(Files.readAllBytes(path), UTF_8), Resources.toString(url, UTF_8)); }
Source:
<code>public void run() { try { if (!CoverageUtil.getBranchFromUser(false)) { return; } IOseeBranch branch = CoverageUtil.getBranch(); CoveragePackageArtifactListDialog dialog = new CoveragePackageArtifactListDialog("Delete Package", "Select Package"); dialog.setInput(OseeCoveragePackageStore.getCoveragePackageArtifacts(branch)); <START> if (dialog.open() == 0) { <END> if (dialog.getResult().length == 0) { AWorkbench.popup("Must select coverage package."); return; } Artifact coveragePackageArtifact = (Artifact) dialog.getResult()[0]; CoveragePackage coveragePackage = OseeCoveragePackageStore.get(coveragePackageArtifact); MessageDialog cDialog = new MessageDialog( Displays.getActiveShell(), "Delete Package", null, String.format( "This will delete Coverage Package and all related Coverage Units and Test Units.\n\nDelete Package [%s]?", coveragePackage.getName()), MessageDialog.QUESTION, new String[] {"OK", "Cancel"}, 0); if (cDialog.open() == 0) { SkynetTransaction transaction = TransactionManager.createTransaction(branch, "Delete Coverage Package - " + coveragePackage.getName()); CoveragePackageEvent coverageEvent = new CoveragePackageEvent(coveragePackage, CoverageEventType.Deleted); OseeCoveragePackageStore.get(coveragePackage, branch).delete(transaction, coverageEvent, false); transaction.execute(); CoverageEventManager.instance.sendRemoteEvent(coverageEvent); } } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }</code><technical_language>Window.OK instead of 0</technical_language>

Target:
public void run() { try { if (!CoverageUtil.getBranchFromUser(false)) { return; } IOseeBranch branch = CoverageUtil.getBranch(); CoveragePackageArtifactListDialog dialog = new CoveragePackageArtifactListDialog("Delete Package", "Select Package"); dialog.setInput(OseeCoveragePackageStore.getCoveragePackageArtifacts(branch)); if (dialog.open() == Window.OK) { if (dialog.getResult().length == 0) { AWorkbench.popup("Must select coverage package."); return; } Artifact coveragePackageArtifact = (Artifact) dialog.getResult()[0]; CoveragePackage coveragePackage = OseeCoveragePackageStore.get(coveragePackageArtifact); MessageDialog cDialog = new MessageDialog( Displays.getActiveShell(), "Delete Package", null, String.format( "This will delete Coverage Package and all related Coverage Units and Test Units.\n\nDelete Package [%s]?", coveragePackage.getName()), MessageDialog.QUESTION, new String[] {"OK", "Cancel"}, 0); if (cDialog.open() == Window.OK) { SkynetTransaction transaction = TransactionManager.createTransaction(branch, "Delete Coverage Package - " + coveragePackage.getName()); CoveragePackageEvent coverageEvent = new CoveragePackageEvent(coveragePackage, CoverageEventType.Deleted); OseeCoveragePackageStore.get(coveragePackage, branch).delete(transaction, coverageEvent, false); transaction.execute(); CoverageEventManager.instance.sendRemoteEvent(coverageEvent); } } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder("batch: ").append(batchType).append('\n'); for (Single q : queries) <START> { <END> sb.append(q.toString()).append('\n'); } sb.append("end batch"); return sb.toString(); }</code><technical_language>Redundant braces for a single statement block</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder("batch: ").append(batchType).append('\n'); for (Single q : queries) sb.append(q.toString()).append('\n'); sb.append("end batch"); return sb.toString(); }
Source:
<code>private static String getRecipientNames(Set<String> recipients, String studentEmail, CourseRoster roster) { StringBuilder namesStringBuilder = new StringBuilder(); int i = 0; for (String recipient : recipients) { if (i == recipients.size() - 1 && recipients.size() > 1) { namesStringBuilder.append("and "); } StudentAttributes student = roster.getStudentForEmail(recipient); if (recipient.equals(studentEmail)) { namesStringBuilder.append("you, "); } else if (data.getCourseId().equals(recipient)) { namesStringBuilder.append("All Students In This Course, "); } else if(student != null){ if (recipients.size() == 1) { namesStringBuilder.append(student.name + " (" + student.team + ", " + student.email + "), "); } else { namesStringBuilder.append(student.name + ", "); } } else { namesStringBuilder.append(recipient + ", "); } i++; } String namesString = namesStringBuilder.toString(); <START> return namesString.substring(0, namesString.length() - 2); <END> }</code><technical_language>This dangerous if namesString is empty</technical_language>

Target:
private static String getRecipientNames(Set<String> recipients, String studentEmail, CourseRoster roster) { StringBuilder namesStringBuilder = new StringBuilder(); int i = 0; for (String recipient : recipients) { if (i == recipients.size() - 1 && recipients.size() > 1) { namesStringBuilder.append(" and "); } else if ( i > 0 && i < recipients.size() - 1 && recipients.size() > 2) { namesStringBuilder.append(", "); } StudentAttributes student = roster.getStudentForEmail(recipient); if (recipient.equals(studentEmail)) { namesStringBuilder.append("you"); } else if (data.getCourseId().equals(recipient)) { namesStringBuilder.append("All Students In This Course"); } else if(student != null){ if (recipients.size() == 1) { namesStringBuilder.append(student.name + " (" + student.team + ", " + student.email + ")"); } else { namesStringBuilder.append(student.name); } } else { namesStringBuilder.append(recipient); } i++; } String namesString = namesStringBuilder.toString(); return namesString; }
Source:
<code><START> public List<AuditEntry> fetchAuditHistory(final String key, final String type, int limit) { <END> final int theLimit = getLimitOrDefault(limit); return dbi.withHandle( new HandleCallback<List<AuditEntry>>() { @Override public List<AuditEntry> withHandle(Handle handle) throws Exception { return handle.createQuery( String.format( "SELECT payload FROM %s WHERE audit_key = :audit_key and type = :type ORDER BY created_date DESC", getAuditTable() ) ) .bind("type", type) .bind("audit_key", key) .setMaxRows(theLimit) .map( new ResultSetMapper<AuditEntry>() { @Override public AuditEntry map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { return jsonMapper.readValue(r.getBytes("payload"), AuditEntry.class); } catch (IOException e) { throw new SQLException(e); } } } ) .list(); } } ); }</code><technical_language>functions refactored a bit duplicate code</technical_language>

Target:
public List<AuditEntry> fetchAuditHistory(final String key, final String type, int limit) throws IllegalArgumentException { return fetchAuditHistoryLastEntries(key, type, limit); }
Source:
<code>public List<SubscriptionCursorWithoutToken> calculate( final Subscription subscription, final TimelineService timelineService, final CursorConverter converter) { return subscription.getEventTypes() .stream() .map(et -> { try { final List<Timeline> activeTimelines = timelineService.getActiveTimelinesOrdered(et); return activeTimelines.get(activeTimelines.size() - 1); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }) .collect(groupingBy(Timeline::getStorage)) .values() .stream() .flatMap(timelines -> { try { return timelineService.getTopicRepository(timelines.get(0)) <START> .loadTopicStatistics(timelines).stream(); <END> } catch (final ServiceUnavailableException e) { throw new NakadiRuntimeException(e); } }) .map(PartitionStatistics::getLast) .map(converter::convertToNoToken) .collect(Collectors.toList()); }</code><technical_language>loadTopicEndStatistics</technical_language>

Target:
public List<SubscriptionCursorWithoutToken> calculate( final Subscription subscription, final TimelineService timelineService, final CursorConverter converter) { return subscription.getEventTypes() .stream() .map(et -> { try { final List<Timeline> activeTimelines = timelineService.getActiveTimelinesOrdered(et); return activeTimelines.get(activeTimelines.size() - 1); } catch (final NakadiException e) { throw new NakadiRuntimeException(e); } }) .collect(groupingBy(Timeline::getStorage)) .values() .stream() .flatMap(timelines -> { try { return timelineService.getTopicRepository(timelines.get(0)) .loadTopicEndStatistics(timelines).stream(); } catch (final ServiceUnavailableException e) { throw new NakadiRuntimeException(e); } }) .map(PartitionEndStatistics::getLast) .map(converter::convertToNoToken) .collect(Collectors.toList()); }
Source:
<code>public void testCreateHeaderFromSession() { Map<String, String> result = sessionProperties.createHeaderFromSession( createTestSession( <START> ImmutableMap.of( <END> "string_session_prop", "123", "int_session_prop", 1, "double_session_prop", 100.0, "bool_session_prop", true))); Map<String, String> expected = ImmutableMap.of( "test_session_prop1", "123", "test_session_prop2", "1", "test_session_prop3", "100.0", "test_session_prop4", "true"); assertEquals(result, expected); }</code><technical_language>Nit: ImmutableMap.Builder, easier read modify, is special case for item. I of() if is item. for rest of this class (except usages item)</technical_language>

Target:
public void testCreateHeaderFromSession() { Map<String, Object> sessionValues = ImmutableMap.<String, Object>builder() .put("string_session_prop", "123") .put("int_session_prop", 1) .put("long_session_prop", 13L) .put("double_session_prop", 100.0) .put("bool_session_prop", true) .build(); Map<String, String> result = sessionProperties.toHeader(createTestSession(sessionValues)); Map<String, String> expected = ImmutableMap.<String, String>builder() .put("test_session_prop1", "123") .put("test_session_prop2", "1") .put("test_session_prop3", "13") .put("test_session_prop4", "100.0") .put("test_session_prop5", "true") .build(); assertEquals(result, expected); }
Source:
<code>public void memberRemoved(MembershipEvent membershipEvent) { SocketAddress removedMemberSocketAddress = membershipEvent.getMember().getSocketAddress(); Set<HazelcastInstance> hazelcastLocalInstanceSet = Hazelcast.getAllHazelcastInstances(); if (!hazelcastLocalInstanceSet.isEmpty()) { HazelcastInstance hazelcastInstance = hazelcastLocalInstanceSet.iterator().next(); Lock lock = hazelcastInstance .getLock(ApplicationContextStartEventHandler.HZ_INTERNAL_CONFIGURATION_MULTI_MAP_LOCK); lock.lock(); try { MultiMap<SocketAddress, SocketAddress> configMultiMap = hazelcastInstance .getMultiMap(ApplicationContextStartEventHandler.HZ_INTERNAL_CONFIGURATION_MULTI_MAP); <START> if (configMultiMap.keySet().contains(removedMemberSocketAddress)) { <END> SocketAddress newAdminSocketAddress = getNewAdminInstanceSocketAddress( configMultiMap, removedMemberSocketAddress); for (SocketAddress socketAddress : configMultiMap.values()) { if (!socketAddress.equals(removedMemberSocketAddress)) { configMultiMap.put(newAdminSocketAddress, socketAddress); } } configMultiMap.remove(removedMemberSocketAddress); } else { configMultiMap.remove(configMultiMap.keySet().iterator().next(), removedMemberSocketAddress); } } finally { lock.unlock(); } } }</code><technical_language>configMultiMap.containsKey</technical_language>

Target:
public void memberRemoved(MembershipEvent membershipEvent) { SocketAddress removedMemberSocketAddress = membershipEvent.getMember().getSocketAddress(); Set<HazelcastInstance> hazelcastLocalInstanceSet = Hazelcast.getAllHazelcastInstances(); if (!hazelcastLocalInstanceSet.isEmpty()) { HazelcastInstance hazelcastInstance = hazelcastLocalInstanceSet.iterator().next(); Lock lock = hazelcastInstance .getLock(HazelcastLocalInstanceRegistrar.SPRING_INTEGRATION_INTERNAL_CLUSTER_LOCK); lock.lock(); try { MultiMap<SocketAddress, SocketAddress> configMultiMap = hazelcastInstance .getMultiMap(HazelcastLocalInstanceRegistrar.SPRING_INTEGRATION_INTERNAL_CLUSTER_MULTIMAP); if (configMultiMap.containsKey(removedMemberSocketAddress)) { SocketAddress newAdminSocketAddress = getNewAdminInstanceSocketAddress( configMultiMap, removedMemberSocketAddress); for (SocketAddress socketAddress : configMultiMap.values()) { if (!socketAddress.equals(removedMemberSocketAddress)) { configMultiMap.put(newAdminSocketAddress, socketAddress); } } configMultiMap.remove(removedMemberSocketAddress); } else { configMultiMap.remove(configMultiMap.keySet().iterator().next(), removedMemberSocketAddress); } } finally { lock.unlock(); } } }
Source:
<code>public void copyFrom(ChunkletStore otherStore) { <START> if (otherStore instanceof PrimitiveChunkStore) { AtomicIntegerArray data = ((PrimitiveChunkStore) otherStore).data; AtomicIntegerArray to = this.data = new AtomicIntegerArray(data.length()); int end = to.length(); while (end-- > 0) { to.set(end, data.get(end)); } } else { int wh = worldHeight; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < wh; y++) { set(x, y, z, otherStore.isTrue(x, y, z)); } <END> } } } }</code><technical_language>Please explain operations here, especially thoughts nested for loops while loop</technical_language>

Target:
public void copyFrom(ChunkletStore otherStore) { if (otherStore instanceof PrimitiveChunkStore) { AtomicIntegerArray from = ((PrimitiveChunkStore) otherStore).data; AtomicIntegerArray into = this.data = new AtomicIntegerArray( worldHeight * PAGE_SIZE ); int end = Math.min(from.length(), into.length()); while (end-- > 0) { into.set(end, from.get(end)); } } else { int worldHeight = this.worldHeight; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < worldHeight; y++) { set(x, y, z, otherStore.isTrue(x, y, z)); } } } } }
Source:
<code>public Tag(String name, String description, User author) { this.name = name.toLowerCase(); this.sluggedName = toSlug(name); <START> this.description = description; <END> this.author = author; }</code><technical_language>tab for indentation(with size of 4 blank spaces), configure editor for that</technical_language>

Target:
public Tag(String name, String description, User author) { this.name = name.toLowerCase(); this.sluggedName = toSlug(name, true); this.description = description; this.author = author; }
Source:
<code>public void generateReports_WithTrendsFile_GeneratesPages() { <START> List<String> jsonReports = Arrays.asList(ReportGenerator.reportFromResourceJson(ReportGenerator.SAMPLE_JSON)); <END> Configuration configuration = new Configuration(reportDirectory, "myProject"); ReportBuilder builder = new ReportBuilder(jsonReports, configuration, Collections.<String>emptyList()); configuration.setTrendsStatsFile(trendsFileTmp); Reportable result = builder.generateReports(); assertThat(countHtmlFiles()).hasSize(10); assertThat(result).isNotNull(); }</code><technical_language>if revert constructor existing tests left unchanged</technical_language>

Target:
public void generateReports_WithTrendsFile_GeneratesPages() { List<String> jsonReports = Arrays.asList(ReportGenerator.reportFromResource(ReportGenerator.SAMPLE_JSON)); Configuration configuration = new Configuration(reportDirectory, "myProject"); ReportBuilder builder = new ReportBuilder(jsonReports, configuration); configuration.setTrendsStatsFile(trendsFileTmp); Reportable result = builder.generateReports(); assertThat(countHtmlFiles()).hasSize(10); assertThat(result).isNotNull(); }
Source:
<code>public void testJsonDiskDescription() { String diskAlias = null; try { diskAlias = ImagesHandler.getJsonDiskDescription("DiskAlias", "DiskDescription"); } catch (IOException e) { } assertTrue("Should be map of disk alias and disk description", diskAlias.equals("{\"DiskDescription\":\"DiskDescription\",\"DiskAlias\":\"DiskAlias\"}")); <START> } <END></code><technical_language>missing: a test for empty ("") description a null description</technical_language>

Target:
public void testJsonDiskDescription() throws IOException { String jsonDescription = null; jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", "DiskDescription"); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"DiskDescription\",\"DiskAlias\":\"DiskAlias\"}")); }
Source:
<code>public boolean isOwnerOf(AccessSection section) { <START> return RefUtil.isAnySuperSet(getOwnerOf(), section.getRefPattern()); <END> }</code><technical_language>this accuracy is necessary web UI side. need if user is owner of a local section in order edit</technical_language>

Target:
public boolean isOwnerOf(AccessSection section) { return getOwnerOf().contains(section.getRefPattern()); }
Source:
<code>public void write(byte[] data) { try { writeSafely(data); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); <START> LogKitten.e(sw.toString()); <END> } }</code><technical_language>LogKitten.ex(e)</technical_language>

Target:
public void write(byte[] data) { try { writeSafely(data); } catch (UncleanStatusException e) { LogKitten.ex(e); } }
Source:
<code>protected List<String> initialKnifeParameters() { <START> MutableList<String> result = new MutableList<String>(); <END> result.add("node"); result.add("show"); result.add("-l"); result.add(nodeName); result.add("--format"); result.add("json"); return result; }</code><technical_language>for: return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json")</technical_language>

Target:
protected List<String> initialKnifeParameters() { return ImmutableList.of("node", "show", "-l", nodeName, "--format", "json"); }
Source:
<code>public static void writeTag(Tag tag, NdefMessage message) { if (tag != null) { try { Ndef ndefTag = Ndef.get(tag); if (ndefTag == null) { NdefFormatable nForm = NdefFormatable.get(tag); if (nForm != null) { nForm.connect(); nForm.format(message); nForm.close(); } } else { ndefTag.connect(); ndefTag.writeNdefMessage(message); ndefTag.close(); } <START> } catch (Exception e) { <END> Log.d(NfcHandler.class.getSimpleName(), "Couldn't create message", e); } } }</code><technical_language>[Do catch Exception](<LINK_0></technical_language>

Target:
public static void writeTag(Tag tag, NdefMessage message) { if (tag != null) { try { Ndef ndefTag = Ndef.get(tag); if (ndefTag == null) { NdefFormatable nForm = NdefFormatable.get(tag); if (nForm != null) { nForm.connect(); nForm.format(message); nForm.close(); } } else { ndefTag.connect(); ndefTag.writeNdefMessage(message); ndefTag.close(); } } catch (IOException | FormatException e) { Log.d(TAG, "Couldn't create message", e); } } }
Source:
<code>public CreateInternalVariableCommand(final BasicFBType fbType) { <START> this.dataType = DataTypeLibrary.getInstance().getType("BOOL"); this.fbType = fbType; this.name = DEFAULT_VAR_NAME; this.index = fbType.getInternalVars().size() - 1; <END> }</code><technical_language>algorithm command I calling new constructor values nice here. This cool new logic of new constructor</technical_language>

Target:
public CreateInternalVariableCommand(final BasicFBType fbType) { this(fbType, fbType.getInternalVars().size() - 1, null, null); }
Source:
<code><START> public void deactivate() { <END> View view = getView(); if (view == null) { return; } getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement == null) { return; } for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); hostSemanticElement = null; }</code><technical_language>Avoid multiple returns</technical_language>

Target:
public void deactivate() { View view = getView(); if (view != null) { getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement != null) { for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); hostSemanticElement = null; } } }
Source:
<code>private CompositeJobParametersValidator compositeJobParametersValidator(JobParameters jobParameters) { List<JobParametersValidator> jobParametersValidators = new ArrayList<>(); jobParametersValidators.add(new VariantLoaderStepParametersValidator()); jobParametersValidators.add(new FileLoaderStepParametersValidator()); Boolean skipAnnotation = Boolean.valueOf(jobParameters.getString(JobParametersNames.ANNOTATION_SKIP)); if (!skipAnnotation) { <START> jobParametersValidators.add(new InputStudyIdValidator()); <END> jobParametersValidators.add(new VepInputGeneratorStepParametersValidator()); jobParametersValidators.add(new VepAnnotationGeneratorStepParametersValidator()); jobParametersValidators.add(new AnnotationLoaderStepParametersValidator()); jobParametersValidators.add(new AnnotationMetadataStepParametersValidator()); } Boolean skipStats = Boolean.valueOf(jobParameters.getString(JobParametersNames.STATISTICS_SKIP)); if (!skipStats) { jobParametersValidators.add(new PopulationStatisticsGeneratorStepParametersValidator()); jobParametersValidators.add(new PopulationStatisticsLoaderStepParametersValidator()); } CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }</code><technical_language>InputStudyId a empty default avoid states: null, empty, value. a empty default reduce problem if want execute step is mandatory , if job is mandatory</technical_language>

Target:
private CompositeJobParametersValidator compositeJobParametersValidator(JobParameters jobParameters) { List<JobParametersValidator> jobParametersValidators = new ArrayList<>(); jobParametersValidators.add(new VariantLoaderStepParametersValidator()); jobParametersValidators.add(new FileLoaderStepParametersValidator()); Boolean skipAnnotation = Boolean.valueOf(jobParameters.getString(JobParametersNames.ANNOTATION_SKIP)); if (!skipAnnotation) { boolean studyIdRequired = true; jobParametersValidators.add(new VepInputGeneratorStepParametersValidator()); jobParametersValidators.add(new VepAnnotationGeneratorStepParametersValidator(studyIdRequired)); jobParametersValidators.add(new AnnotationLoaderStepParametersValidator(studyIdRequired)); jobParametersValidators.add(new AnnotationMetadataStepParametersValidator()); } Boolean skipStats = Boolean.valueOf(jobParameters.getString(JobParametersNames.STATISTICS_SKIP)); if (!skipStats) { jobParametersValidators.add(new PopulationStatisticsGeneratorStepParametersValidator()); jobParametersValidators.add(new PopulationStatisticsLoaderStepParametersValidator()); } CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }
Source:
<code>private static int calculateTypeWidth(Type wireType) { Type type = wireType.getConcrete(); int fcount = 0; while (type instanceof FunType) { fcount++; type = ((FunType)type).getResult(); } if (fcount > 0) { return 4 + 2*fcount; } int arity = 0; while (type instanceof TypeApp) { arity++; type = ((TypeApp)type).getTypeFun(); } if (type instanceof ListTypeCon) { <START> return 5; <END> } if (type instanceof TypeCon) { return 2 + arity; } return 3 + arity; }</code><technical_language>~~Why do types a list a constant width?~~ bad, for _outer_ type is a list</technical_language>

Target:
private static int calculateTypeWidth(Type wireType) { Type type = wireType.getConcrete(); int fcount = 0; while (type instanceof FunType) { fcount++; type = ((FunType)type).getResult(); } if (fcount > 0) { return 4 + 2*fcount; } int arity = 0; while (type instanceof TypeApp) { arity++; type = ((TypeApp)type).getTypeFun(); } if (type instanceof ListTypeCon) { return 5; } return 3 + arity; }
Source:
<code>public void testUserLogin() { User <START> user2 = <END> User.getUser(); assertThat(user2.getUsername(), is("name")); assertThat(user2.getPassword(), is("pwd")); assertThat(user2.getUserID(), is(USER_ID)); assertThat(user2.getGroupMemberships(), is(GROUPS)); }</code><technical_language>new this patch I "user" more sense. distinction "user2" is</technical_language>

Target:
public void testUserLogin() { User user = User.getUser(); assertThat(user.getUsername(), is("name")); assertThat(user.getPassword(), is("pwd")); assertThat(user.getUserID(), is(USER_ID)); assertThat(user.getGroupMemberships(), is(GROUPS)); }
Source:
<code>public static Slice allocate(int capacity) { <START> checkArgument(capacity < Integer.MAX_VALUE - 8, "cannot allocate slice larger than %d bytes", Integer.MAX_VALUE - 8); <END> if (capacity == 0) { return EMPTY_SLICE; } return new Slice(new byte[capacity]); }</code><technical_language>Add a constant java // java.util.ArrayList for explanation private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;</technical_language>

Target:
public static Slice allocate(int capacity) { if (capacity == 0) { return EMPTY_SLICE; } checkArgument(capacity <= MAX_ARRAY_SIZE, "cannot allocate slice larger than %s bytes", MAX_ARRAY_SIZE); return new Slice(new byte[capacity]); }
Source:
<code>public Role createRole(String name, Role role, String description) { checkCallerAccess(); return Transaction.execute(new TransactionCallback<RoleVO>() { @Override public RoleVO doInTransaction(TransactionStatus status) { RoleVO newRoleVO = roleDao.persist(new RoleVO(name, role.getRoleType(), description)); if (newRoleVO == null) { <START> throw new CloudRuntimeException("Unable to add role into DB, is DB full?"); <END> } List<RolePermissionVO> rolePermissions = rolePermissionsDao.findAllByRoleIdSorted(role.getId()); if (rolePermissions != null && !rolePermissions.isEmpty()) { for (RolePermissionVO permission : rolePermissions) { rolePermissionsDao.persist(new RolePermissionVO(newRoleVO.getId(), permission.getRule().toString(), permission.getPermission(), permission.getDescription())); } } return newRoleVO; } }); }</code><technical_language>improve exception message</technical_language>

Target:
public Role createRole(String name, Role role, String description) { checkCallerAccess(); return Transaction.execute(new TransactionCallback<RoleVO>() { @Override public RoleVO doInTransaction(TransactionStatus status) { RoleVO newRoleVO = roleDao.persist(new RoleVO(name, role.getRoleType(), description)); if (newRoleVO == null) { throw new CloudRuntimeException("Unable to create the role: " + name + ", failed to persist in DB"); } List<RolePermissionVO> rolePermissions = rolePermissionsDao.findAllByRoleIdSorted(role.getId()); if (rolePermissions != null && !rolePermissions.isEmpty()) { for (RolePermissionVO permission : rolePermissions) { rolePermissionsDao.persist(new RolePermissionVO(newRoleVO.getId(), permission.getRule().toString(), permission.getPermission(), permission.getDescription())); } } return newRoleVO; } }); }
Source:
<code>public void apply() throws ConnectException { try { if (!storage.exists(logFile)) { log.debug("Storage does not exist"); return; } acquireLease(); log.debug("Lease acquired"); if (reader == null) { reader = new WALFile.Reader(conf.getHadoopConfiguration(), Reader.file(new Path(logFile))); } Map<WALEntry, WALEntry> entries = new HashMap<>(); WALEntry key = new WALEntry(); WALEntry value = new WALEntry(); while (reader.next(key, value)) { String keyName = key.getName(); if (keyName.equals(beginMarker)) { entries.clear(); } else if (keyName.equals(endMarker)) { for (Map.Entry<WALEntry, WALEntry> entry: entries.entrySet()) { String tempFile = entry.getKey().getName(); String committedFile = entry.getValue().getName(); RecoveryHelper.getInstance().addFile(committedFile); if (!storage.exists(committedFile)) { storage.commit(tempFile, committedFile); } } } else { WALEntry mapKey = new WALEntry(key.getName()); WALEntry mapValue = new WALEntry(value.getName()); entries.put(mapKey, mapValue); <START> if (value.getName().equals(RecoveryHelper.RECOVERY_RECORD_KEY)) { <END> RecoveryHelper.getInstance().addFile(value.getName()); } } } } catch (IOException e) { log.error("Error applying WAL file: {}, {}", logFile, e); close(); throw new DataException(e); } log.debug("Finished applying WAL"); }</code><technical_language>this do anything? RECOVERY_RECORD_KEY is written key - wal.append(RecoveryHelper.RECOVERY_RECORD_KEY, fileStatusWithMaxOffset.getPath().toString())</technical_language>

Target:
public void apply() throws ConnectException { try { if (!storage.exists(logFile)) { log.debug("Storage does not exist"); return; } acquireLease(); log.debug("Lease acquired"); if (reader == null) { reader = new WALFile.Reader(conf.getHadoopConfiguration(), Reader.file(new Path(logFile))); } Map<WALEntry, WALEntry> entries = new HashMap<>(); WALEntry key = new WALEntry(); WALEntry value = new WALEntry(); while (reader.next(key, value)) { String keyName = key.getName(); if (keyName.equals(beginMarker)) { entries.clear(); } else if (keyName.equals(endMarker)) { for (Map.Entry<WALEntry, WALEntry> entry: entries.entrySet()) { String tempFile = entry.getKey().getName(); String committedFile = entry.getValue().getName(); RecoveryHelper.getInstance().addFile(committedFile); if (!storage.exists(committedFile)) { storage.commit(tempFile, committedFile); } } } else { WALEntry mapKey = new WALEntry(key.getName()); WALEntry mapValue = new WALEntry(value.getName()); entries.put(mapKey, mapValue); if (key.getName().equals(RecoveryHelper.RECOVERY_RECORD_KEY)) { RecoveryHelper.getInstance().addFile(value.getName()); } } } } catch (IOException e) { log.error("Error applying WAL file: {}, {}", logFile, e); close(); throw new DataException(e); } log.debug("Finished applying WAL"); }
Source:
<code>public void visitIfStatement(IfStatementTree tree) { if (!tree.is(Kind.IF_STATEMENT) || checkedIfStatements.contains(tree)) { super.visitIfStatement(tree); return; } boolean hasElse = false; List<List<StatementTree>> branches = new ArrayList<>(); for (Tree clause : getClauses(tree)) { if (clause.is(Kind.IF_STATEMENT)) { IfStatementTree ifStatementTree = (IfStatementTree) clause; branches.add(ifStatementTree.statements()); } else if (clause.is(Kind.ELSEIF_CLAUSE)) { ElseifClauseTree elseifClauseTree = (ElseifClauseTree) clause; branches.add(elseifClauseTree.statements()); } else if (clause.is(Kind.ELSE_CLAUSE)) { ElseClauseTree elseClause = (ElseClauseTree) clause; if (!elseClause.statements().get(0).is(Kind.IF_STATEMENT)) { branches.add(elseClause.statements()); hasElse = true; } } } <START> checkBranches("branch", branches, hasElse, tree.ifToken()); <END> super.visitIfStatement(tree); }</code><technical_language>hasElse means reportAllEquivalent</technical_language>

Target:
public void visitIfStatement(IfStatementTree tree) { if (!tree.is(Kind.IF_STATEMENT) || checkedIfStatements.contains(tree)) { super.visitIfStatement(tree); return; } boolean hasElse = false; List<List<StatementTree>> branches = new ArrayList<>(); for (Tree clause : getClauses(tree)) { if (clause.is(Kind.IF_STATEMENT)) { IfStatementTree ifStatementTree = (IfStatementTree) clause; branches.add(ifStatementTree.statements()); } else if (clause.is(Kind.ELSEIF_CLAUSE)) { ElseifClauseTree elseifClauseTree = (ElseifClauseTree) clause; branches.add(elseifClauseTree.statements()); } else { branches.add(((ElseClauseTree) clause).statements()); hasElse = true; } } boolean reportAllDuplicate = hasElse; checkBranches("branch", branches, reportAllDuplicate, tree.ifToken()); super.visitIfStatement(tree); }
Source:
<code>private void sendLoanRaisingCompleteNotification(LoanRaisingCompleteNotifyDto dto) { try { DateTime beginSendTime = new DateTime().withTimeAtStartOfDay().withHourOfDay(loanRaisingCompleteNotifyStartHour); DateTime endSendTime = new DateTime().withTimeAtStartOfDay().withHourOfDay(loanRaisingCompleteNotifyEndHour); if (beginSendTime.isBeforeNow() && endSendTime.isAfterNow()) { smsWrapperClient.sendLoanRaisingCompleteNotify(dto); } else { <START> DateTime nextSendTime = beginSendTime.isBeforeNow() ? beginSendTime : beginSendTime.plusDays(1); <END> DelayMessageDeliveryJobCreator.createLoanRaisingCompleteNotifyDelayJob(jobManager, nextSendTime.toDate(), JsonConverter.writeValueAsString(dto)); } } catch (JsonProcessingException e) { logger.info("can not send loan raising complete notify", e); } }</code><technical_language>beginSendTime.isAfterNow()</technical_language>

Target:
private void sendLoanRaisingCompleteNotification(LoanRaisingCompleteNotifyDto dto) { try { DateTime beginSendTime = new DateTime().withTimeAtStartOfDay().withHourOfDay(loanRaisingCompleteNotifyStartHour); DateTime endSendTime = new DateTime().withTimeAtStartOfDay().withHourOfDay(loanRaisingCompleteNotifyEndHour); if (beginSendTime.isBeforeNow() && endSendTime.isAfterNow()) { smsWrapperClient.sendLoanRaisingCompleteNotify(dto); } else { DateTime nextSendTime = beginSendTime.isAfterNow() ? beginSendTime : beginSendTime.plusDays(1); DelayMessageDeliveryJobCreator.createLoanRaisingCompleteNotifyDelayJob(jobManager, nextSendTime.toDate(), JsonConverter.writeValueAsString(dto)); } } catch (JsonProcessingException e) { logger.info("can not send loan raising complete notify", e); } }
Source:
<code><START> private void processOutput() { <END> CallContext callContext = getCallContexts().poll(); if(callContext != null) { calling:while (true){ if(!processOutput(callContext)) break calling; } } }</code><technical_language>This method handle callContext field, callContexts (aka callContextQueue) field. while loop simplified to: CallContext callContext = getCallContext(); // a getter for single field for queue while (processOutput(callContext)) ; While BulkIOEndpointCallerImpl a getter for callContexts (aka callContextQueue) field, I missing a getter for single callContext field subclasses in revised while loop sketched above</technical_language>

Target:
private void processOutput() { CallContext callContext = getCallContext(); if(callContext != null) { while (processOutput(callContext)); } }
Source:
<code>public static void assertEquals(String pattern, String current){ boolean isAssertPassed = true; pattern = encodeSpecialChars(pattern); current = encodeSpecialChars(current); try { Assert.assertEquals(pattern, current); PageObjectLogging.log( "assertEquals", "assertion passed<br/>pattern: " + pattern + "<br/>current: " + current, true ); } catch(AssertionError ass){ isAssertPassed = false; addVerificationFailure(ass); PageObjectLogging.log( "assertEquals", "assertion failed<br/>pattern: " + pattern + "<br/>current: " <START> + current, <END> false ); } }</code><technical_language>is save remove this block</technical_language>

Target:
public static void assertEquals(String pattern, String current){ boolean isAssertPassed = true; String patternEncoded = encodeSpecialChars(pattern); String currentEncoded = encodeSpecialChars(current); try { Assert.assertEquals(pattern, current); } catch(AssertionError err){ isAssertPassed = false; addVerificationFailure(err); PageObjectLogging.log( "assertEquals", "assertion failed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, false ); } PageObjectLogging.log( "assertEquals", "assertion passed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, true ); }
Source:
<code>public void setupSystemKeyspace() throws Exception { logger.info( "Initialize system keyspace" ); migrate(); <START> cass.createColumnFamily( SYSTEM_KEYSPACE, <END> createColumnFamilyDefinition( SYSTEM_KEYSPACE, APPLICATIONS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( SYSTEM_KEYSPACE, createColumnFamilyDefinition( SYSTEM_KEYSPACE, PROPERTIES_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( SYSTEM_KEYSPACE, createColumnFamilyDefinition( SYSTEM_KEYSPACE, TOKENS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( SYSTEM_KEYSPACE, createColumnFamilyDefinition( SYSTEM_KEYSPACE, PRINCIPAL_TOKEN_CF, ComparatorType.UUIDTYPE ) ); logger.info( "System keyspace initialized" ); }</code><technical_language>Is a check created keyspaces? show exception try recreate existing keyspaces</technical_language>

Target:
public void setupSystemKeyspace() throws Exception { logger.info( "Initialize system keyspace" ); migrate(); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), APPLICATIONS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), PROPERTIES_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), TOKENS_CF, ComparatorType.BYTESTYPE ) ); cass.createColumnFamily( getApplicationKeyspace(), createColumnFamilyDefinition( getApplicationKeyspace(), PRINCIPAL_TOKEN_CF, ComparatorType.UUIDTYPE ) ); logger.info( "System keyspace initialized" ); }
Source:
<code>public String toString() { <START> return String.valueOf(value); <END> }</code><technical_language>return here</technical_language>

Target:
public String toString() { return value; }
Source:
<code>private static Set<List<JavaFileScannerContext.Location>> flowFromNode(ExplodedGraph.Node node, boolean conditionIsAlwaysTrue) { List<Class<? extends Constraint>> domains = Lists.newArrayList(ObjectConstraint.class, BooleanConstraint.class); <START> Set<List<JavaFileScannerContext.Location>> flows = FlowComputation.flow(node, node.programState.peekValue(), domains); <END> return flows.stream() .map(f -> addIssueLocation(f, node, conditionIsAlwaysTrue)) .collect(Collectors.toSet()); }</code><technical_language>This modification a bit suspicious a testcase sound a quality flaw fix</technical_language>

Target:
private static Set<List<JavaFileScannerContext.Location>> flowFromNode(ExplodedGraph.Node node, boolean conditionIsAlwaysTrue) { List<Class<? extends Constraint>> domains = Lists.newArrayList(ObjectConstraint.class, BooleanConstraint.class); Set<List<JavaFileScannerContext.Location>> flows = FlowComputation.flow(node.parent(), node.programState.peekValue(), domains); return flows.stream() .map(f -> addIssueLocation(f, node, conditionIsAlwaysTrue)) .collect(Collectors.toSet()); }