auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Expression string(JSONArray json, int index) { Object obj = json.get(index); if (obj == null) { return ff.literal(null); } else if (obj instanceof String) { String str = (String) obj; return ff.literal(str); } else if (obj instanceof Number) { Number number = (Number) obj; return ff.literal(number); } else if (obj instanceof Boolean) { Boolean bool = (Boolean) obj; return ff.literal(bool); } else if (obj instanceof JSONObject) { MBFunction function = new MBFunction(this, (JSONObject) obj); return function.function(String.class); } else if (obj instanceof JSONArray) { JSONArray array = (JSONArray) obj; if (isString(array, 0)) { String expressionName = get(array, 0); if (MBExpression.canCreate(expressionName)) { return MBExpression.transformExpression(array); } else { throw new MBFormatException( context + " string unavailable: expression' " + expressionName + "' not supported."); } } else { <START> throw new MBFormatException(context + " string from JSONArray not a supported"); <END> } } else { throw new IllegalArgumentException( "json contents invalid, " + context + " value limited to String, Number, Boolean, JSONArray or JSONObject but was " + obj.getClass().getSimpleName()); } }</code><technical_language>"... a supported" what? This error message worse before</technical_language>

Target:
public Expression string(JSONArray json, int index) { Object obj = json.get(index); if (obj == null) { return ff.literal(null); } else if (obj instanceof String) { String str = (String) obj; return ff.literal(str); } else if (obj instanceof Number) { Number number = (Number) obj; return ff.literal(number); } else if (obj instanceof Boolean) { Boolean bool = (Boolean) obj; return ff.literal(bool); } else if (obj instanceof JSONObject) { MBFunction function = new MBFunction(this, (JSONObject) obj); return function.function(String.class); } else if (obj instanceof JSONArray) { JSONArray array = (JSONArray) obj; if (isString(array, 0)) { String expressionName = get(array, 0); if (MBExpression.canCreate(expressionName)) { return MBExpression.transformExpression(array); } else { throw new MBFormatException( context + " string unavailable: data expression \"" + expressionName + "\" invalid. It may be misspelled or not supported by this implementation"); } } else { throw new MBFormatException( context + " string unavailable: Conversion from a JSONArray not a supported: " + array); } } else { throw new IllegalArgumentException( context + " string unavailable: json contents invalid - value limited to String, Number, Boolean, JSONArray or JSONObject but was " + obj.getClass().getSimpleName()); } }
Source:
<code><START> public static ArgumentFilter createFilter(Method method) { <END> Subscribe annotation = method.getAnnotation(Subscribe.class); checkAnnotated(method, annotation); @Nullable Where where = filterAnnotationOf(method); @Nullable ByField byField = annotation.filter(); boolean byFieldEmpty = byField.path().isEmpty(); String fieldPath; String value; if (where != null) { fieldPath = where.field(); value = where.equals(); checkState( byFieldEmpty, "The subscriber method `%s()` has `@%s` and `@%s`" + " annotations at the same time." + " Please use only one, preferring `%s` because `%s` is deprecated.", method.getName(), ByField.class.getName(), Where.class.getName(), Where.class.getName(), ByField.class.getName() ); } else { if (byFieldEmpty) { return acceptingAll(); } fieldPath = byField.path(); value = byField.value(); } Class<Message> paramType = firstParamType(method); Field field = Field.parse(fieldPath); Class<?> fieldType = field.findType(paramType).orElseThrow( () -> newIllegalStateException( "The message with the type `%s` does not have the field `%s`.", paramType.getName(), field) ); Object expectedValue = fromString(value, fieldType); return acceptingOnly(field.path(), expectedValue); }</code><technical_language>Please split this method more readable</technical_language>

Target:
public static ArgumentFilter createFilter(Method method) { Subscribe annotation = method.getAnnotation(Subscribe.class); checkAnnotated(method, annotation); @Nullable Where where = filterAnnotationOf(method); ByField byField = annotation.filter(); boolean byFieldEmpty = byField.path().isEmpty(); String fieldPath; String value; if (where != null) { fieldPath = where.field(); value = where.equals(); checkNoByFieldAnnotation(byFieldEmpty, method); } else { if (byFieldEmpty) { return acceptingAll(); } fieldPath = byField.path(); value = byField.value(); } return createFilter(method, fieldPath, value); }
Source:
<code>public void plotGraphMap(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { rsp.sendRedirect2(req.getContextPath() + "/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); <START> setDescription(req); <END> generatePlot(false); ChartRenderingInfo info = new ChartRenderingInfo(); plot.createBufferedImage(getWidth(), getHeight(), info); rsp.setContentType("text/plain;charset=UTF-8"); rsp.getWriter().println(ChartUtilities.getImageMap(getCsvFileName(), info)); }</code><technical_language>This remove description set, please remove</technical_language>

Target:
public void plotGraphMap(StaplerRequest req, StaplerResponse rsp) throws IOException { if (ChartUtil.awtProblemCause != null) { rsp.sendRedirect2(req.getContextPath() + "/images/headless.png"); return; } setWidth(req); setHeight(req); setNumBuilds(req); setRightBuildNum(req); setHasLegend(req); setTitle(req); setStyle(req); setUseDescr(req); generatePlot(false); ChartRenderingInfo info = new ChartRenderingInfo(); plot.createBufferedImage(getWidth(), getHeight(), info); rsp.setContentType("text/plain;charset=UTF-8"); rsp.getWriter().println(ChartUtilities.getImageMap(getCsvFileName(), info)); }
Source:
<code>public boolean equals(Object other, boolean deepCompare) { if (other == this) { return true; } if (other == null || other.getClass() != getClass()) { return false; } boolean result = true; SystemTreeItemModel otherModel = (SystemTreeItemModel) other; if (getChildren().size() > 0 && deepCompare) { if (otherModel.getChildren().size() == getChildren().size()) { for (int i = 0; i < getChildren().size(); i++) { result = getChildren().get(i).equals(otherModel.getChildren().get(i), deepCompare); if (!result) { break; } } } else { result = false; } } if (result) { if ((otherModel.getEntity() == null && getEntity() == null) || (otherModel.getEntity() != null && otherModel.getEntity().equals(getEntity()) <START> && otherModel.getTitle().equals(getTitle()))) { <END> result = true; } else { result = false; } } return result; }</code><technical_language>I for title attribute null, honor contract of equals method, I suggest perform null check here</technical_language>

Target:
public boolean equals(Object other, boolean deepCompare) { if (other == this) { return true; } if (other == null || other.getClass() != getClass()) { return false; } boolean result = true; SystemTreeItemModel otherModel = (SystemTreeItemModel) other; if (getChildren().size() > 0 && deepCompare) { if (otherModel.getChildren().size() == getChildren().size()) { for (int i = 0; i < getChildren().size(); i++) { result = getChildren().get(i).equals(otherModel.getChildren().get(i), deepCompare); if (!result) { break; } } } else { result = false; } } if (result) { if (!((otherModel.getEntity() == null && getEntity() == null) || (otherModel.getEntity() != null && otherModel.getEntity().equals(getEntity()) && ((otherModel.getTitle() == null && getTitle() == null) || (otherModel.getTitle() != null && otherModel.getTitle().equals(getTitle())))))) { result = false; } } return result; }
Source:
<code>public CatalogDatabase getDatabase(String databaseName) throws DatabaseNotExistException, CatalogException { Database hiveDatabase = getHiveDatabase(databaseName); Map<String, String> properties = hiveDatabase.getParameters(); <START> boolean isGeneric = getObjectIsGeneric(properties); <END> if (!isGeneric) { properties.put(SqlCreateHiveDatabase.DATABASE_LOCATION_URI, hiveDatabase.getLocationUri()); } return new CatalogDatabaseImpl(properties, hiveDatabase.getDescription()); }</code><technical_language>put properties key in connector validator instead of SqlNode, i think</technical_language>

Target:
public CatalogDatabase getDatabase(String databaseName) throws DatabaseNotExistException, CatalogException { Database hiveDatabase = getHiveDatabase(databaseName); Map<String, String> properties = hiveDatabase.getParameters(); boolean isGeneric = isGenericForGet(properties); if (!isGeneric) { properties.put(SqlCreateHiveDatabase.DATABASE_LOCATION_URI, hiveDatabase.getLocationUri()); } return new CatalogDatabaseImpl(properties, hiveDatabase.getDescription()); }
Source:
<code>public ListenableFuture getCloseFuture() { if <START> (mReleaseFuture == <END> null) { synchronized (mReleaseLock) { mReleaseFuture = CallbackToFutureAdapter.getFuture( new CallbackToFutureAdapter.Resolver<Void>() { @Override public Object attachCompleter(@NonNull CallbackToFutureAdapter.Completer<Void> completer) { Preconditions.checkState(Thread.holdsLock(mReleaseLock)); Preconditions.checkState(mReleaseCompleter == null, "Release completer expected to be null"); mReleaseCompleter = completer; return "Release[imageProxy=" + FakeImageProxy.this + "]"; } }); return mReleaseFuture; } } else { return Futures.immediateFuture(null); } }</code><technical_language>accessing mReleaseFuture release lock annotated '@GuardedBy("mReleaseLock")'</technical_language>

Target:
public ListenableFuture getCloseFuture() { synchronized (mReleaseLock) { if (mReleaseFuture == null) { mReleaseFuture = CallbackToFutureAdapter.getFuture( new CallbackToFutureAdapter.Resolver<Void>() { @Override public Object attachCompleter(@NonNull CallbackToFutureAdapter.Completer<Void> completer) { Preconditions.checkState(Thread.holdsLock(mReleaseLock)); Preconditions.checkState(mReleaseCompleter == null, "Release completer expected to be null"); mReleaseCompleter = completer; return "Release[imageProxy=" + FakeImageProxy.this + "]"; } }); } return mReleaseFuture; } }
Source:
<code><START> public long cyclesToNanos(long cycles) { <END> CTFTrace trace = fTrace; if (trace != null) { CTFClock clock = trace.getClock(); return trace.timestampCyclesToNanos(cycles - trace.getOffset()) + clock.getClockOffsetNs(); } return 0; }</code><technical_language>This method is a simple converter is dependent frequency dependent clock offset. return cycles * clock.getScale(), cycles if clock is null</technical_language>

Target:
public long cyclesToNanos(long cycles) { CTFTrace trace = fTrace; if (trace != null) { return trace.timestampCyclesToNanos(cycles - trace.getOffset()); } return 0; }
Source:
<code>private void initializeShallowCommits() throws IOException { if (shallowCommitsInitialized) return; shallowCommitsInitialized = true; for (ObjectId id : reader.getShallowCommits()) { <START> final RevCommit commit = lookupCommit(id); <END> commit.parents = new RevCommit[0]; } }</code><technical_language>This shorter: for (ObjectId id : reader.getShallowCommits()) lookupCommit(id).parents = RevCommit.NO_PARENTS; static array a tiny amount of memory, making new instances shallow commit</technical_language>

Target:
void initializeShallowCommits() throws IOException { if (shallowCommitsInitialized) throw new IllegalStateException(JGitText.get().outputHasAlreadyBeenStarted); shallowCommitsInitialized = true; for (ObjectId id : reader.getShallowCommits()) lookupCommit(id).parents = RevCommit.NO_PARENTS; }
Source:
<code>private void interruptAndWaitCleanupTime() { threadToKill.interrupt(); int iterationsToHitWaitingTimeLimit = CLEANUP_SECONDS_AFTER_FIRST_INTERRUPT * 100; <START> for(int i = 0; threadToKill.isAlive() && i < iterationsToHitWaitingTimeLimit ; i++ ) { <END> try { Thread.sleep(10); } catch (InterruptedException e) { } } }</code><technical_language>Formatting</technical_language>

Target:
private void interruptAndWaitCleanupTime() { threadToKill.interrupt(); int iterationsToHitWaitingTimeLimit = SECONDS_TO_WAIT_UNTIL_AGGRESSIVELY_INTERRUPT_TASK * THREAD_INTERRUPT_SLEEP_TO_SECONDS_MULTIPLIER; for (int i = 0; threadToKill.isAlive() && i < iterationsToHitWaitingTimeLimit; i++) { threadInterruptSleeper.sleep(); } }
Source:
<code>DialogueFeignClient(Class<?> jaxrsInterface, Channel channel, ConjureRuntime runtime, String baseUrl) { this.channel = Preconditions.checkNotNull(channel, "Channel is required"); this.serviceName = jaxrsInterface.getSimpleName(); this.version = Optional.ofNullable(jaxrsInterface.getPackage().getImplementationVersion()) .orElse("0.0.0"); this.baseUrl = baseUrl; <START> this.clients = runtime.clients(); <END> }</code><technical_language>store ConjureRuntime a field? read Clients clients worry this some kind of internal caching</technical_language>

Target:
DialogueFeignClient(Class<?> jaxrsInterface, Channel channel, ConjureRuntime runtime, String baseUrl) { this.channel = Preconditions.checkNotNull(channel, "Channel is required"); this.baseUrl = Preconditions.checkNotNull(baseUrl, "Base URL is required"); this.runtime = Preconditions.checkNotNull(runtime, "ConjureRuntime is required"); this.serviceName = Preconditions.checkNotNull(jaxrsInterface, "Service is required") .getSimpleName(); this.version = Optional.ofNullable(jaxrsInterface.getPackage().getImplementationVersion()) .orElse("0.0.0"); }
Source:
<code>private float getCharcoalAmount(World world, BlockPos pos) { float charcoalAmount = 0F; for (EnumFacing facing : EnumFacing.VALUES) { charcoalAmount += getCharcoalFaceAmount(world, pos, facing); } float ret = charcoalAmount / 6; if (ret > 0F) { <START> ret += 9F; END> } return ret; }</code><technical_language>if ret is this moment bigger 6? ash block a valid metadata 0 15</technical_language>

Target:
private float getCharcoalAmount(World world, BlockPos pos) { float charcoalAmount = 0F; for (EnumFacing facing : EnumFacing.VALUES) { charcoalAmount += getCharcoalFaceAmount(world, pos, facing); } return Math.min(charcoalAmount / 6, 15.0F); }
Source:
<code>private int instrumentZip(final InputStream input, final OutputStream output, final String name) throws IOException { if (generators.getLast() instanceof OfflineInstrumentationCompanionAccessGenerator) { generators .addLast(new OfflineInstrumentationCompanionAccessGenerator()); } final ZipInputStream zipin = new ZipInputStream(input); final ZipOutputStream zipout = new ZipOutputStream(output); ZipEntry entry; int count = 0; while ((entry = zipin.getNextEntry()) != null) { final String entryName = entry.getName(); if (signatureRemover.removeEntry(entryName)) { continue; } zipout.putNextEntry(new ZipEntry(entryName)); if (!signatureRemover.filterEntry(entryName, zipin, zipout)) { count += instrumentAll(zipin, zipout, name + "@" + entryName); } <START> zipout.closeEntry(); <END> } if (generators.getLast() instanceof OfflineInstrumentationCompanionAccessGenerator) { OfflineInstrumentationCompanionAccessGenerator companionGenerator = (OfflineInstrumentationCompanionAccessGenerator) generators .getLast(); if (companionGenerator.getNumberOfInstrumentedClasses() != 0) { zipout.putNextEntry( new ZipEntry(companionGenerator.getClassName() + ".class")); zipout.write(companionGenerator.getClassDefinition()); zipout.closeEntry(); } generators.removeLast(); } zipout.finish(); return count; }</code><technical_language>I guess this while loop needs check Companions.FIELDS_PER_CLASS</technical_language>

Target:
private int instrumentZip(final InputStream input, final OutputStream output, final String name) throws IOException { final ZipInputStream zipin = new ZipInputStream(input); final ZipOutputStream zipout = new ZipOutputStream(output); if (generators .getLast() instanceof OfflineInstrumentationCompanionAccessGenerator) { generators .addLast(new OfflineInstrumentationCompanionAccessGenerator( new IClassFileWriter() { public void write(final String name, final byte[] bytes) { try { zipout.putNextEntry(new ZipEntry(name)); zipout.write(bytes); zipout.closeEntry(); } catch (IOException e) { throw new RuntimeException(e); } } })); } ZipEntry entry; int count = 0; while ((entry = zipin.getNextEntry()) != null) { final String entryName = entry.getName(); if (signatureRemover.removeEntry(entryName)) { continue; } zipout.putNextEntry(new ZipEntry(entryName)); if (!signatureRemover.filterEntry(entryName, zipin, zipout)) { count += instrumentAll(zipin, zipout, name + "@" + entryName); } zipout.closeEntry(); } if (generators.getLast() instanceof OfflineInstrumentationCompanionAccessGenerator) { OfflineInstrumentationCompanionAccessGenerator companionGenerator = (OfflineInstrumentationCompanionAccessGenerator) generators .getLast(); companionGenerator.end(); generators.removeLast(); } zipout.finish(); return count; }
Source:
<code><START> public User initializeUser(final Integer userId) { <END> final User user = new User(); final Person person = new Person(); person.setId(2); person.setFirstName("Diego"); person.setMiddleName(""); person.setLastName("Cuenya"); person.setEmail("diego.cuenya@leafnode.io"); person.setTitle("-"); person.setContact("-"); person.setExtension("-"); person.setFax("-"); person.setInstituteId(0); person.setLanguage(0); person.setNotes("-"); person.setPositionName("-"); person.setPhone("-"); user.setPerson(person); user.setPersonid(person.getId()); user.setPerson(person); user.setName("Cuenyad"); user.setAccess(0); user.setInstalid(0); user.setType(0); return user; }</code><technical_language>@cuenyad Thanks for checking this function</technical_language>

Target:
public User initializeUser(final Integer userId) { final User user = new User(); final Person person = new Person(); person.setId(2); final String firstName = RandomStringUtils.randomAlphanumeric(20); person.setFirstName(firstName); person.setMiddleName(""); final String lastName = RandomStringUtils.randomAlphanumeric(50); person.setLastName(lastName); final String email = RandomStringUtils.randomAlphanumeric(24); person.setEmail("test" + email + "@leafnode.io"); person.setTitle("-"); person.setContact("-"); person.setExtension("-"); person.setFax("-"); person.setInstituteId(0); person.setLanguage(0); person.setNotes("-"); person.setPositionName("-"); person.setPhone("-"); user.setPerson(person); user.setPersonid(person.getId()); user.setPerson(person); final String username = RandomStringUtils.randomAlphanumeric(30); user.setName(username); user.setAccess(0); user.setInstalid(0); user.setType(0); return user; }
Source:
<code>public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { try { engine.eval(String.format("var %s = %s;", VARIABLE_NAME, GSON.toJson(input))); <START> Emitter<Map> jsEmitter = new JSEmitter(emitter, <END> schema == null ? input.getSchema() : schema, getContext().getFailureCollector()); engine.put(EMITTER_NAME, jsEmitter); invocable.invokeFunction(FUNCTION_NAME); } catch (Exception e) { throw new IllegalArgumentException("Could not transform input: " + e.getMessage(), e); } }</code><technical_language>changing transform method. I changes in init method sufficient</technical_language>

Target:
public void transform(StructuredRecord input, Emitter<StructuredRecord> emitter) { try { engine.eval(String.format("var %s = %s;", VARIABLE_NAME, GSON.toJson(input))); Emitter<Map> jsEmitter = new JSEmitter(emitter, schema == null ? input.getSchema() : schema); engine.put(EMITTER_NAME, jsEmitter); invocable.invokeFunction(FUNCTION_NAME); } catch (Exception e) { throw new IllegalArgumentException("Could not transform input: " + e.getMessage(), e); } }
Source:
<code>protected String determineBranchName(@NotNull Map<String, String> env) throws GitCommitIdExecutionException { if (!BuildServerDataProvider.checkBuildEnvironmentForType(env).equals(BuildEnvironmentType.UNKNOWN)) { <START> String branchName = BuildServerDataProvider.getBuildServerProvider(env,log).getBuildBranch(env,log); <END> if (isNullOrEmpty(branchName)) { log.info("Detected that running on CI environment, but using repository branch, no GIT_BRANCH detected."); return getBranchName(); } return branchName; } else { return getBranchName(); } }</code><technical_language>statement getBuildServerProvider(env,log).getBuildBranch(env,log) reads a bit weird. more sense change java BuildServerDataProvider buildServerDataProvider = BuildServerDataProvider.getBuildServerProvider(env,log); if (!buildServerDataProvider.getBuildEnvironmentType().equals(BuildEnvironmentType.UNKNOWN)) { String branchName = buildServerDataProvider.getBuildBranch(); } A BuildServerDataProvider a reference of env log. this avoid passing arguments a time</technical_language>

Target:
protected String determineBranchName(@NotNull Map<String, String> env) throws GitCommitIdExecutionException { BuildServerDataProvider buildServerDataProvider = BuildServerDataProvider.getBuildServerProvider(env,log); if (!(buildServerDataProvider instanceof UnknownBuildServerData)) { String branchName = buildServerDataProvider.getBuildBranch(); if (isNullOrEmpty(branchName)) { log.info("Detected that running on CI environment, but using repository branch, no GIT_BRANCH detected."); return getBranchName(); } return branchName; } else { return getBranchName(); } }
Source:
<code>public void initialise() { addDesiredStateChange(new SetViewportToSizeOf(WRITEONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new BindFBO(WRITEONLY_GBUFFER, displayResolutionDependentFBOs)); update(); addDesiredStateChange(new EnableMaterial(DEFERRED_LIGHTING_MATERIAL.toString())); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFBO( <START> textureSlot++, READONLY_GBUFFER, SetInputTextureFromFBO.FboTexturesTypes.ColorTexture, <END> displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaque")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot++, READONLY_GBUFFER, SetInputTextureFromFBO.FboTexturesTypes.DepthStencilTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueDepth")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot++, READONLY_GBUFFER, SetInputTextureFromFBO.FboTexturesTypes.NormalsTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueNormals")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot, READONLY_GBUFFER, SetInputTextureFromFBO.FboTexturesTypes.LightAccumulationTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueLightBuffer")); displayResolutionDependentFBOs.subscribe(this); }</code><technical_language>enums shorter here: ColorTexture remain</technical_language>

Target:
public void initialise() { addDesiredStateChange(new BindFBO(WRITEONLY_GBUFFER, displayResolutionDependentFBOs)); update(); displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial(DEFERRED_LIGHTING_MATERIAL.toString())); int textureSlot = 0; addDesiredStateChange(new SetInputTextureFromFBO( textureSlot++, READONLY_GBUFFER, ColorTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaque")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot++, READONLY_GBUFFER, DepthStencilTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueDepth")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot++, READONLY_GBUFFER, NormalsTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueNormals")); addDesiredStateChange(new SetInputTextureFromFBO( textureSlot, READONLY_GBUFFER, LightAccumulationTexture, displayResolutionDependentFBOs, DEFERRED_LIGHTING_MATERIAL, "texSceneOpaqueLightBuffer")); }
Source:
<code>public void batchDelete(Collection<Entitlement> entitlements) { for (Entitlement entitlement : entitlements) { this.deleteImpl(entitlement); entitlement.getCertificates().clear(); entitlement.getConsumer().getEntitlements().remove(entitlement); <START> entitlement.getPool().getEntitlements().remove(entitlement); <END> } }</code><technical_language>NACK. this undoes #1272</technical_language>

Target:
public void batchDelete(Collection<Entitlement> entitlements) { for (Entitlement entitlement : entitlements) { this.deleteImpl(entitlement); entitlement.getCertificates().clear(); if (Hibernate.isInitialized(entitlement.getConsumer().getEntitlements())) { entitlement.getConsumer().getEntitlements().remove(entitlement); } if (Hibernate.isInitialized(entitlement.getPool().getEntitlements())) { entitlement.getPool().getEntitlements().remove(entitlement); } } }
Source:
<code>public void loadAndGetReturnsNullForEmpty() { String data = empty.loadAndGet() <START> .orElse(null); <END> assertThat(data, equalTo(null)); }</code><technical_language>orElse return else null</technical_language>

Target:
public void loadAndGetReturnsNullForEmpty() { String data = empty.loadAndGet() .orElse("null!!"); assertThat(data, equalTo(null)); }
Source:
<code>private static int indexOfTypeParameter(List<DetailAST> typeParams, String requiredTypeName) { final Iterator<DetailAST> typeParamsIt = typeParams.iterator(); int paramIndex = -1; int index = 0; while (typeParamsIt.hasNext()) { <START> final DetailAST typeParam = typeParamsIt.next(); <END> if (typeParam.findFirstToken(TokenTypes.IDENT).getText() .equals(requiredTypeName)) { paramIndex = index; break; } index++; } return paramIndex; }</code><technical_language>this a for loop other method</technical_language>

Target:
private static int indexOfTypeParameter(List<DetailAST> typeParams, String requiredTypeName) { int paramIndex = -1; int index = 0; for (DetailAST typeParam : typeParams) { if (typeParam.findFirstToken(TokenTypes.IDENT).getText() .equals(requiredTypeName)) { paramIndex = index; break; } index++; } return paramIndex; }
Source:
<code>public Event() { this.properties = new Properties(); this.data = new Properties(); this.properties.putValue(Keys.DATA, this.data); setCustomProperties(); <START> this.properties.put(Keys.CONTEXT, getAppNameContext()); <END> }</code><technical_language>This method is in place, removed, logic centralized here</technical_language>

Target:
public Event() { this.properties = new Properties(); this.data = new Properties(); this.properties.putValue(Keys.DATA, this.data); setCustomProperties(); Properties cxtProps = new Properties(); cxtProps.putValue(Keys.APP, Values.APP_NAME); this.properties.put(Keys.CONTEXT, cxtProps); }
Source:
<code>public void validateAddingNonExistingNetwork() { List<VdsNetworkInterface> vdsNics = new ArrayList<VdsNetworkInterface>(); VdsNetworkInterface nic1 = new VdsNetworkInterface(); nic1.setNetworkName("vmnet"); vdsNics.add(nic1); VdsNetworkInterface nic2 = new VdsNetworkInterface(); nic2.setNetworkName("mgmtnet"); vdsNics.add(nic2); List<network> clusterNetworks = new ArrayList<network>(); network net1 = new network(); net1.setname("vmnet"); network net2 = new network(); net2.setname("mgmtnet"); clusterNetworks.add(net1); clusterNetworks.add(net2); List<VdsNetworkInterface> nics = new ArrayList<VdsNetworkInterface>(); VdsNetworkInterface nicWithUknownNetowrk = new VdsNetworkInterface(); nicWithUknownNetowrk.setNetworkName("nonExisitigNetworkName"); nics.add(nicWithUknownNetowrk); initMocks(vdsNics, clusterNetworks); SetupNetworksParameters params = new SetupNetworksParameters(); params.setInterfaces(nics); SetupNetworksHelper validator = createHelper(params); <START> assertTrue(validator.validate().contains(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER)); <END> }</code><technical_language>for sake of consistency, this imported static well</technical_language>

Target:
public void validateAddingNonExistingNetwork() { List<VdsNetworkInterface> vdsNics = new ArrayList<VdsNetworkInterface>(); VdsNetworkInterface nic1 = new VdsNetworkInterface(); nic1.setNetworkName("vmnet"); vdsNics.add(nic1); VdsNetworkInterface nic2 = new VdsNetworkInterface(); nic2.setNetworkName("mgmtnet"); vdsNics.add(nic2); List<network> clusterNetworks = new ArrayList<network>(); network net1 = new network(); net1.setname("vmnet"); network net2 = new network(); net2.setname("mgmtnet"); clusterNetworks.add(net1); clusterNetworks.add(net2); List<VdsNetworkInterface> nics = new ArrayList<VdsNetworkInterface>(); VdsNetworkInterface nicWithUknownNetowrk = new VdsNetworkInterface(); nicWithUknownNetowrk.setNetworkName("nonExisitigNetworkName"); nics.add(nicWithUknownNetowrk); initMocks(vdsNics, clusterNetworks); SetupNetworksParameters params = new SetupNetworksParameters(); params.setInterfaces(nics); SetupNetworksHelper validator = createHelper(params); assertTrue(validator.validate().contains(NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER)); }
Source:
<code>void download() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == PAUSED || status == DELETION) { return; } <START> if(!downloadConnectionAllowedChecker.isAllowedToDownload()) { <END> downloadBatchStatus.markAsError(Optional.of(new DownloadError(DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE)), downloadsBatchPersistence); notifyCallback(downloadBatchStatus); DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); return; } downloadBatchStatus.markAsDownloading(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); totalBatchSizeBytes = getTotalSize(downloadFiles); if (totalBatchSizeBytes <= ZERO_BYTES) { Optional<DownloadError> downloadError = Optional.of(new DownloadError(DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE)); downloadBatchStatus.markAsError(downloadError, downloadsBatchPersistence); notifyCallback(downloadBatchStatus); return; } for (DownloadFile downloadFile : downloadFiles) { downloadFile.download(fileDownloadCallback); if (batchCannotContinue()) { break; } } if (networkError()) { DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); } callbackThrottle.stopUpdates(); }</code><technical_language>this work if resume a download? instance right</technical_language>

Target:
void download() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == PAUSED || status == DELETION) { return; } if (!connectionChecker.isAllowedToDownload()) { downloadBatchStatus.markAsError(Optional.of(new DownloadError(DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE)), downloadsBatchPersistence); notifyCallback(downloadBatchStatus); DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); return; } downloadBatchStatus.markAsDownloading(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); totalBatchSizeBytes = getTotalSize(downloadFiles); if (totalBatchSizeBytes <= ZERO_BYTES) { Optional<DownloadError> downloadError = Optional.of(new DownloadError(DownloadError.Error.NETWORK_ERROR_CANNOT_DOWNLOAD_FILE)); downloadBatchStatus.markAsError(downloadError, downloadsBatchPersistence); notifyCallback(downloadBatchStatus); return; } for (DownloadFile downloadFile : downloadFiles) { downloadFile.download(fileDownloadCallback); if (batchCannotContinue()) { break; } } if (networkError()) { DownloadsNetworkRecoveryCreator.getInstance().scheduleRecovery(); } callbackThrottle.stopUpdates(); }
Source:
<code>public String getGatewayKeystoreDir() { <START> return getGatewaySecurityDir() + "/keystores"; <END> }</code><technical_language>Paths.get os specific separator</technical_language>

Target:
public String getGatewayKeystoreDir() { return getGatewayKeystorePath().toString(); }
Source:
<code>public void testGetLastInputInfo() throws Exception { LASTINPUTINFO plii = new LASTINPUTINFO(); assertEquals(plii.size(), plii.cbSize); <START> boolean flag = User32.INSTANCE.GetLastInputInfo(plii); <END> assertTrue(flag); assertTrue(Kernel32.INSTANCE.GetTickCount() >= plii.dwTime); assertTrue(plii.dwTime > 0); }</code><technical_language>I nitpicking, please this assertTrue(User32.INSTANCE.GetLastInputInfo(plii)). reason a local flag around, once. expresses intent of test - GetLastInputInfo returns a non-zero succeeds</technical_language>

Target:
public void testGetLastInputInfo() throws Exception { LASTINPUTINFO plii = new LASTINPUTINFO(); assertEquals(plii.size(), plii.cbSize); assertTrue(User32.INSTANCE.GetLastInputInfo(plii)); assertTrue(Kernel32.INSTANCE.GetTickCount() >= plii.dwTime); assertTrue(plii.dwTime > 0); }
Source:
<code>public NetworkCommon(T parameters) { super(parameters); <START> this.setStoragePoolId(getNetwork().getDataCenterId()); <END> }</code><technical_language>changes this line relevant for AddNetworkCommand. Please remove modify: AddNetworkCommand.getPermissionCheckSubjects() getNetwork() instead in a safe way. a follower patch</technical_language>

Target:
public NetworkCommon(T parameters) { super(parameters); }
Source:
<code>public void taskCountUpdates() throws InterruptedException { Meter meter = getMeter(ThreadPoolMonitor.TASK_COUNT); Iterator<Measurement> measurements = meter.measure().iterator(); assertEquals(0.0, measurements.next().value(), 0.0); Cancellable command = new Cancellable(); threadPoolExecutor.execute(command); <START> Thread.sleep(60); <END> PolledMeter.update(registry); measurements = meter.measure().iterator(); assertEquals(1.0, measurements.next().value(), 0.0); command.canceled = true; }</code><technical_language>I prefer avoid of sleep in tests. In experience extremely brittle. A latch work here: java final CountDownLatch latch = new CountDownLatch(1); threadPoolExecutor.execute(latch::countDown); latch.await(5, TimeUnit.SECONDS);</technical_language>

Target:
public void taskCountUpdates() throws InterruptedException { final Counter counter = getCounter(ThreadPoolMonitor.TASK_COUNT); assertEquals(0, counter.count()); final CountDownLatch synchronizer = new CountDownLatch(1); final CountDownLatch terminator = new CountDownLatch(1); final TestRunnable command = new TestRunnable(synchronizer, terminator); latchedExecutor.execute(command); synchronizer.await(6, TimeUnit.SECONDS); PolledMeter.update(registry); assertEquals(1, counter.count(), 0.0); terminator.countDown(); }
Source:
<code>private Duration getTemporalValidationTolerance(ConfigurationState configurationState, Map<String, String> properties) { if ( configurationState instanceof ConfigurationImpl ) { ConfigurationImpl hibernateSpecificConfig = (ConfigurationImpl) configurationState; if ( hibernateSpecificConfig.getTemporalValidationTolerance() != null ) { if ( !Duration.ZERO.equals( hibernateSpecificConfig.getTemporalValidationTolerance() ) ) { LOG.logTemporalValidationTolerance( hibernateSpecificConfig.getTemporalValidationTolerance() ); <START> } <END> return hibernateSpecificConfig.getTemporalValidationTolerance(); } } String temporalValidationToleranceProperty = properties.get( HibernateValidatorConfiguration.TEMPORAL_VALIDATION_TOLERANCE ); if ( temporalValidationToleranceProperty != null ) { try { Duration tolerance = Duration.ofMillis( Long.parseLong( temporalValidationToleranceProperty ) ).abs(); if ( !Duration.ZERO.equals( tolerance ) ) { LOG.logTemporalValidationTolerance( tolerance ); } return tolerance; } catch (Exception e) { throw LOG.getUnableToParseTemporalValidationToleranceException( temporalValidationToleranceProperty, e ); } } return Duration.ZERO; }</code><technical_language>Is null if defined all? If so, consider logging explicitly set remove LOG.logTemporalValidationTolerance( Duration.ZERO ); line below</technical_language>

Target:
private Duration getTemporalValidationTolerance(ConfigurationState configurationState, Map<String, String> properties) { if ( configurationState instanceof ConfigurationImpl ) { ConfigurationImpl hibernateSpecificConfig = (ConfigurationImpl) configurationState; if ( hibernateSpecificConfig.getTemporalValidationTolerance() != null ) { LOG.logTemporalValidationTolerance( hibernateSpecificConfig.getTemporalValidationTolerance() ); return hibernateSpecificConfig.getTemporalValidationTolerance(); } } String temporalValidationToleranceProperty = properties.get( HibernateValidatorConfiguration.TEMPORAL_VALIDATION_TOLERANCE ); if ( temporalValidationToleranceProperty != null ) { try { Duration tolerance = Duration.ofMillis( Long.parseLong( temporalValidationToleranceProperty ) ).abs(); LOG.logTemporalValidationTolerance( tolerance ); return tolerance; } catch (Exception e) { throw LOG.getUnableToParseTemporalValidationToleranceException( temporalValidationToleranceProperty, e ); } } return Duration.ZERO; }
Source:
<code>private void waiterInterruptRoutine() { LOG.debug("Interrupt-cycle interrupting %d waiters/holders: {%s}", Thread.currentThread().getId(), mSharedWaitersAndHolders.size(), mSharedWaitersAndHolders <START> .stream().map((th) -> Long.toString(th.getId())).collect(Collectors.joining(","))); <END> for (Thread th : mSharedWaitersAndHolders) { th.interrupt(); } }</code><technical_language>this accurate, real interrupt in loop below</technical_language>

Target:
private void waiterInterruptRoutine() { List<Thread> interruptedThreads = new ArrayList(mSharedWaitersAndHolders.size()); for (Thread th : mSharedWaitersAndHolders) { th.interrupt(); interruptedThreads.add(th); } LOG.info("Interrupt-cycle interrupted waiters/holders: {}", interruptedThreads.size(), interruptedThreads.stream().map((th) -> ThreadUtils.getThreadIdentifier(th)) .collect(Collectors.joining(","))); }
Source:
<code>private ResponseEntity<Object> indexObjectAndChildren(String id, Boolean inplace) { Map<String, Object> result = new HashMap<>(); result.put("action", "reindex"); result.put("pid", id); PID objectPid = PIDs.get(id); if (inplace == null || inplace) { log.info("Reindexing " + id + ", inplace reindex mode"); } else { log.info("Reindexing " + id + ", clean reindex mode"); } try { indexingService.reindexObjectAndChildren(AgentPrincipals.createFromThread(), objectPid, inplace); } catch (Exception e) { result.put("error", e.getMessage()); Throwable t = e.getCause(); if (t instanceof AuthorizationException || t instanceof AccessRestrictionException) { return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { <START> log.error("Failed to reindex repository due to {}", e); <END> return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }</code><technical_language>"Failed reindex object children"</technical_language>

Target:
private ResponseEntity<Object> indexObjectAndChildren(String id, Boolean inplace) { Map<String, Object> result = new HashMap<>(); result.put("action", "reindex"); result.put("pid", id); PID objectPid = PIDs.get(id); if (inplace == null || inplace) { log.info("Reindexing " + id + ", inplace reindex mode"); } else { log.info("Reindexing " + id + ", clean reindex mode"); } try { indexingService.reindexObjectAndChildren(AgentPrincipals.createFromThread(), objectPid, inplace); } catch (Exception e) { result.put("error", e.getMessage()); if (e instanceof AuthorizationException || e instanceof AccessRestrictionException) { return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); } else { log.error("Failed to reindex object and its children", id, e); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } } result.put("timestamp", System.currentTimeMillis()); return new ResponseEntity<>(result, HttpStatus.OK); }
Source:
<code>public void test_ringBuffer() throws Exception { ReadWriteBuffer<Integer> buffer = new RingBuffer<>(2); assertThat(buffer.isEmpty(), equalTo(true)); assertThat(buffer.size(), equalTo(0)); assertThat(buffer.read(), equalTo(null)); assertThat(buffer.stream().count(), equalTo(0L)); buffer.put(1); buffer.put(2); assertThat(buffer.isEmpty(), equalTo(false)); assertThat(buffer.size(), equalTo(2)); buffer.put(3); assertThat(buffer.size(), equalTo(2)); assertThat(buffer.read(), equalTo(2)); assertThat(buffer.size(), equalTo(1)); assertThat(buffer.read(), equalTo(3)); assertThat(buffer.isEmpty(), equalTo(true)); assertThat(buffer.size(), equalTo(0)); <START> <END> assertThat(buffer.read(), equalTo(null)); }</code><technical_language>buffer.put(1); buffer.put(2); assertThat(buffer.size(), equalTo(2)); List<Integer> collect = buffer.stream().collect(Collectors.toList()); assertThat(collect.get(0), equalTo(1)); assertThat(collect.get(1), equalTo(2)); // stream consumed once, calling buffer returns empty stream assertThat(buffer.stream().count(), equalTo(0L));</technical_language>

Target:
public void test_ringBuffer() throws Exception { ReadWriteBuffer<Integer> buffer = new RingBuffer<>(2); assertThat(buffer.isEmpty(), equalTo(true)); assertThat(buffer.size(), equalTo(0)); assertThat(buffer.read(), equalTo(null)); assertThat(buffer.stream().count(), equalTo(0L)); buffer.put(1); buffer.put(2); assertThat(buffer.isEmpty(), equalTo(false)); assertThat(buffer.size(), equalTo(2)); buffer.put(3); assertThat(buffer.size(), equalTo(2)); assertThat(buffer.read(), equalTo(2)); assertThat(buffer.size(), equalTo(1)); assertThat(buffer.read(), equalTo(3)); assertThat(buffer.isEmpty(), equalTo(true)); assertThat(buffer.size(), equalTo(0)); assertThat(buffer.read(), equalTo(null)); buffer.put(1); buffer.put(2); assertThat(buffer.size(), equalTo(2)); List<Integer> collect = buffer.stream().collect(Collectors.toList()); assertThat(collect.get(0), equalTo(1)); assertThat(collect.get(1), equalTo(2)); assertThat(buffer.stream().count(), equalTo(0L)); }
Source:
<code>public void testNullHeaderMateReferenceIndex() { SAMRecord sam = new SAMRecordSetBuilder().addFrag("test", 0, 1, false, false, "3S9M", null, 2); final SAMFileHeader header = sam.getHeader(); sam.setHeader(null); sam.setMateReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); Assert.assertTrue(sam.getMateReferenceIndex().equals(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX)); Assert.assertTrue(sam.getMateReferenceName().equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME)); sam = new SAMRecordSetBuilder().addFrag("test", 0, 1, false, false, "3S9M", null, 2); sam.setHeader(null); sam.setMateReferenceName(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME); Assert.assertTrue(sam.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); sam = new SAMRecord(null); Assert.assertTrue(sam.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); sam = new SAMRecord(null); final String unresolvableRefName = "unresolvable"; <START> sam.setMateReferenceName(unresolvableRefName); <END> sam.setHeader(header); Assert.assertTrue(sam.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); }</code><technical_language>Check of mMateReferenceIndex this point, advantage of protected access</technical_language>

Target:
public void testNullHeaderMateReferenceIndex() { SAMRecord sam = createTestRecordHelper(); final SAMFileHeader samHeader = sam.getHeader(); sam.setMateReferenceName("chr1"); int originalMateRefIndex = sam.getMateReferenceIndex(); Assert.assertTrue(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX != originalMateRefIndex); sam.setHeader(null); Assert.assertTrue(null == sam.mMateReferenceIndex); sam.setHeader(samHeader); Assert.assertTrue(sam.getMateReferenceIndex().equals(originalMateRefIndex)); sam.setHeader(null); sam.setMateReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); Assert.assertTrue(sam.getMateReferenceIndex().equals(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX)); Assert.assertTrue(sam.getMateReferenceName().equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME)); sam = new SAMRecord(null); Assert.assertTrue(null == sam.mMateReferenceIndex); Assert.assertTrue(sam.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); final String unresolvableRefName = "unresolvable"; sam.setMateReferenceName(unresolvableRefName); sam.setHeader(samHeader); Assert.assertTrue(null == sam.mMateReferenceIndex); Assert.assertTrue(sam.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX); }
Source:
<code>void postCommandsInBulk() { final Command first = newCommand(); final Command second = newCommand(); final List<Command> commands = newArrayList(first, second); commandBus.unregister(createProjectHandler); commandBus.register(createProjectHandler); final CommandBus spy = spy(commandBus); <START> spy.post(commands, StreamObservers.memoizingObserver()); <END> @SuppressWarnings("unchecked") final ArgumentCaptor<Iterable<Command>> storingCaptor = forClass(Iterable.class); verify(spy).store(storingCaptor.capture()); final Iterable<Command> storingArgs = storingCaptor.getValue(); assertSize(commands.size(), storingArgs); assertContainsAll(storingArgs, first, second); final ArgumentCaptor<CommandEnvelope> postingCaptor = forClass(CommandEnvelope.class); verify(spy, times(2)).doPost(postingCaptor.capture()); final List<CommandEnvelope> postingArgs = postingCaptor.getAllValues(); assertSize(commands.size(), postingArgs); assertEquals(commands.get(0), postingArgs.get(0).getCommand()); assertEquals(commands.get(1), postingArgs.get(1).getCommand()); commandBus.unregister(createProjectHandler); }</code><technical_language>This imported statically, if I mistaken</technical_language>

Target:
void postCommandsInBulk() { final Command first = newCommand(); final Command second = newCommand(); final List<Command> commands = newArrayList(first, second); commandBus.unregister(createProjectHandler); commandBus.register(createProjectHandler); final CommandBus spy = spy(commandBus); spy.post(commands, memoizingObserver()); @SuppressWarnings("unchecked") final ArgumentCaptor<Iterable<Command>> storingCaptor = forClass(Iterable.class); verify(spy).store(storingCaptor.capture()); final Iterable<Command> storingArgs = storingCaptor.getValue(); assertSize(commands.size(), storingArgs); assertContainsAll(storingArgs, first, second); final ArgumentCaptor<CommandEnvelope> postingCaptor = forClass(CommandEnvelope.class); verify(spy, times(2)).doPost(postingCaptor.capture()); final List<CommandEnvelope> postingArgs = postingCaptor.getAllValues(); assertSize(commands.size(), postingArgs); assertEquals(commands.get(0), postingArgs.get(0).getCommand()); assertEquals(commands.get(1), postingArgs.get(1).getCommand()); commandBus.unregister(createProjectHandler); }