auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public JsonElement serialize(Arguments arguments, Type type, JsonSerializationContext context) { JsonObject root = new JsonObject(); if (arguments.game != null) { JsonArray gameArguments = new JsonArray(); arguments.game.forEach(arg -> { if (arg.rules != null) { JsonObject object = new JsonObject(); object.add("rules", Gsons.MINECRAFT.toJsonTree(arg.rules)); if (arg.value instanceof String) { object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); } else if (arg.value instanceof List) { object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); } gameArguments.add(object); } else { gameArguments.add((String) arg.value); } }); root.add("game", gameArguments); } if (arguments.jvm != null) { JsonArray jvmArguments = new JsonArray(); arguments.jvm.forEach(arg -> { if (arg.rules != null) { JsonObject object = new JsonObject(); object.add("rules", Gsons.MINECRAFT.toJsonTree(arg.rules)); if (arg.value instanceof String) { object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); <START> } else if (arg.value instanceof List) { <END> object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); } jvmArguments.add(object); } else { jvmArguments.add((String) arg.value); } }); root.add("jvm", jvmArguments); } return root; }</code><technical_language>this work cast? If so, combine instance of checks in if else if a single if content of block is if need cast</technical_language>

Target:
public JsonElement serialize(Arguments arguments, Type type, JsonSerializationContext context) { JsonObject root = new JsonObject(); if (arguments.game != null) { JsonArray gameArguments = new JsonArray(); arguments.game.forEach(arg -> { if (arg.rules != null) { JsonObject object = new JsonObject(); object.add("rules", Gsons.MINECRAFT.toJsonTree(arg.rules)); if (arg.value instanceof String || arg.value instanceof List) { object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); } gameArguments.add(object); } else { gameArguments.add((String) arg.value); } }); root.add("game", gameArguments); } if (arguments.jvm != null) { JsonArray jvmArguments = new JsonArray(); arguments.jvm.forEach(arg -> { if (arg.rules != null) { JsonObject object = new JsonObject(); object.add("rules", Gsons.MINECRAFT.toJsonTree(arg.rules)); if (arg.value instanceof String || arg.value instanceof List) { object.add("value", Gsons.MINECRAFT.toJsonTree(arg.value)); } jvmArguments.add(object); } else { jvmArguments.add((String) arg.value); } }); root.add("jvm", jvmArguments); } return root; }
Source:
<code>protected static Object getDelegateFromUnmodifiableNavigableSet(NavigableSet<?> object) { try { Class<?> clazz = Class.forName(Sets.class.getCanonicalName() + "$UnmodifiableNavigableSet"); Field field = clazz.getDeclaredField("delegate"); <START> field.setAccessible(true); <END> return field.get(object); } catch (IllegalArgumentException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } catch (IllegalAccessException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } catch (ClassNotFoundException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } catch (SecurityException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } catch (NoSuchFieldException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } }</code><technical_language>This field resolved cached construction time done write</technical_language>

Target:
protected Object getDelegateFromUnmodifiableNavigableSet(NavigableSet<?> object) { try { return delegate.get(object); } catch (IllegalArgumentException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } catch (IllegalAccessException e) { throw new RuntimeException("Issues reflectively writing UnmodifiableNavigableSet", e); } }
Source:
<code>public void clear() { clearSocialLoginToken(); setSubtitleLanguage(null); <START> setPlaybackSpeed(1.0f); <END> pref.put(PrefManager.Key.PROFILE_JSON, null); pref.put(PrefManager.Key.AUTH_JSON, null); EdxCookieManager.getSharedInstance(MainApplication.instance()).clearWebWiewCookie(); }</code><technical_language>1.0f a constant somewhere</technical_language>

Target:
public void clear() { clearSocialLoginToken(); setSubtitleLanguage(null); saveDefaultPlaybackSpeed(VideoPlaybackSpeed.NORMAL.getSpeedValue()); pref.put(PrefManager.Key.PROFILE_JSON, null); pref.put(PrefManager.Key.AUTH_JSON, null); EdxCookieManager.getSharedInstance(MainApplication.instance()).clearWebWiewCookie(); }
Source:
<code>@Test public void withImports() throws IOException { ClassWriter classWriter = ClassWriter.forClassName(className); classWriter.addField(threadName, "thread"); ConstructorWriter constructorWriter = classWriter.addConstructor(); AnonymousClassWriter threadWriter = AnonymousClassWriter.forClassName(threadName); FieldWriter threadListField = threadWriter.addField( ParameterizedTypeName.create(List.class, ClassName.fromClass(String.class)), "list"); threadListField.setInitializer("%s.asList(\"Hello World\")", ClassName.fromClass(Arrays.class)); MethodWriter threadStartMethod = threadWriter.addMethod(void.class, "start"); threadStartMethod.annotate(Override.class); threadStartMethod.addModifiers(PUBLIC); threadStartMethod.body().addSnippet("System.out.println(list.get(0));"); constructorWriter.body().addSnippet("thread = %s;", threadWriter); StringBuilder stringBuilder = new StringBuilder(); <START> assertThat(classWriter.writeTypeToAppendable(stringBuilder).toString()).isEqualTo("" <END> + "package com.foo;\n" + "\n" + "import java.util.Arrays;\n" + "import java.util.List;\n" + "\n" + "class Bar {\n" + " Thread thread;\n" + "\n" + " Bar() {\n" + " thread = new Thread() {\n" + " List<String> list = Arrays.asList(\"Hello World\");\n" + "\n" + " @Override\n" + " public void start() {\n" + " System.out.println(list.get(0));\n" + " }\n" + " };\n" + " }\n" + "}\n"); }</code><technical_language>Writeables.writeToString</technical_language>

Target:
@Test public void withImports() throws IOException { ClassWriter classWriter = ClassWriter.forClassName(className); classWriter.addField(threadName, "thread"); ConstructorWriter constructorWriter = classWriter.addConstructor(); AnonymousClassWriter threadWriter = AnonymousClassWriter.forClassName(threadName); FieldWriter threadListField = threadWriter.addField( ParameterizedTypeName.create(List.class, ClassName.fromClass(String.class)), "list"); threadListField.setInitializer("%s.asList(\"Hello World\")", ClassName.fromClass(Arrays.class)); MethodWriter threadStartMethod = threadWriter.addMethod(void.class, "start"); threadStartMethod.annotate(Override.class); threadStartMethod.addModifiers(PUBLIC); threadStartMethod.body().addSnippet("System.out.println(list.get(0));"); constructorWriter.body().addSnippet("thread = %s;", threadWriter); assertThat(classWriter.toString()).isEqualTo("" + "package com.foo;\n" + "\n" + "import java.util.Arrays;\n" + "import java.util.List;\n" + "\n" + "class Bar {\n" + " Thread thread;\n" + "\n" + " Bar() {\n" + " thread = new Thread() {\n" + " List<String> list = Arrays.asList(\"Hello World\");\n" + "\n" + " @Override\n" + " public void start() {\n" + " System.out.println(list.get(0));\n" + " }\n" + " };\n" + " }\n" + "}\n"); }
Source:
<code>protected boolean validateRawCoordinates() { if (rawGeometryCoordinates.length != 3) { <START> log.error("Invalid arc geometry. Arc must be represented by 3 points in GML."); <END> return false; } return true; }</code><technical_language>a note - decided 3 point representation for interpolation, fine, class is GML specific representation neither, I remove GML reference here</technical_language>

Target:
protected boolean validateRawCoordinates() { if (rawGeometryCoordinates.length != 3) { log.error("Invalid arc geometry. Arc must be represented by 3 points."); return false; } return true; }
Source:
<code>public void start(Set<File> files, Consumer<Set<File>> callback) { if (isStarted()) { throw new IllegalStateException("start() should not be called more than once"); } Preconditions.checkArgument(files.size() > 0, "must specify at least 1 file to watch for changes"); this.callback = requireNonNull(callback); <START> watchedFiles = ImmutableSet.copyOf(files); <END> executorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1)); future = executorService.scheduleAtFixedRate( this::scanFilesForChanges, initialDelay, interval, timeUnit); }</code><technical_language>slightly form i guess copy files first, check size of copy > 0</technical_language>

Target:
@Override public void start(Set<File> files, Consumer<Set<File>> callback) { if (isStarted()) { throw new IllegalStateException("start() should not be called more than once"); } Set<File> filesCopy = ImmutableSet.copyOf(files); Preconditions.checkArgument(filesCopy.size() > 0, "must specify at least 1 file to watch for changes"); this.callback = requireNonNull(callback); watchedFiles = filesCopy; executorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1)); future = executorService.scheduleAtFixedRate( this::scanFilesForChanges, initialDelay, interval, timeUnit); }
Source:
<code>public void start(List<PluginWrapper> plugins) throws Exception { <START> try (ACLContext context = ACL.as(ACL.SYSTEM)) { <END> Map<String, PluginWrapper> pluginsByName = plugins.stream().collect(Collectors.toMap(p1 -> p1.getShortName(), p -> p)); for (PluginWrapper depender : this.plugins) { if (plugins.contains(depender)) { continue; } for (Dependency d : depender.getOptionalDependencies()) { PluginWrapper dependee = pluginsByName.get(d.shortName); if (dependee != null) { getPluginStrategy().updateDependency(depender, dependee); break; } } } Jenkins.get().refreshExtensions(); for (PluginWrapper p : plugins) { p.getPlugin().postInitialize(); } Reactor r = new Reactor(InitMilestone.ordering()); Set<ClassLoader> loaders = plugins.stream().map(p -> p.classLoader).collect(Collectors.toSet()); r.addAll(new InitializerFinder(uberClassLoader) { @Override protected boolean filter(Method e) { return !loaders.contains(e.getDeclaringClass().getClassLoader()) || super.filter(e); } }.discoverTasks(r)); new InitReactorRunner().run(r); resolveDependentPlugins(); try { Jenkins.get().refreshExtensions(); } catch (ExtensionRefreshException e) { throw new IOException("Failed to refresh extensions after installing some plugins", e); } } }</code><technical_language>For other reviewers: **Hide whitespace changes**</technical_language>

Target:
public void start(List<PluginWrapper> plugins) throws Exception { try (ACLContext context = ACL.as(ACL.SYSTEM)) { Map<String, PluginWrapper> pluginsByName = plugins.stream().collect(Collectors.toMap(p -> p.getShortName(), p -> p)); for (PluginWrapper depender: this.plugins) { if (plugins.contains(depender)) { continue; } for (Dependency d: depender.getOptionalDependencies()) { PluginWrapper dependee = pluginsByName.get(d.shortName); if (dependee != null) { getPluginStrategy().updateDependency(depender, dependee); break; } } } resolveDependentPlugins(); try { Jenkins.get().refreshExtensions(); } catch (ExtensionRefreshException e) { throw new IOException("Failed to refresh extensions after installing some plugins", e); } for (PluginWrapper p : plugins) { p.getPlugin().postInitialize(); } Reactor r = new Reactor(InitMilestone.ordering()); Set<ClassLoader> loaders = plugins.stream().map(p -> p.classLoader).collect(Collectors.toSet()); r.addAll(new InitializerFinder(uberClassLoader) { @Override protected boolean filter(Method e) { return !loaders.contains(e.getDeclaringClass().getClassLoader()) || super.filter(e); } }.discoverTasks(r)); new InitReactorRunner().run(r); } }
Source:
<code>public void fireCallback(final ClientCallback call) { try { call.setMessageId(messageId++); callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { ex.printStackTrace(); UserManager.getInstance().getUser(userId).ifPresent(user-> { <START> logger.warn("SESSION CALLBACK EXCEPTION - " + (user != null ? user.getName() : "") + " userId " + userId); <END> logger.warn(" - method: " + call.getMethod()); logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.trace("Stack trace:", ex); userLostConnection(); }); } }</code><technical_language>this is executed now, if a user is present, user check != null longer sense</technical_language>

Target:
public void fireCallback(final ClientCallback call) { try { call.setMessageId(messageId++); callbackHandler.handleCallbackOneway(new Callback(call)); } catch (HandleCallbackException ex) { ex.printStackTrace(); UserManager.getInstance().getUser(userId).ifPresent(user-> { logger.warn("SESSION CALLBACK EXCEPTION - " + user.getName() + " userId " + userId); logger.warn(" - method: " + call.getMethod()); logger.warn(" - cause: " + getBasicCause(ex).toString()); logger.trace("Stack trace:", ex); userLostConnection(); }); } }
Source:
<code>JWTProcessor<SecurityContext> processor() { ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations); JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource)); jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); <START> jwtProcessorCustomizer.accept(jwtProcessor); <END> return jwtProcessor; }</code><technical_language>For consistency rest of code here, please prefix member variable references this.</technical_language>

Target:
JWTProcessor<SecurityContext> processor() { ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations); JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource)); jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); this.jwtProcessorCustomizer.accept(jwtProcessor); return jwtProcessor; }
Source:
<code>public List<GridColumn.HeaderMetaData> makeHeaderMetaData(final BaseColumn column) { <START> final ArrayList<GridColumn.HeaderMetaData> result = new ArrayList<>(); result.add(new BaseHeaderMetaData(GuidedDecisionTableConstants.INSTANCE.RuleName(), RuleNameColumn.class.getName())); <END> return result; }</code><technical_language>is general practice declare variables general type, singletoneList, WDYT? java final List<GridColumn.HeaderMetaData> result = Collections.singletonList(new BaseHeaderMetaData(GuidedDecisionTableConstants.INSTANCE.RuleName(), RuleNameColumn.class.getName()));</technical_language>

Target:
public List<GridColumn.HeaderMetaData> makeHeaderMetaData(final BaseColumn column) { return Collections.singletonList(new BaseHeaderMetaData(GuidedDecisionTableConstants.INSTANCE.RuleName(), RuleNameColumn.class.getName())); }
Source:
<code>public boolean canRestartModule(IModule[] module) { <START> if( module.length == 1 ) <END> return true; return false; }</code><technical_language>module[0] == null considered</technical_language>

Target:
public boolean canRestartModule(IModule[] module) { if( module.length == 1 && module[0] != null) return true; return false; }
Source:
<code>public void setWatchEvents(WatchEventType... watchEvents) { <START> Assert.notEmpty(watchEvents, "'watchEvents' must not be empty."); <END> this.watchEvents = watchEvents; }</code><technical_language>Assert.noNullElements() Assert.state(!this.running, "Cannot change watch events while running")</technical_language>

Target:
public void setWatchEvents(WatchEventType... watchEvents) { Assert.notEmpty(watchEvents, "'watchEvents' must not be empty."); Assert.noNullElements(watchEvents, "'watchEvents' must not contain null elements."); Assert.state(!this.running, "Cannot change watch events while running."); this.watchEvents = Arrays.copyOf(watchEvents, watchEvents.length); }
Source:
<code>public void execute(Context context) throws SQLException { String builtInQGUuid = context.prepareSelect("select uuid from quality_gates where is_built_in = ?") .setBoolean(1, true) .get(row -> row.getString(1)); if (builtInQGUuid == null) { throw new IllegalStateException("Unable to find the builtin quality gate"); <START> } <END> MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select uuid from organizations " + " where default_quality_gate_uuid is null"); massUpdate.rowPluralName("organizations"); massUpdate.update("update organizations set default_quality_gate_uuid = ?, updated_at=? where uuid = ?"); massUpdate.execute((row, update) -> { update.setString(1, builtInQGUuid); update.setLong(2, system2.now()); update.setString(3, row.getString(1)); return true; }); }</code><technical_language>Replace lines Preconditions.checkState(builtInQGUuid != null, "Unable find builtin quality gate");</technical_language>

Target:
public void execute(Context context) throws SQLException { List<String> builtInQGUuids = context.prepareSelect("select uuid from quality_gates where is_built_in = ?") .setBoolean(1, true) .list(row -> row.getString(1)); checkState(!builtInQGUuids.isEmpty(), "Unable to find the builtin quality gate"); checkState(builtInQGUuids.size() == 1, "There are too many built in quality gates, one and only one is expected"); final long now = system2.now(); MassUpdate massUpdate = context.prepareMassUpdate(); massUpdate.select("select uuid from organizations " + " where default_quality_gate_uuid is null"); massUpdate.rowPluralName("organizations"); massUpdate.update("update organizations set default_quality_gate_uuid = ?, updated_at=? where uuid = ?"); massUpdate.execute((row, update) -> { update.setString(1, builtInQGUuids.get(0)); update.setLong(2, now); update.setString(3, row.getString(1)); return true; }); }
Source:
<code>private void setAddPreferencesFromResourceBlock() { JMethod method = getGeneratedClass().method(PUBLIC, codeModel().VOID, "addPreferencesFromResource"); method.annotate(Override.class); JVar preferencesResIdParam = method.param(int.class, "preferencesResId"); method.body().invoke(JExpr._super(), "addPreferencesFromResource").arg(preferencesResIdParam); addPreferencesFromResourceBlock = method.body(); <START> addPreferencesFromResourceBlockBeforeInject = addPreferencesFromResourceBlock.blockSimple(); END> }</code><technical_language>I implement this in #1585</technical_language>

Target:
private void setAddPreferencesFromResourceBlock() { JMethod method = getGeneratedClass().method(PUBLIC, codeModel().VOID, "addPreferencesFromResource"); method.annotate(Override.class); JVar preferencesResIdParam = method.param(int.class, "preferencesResId"); method.body().invoke(JExpr._super(), "addPreferencesFromResource").arg(preferencesResIdParam); addPreferencesFromResourceInjectionBlock = method.body().blockVirtual(); addPreferencesFromResourceAfterInjectionBlock = method.body().blockVirtual(); }
Source:
<code>public boolean add(NonTerminal newNT) { <START> if (startNonTerminals.containsKey(newNT.nonTerminalId)) { <END> return false; } else { startNonTerminals.put(newNT.nonTerminalId, newNT); return true; } }</code><technical_language>I NonTerminal contains a NonTerminalId field, a Map<NonTerminalId, NonTerminal>. stops Map connecting NonTerminalId a NonTerminal a NonTerminalId? If want maintain a bijection NonTerminals Ids, maintain bijection in place, a BiMap, authoritative source for ID information. this class implement BiMap..</technical_language>

Target:
public boolean add(NonTerminal newNT) { if (startNonTerminals.containsKey(newNT.name)) { return false; } else { startNonTerminals.put(newNT.name, newNT); return true; } }
Source:
<code>public VDSReturnValue get(long timeout, TimeUnit unit) throws TimeoutException { try { status = new StatusOnlyReturnForXmlRpc(httpTask.get(timeout, unit)); proceedProxyReturnValue(); } catch (TimeoutException e) { httpTask.cancel(true); VDSNetworkException ex = new VDSNetworkException("Timeout during xml-rpc call"); ex.setVdsError(new VDSError(EngineError.VDS_NETWORK_ERROR, "Timeout during xml-rpc call")); setVdsRuntimeError(ex); log.error("Timeout waiting for VDSM response: {}", e.getMessage()); log.debug("Exception", e); throw e; } catch (VDSNetworkException e) { <START> setVdsRuntimeError(e); <END> if (!"Policy reset".equals(e.getVdsError().getMessage())) { log.error("Error: {}", e.getMessage()); log.error("Exception", e); } else { log.info("Policy reset required for network reconfiguration"); } } catch (Exception e) { log.error("Error: {}", e.getMessage()); log.error("Exception", e); setVdsRuntimeError(e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e)); } return getVDSReturnValue(); }</code><technical_language>FutureVDSCommand extends VdsBrokerCommand, a protected method VdsBrokerCommand.isPolicyResetMessage(str) in cases instead of repeating condition hard-coded string. also, reverse condition (positive first)</technical_language>

Target:
public VDSReturnValue get(long timeout, TimeUnit unit) throws TimeoutException { try { status = new StatusOnlyReturnForXmlRpc(httpTask.get(timeout, unit)); proceedProxyReturnValue(); } catch (TimeoutException e) { httpTask.cancel(true); VDSNetworkException ex = new VDSNetworkException("Timeout during xml-rpc call"); ex.setVdsError(new VDSError(EngineError.VDS_NETWORK_ERROR, "Timeout during xml-rpc call")); setVdsRuntimeError(ex); log.error("Timeout waiting for VDSM response: {}", e.getMessage()); log.debug("Exception", e); throw e; } catch (VDSNetworkException e) { setVdsRuntimeError(e); if (isPolicyResetMessage(e.getVdsError().getMessage())) { log.info("Policy reset required for network reconfiguration"); } else { log.error("Error: {}", e.getMessage()); log.error("Exception", e); } } catch (Exception e) { log.error("Error: {}", e.getMessage()); log.error("Exception", e); setVdsRuntimeError(e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e)); } return getVDSReturnValue(); }
Source:
<code>public void testGetSWTColor() { <START> Color result = getSWTColor(colorValue("red"), display); <END> assertNotNull(result); assertEquals(255, result.getRed()); assertEquals(0, result.getBlue()); assertEquals(0, result.getGreen()); }</code><technical_language>In this class colors created, disposed end</technical_language>

Target:
public void testGetSWTColor() { result = getSWTColor(colorValue("red"), display); assertNotNull(result); assertEquals(255, result.getRed()); assertEquals(0, result.getBlue()); assertEquals(0, result.getGreen()); }
Source:
<code>public String getUserAgent() { if(userAgent == null) { String ua = this.getUserAgentFromResource(); if(Misc.isRunningOnAndroid()) { try { Class c = Class.forName("android.os.Build$VERSION"); String codename = (String)c.getField("CODENAME").get(null); int sdkInt = c.getField("SDK_INT").getInt(null); userAgent = String.format("%s Android %s %d", ua, codename, sdkInt); } catch (Exception e) { <START> userAgent = "?"; <END> } } else { userAgent = String.format("%s (%s; %s; %s)", ua, System.getProperty("os.arch"), System.getProperty("os.name"), System.getProperty("os.version")); } } return userAgent; }</code><technical_language>This more descriptive, useful in logs. String.format("%s Android Unknown Version", ua);</technical_language>

Target:
public String getUserAgent() { if(userAgent == null) { String ua = this.getUserAgentFromResource(); if(Misc.isRunningOnAndroid()) { try { Class c = Class.forName("android.os.Build$VERSION"); String codename = (String)c.getField("CODENAME").get(null); int sdkInt = c.getField("SDK_INT").getInt(null); userAgent = String.format("%s Android %s %d", ua, codename, sdkInt); } catch (Exception e) { userAgent = String.format("%s Android unknown version", ua); } } else { userAgent = String.format("%s (%s; %s; %s)", ua, System.getProperty("os.arch"), System.getProperty("os.name"), System.getProperty("os.version")); } } return userAgent; }
Source:
<code>void testVerifierEnabled() throws InterruptedException { TestVerifier verifier = new TestVerifier(true); ExecutorService executorService = Executors.newSingleThreadExecutor(); DarkClusterVerifierManager verifierManager = new DarkClusterVerifierManagerImpl(verifier, executorService); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("foo")).build(); RestResponse res = new RestResponseBuilder().build(); verifierManager.onDarkResponse(dummyRestRequest, res, DARK_CLUSTER1_NAME); verifierManager.onDarkResponse(dummyRestRequest, res, DARK_CLUSTER1_NAME); verifierManager.onResponse(dummyRestRequest, res); <START> final CountDownLatch latch = new CountDownLatch(1); <END> Runnable myCallable = latch::countDown; executorService.submit(myCallable); if (!latch.await(30, TimeUnit.SECONDS)) { fail("unable to execute task on executor"); } Assert.assertEquals(verifier.onResponseCount, 1, "expected on response count of 1"); Assert.assertEquals(verifier.onDarkResponseCount, 2, "expected on dark response count of 2"); }</code><technical_language>extract out private method reduce duplicate code</technical_language>

Target:
public void testVerifierEnabled() throws InterruptedException { setup(true); RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("foo")).build(); RestResponse res = new RestResponseBuilder().build(); _verifierManager.onDarkResponse(dummyRestRequest, res, DARK_CLUSTER1_NAME); _verifierManager.onDarkResponse(dummyRestRequest, res, DARK_CLUSTER1_NAME); _verifierManager.onResponse(dummyRestRequest, res); waitForLatch(); Assert.assertEquals(_verifier.onResponseCount, 1, "expected on response count of 1"); Assert.assertEquals(_verifier.onDarkResponseCount, 2, "expected on dark response count of 2"); }
Source:
<code>private void postInitTemplate(List<VmTemplate> templates) { List<VmTemplate> baseWithoutBlank = filterOutBlank(keepBaseTemplates(templates)); if (baseWithoutBlank.isEmpty()) { <START> getModel().getIsSubTemplate().setEntity(false); <END> getModel().getIsSubTemplate().setIsChangeable(false, constants.someNonDefaultTemplateHasToExistFirst()); return; } getModel().getIsSubTemplate().setEntity(false); getModel().getIsSubTemplate().setIsChangeable(true); VmTemplate currentTemplate = Linq.firstOrDefault(templates, new Linq.TemplatePredicate(vm.getVmtGuid())); getModel().getBaseTemplate().setItems(baseWithoutBlank); getModel().getBaseTemplate().setSelectedItem(Linq.firstOrDefault(baseWithoutBlank, new Linq.TemplatePredicate(currentTemplate.getBaseTemplateId()))); }</code><technical_language>this line 206 - move of if</technical_language>

Target:
private void postInitTemplate(List<VmTemplate> templates) { List<VmTemplate> baseWithoutBlank = filterOutBlank(keepBaseTemplates(templates)); getModel().getIsSubTemplate().setEntity(false); if (baseWithoutBlank.isEmpty()) { getModel().getIsSubTemplate().setIsChangeable(false, constants.someNonDefaultTemplateHasToExistFirst()); return; } getModel().getIsSubTemplate().setIsChangeable(true); VmTemplate currentTemplate = Linq.firstOrDefault(templates, new Linq.TemplatePredicate(vm.getVmtGuid())); getModel().getBaseTemplate().setItems(baseWithoutBlank); getModel().getBaseTemplate().setSelectedItem(Linq.firstOrDefault(baseWithoutBlank, new Linq.TemplatePredicate(currentTemplate.getBaseTemplateId()))); }
Source:
<code>public String getFriendlyCategoryName(){ switch (this.dataverseType) { <START> case RESEARCHERS: <END> return BundleUtil.getStringFromBundle("dataverse.type.selectTab.researchers", null , "en"); case RESEARCH_PROJECTS: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.researchProjects",null, "en"); case JOURNALS: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.journals", null, "en"); case ORGANIZATIONS_INSTITUTIONS: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.organizationsAndInsitutions",null, "en"); case TEACHING_COURSES: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.teachingCourses",null, "en"); case LABORATORY: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.laboratory",null, "en"); case RESEARCH_GROUP: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.researchGroup",null, "en"); case DEPARTMENT: return BundleUtil.getStringFromBundle("dataverse.type.selectTab.department",null, "en"); case UNCATEGORIZED: return uncategorizedString; default: return ""; } }</code><technical_language>need careful this (and other changes in this PR) places in app do want localized version. change getIndexableCategoryName instead? (ideally, this call method, pass parameters get localized default)</technical_language>

Target:
public String getFriendlyCategoryName(){ String key = getFriendlyCategoryKey(); return BundleUtil.getStringFromBundle(key); }
Source:
<code>public static CommitMessageComponentState loadState(Repository repository) { IDialogSettings dialogSettings = getDialogSettings(); String[] values = dialogSettings.getArray(repository.getDirectory() .getAbsolutePath()); if (values == null || values.length < MEMBER_COUNT_WITHOUT_CARET_POSITION) { return null; } CommitMessageComponentState state = new CommitMessageComponentState(); state.setAmend(Boolean.parseBoolean(values[0])); state.setAuthor(values[1]); state.setCommitMessage(values[2]); state.setCommitter(values[3]); state.setHeadCommit(ObjectId.fromString(values[4])); if (values.length <START> == MEMBER_COUNT) <END> { state.setCaretPosition(Integer.parseInt(values[5])); } else if (values.length == MEMBER_COUNT_WITHOUT_CARET_POSITION) { state.setCaretPosition( CommitMessageComponentState.CARET_DEFAULT_POSITION); } return state; }</code><technical_language>= . caret position set if this is extended additional fields</technical_language>

Target:
public static CommitMessageComponentState loadState(Repository repository) { IDialogSettings dialogSettings = getDialogSettings(); String[] values = dialogSettings.getArray(repository.getDirectory() .getAbsolutePath()); if (values == null || values.length < MEMBER_COUNT_WITHOUT_CARET_POSITION) { return null; } CommitMessageComponentState state = new CommitMessageComponentState(); state.setAmend(Boolean.parseBoolean(values[0])); state.setAuthor(values[1]); state.setCommitMessage(values[2]); state.setCommitter(values[3]); state.setHeadCommit(ObjectId.fromString(values[4])); if (values.length >= MEMBER_COUNT) { state.setCaretPosition(Integer.parseInt(values[5])); } else { state.setCaretPosition( CommitMessageComponentState.CARET_DEFAULT_POSITION); } return state; }
Source:
<code>public Map<String, Object> getBackendHints() { <START> return null; <END> }</code><technical_language>For compatibility, return empty map instead? This NPE for older code, while compiles</technical_language>

Target:
public Map<String, Object> getBackendHints() { return Collections.emptyMap(); }
Source:
<code>public void createTest() { Item milk = createMilk(); <START> assertEquals("milk-bottle", milk.getId()); <END> assertEquals("milk", milk.getName()); assertEquals("Milk in a bottle", milk.getDescription()); assertEquals(Integer.valueOf(1), milk.getWeight()); }</code><technical_language>item id "milk-bottle". standard id name is (1 letter type)(3 letter identifier)(level), milk is fmil1. Type is broken f - food, w - weapon, a - armour, p - potion</technical_language>

Target:
public void createTest() { Item milk = createMilk(); assertEquals("fmil1", milk.getId()); assertEquals("milk", milk.getName()); assertEquals("Milk in a bottle", milk.getDescription()); assertEquals(Integer.valueOf(1), milk.getWeight()); }
Source:
<code>public void calculateScrollWidth() { if (scrollbar.isAttached()) { <START> double plotWidth = simplePlot.getOffsetWidth() - simplePlot.getOptions().getYAxisOptions().getLabelWidth() - 4; <END> double visibleRange = simplePlot.getAxes().getX().getMaximumValue() - simplePlot.getAxes().getX().getMinimumValue(); double ratio = maxRange / visibleRange; scrollbar.setScrollWidth((int) (plotWidth * ratio)); } }</code><technical_language>hard coded numbers - pain in future :-). Please replace constant</technical_language>

Target:
public void calculateScrollWidth() { if (scrollbar.isAttached()) { double plotWidth = getPlotWidth() - TOTAL_BORDERS_WIDTH; double visibleRange = getVisibleRange(); double ratio = maxRange / visibleRange; scrollbar.setScrollWidth((int) (plotWidth * ratio)); } }
Source:
<code>public void testDataProviderWithOutOfBoundIndex() { VirtualTableQueryFilter queryFilter = new EventTableQueryFilter(Collections.emptyList(), 2000000, 5, null); TmfModelResponse<ITmfVirtualTableModel<EventTableLine>> response = fProvider.fetch(queryFilter, null); ITmfVirtualTableModel<EventTableLine> currentModel = response.getModel(); List<Long> <START> expectedColumnsId = <END> Arrays.asList(TIMESTAMP_COLUMN_ID, EVENT_TYPE_COLUMN_ID, CONTENTS_COLUMN_ID); assertNotNull(currentModel); assertEquals(expectedColumnsId, currentModel.getColumnsIds()); assertTrue(currentModel.getData().isEmpty()); }</code><technical_language>ditto column IDs</technical_language>

Target:
public void testDataProviderWithOutOfBoundIndex() { VirtualTableQueryFilter queryFilter = new EventTableQueryFilter(Collections.emptyList(), 2000000, 5, null); TmfModelResponse<ITmfVirtualTableModel<EventTableLine>> response = fProvider.fetchLines(queryFilter, null); ITmfVirtualTableModel<EventTableLine> currentModel = response.getModel(); assertNotNull(currentModel); assertEquals(fColumnId, currentModel.getColumnsIds()); assertTrue(currentModel.getData().isEmpty()); }
Source:
<code>public static Map<String, Set<IType>> createAQLVariableTypesFromInterpreterContext(IInterpreterContext context, IQueryEnvironment queryEnvironment) { Map<String, Set<IType>> variableTypes = new LinkedHashMap<String, Set<IType>>(); final Set<IType> selfTyping = new LinkedHashSet<IType>(2); for (String targetType : context.getTargetTypes()) { EClassifier found = null; int separatorPosition = targetType.indexOf('.'); if (separatorPosition > -1) { String typeName = targetType.substring(separatorPosition + 1); String nsPrefix = targetType.substring(0, separatorPosition); found = queryEnvironment.getEPackageProvider().getType(nsPrefix, typeName); } else { found = queryEnvironment.getEPackageProvider().getType(targetType); } if (found != null) { selfTyping.add(new EClassifierType(found)); } } if (selfTyping.size() == 0) { selfTyping.add(new ClassType(EObject.class)); } variableTypes.put("self", selfTyping); for (Entry<String, String> varDef : context.getVariables().entrySet()) { String typeDescription = varDef.getValue(); <START> int indexOfSeparator = typeDescription.indexOf('.'); if (indexOfSeparator > -1) { String nsPrefix = typeDescription.substring(0, indexOfSeparator); String typeName = typeDescription.substring(indexOfSeparator + 1); EClassifier found = queryEnvironment.getEPackageProvider().getType(nsPrefix, typeName); if (found != null) { final Set<IType> potentialTypes = new LinkedHashSet<IType>(2); potentialTypes.add(new EClassifierType(found)); variableTypes.put(varDef.getKey(), potentialTypes); } } <END> } return variableTypes; }</code><technical_language>"String IType" is partially duplicated similar logic above, extracted in a self-contained method</technical_language>

Target:
public static Map<String, Set<IType>> createAQLVariableTypesFromInterpreterContext(IInterpreterContext context, IQueryEnvironment queryEnvironment) { Map<String, Set<IType>> variableTypes = new LinkedHashMap<String, Set<IType>>(); final Set<IType> selfTyping = new LinkedHashSet<IType>(2); for (String targetTypeName : context.getTargetTypes()) { EClassifierType found = searchEClassifierType(queryEnvironment, targetTypeName); if (found != null) { selfTyping.add(found); } } if (selfTyping.size() == 0) { selfTyping.add(new ClassType(EObject.class)); } variableTypes.put("self", selfTyping); for (Entry<String, String> varDef : context.getVariables().entrySet()) { String typeName = varDef.getValue(); if (typeName != null) { EClassifierType found = searchEClassifierType(queryEnvironment, typeName); if (found != null) { final Set<IType> potentialTypes = new LinkedHashSet<IType>(2); potentialTypes.add(found); variableTypes.put(varDef.getKey(), potentialTypes); } } } return variableTypes; }
Source:
<code>int gdk_pointer_grab (long window, int grab_ownership, boolean owner_events, int event_mask, long confine_to, long cursor, int time_) { long display = 0; if( window != 0) { display = GDK.gdk_window_get_display (window); } else { window = GDK.gdk_get_default_root_window (); display = GDK.gdk_window_get_display (window); } if (GTK.GTK_VERSION >= OS.VERSION(3, 20, 0)) { long seat = GDK.gdk_display_get_default_seat(display); <START> GDK.gdk_window_show(window); <END> return GDK.gdk_seat_grab(seat, window, GDK.GDK_SEAT_CAPABILITY_ALL_POINTING, owner_events, cursor, 0, 0, 0); } else { long pointer = GDK.gdk_get_pointer(display); return GDK.gdk_device_grab (pointer, window, grab_ownership, owner_events, event_mask, cursor, time_); } }</code><technical_language>Is this gdk_window_show() call necessary? I worried flickering similar. Is a it</technical_language>

Target:
int gdk_pointer_grab (long window, int grab_ownership, boolean owner_events, int event_mask, long confine_to, long cursor, int time_) { long display = 0; if( window != 0) { display = GDK.gdk_window_get_display (window); } else { window = GDK.gdk_get_default_root_window (); display = GDK.gdk_window_get_display (window); } if (GTK.GTK_VERSION >= OS.VERSION(3, 20, 0)) { long seat = GDK.gdk_display_get_default_seat(display); if (gdkSeatGrabPrepareFunc == null) { gdkSeatGrabPrepareFunc = new Callback(Widget.class, "GdkSeatGrabPrepareFunc", 3); } long gdkSeatGrabPrepareFuncAddress = gdkSeatGrabPrepareFunc.getAddress(); if (gdkSeatGrabPrepareFuncAddress == 0) SWT.error (SWT.ERROR_NO_MORE_CALLBACKS); return GDK.gdk_seat_grab(seat, window, GDK.GDK_SEAT_CAPABILITY_ALL_POINTING, owner_events, cursor, 0, gdkSeatGrabPrepareFuncAddress, window); } else { long pointer = GDK.gdk_get_pointer(display); return GDK.gdk_device_grab (pointer, window, grab_ownership, owner_events, event_mask, cursor, time_); } }
Source:
<code>public void migratePrimaryKeyTableIfNeeded_second() throws IOException { configFactory.copyRealmFromAssets(context, "0841_annotationtypes.realm", "default.realm"); sharedRealm = SharedRealm.getInstance(config); sharedRealm.beginTransaction(); assertTrue(Table.migratePrimaryKeyTableIfNeeded(sharedRealm)); sharedRealm.commitTransaction(); Table t = sharedRealm.getTable("class_AnnotationTypes"); assertEquals(t.getColumnIndex("id"), t.getPrimaryKey()); <START> assertTrue(t.hasPrimaryKey()); <END> assertEquals("AnnotationTypes", sharedRealm.getTable("pk").getString(0, 0)); }</code><technical_language>minor: this assert is above</technical_language>

Target:
public void migratePrimaryKeyTableIfNeeded_second() throws IOException { configFactory.copyRealmFromAssets(context, "0841_annotationtypes.realm", "default.realm"); sharedRealm = SharedRealm.getInstance(config); sharedRealm.beginTransaction(); assertTrue(Table.migratePrimaryKeyTableIfNeeded(sharedRealm)); sharedRealm.commitTransaction(); Table t = sharedRealm.getTable("class_AnnotationTypes"); assertTrue(t.hasPrimaryKey()); assertEquals(t.getColumnIndex("id"), t.getPrimaryKey()); assertEquals("AnnotationTypes", sharedRealm.getTable("pk").getString(0, 0)); }
Source:
<code>public void invalidate(String namespace) { <START> topologyEntityCache.refresh(); <END> serviceLocator.findServices(MetaTopologyProvider.class, null).stream() .filter(metaTopologyProvider -> metaTopologyProvider.getGraphProviderBy(namespace) != null) .forEach(metaTopologyProvider -> { graphProviderCache.invalidate(new GraphProviderKey(metaTopologyProvider.getId(), namespace)); }); }</code><technical_language>Data is cached for a 30 seconds default. This means changes curtains 30 seconds visualised. In order wait 30 + delta seconds I opted in for allowing invalidating cache manually, forcing data reloaded queried afterwards. point of view this is correct place. in mind, cache is invalidated if event is send manually OpenNMS (or 30 seconds pass of course). This functionality is leveraged some smoke tests enforce reloading of cache wait previous mentioned seconds speed test execution Besides thetopologyEntityCache is in nodes namespace. refresh if namespace.startsWith("nodes")</technical_language>

Target:
public void invalidate(String namespace) { if(namespace.startsWith("nodes")) { topologyEntityCache.refresh(); } serviceLocator.findServices(MetaTopologyProvider.class, null).stream() .filter(metaTopologyProvider -> metaTopologyProvider.getGraphProviderBy(namespace) != null) .forEach(metaTopologyProvider -> { graphProviderCache.invalidate(new GraphProviderKey(metaTopologyProvider.getId(), namespace)); }); }
Source:
<code>public ResponseEntity saveStorage(@ApiParam(value = "The storage object", required = true) @RequestBody Storage storage) throws IOException, JAXBException { try { configurationManagementService.saveStorage(storage); if (!storage.existsOnFileSystem()) { storageManagementService.createStorage(storage); } <START> return ResponseEntity.ok(ResponseStatusEnum.OK.value()); <END> } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(ResponseStatusEnum.FAILED.value()); } }</code><technical_language>removed actual text response here</technical_language>

Target:
public ResponseEntity saveStorage(@ApiParam(value = "The storage object", required = true) @RequestBody Storage storage) throws IOException, JAXBException { try { configurationManagementService.saveStorage(storage); if (!storage.existsOnFileSystem()) { storageManagementService.createStorage(storage); } return ResponseEntity.ok("The storage was updated successfully."); } catch (IOException | JAXBException e) { logger.error(e.getMessage(), e); return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR); } }
Source:
<code>public void serialize(XMLExtendedStreamWriter writer, JpaStoreConfiguration configuration) throws XMLStreamException { AttributeSet attributes = configuration.attributes(); writer.writeStartElement(Element.JPA_STORE); <START> attributes.write(writer, JpaStoreConfiguration.ENTITY_CLASS, Attribute.ENTITY_CLASS_NAME); <END> attributes.write(writer, JpaStoreConfiguration.PERSISTENCE_UNIT_NAME, Attribute.PERSISTENCE_UNIT_NAME); attributes.write(writer, JpaStoreConfiguration.BATCH_SIZE, Attribute.BATCH_SIZE); attributes.write(writer, JpaStoreConfiguration.STORE_METADATA, Attribute.STORE_METADATA); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }</code><technical_language>need write attributes individually. do configuration.attributes().write(writer) abstract store attributes serialized</technical_language>

Target:
public void serialize(XMLExtendedStreamWriter writer, JpaStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.JPA_STORE); configuration.attributes().write(writer); writeCommonStoreSubAttributes(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
<code>public Boolean delete(List<T> items) { boolean deleted = true; if (items != null) { for (T item : items) { <START> if (null == item) { <END> continue; } updateApiVersionResource(item); try { R op; if (item instanceof HasMetadata && ((HasMetadata) item).getMetadata() != null && ((HasMetadata) item).getMetadata().getName() != null && !((HasMetadata) item).getMetadata().getName().isEmpty()) { op = (R) inNamespace(checkNamespace(item)).withName(((HasMetadata) item).getMetadata().getName()); } else { op = (R) withItem(item); } deleted &= op.delete(); } catch (KubernetesClientException e) { if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) { throw e; } return false; } } } return deleted; }</code><technical_language>suggestion if (item == null) {</technical_language>

Target:
public Boolean delete(List<T> items) { boolean deleted = true; if (items != null) { for (T item : items) { updateApiVersionResource(item); try { R op; if (item instanceof HasMetadata && ((HasMetadata) item).getMetadata() != null && ((HasMetadata) item).getMetadata().getName() != null && !((HasMetadata) item).getMetadata().getName().isEmpty()) { op = (R) inNamespace(checkNamespace(item)).withName(((HasMetadata) item).getMetadata().getName()); } else { op = (R) withItem(item); } deleted &= op.delete(); } catch (KubernetesClientException e) { if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) { throw e; } return false; } } } return deleted; }
Source:
<code>private static void checkMaxSize(long bytes, long count) { <START> checkCondition(bytes <= (MAX_SIZE_IN_BYTES + count) / count, <END> INVALID_FUNCTION_ARGUMENT, "repeat should not create an array greater than %s bytes", MAX_SIZE_IN_BYTES); }</code><technical_language>argument line</technical_language>

Target:
private static void checkMaxSize(long bytes, long count) { checkCondition( bytes <= (MAX_SIZE_IN_BYTES + count) / count, INVALID_FUNCTION_ARGUMENT, "result of repeat function must not take more than 1000000 bytes"); }
Source:
<code>public Host cancelMaintenance(final CancelMaintenanceCmd cmd) { final Long hostId = cmd.getId(); final HostVO host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); } <START> if (host.getResourceState() != ResourceState.PrepareForMaintenance && <END> host.getResourceState() != ResourceState.ErrorInPrepareForMaintenance && host.getResourceState() != ResourceState.Maintenance && host.getResourceState() != ResourceState.ErrorInMaintenance) { throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = " + hostId); } processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId); final boolean success = cancelMaintenance(hostId); processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, hostId); if (!success) { throw new CloudRuntimeException("Internal error cancelling maintenance."); } return host; }</code><technical_language>Simply readability Arrays().contains() equivalent</technical_language>

Target:
public Host cancelMaintenance(final CancelMaintenanceCmd cmd) { final Long hostId = cmd.getId(); final HostVO host = _hostDao.findById(hostId); if (host == null || host.getRemoved() != null) { throw new InvalidParameterValueException("Host with id " + hostId.toString() + " doesn't exist"); } if (!ResourceState.isMaintenanceState(host.getResourceState())) { throw new CloudRuntimeException("Cannot perform cancelMaintenance when resource state is " + host.getResourceState() + ", hostId = " + hostId); } processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_BEFORE, hostId); final boolean success = cancelMaintenance(hostId); processResourceEvent(ResourceListener.EVENT_CANCEL_MAINTENANCE_AFTER, hostId); if (!success) { throw new CloudRuntimeException("Internal error cancelling maintenance."); } return host; }