auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Timestamp toTimestamp(TimeMeta tm, TimeZone tz) { <START> long javaTime = DateTimeUtil.julianTimeToJavaTime(DateTimeUtil.toJulianTimestamp(tm)); <END> Instant instant = Instant.ofEpochMilli(javaTime); if (tz != null) { ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, tz.toZoneId()); return Timestamp.valueOf(zonedDateTime.toLocalDateTime()); } else { return Timestamp.from(instant); } }</code><technical_language>inconvenient call functions want convert TimeMeta java time. adding a function simply wraps calls</technical_language>

Target:
private Timestamp toTimestamp(TimeMeta tm, TimeZone tz) { return DateTimeUtil.toJavaTimestamp(tm, tz); }
Source:
<code>public PaginationList build() { if (this.contents == null) { this.contents = ImmutableList.of(); <START> } <END> if (this.paginationList == null) { this.paginationList = new SpongePaginationList(this.service, this.contents, this.title, this.header, this.footer, this.paginationSpacer, this.linesPerPage); } return this.paginationList; }</code><technical_language>IMO more error contents. this throw ISException. matter</technical_language>

Target:
public PaginationList build() { checkState(this.contents != null, "The contents of the pagination list cannot be null!"); if (this.paginationList == null) { this.paginationList = new SpongePaginationList(this.service, this.contents, this.title, this.header, this.footer, this.paginationSpacer, this.linesPerPage); } return this.paginationList; }
Source:
<code><START> public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { <END> service.findCashPoints(Context.getLocationService().getLocation(1),"Test 1 Cash Point",false); }</code><technical_language>This test expect exception pass in empty string</technical_language>

Target:
public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { service.findCashPoints(Context.getLocationService().getLocation(1),"",false); }
Source:
<code>public void testFullResolveHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin1", 0), new PutOperation<>(1L, "Albin2", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Map<Long, PutOperation<Long, String>> resolved = resolver.resolveChain(chain, 3); <START> <END> assertThat(resolved, hasEntry(1L, new PutOperation<>(1L, "Albin3", 3))); }</code><technical_language>this test more "accurate" if changed in entry timestamp (and value)</technical_language>

Target:
public void testFullResolveHasCorrectTimeStamp() { Chain chain = getChainFromOperations( new PutOperation<>(1L, "Albin", 0), new PutOperation<>(1L, "Albin", 1), new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin", 3)); ChainResolver<Long, String> resolver = createChainResolver(ExpiryPolicyBuilder.noExpiration()); Map<Long, PutOperation<Long, String>> resolved = resolver.resolveChain(chain, 3); assertThat(resolved, hasEntry(1L, new PutOperation<>(1L, "Albin", 3))); }
Source:
<code>protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { <START> super(); <END> this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }</code><technical_language>Style-nit: call super if arguments it</technical_language>

Target:
protected MergeChunk(int sequenceIndex, int begin, int end, ConflictState conflictState) { this.sequenceIndex = sequenceIndex; this.begin = begin; this.end = end; this.conflictState = conflictState; }
Source:
<code>public QueryResponse getStudy(@PathVariable("study") String study, @RequestParam(name = "species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); VariantStudySummary variantStudySummary = variantStudySummaryRepository.findByStudyNameOrStudyId(study); <START> QueryResult<VariantStudySummary> queryResult = new QueryResult<>(); <END> if (variantStudySummary == null) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { queryResult = Utils.buildQueryResult(Collections.singletonList(variantStudySummary)); } return setQueryResponse(queryResult); }</code><technical_language>new QueryResult<>() is redundant</technical_language>

Target:
public QueryResponse getStudy(@PathVariable("study") String study, @RequestParam(name = "species") String species, HttpServletResponse response) throws UnknownHostException, IllegalOpenCGACredentialsException, IOException { initializeQueryOptions(); MultiMongoDbFactory.setDatabaseNameForCurrentThread(DBAdaptorConnector.getDBName(species)); VariantStudySummary variantStudySummary = variantStudySummaryRepository.findByStudyNameOrStudyId(study); QueryResult<VariantStudySummary> queryResult; if (variantStudySummary == null) { queryResult = Utils.buildQueryResult(Collections.emptyList()); queryResult.setErrorMsg("Study identifier not found"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { queryResult = Utils.buildQueryResult(Collections.singletonList(variantStudySummary)); } return setQueryResponse(queryResult); }
Source:
<code>private void changeAvatar(final File selectedFile, final Component parent) { SwingWorker worker = new SwingWorker() { public Object construct() { try { ImageIcon imageOnDisk = new ImageIcon(selectedFile.getCanonicalPath()); <START> setAvatar(imageOnDisk); <END> return cropImageFile(selectedFile); } catch (IOException ex) { Log.error(ex); } return null; } public void finished() { File avatarImage = (File)get(); avatarFile = avatarImage; } }; worker.start(); }</code><technical_language>I simply miss here, invocation of setAvatar moved finished construct? Also, colled a larger, unscaled, image now? intentional? affect performance</technical_language>

Target:
private void changeAvatar(final File selectedFile, final Component parent) { SwingWorker worker = new SwingWorker() { public Object construct() { return cropImageFile(selectedFile); } public void finished() { BufferedImage avatarImage = (BufferedImage)get(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(avatarImage, "png", baos); setAvatar(new ImageIcon(avatarImage)); setAvatarBytes(baos.toByteArray()); } catch (IOException ex) { Log.error(ex); } } }; worker.start(); }
Source:
<code>private URL appendQuery(String query, URL baseURL) { try { URI baseURI = baseURL.toURI(); String baseQuery = baseURI.getQuery(); if (baseQuery == null || baseQuery.isEmpty()) { baseQuery = query; } else { if (query != null && !query.isEmpty()) { baseQuery = baseQuery + "&" + query; } } if (baseQuery.isEmpty()) { baseQuery = null; } <START> URL url = new URI(baseURI.getScheme(), baseURI.getUserInfo(), baseURI.getHost(), baseURI.getPort(), baseURI.getPath(), baseQuery, baseURI.getFragment()).toURL(); <END> String temp[] = url.toString().split("\\?"); temp[0] = temp[0].replace("%252F", "%2F"); String urlString = temp[0]; if(temp.length > 1){ urlString = urlString + "?" + temp[1]; } return new URL(urlString); } catch (MalformedURLException ex) { Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex); throw new RuntimeException(ex); } catch (URISyntaxException ex) { Log.e(TAG, "Error turning " + query + " into URI query.", ex); throw new RuntimeException(ex); } }</code><technical_language>getRawPath instead of escape yourself</technical_language>

Target:
private URL appendQuery(String query, URL baseURL) { try { Uri uri = Uri.parse(baseURL.toString()); String baseQuery = uri.getEncodedQuery(); if (baseQuery == null || baseQuery.isEmpty()) { baseQuery = query; } else { if (query != null && !query.isEmpty()) { baseQuery = baseQuery + "&" + query; } } if (baseQuery.isEmpty()) { baseQuery = null; } Uri.Builder uriBuilder = uri.buildUpon(); uriBuilder.encodedQuery(baseQuery); return new URL(uriBuilder.build().toString()); } catch (MalformedURLException ex) { Log.e(TAG, "The URL could not be created from " + baseURL.toString(), ex); throw new RuntimeException(ex); } }
Source:
<code>public void testLongPathWithoutCloneOption() throws Exception { RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('a', 'z').build(); String fileName = generator.generate(200); File tempDir = Files.createTempDirectory(fileName).toFile(); if (isWindows()) { GitException gitException = assertThrows(GitException.class, () -> { if (workspace.getGitFileDir().renameTo(tempDir)) { CloneCommand cmd = workspace.getGitClient().clone_().url(workspace.localMirror()).repositoryName("origin"); cmd.execute(); } }); <START> assertThat(gitException.getMessage().contains("FileName too long"), is(true)); <END> } }</code><technical_language>Provide a error message in case of failure. is(true) assertion fail true expected false seen. containsString() assertion fail FileName long expected some other message seen. Easier diagnose failure additional context of message unexpectedly. suggestion assertThat(gitException.getMessage(), containsString("FileName long"));</technical_language>

Target:
public void testLongPathWithoutCloneOption() throws Exception { RandomStringGenerator generator = new RandomStringGenerator.Builder() .withinRange('a', 'z').build(); String fileName = generator.generate(133); String subDirName = generator.generate(80); File tempDir = Files.createTempDirectory(fileName).toFile(); File tempSubDir = new File(tempDir, subDirName); Path subDirectory = Paths.get(tempSubDir.getAbsolutePath()); Files.createDirectories(subDirectory); assertThat(tempSubDir.getAbsolutePath().length(), greaterThan(259)); if (Files.isDirectory(subDirectory)) { File[] files = subDirectory.toFile().listFiles(); } if (Files.isDirectory(subDirectory)) { WorkspaceWithRepo tempRepo = new WorkspaceWithRepo(tempSubDir, gitImplName, listener); if (isWindows()) { GitException gitException = assertThrows(GitException.class, () -> { CloneCommand cmd = tempRepo.getGitClient().clone_().url(tempRepo.localMirror()).repositoryName("origin"); cmd.execute(); }); assertThat(gitException.getMessage(), containsString("FileName too long")); } } }
Source:
<code>private String getTypeOfPeopleCanViewComment(FeedbackResponseCommentAttributes comment, FeedbackQuestionAttributes relatedQuestion) { List<FeedbackParticipantType> showCommentTo; if (comment.isVisibilityFollowingFeedbackQuestion) { showCommentTo = relatedQuestion.showResponsesTo; } else { showCommentTo = comment.showCommentTo; } if (showCommentTo == null || showCommentTo.isEmpty()) { return "nobody"; } StringBuilder peopleCanView = new StringBuilder(100); for (int i = 0; i < showCommentTo.size(); i++) { FeedbackParticipantType commentViewer = showCommentTo.get(i); if (i == showCommentTo.size() - 1 && showCommentTo.size() > 1) { peopleCanView.append("and "); } switch (commentViewer) { case GIVER: peopleCanView.append("response giver, "); break; case RECEIVER: peopleCanView.append("response recipient, "); break; case OWN_TEAM_MEMBERS: peopleCanView.append("response giver's team, "); break; case RECEIVER_TEAM_MEMBERS: peopleCanView.append("response recipient's team, "); break; case STUDENTS: peopleCanView.append("other students in this course, "); break; case INSTRUCTORS: peopleCanView.append("instructors, "); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: peopleCanView.append("response giver's team members and response giver, "); break; default: <START> break; <END> } } String peopleCanViewString = peopleCanView.toString(); return removeEndComma(peopleCanViewString); }</code><technical_language>If miss viewer, happen before</technical_language>

Target:
private String getTypeOfPeopleCanViewComment(FeedbackResponseCommentAttributes comment, FeedbackQuestionAttributes relatedQuestion) { List<FeedbackParticipantType> showCommentTo; if (comment.isVisibilityFollowingFeedbackQuestion) { showCommentTo = relatedQuestion.showResponsesTo; } else { showCommentTo = comment.showCommentTo; } if (showCommentTo == null || showCommentTo.isEmpty()) { return "nobody"; } StringBuilder peopleCanView = new StringBuilder(100); for (int i = 0; i < showCommentTo.size(); i++) { FeedbackParticipantType commentViewer = showCommentTo.get(i); if (i == showCommentTo.size() - 1 && showCommentTo.size() > 1) { peopleCanView.append("and "); } switch (commentViewer) { case GIVER: peopleCanView.append("response giver, "); break; case RECEIVER: peopleCanView.append("response recipient, "); break; case OWN_TEAM_MEMBERS: peopleCanView.append("response giver's team members, "); break; case RECEIVER_TEAM_MEMBERS: peopleCanView.append("response recipient's team, "); break; case STUDENTS: peopleCanView.append("other students in this course, "); break; case INSTRUCTORS: peopleCanView.append("instructors, "); break; case OWN_TEAM_MEMBERS_INCLUDING_SELF: peopleCanView.append("response giver's team members and response giver, "); break; default: break; } } String peopleCanViewString = peopleCanView.toString(); return removeEndComma(peopleCanViewString); }
Source:
<code>public synchronized void performFailover(T currentProxy) { RPC.stopProxy(currentProxy); Set<String> rmIds = new HashSet<>(); for (Entry<String, T> entry : proxies.entrySet()) { if (entry.getValue().equals(currentProxy)) { <START> rmIds.add(entry.getKey()); <END> } } for (String rmId : rmIds) { proxies.remove(rmId); } super.performFailover(currentProxy); }</code><technical_language>For readability, extract rmId = entry.getKey();</technical_language>

Target:
public synchronized void performFailover(T currentProxy) { RPC.stopProxy(currentProxy); Set<String> rmIds = new HashSet<>(); for (Entry<String, T> entry : proxies.entrySet()) { T proxy = entry.getValue(); if (proxy.equals(currentProxy)) { String rmId = entry.getKey(); rmIds.add(rmId); } } for (String rmId : rmIds) { proxies.remove(rmId); } super.performFailover(currentProxy); }
Source:
<code>public void stop() { LOG.info("Stopping event hub system consumer..."); <START> reconnectTaskRunner.shutdown(); <END> shutdownEventHubsManagers(); isStarted = false; LOG.info("Event hub system consumer stopped."); }</code><technical_language>invoke shutdownNow()</technical_language>

Target:
public void stop() { LOG.info("Stopping event hub system consumer..."); try { reconnectTaskRunner.shutdown(); shutdownEventHubsManagers(); isStarted = false; } catch (Exception e) { LOG.warn("Exception during stop.", e); } LOG.info("Event hub system consumer stopped."); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { ((WordPress) getApplication()).component().inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); if (savedInstanceState == null) { if (getIntent() != null) { mJetpackConnectSource = (JetpackConnectionSource) getIntent().getSerializableExtra(ARG_JETPACK_CONNECT_SOURCE); } mLoginAnalyticsListener.trackLoginAccessed(); switch (getLoginMode()) { case FULL: case WPCOM_LOGIN_ONLY: showFragment(new LoginPrologueFragment(), LoginPrologueFragment.TAG); break; case SELFHOSTED_ONLY: showFragment(new LoginSiteAddressFragment(), LoginSiteAddressFragment.TAG); break; case JETPACK_STATS: case WPCOM_LOGIN_DEEPLINK: case WPCOM_REAUTHENTICATE: case SHARE_INTENT: checkSmartLockPasswordAndStartLogin(); break; } } else { mSignupSheetDisplayed = savedInstanceState.getBoolean(KEY_SIGNUP_SHEET_DISPLAYED); mSmartLockHelperState = SmartLockHelperState.valueOf( savedInstanceState.getString(KEY_SMARTLOCK_HELPER_STATE)); if (mSmartLockHelperState != SmartLockHelperState.NOT_TRIGGERED) { initSmartLockHelperConnection(); } if (mSignupSheetDisplayed) { <START> mSignupSheet = new SignupBottomSheetDialogFragment(this); <END> mSignupSheet.show(getSupportFragmentManager(), SignupBottomSheetDialogFragment.TAG); } } }</code><technical_language>Do need manually recreate dialog(fragment), a configuration change? I fragment manager of activity care of for us. Wdyt</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { ((WordPress) getApplication()).component().inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); if (savedInstanceState == null) { if (getIntent() != null) { mJetpackConnectSource = (JetpackConnectionSource) getIntent().getSerializableExtra(ARG_JETPACK_CONNECT_SOURCE); } mLoginAnalyticsListener.trackLoginAccessed(); switch (getLoginMode()) { case FULL: case WPCOM_LOGIN_ONLY: showFragment(new LoginPrologueFragment(), LoginPrologueFragment.TAG); break; case SELFHOSTED_ONLY: showFragment(new LoginSiteAddressFragment(), LoginSiteAddressFragment.TAG); break; case JETPACK_STATS: case WPCOM_LOGIN_DEEPLINK: case WPCOM_REAUTHENTICATE: case SHARE_INTENT: checkSmartLockPasswordAndStartLogin(); break; } } else { mSmartLockHelperState = SmartLockHelperState.valueOf( savedInstanceState.getString(KEY_SMARTLOCK_HELPER_STATE)); if (mSmartLockHelperState != SmartLockHelperState.NOT_TRIGGERED) { initSmartLockHelperConnection(); } } }
Source:
<code>protected Event createEventByType(String eventType, String topic, String payload, String source) throws Exception { <START> if (topic.endsWith("/failed")) { <END> String[] properties = deserializePayload(payload, String[].class); Event event = new ExtensionEvent(topic, payload, properties[0], properties[1]); return event; } else { String id = deserializePayload(payload, String.class); Event event = new ExtensionEvent(topic, payload, id); return event; } }</code><technical_language>you, I prefer similar java static final String EXTENSION_FAILURE_EVENT_TOPIC_POSTFIX = "/failed"; static final String EXTENSION_FAILURE_EVENT_TOPIC = "smarthome/extensions/{id}" + EXTENSION_FAILURE_EVENT_TOPIC_POSTFIX; ... if (topic.endsWith(EXTENSION_FAILURE_EVENT_TOPIC_POSTFIX)) {</technical_language>

Target:
protected Event createEventByType(String eventType, String topic, String payload, String source) throws Exception { if (topic.endsWith(EXTENSION_FAILURE_EVENT_TOPIC_POSTFIX)) { String[] properties = deserializePayload(payload, String[].class); Event event = new ExtensionEvent(topic, payload, properties[0], properties[1]); return event; } else { String id = deserializePayload(payload, String.class); Event event = new ExtensionEvent(topic, payload, id); return event; } }
Source:
<code>public void reportSingleLogMessage( String logger, Level loglevel, String message, String exception ) { if( Backendless.isCodeRunner() ) { <START> Invoker.invokeSync( LOGGING_SERVER_ALIAS, "log", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), loglevel.name(), logger, message, exception } ); <END> } else { Invoker.invokeAsync( LOGGING_SERVER_ALIAS, "log", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), loglevel.name(), logger, message, exception }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } }</code><technical_language>getVersion? I thought rid of versions</technical_language>

Target:
public void reportSingleLogMessage( String logger, Level loglevel, String message, String exception ) { if( Backendless.isCodeRunner() ) { Invoker.invokeSync( LOGGING_SERVER_ALIAS, "log", new Object[]{ loglevel.name(), logger, message, exception } ); } else { Invoker.invokeAsync( LOGGING_SERVER_ALIAS, "log", new Object[]{ loglevel.name(), logger, message, exception }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { } @Override public void handleFault( BackendlessFault fault ) { } } ); } }
Source:
<code>public void createWithResponse() { DirectoryClient directoryClient = createClientWithSASToken(); Response<DirectoryInfo> response = directoryClient.createWithResponse( <START> Collections.singletonMap("directory", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); <END> System.out.println("Completed creating the directory with status code: " + response.statusCode()); END: com.azure.storage.file.directoryClient.createWithResponse#map-duration-context }</code><technical_language>other code snippet class duration</technical_language>

Target:
public void createWithResponse() { DirectoryClient directoryClient = createClientWithSASToken(); FileSmbProperties smbProperties = new FileSmbProperties(); String filePermission = "filePermission"; Response<DirectoryInfo> response = directoryClient.createWithResponse(smbProperties, filePermission, Collections.singletonMap("directory", "metadata"), Duration.ofSeconds(1), new Context(key1, value1)); System.out.println("Completed creating the directory with status code: " + response.statusCode()); END: com.azure.storage.file.directoryClient.createWithResponse#filesmbproperties-string-map-duration-context }
Source:
<code>public void execute() { <START> CustomizeEntryTypeDialogView dialog = new CustomizeEntryTypeDialogView(this.frame.getCurrentBasePanel().getBibDatabaseContext()); <END> dialog.showAndWait(); }</code><technical_language>Please statemanager instead of JabRefFrame. Moreover, bind executable correctly in e.g <LINK_0></technical_language>

Target:
public void execute() { BibDatabaseContext database = stateManager.getActiveDatabase().orElseThrow(() -> new NullPointerException("Database null")); CustomizeEntryTypeDialogView dialog = new CustomizeEntryTypeDialogView(database, entryTypesManager); dialog.showAndWait(); }
Source:
<code>public void testSegmentedResponseTransmit() { if (PropertyUtil.getFirstApiLevel() < <START> 28) { <END> return; } try { waitForConnection(); Reader[] readers = seService.getReaders(); for (Reader reader : readers) { for (byte[] apdu : SEGMENTED_RESP_APDU) { byte[] response = internalTransmitApdu(reader, apdu); byte[] b = { 0x00, 0x00, apdu[2], apdu[3] }; ByteBuffer wrapped = ByteBuffer.wrap(b); int expectedLength = wrapped.getInt(); assertEquals(response.length, expectedLength + 2); assertEquals(response[response.length - 1] & 0xFF, 0x00); assertEquals(response[response.length - 2] & 0xFF, 0x90); assertEquals(response[response.length - 3] & 0xFF, 0xFF); } } } catch (Exception e) { fail("unexpected exception " + e); } }</code><technical_language>instead of raw numbers please Build.Version.P similar? readable avoid errors</technical_language>

Target:
public void testSegmentedResponseTransmit() { if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.P) { return; } try { waitForConnection(); Reader[] readers = seService.getReaders(); for (Reader reader : readers) { for (byte[] apdu : SEGMENTED_RESP_APDU) { byte[] response = internalTransmitApdu(reader, apdu); byte[] b = { 0x00, 0x00, apdu[2], apdu[3] }; ByteBuffer wrapped = ByteBuffer.wrap(b); int expectedLength = wrapped.getInt(); assertEquals(response.length, expectedLength + 2); assertEquals(response[response.length - 1] & 0xFF, 0x00); assertEquals(response[response.length - 2] & 0xFF, 0x90); assertEquals(response[response.length - 3] & 0xFF, 0xFF); } } } catch (Exception e) { fail("unexpected exception " + e); } }
Source:
<code>public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } int totDuration = 0; int totMotion = 0; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += stat.motionScore.numMotions; totDuration += stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentageFloat = (float) totMotion / (float) totDuration; final int averageMotionPercentage = (int) (averageMotionPercentageFloat * 100.0f); final float overallDiffFloat = (averageMotionPercentageFloat - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC * 100.0f; final int overallDiff = (int) overallDiffFloat; <START> <END> Text text; if (Math.abs(overallDiffFloat) >= SIGNIFICANT_DIFF) { if (overallDiffFloat > 0) { text = SleepMotionMsgEN.moreMovement(numDays, overallDiff, averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, overallDiff, averageMotionPercentage); } } else { text = SleepMotionMsgEN.equalMovement(numDays, overallDiff, averageMotionPercentage); } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }</code><technical_language>change AVERAGE_SLEEP_PERC SIGNIFICANT_DIFF static int, need float version around. need precise</technical_language>

Target:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }
Source:
<code><START> public void whenDeleteEventTypeNotAdminAndDeletionDeactivatedThenForbidden() throws Exception { <END> final EventType eventType = buildDefaultEventType(); doReturn(eventType).when(eventTypeRepository).findByName(eventType.getName()); doReturn(Optional.of(eventType)).when(eventTypeRepository).findByNameO(eventType.getName()); doReturn(SecuritySettings.AuthMode.BASIC).when(settings).getAuthMode(); doReturn(true).when(featureToggleService).isFeatureEnabled(CHECK_APPLICATION_LEVEL_PERMISSIONS); doReturn(true).when(featureToggleService).isFeatureEnabled(DISABLE_EVENT_TYPE_DELETION); final Multimap<TopicRepository, String> topicsToDelete = ArrayListMultimap.create(); topicsToDelete.put(topicRepository, eventType.getTopic()); doReturn(topicsToDelete).when(timelineService).deleteAllTimelinesForEventType(eventType.getName()); deleteEventType(eventType.getName(), "somebody").andExpect(status().isForbidden()); }</code><technical_language>methods line. extract a helper method here</technical_language>

Target:
public void whenDeleteEventTypeNotAdminAndDeletionDeactivatedThenForbidden() throws Exception { final EventType eventType = buildDefaultEventType(); postEventType(eventType); disableETDeletionFeature(); deleteEventType(eventType.getName(), "somebody").andExpect(status().isForbidden()); }
Source:
<code>public void testDateTimeFormatterLocaleChange() throws AuthenticationException { DefaultTokenCacheStore store = (DefaultTokenCacheStore) setupItems(); List<TokenCacheItem> tokens = store.getTokensForResource("resource"); <START> final long precision = 1000; <END> TokenCacheItem item = tokens.get(0); String cacheKey = CacheKey.createCacheKey(item); Calendar time = Calendar.getInstance(); Date dateTimeNow = time.getTime(); long timeNowMiliSeconds = dateTimeNow.getTime(); item.setExpiresOn(dateTimeNow); store.setItem(cacheKey, item); TokenCacheItem fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.FRANCE); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.US); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+03:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+05:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); }</code><technical_language>this. DefaultTokenCacheStore objects in rest of this file final too. #Closed</technical_language>

Target:
public void testDateTimeFormatterLocaleChange() throws AuthenticationException { final DefaultTokenCacheStore store = (DefaultTokenCacheStore) setupItems(); List<TokenCacheItem> tokens = store.getTokensForResource("resource"); final long precision = 1000; TokenCacheItem item = tokens.get(0); String cacheKey = CacheKey.createCacheKey(item); Calendar time = Calendar.getInstance(); Date dateTimeNow = time.getTime(); long timeNowMiliSeconds = dateTimeNow.getTime(); item.setExpiresOn(dateTimeNow); store.setItem(cacheKey, item); TokenCacheItem fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.FRANCE); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); Locale.setDefault(Locale.US); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+03:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); TimeZone.setDefault(TimeZone.getTimeZone("GMT+05:00")); fromCache = store.getItem(cacheKey); assertTrue(Math.abs(timeNowMiliSeconds - fromCache.getExpiresOn().getTime()) < precision); }
Source:
<code>private boolean sendUsingSmpp(String from, String to, String body, TlvSet tlvSet, Charset encoding) { if ((SmppClientOpsThread.getSmppSession() != null && SmppClientOpsThread.getSmppSession().isBound()) && smppMessageHandler != null) { if(logger.isInfoEnabled()) { logger.info("SMPP session is available and connected, outbound message will be forwarded to : " + to ); logger.info("Encoding: " + encoding ); } SmsMessage record = (SmsMessage)this.attributes.get("record"); Sid sid = null; if(record!=null) { sid = record.getSid(); <START> logger.error("record sid = "+sid.toString()); <END> }else{ logger.error("record is null"); } try { final SmppOutboundMessageEntity sms = new SmppOutboundMessageEntity(to, from, body, encoding, tlvSet, sid); smppMessageHandler.tell(sms, null); }catch (final Exception exception) { logger.error("There was an error sending SMS to SMPP endpoint : " + exception); } return true; } return false; }</code><technical_language>lets cautius logger level. I dont thin kthis is error level</technical_language>

Target:
private boolean sendUsingSmpp(String from, String to, String body, TlvSet tlvSet, Charset encoding) { if ((SmppClientOpsThread.getSmppSession() != null && SmppClientOpsThread.getSmppSession().isBound()) && smppMessageHandler != null) { if(logger.isInfoEnabled()) { logger.info("SMPP session is available and connected, outbound message will be forwarded to : " + to ); logger.info("Encoding: " + encoding ); } SmsMessage record = (SmsMessage)this.attributes.get("record"); Sid sid = null; if(record!=null) { sid = record.getSid(); if(logger.isInfoEnabled()) { logger.info("record sid = "+sid.toString()); } }else{ logger.error("record is null"); } try { final SmppOutboundMessageEntity sms = new SmppOutboundMessageEntity(to, from, body, encoding, tlvSet, sid); smppMessageHandler.tell(sms, null); }catch (final Exception exception) { logger.error("There was an error sending SMS to SMPP endpoint : " + exception); } return true; } return false; }
Source:
<code>public GenericEdge(GenericVertexRef source, GenericVertexRef target, Map<String, Object> properties) { super(properties); this.source = Objects.requireNonNull(source); this.target = Objects.requireNonNull(target); if(!source.getNamespace().equals(getNamespace()) && !target.getNamespace().equals(getNamespace())) { <START> throw new IllegalArgumentException( <END> String.format("Neither the namespace of the source VertexRef(namespace=%s) nor the target VertexRef(%s) matches our namespace=%s", source.getNamespace(), target.getNamespace(), getNamespace())); } this.setId(source.getNamespace() + ":" + source.getId() + "->" + target.getNamespace() + ":" + target.getId()); }</code><technical_language>This is in general a bit tricky. This check implies, namespace is contained in properties. Is this case? namespace enforced equal Besides this, edge connect vertex, pointing itself. This often, AFAIK happen linkd</technical_language>

Target:
private GenericEdge(GenericVertexRef source, GenericVertexRef target, Map<String, Object> properties) { super(properties); this.source = Objects.requireNonNull(source); this.target = Objects.requireNonNull(target); if(!source.getNamespace().equals(getNamespace()) && !target.getNamespace().equals(getNamespace())) { throw new IllegalArgumentException( String.format("Neither the namespace of the source VertexRef(namespace=%s) nor the target VertexRef(%s) matches our namespace=%s", source.getNamespace(), target.getNamespace(), getNamespace())); } this.setId(source.getNamespace() + ":" + source.getId() + "->" + target.getNamespace() + ":" + target.getId()); }
Source:
<code>private void notifyPacketReceived(final XBeePacket packet) { try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); <START> ScheduledExecutorService executor = Executors.newScheduledThreadPool(packetReceiveListeners.size()); <END> for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).hasAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>moment thread pool size number of listeners notify. want set a thread limit a constant (that modified) set thread pool size minimum constant real listeners size. This way, if notify for example 60 listeners do create 60 threads</technical_language>

Target:
private void notifyPacketReceived(final XBeePacket packet) { try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, packetReceiveListeners.size())); for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).needsAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { e.printStackTrace(); } }
Source:
<code><START> public static long inMillis(String durationStr) { <END> String[] parts = durationStr.trim().split(":"); if (parts.length == 1) { return toMillis(parts[0]); } else if (parts.length == 2) { return toMillis("0", parts[0], parts[1]); } else if (parts.length == 3) { return toMillis(parts[0], parts[1], parts[2]); } else { throw new NumberFormatException(); } }</code><technical_language>I explicitly write throws NumberFormatException here</technical_language>

Target:
public static long inMillis(String durationStr) throws NumberFormatException { String[] parts = durationStr.trim().split(":"); if (parts.length == 1) { return toMillis(parts[0]); } else if (parts.length == 2) { return toMillis("0", parts[0], parts[1]); } else if (parts.length == 3) { return toMillis(parts[0], parts[1], parts[2]); } else { throw new NumberFormatException(); } }
Source:
<code><START> public void lowerBoundDifferentNumberOfTokens() { <END> Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); Map<String, TrackingToken> expectedTokens = new HashMap<>(); expectedTokens.put("token1", new GlobalSequenceTrackingToken(0)); expectedTokens.put("token2", new GlobalSequenceTrackingToken(0)); ; MultiSourceTrackingToken newMultiToken = (MultiSourceTrackingToken) testSubject .lowerBound(new MultiSourceTrackingToken(newTokens)); }</code><technical_language>I upperBound() covers() method benefit a number of tokens test</technical_language>

Target:
public void lowerBoundDifferentNumberOfTokens() { Map<String, TrackingToken> newTokens = new HashMap<>(); newTokens.put("token1", new GlobalSequenceTrackingToken(1)); testSubject.lowerBound(new MultiSourceTrackingToken(newTokens)); }
Source:
<code>public ScreenshotSize get() { <START> if (config.getScreenshotSize() == ScreenshotSize.DOUBLE_SIZE) { <END> return ScreenshotSize.DOUBLE_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.NORMAL_SIZE) { return ScreenshotSize.NORMAL_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.HALF_SIZE) { return ScreenshotSize.HALF_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.QUARTER_SIZE) { return ScreenshotSize.QUARTER_SIZE; } else { return ScreenshotSize.NORMAL_SIZE; } }</code><technical_language>Again, return if null</technical_language>

Target:
public ScreenshotSize get() { if(config.getScreenshotSize() != null) { return config.getScreenshotSize(); } else { return ScreenshotSize.NORMAL_SIZE; } }
Source:
<code>private String getNextRunMessage(String field) { <START> if (field.equals("minAllocatedMem")) { END> String translated = nextRunMessages.minAllocatedMem(); try { translated = nextRunMessages.getString("minAllocatedMem"); } catch (MissingResourceException e) { } return translated; } return field; }</code><technical_language>need for this check</technical_language>

Target:
private String getNextRunMessage(String field) { try { return nextRunMessages.getString(field); } catch (MissingResourceException e) { } return field; }
Source:
<code>public void error(String message, Throwable t) { LoggerFactory lf = getLoggerFactory(); if (lf == null) { parentServletContext.log(message, t); } else { lf.getLogger(consumingContext.getBundle(), HttpServiceRuntimeImpl.class.getName(), <START> Logger.class).error("{}", message, t); END> } }</code><technical_language>call error(message, t);</technical_language>

Target:
public void error(String message, Throwable t) { Logger logger = loggerFactoryTracker.getService(); if (logger == null) { parentServletContext.log(String.valueOf(message), t); } else { logger.error(String.valueOf(message), t); } }
Source:
<code>public String confirmation(@QueryParam("hash") String hash) throws Exception { QueryFactory query = orcsApi.getQueryFactory(null); AccountInfoData info = accountOps.getAccountData(accountId); int groupId = 0; int userId = 0; <START> String[] combined = EncryptUtility.decrypt(hash, SECRET).split(":"); <END> userId = Integer.parseInt(combined[0]); groupId = Integer.parseInt(combined[1]); if (info.getAccountId() != userId) { throw new OseeCoreException(String.format("Invalid hash[%s] in request", hash)); } ArtifactReadable user = query.fromBranch(COMMON).andLocalId(userId).getResults().getExactlyOne(); ArtifactReadable group = query.fromBranch(COMMON).andLocalId(groupId).getResults().getExactlyOne(); ResourceToken token = new ClassBasedResourceToken("groupUnsubscribe.html", getClass()); return PageFactory.realizePage(orcsApi.getResourceRegistry(), token, "userName", user.getName(), "groupName", group.getName(), "hash", hash); }</code><technical_language>null check hash get error message null pointer constraint error</technical_language>

Target:
public String confirmation(@QueryParam("hash") String hash) throws Exception { Conditions.checkNotNull(hash, "Hash parameter"); QueryFactory query = orcsApi.getQueryFactory(null); AccountInfoData info = accountOps.getAccountData(accountId); int groupId = 0; int userId = 0; String[] combined = EncryptUtility.decrypt(hash, SECRET).split(":"); userId = Integer.parseInt(combined[0]); groupId = Integer.parseInt(combined[1]); if (info.getAccountId() != userId) { throw new OseeCoreException(String.format("Invalid hash[%s] in request", hash)); } ArtifactReadable user = query.fromBranch(COMMON).andLocalId(userId).getResults().getExactlyOne(); ArtifactReadable group = query.fromBranch(COMMON).andLocalId(groupId).getResults().getExactlyOne(); ResourceToken token = new ClassBasedResourceToken("groupUnsubscribe.html", getClass()); return PageFactory.realizePage(orcsApi.getResourceRegistry(), token, "userName", user.getName(), "groupName", group.getName(), "hash", hash); }
Source:
<code>private String signJsonWebSignature(JsonFactory jsonFactory, JsonWebSignature.Header header, JsonWebToken.Payload payload) throws IOException { String signedContentString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header)) + "." + Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload)); byte[] signedContentBytes = StringUtils.getBytesUtf8(signedContentString); try { byte[] signature = this.sign(signedContentBytes); return signedContentString + "." + Base64.encodeBase64URLSafeString(signature); } catch (Exception e) { throw new IOException( <START> "Error signing service account access token request with private key.", e); <END> } }</code><technical_language>googlestyle 4 space indents for continuation lines</technical_language>

Target:
private String signJsonWebSignature(JsonFactory jsonFactory, JsonWebSignature.Header header, JsonWebToken.Payload payload) throws IOException { String signedContentString = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header)) + "." + Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload)); byte[] signedContentBytes = StringUtils.getBytesUtf8(signedContentString); try { byte[] signature = this.sign(signedContentBytes); return signedContentString + "." + Base64.encodeBase64URLSafeString(signature); } catch (SigningException e) { throw new IOException( "Error signing service account access token request with private key.", e); } }
Source:
<code>public static boolean hasOpenCvLoaded() { <START> return OPEN_CV_LOADED; <END> }</code><technical_language>I OPEN_CV_LOADED identifier is new, while in put in standard varibale name camel case, this is a constant</technical_language>

Target:
public static boolean hasOpenCvLoaded() { return openCvLoaded; }
Source:
<code>private boolean isUseJournalStore() throws IOException { <START> return operations.readAttribute(TRANSACTIONS_ADDRESS, USE_JOURNAL_STORE_ATTR).value().asBoolean(); <END> }</code><technical_language>booleanValue() instead of .value().asBoolean()</technical_language>

Target:
private boolean isUseJournalStore() throws IOException { return operations.readAttribute(TRANSACTIONS_ADDRESS, USE_JOURNAL_STORE_ATTR).booleanValue(); }
Source:
<code>public static void checkDataBlock( PropertyBlock block, CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine, RecordAccess records ) { if ( block.getKeyIndexId() < 0 ) { engine.report().invalidPropertyKey( block ); } else { engine.comparativeCheck( records.propertyKey( block.getKeyIndexId() ), propertyKey( block ) ); } PropertyType type = block.forceGetType(); if ( type == null ) { engine.report().invalidPropertyType( block ); } else { switch ( type ) { case STRING: engine.comparativeCheck( records.string( block.getSingleValueLong() ), DynamicReference.string( block ) ); break; case ARRAY: engine.comparativeCheck( records.array( block.getSingleValueLong() ), DynamicReference.array( block ) ); break; default: try { <START> type.getValueNow( block, null ); <END> } catch ( Exception e ) { engine.report().invalidPropertyValue( block ); } break; } } }</code><technical_language>I prefer if call methods getValue getLazyValue lazyValue instead</technical_language>

Target:
public static void checkDataBlock( PropertyBlock block, CheckerEngine<PropertyRecord, ConsistencyReport.PropertyConsistencyReport> engine, RecordAccess records ) { if ( block.getKeyIndexId() < 0 ) { engine.report().invalidPropertyKey( block ); } else { engine.comparativeCheck( records.propertyKey( block.getKeyIndexId() ), propertyKey( block ) ); } PropertyType type = block.forceGetType(); if ( type == null ) { engine.report().invalidPropertyType( block ); } else { switch ( type ) { case STRING: engine.comparativeCheck( records.string( block.getSingleValueLong() ), DynamicReference.string( block ) ); break; case ARRAY: engine.comparativeCheck( records.array( block.getSingleValueLong() ), DynamicReference.array( block ) ); break; default: try { type.value( block, null ); } catch ( Exception e ) { engine.report().invalidPropertyValue( block ); } break; } } }
Source:
<code>public ValidationResult diskImagesBelongToSameImageGroup() { Guid imageGroupId = null; for (DiskImage diskImage : diskImages) { if (imageGroupId == null || diskImage.getId().equals(imageGroupId)) { imageGroupId = diskImage.getId(); <START> continue; <END> } return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_SNAPSHOTS_DONT_BELONG_TO_SAME_DISK, String.format("diskalias %s", diskImage.getDiskAlias())); } return ValidationResult.VALID; }</code><technical_language>disk id is right one</technical_language>

Target:
public ValidationResult diskImagesBelongToSameImageGroup() { Guid imageGroupId = null; for (DiskImage diskImage : diskImages) { if (imageGroupId == null || diskImage.getId().equals(imageGroupId)) { imageGroupId = diskImage.getId(); continue; } return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_DISKS_SNAPSHOTS_DONT_BELONG_TO_SAME_DISK); } return ValidationResult.VALID; }
Source:
<code>public void actionPerformed(ActionEvent e) { try { <START> backend.resetCoordinateToZero('Z'); <END> } catch (Exception ex) { GUIHelpers.displayErrorDialog(ex.getLocalizedMessage()); } }</code><technical_language>I this is code, I love a enum constant instead of magic char</technical_language>

Target:
public void actionPerformed(ActionEvent e) { try { backend.resetCoordinateToZero(Z); } catch (Exception ex) { GUIHelpers.displayErrorDialog(ex.getLocalizedMessage()); } }