auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>RowLock(ReentrantLock rlock, ByteSequence rowSeq) { this.rlock = rlock; <START> this.count = new AtomicInteger(1); <END> this.rowSeq = rowSeq; }</code><technical_language>this count is accessed in lambdas running in Map.compute(), I do needs atomic integer. atomic integer force unneeded trips main memory. lock held Map.compute ensure consistency main memory end of sync block Map.compute() ensure mutually exclusive access</technical_language>

Target:
RowLock(ReentrantLock rlock, ByteSequence rowSeq) { this.rlock = rlock; this.count = 1; this.rowSeq = rowSeq; }
Source:
<code>public void setStringValue(BaseElement element, String value) { <START> String[] variables = value.split(","); <END> for (String variable : variables) { if (!variable.isEmpty()) { FeatureMap.Entry extension = extensionOf( DOCUMENT_ROOT__GLOBAL, globalTypeDataOf(variable)); getExtensionElements(element).add(extension); } } }</code><technical_language>I suggest move of Streams (stream().filter().map().forEach()) code more readable</technical_language>

Target:
protected void setStringValue(BaseElement element, String value) { Stream.of(value.split(",")) .map(this::extensionOf) .forEach(getExtensionElements(element)::add); }
Source:
<code>public Socket createSocket() throws IOException { Socket tcpSocket = super.createSocket(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(tcpSocket, host, port, true); ArrayList<String> protocolsList = Utils.splitString(sslConfig.sslEnabledProtocols, ","); if (!protocolsList.isEmpty()) { <START> String[] enabledProtocols = protocolsList.toArray(new String[protocolsList.size()]); <END> sslSocket.setEnabledProtocols(enabledProtocols); } ArrayList<String> cipherSuitesList = Utils.splitString(sslConfig.sslCipherSuites, ","); if (!cipherSuitesList.isEmpty()) { String[] cipherSuites = cipherSuitesList.toArray(new String[cipherSuitesList.size()]); sslSocket.setEnabledCipherSuites(cipherSuites); } try { sslSocket.startHandshake(); sslClientHandshakeCount.inc(); } catch (IOException e) { sslClientHandshakeErrorCount.inc(); throw e; } logger.debug( "Converted socket to SSL with enabled protocols and ciphers {}", sslSocket.getEnabledProtocols(), sslSocket.getEnabledCipherSuites() ); return sslSocket; }</code><technical_language>call tcpSocket.close() if exception SSL initialization</technical_language>

Target:
public Socket createSocket() throws IOException { Socket tcpSocket = super.createSocket(); SSLSocket sslSocket = null; try { sslSocket = (SSLSocket) sslSocketFactory.createSocket(tcpSocket, host, port, true); ArrayList<String> protocolsList = Utils.splitString(sslConfig.sslEnabledProtocols, ","); if (!protocolsList.isEmpty()) { String[] enabledProtocols = protocolsList.toArray(new String[protocolsList.size()]); sslSocket.setEnabledProtocols(enabledProtocols); } ArrayList<String> cipherSuitesList = Utils.splitString(sslConfig.sslCipherSuites, ","); if (!cipherSuitesList.isEmpty()) { String[] cipherSuites = cipherSuitesList.toArray(new String[cipherSuitesList.size()]); sslSocket.setEnabledCipherSuites(cipherSuites); } sslSocket.startHandshake(); sslClientHandshakeCount.inc(); } catch (IOException e) { sslClientHandshakeErrorCount.inc(); tcpSocket.setSoLinger(true, 0); tcpSocket.close(); throw e; } logger.debug( "Converted socket to SSL with enabled protocols and ciphers {}", sslSocket.getEnabledProtocols(), sslSocket.getEnabledCipherSuites() ); return sslSocket; }
Source:
<code>public void testLoadPropertiesWithoutPropertiesFile() throws Exception { Properties testProperties = PROPERTIES_LOADER.loadProperties(null, null); Properties emptyProperties = new Properties(); <START> Assert.assertEquals("Returns empty properties", emptyProperties, testProperties); <END> }</code><technical_language>simplified Hamcrest</technical_language>

Target:
public void testLoadPropertiesWithoutPropertiesFile() throws Exception { Properties testProperties = PROPERTIES_LOADER.loadProperties(null, null); assertThat(testProperties.entrySet(), is(empty())); }
Source:
<code>private LogicalPlan plan(String statement) { <START> return withMemoryLimit(ByteSizeUnit.MB.toBytes(8), () -> sqlExecutor.logicalPlan(statement)); <END> }</code><technical_language>is this limited 8MB</technical_language>

Target:
private LogicalPlan plan(String statement) { return assertMaxBytesAllocated(ByteSizeUnit.MB.toBytes(8), () -> sqlExecutor.logicalPlan(statement)); }
Source:
<code>public PaxosAgent(TimeLockInstallConfiguration install, Observable<TimeLockRuntimeConfiguration> runtime, TimeLockDeprecatedConfiguration deprecated, Consumer<Object> registrar) { super(install, runtime, deprecated, registrar); <START> Preconditions.checkState(install.algorithm() instanceof PaxosInstallConfiguration, <END> "Cannot initialize a Paxos agent with a non-Paxos algorithm configuration."); this.paxosInstall = (PaxosInstallConfiguration) install.algorithm(); this.paxosResource = PaxosResource.create(paxosInstall.dataDirectory().toString()); this.leadershipAgent = new PaxosLeadershipCreator(install, runtime, registrar); this.lockCreator = new LockCreator(runtime, deprecated); this.timestampCreator = new PaxosTimestampCreator(paxosResource, PaxosRemotingUtils.getRemoteServerPaths(install), install.cluster().cluster().security().map(SslSocketFactories::createSslSocketFactory), runtime.map(x -> x.algorithm().orElse(ImmutablePaxosRuntimeConfiguration.builder().build()))); }</code><technical_language>I constructor reference construct time in PaxosConfiguration right</technical_language>

Target:
public PaxosAgent(TimeLockInstallConfiguration install, Observable<TimeLockRuntimeConfiguration> runtime, TimeLockDeprecatedConfiguration deprecated, Consumer<Object> registrar) { super(install, runtime, deprecated, registrar); this.paxosInstall = install.algorithm(); this.paxosResource = PaxosResource.create(paxosInstall.dataDirectory().toString()); this.leadershipAgent = new PaxosLeadershipCreator(install, runtime, registrar); this.lockCreator = new LockCreator(runtime, deprecated); this.timestampCreator = new PaxosTimestampCreator(paxosResource, PaxosRemotingUtils.getRemoteServerPaths(install), install.cluster().cluster().security().map(SslSocketFactories::createSslSocketFactory), runtime.map(x -> x.algorithm().orElse(ImmutablePaxosRuntimeConfiguration.builder().build()))); }
Source:
<code>public void map(Text key, Writable value, Context context) throws IOException, InterruptedException { String url; try { if (value instanceof CrawlDatum) { context.write(key, (CrawlDatum) value); } else if (value instanceof HostDatum) { String host = key.toString(); if((url = filterNormalize("http://" + host + "/")) == null && (url = filterNormalize("https://" + host + "/")) == null && (url = filterNormalize("ftp://" + host + "/")) == null && (url = filterNormalize("file:/" + host + "/")) == null) { context.getCounter("Sitemap", "filtered_records").increment(1); return; } <START> BaseRobotRules rules = protocolFactory.getProtocol(url).getRobotRules(new Text(url), datum, new LinkedList<>()); <END> List<String> sitemaps = rules.getSitemaps(); for(String sitemap: sitemaps) { context.getCounter("Sitemap", "sitemaps_from_hostdb").increment(1); generateSitemapUrlDatum(protocolFactory.getProtocol(sitemap), sitemap, context); } } else if (value instanceof Text) { if((url = filterNormalize(key.toString())) == null) { context.getCounter("Sitemap", "filtered_records").increment(1); return; } context.getCounter("Sitemap", "sitemap_seeds").increment(1); generateSitemapUrlDatum(protocolFactory.getProtocol(url), url, context); } } catch (Exception e) { LOG.warn("Exception for record " + key.toString() + " : " + StringUtils.stringifyException(e)); } }</code><technical_language>safe pass null want robots.txt content</technical_language>

Target:
public void map(Text key, Writable value, Context context) throws IOException, InterruptedException { String url; try { if (value instanceof CrawlDatum) { context.write(key, (CrawlDatum) value); } else if (value instanceof HostDatum) { String host = key.toString(); if((url = filterNormalize("http://" + host + "/")) == null && (url = filterNormalize("https://" + host + "/")) == null && (url = filterNormalize("ftp://" + host + "/")) == null && (url = filterNormalize("file:/" + host + "/")) == null) { context.getCounter("Sitemap", "filtered_records").increment(1); return; } BaseRobotRules rules = protocolFactory.getProtocol(url).getRobotRules(new Text(url), datum, null); List<String> sitemaps = rules.getSitemaps(); for(String sitemap: sitemaps) { context.getCounter("Sitemap", "sitemaps_from_hostdb").increment(1); generateSitemapUrlDatum(protocolFactory.getProtocol(sitemap), sitemap, context); } } else if (value instanceof Text) { if((url = filterNormalize(key.toString())) == null) { context.getCounter("Sitemap", "filtered_records").increment(1); return; } context.getCounter("Sitemap", "sitemap_seeds").increment(1); generateSitemapUrlDatum(protocolFactory.getProtocol(url), url, context); } } catch (Exception e) { LOG.warn("Exception for record : {}", key.toString(), StringUtils.stringifyException(e)); } }
Source:
<code>private void verifyMasterSecret(final Socket sock) { if (sock instanceof SSLSocket) { SSLSocket ssl = (SSLSocket)sock; final SSLSession session = ssl.getSession(); if (session != null) { final String className = session.getClass().getName(); if ("sun.security.ssl.SSLSessionImpl".equals(className)) { boolean success = false; Object masterSecret = null; try { masterSecret = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { Class<?> clazz = Class.forName(className); Method method = clazz.getDeclaredMethod("getMasterSecret"); method.setAccessible(true); return method.invoke(session); } }); success = true; } catch (SecurityException e) { failedToVerifyMasterSecret(e); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if (cause instanceof InvocationTargetException) { cause = cause.getCause(); } failedToVerifyMasterSecret(cause); } <START> if (success && masterSecret == null) <END> throw log(new SecurityException("Invalid SSL master secret")); } } } return; }</code><technical_language>get rid of "success" variable if moved line 164-165 line 152. Furthermore, get rid of line 141 declaring masterSecret line 143: java Object masterSecret = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {</technical_language>

Target:
private void verifyMasterSecret(final Socket sock) throws SSLException { if (sock instanceof SSLSocket) { SSLSocket ssl = (SSLSocket)sock; SSLSession session = ssl.getSession(); if (session != null) { String className = session.getClass().getName(); if ("sun.security.ssl.SSLSessionImpl".equals(className)) { try { Class<?> clazz = Class.forName(className); Method method = clazz.getDeclaredMethod("getMasterSecret"); method.setAccessible(true); Object masterSecret = method.invoke(session); if (masterSecret == null) { session.invalidate(); if (log.isDebugEnabled()) { log.debug("Invalidated session " + session); } throw log(new SSLException("Invalid SSL master secret")); } } catch (SecurityException e) { failedToVerifyMasterSecret(e); } catch (ClassNotFoundException e) { failedToVerifyMasterSecret(e); } catch (NoSuchMethodException e) { failedToVerifyMasterSecret(e); } catch (IllegalAccessException e) { failedToVerifyMasterSecret(e); } catch (InvocationTargetException e) { failedToVerifyMasterSecret(e.getCause()); } } } } return; }
Source:
<code>public int read(byte[] b, int off, int len) throws IOException { validateParameters(b, off, len); if (len == 0) { return 0; } <START> if (firstRead) { <END> firstRead = false; parsedStream = new DataFileStream<>(networkStream, new GenericDatumReader<>()); this.userBuffer = new ByteArrayInputStream(new byte[0]); } if (this.userBuffer.available() == 0) { while (this.userBuffer.available() == 0 && this.parsedStream.hasNext()) { parseRecord(this.parsedStream.next()); } } if (this.userBuffer.available() > 0) { return this.userBuffer.read(b, off, len); } if (this.endRecordSeen) { return -1; } return 0; }</code><technical_language>I generally skip a firstRead variable checking if parsedStream is null</technical_language>

Target:
public int read(byte[] b, int off, int len) throws IOException { validateParameters(b, off, len); if (len == 0) { return 0; } if (this.parsedStream == null) { parsedStream = new DataFileStream<>(networkStream, new GenericDatumReader<>()); this.buffer = new ByteArrayInputStream(new byte[0]); } if (this.buffer.available() == 0) { while (this.buffer.available() == 0 && this.parsedStream.hasNext()) { parseRecord(this.parsedStream.next()); } } if (this.buffer.available() > 0) { return this.buffer.read(b, off, len); } if (this.endRecordSeen) { return -1; } else { throw new IOException("Error parsing blob quick query stream. No end record was present. This may indicate " + "that not all data was returned."); } }
Source:
<code>private void quitLeading() { synchronized(connectingFollowers) { quitWaitForEpoch = true; connectingFollowers.notifyAll(); } <START> LOG.info("Quit leading due to disloyal voter."); <END> }</code><technical_language>avoid 'disloyal' here, Byzantine style fault, vote is disloyal protocol? 'quite leading due a voter previously voted changed vote of ....'.</technical_language>

Target:
private void quitLeading() { synchronized(connectingFollowers) { quitWaitForEpoch = true; connectingFollowers.notifyAll(); } LOG.info("Quit leading due to voter changed mind."); }
Source:
<code>private static String simpleTypeName(TypeMirror type) { switch (type.getKind()) { case ARRAY: return simpleTypeName(((ArrayType) type).getComponentType()) + "[]"; case TYPEVAR: return ((TypeVariable) type).asElement().getSimpleName().toString(); case DECLARED: return ((DeclaredType) type).asElement().getSimpleName().toString(); default: if (type.getKind().isPrimitive()) { <START> switch (type.getKind()) { <END> case BOOLEAN: return "boolean"; case BYTE: return "byte"; case CHAR: return "char"; case DOUBLE: return "double"; case FLOAT: return "float"; case INT: return "int"; case LONG: return "long"; case SHORT: return "short"; default: throw new BugInCF("expected a primitive type, but found " + type); } } } throw new BugInCF("ElementUtils: unhandled type kind: %s, type: %s", type.getKind(), type); }</code><technical_language>TypeAnnotationUtils.unannotatedType(type).toString();. This sense break out a separate PR</technical_language>

Target:
private static String simpleTypeName(TypeMirror type) { switch (type.getKind()) { case ARRAY: return simpleTypeName(((ArrayType) type).getComponentType()) + "[]"; case TYPEVAR: return ((TypeVariable) type).asElement().getSimpleName().toString(); case DECLARED: return ((DeclaredType) type).asElement().getSimpleName().toString(); default: if (type.getKind().isPrimitive()) { return TypeAnnotationUtils.unannotatedType(type).toString(); } } throw new BugInCF("ElementUtils: unhandled type kind: %s, type: %s", type.getKind(), type); }
Source:
<code>public static RelDataType createJoinType( RelDataTypeFactory typeFactory, RelDataType leftType, RelDataType rightType, List<String> fieldNameList, List<RelDataTypeField> systemFieldList) { assert (fieldNameList == null) || (fieldNameList.size() == (systemFieldList.size() + leftType.getFieldCount() <START> + (rightType == null ? 0 : rightType.getFieldCount()))); <END> List<String> nameList = new ArrayList<>(); final List<RelDataType> typeList = new ArrayList<>(); final Set<String> uniqueNameList = typeFactory.getTypeSystem().isSchemaCaseSensitive() ? new HashSet<String>() : new TreeSet<>(String.CASE_INSENSITIVE_ORDER); addFields(systemFieldList, typeList, nameList, uniqueNameList); addFields(leftType.getFieldList(), typeList, nameList, uniqueNameList); if (rightType != null) { addFields( rightType.getFieldList(), typeList, nameList, uniqueNameList); } if (fieldNameList != null) { assert fieldNameList.size() == nameList.size(); nameList = fieldNameList; } return typeFactory.createStructType(typeList, nameList); }</code><technical_language>require rightType is null. add precondition, making code more defensive</technical_language>

Target:
public static RelDataType createJoinType( RelDataTypeFactory typeFactory, RelDataType leftType, RelDataType rightType, List<String> fieldNameList, List<RelDataTypeField> systemFieldList) { assert rightType != null; assert (fieldNameList == null) || (fieldNameList.size() == (systemFieldList.size() + leftType.getFieldCount() + rightType.getFieldCount())); List<String> nameList = new ArrayList<>(); final List<RelDataType> typeList = new ArrayList<>(); final Set<String> uniqueNameList = typeFactory.getTypeSystem().isSchemaCaseSensitive() ? new HashSet<String>() : new TreeSet<>(String.CASE_INSENSITIVE_ORDER); addFields(systemFieldList, typeList, nameList, uniqueNameList); addFields(leftType.getFieldList(), typeList, nameList, uniqueNameList); if (rightType != null) { addFields( rightType.getFieldList(), typeList, nameList, uniqueNameList); } if (fieldNameList != null) { assert fieldNameList.size() == nameList.size(); nameList = fieldNameList; } return typeFactory.createStructType(typeList, nameList); }
Source:
<code>public boolean sameAs(FormEntryPrompt question) { return question != null && question.getIndex().equals(index) && (question.getQuestionText() == null ? questionText == null : question.getQuestionText().equals(questionText)) && (question.getHelpText() == null ? helpText == null : question.getHelpText().equals(helpText)) && (question.getAnswerText() == null ? answerText == null : question.getAnswerText().equals(answerText)) && (question.isReadOnly() == isReadOnly) <START> && (question.getSelectChoices() == null ? selectChoices == null : question.getSelectChoices().equals(selectChoices)); <END> }</code><technical_language>call this conventional name equals is this intentionally different</technical_language>

Target:
public boolean sameAs(FormEntryPrompt question) { return question != null && question.getIndex().equals(index) && (question.getQuestionText() == null ? questionText == null : question.getQuestionText().equals(questionText)) && (question.getHelpText() == null ? helpText == null : question.getHelpText().equals(helpText)) && (getGuidanceHintText(question) == null ? guidanceText == null : getGuidanceHintText(question).equals(guidanceText)) && (question.getAnswerText() == null ? answerText == null : question.getAnswerText().equals(answerText)) && (question.isReadOnly() == isReadOnly) && selectChoiceListsEqual(question.getSelectChoices(), selectChoices); }
Source:
<code>public static List<CurveGroup> load( LocalDate marketDataDate, ResourceLocator groupsResource, ResourceLocator settingsResource, Collection<ResourceLocator> curvesResources) { List<CurveGroupDefinition> curveGroups = CurveGroupDefinitionCsvLoader.loadCurveGroups(groupsResource); Multimap<LocalDate, Curve> allCurves = loadCurves(settingsResource, curvesResources, marketDataDate); Collection<Curve> curves = allCurves.get(marketDataDate); Set<CurveName> curveNames = new HashSet<>(); for (Curve curve : curves) { <START> if (curveNames.contains(curve.getName())) { <END> throw new IllegalArgumentException("Multiple curves with the same name: " + curve.getName()); } curveNames.add(curve.getName()); } return curveGroups.stream().map(groupDef -> CurveGroup.ofCurves(groupDef, curves)).collect(toImmutableList()); }</code><technical_language>if (!curveNames.add(curve.getName())) {</technical_language>

Target:
public static List<CurveGroup> load( LocalDate marketDataDate, ResourceLocator groupsResource, ResourceLocator settingsResource, Collection<ResourceLocator> curvesResources) { List<CurveGroupDefinition> curveGroups = CurveGroupDefinitionCsvLoader.loadCurveGroups(groupsResource); Multimap<LocalDate, Curve> allCurves = loadCurves(settingsResource, curvesResources, marketDataDate); Collection<Curve> curves = allCurves.get(marketDataDate); Set<CurveName> curveNames = new HashSet<>(); for (Curve curve : curves) { if (!curveNames.add(curve.getName())) { throw new IllegalArgumentException("Multiple curves with the same name: " + curve.getName()); } } return curveGroups.stream().map(groupDef -> CurveGroup.ofCurves(groupDef, curves)).collect(toImmutableList()); }
Source:
<code>public void send(RiemannEvent event) { try { <START> String tagsArr[] = ObjectArrays.concat(event.tags.toArray(new String[event.tags.size()]), new String[]{"storm"}, String.class); <END> createEvent() .description(event.description) .host(event.host) .service(machineName + " " + event.service) .state(event.state) .time(event.time) .metric(event.metric) .ttl(event.ttl) .tags(tagsArr) .attributes(event.customAttributes) .send(); } catch (Throwable t) { logger.warn("Riemann error during general event ("+ event.description+") send attempt: ", t); } }</code><technical_language>check if fluent api add storm tag</technical_language>

Target:
public void send(RiemannEvent event) { try { createEvent() .description(event.description) .host(event.host) .service(machineName + " " + event.service) .state(event.state) .time(event.time) .metric(event.metric) .ttl(event.ttl) .tag("storm") .tags(event.tags) .attributes(event.customAttributes) .send(); } catch (Throwable t) { logger.warn("Riemann error during event ("+ event.description+") send attempt: ", t); } }
Source:
<code>private Mono<HttpResponse> attemptAsync(final HttpPipelineCallContext context, final HttpPipelineNextPolicy next, final HttpRequest originalHttpRequest, final int tryCount) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process() .flatMap(httpResponse -> { if (shouldRetry(httpResponse, tryCount)) { return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(determineDelayDuration(httpResponse)); } else { return Mono.just(httpResponse); } }) .onErrorResume(err -> { if (tryCount < maxRetries) { return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(this.delayDuration); } else { <START> return Mono.error(new RuntimeException("Max retries exceeded. Error Details: " + err.getMessage(), <END> err)); } }); }</code><technical_language>Do want add retried attempted</technical_language>

Target:
private Mono<HttpResponse> attemptAsync(final HttpPipelineCallContext context, final HttpPipelineNextPolicy next, final HttpRequest originalHttpRequest, final int tryCount) { context.setHttpRequest(originalHttpRequest.copy()); return next.clone().process() .flatMap(httpResponse -> { if (shouldRetry(httpResponse, tryCount)) { return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(determineDelayDuration(httpResponse)); } else { return Mono.just(httpResponse); } }) .onErrorResume(err -> { if (tryCount < maxRetries) { return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(this.delayDuration); } else { return Mono.error(new RuntimeException( String.format("Max retries %d times exceeded. Error Details: %s", maxRetries, err.getMessage()), err)); } }); }
Source:
<code>private Iterator<HiveFileInfo> cachingIterator(Iterator<HiveFileInfo> iterator, Path path) { return new Iterator<HiveFileInfo>() { private final List<HiveFileInfo> files = new ArrayList<>(); @Override public boolean hasNext() { boolean hasNext = iterator.hasNext(); if (!hasNext) { <START> cache.put(path, files); <END> } return hasNext; } @Override public HiveFileInfo next() { HiveFileInfo next = iterator.next(); files.add(next); return next; } }; }</code><technical_language>nit: safe copy part of code</technical_language>

Target:
private Iterator<HiveFileInfo> cachingIterator(Iterator<HiveFileInfo> iterator, Path path) { return new Iterator<HiveFileInfo>() { private final List<HiveFileInfo> files = new ArrayList<>(); @Override public boolean hasNext() { boolean hasNext = iterator.hasNext(); if (!hasNext) { cache.put(path, ImmutableList.copyOf(files)); } return hasNext; } @Override public HiveFileInfo next() { HiveFileInfo next = iterator.next(); files.add(next); return next; } }; }
Source:
<code>public DomainRootDefinition( final DomainController domainController, final HostControllerEnvironment environment, final ExtensibleConfigurationPersister configurationPersister, final ContentRepository contentRepo, final HostFileRepository fileRepository, final boolean isMaster, final LocalHostControllerInfo hostControllerInfo, final ExtensionRegistry extensionRegistry, final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry, final PathManagerService pathManager, final DomainControllerRuntimeIgnoreTransformationRegistry runtimeIgnoreTransformationRegistry, final DelegatingConfigurableAuthorizer authorizer, final HostRegistrations hostRegistrations) { <START> this(domainController, environment, configurationPersister, contentRepo, fileRepository, isMaster, <END> hostControllerInfo, extensionRegistry, ignoredDomainResourceRegistry, pathManager, runtimeIgnoreTransformationRegistry, authorizer, hostRegistrations, null); }</code><technical_language>modify method is public API. This require update of wildfly-legacy, I this is merged</technical_language>

Target:
public DomainRootDefinition( final DomainController domainController, final HostControllerEnvironment environment, final ExtensibleConfigurationPersister configurationPersister, final ContentRepository contentRepo, final HostFileRepository fileRepository, final boolean isMaster, final LocalHostControllerInfo hostControllerInfo, final ExtensionRegistry extensionRegistry, final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry, final PathManagerService pathManager, final DomainControllerRuntimeIgnoreTransformationRegistry runtimeIgnoreTransformationRegistry, final DelegatingConfigurableAuthorizer authorizer, final HostRegistrations hostRegistrations) { super(null, DomainResolver.getResolver(DOMAIN, false)); this.domainController = domainController; this.isMaster = isMaster; this.environment = environment; this.hostControllerInfo = hostControllerInfo; this.configurationPersister = configurationPersister; this.contentRepo = contentRepo; this.fileRepository = fileRepository; this.extensionRegistry = extensionRegistry; this.ignoredDomainResourceRegistry = ignoredDomainResourceRegistry; this.pathManager = pathManager; this.runtimeIgnoreTransformationRegistry = runtimeIgnoreTransformationRegistry; this.authorizer = authorizer; this.hostRegistrations = hostRegistrations; }
Source:
<code><START> private void waitForPriorityEvents(InputGate inputGate, MailboxExecutor mailboxExecutor) { final CompletableFuture<?> priorityEventAvailableFuture = inputGate.getPriorityEventAvailableFuture(); priorityEventAvailableFuture.thenRun(() -> { <END> mailboxExecutor.execute(this::processPriorityEvents, "process priority even @ gate %s", inputGate); }); }</code><technical_language>1. Again, do I understand this correctly? Is this assuming polls completing getPriorityEventAvailableFuture executing this::processPriorityEvents? a bit fragile? 2. motivation for passing priority events StreamTaskNetworkInput? 3. processing priority events part of pollNext()</technical_language>

Target:
private void waitForPriorityEvents(InputGate inputGate, MailboxExecutor mailboxExecutor) { final CompletableFuture<?> priorityEventAvailableFuture = inputGate.getPriorityEventAvailableFuture(); priorityEventAvailableFuture.thenRun(() -> mailboxExecutor.execute(this::processPriorityEvents, "process priority event @ gate %s", inputGate)); }
Source:
<code>public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); if (response.isSuccessful()) { return response; } else { try { final JsonNode responseBody = mapper.readTree(response.body().string()); throw new GenieClientException(response.code(), response.message() + " : " + responseBody.get("message")); <START> } catch (JsonMappingException jme) { <END> throw new GenieClientException(response.code(), response.message() + response.body().toString()); } } }</code><technical_language>Catching JsonProcessingException encompass JsonMappingException JsonParseException. catch explicitly</technical_language>

Target:
public Response intercept(final Chain chain) throws IOException { final Response response = chain.proceed(chain.request()); if (response.isSuccessful()) { return response; } else { final String bodyContent = response.body().string(); try { final JsonNode responseBody = mapper.readTree(bodyContent); throw new GenieClientException(response.code(), response.message() + " : " + responseBody.get("message")); } catch (JsonProcessingException jpe) { throw new GenieClientException(response.code(), response.message() + bodyContent); } } }
Source:
<code>public String toXMLString() throws XMLStreamException, FactoryConfigurationError { StringWriter buffer = new StringWriter(); XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(buffer); String server = getServer(); int port = getPort(); String group = getGroup(); String database = getDatabase(); String modulesDatabase = getModulesDatabase(); writer.writeStartDocument(); writer.writeStartElement("rest-api"); writer.writeDefaultNamespace("<LINK_0>"); writer.writeStartElement("name"); if(server != null) writer.writeCharacters(server); writer.writeEndElement(); if (group != null && group.length() > 0) { writer.writeStartElement("group"); writer.writeCharacters(group); writer.writeEndElement(); } writer.writeStartElement("database"); if(database != null) writer.writeCharacters(database); writer.writeEndElement(); if (modulesDatabase != null && modulesDatabase.length() > 0) { writer.writeStartElement("modules-database"); writer.writeCharacters(modulesDatabase); writer.writeEndElement(); } writer.writeStartElement("port"); <START> if(String.valueOf(port) != null) <END> writer.writeCharacters(String.valueOf(port)); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); return buffer.toString(); }</code><technical_language>int null, skip this check</technical_language>

Target:
public String toXMLString() throws XMLStreamException, FactoryConfigurationError { StringWriter buffer = new StringWriter(); XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(buffer); String server = getServer(); int port = getPort(); String group = getGroup(); String database = getDatabase(); String modulesDatabase = getModulesDatabase(); writer.writeStartDocument(); writer.writeStartElement("rest-api"); writer.writeDefaultNamespace("<LINK_0>"); writer.writeStartElement("name"); if(server != null) writer.writeCharacters(server); writer.writeEndElement(); if (group != null && group.length() > 0) { writer.writeStartElement("group"); writer.writeCharacters(group); writer.writeEndElement(); } writer.writeStartElement("database"); if(database != null) writer.writeCharacters(database); writer.writeEndElement(); if (modulesDatabase != null && modulesDatabase.length() > 0) { writer.writeStartElement("modules-database"); writer.writeCharacters(modulesDatabase); writer.writeEndElement(); } writer.writeStartElement("port"); writer.writeCharacters(String.valueOf(port)); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); return buffer.toString(); }
Source:
<code>private Cursor fetchThemes(int position) { if (WordPress.getCurrentBlog() == null) { return null; } String blogId = String.valueOf(WordPress.getCurrentBlog().getRemoteBlogId()); switch (position) { <START> case 2: <END> return WordPress.wpDB.getThemesPremium(blogId); case 1: return WordPress.wpDB.getThemesFree(blogId); case 0: default: return WordPress.wpDB.getThemesAll(blogId); } }</code><technical_language>a constant for this hardcode</technical_language>

Target:
private Cursor fetchThemes(int position) { if (WordPress.getCurrentBlog() == null) { return null; } String blogId = String.valueOf(WordPress.getCurrentBlog().getRemoteBlogId()); switch (position) { case THEME_FILTER_PREMIUM_INDEX: return WordPress.wpDB.getThemesPremium(blogId); case THEME_FILTER_FREE_INDEX: return WordPress.wpDB.getThemesFree(blogId); case THEME_FILTER_ALL_INDEX: default: return WordPress.wpDB.getThemesAll(blogId); } }
Source:
<code>private SortedSet<Edge<V>> convertEdges(final Set<DefaultEdge> input) { <START> Iterator<DefaultEdge> edgeIt = input.iterator(); <END> SortedSet<Edge<V>> output = new TreeSet<>(new EdgeComparatorByVertex()); while (edgeIt.hasNext()) { output.add(edgeFact.getEdge(edgeIt.next())); } return output; }</code><technical_language>Iterator instead of a for loop</technical_language>

Target:
private SortedSet<Edge<V>> convertEdges(final Set<DefaultEdge> input) { SortedSet<Edge<V>> output = new TreeSet<>(new EdgeComparatorByVertex()); for (DefaultEdge e : input) { output.add(edgeFact.getEdge(e)); } return output; }
Source:
<code>public static void main(String[] args) throws Exception { InputAdvanceJava9TryWithResources v = new InputAdvanceJava9TryWithResources(); try (v.finalWrapper.finalField) { } try (new InputAdvanceJava9TryWithResources() { }.finalWrapper.finalField) { } try ((args.length > 0 ? v : new InputAdvanceJava9TryWithResources()).finalWrapper.finalField) { } InputAdvanceJava9TryWithResources i1 = new InputAdvanceJava9TryWithResources(); try (i1; InputAdvanceJava9TryWithResources i2 = new InputAdvanceJava9TryWithResources(true)) { } InputAdvanceJava9TryWithResources m1 = new InputAdvanceJava9TryWithResources(); try (m1; InputAdvanceJava9TryWithResources m2 = m1; InputAdvanceJava9TryWithResources m3 = m2;) { } try { } catch (Exception ex) { try (v) { } } InputAdvanceJava9TryWithResources n = null; try (n) { } AutoCloseable a = new AutoCloseable() { public void close() { }; }; <START> try (a) { <END> } catch (Exception e) }</code><technical_language>please explain this code is related issue try resolve. is from: InputAdvanceJava9TryWithResources n = null; try (n) { parser do care values logic in code. If extending code base more Input for coverage - awesome, please move separate Input file. need focus cases of field usage in try</technical_language>

Target:
public static void main(String[] args) throws Exception { InputAdvanceJava9TryWithResources v = new InputAdvanceJava9TryWithResources(); try (v.finalWrapper.finalField) { } try (new InputAdvanceJava9TryWithResources() { }.finalWrapper.finalField) { } try ((args.length > 0 ? v : new InputAdvanceJava9TryWithResources()).finalWrapper.finalField) { } InputAdvanceJava9TryWithResources i1 = new InputAdvanceJava9TryWithResources(); try (i1; InputAdvanceJava9TryWithResources i2 = new InputAdvanceJava9TryWithResources()) { } InputAdvanceJava9TryWithResources m1 = new InputAdvanceJava9TryWithResources(); try (m1; InputAdvanceJava9TryWithResources m2 = m1; InputAdvanceJava9TryWithResources m3 = m2;) { } }
Source:
<code>private static int maskVar(final String desc, final boolean constructor) { final Type[] argumentTypes = Type.getMethodType(desc) .getArgumentTypes(); int slot = 0; for (int i = 0; i < argumentTypes.length <START> - (constructor ? 1 : 2); i++) { <END> slot += argumentTypes[i].getSize(); } return slot; }</code><technical_language>do magic numbers mean? enlight future readers of code a local variable: int descripiveName = constructor ? 1 : 2;</technical_language>

Target:
private static int maskVar(final String desc, final boolean constructor) { int slot = 0; if (constructor) { slot++; } final Type[] argumentTypes = Type.getMethodType(desc) .getArgumentTypes(); final int penultimateArgument = argumentTypes.length - 2; for (int i = 0; i < penultimateArgument; i++) { slot += argumentTypes[i].getSize(); } return slot; }
Source:
<code>public void trackConstructorTest() { URL resourceUrl = getClass().getResource("/beep.mp3"); Path resourcePath; try { resourcePath = Paths.get(resourceUrl.toURI()); <START> Track tr = new Track(resourcePath.toString()); <END> assertEquals(tr.getAlbum(), "Beeps of the year"); assertEquals(tr.getTitle(), "Beep"); assertEquals(tr.getArtist(), "Flix"); assertEquals(tr.getLength(), new Long(575)); } catch (URISyntaxException e) { fail("file wans't read correctly"); e.printStackTrace(); } }</code><technical_language>In terms of naming things, I shortening 'track' 'tr'. readable overall</technical_language>

Target:
public void trackConstructorTest() { URL resourceUrl = getClass().getResource("/beep.mp3"); Path resourcePath; try { resourcePath = Paths.get(resourceUrl.toURI()); Track track = new Track(resourcePath.toString()); assertEquals(track.getAlbum(), "Beeps of the year"); assertEquals(track.getTitle(), "Beep"); assertEquals(track.getArtist(), "Flix"); assertEquals(track.getLength(), new Long(575)); } catch (URISyntaxException e) { fail("file wans't read correctly"); e.printStackTrace(); } }
Source:
<code>public static EmbeddedCacheManager createCacheManagerEnforceJmxDomain(String jmxDomain, String cacheManagerName, boolean exposeGlobalJmx, boolean exposeCacheJmx, boolean allowDuplicates) { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .globalJmxStatistics() .allowDuplicateDomains(allowDuplicates) .jmxDomain(jmxDomain) .mBeanServerLookup(MBeanServerLookupProvider.create()) <START> .enabled(exposeGlobalJmx); <END> if (cacheManagerName != null) globalConfiguration.cacheManagerName(cacheManagerName); ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.jmxStatistics().enabled(exposeCacheJmx); return createCacheManager(globalConfiguration, configuration, true); }</code><technical_language>enabled is deprecated, update this globalBuilder.cacheContainer().statistics(exposeGlobalJmx)</technical_language>

Target:
public static EmbeddedCacheManager createCacheManagerEnforceJmxDomain(String jmxDomain, String cacheManagerName, boolean exposeGlobalJmx, boolean exposeCacheJmx, boolean allowDuplicates) { GlobalConfigurationBuilder globalConfiguration = new GlobalConfigurationBuilder(); globalConfiguration .cacheContainer().statistics(exposeGlobalJmx) .globalJmxStatistics() .allowDuplicateDomains(allowDuplicates) .jmxDomain(jmxDomain) .mBeanServerLookup(MBeanServerLookupProvider.create()); if (cacheManagerName != null) globalConfiguration.cacheManagerName(cacheManagerName); ConfigurationBuilder configuration = new ConfigurationBuilder(); configuration.jmxStatistics().enabled(exposeCacheJmx); return createCacheManager(globalConfiguration, configuration, true); }
Source:
<code>public boolean isReachable() { Socket socket = null; boolean reachable = false; try { if (LOG.isDebugEnabled()) <START> LOG.debug("Checking host "+ InetAddress.getLocalHost() + "and port " + getPort() ); <END> if (port.isPresent()) { socket = new Socket(InetAddress.getLocalHost(), getPort().get()); reachable = true; } } catch (Exception e) { } finally { IOUtils.closeQuietly(socket); } return reachable; }</code><technical_language>Space "+</technical_language>

Target:
public boolean isReachable() { Socket socket = null; boolean reachable = false; try { if (LOG.isDebugEnabled()) { LOG.debug("Checking host " + InetAddress.getLocalHost() + " and port " + getPort()); } if (port.isPresent()) { socket = new Socket(InetAddress.getLocalHost(), getPort().get()); reachable = true; } } catch (Exception e) { } finally { IOUtils.closeQuietly(socket); } return reachable; }
Source:
<code>public DistributedObject createDistributedObject(String cacheNameWithPrefix) { try { CacheConfig cacheConfig = getCacheConfig(cacheNameWithPrefix); if (cacheConfig == null) { String cacheName = cacheNameWithPrefix.substring(HazelcastCacheManager.CACHE_MANAGER_PREFIX.length()); cacheConfig = findCacheConfig(cacheName); if (cacheConfig == null) { throw new CacheNotExistsException("Couldn't find cache config with name " + cacheNameWithPrefix); } cacheConfig.setManagerPrefix(HazelcastCacheManager.CACHE_MANAGER_PREFIX); } <START> SplitBrainMergePolicyProvider mergePolicyProvider = nodeEngine.getSplitBrainMergePolicyProvider(); <END> checkCacheConfig(cacheConfig, mergePolicyProvider); String mergePolicyName = cacheConfig.getMergePolicyConfig().getPolicy(); Object mergePolicy = mergePolicyProvider.getMergePolicy(mergePolicyName); checkMergePolicySupportsInMemoryFormat(cacheConfig.getName(), mergePolicy, cacheConfig.getInMemoryFormat(), true, logger); if (putCacheConfigIfAbsent(cacheConfig) == null) { createCacheConfigOnAllMembers(PreJoinCacheConfig.of(cacheConfig)); } return new CacheProxy(cacheConfig, nodeEngine, this); } catch (Throwable t) { throw rethrow(t); } }</code><technical_language>Minor: omit this line field initialised in init()</technical_language>

Target:
public DistributedObject createDistributedObject(String cacheNameWithPrefix) { try { CacheConfig cacheConfig = getCacheConfig(cacheNameWithPrefix); if (cacheConfig == null) { String cacheName = cacheNameWithPrefix.substring(HazelcastCacheManager.CACHE_MANAGER_PREFIX.length()); cacheConfig = findCacheConfig(cacheName); if (cacheConfig == null) { throw new CacheNotExistsException("Couldn't find cache config with name " + cacheNameWithPrefix); } cacheConfig.setManagerPrefix(HazelcastCacheManager.CACHE_MANAGER_PREFIX); } checkCacheConfig(cacheConfig, mergePolicyProvider); String mergePolicyName = cacheConfig.getMergePolicyConfig().getPolicy(); Object mergePolicy = mergePolicyProvider.getMergePolicy(mergePolicyName); checkMergePolicySupportsInMemoryFormat(cacheConfig.getName(), mergePolicy, cacheConfig.getInMemoryFormat(), true, logger); if (putCacheConfigIfAbsent(cacheConfig) == null) { createCacheConfigOnAllMembers(PreJoinCacheConfig.of(cacheConfig)); } return new CacheProxy(cacheConfig, nodeEngine, this); } catch (Throwable t) { throw rethrow(t); } }
Source:
<code>public static boolean eq(Object b0, Object b1) { if (b0.getClass().equals(b1.getClass())) { <START> if (bothParametersAssignable(b0, b1, BigDecimal.class)) { <END> return eq((BigDecimal) b0, (BigDecimal) b1); } else { return b0.equals(b1); } } else if (bothParametersAssignable(b0, b1, Number.class)) { return eq(toBigDecimal((Number) b0), toBigDecimal((Number) b1)); } return false; }</code><technical_language>nit: b0 b1 of Class, enough if checkBigDecimal.class.isAssignable(b0)</technical_language>

Target:
public static boolean eq(Object b0, Object b1) { return b0.equals(b1); }
Source:
<code>public void testAddMergeAggregatorOff() { when(_mockConfig.getBoolean(eq("kairosdb.proxy.addMergeAggregator"))).thenReturn(false); final KairosDbProxyController controller = new KairosDbProxyController( _mockConfig, _mockWSClient, _mockKairosDbClient, OBJECT_MAPPER, _mockMetricsFactory, _mockMetricsqueryConfig ); final Metric metric1 = new Metric.Builder() .setName("metric1") .setAggregators(ImmutableList.of(new Aggregator.Builder().setName("count").build())) .build(); final Metric metric2 = new Metric.Builder() .setName("metric2") .setAggregators(ImmutableList.of(new Aggregator.Builder().setName("filter").build())) .build(); final MetricsQuery metricsQuery = new MetricsQuery.Builder() .setStartTime(Instant.now()) .setMetrics(ImmutableList.of(metric1, metric2)) .build(); <START> final Http.RequestBuilder request = Helpers.fakeRequest() .method(Helpers.POST) .uri("/api/v1/datapoints/query") .header("Content-Type", "application/json") .bodyJson(OBJECT_MAPPER.<JsonNode>valueToTree(metricsQuery)); when(_mockKairosDbClient.queryMetrics(metricsQuery)).thenReturn( CompletableFuture.completedFuture(new MetricsQueryResponse.Builder() .setQueries(ImmutableList.of()).build()) ); final Result result = Helpers.invokeWithContext(request, Helpers.contextComponents(), () -> { final CompletionStage<Result> completionStage = controller.queryMetrics(); return completionStage.toCompletableFuture().get(10, TimeUnit.SECONDS); }); assertEquals(Http.Status.OK, result.status()); assertEquals("{\"queries\":[]}", Helpers.contentAsString(result)); <END> }</code><technical_language>ask, sorry: 18 lines repeated test-methods, differing in: - argument passing when(_mockKairosDbClient.queryMetrics(...)) - controller is hit request refactor this out a method? (This a great chance experiment IntelliJ's "Extract method" functionality! Select a bunch of code, right-click, "Refactor", "Extract method". easy refactor a chunk of code out method.)</technical_language>

Target:
public void testAddMergeAggregatorOff() { when(_mockConfig.getBoolean(eq("kairosdb.proxy.addMergeAggregator"))).thenReturn(false); final KairosDbProxyController controller = new KairosDbProxyController( _mockConfig, _mockWSClient, _mockKairosDbClient, OBJECT_MAPPER, _mockMetricsFactory, _mockMetricsqueryConfig ); final Metric metric1 = new Metric.Builder() .setName("metric1") .setAggregators(ImmutableList.of(new Aggregator.Builder().setName("count").build())) .build(); final Metric metric2 = new Metric.Builder() .setName("metric2") .setAggregators(ImmutableList.of(new Aggregator.Builder().setName("filter").build())) .build(); final MetricsQuery metricsQuery = new MetricsQuery.Builder() .setStartTime(Instant.now()) .setMetrics(ImmutableList.of(metric1, metric2)) .build(); mockQueryMetrics(controller, metricsQuery, metricsQuery); }
Source:
<code>void tryEmit(InnerSubscriber<T> subscriber, T value) { boolean success = false; long r = producer.get(); if (r != 0L) { synchronized (this) { r = producer.get(); if (!emitting && r != 0L) { emitting = true; success = true; } } } if (success) { <START> if (subscriber.queue == null || subscriber.queue.isEmpty()) { <END> emitScalar(subscriber, value, r); } else { queueScalar(subscriber, value); emitLoop(); } } else { queueScalar(subscriber, value); emit(); } }</code><technical_language>assign subscriber.queue local variable avoid double volatile read</technical_language>

Target:
void tryEmit(InnerSubscriber<T> subscriber, T value) { boolean success = false; long r = producer.get(); if (r != 0L) { synchronized (this) { r = producer.get(); if (!emitting && r != 0L) { emitting = true; success = true; } } } if (success) { RxRingBuffer subscriberQueue = subscriber.queue; if (subscriberQueue == null || subscriberQueue.isEmpty()) { emitScalar(subscriber, value, r); } else { queueScalar(subscriber, value); emitLoop(); } } else { queueScalar(subscriber, value); emit(); } }
Source:
<code>public void bind(TypeBindingContext context) { context.getDependencies().useRootOnly(); <START> IndexReferenceHolder indexReferenceProvider = createIndexReferenceProvider(context, 5); <END> Descriptor descriptor = globalReferenceHolder.getDescriptor(rootMessageName); context.setBridge(new ProtobufMessageBridge(indexReferenceProvider, descriptor)); }</code><technical_language>Important: this 5 means handle 5 level of embedding. In order improve this, need add a proper @IndexedEmbedded annotation annotations supported protobuf, a maxDepth attribute. support includePaths attribute do in Hibernate Search, require some more work code handle a maxDepth</technical_language>

Target:
public void bind(TypeBindingContext context) { context.getDependencies().useRootOnly(); IndexReferenceHolder indexReferenceProvider = createIndexReferenceProvider(context, MAX_DEPTH); Descriptor descriptor = globalReferenceHolder.getDescriptor(rootMessageName); context.setBridge(new ProtobufMessageBridge(indexReferenceProvider, descriptor)); }
Source:
<code>public IResource getResource() { ByteArrayOutputStream webResponse = new ByteArrayOutputStream(); AbstractSelect2Choice.generateJSON(getChoiceProvider(), webResponse); <START> StringResourceStream resourceStream = new StringResourceStream(webResponse.toString(), "application/json"); <END> return new ResourceStreamResource(resourceStream); }</code><technical_language>This platform's default encoding. I is safer .toString("UTF-8")</technical_language>

Target:
public IResource getResource() { ByteArrayOutputStream webResponse = new ByteArrayOutputStream(); AbstractSelect2Choice.generateJSON(getChoiceProvider(), webResponse); StringResourceStream resourceStream; try { resourceStream = new StringResourceStream(webResponse.toString("UTF-8"), "application/json"); } catch (UnsupportedEncodingException e) { logger.error("getResource", e); throw new WicketRuntimeException(e); } return new ResourceStreamResource(resourceStream); }