auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) { try (CloseableTrace trace = startLocalTrace("get({}, cells)", <START> LoggingArgs.tableRefValue(tableRef), timestampByCell.size())) { <END> return delegate().get(tableRef, timestampByCell); } }</code><technical_language>below, need LoggingArgs.tableRefValue code path is allocation free if tracing is enabled. If tracing is enabled, message formatter call toString() args, lazily computed</technical_language>

Target:
public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) { try (CloseableTrace trace = startLocalTrace("get({}, cells)", LoggingArgs.safeTableOrPlaceholder(tableRef), timestampByCell.size())) { return delegate().get(tableRef, timestampByCell); } }
Source:
<code>private List<CourseEditSectionRow> createSectionRows(int instructorIndex, List<String> sectionNames, List<String> feedbackNames) { firstBlankSectionRowIndex = sectionNames.size(); List<CourseEditSectionRow> rows = new ArrayList<CourseEditSectionRow>(); Map<Integer, String> specialSectionNames = new TreeMap<Integer, String>(); Map<Integer, String> nonSpecialSectionNames = new TreeMap<Integer, String>(); int sectionIndex = -1; for (String sectionName : sectionNames) { sectionIndex++; if (isSectionSpecial(sectionName)) { specialSectionNames.put(sectionIndex, sectionName); } else { nonSpecialSectionNames.put(sectionIndex, sectionName); } } int panelIndex = -1; for (Map.Entry<Integer, String> sectionNameEntry : specialSectionNames.entrySet()) { panelIndex++; sectionIndex = sectionNameEntry.getKey(); String sectionName = sectionNameEntry.getValue(); CourseEditSectionRow sectionRow = new CourseEditSectionRow(sectionName, sectionNames, sectionIndex, panelIndex, instructor, instructorIndex, feedbackNames); rows.add(sectionRow); } for (Map.Entry<Integer, String> sectionNameEntry : nonSpecialSectionNames.entrySet()) { panelIndex++; if (firstBlankSectionRowIndex == sectionNames.size()) { firstBlankSectionRowIndex = panelIndex; } sectionIndex = sectionNameEntry.getKey(); String sectionName = sectionNameEntry.getValue(); CourseEditSectionRow sectionRow = new CourseEditSectionRow(sectionName, sectionNames, sectionIndex, panelIndex, instructor, instructorIndex, feedbackNames); rows.add(sectionRow); } return rows; <START> } <END></code><technical_language>This method is 50 lines long loops. possibility of shortening SLAP</technical_language>

Target:
private List<CourseEditSectionRow> createSectionRows( int instructorIndex, List<String> sectionNames, List<String> feedbackNames) { firstBlankSectionRowIndex = sectionNames.size(); Map<Integer, String> specialSectionNames = new TreeMap<Integer, String>(); Map<Integer, String> nonSpecialSectionNames = new TreeMap<Integer, String>(); distinguishSpecialAndNonSpecialSections(sectionNames, specialSectionNames, nonSpecialSectionNames); List<CourseEditSectionRow> rows = createSpecialAndNonSpecialSectionRowsInOrder(instructorIndex, sectionNames, feedbackNames, specialSectionNames, nonSpecialSectionNames); return rows; }
Source:
<code>public static <K,V> ConflictManager<K,V> get(AdvancedCache<K, V> cache) { AuthorizationManager authzManager = cache.getAuthorizationManager(); if (authzManager != null) { authzManager.checkPermission(AuthorizationPermission.ALL_READ); authzManager.checkPermission(AuthorizationPermission.ALL_WRITE); } <START> return Objects.requireNonNull(cache, "Cache cannot be null") <END> .getAdvancedCache() .getComponentRegistry() .getComponent(ConflictManager.class); }</code><technical_language>invoking cache.getAuthorizationManager() before. I Objects.requireNonNull() is needed :)</technical_language>

Target:
public static <K,V> ConflictManager<K,V> get(AdvancedCache<K, V> cache) { AuthorizationManager authzManager = cache.getAuthorizationManager(); if (authzManager != null) { authzManager.checkPermission(AuthorizationPermission.ALL_READ); authzManager.checkPermission(AuthorizationPermission.ALL_WRITE); } return cache .getComponentRegistry() .getComponent(InternalConflictManager.class); }
Source:
<code>public void testRequiredSerializedNameNonNull() { SerializedNameModel expected = new SerializedNameModel(); expected.bar = "hello world"; <START> SerializedNameModel result = unmarshal(SerializedNameModel.class, "{ \"foo\": \"hello world\" }"); <END> assertThat(result, is(expected)); }</code><technical_language>I this marshal(expected)</technical_language>

Target:
public void testRequiredSerializedNameNonNull() { SerializedNameModel expected = new SerializedNameModel(); expected.bar = "hello world"; SerializedNameModel result = unmarshal(gson, SerializedNameModel.class, marshal(gson, expected)); assertThat(result, is(expected)); }
Source:
<code>public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); final Session session = createSession(hc, user, host, port, fs); if (pass != null) session.setPassword(pass); final String strictHostKeyCheckingPolicy = hc .getStrictHostKeyChecking(); if (strictHostKeyCheckingPolicy != null) session.setConfig("StrictHostKeyChecking", strictHostKeyCheckingPolicy); final String pauth = hc.getPreferredAuthentications(); if (pauth != null) session.setConfig("PreferredAuthentications", pauth); if (credentialsProvider != null && (!hc.isBatchMode() || !credentialsProvider <START> .isInteractive())) { <END> session.setUserInfo(new CredentialsProviderUserInfo(session, credentialsProvider)); } configure(hc, session); if (!session.isConnected()) session.connect(tms); return new JschSession(session, uri); } catch (final JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }</code><technical_language>Style-nit: try pulling this prior line block more closely matches version</technical_language>

Target:
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); final Session session = createSession(hc, user, host, port, fs); if (pass != null) session.setPassword(pass); final String strictHostKeyCheckingPolicy = hc .getStrictHostKeyChecking(); if (strictHostKeyCheckingPolicy != null) session.setConfig("StrictHostKeyChecking", strictHostKeyCheckingPolicy); final String pauth = hc.getPreferredAuthentications(); if (pauth != null) session.setConfig("PreferredAuthentications", pauth); if (credentialsProvider != null && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) { session.setUserInfo(new CredentialsProviderUserInfo(session, credentialsProvider)); } configure(hc, session); if (!session.isConnected()) session.connect(tms); return new JschSession(session, uri); } catch (JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }
Source:
<code>public void returnProgramStateWhenObjectIsDefined() throws Exception { state = state.pushToStack(new SymbolicValueWithConstraint(Constraint.ANY_VALUE)); <START> assertThat(dotMemberPoint.execute(state).isPresent()).isTrue(); <END> state = state.pushToStack(new SymbolicValueWithConstraint(Constraint.ANY_VALUE)).pushToStack(new SymbolicValueWithConstraint(Constraint.ZERO)); assertThat(bracketMemberPoint.execute(state).isPresent()).isTrue(); }</code><technical_language>@inverno assert state well, constraint is NOT_NULLY</technical_language>

Target:
public void returnProgramStateWhenObjectIsDefined() throws Exception { state = state.pushToStack(ANY_VALUE); Optional<ProgramState> stateAfterDot = dotMemberPoint.execute(state); assertThat(dotMemberPoint.execute(state).isPresent()).isTrue(); stateAfterDot.ifPresent(s -> assertThat(s.getConstraint(s.peekStack()).isStricterOrEqualTo(Constraint.NOT_NULLY)).isTrue()); state = state.pushToStack(ANY_VALUE).pushToStack(ZERO); Optional<ProgramState> stateAfterBracket = bracketMemberPoint.execute(state); assertThat(stateAfterBracket.isPresent()).isTrue(); stateAfterBracket.ifPresent(s -> assertThat(s.getConstraint(s.peekStack()).isStricterOrEqualTo(Constraint.NOT_NULLY)).isTrue()); }
Source:
<code>public void testAddExistingContainer() throws Exception { Run run = (Run) getSession().get(Run.class, 5002L); assertTrue(run.getSequencerPartitionContainers().isEmpty()); RunPage page = RunPage.getForEdit(getDriver(), getBaseUrl(), 5002L); RunPage page2 = page.addContainer("EXISTING", "Illumina", false); <START> assertNotNull(page2); <END> Run addedRun = (Run) getSession().get(Run.class, 5002L); assertEquals(1, addedRun.getSequencerPartitionContainers().size()); assertEquals("EXISTING", addedRun.getSequencerPartitionContainers().get(0).getIdentificationBarcode()); }</code><technical_language>checking container shows in UI. for removing container adding/removing/changing pool</technical_language>

Target:
public void testAddExistingContainer() throws Exception { Run run = (Run) getSession().get(Run.class, 5002L); assertTrue(run.getSequencerPartitionContainers().isEmpty()); RunPage page = RunPage.getForEdit(getDriver(), getBaseUrl(), 5002L); RunPage page2 = page.addContainer("EXISTING", "Illumina", false); assertTrue(page2.getTable("list_container").doesColumnContain(Columns.SERIAL_NUMBER, "EXISTING")); Run addedRun = (Run) getSession().get(Run.class, 5002L); assertEquals(1, addedRun.getSequencerPartitionContainers().size()); assertEquals("EXISTING", addedRun.getSequencerPartitionContainers().get(0).getIdentificationBarcode()); }
Source:
<code>public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class .cast(point.getSignature()) .getMethod(); final RetryOnFailure rof = method.getAnnotation(RetryOnFailure.class); int attempt = 0; final long begin = System.nanoTime(); while (true) { final long start = System.nanoTime(); try { return point.proceed(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw ex; } catch (Throwable ex) { ++attempt; if (rof.verbose()) { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d of %d failed in %[nano]s (%[nano]s waiting already) with %[exception]s", method.getName(), attempt, rof.attempts(), System.nanoTime() - start, System.nanoTime() - begin, ex ); } else { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d/%d failed with %[type]s in %[nano]s (%[nano]s in total): %s", method.getName(), attempt, rof.attempts(), ex, System.nanoTime() - start, System.nanoTime() - begin, Repeater.message(ex) ); } if (attempt >= rof.attempts()) { throw ex; } if (rof.delay() > 0) { <START> delay(rof, attempt); <END> } } } }</code><technical_language>this.delay()</technical_language>

Target:
public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class .cast(point.getSignature()) .getMethod(); final RetryOnFailure rof = method.getAnnotation(RetryOnFailure.class); int attempt = 0; final long begin = System.nanoTime(); while (true) { final long start = System.nanoTime(); try { return point.proceed(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw ex; } catch (Throwable ex) { ++attempt; if (rof.verbose()) { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d of %d failed in %[nano]s (%[nano]s waiting already) with %[exception]s", method.getName(), attempt, rof.attempts(), System.nanoTime() - start, System.nanoTime() - begin, ex ); } else { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d/%d failed with %[type]s in %[nano]s (%[nano]s in total): %s", method.getName(), attempt, rof.attempts(), ex, System.nanoTime() - start, System.nanoTime() - begin, Repeater.message(ex) ); } if (attempt >= rof.attempts()) { throw ex; } if (rof.delay() > 0) { this.delay(rof, attempt); } } } }
Source:
<code>private void convertOrg(File file, CisConversionResult result) throws Exception { try (FileInputStream inputStream = new FileInputStream(file)) { Workbook workbook = new Workbook(inputStream); LOGGER.debug("Aangetroffen locale: " + workbook.getSettings().getLocale() + " en region: " + workbook.getSettings().getRegion()); <START> workbook.getSettings().setLocale(Locale.GERMAN); <END> workbook.getSettings().setRegion(CountryCode.GERMANY); LOGGER.debug("Overschreven met locale: " + workbook.getSettings().getLocale() + " en region: " + workbook.getSettings().getRegion()); Style style = workbook.getDefaultStyle(); LOGGER.debug("Default font: " + style.getFont()); workbook.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.PDF); result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile())); } }</code><technical_language>is locale/region set GERMAN/GERMANY?</technical_language>

Target:
private void convertOrg(File file, CisConversionResult result) throws Exception { try (FileInputStream inputStream = new FileInputStream(file)) { Workbook workbook = new Workbook(inputStream); Style style = workbook.getDefaultStyle(); LOGGER.debug("Default font: " + style.getFont()); workbook.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.PDF); result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile())); } }
Source:
<code>public PagedList<models.ebean.Alert> createAlertQuery(final AlertQuery query) { ExpressionList<models.ebean.Alert> ebeanExpressionList = Ebean.find(models.ebean.Alert.class).where(); if (query.getCluster().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("cluster", query.getCluster().get()); } if (query.getContext().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("context", query.getContext().get().toString()); } if (query.getService().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("service", query.getService().get()); } <START> final Query<models.ebean.Alert> ebeanQuery = ebeanExpressionList.query(); <END> int pageOffset = 0; if (query.getOffset().isPresent()) { pageOffset = query.getOffset().get() / query.getLimit(); } return ebeanQuery.findPagedList(pageOffset, query.getLimit()); }</code><technical_language>existing AlertQuery query supports a "contains" clause. I support for here. prevent this out of hand (you'll need add a full text index query logic) please add issue in Github do work a fast-follow</technical_language>

Target:
public PagedList<models.ebean.Alert> createAlertQuery(final AlertQuery query) { ExpressionList<models.ebean.Alert> ebeanExpressionList = Ebean.find(models.ebean.Alert.class).where(); if (query.getCluster().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("cluster", query.getCluster().get()); } if (query.getContext().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("context", query.getContext().get().toString()); } if (query.getService().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("service", query.getService().get()); } if (query.getContains().isPresent()) { final Junction<models.ebean.Alert> junction = ebeanExpressionList.disjunction(); ebeanExpressionList = junction.contains("name", query.getContains().get()); if (!query.getCluster().isPresent()) { ebeanExpressionList = junction.contains("cluster", query.getContains().get()); } if (!query.getService().isPresent()) { ebeanExpressionList = junction.contains("service", query.getContains().get()); } ebeanExpressionList = junction.contains("metric", query.getContains().get()); ebeanExpressionList = junction.contains("statistic", query.getContains().get()); ebeanExpressionList = junction.contains("operator", query.getContains().get()); ebeanExpressionList = ebeanExpressionList.endJunction(); } final Query<models.ebean.Alert> ebeanQuery = ebeanExpressionList.query(); int pageOffset = 0; if (query.getOffset().isPresent()) { pageOffset = query.getOffset().get() / query.getLimit(); } return ebeanQuery.findPagedList(pageOffset, query.getLimit()); }
Source:
<code>public void add(E newInterval) { super.add(newInterval); <START> fListeners.stream().forEach(l -> l.elementAdded(this, newInterval)); <END> }</code><technical_language>do fListeners.forEach() Collections</technical_language>

Target:
public void add(E newInterval) { super.add(newInterval); }
Source:
<code>public PypiWheelArtifactCoordinates(String distribution, String version, String build, String languageImplementationVersion, String abi, String platform) { <START> if (distribution == "" || version == "" || languageImplementationVersion == "" || abi == "" || platform == "") <END> { throw new IllegalArgumentException("The distribution, version, language_implementation_version_tag, abi_tag, and platform_tag are mandatory fields."); } if (build != "" && !Character.isDigit(build.charAt(0))) { throw new IllegalArgumentException("Illegal build tag!"); } setId(distribution); setVersion(version); setBuild(build); setLanguageImplementationVersion(languageImplementationVersion); setAbi(abi); setPlatform(platform); }</code><technical_language>In Java, comparing objects done equals(). Checking == checks operands point object. a articles: * <LINK_2> * <LINK_0> * <LINK_1> checking if a string is blank, please StringUtils.isBlank()? please fix checks pull request? Thanks</technical_language>

Target:
public PypiWheelArtifactCoordinates(String distribution, String version, String build, String languageImplementationVersion, String abi, String platform) { if (StringUtils.isBlank(distribution) || StringUtils.isBlank(version) || StringUtils.isBlank(languageImplementationVersion) || StringUtils.isBlank(abi) || StringUtils.isBlank(platform)) { throw new IllegalArgumentException("The distribution, version, languageImplementationVersion, abi, and platform fields are mandatory."); } if (!StringUtils.isBlank(build) && !Character.isDigit(build.charAt(0))) { throw new IllegalArgumentException("Illegal build tag!"); } setId(distribution); setVersion(version); setBuild(build); setLanguageImplementationVersion(languageImplementationVersion); setAbi(abi); setPlatform(platform); }
Source:
<code>private Sequence<T> deserializeResults( final byte[] cachedResult, CacheStrategy strategy, String resultSetId ) { <START> if (cachedResult == null) { <END> return null; } final Function<Object, T> pullFromCacheFunction = strategy.pullFromResultLevelCache(); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); byte[] prunedCacheData = Arrays.copyOfRange( cachedResult, Integer.BYTES + resultSetId.length(), cachedResult.length ); Sequence<T> cachedSequence = Sequences.simple(() -> { try { if (cachedResult.length == 0) { return Iterators.emptyIterator(); } return objectMapper.readValues( objectMapper.getFactory().createParser(prunedCacheData), cacheObjectClazz ); } catch (IOException e) { throw new RuntimeException(e); } }); return Sequences.map(cachedSequence, pullFromCacheFunction); }</code><technical_language>in private methods , this null a coding error throw exception instead Preconditions.checkNotNull(..) etc</technical_language>

Target:
private Sequence<T> deserializeResults( final byte[] cachedResult, CacheStrategy strategy, String resultSetId ) { if (cachedResult == null) { log.error("Cached result set is null"); } final Function<Object, T> pullFromCacheFunction = strategy.pullFromCache(true); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); Sequence<T> cachedSequence = Sequences.simple(() -> { try { int resultOffset = Integer.BYTES + resultSetId.length(); return objectMapper.readValues( objectMapper.getFactory().createParser( cachedResult, resultOffset, cachedResult.length - resultOffset ), cacheObjectClazz ); } catch (IOException e) { throw new RE(e, "Failed to retrieve results from cache for query ID [%s]", query.getId()); } }); return Sequences.map(cachedSequence, pullFromCacheFunction); }
Source:
<code>public void networkNameTakenBySameNetwork() throws Exception { Network otherNetwork = new Network(); otherNetwork.setName(DEFAULT_NETWORK_NAME); <START> otherNetwork.setId(new Guid(DEFAULT_GUID)); <END> networkNameAvailableTest(ValidationResult.VALID, Collections.singletonList(otherNetwork)); }</code><technical_language>extract this code for creating network name, repeats in a cases</technical_language>

Target:
public void networkNameTakenBySameNetwork() throws Exception { networkNameAvailableTest(ValidationResult.VALID, getSingletonNamedNetworkList(DEFAULT_NETWORK_NAME, DEFAULT_GUID)); }
Source:
<code>public static NameMetadataDescription create(List<NameComponentDescription> components, boolean hasFirstComponentHash) { if (hasFirstComponentHash) { <START> return NameMetadataDescription.create(components, 1); <END> } else { return NameMetadataDescription.create(components, 0); } }</code><technical_language>cleaner Operator (?:) here. nit: move this method diff is clearer general practice of calling static methods bellow itself</technical_language>

Target:
public static NameMetadataDescription create(List<NameComponentDescription> components, boolean hasFirstComponentHash) { return NameMetadataDescription.create(components, hasFirstComponentHash ? 1 : 0); }
Source:
<code>public void headersDoIncludeUserAgent() throws Exception { URI uri = new URI("<LINK_0>"); EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); <START> ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); <END> DownloadCommand cmd = new DownloadCommand(uri, true, "abcdef", new ByteArrayOutputStream()); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.headers().get(HttpHeaderNames.USER_AGENT)).isEqualTo("Bazel/development version"); }</code><technical_language>out is unused</technical_language>

Target:
public void headersDoIncludeUserAgent() throws Exception { URI uri = new URI("<LINK_0>"); EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler( null)); DownloadCommand cmd = new DownloadCommand(uri, true, "abcdef", new ByteArrayOutputStream()); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.headers().get(HttpHeaderNames.USER_AGENT)).isEqualTo("bazel/HEAD"); }
Source:
<code><START> public void onFire(int seconds, CallbackInfo ci, int i) { <END> if (((IMixinWorld) world).isFake() || !ShouldFire.IGNITE_ENTITY_EVENT) { return; } if (!this.isBurning()) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { if (this.originalLava != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.MAGMA); frame.pushCause(this.originalLava); } if (this.originalInFire != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.FIRE); frame.pushCause(this.originalInFire); } if (this.originalLightning != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.FIRE); frame.pushCause(this.originalLightning); } frame.pushCause(this.getLocation().getExtent()); IgniteEntityEvent event = SpongeEventFactory. createIgniteEntityEvent(frame.getCurrentCause(), i, i, this); if (SpongeImpl.postEvent(event)) { ci.cancel(); } } } }</code><technical_language>public</technical_language>

Target:
private void onFire(int seconds, CallbackInfo ci, int i) { if (((IMixinWorld) world).isFake() || !ShouldFire.IGNITE_ENTITY_EVENT) { return; } if (this.fire < 1) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this.getLocation().getExtent()); IgniteEntityEvent event = SpongeEventFactory. createIgniteEntityEvent(frame.getCurrentCause(), i, i, this); if (SpongeImpl.postEvent(event)) { ci.cancel(); } } } }
Source:
<code>public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { <START> return (OffsetDateTime) rs.getObject(columnName); <END> }</code><technical_language>argument of getObject() instead of cast. suggestion return rs.getObject(columnName, OffsetDateTime.class);</technical_language>

Target:
public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getObject(columnName, OffsetDateTime.class); }
Source:
<code>public ByteBuffer getBlob(ByteRange range) throws RouterException { try { if (range == null) { <START> return getBlob(); <END> } ByteRange resolvedRange = range.toResolvedByteRange(blob.array().length); return ByteBuffer.wrap(blob.array(), (int) resolvedRange.getStartOffset(), (int) resolvedRange.getRangeSize()); } catch (IllegalArgumentException e) { throw new RouterException("Invalid range for blob", e, RouterErrorCode.RangeNotSatisfiable); } }</code><technical_language>i _really_ prefer a single return path. I find multiple return paths nests confusing. alternate (single return path) is complicated, prefer that</technical_language>

Target:
public ByteBuffer getBlob(ByteRange range) throws RouterException { ByteBuffer buf; if (range == null) { buf = getBlob(); } else { ByteRange resolvedRange; try { resolvedRange = range.toResolvedByteRange(blob.array().length); } catch (IllegalArgumentException e) { throw new RouterException("Invalid range for blob", e, RouterErrorCode.RangeNotSatisfiable); } buf = ByteBuffer.wrap(blob.array(), (int) resolvedRange.getStartOffset(), (int) resolvedRange.getRangeSize()); } return buf; }
Source:
<code>public boolean isVariadic() { for(Parameter p : getParameters()){ if(p.isVarArgs()) return true; } return false; <START> } <END></code><technical_language>simplify this return getVarArgIndex() > -1;</technical_language>

Target:
public boolean isVariadic() { return getVarArgIndex() > -1; }
Source:
<code>public StorageManagementClient buildClient() { if (host == null) { <START> this.host = "<LINK_0>"; <END> } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }</code><technical_language>In track 2, named this endpoint instead of host</technical_language>

Target:
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "<LINK_0>"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
Source:
<code>private void stop() { if (brokers.length > 1) { try { <START> deleteAllTopicsAndWait(60_000L); <END> } catch (final InterruptedException e) { log.warn("Couldn't delete all topics before stopping brokers", e); } } for (final KafkaEmbedded broker : brokers) { broker.stopAsync(); } for (final KafkaEmbedded broker : brokers) { broker.awaitStoppedAndPurge(); } zookeeper.shutdown(); }</code><technical_language>Do need wait avoid leader election</technical_language>

Target:
private void stop() { if (brokers.length > 1) { final Set<String> topics = getAllTopicsInCluster(); if (!topics.isEmpty()) { try (final Admin adminClient = brokers[0].createAdminClient()) { adminClient.deleteTopics(topics).all().get(); } catch (final InterruptedException e) { log.warn("Got interrupted while deleting topics in preparation for stopping embedded brokers", e); throw new RuntimeException(e); } catch (final ExecutionException | RuntimeException e) { log.warn("Couldn't delete all topics before stopping brokers", e); } } } for (final KafkaEmbedded broker : brokers) { broker.stopAsync(); } for (final KafkaEmbedded broker : brokers) { broker.awaitStoppedAndPurge(); } zookeeper.shutdown(); }
Source:
<code>private void stage(final IStructuredSelection selection) { awaitStageJob(); stageJob = new Job(UIText.StagingView_Staging) { public IStatus run(IProgressMonitor monitor) { <START> asyncLockUI(); <END> try { Git git = new Git(currentRepository); AddCommand add = null; RmCommand rm = null; Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: if (add == null) add = git.add(); add.addFilepattern(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } if (add != null) try { add.call(); } catch (NoFilepatternException e1) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } finally { asyncUnlockUI(); } return Status.OK_STATUS; } }; stageJob.setUser(true); stageJob.schedule(); }</code><technical_language>Joining a Job UI thread a problem (blocks UI thread). user chance trigger a stage/unstage job while is running (tables disabled) ok</technical_language>

Target:
private void stage(final IStructuredSelection selection) { awaitStageJob(); stageJob = new Job(UIText.StagingView_Staging) { public IStatus run(IProgressMonitor monitor) { asyncLockUI(); try { Git git = new Git(currentRepository); RmCommand rm = null; Iterator iterator = selection.iterator(); List<String> addPaths = new ArrayList<String>(); while (iterator.hasNext()) { Object element = iterator.next(); if (element instanceof StagingEntry) { StagingEntry entry = (StagingEntry) element; switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: addPaths.add(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } else { IResource resource = AdapterUtils.adapt(element, IResource.class); if (resource != null) { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping != null && mapping.getRepository() == currentRepository) { String path = mapping.getRepoRelativePath(resource); if ("".equals(path)) addPaths.add("."); else addPaths.add(path); } } } } if (!addPaths.isEmpty()) try { AddCommand add = git.add(); for (String addPath : addPaths) add.addFilepattern(addPath); add.call(); } catch (NoFilepatternException e1) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } finally { asyncUnlockUI(); } return Status.OK_STATUS; } }; stageJob.setUser(true); stageJob.schedule(); }
Source:
<code>public JavaType conditionalExpressionType(JavaType trueType, JavaType falseType) { <START> if (trueType == falseType) { <END> return trueType; } if (isNullAndPrimitive(trueType, falseType)) { return falseType.isPrimitive() ? falseType.primitiveWrapperType() : falseType; } if (isNullAndPrimitive(falseType, trueType)) { return trueType.isPrimitive() ? trueType.primitiveWrapperType() : trueType; } JavaType secondOperand = getPrimitive(trueType); JavaType thirdOperand = getPrimitive(falseType); if (secondOperand != null && thirdOperand != null && isNumericalConditionalExpression(secondOperand, thirdOperand)) { if ((secondOperand.tag < thirdOperand.tag || secondOperand.isTagged(JavaType.INT)) && !thirdOperand.isTagged(JavaType.INT)) { return thirdOperand; } else { return secondOperand; } } return (JavaType) leastUpperBound(Lists.<Type>newArrayList(trueType, falseType)); }</code><technical_language>![MAJOR](<LINK_1> Change this comparison equals method. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public JavaType conditionalExpressionType(JavaType trueType, JavaType falseType) { if (trueType == falseType) { return trueType; } if (trueType.isTagged(JavaType.BOT)) { return falseType.isPrimitive() ? falseType.primitiveWrapperType() : falseType; } if (falseType.isTagged(JavaType.BOT)) { return trueType.isPrimitive() ? trueType.primitiveWrapperType() : trueType; } JavaType secondOperand = getPrimitive(trueType); JavaType thirdOperand = getPrimitive(falseType); if (secondOperand != null && thirdOperand != null && isNumericalConditionalExpression(secondOperand, thirdOperand)) { if ((secondOperand.tag < thirdOperand.tag || secondOperand.isTagged(JavaType.INT)) && !thirdOperand.isTagged(JavaType.INT)) { return thirdOperand; } else { return secondOperand; } } return (JavaType) leastUpperBound(Lists.<Type>newArrayList(trueType, falseType)); }
Source:
<code>public Object getValue(Object adaptable, String name, Type type, AnnotatedElement annotatedElement, DisposalCallbackRegistry disposalCallbackRegistry) { <START> Integer maxLevel = annotatedElement.getAnnotation(ParentResourceValueMapValue.class).maxLevel(); <END> if (adaptable instanceof Resource) { return getInheritedProperty((Resource)adaptable, name, type, maxLevel); } else if (adaptable instanceof SlingHttpServletRequest) { Resource adaptableResource = ((SlingHttpServletRequest) adaptable).getResource(); return getInheritedProperty(adaptableResource, name, type, maxLevel); } return null; }</code><technical_language>check annotation, similar done in com.adobe.acs.commons.models.injectors.impl.HierarchicalPagePropertyInjector#getValue if (!element.isAnnotationPresent(HierarchicalPageProperty.class)) { //skipping javax.Inject for performance reasons. supports direct injection. return null; }</technical_language>

Target:
public Object getValue(Object adaptable, String name, Type type, AnnotatedElement annotatedElement, DisposalCallbackRegistry disposalCallbackRegistry) { if (!annotatedElement.isAnnotationPresent(ParentResourceValueMapValue.class)) { return null; } Integer maxLevel = annotatedElement.getAnnotation(ParentResourceValueMapValue.class).maxLevel(); if (adaptable instanceof Resource) { return getInheritedProperty((Resource)adaptable, name, type, maxLevel); } else if (adaptable instanceof SlingHttpServletRequest) { Resource adaptableResource = ((SlingHttpServletRequest) adaptable).getResource(); return getInheritedProperty(adaptableResource, name, type, maxLevel); } return null; }
Source:
<code>protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); <START> setCommandShouldBeLogged(false); <END> if (stopVms()) { onStopVmsSucceeded(); } else { setSucceeded(true); } }</code><technical_language>I prefer a approach comply commands framework - disable auditing</technical_language>

Target:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); log(); stopVms(); if (allVmsDown) { getParameters().setTaskGroupSuccess(true); endAction(); } else { setSucceeded(true); } }
Source:
<code>private Date convertDate(Date inDate, String tZone) { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); <START> format.setTimeZone(TimeZone.getTimeZone(schedule.getTimeZone())); <END> String formattedStartDate = format.format(schedule.getStartDate()); return new Date(formattedStartDate); }</code><technical_language>tZone param</technical_language>

Target:
private Date convertDate(Date inDate, String tZone) { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); String formattedStartDate = format.format(inDate); format.setTimeZone(TimeZone.getTimeZone(tZone)); try { return format.parse(formattedStartDate); } catch (Exception ex) { log.error("Error while converting the date to engine time zone"); return null; } }
Source:
<code>public void provision(EnvironmentImpl environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { osEnv.getPersistentVolumeClaims() .put(runtimeIdentity.getWorkspaceId(), new PersistentVolumeClaimBuilder() .withNewMetadata() <START> .withName(runtimeIdentity.getWorkspaceId()) <END> .endMetadata() .withNewSpec() .withAccessModes(pvcAccessMode) .withNewResources() .withRequests(ImmutableMap.of("storage", new Quantity(pvcQuantity))) .endResources() .endSpec() .build()); final String devMachineName = Utils.getDevMachineName(environment); for (Pod pod : osEnv.getPods().values()) { for (Container container : pod.getSpec().getContainers()) { final String machineName = pod.getMetadata().getName() + "/" + container.getName(); if (devMachineName != null && devMachineName.equals(machineName)) { final String workspaceId = runtimeIdentity.getWorkspaceId(); final VolumeMount volumeMount = new VolumeMountBuilder().withMountPath(projectFolderPath) .withName(workspaceId) .build(); container.getVolumeMounts().add(volumeMount); final PersistentVolumeClaimVolumeSource pvcs = new PersistentVolumeClaimVolumeSourceBuilder() .withClaimName(workspaceId) .build(); final Volume volume = new VolumeBuilder().withPersistentVolumeClaim(pvcs) .withName(workspaceId) .build(); pod.getSpec().getVolumes().add(volume); return; } } } } }</code><technical_language>wsId-projects for name of this pvc. WDYT</technical_language>

Target:
public void provision(EnvironmentImpl environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { osEnv.getPersistentVolumeClaims() .put(pvcName, new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(pvcName) .endMetadata() .withNewSpec() .withAccessModes(pvcAccessMode) .withNewResources() .withRequests(ImmutableMap.of("storage", new Quantity(pvcQuantity))) .endResources() .endSpec() .build()); final String devMachineName = Utils.getDevMachineName(environment); for (Pod pod : osEnv.getPods().values()) { for (Container container : pod.getSpec().getContainers()) { final String machineName = pod.getMetadata().getName() + "/" + container.getName(); if (devMachineName != null && devMachineName.equals(machineName)) { final VolumeMount volumeMount = new VolumeMountBuilder() .withMountPath(projectFolderPath) .withName(pvcName) .build(); container.getVolumeMounts().add(volumeMount); final PersistentVolumeClaimVolumeSource pvcs = new PersistentVolumeClaimVolumeSourceBuilder() .withClaimName(pvcName) .build(); final Volume volume = new VolumeBuilder().withPersistentVolumeClaim(pvcs) .withName(pvcName) .build(); pod.getSpec().getVolumes().add(volume); return; } } } } }
Source:
<code>public String getPrimaryVideoTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(MPEGPS, MPEG2, AC3)) { return MPEGPS; } <START> if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, MPEG2, AAC)) { <END> return MPEGTS; } if (supportSpec.match(WMV, WMV, WMA)) { return WMV; } } return null; }</code><technical_language>(MPEGTS, H264, AAC)</technical_language>

Target:
public String getPrimaryVideoTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(MPEGPS, MPEG2, AC3)) { return MPEGPS; } if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, H264, AAC)) { return MPEGTS; } if (supportSpec.match(WMV, WMV, WMA)) { return WMV; } } return null; }
Source:
<code>private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); <START> for (String uniqueName : Arrays.asList(uniqueNames)) { <END> Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); } } } } catch (BackingStoreException e) { throw new RuntimeException("Failed to validate Os Repository due to " + e); } }</code><technical_language>please: 1. constant OS_ROOT_NODE instead of "/os" 2. inline this get a free iterator? for (String uniqueName : prefs.node(OS_ROOT_NODE).childrenNames())</technical_language>

Target:
private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); log.warn("Illegal parent for os: " + uniqueName); } } } } catch (BackingStoreException e) { log.warn("Failed to validate Os Repository due to " + e); throw new RuntimeException("Failed to validate Os Repository due to " + e); } }
Source:
<code>public static String readContent(String url) throws IOException { HttpURLConnection conn = null; BufferedReader reader = null; try { conn = (HttpURLConnection)new URL(url).openConnection(); conn.connect(); int httpCode = conn.getResponseCode(); if (httpCode == 200) { <START> reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); <END> return reader.readLine(); } else if (httpCode == 404) { return null; } throw new RuntimeException("Un expected response code: " + httpCode); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } }</code><technical_language>leak</technical_language>

Target:
public static String readContent(String url) throws IOException { HttpURLConnection conn = null; try { conn = (HttpURLConnection)new URL(url).openConnection(); conn.connect(); int httpCode = conn.getResponseCode(); if (httpCode == 200) { try (InputStream input = conn.getInputStream(); InputStreamReader inputReader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputReader)) { return reader.readLine(); } } else if (httpCode == 404) { return null; } throw new RuntimeException("Un expected response code: " + httpCode); } finally { if (conn != null) { conn.disconnect(); } } }
Source:
<code>public void createObjects() { <START> log = LoggerFactory.getLogger(OptimizerTOSCADecember2015AutoscalingPoliciesTest.class); <END> log.info("Starting TEST optimizer for the TOSCA syntax of September 2015"); final String dir = System.getProperty("user.dir"); log.debug("Trying to open files: current executino dir = " + dir); try { appModel = filenameToString(TestConstants.APP_MODEL_FILENAME); } catch (IOException e) { log.error("File for APPmodel not found"); e.printStackTrace(); } try { suitableCloudOffer = filenameToString(TestConstants.CLOUD_OFFER_FILENAME_IN_JSON); } catch (IOException e) { log.error("File for Cloud Offers not found"); e.printStackTrace(); } }</code><technical_language>log initialized defined [above](<LINK_0></technical_language>

Target:
public void createObjects() { log = LoggerFactory.getLogger(OptimizerTOSCADecember2015AutoscalingPoliciesTest.class); log.info("Starting TEST optimizer for the TOSCA syntax of September 2015"); openInputFiles(); }
Source:
<code>public String getDescription() { <START> return "1.13+ Flatting Spawn Egg Provider"; <END> }</code><technical_language>Nitpick, "Flat" "Flattening", in</technical_language>

Target:
public String getDescription() { return "1.13+ Flattening Spawn Egg Provider"; }
Source:
<code>public void enableProcessing(String queueId, boolean value) { WorkQueueDescriptor config = workQueueConfig.get(queueId); if (config == null) { throw new IllegalArgumentException("no such queue " + queueId); } if (!value) { if (!queuing.supportProcessingDisablement()) { log.error("Attempting to disable works processing on a WorkQueuing instance that does not support it." <START> + "Works will still be processed."); <END> } deactivateQueue(config); } else { activateQueue(config); } }</code><technical_language>message is correct fix this</technical_language>

Target:
public void enableProcessing(String queueId, boolean value) { WorkQueueDescriptor config = workQueueConfig.get(queueId); if (config == null) { throw new IllegalArgumentException("no such queue " + queueId); } if (!value) { if (!queuing.supportsProcessingDisabling()) { log.error("Attempting to disable works processing on a WorkQueuing instance that does not support it." + "Works will still be processed." + "Disabling works processing to manage distribution finely can be done using Redis or Stream implementations."); } deactivateQueue(config); } else { activateQueue(config); } }
Source:
<code>public void testZookeeperConnectionStartup() throws Exception { ClusterService service = ClusterServiceFactory.createClusterService( TestUtils.createGoldenConfiguration(testingServer.getConnectString())); service.startService(); <START> synchronized((ZookeeperClusterService)service){ <END> try{ (service).wait(); }catch(InterruptedException e){ e.printStackTrace(); } } Stat stat = client.checkExists().forPath("/jmxtrans/workers/worker_01"); assertThat(stat).isNotEqualTo(null); service.stopService(); }</code><technical_language>Cast is necessary</technical_language>

Target:
public void testZookeeperConnectionStartup() throws Exception { ClusterService service = ClusterServiceFactory.createClusterService( ConfigurationFixtures.createGoldenConfiguration(testingServer.getConnectString())); service.startService(); synchronized(service){ try{ service.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } Stat stat = client.checkExists().forPath("/jmxtrans/workers/worker_01"); assertThat(stat).isNotEqualTo(null); service.stopService(); }
Source:
<code>@Override public void onPositiveClicked(@NonNull String instanceTag) { Fragment fragment = getMySiteFragment(); if (fragment != null) { <START> getMySiteFragment().onPositiveClicked(instanceTag); <END> } }</code><technical_language>getMySiteFragment() is assigned fragment, is is null checked, fragment.onPositiveClicked(instanceTag); instead</technical_language>

Target:
public void onPositiveClicked(@NonNull String instanceTag) { MySiteFragment fragment = getMySiteFragment(); if (fragment != null) { fragment.onPositiveClicked(instanceTag); } }