auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setAllowedFields(String[] allowedFields) { List<String> trimedFields = new ArrayList<>(); for (String field : allowedFields) { trimedFields.add(field.trim()); } if (!trimedFields.contains("email")) { trimedFields.add("email"); } if (!trimedFields.contains("password")) { trimedFields.add("password"); } <START> if (!trimedFields.contains("confirmPassword")) { <END> confirmedPasswordIsConfigured = false; } String fieldUserName = "userName"; if (!usernameEqualsEmail && !trimedFields.contains(fieldUserName)) { trimedFields.add(fieldUserName); } else if (usernameEqualsEmail && trimedFields.contains(fieldUserName)) { trimedFields.remove(fieldUserName); } this.allowedFields = trimedFields.toArray(new String[trimedFields.size()]); }</code><technical_language>Typo: trimed -> trimmed</technical_language>

Target:
private void setAllowedFields(String[] allowedFields) { List<String> trimmedFields = new ArrayList<>(); for (String field : allowedFields) { trimmedFields.add(field.trim()); } if (!trimmedFields.contains("email")) { trimmedFields.add("email"); } if (!trimmedFields.contains("password")) { trimmedFields.add("password"); } if (!trimmedFields.contains("confirmPassword")) { confirmPasswordRequired = false; } String fieldUserName = "userName"; if (!usernameEqualsEmail && !trimmedFields.contains(fieldUserName)) { trimmedFields.add(fieldUserName); } else if (usernameEqualsEmail && trimmedFields.contains(fieldUserName)) { trimmedFields.remove(fieldUserName); } this.allowedFields = trimmedFields.toArray(new String[trimmedFields.size()]); }
Source:
<code>private static int majorVersionFromSystemClass() { <START> InputStream in = ClassLoader.getSystemResourceAsStream("java/lang/ClassLoader.class"); <END> assert in != null; int version; try { in.skip(6L); version = (in.read() << 8) + in.read() - 44; } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { in.close(); } catch (IOException ignored) { } } assert version >= 6; return version; }</code><technical_language>@xxDark link spec of this is explained</technical_language>

Target:
private static int majorVersionFromSystemClass() { InputStream in = ClassLoader.getSystemResourceAsStream("java/lang/ClassLoader.class"); if (in == null) { return majorVersionFromJavaSpecificationVersion(); } int version; try { in.skip(6L); version = (in.read() << 8) + in.read() - 44; } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { in.close(); } catch (IOException ignored) { } } assert version >= 6; return version; }
Source:
<code>private ExecutableElement findFirst(Collection<ExecutableElement> elements, String name) { for (ExecutableElement executableElement : elements) { <START> if (executableElement.getSimpleName().toString().equals(name)) <END> return executableElement; } throw new IllegalArgumentException(name + " not found in " + elements); }</code><technical_language>braces</technical_language>

Target:
private ExecutableElement findFirst(Collection<ExecutableElement> elements, String name) { for (ExecutableElement executableElement : elements) { if (executableElement.getSimpleName().toString().equals(name)) { return executableElement; } } throw new IllegalArgumentException(name + " not found in " + elements); }
Source:
<code>public T revertFromTrash(Long trashId) { validateCredentials(); Object trashRecord = trashService.findTrashById(trashId, getClassType().getName()); if (trashRecord == null) { throw new TrashInstanceNotFoundException(getClassType().getName(), trashId); } verifySchemaVersion(trashRecord, trashId, true); try { T newInstance = getClassType().newInstance(); copyValuesFromRecord(newInstance, trashRecord); <START> newInstance = repository.create(newInstance); <END> trashService.moveFromTrash(newInstance, trashRecord, recordHistory); return newInstance; } catch (InstantiationException | IllegalAccessException e) { throw new ObjectUpdateException(trashRecord.getClass().getName(), trashId, e); } }</code><technical_language>create motechdataservice, change lost sending create event</technical_language>

Target:
public T revertFromTrash(Long trashId) { validateCredentials(); Object trashRecord = trashService.findTrashById(trashId, getClassType().getName()); if (trashRecord == null) { throw new TrashInstanceNotFoundException(getClassType().getName(), trashId); } verifySchemaVersion(trashRecord, trashId, true); try { T newInstance = getClassType().newInstance(); copyValuesFromRecord(newInstance, trashRecord); newInstance = create(newInstance); trashService.removeFromTrash(trashRecord); return newInstance; } catch (InstantiationException | IllegalAccessException e) { throw new ObjectUpdateException(trashRecord.getClass().getName(), trashId, e); } }
Source:
<code>@Override public Response execute(Request request) throws IOException { com.squareup.okhttp.Request requestOk = new com.squareup.okhttp.Request.Builder() .url(request.getUrl()) .build(); com.squareup.okhttp.Response response = client.newCall(requestOk).execute(); List<Header> headerList = new ArrayList<Header>(); <START> for (int i = 0; i < response.headers().size(); i++) { <END> Header header = new Header(response.headers().name(i), response.headers().value(i)); headerList.add(header); } TypedInput responseBody = new TypedInputStream( response.body().contentType().type(), response.body().contentLength(), response.body().byteStream()); Response resp = new Response(request.getUrl(), response.code(), response.message(), headerList, responseBody); return resp; }</code><technical_language>dereference response.headers() single time. Cache in local variable</technical_language>

Target:
public Response execute(Request request) throws IOException { com.squareup.okhttp.Request requestOk = new com.squareup.okhttp.Request.Builder() .url(request.getUrl()) .build(); com.squareup.okhttp.Response response = client.newCall(requestOk).execute(); List<Header> headerList = new ArrayList<Header>(); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { Header header = new Header(headers.name(i), headers.value(i)); headerList.add(header); } TypedInput responseBody = new TypedInputStream( response.body().contentType().type(), response.body().contentLength(), response.body().byteStream()); Response resp = new Response(request.getUrl(), response.code(), response.message(), headerList, responseBody); return resp; }
Source:
<code>public boolean checkSourceCodeValidity() { try { GHRateLimit ghRateLimit = github.rateLimit(); if (ghRateLimit.remaining == 0) { ZonedDateTime zonedDateTime = Instant.ofEpochSecond(ghRateLimit.reset.getTime()).atZone(ZoneId.systemDefault()); throw new CustomWebApplicationException("Out of rate limit, please wait till " + zonedDateTime, HttpStatus.SC_BAD_REQUEST); } github.getMyOrganizations(); } catch (IOException e) { throw new CustomWebApplicationException( <START> "Please recreate your GitHub token by unlinking and then relinking your Github account through the Accounts page. " <END> + "We need an upgraded token to list your organizations.", HttpStatus.SC_BAD_REQUEST); } return true; }</code><technical_language>Github => GitHub</technical_language>

Target:
public boolean checkSourceCodeValidity() { try { GHRateLimit ghRateLimit = github.rateLimit(); if (ghRateLimit.remaining == 0) { ZonedDateTime zonedDateTime = Instant.ofEpochSecond(ghRateLimit.reset.getTime()).atZone(ZoneId.systemDefault()); throw new CustomWebApplicationException("Out of rate limit, please wait till " + zonedDateTime, HttpStatus.SC_BAD_REQUEST); } github.getMyOrganizations(); } catch (IOException e) { throw new CustomWebApplicationException( "Please recreate your GitHub token by unlinking and then relinking your GitHub account through the Accounts page. " + "We need an upgraded token to list your organizations.", HttpStatus.SC_BAD_REQUEST); } return true; }
Source:
<code>public void getUserLocation_shouldGetAUserLocationByItsId() throws Exception { <START> Assert.fail("Not yet implemented"); <END> }</code><technical_language>want fix this, else test fail</technical_language>

Target:
public void getUserLocation_shouldGetAUserLocationByItsId() throws Exception { MohCoreService cservice = Context.getService(MohCoreService.class); User sysUser = new User(); sysUser.setUserId(501); Location userLoc = new Location(); userLoc.setLocationId(1); UserLocation userlocation = new UserLocation(); userlocation.setSysUser(sysUser); userlocation.setUserLoc(userLoc); UserLocation returnedUserLocation=cservice.saveUserLocation(userlocation); Assert.assertNotNull(cservice.getUserLocation(returnedUserLocation.getUserLocationId())); }
Source:
<code>protected void start() throws InterruptedException { logger.info("Starting NettyPerfClient"); reporter.start(); <START> group = new NioEventLoopGroup(concurrency); <END> b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler()).addLast(new RequestSender()); } }); logger.info("Connecting to {}:{}", host, port); b.remoteAddress(host, port); perfClientStartTime = System.currentTimeMillis(); for (int i = 0; i < concurrency; i++) { b.connect().addListener(channelConnectListener); } logger.info("Created channel(s)", concurrency); logger.info("NettyPerfClient started"); }</code><technical_language>concurrency is realized setting number of worker threads in NioEventLoopGroup. However, enforce this is clear me. For example, if in this line group = new NioEventLoopGroup(2);, in ln. 206 for (int i = 0; i < 3; i++) {, perf client runs 2 3 introduce inconsistency. In this case, is concurrency then</technical_language>

Target:
protected void start() throws InterruptedException { logger.info("Starting NettyPerfClient"); reporter.start(); group = new NioEventLoopGroup(concurrency); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpClientCodec()).addLast(new ChunkedWriteHandler()).addLast(new ResponseHandler()); } }); logger.info("Connecting to {}:{}", host, port); b.remoteAddress(host, port); perfClientStartTime = System.currentTimeMillis(); for (int i = 0; i < concurrency; i++) { b.connect().addListener(channelConnectListener); } isRunning = true; logger.info("Created channel(s)", concurrency); logger.info("NettyPerfClient started"); }
Source:
<code>private static void initMessages() { ResourceBundle bundle = readMessagesFromBundle(); for (String key : bundle.keySet()) { try { AuditLogType type = AuditLogType.valueOf(key); if (!messages.containsKey(type)) { messages.put(type, bundle.getString(key)); } else { log.errorFormat("The type {0} appears more then once in audit log messages bundle with the values '{1}' and '{2}'", messages.get(type), <START> bundle.getString(key)); <END> } } catch (Exception e) { log.errorFormat("Cannot convert the string {0} to AuditLogType, the key does not exist in the AuditLogType declared types", bundle.getString(key)); } } checkMessages(); }</code><technical_language>wait - format elements {0}, {1} {2}, input params. guessing "key"</technical_language>

Target:
private static void initMessages() { ResourceBundle bundle = readMessagesFromBundle(); for (String key : bundle.keySet()) { try { AuditLogType type = AuditLogType.valueOf(key); if (!messages.containsKey(type)) { messages.put(type, bundle.getString(key)); } else { log.errorFormat("The type {0} appears more then once in audit log messages bundle with the values '{1}' and '{2}'", type, messages.get(type), bundle.getString(key)); } } catch (Exception e) { log.errorFormat("Cannot convert the string {0} to AuditLogType, the key does not exist in the AuditLogType declared types", bundle.getString(key)); } } checkMessages(); }
Source:
<code>ValueHolder<V> get(K key) throws CacheAccessException; boolean containsKey(K key) throws CacheAccessException; <START> void put(K key, V value, long creationTime, long lastAccessTime) throws CacheAccessException; <END> void remove(K key) throws CacheAccessException; void clear() throws CacheAccessException; void destroy() throws CacheAccessException; void close() throws CacheAccessException; Store.Iterator<Cache.Entry<K, ValueHolder<V>>> iterator(); public interface ValueHolder<V> { V value(); long creationTime(); long lastAccessTime(); }</code><technical_language>alt? Creating ValueHolder put(K key, ValueHolder<V> valueHolder)? do need if want give more minimal set</technical_language>

Target:
ValueHolder<V> get(K key) throws CacheAccessException; boolean containsKey(K key) throws CacheAccessException; void put(K key, ValueHolder<V> value) throws CacheAccessException; void remove(K key) throws CacheAccessException; void clear() throws CacheAccessException; void destroy() throws CacheAccessException; void close() throws CacheAccessException; Store.Iterator<Cache.Entry<K, ValueHolder<V>>> iterator(); public interface ValueHolder<V> { V value(); long creationTime(); long lastAccessTime(); }
Source:
<code>public Coordinate getCoordinateInDirection(Direction direction) { switch (direction) { case NORTH: return new Coordinate(x, y - 1); case EAST: return new Coordinate(x + 1, y); case WEST: return new Coordinate(x - 1, y); case SOUTH: return new Coordinate(x, y + 1); case NORTHEAST: return new Coordinate(x + 1, y - 1); case NORTHWEST: return new Coordinate(x - 1, y - 1); case SOUTHEAST: return new Coordinate(x + 1, y + 1); case SOUTHWEST: return new Coordinate(x - 1, y + 1); default: throw new IllegalArgumentException(); <START> } <END> }</code><technical_language>if direction == null</technical_language>

Target:
public Coordinate getCoordinateInDirection(Direction direction) { if (direction == null) throw new IllegalArgumentException(); switch (direction) { case NORTH: return new Coordinate(x, y - 1); case EAST: return new Coordinate(x + 1, y); case WEST: return new Coordinate(x - 1, y); case SOUTH: return new Coordinate(x, y + 1); case NORTHEAST: return new Coordinate(x + 1, y - 1); case NORTHWEST: return new Coordinate(x - 1, y - 1); case SOUTHEAST: return new Coordinate(x + 1, y + 1); case SOUTHWEST: return new Coordinate(x - 1, y + 1); default: throw new IllegalArgumentException(); } }
Source:
<code>public int execute() { try { TableExport.Paths exportPaths = new TableExport.Paths( work.getAstRepresentationForErrorMsg(), work.getExportRootDir(), conf, false); Hive db = getHive(); LOG.debug("Exporting data to: {}", exportPaths.exportRootDir()); work.acidPostProcess(db); TableExport tableExport = new TableExport(exportPaths, work.getTableSpec(), work.getReplicationSpec(), db, null, conf, work.getMmContext()); <START> tableExport.write(true); <END> } catch (Exception e) { LOG.error("failed", e); setException(e); return 1; } return 0; }</code><technical_language>is check removed</technical_language>

Target:
public int execute() { try { TableExport.Paths exportPaths = new TableExport.Paths( work.getAstRepresentationForErrorMsg(), work.getExportRootDir(), conf, false); Hive db = getHive(); LOG.debug("Exporting data to: {}", exportPaths.exportRootDir()); work.acidPostProcess(db); TableExport tableExport = new TableExport(exportPaths, work.getTableSpec(), work.getReplicationSpec(), db, null, conf, work.getMmContext()); if (!tableExport.write()) { throw new SemanticException(ErrorMsg.INCOMPATIBLE_SCHEMA.getMsg()); } } catch (Exception e) { LOG.error("failed", e); setException(e); return 1; } return 0; }
Source:
<code>public void testValidateFailed() { PlanNode root = new OutputNode(idAllocator.getNextId(), new ExplainAnalyzeNode(idAllocator.getNextId(), new OutputNode(idAllocator.getNextId(), new ProjectNode(idAllocator.getNextId(), new ValuesNode( idAllocator.getNextId(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of()), Assignments.of() <START> ), ImmutableList.of(), ImmutableList.of(), ImmutableList.of() <END> ), new VariableReferenceExpression("a", BIGINT), false), ImmutableList.of(), ImmutableList.of(), ImmutableList.of()); new VerifyOnlyOneOutputNode().validate(root, null, null, null, null, WarningCollector.NOOP); }</code><technical_language>same, param line</technical_language>

Target:
public void testValidateFailed() { PlanNode root = new OutputNode(idAllocator.getNextId(), new ExplainAnalyzeNode(idAllocator.getNextId(), new OutputNode(idAllocator.getNextId(), new ProjectNode(idAllocator.getNextId(), new ValuesNode( idAllocator.getNextId(), ImmutableList.of(), ImmutableList.of()), Assignments.of() ), ImmutableList.of(), ImmutableList.of() ), new VariableReferenceExpression("a", BIGINT), false), ImmutableList.of(), ImmutableList.of()); new VerifyOnlyOneOutputNode().validate(root, null, null, null, null, WarningCollector.NOOP); }
Source:
<code>public Allele getAltAlleleWithHighestAlleleCount() { if ( isBiallelic() ) return getAlternateAllele(0); return getAlternateAlleles().stream() <START> .max((a1, a2) -> Integer.compare(getCalledChrCount(a1), getCalledChrCount(a2))) <END> .get(); }</code><technical_language>While this is neater, a lot slower big VCFs samples multiple alleles, getCalledChrCount(allele) traverses genotypes time called</technical_language>

Target:
public Allele getAltAlleleWithHighestAlleleCount() { if ( isBiallelic() ) return getAlternateAllele(0); return getAlternateAlleles().stream() .map(allele -> new Tuple<>(allele, getCalledChrCount(allele))) .max((alleleAndCount1, alleleAndCount2) -> Integer.compare(alleleAndCount1.b, alleleAndCount2.b)) .get() .a; }
Source:
<code>FileSender( StoreResource resource ) { this.resource = resource; <START> this.byteBuffer = ByteBuffer.allocate( MAX_SIZE ); <END> }</code><technical_language>this extra copying of buffer contents transferring data network storage</technical_language>

Target:
FileSender( StoreResource resource ) { this.resource = resource; this.byteBuffer = ByteBuffer.allocateDirect( MAX_SIZE ); }
Source:
<code>public void setPageIndicator(int from, int to, int total) { <START> this.pageIndicator.textContent = from + "-" + to + " of " + total; <END> }</code><technical_language>i18n of " of "</technical_language>

Target:
public void setPageIndicator(int from, int to, int total) { this.pageIndicator.textContent = from + "-" + to + " " + ts.getTranslation(LibraryConstants.Of) + " " + total; }
Source:
<code>public OptionSet setOscore(byte[] oscore){ <START> if(oscore != null) <END> this.oscore = oscore.clone(); return this; }</code><technical_language>information that</technical_language>

Target:
public OptionSet setOscore(byte[] oscore){ if(oscore != null){ this.oscore = oscore.clone(); }else{ throw new NullPointerException("Oscore cannot be null."); } return this; }
Source:
<code>private boolean isInSelection(Event event) { if (selection.x == selection.y) return false; int offset = getOffsetAtPoint(event.x, event.y, null, true); if (selection.x <= offset && offset < selection.y) return true; <START> else return false; <END> }</code><technical_language>'return false' instead of 'else return false'</technical_language>

Target:
private boolean isInSelection(Event event) { if (selection.x == selection.y) return false; int offset = getOffsetAtPoint(event.x, event.y, null, true); if (selection.x <= offset && offset < selection.y) return true; return false; }
Source:
<code>public static SortedKeyValueIterator<Key,Value> setupSystemScanIterators( SortedKeyValueIterator<Key,Value> source, Set<Column> cols, Authorizations auths, <START> byte[] defaultVisibility, AccumuloConfiguration conf) { <END> SortedKeyValueIterator<Key,Value> delIter = DeletingIterator.wrap(source, false, DeletingIterator.getBehavior(conf)); ColumnFamilySkippingIterator cfsi = new ColumnFamilySkippingIterator(delIter); SortedKeyValueIterator<Key,Value> colFilter = ColumnQualifierFilter.wrap(cfsi, cols); return VisibilityFilter.wrap(colFilter, auths, defaultVisibility); }</code><technical_language>Is this of quasi API classes</technical_language>

Target:
public static SortedKeyValueIterator<Key,Value> setupSystemScanIterators( SortedKeyValueIterator<Key,Value> source, Set<Column> cols, Authorizations auths, byte[] defaultVisibility, AccumuloConfiguration conf) throws IOException { SortedKeyValueIterator<Key,Value> delIter = DeletingIterator.wrap(source, false, DeletingIterator.getBehavior(conf)); ColumnFamilySkippingIterator cfsi = new ColumnFamilySkippingIterator(delIter); SortedKeyValueIterator<Key,Value> colFilter = ColumnQualifierFilter.wrap(cfsi, cols); return VisibilityFilter.wrap(colFilter, auths, defaultVisibility); }
Source:
<code>public void toggleDirectBuffers() throws Exception { <START> ModelNodeResult modelNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, DIRECT_BUFFERS); <END> modelNodeResult.assertSuccess(); final boolean originalValue = !modelNodeResult.hasDefinedValue() || modelNodeResult.booleanValue(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.CHECKBOX, DIRECT_BUFFERS, !originalValue) .verifyFormSaved() .verifyAttribute(DIRECT_BUFFERS, !originalValue); new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.CHECKBOX, DIRECT_BUFFERS, originalValue) .verifyFormSaved() .verifyAttribute(DIRECT_BUFFERS, originalValue); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, DIRECT_BUFFERS, modelNodeResult.value()); } }</code><technical_language>Please rename originalDirectBuffersResult originalResult</technical_language>

Target:
public void toggleDirectBuffers() throws Exception { final ModelNodeResult originalNodeResult = operations.readAttribute(BUFFER_POOL_ADDRESS, DIRECT_BUFFERS); originalNodeResult.assertSuccess(); final boolean originalValue = !originalNodeResult.hasDefinedValue() || originalNodeResult.booleanValue(); try { new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.CHECKBOX, DIRECT_BUFFERS, !originalValue) .verifyFormSaved() .verifyAttribute(DIRECT_BUFFERS, !originalValue); new ConfigChecker.Builder(client, BUFFER_POOL_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.CHECKBOX, DIRECT_BUFFERS, originalValue) .verifyFormSaved() .verifyAttribute(DIRECT_BUFFERS, originalValue); } finally { operations.writeAttribute(BUFFER_POOL_ADDRESS, DIRECT_BUFFERS, originalNodeResult.value()); } }
Source:
<code>public void testGoodTableSourceWithMetadataFields() { TableSchema sourceSchema = defaultSourceSchema().build(); Map<String, String> sourceOptions = defaultSourceOptions().build(); KinesisDynamicSource actualSource = (KinesisDynamicSource) FactoryUtil.createTableSource( null, ObjectIdentifier.of("default", "default", SOURCE_TABLE), createSourceTable(sourceSchema, sourceOptions, Collections.emptyList()), new Configuration(), Thread.currentThread().getContextClassLoader(), <START> false); <END> KinesisDynamicSource expectedSource = new KinesisDynamicSource( sourceSchema.toPhysicalRowDataType(), SOURCE_STREAM, KINESIS_PROPERTIES, new TestFormatFactory.DecodingFormatMock(",", true)); List<String> metadataKeys = Arrays.asList("ShardId", "ApproximateArrivalTimestamp"); DataType producedDataType = getProducedType(sourceSchema, Metadata.values()); expectedSource.applyReadableMetadata(metadataKeys, producedDataType); actualSource.applyReadableMetadata(metadataKeys, producedDataType); assertEquals(expectedSource, actualSource); assertEquals(expectedSource, actualSource.copy()); }</code><technical_language>testing if call methods parameters, instead test contents of mutable member variables</technical_language>

Target:
public void testGoodTableSourceWithMetadataFields() { TableSchema sourceSchema = defaultSourceSchema().build(); Map<String, String> sourceOptions = defaultTableOptions().build(); CatalogTable sourceTable = createSourceTable(sourceSchema, sourceOptions); Metadata[] requestedMetadata = new Metadata[]{ShardId, Timestamp}; List<String> metadataKeys = Arrays.asList(ShardId.getFieldName(), Timestamp.getFieldName()); DataType producedDataType = getProducedType(sourceSchema, requestedMetadata); KinesisDynamicSource actualSource = actualDynamicSource(sourceTable); actualSource.applyReadableMetadata(metadataKeys, producedDataType); KinesisDynamicSource expectedSource = new KinesisDynamicSource( sourceSchema.toPhysicalRowDataType(), STREAM_NAME, defaultConsumerProperties(), new TestFormatFactory.DecodingFormatMock(",", true), producedDataType, Arrays.asList(requestedMetadata)); assertEquals(expectedSource, actualSource); assertEquals(expectedSource, actualSource.copy()); }
Source:
<code>private void authenticate() { SessionFactory sessionFactory = SessionFactoryImpl.newInstance(); Map<String, String> param = retrieveSessionParameters(); cmisSession = createSession(sessionFactory, param); boolean isAlfresco = cmisSession.getRepositoryInfo().getProductName() .startsWith(OnPremiseConstant.ALFRESCO_VENDOR); String version = RepositoryVersionHelper.getVersionString(cmisSession.getRepositoryInfo().getProductVersion(), 0); RepositoryInfo tmpRepositoryInfo = new OnPremiseRepositoryInfoImpl(cmisSession.getRepositoryInfo()); if (isAlfresco && version != null && Integer.parseInt(version) >= OnPremiseConstant.ALFRESCO_VERSION_4) { param.put(SessionParameter.ATOMPUB_URL, baseUrl.concat(OnPremiseUrlRegistry.BINDING_CMISATOM)); Session cmisSession2 = null; try { cmisSession2 = createSession(sessionFactory, param); } catch (Exception e) { cmisSession2 = null; } cmisSession = (cmisSession2 != null) ? cmisSession2 : cmisSession; } rootNode = new FolderImpl(cmisSession.getRootFolder()); repositoryInfo = new OnPremiseRepositoryInfoImpl(cmisSession.getRepositoryInfo()); if (repositoryInfo.getEdition() == OnPremiseConstant.ALFRESCO_EDITION_UNKNOWN && tmpRepositoryInfo.getEdition() != OnPremiseConstant.ALFRESCO_EDITION_UNKNOWN) { <START> repositoryInfo = tmpRepositoryInfo; <END> } create(); }</code><technical_language>a bit wary of this, replacing RepositoryInfo object _may_ give issues in future, for example, if /cmisatom binding provides more capabilities /service/cmis binding hide them. Is a replace/override Edition property RepoInfo object</technical_language>

Target:
private void authenticate() { SessionFactory sessionFactory = SessionFactoryImpl.newInstance(); Map<String, String> param = retrieveSessionParameters(); cmisSession = createSession(sessionFactory, param); boolean isAlfresco = cmisSession.getRepositoryInfo().getProductName() .startsWith(OnPremiseConstant.ALFRESCO_VENDOR); String version = RepositoryVersionHelper.getVersionString(cmisSession.getRepositoryInfo().getProductVersion(), 0); RepositoryInfo tmpRepositoryInfo = new OnPremiseRepositoryInfoImpl(cmisSession.getRepositoryInfo()); if (isAlfresco && version != null && Integer.parseInt(version) >= OnPremiseConstant.ALFRESCO_VERSION_4) { param.put(SessionParameter.ATOMPUB_URL, baseUrl.concat(OnPremiseUrlRegistry.BINDING_CMISATOM)); Session cmisSession2 = null; try { cmisSession2 = createSession(sessionFactory, param); } catch (Exception e) { cmisSession2 = null; } cmisSession = (cmisSession2 != null) ? cmisSession2 : cmisSession; } rootNode = new FolderImpl(cmisSession.getRootFolder()); repositoryInfo = new OnPremiseRepositoryInfoImpl(cmisSession.getRepositoryInfo()); if (repositoryInfo.getEdition() == OnPremiseConstant.ALFRESCO_EDITION_UNKNOWN && tmpRepositoryInfo.getEdition() != OnPremiseConstant.ALFRESCO_EDITION_UNKNOWN) { repositoryInfo = new OnPremiseRepositoryInfoImpl(cmisSession.getRepositoryInfo(), tmpRepositoryInfo.getEdition()); } create(); }
Source:
<code>protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) { return CompletableFuture.runAsync(() -> { try { IJavaElement element= super.getElement(); long implCount = 0; if (element instanceof IType) { implCount= countTypeImplementations((IType) element, monitor); action= implCount > 0 ? e -> new OpenTypeHierarchyAction(editor).run(new StructuredSelection(element)) : null; if (implCount == 0 && showImplementationsAtLeastOne) { super.setLabel(""); } else { super.setLabel(MessageFormat.format(JavaCodeMiningMessages.JavaImplementationCodeMining_label, implCount)); } } else if (element instanceof IMethod) { implCount= countMethodImplementations((IMethod) element, monitor); action= implCount > 0 ? e -> new FindDeclarationsInHierarchyAction(editor).run(element) : null; if (implCount == 0 && showImplementationsAtLeastOne) { super.setLabel(""); } else { super.setLabel(MessageFormat.format(JavaCodeMiningMessages.JavaImplementationCodeMining_label, implCount)); } } } catch <START> (JavaModelException e) <END> { } catch (CoreException e1) { } }); }</code><technical_language>JavaModelException is subclassed CoreException if safe ignore both, I one, CoreException</technical_language>

Target:
protected CompletableFuture<Void> doResolve(ITextViewer viewer, IProgressMonitor monitor) { return CompletableFuture.runAsync(() -> { try { IJavaElement element= super.getElement(); long implCount = 0; if (element instanceof IType) { implCount= countTypeImplementations((IType) element, monitor); action= implCount > 0 ? e -> new OpenTypeHierarchyAction(editor).run(new StructuredSelection(element)) : null; if (implCount == 0 && showImplementationsAtLeastOne) { super.setLabel(""); } else { super.setLabel(MessageFormat.format(JavaCodeMiningMessages.JavaImplementationCodeMining_label, implCount)); } } else if (element instanceof IMethod) { implCount= countMethodImplementations((IMethod) element, monitor); action= implCount > 0 ? e -> new FindDeclarationsInSubHierarchyAction(editor).run(element) : null; if (implCount == 0 && showImplementationsAtLeastOne) { super.setLabel(""); } else { super.setLabel(MessageFormat.format(JavaCodeMiningMessages.JavaImplementationCodeMining_label, implCount)); } } } catch (JavaModelException e) { } catch (CoreException e1) { } }); }
Source:
<code>public void writeLeaderInformation(LeaderInformation leaderInformation) { final UUID confirmedLeaderSessionID = leaderInformation.getLeaderSessionID(); final String confirmedLeaderAddress = leaderInformation.getLeaderAddress(); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { <START> if (confirmedLeaderAddress != null && confirmedLeaderSessionID != null) { <END> configMap.getData().put(LEADER_ADDRESS_KEY, confirmedLeaderAddress); configMap.getData().put(LEADER_SESSION_ID_KEY, confirmedLeaderSessionID.toString()); } configMap.getLabels().putAll(configMapLabels); return Optional.of(configMap); } return Optional.empty(); }).get(); } catch (Exception e) { fatalErrorHandler.onFatalError( new KubernetesException("Could not update ConfigMap " + configMapName, e)); } }</code><technical_language>leaderInformation a leader address? allowing explicitly remove leader information</technical_language>

Target:
public void writeLeaderInformation(LeaderInformation leaderInformation) { assert(running); final UUID confirmedLeaderSessionID = leaderInformation.getLeaderSessionID(); final String confirmedLeaderAddress = leaderInformation.getLeaderAddress(); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { if (confirmedLeaderAddress == null) { configMap.getData().remove(LEADER_ADDRESS_KEY); } else { configMap.getData().put(LEADER_ADDRESS_KEY, confirmedLeaderAddress); } if (confirmedLeaderSessionID == null) { configMap.getData().remove(LEADER_SESSION_ID_KEY); } else { configMap.getData().put(LEADER_SESSION_ID_KEY, confirmedLeaderSessionID.toString()); } configMap.getLabels().putAll(configMapLabels); return Optional.of(configMap); } return Optional.empty(); }).get(); if (LOG.isDebugEnabled()) { LOG.debug( "Successfully wrote leader information: Leader={}, session ID={}.", confirmedLeaderAddress, confirmedLeaderSessionID); } } catch (Exception e) { fatalErrorHandler.onFatalError( new KubernetesException("Could not write leader information since ConfigMap " + configMapName + " does not exist.", e)); } }
Source:
<code>public static void main(String[] args) throws HTTPError, NoResultsFound, MultipleResultsFound { anced.configure("ak-test-aUV295IugdhWSNx2JFckYBCSvfY2ibgq"); BankAccount bankAccount = new BankAccount("/bank_accounts/BA1BnM6LmT9DLV4bZDIjUmHD"); Order order = new Order("/orders/OR1s2WQKp0shLH9Qb0LiUfEJ"); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); <START> try { <END> Credit credit = order.creditTo(bankAccount, payload); } catch (HTTPError e) }</code><technical_language>indentation in this file broken</technical_language>

Target:
public static void main(String[] args) throws HTTPError, NoResultsFound, MultipleResultsFound { Balanced.configure("ak-test-aUV295IugdhWSNx2JFckYBCSvfY2ibgq"); BankAccount bankAccount = new BankAccount("/bank_accounts/BA5KLH6jhFgtVENHXOcF3Cfj/credits"); Order order = new Order("/orders/OR5QcYnwysJXQswImokq6ZSx"); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); try { Credit credit = order.creditTo(bankAccount, payload); } catch (HTTPError e) }
Source:
<code><START> private void updateNullCheckedResources(IfStatementTree tree, boolean value) { <END> if (isRightSideNullCheck(tree)) { contentResources.replace(tree.condition().firstToken().text(), value); } else { contentResources.replace(tree.condition().lastToken().text(), value); } }</code><technical_language>Merged Issue 65 - refactoring proposal #101</technical_language>

Target:
private void updateNullCheckedResources(IfStatementTree tree, boolean value) { boolean rightOperandIsNull = Kind.NULL_LITERAL.equals(tree.condition().lastToken().parent().kind()); SyntaxToken variable = rightOperandIsNull ? tree.condition().firstToken() : tree.condition().lastToken(); contentResources.replace(variable.text(), value); }
Source:
<code>List<XmlSuite> extractSuitesFrom(File jarFile) { try { Utils.log("TestNG", 2, "Trying to open jar file:" + jarFile); List<String> classes = Lists.newArrayList(); boolean foundTestngXml = testngXmlExistsInJar(jarFile, classes); if (!foundTestngXml) { Utils.log("TestNG", 1, "Couldn't find the " + xmlPathInJar + " in the jar file, running all the classes"); XmlSuite suite = XmlSuiteUtils.newXmlSuiteUsing(classes); <START> if (this.mode != null) { <END> suite.setParallel(this.mode); } suites.add(suite); } } catch (IOException ex) { throw new TestNGException(ex); } return suites; }</code><technical_language>If mode null, need check ;)</technical_language>

Target:
List<XmlSuite> extractSuitesFrom(File jarFile) { try { Utils.log("TestNG", 2, "Trying to open jar file:" + jarFile); List<String> classes = Lists.newArrayList(); boolean foundTestngXml = testngXmlExistsInJar(jarFile, classes); if (!foundTestngXml) { Utils.log("TestNG", 1, "Couldn't find the " + xmlPathInJar + " in the jar file, running all the classes"); XmlSuite suite = XmlSuiteUtils.newXmlSuiteUsing(classes); suite.setParallel(this.mode); suites.add(suite); } } catch (IOException ex) { throw new TestNGException(ex); } return suites; }
Source:
<code>public Iterable<Edge> getEdges(Direction direction, final String[] labels, FetchHints fetchHints, Authorizations authorizations) { <START> getFetchHints().validateHasEdgeFetchHints(direction); <END> return getGraph().getEdges(getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations), fetchHints, authorizations); }</code><technical_language>checking labels</technical_language>

Target:
public Iterable<Edge> getEdges(Direction direction, final String[] labels, FetchHints fetchHints, Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction, labels); return getGraph().getEdges(getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations), fetchHints, authorizations); }
Source:
<code>public void selectNextBestMatchingMilestone() { Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones); if (!canIncreaseIndex(curSelectedIndex, bestMatchingMilestones)) return; <START> selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.isPresent() ? curSelectedIndex.get() + 1 : 0); <END> }</code><technical_language>curSelectedIndex.orElse(-1) + 1 here</technical_language>

Target:
public void selectNextBestMatchingMilestone() { Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones); if (!canIncreaseIndex(curSelectedIndex, bestMatchingMilestones)) return; selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.orElse(-1) + 1); }
Source:
<code>public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { Image image = getImage(); FontMetrics fontMetrics = gc.getFontMetrics(); gc.drawImage(image, x, y); Rectangle bounds = image.getBounds(); <START> int labelX = bounds.width + (int) fontMetrics.getAverageCharacterWidth(); <END> return super.draw(gc, textWidget, color, labelX, y); }</code><technical_language>labelX x + ..</technical_language>

Target:
public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { Image image = getImage(); FontMetrics fontMetrics = gc.getFontMetrics(); Rectangle bounds = image.getBounds(); int imageY = y; int deltaY = fontMetrics.getHeight() - bounds.height; if (deltaY > 0) { imageY = imageY + deltaY / 2; } gc.drawImage(image, x, imageY); int labelX = x + bounds.width + (int) fontMetrics.getAverageCharacterWidth(); return super.draw(gc, textWidget, color, labelX, y); }
Source:
<code>public String toString() { StringBuilder result = new StringBuilder(); result.append("Hint.withText(\"" + hintText + "\")"); if (effort != 0) result.append(".withEffort(" + effort + ")"); if (links != null && !links.isEmpty()) <START> result.append(".with(" + links + ")"); <END> return result.toString(); }</code><technical_language>Formatting</technical_language>

Target:
public String toString() { StringBuilder result = new StringBuilder(); result.append("Hint.withText(\"" + hintTextPattern.getPattern() + "\")"); if (effort != 0) result.append(".withEffort(" + effort + ")"); if (links != null && !links.isEmpty()) result.append(".with(" + links + ")"); return result.toString(); }
Source:
<code>protected IFile[] getChangedFiles() throws CoreException { Set<IFile> combined= new HashSet<>(); combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()))); if (fRenameSubpackages) { for (IPackageFragment <START> packagefrag : <END> JavaElementUtil.getPackageAndSubpackages(fPackage)) { combined.addAll(Arrays.asList(ResourceUtil.getFiles(packagefrag.getCompilationUnits()))); } } else { combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getCompilationUnits()))); } if (fQualifiedNameSearchResult != null) combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles())); return combined.toArray(new IFile[combined.size()]); }</code><technical_language>consistency: loop vars for type IPackageFragment called in this file: packagefrag, pack, allSubpackage => harmonize 'pack' is</technical_language>

Target:
protected IFile[] getChangedFiles() throws CoreException { Set<IFile> combined= new HashSet<>(); combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()))); if (fRenameSubpackages) { for (IPackageFragment pack : JavaElementUtil.getPackageAndSubpackages(fPackage)) { combined.addAll(Arrays.asList(ResourceUtil.getFiles(pack.getCompilationUnits()))); } } else { combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getCompilationUnits()))); } if (fQualifiedNameSearchResult != null) combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles())); return combined.toArray(new IFile[combined.size()]); }
Source:
<code>public Dialog onCreateDialog(Bundle savedInstanceState) { final ArrayList<Song> songs = getArguments().getParcelableArrayList("songs"); int title; CharSequence content; if (songs.size() > 1) { title = R.string.delete_songs_title; content = Html.fromHtml(getString(R.string.delete_x_songs, songs.size())); } else { title = R.string.delete_song_title; content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).title)); } return new MaterialDialog.Builder(getActivity()) .title(title) .content(content) .positiveText(R.string.delete_action) .negativeText(android.R.string.cancel) .autoDismiss(false) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Activity activity = getActivity(); if (activity == null) return; songsToRemove = songs; if (!SAFUtil.isSAFRequiredForSongs(songs)) { deleteSongs(songs, null); <START> dismiss(); <END> } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (SAFUtil.isSDCardAccessGranted(activity)) { deleteSongs(songs, null); dismiss(); } else { startActivityForResult(new Intent(getActivity(), SAFGuideActivity.class), SAFGuideActivity.REQUEST_CODE_SAF_GUIDE); } } else { deleteSongsKitkat(); } } } }) .build(); }</code><technical_language>I if a loading animation in tag editor "saving changes" dialog while deleting songs dialog stuck while songs deleting app frozen</technical_language>

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { final ArrayList<Song> songs = getArguments().getParcelableArrayList("songs"); int title; CharSequence content; if (songs.size() > 1) { title = R.string.delete_songs_title; content = Html.fromHtml(getString(R.string.delete_x_songs, songs.size())); } else { title = R.string.delete_song_title; content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).title)); } return new MaterialDialog.Builder(getActivity()) .title(title) .content(content) .positiveText(R.string.delete_action) .negativeText(android.R.string.cancel) .autoDismiss(false) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { songsToRemove = songs; new DeleteSongsAsyncTask(DeleteSongsDialog.this).execute(new DeleteSongsAsyncTask.LoadingInfo(songs, null)); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { dismiss(); } }) .build(); }
Source:
<code>public static List<Pair<String, String[]>> sqlList(List<Integer> input, int maxArgs) { List<Pair<String, String[]>> ops = new ArrayList<Pair<String, String[]>>(); int numIterations = (int)Math.ceil(((double)input.size()) / maxArgs); for(int currentRound = 0 ; currentRound < numIterations ; ++currentRound) { int startPoint = currentRound * maxArgs; int lastIndex = Math.min((currentRound + 1) * maxArgs, input.size()); String ret = "("; for(int i = startPoint ; i < lastIndex ; ++i) { <START> ret += "?" + ","; <END> } String[] array = new String[lastIndex - startPoint]; int count = 0 ; for(int i = startPoint ; i < lastIndex ; ++i) { array[count++] = String.valueOf(input.get(i)); } ops.add(new Pair<String, String[]>(ret.substring(0, ret.length()-1) + ")", array)); } return ops; }</code><technical_language>a good place for a string builder</technical_language>

Target:
public static List<Pair<String, String[]>> sqlList(List<Integer> input, int maxArgs) { List<Pair<String, String[]>> ops = new ArrayList<Pair<String, String[]>>(); int numIterations = (int)Math.ceil(((double)input.size()) / maxArgs); for(int currentRound = 0 ; currentRound < numIterations ; ++currentRound) { int startPoint = currentRound * maxArgs; int lastIndex = Math.min((currentRound + 1) * maxArgs, input.size()); StringBuilder stringBuilder = new StringBuilder("("); for(int i = startPoint ; i < lastIndex ; ++i) { stringBuilder.append("?,"); } String[] array = new String[lastIndex - startPoint]; int count = 0 ; for(int i = startPoint ; i < lastIndex ; ++i) { array[count++] = String.valueOf(input.get(i)); } ops.add(new Pair<>(stringBuilder.toString().substring(0, stringBuilder.toString().length()-1) + ")", array)); } return ops; }
Source:
<code>public void registerAttributes(ManagementResourceRegistration resourceRegistration) { AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attribute : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute); } <START> HAPolicySynchronizationStatusReadHandler.registerSlaveAttributes(resourceRegistration); <END> }</code><technical_language>This registered HC</technical_language>

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attribute : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute); } if(registerRuntime) { HAPolicySynchronizationStatusReadHandler.registerSlaveAttributes(resourceRegistration); } }
Source:
<code><START> boolean isModified(String path) throws CorruptObjectException, IOException { <END> DirCache dc = DirCache.read(repo); NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); tw.reset(); tw.addTree(new DirCacheIterator(dc)); tw.addTree(new FileTreeIterator(repo.getWorkDir(), repo.getFS())); tw.setRecursive(true); tw.setFilter(PathFilter.create(path)); DirCacheIterator dcIt; WorkingTreeIterator wtIt; while(tw.next()) { dcIt = tw.getTree(0, DirCacheIterator.class); wtIt = tw.getTree(1, WorkingTreeIterator.class); if (dcIt==null || wtIt==null) return true; if (wtIt.isModified(dcIt.getDirCacheEntry(), true, config_filemode(), repo.getFS())) { return true; } } return false; }</code><technical_language>this private</technical_language>

Target:
private boolean isModified(String path) throws CorruptObjectException, IOException { DirCache dc = DirCache.read(repo); NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); tw.reset(); tw.addTree(new DirCacheIterator(dc)); tw.addTree(new FileTreeIterator(repo.getWorkDir(), repo.getFS())); tw.setRecursive(true); tw.setFilter(PathFilter.create(path)); DirCacheIterator dcIt; WorkingTreeIterator wtIt; while(tw.next()) { dcIt = tw.getTree(0, DirCacheIterator.class); wtIt = tw.getTree(1, WorkingTreeIterator.class); if (dcIt == null || wtIt == null) return true; if (wtIt.isModified(dcIt.getDirCacheEntry(), true, config_filemode(), repo.getFS())) { return true; } } return false; }