auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public UserGroup(UserClock clock, int id, ProcessingConfig.Test.Task.User config, long time) { this(clock, id, Parser.parseInt(config.getCount(), clock.getRandom()), (int) config.getStartCount(), time + Parser.parseTime(config.getStartIn(), clock.getRandom()), Parser.parseTime(config.getStartBy(), clock.getRandom()), Parser.parseTime(config.getLife(), clock.getRandom()) ); double floor = (Double.compare(config.getStartCount(), 1.0) < 0) ? +0.0 : +Math.floor(config.getStartCount()); double slewRate = config.getStartCount() - floor; <START> this.slewRate = slewRate; <END> this.extraUser = slewRate; }</code><technical_language>is slew rate (users/seconds). is extraUserStep (users)</technical_language>

Target:
public UserGroup(UserClock clock, int id, ProcessingConfig.Test.Task.User config, long time) { this(clock, id, Parser.parseInt(config.getCount(), clock.getRandom()), (int) config.getStartCount(), time + Parser.parseTime(config.getStartIn(), clock.getRandom()), Parser.parseTime(config.getStartBy(), clock.getRandom()), Parser.parseTime(config.getLife(), clock.getRandom()) ); double floor = (Double.compare(config.getStartCount(), 1.0) < 0) ? +0.0 : +Math.floor(config.getStartCount()); double extraUserStep = config.getStartCount() - floor; this.extraUserStep = extraUserStep; this.extraUser = extraUserStep; }
Source:
<code>private void clearMetadata(Entry entry) { entry.setAuthor(null); entry.setEmail(null); <START> entry.setDescription(null); <END> }</code><technical_language>In lieu of validation in develop, akin "syntax error, please check WDL file"</technical_language>

Target:
private void clearMetadata(Entry entry) { entry.setAuthor(null); entry.setEmail(null); entry.setDescription(WDL_SYNTAX_ERROR); }
Source:
<code><START> public MemberInfo apply(GroupResource resource, Input input) <END> throws AuthException, BadRequestException, ResourceConflictException, Exception { final GroupDescription.Basic group = resource.getGroup(); if (!(group instanceof GroupDescription.Internal)) { throw new MethodNotAllowedException(); } final Account a = findAccount(input.nameOrEmail); if (!a.isActive()) { throw new InactiveAccountException(a.getFullName()); } final AccountGroup internalGroup = ((GroupDescription.Internal) group).getAccountGroup(); final GroupControl control = groupControlFactory.controlFor(internalGroup); if (!control.canAddMember(a.getId())) { throw new AuthException("Cannot add member: " + a.getFullName()); } final AccountGroupMember.Key key = new AccountGroupMember.Key(a.getId(), internalGroup.getId()); AccountGroupMember m = db.accountGroupMembers().get(key); if (m == null) { m = new AccountGroupMember(key); db.accountGroupMembersAudit().insert( Collections.singleton(new AccountGroupMemberAudit(m, m.getAccountId()))); db.accountGroupMembers().insert(Collections.singleton(m)); accountCache.evict(m.getAccountId()); } return MembersCollection.parse(a); }</code><technical_language>This return List<MemberInfo> if multiple members put once</technical_language>

Target:
public List<MemberInfo> apply(GroupResource resource, Input input) throws AuthException, BadRequestException, ResourceConflictException, Exception { final GroupDescription.Basic group = resource.getGroup(); if (!(group instanceof GroupDescription.Internal)) { throw new MethodNotAllowedException(); } final List<AccountGroupMember> newAccountGroupMembers = Lists.newLinkedList(); final List<AccountGroupMemberAudit> newAccountGroupMemberAudits = Lists.newLinkedList(); final List<String> errors = Lists.newLinkedList(); final List<MemberInfo> newMembers = Lists.newLinkedList(); final Account.Id me = ((IdentifiedUser) self.get()).getAccountId(); for (final String nameOrEmail : input.members) { final Account a; try { a = findAccount(nameOrEmail); } catch (NoSuchAccountException e) { errors.add(e.getMessage()); continue; } if (!a.isActive()) { errors.add((new InactiveAccountException(a.getFullName())).getMessage()); continue; } final AccountGroup internalGroup = ((GroupDescription.Internal) group).getAccountGroup(); final GroupControl control = groupControlFactory.controlFor(internalGroup); if (!control.canAddMember(a.getId())) { throw new AuthException("Cannot add member: " + a.getFullName()); } final AccountGroupMember.Key key = new AccountGroupMember.Key(a.getId(), internalGroup.getId()); AccountGroupMember m = db.accountGroupMembers().get(key); if (m == null) { m = new AccountGroupMember(key); newAccountGroupMembers.add(m); newAccountGroupMemberAudits.add(new AccountGroupMemberAudit(m, me)); } newMembers.add(MembersCollection.parse(a)); } failWithBadRequestOnError(errors); db.accountGroupMembersAudit().insert(newAccountGroupMemberAudits); db.accountGroupMembers().insert(newAccountGroupMembers); for (final AccountGroupMember m : newAccountGroupMembers) { accountCache.evict(m.getAccountId()); } return newMembers; }
Source:
<code>private void changeUserStatus( final String userId, final UserStatusEnum newUserStatus, final AsyncCallback<Void> responder ) { <START> synchronized( currentUserLock ) <END> { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "changeUserStatus", new Object[] { userId, newUserStatus }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { if( currentUser != null && !currentUser.isEmpty() && currentUser.getObjectId().equals( userId ) ) currentUser.setProperty( USER_STATUS_COLUMN, newUserStatus.toString() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } }</code><technical_language>do need synchronized</technical_language>

Target:
private void changeUserStatus( final String userId, final UserStatusEnum newUserStatus, final AsyncCallback<Void> responder ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "changeUserStatus", new Object[] { userId, newUserStatus }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { if( currentUser != null && !currentUser.isEmpty() && currentUser.getObjectId().equals( userId ) ) currentUser.setProperty( USER_STATUS_COLUMN, newUserStatus.toString() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); }
Source:
<code><START> static void replyError(HttpServletResponse res, int statusCode, <END> String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }</code><technical_language>Unnecessary</technical_language>

Target:
public static void replyError(HttpServletResponse res, int statusCode, String msg) throws IOException { res.setStatus(statusCode); CacheHeaders.setNotCacheable(res); replyText(null, res, msg); }
Source:
<code>public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = "invalid_type_true"; setAuthenticationPrincipal(principal); try { resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null); fail("should not reach here"); <START> } catch(ClassCastException ex) <END> }</code><technical_language>AssertJ's assertThatCode instead of try-catch</technical_language>

Target:
public void resolveArgumentSecurityContextErrorOnInvalidTypeTrue() throws Exception { String principal = "invalid_type_true"; setAuthenticationPrincipal(principal); assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeTrue(), null, null, null)); }
Source:
<code>private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId, List<Integer> logsQuarks) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); String childName = ss.getAttributeName(child); if (!childName.equals(IOpenTracingConstants.LOGS)) { List<LogEvent> logs = new ArrayList<>(); int logQuark = getLogQuark(ss, childName, logsQuarks); long startTime = ss.getStartTime(); try { <START> for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(child), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { startTime = interval.getStartTime(); break; } } <END> for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(logQuark), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { logs.add(new LogEvent(interval.getStartTime(), String.valueOf(interval.getValue()))); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { } builder.add(new SpanLifeEntryModel(childId, parentId, getSpanName(childName), startTime, ss.getCurrentEndTime(), logs, getErrorTag(childName))); addChildren(ss, builder, child, childId, logsQuarks); } } }</code><technical_language>I need anymore</technical_language>

Target:
private void addChildren(ITmfStateSystem ss, Builder<@NonNull TimeGraphEntryModel> builder, int quark, long parentId, List<Integer> logsQuarks) { for (Integer child : ss.getSubAttributes(quark, false)) { long childId = getId(child); String childName = ss.getAttributeName(child); if (!childName.equals(IOpenTracingConstants.LOGS)) { List<LogEvent> logs = new ArrayList<>(); int logQuark = getLogQuark(ss, childName, logsQuarks); try { for (ITmfStateInterval interval : ss.query2D(Collections.singletonList(logQuark), ss.getStartTime(), ss.getCurrentEndTime())) { if (!interval.getStateValue().isNull()) { logs.add(new LogEvent(interval.getStartTime(), String.valueOf(interval.getValue()))); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { } builder.add(new SpanLifeEntryModel(childId, parentId, getSpanName(childName), ss.getStartTime(), ss.getCurrentEndTime(), logs, getErrorTag(childName))); addChildren(ss, builder, child, childId, logsQuarks); } } }
Source:
<code>private FTPClient createClient() throws FileSystemException { final GenericFileName rootName = getRoot(); Map<String,String>mParams = null; if(rootName instanceof URLFileName){ mParams = getQueryParams((URLFileName)rootName); } UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES); if (mParams == null) { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())), <START> rootName.getPath(), getFileSystemOptions(), <END> defaultTimeout); } else { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())), rootName.getPath(), getFileSystemOptions(), mParams.get(SftpConstants.PROXY_SERVER), mParams.get(SftpConstants.PROXY_PORT), mParams.get(SftpConstants.PROXY_USERNAME), mParams.get(SftpConstants.PROXY_PASSWORD), mParams.get(SftpConstants.TIMEOUT), mParams.get(SftpConstants.RETRY_COUNT), defaultTimeout); } } finally { UserAuthenticatorUtils.cleanup(authData); } }</code><technical_language>Formatting issues</technical_language>

Target:
private FTPClient createClient() throws FileSystemException { final GenericFileName rootName = getRoot(); Map<String,String>mParams = null; if(rootName instanceof URLFileName){ mParams = getQueryParams((URLFileName)rootName); } UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES); char[] username = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())); char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())); if (mParams == null) { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), username, password, rootName.getPath(), getFileSystemOptions(), defaultTimeout); } else { return FtpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), username, password, rootName.getPath(), getFileSystemOptions(), mParams.get(SftpConstants.PROXY_SERVER), mParams.get(SftpConstants.PROXY_PORT), mParams.get(SftpConstants.PROXY_USERNAME), mParams.get(SftpConstants.PROXY_PASSWORD), mParams.get(SftpConstants.TIMEOUT), mParams.get(SftpConstants.RETRY_COUNT), defaultTimeout); } } finally { UserAuthenticatorUtils.cleanup(authData); } }
Source:
<code>public void updateField(Pool pool, double value, String units) { <START> throw new UnsupportedOperationException("Method not implemented for unspecified field"); <END> }</code><technical_language>![CRITICAL](<LINK_0> 'Severity: CRITICAL') Define a constant instead of duplicating this literal "Method implemented for unspecified field" 5 times. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public void updateField(Pool pool, double value, String units) { pool.setConcentration(value); pool.setConcentrationUnits(units); }
Source:
<code>public void storeSettings() { <START> PreviewPreferences previewPreferences = Globals.prefs.getPreviewPreferences(); <END> if (chosenListProperty.isEmpty()) { chosenListProperty.add(previewPreferences.getTextBasedPreviewLayout()); } PreviewPreferences newPreviewPreferences = Globals.prefs.getPreviewPreferences() .getBuilder() .withPreviewCycle(chosenListProperty) .withPreviewStyle(previewTextProperty.getValue().replace("\n", "__NEWLINE__")) .build(); if (!selectedChosenItemsProperty.getValue().isEmpty()) { newPreviewPreferences = newPreviewPreferences.getBuilder().withPreviewCyclePosition(chosenListProperty.getValue().indexOf(selectedChosenItemsProperty.get(0))).build(); } Globals.prefs.storePreviewPreferences(newPreviewPreferences); for (BasePanel basePanel : JabRefGUI.getMainFrame().getBasePanelList()) { basePanel.closeBottomPane(); } }</code><technical_language>preferences.getPreviewPreferences() ? a JabRef prefs object</technical_language>

Target:
public void storeSettings() { PreviewPreferences previewPreferences = preferences.getPreviewPreferences(); if (chosenListProperty.isEmpty()) { chosenListProperty.add(previewPreferences.getTextBasedPreviewLayout()); } PreviewLayout previewStyle = findLayoutByName("Preview"); if (previewStyle == null) { previewStyle = previewPreferences.getTextBasedPreviewLayout(); } PreviewPreferences newPreviewPreferences = preferences.getPreviewPreferences() .getBuilder() .withPreviewCycle(chosenListProperty) .withPreviewStyle(((TextBasedPreviewLayout) previewStyle).getText()) .build(); if (!chosenSelectionModelProperty.getValue().getSelectedItems().isEmpty()) { newPreviewPreferences = newPreviewPreferences.getBuilder().withPreviewCyclePosition( chosenListProperty.getValue().indexOf( chosenSelectionModelProperty.getValue().getSelectedItems().get(0))).build(); } preferences.storePreviewPreferences(newPreviewPreferences); for (BasePanel basePanel : JabRefGUI.getMainFrame().getBasePanelList()) { basePanel.closeBottomPane(); } }
Source:
<code>double calculateDistance(final Target fromTarget, final Target toTarget) { final SimpleInterval fromInterval = fromTarget.getInterval(); final SimpleInterval toInterval = toTarget.getInterval(); if (fromInterval == null || toInterval == null) { return 0.0; <START> } else if (!fromInterval.getContig().equals(toInterval.getContig())) { <END> return Double.POSITIVE_INFINITY; } else { final double distance = toInterval.getStart() - fromInterval.getEnd() - 1; return distance > 0 ? distance : Math.max(0, fromInterval.getStart() - toInterval.getEnd() - 1); } }</code><technical_language>This is time in this PR comparison of targets' contigs up. worth extracting a method somewhere</technical_language>

Target:
double calculateDistance(final Target fromTarget, final Target toTarget) { final SimpleInterval fromInterval = fromTarget.getInterval(); final SimpleInterval toInterval = toTarget.getInterval(); if (fromInterval == null || toInterval == null) { return 0.0; } else if (fromInterval.overlaps(toInterval)) { return 0.0; } if (!fromInterval.getContig().equals(toInterval.getContig())) { return Double.POSITIVE_INFINITY; } else if (fromInterval.getStart() < toInterval.getStart()) { return toInterval.getStart() - fromInterval.getEnd() - 1; } else { return fromInterval.getStart() - toInterval.getEnd() - 1; } }
Source:
<code>public void describeTo(final Description description) { description.appendText("header: ") .appendDescriptionOf(this.headerm) <START> .appendText(VALUES_STR) <END> .appendDescriptionOf(this.valuem); }</code><technical_language>@exper0 full path HmRsHeader.VALUES_STR</technical_language>

Target:
public void describeTo(final Description description) { description.appendText("header: ") .appendDescriptionOf(this.header) .appendText(HmRsHeader.VALUES_STR) .appendDescriptionOf(this.value); }
Source:
<code>public synchronized Transaction beginTransaction( String bookmark ) { <START> setLastBookmark( bookmark ); <END> return beginTransaction(); }</code><technical_language>disallow a user set null bookmark? (It sense, a user wants break CC this tx?)</technical_language>

Target:
public synchronized Transaction beginTransaction( String bookmark ) { lastBookmark = bookmark; return beginTransaction(); }
Source:
<code>private ChatScriptMessage createMessage(String message) throws InvalidInputMessage { ChatScriptMessage ret = null; try { ret = mapper.readValue(message, ChatScriptMessage.class); } catch (Exception e) { e.printStackTrace(); <START> throw new InvalidInputMessage("Unable to parse the input message. Error Message" + e.getMessage()); <END> } return ret; }</code><technical_language>need create exception, requires change default behavior. Please a standard for use-case</technical_language>

Target:
private ChatScriptMessage createMessage(String message) throws Exception { ChatScriptMessage ret = null; try { ret = mapper.readValue(message, ChatScriptMessage.class); } catch (Exception e) { e.printStackTrace(); throw new Exception("Unable to parse the input message. Error Message" + e.getMessage()); } return ret; }
Source:
<code>@Test public void testJsonType() { check("select json_type(ename) from emp"); checkExp("json_type('{\"foo\":\"bar\"}')"); <START> checkExpType("json_type('{\"foo\":\"bar\"}')", "VARCHAR(20) NOT NULL"); <END> }</code><technical_language>I prefer adding a case for json_type(1), fail validation</technical_language>

Target:
@Test public void testJsonType() { check("select json_type(ename) from emp"); checkExp("json_type('{\"foo\":\"bar\"}')"); checkExpType("json_type('{\"foo\":\"bar\"}')", "VARCHAR(20) NOT NULL"); checkFails("select json_type(^1^) from emp", "(.*)JSON_VALUE_EXPRESSION(.*)"); }
Source:
<code>public AsyncJobStatusDTO populate(ModelTranslator translator, AsyncJobStatus source, AsyncJobStatusDTO destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } Date created = source.getCreated(); destination.setCreated(created != null ? created.toInstant().atOffset(ZoneOffset.UTC) : null); Date updated = source.getUpdated(); destination.setUpdated(updated != null ? updated.toInstant().atOffset(ZoneOffset.UTC) : null); destination.setId(source.getId()); <START> destination.setKey(source.getJobKey()); <END> destination.setName(source.getName()); destination.setGroup(source.getGroup()); destination.setOrigin(source.getOrigin()); destination.setExecutor(source.getExecutor()); destination.setPrincipal(source.getPrincipalName()); JobState state = source.getState(); destination.setState(state != null ? state.name() : null); JobState pstate = source.getPreviousState(); destination.setPreviousState(pstate != null ? pstate.name() : null); Date startTime = source.getStartTime(); destination.setStartTime(startTime != null ? startTime.toInstant().atOffset(ZoneOffset.UTC) : null); Date endTime = source.getEndTime(); destination.setEndTime(endTime != null ? endTime.toInstant().atOffset(ZoneOffset.UTC) : null); destination.setAttempts(source.getAttempts()); destination.setMaxAttempts(source.getMaxAttempts()); destination.setStatusPath("/jobs/" + source.getId()); destination.setResultData(source.getJobResult()); return destination; }</code><technical_language>@sonalidhome self-reference setter methods. destination.id(...).key(..).name('..') ..</technical_language>

Target:
public AsyncJobStatusDTO populate(ModelTranslator translator, AsyncJobStatus source, AsyncJobStatusDTO destination) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (destination == null) { throw new IllegalArgumentException("destination is null"); } destination.created(source.getCreated() != null ? source.getCreated().toInstant().atOffset(ZoneOffset.UTC) : null) .updated(source.getUpdated() != null ? source.getUpdated().toInstant().atOffset(ZoneOffset.UTC) : null) .id(source.getId()) .key(source.getJobKey()) .name(source.getName()) .group(source.getGroup()) .origin(source.getOrigin()) .executor(source.getExecutor()) .principal(source.getPrincipalName()) .state(source.getState() != null ? source.getState().name() : null) .previousState(source.getPreviousState() != null ? source.getPreviousState().name() : null) .startTime(source.getStartTime() != null ? source.getStartTime().toInstant().atOffset(ZoneOffset.UTC) : null) .endTime(source.getEndTime() != null ? source.getEndTime().toInstant().atOffset(ZoneOffset.UTC) : null) .attempts(source.getAttempts()) .maxAttempts(source.getMaxAttempts()) .statusPath(source.getId() != null ? String.format("/jobs/%s", source.getId()) : null) .resultData(source.getJobResult()); return destination; }
Source:
<code>public static void setUpBeforeClass() throws IOException { final Set<Class<?>> checks = CheckUtil.getCheckstyleChecks() .stream() .filter(check -> !AbstractJavadocCheck.class.isAssignableFrom(check)) .collect(Collectors.toSet()); <START> simpleCheckNames = CheckUtil.getSimpleNames(checks); <END> allowedDirectoryAndChecks = simpleCheckNames .stream() .collect(Collectors.toMap(id -> id.toLowerCase(Locale.ENGLISH), id -> id)); }</code><technical_language>I know, do issue finish DetailAST support in xpath</technical_language>

Target:
public static void setUpBeforeClass() throws IOException { simpleCheckNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleChecks()); allowedDirectoryAndChecks = simpleCheckNames .stream() .collect(Collectors.toMap(id -> id.toLowerCase(Locale.ENGLISH), id -> id)); }
Source:
<code>public void getUserCardsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.getUserCards(new RetrofitPromise<List<Card>>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); }</code><technical_language>Add newline return</technical_language>

Target:
public void getUserCardsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.getUserCards(new RetrofitPromise<List<Card>>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards", MOCK_URL)); }
Source:
<code>public boolean checkAccess(File f, int access) { final int mode; switch (access) { case FileSystem.ACCESS_OK: mode = OsConstants.F_OK; break; case FileSystem.ACCESS_READ: mode = OsConstants.R_OK; break; case FileSystem.ACCESS_WRITE: mode = OsConstants.W_OK; break; case FileSystem.ACCESS_EXECUTE: mode = OsConstants.X_OK; break; default: throw new <START> IllegalArgumentException(); <END> } try { return Libcore.os.access(f.getPath(), mode); } catch (ErrnoException e) { return false; } }</code><technical_language>log access for debugging</technical_language>

Target:
public boolean checkAccess(File f, int access) { final int mode; switch (access) { case FileSystem.ACCESS_OK: mode = OsConstants.F_OK; break; case FileSystem.ACCESS_READ: mode = OsConstants.R_OK; break; case FileSystem.ACCESS_WRITE: mode = OsConstants.W_OK; break; case FileSystem.ACCESS_EXECUTE: mode = OsConstants.X_OK; break; default: throw new IllegalArgumentException("Bad access mode: " + access); } try { return Libcore.os.access(f.getPath(), mode); } catch (ErrnoException e) { return false; } }
Source:
<code>public T setBody(Publisher<ByteBuffer> publisher) { <START> return setBody(new ReactiveStreamsBodyGenerator(publisher)); <END> }</code><technical_language>delegate setBody(publisher, -1)</technical_language>

Target:
public T setBody(Publisher<ByteBuffer> publisher) { return setBody(publisher, -1L); }
Source:
<code>private Map<StoreKey, ReplicationStatus> getBlobStatusByReplica(File[] replicas, Map<File, DumpIndexTool.IndexProcessingResults> results) throws Exception { Map<StoreKey, ReplicationStatus> keyReplicationStatusMap = new HashMap<>(); Map<StoreKey, StoreKey> convertMap = createConversionKeyMap(replicas, results); for (File replica : replicas) { DumpIndexTool.IndexProcessingResults result = results.get(replica); for (Map.Entry<StoreKey, DumpIndexTool.Info> entry : result.getKeyToState().entrySet()) { StoreKey key = entry.getKey(); StoreKey newKey = convertMap.get(key); boolean isDeprecated = false; if (newKey == null) { newKey = key; isDeprecated = true; } <START> if (!keyReplicationStatusMap.containsKey(newKey)) { <END> keyReplicationStatusMap.put(newKey, new ReplicationStatus(replicas)); } ReplicationStatus status = keyReplicationStatusMap.get(newKey); DumpIndexTool.Info info = entry.getValue(); status.setBelongsToRecentIndexSegment(info.isInRecentIndexSegment()); if (!isDeprecated && info.getStates().contains(DumpIndexTool.BlobState.Valid)) { status.addAvailable(replica); } else { status.addDeletedOrExpired(replica); } } } return keyReplicationStatusMap; }</code><technical_language>collapse lines java 8 ReplicationStatus status = keyReplicationStatusMap.computeIfAbsent(newKey, -> new ReplicationStatus(replicas))</technical_language>

Target:
private Map<StoreKey, ReplicationStatus> getBlobStatusByReplica(File[] replicas, Map<File, DumpIndexTool.IndexProcessingResults> results) throws Exception { Map<StoreKey, ReplicationStatus> keyReplicationStatusMap = new HashMap<>(); Map<StoreKey, StoreKey> convertMap = dumpIndexTool.createConversionKeyMap(replicas, results); for (File replica : replicas) { DumpIndexTool.IndexProcessingResults result = results.get(replica); for (Map.Entry<StoreKey, DumpIndexTool.Info> entry : result.getKeyToState().entrySet()) { StoreKey key = entry.getKey(); StoreKey newKey = convertMap.get(key); boolean isDeprecated = false; if (newKey == null) { newKey = key; isDeprecated = true; } ReplicationStatus status = keyReplicationStatusMap.computeIfAbsent(newKey, k -> new ReplicationStatus(replicas)); DumpIndexTool.Info info = entry.getValue(); status.setBelongsToRecentIndexSegment(info.isInRecentIndexSegment()); if (!isDeprecated && info.getStates().contains(DumpIndexTool.BlobState.Valid)) { status.addAvailable(replica); } else { status.addDeletedOrExpired(replica); } } } return keyReplicationStatusMap; }
Source:
<code>public boolean containsDate(LocalDate date) { if (isEmpty() || date.isBefore(startDate) ) { return false; } else { <START> if (dateCalculation == SKIP_WEEKENDS && isWeekend(date)) { <END> return false; } int position = dateCalculation.calculatePosition(startDate, date); return position < points.length && isValidPoint(points[position]); } }</code><technical_language>yes, this</technical_language>

Target:
public boolean containsDate(LocalDate date) { return get(date).isPresent(); }
Source:
<code><START> protected ContainerScheduler createContainerScheduler(Context cntxt) { <END> return new ContainerScheduler(cntxt); }</code><technical_language>Is this method exposed for testing? If yes, marked @VisibleForTesting</technical_language>

Target:
protected ContainerScheduler createContainerScheduler(Context cntxt) { return new ContainerScheduler(cntxt, dispatcher, metrics); }
Source:
<code>public long add( Object id ) { String string = (String) id; byte[] bytes = UTF8.encode( string ); int length = bytes.length; if ( length > 0xFFFF ) { throw new IllegalArgumentException( string ); } long endOffset = offset + 2 + bytes.length; ByteArray end = cache.at( endOffset ); if ( end != current ) { offset = endOffset; current = end; <START> } <END> long startOffset = offset; current.setByte( offset++, 0, (byte) (length & 0xFF) ); current.setByte( offset++, 0, (byte) ((length >>> 8) & 0xFF) ); for ( byte charByte : bytes ) { current.setByte( offset++, 0, charByte ); } return startOffset; }</code><technical_language>fit a single chunk</technical_language>

Target:
public long add( Object id ) { String string = (String) id; byte[] bytes = UTF8.encode( string ); int length = bytes.length; if ( length > 0xFFFF ) { throw new IllegalArgumentException( string ); } if ( offset % chunkSize >= chunkSize - 2 ) { offset += chunkSize - (offset % chunkSize); current = cache.at( offset ); } long startOffset = offset; current.setShort( offset, 0, (short) length ); offset += 2; for ( int i = 0; i < length; ) { int bytesLeftToWrite = length - i; int bytesLeftInChunk = (int) (chunkSize - offset % chunkSize); int bytesToWriteInThisChunk = min( bytesLeftToWrite, bytesLeftInChunk ); for ( int j = 0; j < bytesToWriteInThisChunk; j++ ) { current.setByte( offset++, 0, bytes[i++] ); } if ( length > i ) { current = cache.at( offset ); } } return startOffset; }
Source:
<code>protected void handleMessageInternal(Message<?> message) throws Exception { String topic = this.determineTopic(message); Object value = this.messageConverter.fromMessage(message); <START> if (value instanceof byte[]) { <END> this.template.convertAndSend(topic, value); } else { this.template.convertAndSend(topic, ((RedisSerializer<Object>) this.serializer).serialize(value)); } }</code><technical_language>Is a question here? answering question</technical_language>

Target:
protected void handleMessageInternal(Message<?> message) throws Exception { String topic = this.topicExpression.getValue(this.evaluationContext, message, String.class); Object value = this.messageConverter.fromMessage(message); if (value instanceof byte[]) { this.template.convertAndSend(topic, value); } else { this.template.convertAndSend(topic, ((RedisSerializer<Object>) this.serializer).serialize(value)); } }
Source:
<code>public static void main(String[] args) { String url = args[0]; String sampleNumber = args[1]; String filePath = args[2]; log.info("Starting WSO2 Soap Client"); ServiceClient serviceClient; try { serviceClient = new ServiceClient(); Options options = new Options(); options.setTo(new EndpointReference(url)); serviceClient.setOptions(options); if (serviceClient != null) { filePath = SoapUtil.getMessageFilePath(sampleNumber, filePath, url); readMsg(filePath); OMElement omElement1; try { System.out.println("Starting sending of events..."); omElement1 = AXIOMUtil.stringToOM(message.toString()); serviceClient.fireAndForget(omElement1); log.info("Message sent"); } catch (XMLStreamException e) { e.printStackTrace(); } catch (AxisFault axisFault) { axisFault.printStackTrace(); } } } catch (Throwable t) { t.printStackTrace(); <START> } <END> }</code><technical_language>Please log exception.. printStackTrace(). If u other place fix wel.</technical_language>

Target:
public static void main(String[] args) { String url = args[0]; String sampleNumber = args[1]; String filePath = args[2]; log.info("Starting WSO2 Soap Client"); ServiceClient serviceClient; try { serviceClient = new ServiceClient(); Options options = new Options(); options.setTo(new EndpointReference(url)); serviceClient.setOptions(options); if (serviceClient != null) { filePath = SoapUtil.getMessageFilePath(sampleNumber, filePath, url); readMsg(filePath); OMElement omElement1; try { System.out.println("Starting sending of events..."); omElement1 = AXIOMUtil.stringToOM(message.toString()); serviceClient.fireAndForget(omElement1); log.info("Message sent"); } catch (XMLStreamException e) { log.error("Error occurred when sending message " + message.toString(), e); } catch (AxisFault axisFault) { log.error("Error occurred when sending message " + message.toString(), axisFault); } } } catch (Throwable t) { log.error("Error occurred when connecting to endpoint " + url, t); } }
Source:
<code>public void refresh(HelixDataAccessor accessor) { long startTime = System.currentTimeMillis(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Set<PropertyKey> currentPropertyKeys = new HashSet<>(); List<String> resources = accessor.getChildNames(externalViewsKey(keyBuilder)); for (String resource : resources) { currentPropertyKeys.add(externalViewKey(keyBuilder, resource)); } Set<PropertyKey> cachedKeys = new HashSet<>(); Map<PropertyKey, ExternalView> cachedExternalViewMap = Maps.newHashMap(); for (String resource : _externalViewCache.keySet()) { PropertyKey key = externalViewKey(keyBuilder, resource); cachedKeys.add(key); cachedExternalViewMap.put(key, _externalViewCache.get(resource)); } cachedKeys.retainAll(currentPropertyKeys); Set<PropertyKey> reloadKeys = new HashSet<>(currentPropertyKeys); reloadKeys.removeAll(cachedKeys); Map<PropertyKey, ExternalView> updatedMap = refreshProperties(accessor, reloadKeys, new ArrayList<>(cachedKeys), <START> cachedExternalViewMap, reloadKeys); <END> Map<String, ExternalView> newExternalViewMap = Maps.newHashMap(); for (ExternalView externalView : updatedMap.values()) { newExternalViewMap.put(externalView.getResourceName(), externalView); } _externalViewCache = new HashMap<>(newExternalViewMap); _externalViewMap = new HashMap<>(newExternalViewMap); long endTime = System.currentTimeMillis(); LOG.info("Refresh " + _externalViewMap.size() + " ExternalViews for cluster " + _clusterName + ", took " + (endTime - startTime) + " ms"); }</code><technical_language>here, input empty list</technical_language>

Target:
public void refresh(HelixDataAccessor accessor) { long startTime = System.currentTimeMillis(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Set<PropertyKey> currentPropertyKeys = new HashSet<>(); List<String> resources = accessor.getChildNames(externalViewsKey(keyBuilder)); for (String resource : resources) { currentPropertyKeys.add(externalViewKey(keyBuilder, resource)); } Set<PropertyKey> cachedKeys = new HashSet<>(); Map<PropertyKey, ExternalView> cachedExternalViewMap = Maps.newHashMap(); for (String resource : _externalViewCache.keySet()) { PropertyKey key = externalViewKey(keyBuilder, resource); cachedKeys.add(key); cachedExternalViewMap.put(key, _externalViewCache.get(resource)); } cachedKeys.retainAll(currentPropertyKeys); Set<PropertyKey> reloadKeys = new HashSet<>(currentPropertyKeys); reloadKeys.removeAll(cachedKeys); Map<PropertyKey, ExternalView> updatedMap = refreshProperties(accessor, reloadKeys, new ArrayList<>(cachedKeys), cachedExternalViewMap, new HashSet<>()); Map<String, ExternalView> newExternalViewMap = Maps.newHashMap(); for (ExternalView externalView : updatedMap.values()) { newExternalViewMap.put(externalView.getResourceName(), externalView); } _externalViewCache = new HashMap<>(newExternalViewMap); _externalViewMap = new HashMap<>(newExternalViewMap); long endTime = System.currentTimeMillis(); LOG.info("Refresh " + _externalViewMap.size() + " ExternalViews for cluster " + _clusterName + ", took " + (endTime - startTime) + " ms"); }
Source:
<code>protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (isIgnored(method)) { notifier.fireTestIgnored(description); } else { Object test = null; try { test = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); } catch (Throwable e) { StatusHandler.log(new Status(IStatus.ERROR, "org.eclipse.mylyn.commons.sdk.util", NLS.bind("TestClassRunnerForFixture: Testclass {0} has no public constructor", getTestClass().getName()), e)); return; } boolean skipped = false; if (test != null) { List<TestRule> testRules = getTestRules(test); for (TestRule testRule : testRules) { Class<? extends TestRule> klass = testRule.getClass(); <START> klass.getCanonicalName(); <END> if (klass == ConditionalIgnoreRule.class) { Statement statement = testRule.apply(null, description); if (statement != null) { skipped = true; break; } } } if (skipped) { notifier.fireTestIgnored(description); } else { runTest(methodBlock(method), description, notifier); } } } }</code><technical_language>this call deleted</technical_language>

Target:
protected void runChild(final FrameworkMethod method, RunNotifier notifier) { Description description = describeChild(method); if (isIgnored(method)) { notifier.fireTestIgnored(description); } else { Object test = null; try { test = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); } catch (Throwable e) { StatusHandler.log(new Status(IStatus.ERROR, "org.eclipse.mylyn.commons.sdk.util", NLS.bind("TestClassRunnerForFixture: Testclass {0} has no public constructor", getTestClass().getName()), e)); return; } boolean skipped = false; if (test != null) { List<TestRule> testRules = getTestRules(test); for (TestRule testRule : testRules) { if (testRule instanceof ConditionalIgnoreRule) { Statement statement = testRule.apply(null, description); if (statement instanceof IgnoreStatement) { skipped = true; break; } } } if (skipped) { notifier.fireTestIgnored(description); } else { runTest(methodBlock(method), description, notifier); } } } }
Source:
<code>ValidationResult validateNotRemovingUsedNetworkByVms() { Collection<String> removedNetworks = new HashSet<>(); for (NetworkAttachment removedAttachment : removedNetworkAttachments) { removedNetworks.add(existingNetworkRelatedToAttachment(removedAttachment).getName()); } final List<String> vmNames = getVmInterfaceManager().findActiveVmsUsingNetworks(host.getId(), removedNetworks); final List<String> sortedRemovedNetworks = new ArrayList<>(removedNetworks); Collections.sort(sortedRemovedNetworks); <START> if (vmNames.isEmpty()) { <END> return ValidationResult.VALID; } else if (vmNames.size() > 1 && sortedRemovedNetworks.size() > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_VMS, LinqUtils.concat(ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, sortedRemovedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNames))); } else if (vmNames.size() > 1) { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_VMS, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, sortedRemovedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNames))); } else if (vmNames.size() == 1 && sortedRemovedNetworks.size() > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, sortedRemovedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNames))); } else { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, sortedRemovedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNames))); } }</code><technical_language>This class is extremely long anyway. Please consider moving this logic a separate class</technical_language>

Target:
ValidationResult validateNotRemovingUsedNetworkByVms() { Collection<String> removedNetworks = new HashSet<>(); for (NetworkAttachment removedAttachment : removedNetworkAttachments) { removedNetworks.add(existingNetworkRelatedToAttachment(removedAttachment).getName()); } final List<String> vmsNames = getVmInterfaceManager().findActiveVmsUsingNetworks(host.getId(), removedNetworks); final List<String> sortedRemovedNetworks = new ArrayList<>(removedNetworks); Collections.sort(sortedRemovedNetworks); DetachNetworkUsedByVmValidator detachNetworkUsedByVmValidator = new DetachNetworkUsedByVmValidator(vmsNames, sortedRemovedNetworks); return detachNetworkUsedByVmValidator.validate(); }
Source:
<code>public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); <START> <END> }</code><technical_language>double check group created</technical_language>

Target:
public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupUnProcessablePermanent() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); groupRest.setPermanent(true); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/itemReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }
Source:
<code>public synchronized EurekaClientConfig get() { <START> return namespace == null <END> ? new DefaultEurekaClientConfig() : new DefaultEurekaClientConfig(namespace); }</code><technical_language>remove singleton check</technical_language>

Target:
public synchronized EurekaClientConfig get() { if (config == null) { config = (namespace == null) ? new DefaultEurekaClientConfig() : new DefaultEurekaClientConfig(namespace); DiscoveryManager.getInstance().setEurekaClientConfig(config); } return config; }
Source:
<code>private String buildQuery(String folderId, String formattedDateTimeFrom) { <START> return "'"+folderId+"' in parents and mimeType != '" + FOLDER_MIME_TYPE + <END> "' and modifiedTime <= '" + formattedDateTimeFrom + "'"; }</code><technical_language>this more readable String.format</technical_language>

Target:
static String buildQuery(String folderId, String formattedDateTimeFrom) { return String.format("'%s' in parents and mimeType != '%s' and modifiedTime <= '%s'", folderId, FOLDER_MIME_TYPE, formattedDateTimeFrom); }
Source:
<code>public void testGetAllByRLSId() { <START> List<RecordLocatorService> result = RecordLocationServiceDAO.getAllPatientsBy("111222"); <END> assertEquals(2, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("111223"); assertEquals(1, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("111224"); assertEquals(1, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("111225"); assertEquals(1, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("N0n-Ex!sT@nT"); assertEquals(0, result.size()); }</code><technical_language>SQL script for RecordLocationService--requestedPatientId 1, 2, 3, 4, 5 this fail if records in database testGetAllByRLSId</technical_language>

Target:
public void testGetAllByRLSId() { List<RecordLocatorService> result = RecordLocationServiceDAO.getAllPatientsBy("38273N234"); assertEquals(2, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("38273N233"); assertEquals(1, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("38273N244"); assertEquals(2, result.size()); result = RecordLocationServiceDAO.getAllPatientsBy("N0n-Ex!sT@nT"); assertEquals(0, result.size()); }
Source:
<code><START> public void pull(final PullFilters filters, final IPullControllerCallback callback) { <END> conversionLocalDataSource.wipeDataBase(); PULL_IS_ACTIVE = true; this.callback = callback; if (filters.isDemo()) { callback.onStep(PullStep.DEMO); LocalAsyncPull localAsyncPull = new LocalAsyncPull(); localAsyncPull.execute(); return; } conversionLocalDataSource = new ConversionLocalDataSource(callback); pullRemoteDataSource = new PullDhisSDKDataSource(); pullRemoteDataSource.wipeDataBase(); callback.onStep(PullStep.PROGRAMS); pullRemoteDataSource.pullMetadata(new IPullSourceCallback() { @Override public void onComplete() { if (!PULL_IS_ACTIVE) { callback.onCancel(); return; } callback.onStep(PullStep.EVENTS); pullData(filters); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); callback.onError(throwable); } }); }</code><technical_language>@idelcano refactor this method extracting logic new methods ExexuteDemoPull ExecuteRemotePull for code more readable UserAccountRepository</technical_language>

Target:
public void pull(final PullFilters filters, final IPullControllerCallback callback) { conversionLocalDataSource.wipeDataBase(); PULL_IS_ACTIVE = true; this.callback = callback; conversionLocalDataSource = new ConversionLocalDataSource(callback); pullRemoteDataSource = new PullDhisSDKDataSource(); pullRemoteDataSource.wipeDataBase(); callback.onStep(PullStep.PROGRAMS); pullRemoteDataSource.pullMetadata(new IPullSourceCallback() { @Override public void onComplete() { if (!PULL_IS_ACTIVE) { callback.onCancel(); return; } callback.onStep(PullStep.EVENTS); pullData(filters); } @Override public void onError(Throwable throwable) { throwable.printStackTrace(); callback.onError(throwable); } }); }