auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean createTable() { try { ControllerTest.sendPostRequest( ControllerRequestURLBuilder.baseUrl(CONTROLLER_URL).forSchemaCreate(), FileUtils.readFileToString(new File(_schemaFileName))); return true; } catch (IOException e) { <START> System.out.println(e.getMessage()); <END> return false; } }</code><technical_language>error log</technical_language>

Target:
private boolean createTable() { try { ControllerTest.sendPostRequest( ControllerRequestURLBuilder.baseUrl(ClusterDescriptor.CONTROLLER_URL).forTableCreate(), FileUtils.readFileToString(new File(_tableConfigFileName))); return true; } catch (IOException e) { LOGGER.error("Failed to create table with file: {}", _tableConfigFileName, e); return false; } }
Source:
<code>protected void onReadRequestStart(Channel channel) { if (readsSemaphore != null) { if (!readsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); readsBlocked.incrementAndGet(); readsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); readEntryBlockedStats.registerSuccessfulEvent(MathUtils.elapsedNanos(throttlingStartTimeNanos), <START> TimeUnit.NANOSECONDS); <END> readsBlocked.decrementAndGet(); } } final int curr = readsInProgress.incrementAndGet(); maxReadsInProgress.accumulateAndGet(curr, Integer::max); }</code><technical_language>Info/debug message this block helpful</technical_language>

Target:
protected void onReadRequestStart(Channel channel) { if (readsSemaphore != null) { if (!readsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); LOG.info("Too many read requests in progress, disabling autoread on channel {}", channel); readsBlocked.incrementAndGet(); readsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); final long delayNanos = MathUtils.elapsedNanos(throttlingStartTimeNanos); LOG.info("Re-enabled autoread on channel after ReadRequest delay of nanos", channel, delayNanos); readEntryBlockedStats.registerSuccessfulEvent(delayNanos, TimeUnit.NANOSECONDS); readsBlocked.decrementAndGet(); } } final int curr = readsInProgress.incrementAndGet(); maxReadsInProgress.accumulateAndGet(curr, Integer::max); }
Source:
<code>private boolean filterFlushLines() throws IOException { boolean flushed = false; if (buf.position() > 0) { buf.flip(); Matcher matcher = EOL.matcher(buf); int start = 0; while (matcher.find()) { int end = matcher.end(); String line = buf.subSequence(start, end).toString(); String filtered = contentFilter.filter(line); out.write(filtered.getBytes(charset)); start = end; flushed = true; } buf.position(start); if (buf.capacity() - buf.remaining() > DEFAULT_DECODER_CAPACITY) { <START> buf = CharBuffer.allocate(DEFAULT_DECODER_CAPACITY).put(buf); <END> } else { buf.compact(); } } return flushed; }</code><technical_language>I resize buffer smaller here. If some large lines more, want avoid extra allocations/deallocations. resize in reset in case is huge line in a single file in case, unnecessary</technical_language>

Target:
private boolean filterFlushLines() throws IOException { ensureOpen(); boolean flushed = false; if (decodedBuf.position() > 0) { decodedBuf.flip(); Matcher matcher = EOL.matcher(decodedBuf); int start = 0; while (matcher.find()) { int end = matcher.end(); String line = decodedBuf.subSequence(start, end).toString(); String filtered = contentFilter.filter(line); out.write(filtered.getBytes(charset)); start = end; flushed = true; } decodedBuf.position(start); decodedBuf.compact(); } return flushed; }
Source:
<code>public static long dateToLong(Object datelike) { <START> if (datelike instanceof Date) { <END> Date date = (Date) datelike; return date.getTime(); } else if (datelike instanceof Instant) { Instant instant = (Instant) datelike; return instant.toEpochMilli(); } else if (datelike instanceof LocalDateTime) { LocalDateTime date = (LocalDateTime) datelike; return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else if (datelike instanceof LocalDate) { LocalDate date = (LocalDate) datelike; return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else { throw new IllegalArgumentException("Illegal argument " + datelike + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate"); } }</code><technical_language>overloading avoiding Object</technical_language>

Target:
public static long dateToLong(Object datelike) { if (datelike instanceof Date) { Date date = (Date) datelike; return date.getTime(); } else if (datelike instanceof Calendar) { Calendar calendar = (Calendar) datelike; return calendar.getTimeInMillis(); } else if (datelike instanceof Instant) { Instant instant = (Instant) datelike; return instant.toEpochMilli(); } else if (datelike instanceof LocalDateTime) { LocalDateTime date = (LocalDateTime) datelike; return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else if (datelike instanceof LocalDate) { LocalDate date = (LocalDate) datelike; return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); } else { throw new IllegalArgumentException("Illegal argument " + datelike + ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate"); } }
Source:
<code>public void createSimpleSaml2AuthenticatedPrincipal() { <START> Map<String, Object> attributes = TestSamlResponseAttributes.getAttributes(); <END> SimpleSaml2AuthenticatedPrincipal principal = new SimpleSaml2AuthenticatedPrincipal("user", attributes); Assert.assertEquals("user", principal.getName()); Assert.assertTrue("attributes", attributes.equals(principal.getAttributes())); }</code><technical_language>I necessary for full-blown attribute statement prove constructor works</technical_language>

Target:
public void createSimpleSaml2AuthenticatedPrincipal() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); SimpleSaml2AuthenticatedPrincipal principal = new SimpleSaml2AuthenticatedPrincipal("user", attributes); assertThat(principal.getName()).isEqualTo("user"); assertThat(principal.getAttributes()).isEqualTo(attributes); }
Source:
<code>private boolean areAllReferencingExprsCoveredByIndex(IndexDescriptor id) throws StandardException { if (referencingExpressions == null || referencingExpressions.isEmpty()) { return false; } <START> return getRefExprIndexPositions(id).size() == referencingExpressions.size(); <END> }</code><technical_language>This check is simple cover combinations. For example: > create table t1 (a int, b int, primary key(a)); > create index t1_idx t1(a+1, b); > explain select count(*) t1 --splice-properties index=t1_idx > a+1 > 1 b+b > 1; > -> GroupBy(n=4,totalCost=38.017,outputRows=1,outputHeapSize=0 B,partitions=1) > -> ProjectRestrict(n=3,totalCost=30.413,outputRows=4,outputHeapSize=7 B,partitions=1) > -> ProjectRestrict(n=2,totalCost=30.413,outputRows=4,outputHeapSize=7 B,partitions=1,preds=[((B[1:2] + B[1:2]) > 1)]) > -> IndexLookup(n=1,totalCost=30.413,outputRows=7,outputHeapSize=7 B,partitions=1) > -> IndexScan[T1_IDX(7249)](n=0,totalCost=4.013,scannedRows=7,outputRows=7,outputHeapSize=7 B,partitions=1,baseTable=T1(7232),preds=[((A[1:1] + 1) > 1)]) > column B is in index, expensive IndexLookup operation is done in order evaluate b+b > 1. expression-based indexes, reference b+b IndexLookup. handle this, marking rc.isReferenced for column A in this case, detecting column references of a column occur matched index expressions. do IndexLookup is expensive want avoid if possible. want resolve this merging. If not, open a Jira for it</technical_language>

Target:
private boolean areAllReferencingExprsCoveredByIndex(IndexDescriptor id) throws StandardException { if (referencingExpressions == null || referencingExpressions.isEmpty()) { return true; } return getRefExprIndexPositions(id).size() == referencingExpressions.size(); }
Source:
<code>protected void tearDown() throws Exception { target = null; commandStack = null; session.close(new NullProgressMonitor()); <START> session = null; <END> super.tearDown(); }</code><technical_language>add "domain = null;" avoid problem super.tearDown()</technical_language>

Target:
protected void tearDown() throws Exception { domain = null; target = null; commandStack = null; session.close(new NullProgressMonitor()); session = null; super.tearDown(); }
Source:
<code>public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource)) { <START> if (!adminService.hasAllDataAccess(AuthorizationService.Operation.READ)) { <END> throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }</code><technical_language>is normal in Java, curious, IF instead of AND</technical_language>

Target:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource) && !adminService.hasAllDataAccess(AuthorizationService.Operation.READ)) { throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }
Source:
<code>private void processSoftwareRequirement(ArtifactReadable softwareRequirement, String criticality) throws IOException { writer.writeCell(softwareRequirement.getName(), SafetyReportGenerator.SOFTWARE_REQUIREMENT_INDEX); String softwareRequirementDAL = writeCriticalityWithDesignCheck(softwareRequirement, criticality, CoreRelationTypes.Requirement_Trace__Higher_Level, CoreAttributeTypes.DevelopmentAssuranceLevel); writer.writeCell(calculateBoeingEquivalentSWQualLevel(softwareRequirementDAL, softwareRequirement.getAttributeCount(CoreAttributeTypes.Partition))); writer.writeCell(functionalCategory); writer.writeCell(Collections.toString(",", getAttributesToStringList(softwareRequirement, CoreAttributeTypes.Partition))); writer.writeCell(safetyReport.getComponentUtil().getQualifiedComponentNames(softwareRequirement)); <START> Collection<String> codeUnits = safetyReport.getRequirementToCodeUnitsValues(softwareRequirement); <END> if (codeUnits == null || codeUnits.isEmpty()) { writer.endRow(); } else { for (String codeUnit : codeUnits) { writer.writeCell(codeUnit, SafetyReportGenerator.CODE_UNIT_INDEX); writer.endRow(); } } }</code><technical_language>!Conditions.hasValues(codeUnits)</technical_language>

Target:
private void processSoftwareRequirement(ArtifactReadable softwareRequirement, String criticality) throws IOException { writer.writeCell(softwareRequirement.getName(), SafetyReportGenerator.SOFTWARE_REQUIREMENT_INDEX); String softwareRequirementDAL = writeCriticalityWithDesignCheck(softwareRequirement, criticality, CoreRelationTypes.Requirement_Trace__Higher_Level, CoreAttributeTypes.DevelopmentAssuranceLevel); writer.writeCell(calculateBoeingEquivalentSWQualLevel(softwareRequirementDAL, softwareRequirement.getAttributeCount(CoreAttributeTypes.Partition))); writer.writeCell(functionalCategory); writer.writeCell(Collections.toString(",", getAttributesToStringList(softwareRequirement, CoreAttributeTypes.Partition))); writer.writeCell(safetyReport.getComponentUtil().getQualifiedComponentNames(softwareRequirement)); Collection<String> codeUnits = safetyReport.getRequirementToCodeUnitsValues(softwareRequirement); if (Conditions.hasValues(codeUnits)) { for (String codeUnit : codeUnits) { writer.writeCell(codeUnit, SafetyReportGenerator.CODE_UNIT_INDEX); writer.endRow(); } } else { writer.endRow(); } }
Source:
<code>public static <T> TraversalControl changeNode(TraverserContext<T> context, T changedNode) { NodeZipper<T> zipperWithChangedNode = context.getVar(NodeZipper.class).withNewNode(changedNode); boolean changed = context.isChanged(); if (context.isParallel()) { Queue<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { <START> throw new RuntimeException("multiple changes per node not supported for parallel"); <END> } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } else { List<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNode(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } }</code><technical_language>consistency of error message multiple changes node is supported for parallel traversing</technical_language>

Target:
public static <T> TraversalControl changeNode(TraverserContext<T> context, T changedNode) { NodeZipper<T> zipperWithChangedNode = context.getVar(NodeZipper.class).withNewNode(changedNode); boolean changed = context.isChanged(); if (context.isParallel()) { Queue<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNodeParallel(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } else { List<NodeZipper<T>> zippers = context.getSharedContextData(); if (changed) { replaceZipperForNode(zippers, context.thisNode(), changedNode); context.changeNode(changedNode); } else { zippers.add(zipperWithChangedNode); context.changeNode(changedNode); } return TraversalControl.CONTINUE; } }
Source:
<code>void threadSafeStringParametersTest() throws Exception { String[] iatas = { "JFK", "IAD", "SFO", "SJC", "SEA", "LAX", "PHX" }; Future[] future = new Future[iatas.length]; ExecutorService executorService = Executors.newFixedThreadPool(iatas.length); try { for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i].toLowerCase() ); airportRepository.save(airport); <START> } <END> try { Thread.sleep(1000); } catch (InterruptedException ie) { ; } for (int k = 0; k < 100; k++) { Callable<Boolean>[] suppliers = new Callable[iatas.length]; for (int i = 0; i < iatas.length; i++) { final int idx = i; suppliers[i] = () -> { try { Thread.sleep(iatas.length - idx); } catch (InterruptedException ie) { ; } String foundName = airportRepository.getAllByIata(iatas[idx]).get(0).getIata(); assertEquals(iatas[idx], foundName); return iatas[idx].equals(foundName); }; } for (int i = 0; i < iatas.length; i++) { future[i] = executorService.submit(suppliers[i]); } for (int i = 0; i < iatas.length; i++) { future[i].get(); } } } finally { executorService.shutdown(); for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i] ); airportRepository.delete(airport); } } }</code><technical_language>toLowerCase(Locale.ROOT) avoid dependency default locale</technical_language>

Target:
void threadSafeStringParametersTest() throws Exception { String[] iatas = { "JFK", "IAD", "SFO", "SJC", "SEA", "LAX", "PHX" }; Future[] future = new Future[iatas.length]; ExecutorService executorService = Executors.newFixedThreadPool(iatas.length); try { for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i].toLowerCase() ); airportRepository.save(airport); } sleep(1000); for (int k = 0; k < 100; k++) { Callable<Boolean>[] suppliers = new Callable[iatas.length]; for (int i = 0; i < iatas.length; i++) { final int idx = i; suppliers[i] = () -> { sleep(iatas.length - idx); String foundName = airportRepository.getAllByIata(iatas[idx]).get(0).getIata(); assertEquals(iatas[idx], foundName); return iatas[idx].equals(foundName); }; } for (int i = 0; i < iatas.length; i++) { future[i] = executorService.submit(suppliers[i]); } for (int i = 0; i < iatas.length; i++) { future[i].get(); } } } finally { executorService.shutdown(); for (int i = 0; i < iatas.length; i++) { Airport airport = new Airport("airports::" + iatas[i], iatas[i] , iatas[i] ); airportRepository.delete(airport); } } }
Source:
<code>public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { exception.expect(IllegalArgumentException.class); <START> exception.expectMessage("The defaultValue argument cannot be null"); <END> adminService.getGlobalPropertyValue("valid.double", null); }</code><technical_language>in this test I suggest junit rule. getGlobalPropertyValue throws IllegalArgumentException in case, clear case testing do bind test exception message. remove junit rule code replace java @Test(expected = IllegalArgumentException.class)</technical_language>

Target:
public void getGlobalPropertyValue_shouldFailIfDefaultValueIsNull() { adminService.getGlobalPropertyValue("valid.double", null); }
Source:
<code>private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { LOG.debug("object name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); <START> if (ds3Request.getRequiredQueryParams() == null) { <END> return requiredArgsBuilder.build(); } for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) break; LOG.debug("query param " + ds3Param.getType()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } return requiredArgsBuilder.build(); }</code><technical_language>This Guard class check for null empty</technical_language>

Target:
private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { LOG.debug("object name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); if (ConverterUtil.isEmpty(ds3Request.getRequiredQueryParams())) { return requiredArgsBuilder.build(); } for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) break; LOG.debug("query param " + ds3Param.getType()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } return requiredArgsBuilder.build(); }
Source:
<code>public int hashCode() { int result = delegate != null ? delegate.hashCode() : 0; result = 31 * result + typeParameter.hashCode(); <START> result = 31 * result + typeForValidatorResolution.hashCode(); <END> return result; }</code><technical_language>Do need typeForValidatorResolution in here? delegate type parameter suffice for determining identity</technical_language>

Target:
public int hashCode() { return hashCode; }
Source:
<code>public ClientConnection connect() throws TechnicalException { if (this.device == null) { throw new IllegalStateException("Can not connect because no device is set."); } this.checkIpAddress(); try { final ClientConnection connection = this.createConnection(); this.discardInvalidKeys(); return connection; } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + this.device.getIpAddress()); } catch (final IOException e) { if (this.device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(this.device.getDeviceIdentification(), this.device.getIpAddress()); } throw new ConnectionException(e); } catch (final RsaEncrypterException e) { <START> LOGGER.error("RSA decryption on security keys went wrong for device with ip: {}", <END> this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "RSA decryption on security keys went wrong for device with ip: " + this.device.getIpAddress()); } }</code><technical_language>log a message IP a reference? IP is dynamic, reading log match a device anymore. DlmsDevice object is available, log device.getDeviceIdentification() a reference</technical_language>

Target:
public ClientConnection connect() throws TechnicalException { if (this.device == null) { throw new IllegalStateException("Can not connect because no device is set."); } this.checkIpAddress(); try { final ClientConnection connection = this.createConnection(); this.discardInvalidKeys(); return connection; } catch (final UnknownHostException e) { LOGGER.warn("The IP address is not found: {}", this.device.getIpAddress(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "The IP address is not found: " + this.device.getIpAddress()); } catch (final IOException e) { if (this.device.hasNewSecurityKey()) { this.recoverKeyProcessInitiator.initiate(this.device.getDeviceIdentification(), this.device.getIpAddress()); } throw new ConnectionException(e); } catch (final RsaEncrypterException e) { LOGGER.error("RSA decryption on security keys went wrong for device: {}", this.device.getDeviceIdentification(), e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "RSA decryption on security keys went wrong for device: " + this.device.getDeviceIdentification()); } }
Source:
<code>protected void configure() { if (clusterPassword.length() < REQUIRED_DEFAULT_PASSWORD_LENGTH) { logger().warn("The provided cluster admin password length is less then the default password policy length. " + <START> "Cluster start will fail if configured password policy is offended."); <END> } }</code><technical_language>a native speaker, offended a term password policies. this be: suggestion "Cluster start fail if configured password requirements met.");</technical_language>

Target:
protected void configure() { if (clusterPassword.length() < REQUIRED_DEFAULT_PASSWORD_LENGTH) { logger().warn("The provided cluster admin password length is less then the default password policy length. " + "Cluster start will fail if configured password requirements are not met."); } }
Source:
<code><START> public void setVmtGuid(Guid value) { <END> vmtGuid = value; }</code><technical_language>a nice change, unrelated this patch in a separate one</technical_language>

Target:
public void setVmtGuid(Guid value) { this.vmtGuid = value; }
Source:
<code>PluginWrapper createPluginWrapper(File archive) throws IOException; @Nonnull String getShortName(File archive) throws IOException; void load(PluginWrapper wrapper) throws IOException; void initializeComponents(PluginWrapper plugin); <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson); <START> default void updateDependency(PluginWrapper depender, PluginWrapper dependee) <END></code><technical_language>Logging retained, expect implementation do . great a kind of @ShouldImplement annotation auto-checkers build</technical_language>

Target:
PluginWrapper createPluginWrapper(File archive) throws IOException; @Nonnull String getShortName(File archive) throws IOException; void load(PluginWrapper wrapper) throws IOException; void initializeComponents(PluginWrapper plugin); <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson); default void updateDependency(PluginWrapper depender, PluginWrapper dependee) { Logger.getLogger(PluginStrategy.class.getName()).log(Level.WARNING, "{0} does not yet implement updateDependency", getClass()); }
Source:
<code>public Map<String, MapSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } return cache.getNativeCache().values().stream() .map(cacheValue -> (MapSession) cacheValue) .filter(session -> indexValue.equals(principalNameResolver.resolvePrincipal(session))) <START> .collect(Collectors.toMap(session -> session.getId(), session -> session)); <END> }</code><technical_language>Slightly condensed version .collect(Collectors.toMap(MapSession::getId, Function.identity()));</technical_language>

Target:
public Map<String, MapSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } return cache.getNativeCache().values().stream() .map(cacheValue -> (MapSession) cacheValue) .filter(session -> indexValue.equals(principalNameResolver.resolvePrincipal(session))) .collect(Collectors.toMap(MapSession::getId, Function.identity())); }
Source:
<code>public Map<String, List<WriteRequest>> toWriteRequestItems(final List<DeviceData> deviceDataList) { final Map<String, Map<String, WriteRequest>> writeRequestMap = Maps.newHashMap(); for (final DeviceData data: deviceDataList) { final String tableName = getTableName(data.dateTimeUTC); final Map<String, AttributeValue> item = deviceDataToAttributeMap(data); final String hashAndRangeKey = item.get(Attribute.ACCOUNT_ID.name).getN() + item.get(Attribute.RANGE_KEY.name).getS(); final WriteRequest request = new WriteRequest().withPutRequest(new PutRequest().withItem(item)); <START> if (writeRequestMap.containsKey(tableName)) { <END> writeRequestMap.get(tableName).put(hashAndRangeKey, request); } else { final Map<String, WriteRequest> newMap = Maps.newHashMap(); newMap.put(hashAndRangeKey, request); writeRequestMap.put(tableName, newMap); } } Map<String, List<WriteRequest>> requestItems = Maps.newHashMapWithExpectedSize(writeRequestMap.size()); for (final Map.Entry<String, Map<String, WriteRequest>> entry : writeRequestMap.entrySet()) { requestItems.put(entry.getKey(), Lists.newArrayList(entry.getValue().values())); } return requestItems; }</code><technical_language>Is check for duplicates reaching this part of code</technical_language>

Target:
public Map<String, List<WriteRequest>> toWriteRequestItems(final List<DeviceData> deviceDataList) { final Map<String, Map<String, WriteRequest>> writeRequestMap = Maps.newHashMap(); for (final DeviceData data: deviceDataList) { final String tableName = getTableName(data.dateTimeUTC); final Map<String, AttributeValue> item = deviceDataToAttributeMap(data); final String hashAndRangeKey = item.get(Attribute.ACCOUNT_ID.name).getN() + item.get(Attribute.RANGE_KEY.name).getS(); final WriteRequest request = new WriteRequest().withPutRequest(new PutRequest().withItem(item)); if (writeRequestMap.containsKey(tableName)) { writeRequestMap.get(tableName).put(hashAndRangeKey, request); } else { final Map<String, WriteRequest> newMap = Maps.newHashMap(); newMap.put(hashAndRangeKey, request); writeRequestMap.put(tableName, newMap); } } final Map<String, List<WriteRequest>> requestItems = Maps.newHashMapWithExpectedSize(writeRequestMap.size()); for (final Map.Entry<String, Map<String, WriteRequest>> entry : writeRequestMap.entrySet()) { requestItems.put(entry.getKey(), Lists.newArrayList(entry.getValue().values())); } return requestItems; }
Source:
<code>protected void pingCorrectServer(Message clientMessage, DistributedMember targetServer, ServerConnection serverConnection) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Received a Ping request from intended for {}. Forwarding the ping..."); } if (!serverConnection.getCache().getDistributionManager().isCurrentMember(targetServer)) { logger.warn("Unable to ping non-member for client {}", targetServer, serverConnection.getProxyID()); writeErrorResponse(clientMessage, MessageType.PING, serverConnection); serverConnection.setAsTrue(RESPONDED); } else { final DistributedPingMessage distributedPingMessage = <START> new DistributedPingMessage(targetServer, serverConnection.getProxyID()); <END> serverConnection.getCache().getDistributionManager().putOutgoing(distributedPingMessage); writeReply(clientMessage, serverConnection); } }</code><technical_language>this need account version of member is pinged? pinging a member older version fail deserialize this message? assuming of receivers upgraded start pings need forwarded correct server</technical_language>

Target:
protected void pingCorrectServer(Message clientMessage, DistributedMember targetServer, ServerConnection serverConnection) throws IOException { if (logger.isDebugEnabled()) { logger.debug("Received a Ping request from intended for {}. Forwarding the ping...", serverConnection.getProxyID(), targetServer); } if (!serverConnection.getCache().getDistributionManager().isCurrentMember(targetServer)) { logger.warn("Unable to ping non-member for client {}", targetServer, serverConnection.getProxyID()); writeErrorResponse(clientMessage, MessageType.PING, serverConnection); serverConnection.setAsTrue(RESPONDED); } else { final DistributedPingMessage distributedPingMessage = new DistributedPingMessage(targetServer, serverConnection.getProxyID()); serverConnection.getCache().getDistributionManager().putOutgoing(distributedPingMessage); writeReply(clientMessage, serverConnection); } }
Source:
<code>public TrainingParameters getParameters(String namespace) { TrainingParameters params = new TrainingParameters(); Map<String, Object> settings = getObjectSettings(namespace); for (Entry<String, Object> entry: settings.entrySet()) { <START> final String key = entry.getKey(); <END> final Object value = entry.getValue();; if (value instanceof Integer) { params.put(key, (Integer)value); } else if (value instanceof Double) { params.put(key, (Double)value); } else if (value instanceof Boolean) { params.put(key, (Boolean)value); } else { params.put(key, (String)value); } } return params; }</code><technical_language>final</technical_language>

Target:
public TrainingParameters getParameters(String namespace) { TrainingParameters params = new TrainingParameters(); Map<String, Object> settings = getObjectSettings(namespace); for (Entry<String, Object> entry: settings.entrySet()) { String key = entry.getKey(); Object value = entry.getValue();; if (value instanceof Integer) { params.put(key, (Integer)value); } else if (value instanceof Double) { params.put(key, (Double)value); } else if (value instanceof Boolean) { params.put(key, (Boolean)value); } else { params.put(key, (String)value); } } return params; }
Source:
<code>public boolean isInSameLabelUpdateEventGroup(TurboIssueEvent e) { long timeDiffMs = Math.abs(getDate().getTime() - e.getDate().getTime()); <START> long timeDiffMin = TimeUnit.MILLISECONDS.toSeconds(timeDiffMs); <END> return getActor().getLogin().equals(e.getActor().getLogin()) && timeDiffMin <= MAX_TIME_DIFF; }</code><technical_language>toSeconds returns number of minutes</technical_language>

Target:
public boolean isInSameLabelUpdateEventGroup(TurboIssueEvent e) { long timeDiffMs = Math.abs(getDate().getTime() - e.getDate().getTime()); long timeDiffSec = TimeUnit.MILLISECONDS.toSeconds(timeDiffMs); return getActor().getLogin().equals(e.getActor().getLogin()) && timeDiffSec <= MAX_TIME_DIFF; }
Source:
<code>public Map<String, CustomizedView> getCustomizedView(String customizedStateType) { <START> return _customizedViewCaches.get(customizedStateType).getCustomizedViewMap(); <END> }</code><technical_language>Check null. caller pass unknown type</technical_language>

Target:
public Map<String, CustomizedView> getCustomizedView(String customizedStateType) { if (_customizedViewCaches.containsKey(customizedStateType)) { return _customizedViewCaches.get(customizedStateType).getCustomizedViewMap(); } throw new HelixException(String.format( "customizedStateType %s does not exist in customizedViewCaches.", customizedStateType)); }
Source:
<code>public static int calculateAggregateEnvironmentScore(int soundScore, int temperatureScore, int humidityScore) { return (Math.round(0.25f * temperatureScore) + Math.round(0.25f * humidityScore) + <START> Math.round(0.50f * soundScore)); <END> }</code><technical_language>@decarbonization: i this Math.round(0.25f * temperatureScore + 0.25f * humidityScore + 0.50f * soundScore) coz right Math.round(0.25f * 90) + Math.round(0.25f * 90) + Math.round(0.50f * 90) returns 91</technical_language>

Target:
public static int calculateAggregateEnvironmentScore(int soundScore, int temperatureScore, int humidityScore) { return Math.round((0.25f * temperatureScore) + (0.25f * humidityScore) + (0.50f * soundScore)); }
Source:
<code>public void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { try { if (0 < jdbc.update("DELETE FROM attributes_authz WHERE attr_id=?", attribute.getId())) { <START> log.debug("All attribute_authz were deleted for Attribute={}.", attribute); <END> } } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>log object change deleted for {}., attributes toString() is Attribute:[content]</technical_language>

Target:
public void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException { try { if (0 < jdbc.update("DELETE FROM attributes_authz WHERE attr_id=?", attribute.getId())) { log.debug("All attribute_authz were deleted for {}.", attribute); } } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>public void testOpenUrlInvalid() throws Exception { if (!PlatformUiUtil.hasInternalBrowser()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() due to lack of browser support"); return; } <START> if (System.getProperty("mylyn.gerrit.tests.skipBrowserTests") != null) { <END> System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() to avoid browser crash"); return; } TaskRepository repository = GerritFixture.GERRIT_NON_EXISTANT.singleRepository(); EditorHandle handler = BrowserUtil.openUrl(activePage, repository.getUrl() + "/abc", 0); assertNotNull("Expected a browser instance, got: " + handler.getClass(), handler.getAdapter(IWebBrowser.class)); assertEquals(Status.OK_STATUS, handler.getStatus()); }</code><technical_language>I generalize this in Mylyn Commons. other browser tests expose problem</technical_language>

Target:
public void testOpenUrlInvalid() throws Exception { if (!PlatformUiUtil.hasInternalBrowser()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() due to lack of browser support"); return; } if (CommonTestUtil.skipBrowserTests()) { System.err.println("Skipping GerritUrlHandlerTest.testOpenUrlInvalid() to avoid browser crash"); return; } TaskRepository repository = GerritFixture.GERRIT_NON_EXISTANT.singleRepository(); EditorHandle handler = BrowserUtil.openUrl(activePage, repository.getUrl() + "/abc", 0); assertNotNull("Expected a browser instance, got: " + handler.getClass(), handler.getAdapter(IWebBrowser.class)); assertEquals(Status.OK_STATUS, handler.getStatus()); }
Source:
<code><START> public EntityModel<Integer> getMacsCount() { <END> return macsCount; }</code><technical_language>reason change this EntityModel<Long> cast long int below</technical_language>

Target:
public EntityModel<Long> getMacsCount() { return macsCount; }
Source:
<code>private File saveToFile(Bitmap bitmap) throws IOException { <START> File root = null; <END> String fileName = "map-export-image" + System.currentTimeMillis() + ".png"; root = Environment.getExternalStorageDirectory(); File fileDir = new File(root.getAbsolutePath() + "/ArcGIS/"); fileDir.mkdirs(); File file = new File(fileDir, fileName); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); return file; }</code><technical_language>Initializing null is redundant, remove redundancy</technical_language>

Target:
private File saveToFile(Bitmap bitmap) throws IOException { File root; File file = null; String fileName = "map-export-image" + System.currentTimeMillis() + ".png"; root = Environment.getExternalStorageDirectory(); File fileDir = new File(root.getAbsolutePath() + "/ArcGIS Export/"); boolean isDirectoryCreated=fileDir.exists(); if (!isDirectoryCreated) { isDirectoryCreated= fileDir.mkdirs(); } if(isDirectoryCreated) { file = new File(fileDir, fileName); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } return file; }
Source:
<code>public void getEntitiesWithinAABBForEntity(Entity exclude, AxisAlignedBB queryBox, @Nonnull List<Entity> out, Predicate<? super Entity> predicate) { int minCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.minY - World.MAX_ENTITY_RADIUS)); int maxCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.maxY + World.MAX_ENTITY_RADIUS)); <START> for (int cubeY = minCubeY;cubeY < maxCubeY + 1;cubeY++) { <END> Cube cube = getCube(cubeY); cube.getEntitiesWithinAABBForEntity(exclude, queryBox, out, predicate); } }</code><technical_language><=</technical_language>

Target:
public void getEntitiesWithinAABBForEntity(Entity exclude, AxisAlignedBB queryBox, @Nonnull List<Entity> out, Predicate<? super Entity> predicate) { int minCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.minY - World.MAX_ENTITY_RADIUS)); int maxCubeY = Coords.blockToCube(MathHelper.floor_double(queryBox.maxY + World.MAX_ENTITY_RADIUS)); for (int cubeY = minCubeY;cubeY <= maxCubeY;cubeY++) { Cube cube = getCube(cubeY); cube.getEntitiesWithinAABBForEntity(exclude, queryBox, out, predicate); } }
Source:
<code>CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nullable final Timestamp timestamp, @Nonnull final K key) { try { txBegin(timestamp); <START> return ((Table<K, V, M>) getTable(tableName)).get(key); <END> } finally { txEnd(); } }</code><technical_language>NPE cold happen</technical_language>

Target:
CorfuRecord<V, M> getRecord(@Nonnull final String tableName, @Nullable final Timestamp timestamp, @Nonnull final K key) { if (tableName == null) { throw new IllegalArgumentException("Query::getRecord needs a valid tableName"); } try { txBegin(timestamp); Table<K, V, M> table = getTable(tableName); return table.get(key); } finally { txEnd(); } }
Source:
<code><START> public static <N extends Number> PropertyConstraint<N> inRange(final N minInclusive, final N maxInclusive) { <END> return ConstraintFactory.fromPredicate( new Predicate<N>() { @Override public boolean test(N t) { return minInclusive.intValue() <= t.intValue() && maxInclusive.intValue() >= t.intValue(); } }, "Should be between " + minInclusive + " and " + maxInclusive ); }</code><technical_language>I reading <LINK_0> <N extends Number & Comparable>? implement test return minInclusive.compareTo(t) <= 0 && maxInclusive.compareTo(t) >= 0;..</technical_language>

Target:
public static <N extends Number & Comparable<N>> PropertyConstraint<N> inRange(final N minInclusive, final N maxInclusive) { return ConstraintFactory.fromPredicate( new Predicate<N>() { @Override public boolean test(N t) { return minInclusive.compareTo(t) >= 0 && maxInclusive.compareTo(t) <= 0; } }, "Should be between " + minInclusive + " and " + maxInclusive ); }
Source:
<code>public void stop(int batchSize) { if (!isProfiling) { return; } verify(previousTimestamp != NOT_INITALIZED, "start() is not called"); verify(batchSize > 0, "batchSize must be positive"); long now = System.nanoTime(); long delta = NANOSECONDS.toMillis(now - previousTimestamp); <START> meanExecutionTime = (meanExecutionTime * samples + delta) / (samples + 1); <END> samples += batchSize; if (samples >= rowsToProfile) { isProfiling = false; if (meanExecutionTime < expensiveFunctionThresholdMillis) { isExpressionExpensive = false; } } previousTimestamp = NOT_INITALIZED; }</code><technical_language>I is reason a running mean, this is evaluated once. Instead, sum of time rows</technical_language>

Target:
public void stop(int batchSize) { verify(previousTimestamp != NOT_INITALIZED, "start() is not called"); verify(batchSize > 0, "batchSize must be positive"); long now = ticker.read(); long delta = now - previousTimestamp; totalExecutionTimeNanos += delta; samples += batchSize; if ((totalExecutionTimeNanos / samples) < expensiveExpressionThresholdNanos) { isExpressionExpensive = false; } previousTimestamp = NOT_INITALIZED; }
Source:
<code>public void testOpenMRSProviderDataSourceAndCreateEncounterAction() throws InterruptedException, IOException, ParseException, ConceptNameAlreadyInUseException { Long taskID = createProviderTestTask(); activateTrigger(); waitForTaskExecution(taskID); <START> deleteTask(taskID); <END> checkIfProviderWasCreatedProperly(); }</code><technical_language>remove</technical_language>

Target:
public void testOpenMRSProviderDataSourceAndCreateEncounterAction() throws InterruptedException, IOException, ParseException, ConceptNameAlreadyInUseException { Long taskID = createProviderTestTask(); activateTrigger(); assertTrue(waitForTaskExecution(taskID)); checkIfProviderWasCreatedProperly(); }
Source:
<code>public static ImmutableList<Struct> getStructsOrderedList(final Ds3ApiSpec spec) throws ParseException { final ImmutableList.Builder<Struct> orderedStructsBuilder = ImmutableList.builder(); <START> final Queue<Struct> allStructs = new LinkedList(getAllStructs(spec).asList()); <END> final ImmutableSet.Builder<String> existingTypesBuilder = ImmutableSet.builder(); int skippedStructsCount = 0; while (!allStructs.isEmpty()) { final int allStructsSize = allStructs.size(); final Struct structEntry = allStructs.peek(); if (orderedStructsBuilder.build().contains(structEntry)) { continue; } if (StructHelper.isPrimitive(structEntry) || StructHelper.containsExistingStructs(structEntry, existingTypesBuilder.build())) { existingTypesBuilder.add(StructHelper.getResponseTypeName(structEntry.getName())); orderedStructsBuilder.add(allStructs.remove()); } else { allStructs.add(allStructs.remove()); } if (allStructsSize == allStructs.size()) { skippedStructsCount++; if (skippedStructsCount == allStructsSize) { LOG.warn("Unable to progress on remaining structs, aborting!"); LOG.warn(" Remaining structs[" + allStructs.size() + "]"); for (final Struct struct : allStructs) { LOG.warn(" " + struct.getName()); } break; } } } return orderedStructsBuilder.build(); }</code><technical_language>do call asList() here? I know, ImmutableList implements List interface</technical_language>

Target:
public static ImmutableList<Struct> getStructsOrderedList(final Ds3ApiSpec spec) throws ParseException { final ImmutableList.Builder<Struct> orderedStructsBuilder = ImmutableList.builder(); final Queue<Struct> allStructs = new LinkedList(getAllStructs(spec)); final Set<String> existingTypes = new HashSet<>(); int skippedStructsCount = 0; while (!allStructs.isEmpty()) { final int allStructsSize = allStructs.size(); final Struct structEntry = allStructs.remove(); if (existingTypes.contains(structEntry)) { LOG.warn("Skipping structEntry " + structEntry.getName()); continue; } if (StructHelper.isPrimitive(structEntry) || containsExistingStructs(structEntry, existingTypes)) { existingTypes.add(StructHelper.getResponseTypeName(structEntry.getName())); orderedStructsBuilder.add(structEntry); } else { allStructs.add(structEntry); } if (allStructsSize == allStructs.size()) { skippedStructsCount++; if (skippedStructsCount == allStructsSize) { LOG.warn("Unable to progress on remaining structs, aborting!"); LOG.warn(" Remaining structs[" + allStructs.size() + "]"); for (final Struct struct : allStructs) { LOG.warn(" " + struct.getName()); } break; } } } return orderedStructsBuilder.build(); }
Source:
<code>public void init() { super.init(); <START> _setupUI(); <END> }</code><technical_language>noted above, put init code in init() is a reason to</technical_language>

Target:
public void init() { super.init(); removeAllComponents(); _msgCon = new MessageContainer(TimeUnit.SECONDS.toMillis(60)); _msgCon.clearMessages(); QLBuilder facultyQB=_facultyMemberDao.getAllFacultyQB(); int size = facultyQB.getQueryResolver().list().size(); if(size<=0) { _msgCon.sendNotification(new Message(NotificationType.ERROR,getLocaleContext().getLocalizedText(FacultyMemberListUILOK .ERROR_INFO()))); return; } final Label title = new Label(FacultyMemberListUILOK.TITLE()); title.setHTMLElement(HTMLElement.h1); Container imageCon=new Container(); add(Container.of("prop-mainCon", Container.of("top", title),imageCon)); List<FacultyMemberProfile> facultyMembers=facultyQB.getQueryResolver().list(); for(FacultyMemberProfile facultyMember:facultyMembers) { final PushButton nameLink = new PushButton(); nameLink.setLabel(new LocalizedText(facultyMember.getSlug())); nameLink.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { String slug = nameLink.getLabel().getText(getLocaleContext()).toString(); _slug = _facultyMemberDao.getFacultyMemberProfile(slug).getSlug(); Response response = Event.getResponse(); response.redirect(response.createURL(_contentBuilder.getDetailInfoPage()).addParameter("slug", _slug)); } }); if(facultyMember.getPicture()!=null) { Image image= null; try { image = new Image(ImageResource.getResource(facultyMember.getPicture(), 80, 90)); } catch (IOException e) { _logger.error("Something is wrong when get the picture!", e); } ImageComponent imageCom=new ImageComponent(image); imageCon.add(Container.of("prop-image", Container.of("prop-imageCom",imageCom), Container.of("prop-name",nameLink))); } else { imageCon.add(Container.of("prop-image", Container.of("prop-nameLink", nameLink))); } } }
Source:
<code>public Update(Map<String, Object> properties, MetricUnit unit) { super(properties); <START> this.unit = unit == null ? MetricUnit.NONE : unit; <END> }</code><technical_language>This prevent update object update properties. line 72 of valueOrDefault() method. While metric type unit is currently "attribute" behaving way, resource type version behave in past, too, I that. If a of some attribute is in update object, original entity used. Actually, I "properties" behave way, too. is a bug, handled separately</technical_language>

Target:
public Update(Map<String, Object> properties, MetricUnit unit) { super(properties); this.unit = unit; }
Source:
<code>@Override protected void setUp() throws Exception { <START> Assert.assertSame("abc", <END> "abc"); Assert.assertSame(tmpStr1.intern(), new String(tmpStr1).intern()); Assert.assertSame(long1 + long1, long1 + long1); }</code><technical_language>Suggestion: expand code is this: // check assumptions compiler, // new String(String), String.intern() work. failures // invalidate benchmarks. Assert.assertNotSame("abc", new String("abc")); // new String(String) creates a copy Assert.assertSame("abc", "abc"); // constants object Assert.assertSame("abc", "abc".intern()); // interned strings treated constants Assert.assertSame("abc", new String("abc").intern()); // // interned strings treated constants Assert.assertSame(long1 + long1, long1 + long1); // compiler fold constant strings new constants axioms need add interned cases (from told) treated identically constants</technical_language>

Target:
@Override protected void setUp() throws Exception { Assert.assertSame("abc", "abc"); Assert.assertNotSame("abc" , new String("abc")); Assert.assertSame("abc", "abc".intern()); Assert.assertSame("abc", new String("abc").intern()); Assert.assertSame(long1 + long1, long1 + long1); }