auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static String getPasswordEncodeFailMessage(String algo) { String errorMessage = "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; return errorMessage; }

Target:
private static String getPasswordEncodeFailMessage(String algo) { return "Can't encode password because the given algorithm: " + algo + " was not found! (fail)"; }
Source:
public MemoryEstimate visitIndexJoin(IndexJoinNode node, EstimationContext context) { PlanCostEstimate sourcesCost = context.sourcesCosts.stream() .reduce(PlanCostEstimate.zero(), CachingCostProvider::addSiblingsCost); return new MemoryEstimate( sourcesCost.getMaxMemory(), context.localMaxMemory + sourcesCost.getMaxMemoryWhenOutputting()); }

Target:
public MemoryEstimate visitIndexJoin(IndexJoinNode node, EstimationContext context) { PlanCostEstimate sourcesCost = context.sourcesCosts.stream() .reduce(PlanCostEstimate.zero(), CachingCostProvider::addSiblingsCost); return new MemoryEstimate( sourcesCost.getMaxMemoryWhenOutputting(), context.localMaxMemory + sourcesCost.getMaxMemoryWhenOutputting()); }
Source:
public CompletableFuture<Optional<PublicKeyHash>> getPublicKeyHash(String username) { Optional<PublicKeyHash> local = tofu.getPublicKey(username); if (local.isPresent()) return CompletableFuture.completedFuture(local); return source.getChain(username) .thenCompose(chain -> { if(chain.isEmpty()) { CompletableFuture<Boolean> noSuchUser = new CompletableFuture<>(); noSuchUser.complete(false); return noSuchUser; } else { return tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()); } } ).thenApply(x -> x == false ? Optional.empty() : tofu.getPublicKey(username)); }

Target:
public CompletableFuture<Optional<PublicKeyHash>> getPublicKeyHash(String username) { Optional<PublicKeyHash> local = tofu.getPublicKey(username); if (local.isPresent()) return CompletableFuture.completedFuture(local); return source.getChain(username) .thenCompose(chain -> { if(chain.isEmpty()) { return CompletableFuture.completedFuture(false); } else { return tofu.updateChain(username, chain, context.network.dhtClient) .thenCompose(x -> commit()); } } ).thenApply(x -> x == false ? Optional.empty() : tofu.getPublicKey(username)); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RepositoryCache repositoryCache = Activator.getDefault() .getRepositoryCache(); if (repository == null) { Repository[] repositories = repositoryCache.getAllRepositories(); if (repositories.length == 0) { Shell shell = getShell(event); MessageDialog.openInformation(shell, UIText.FetchChangeFromGerritCommand_noRepositorySelectedTitle, UIText.FetchChangeFromGerritCommand_noRepositorySelectedMessage); return null; } else { File activeFile = getActiveFile(); if (activeFile != null) { repository = repositoryCache.getRepository(activeFile); } else { repository = repositories[0]; } } } if (repository == null) { return null; } FetchGerritChangeWizard wiz = new FetchGerritChangeWizard(repository); NonBlockingWizardDialog dlg = new NonBlockingWizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); if (repository == null) { Shell shell = getShell(event); RepositoryCache repositoryCache = Activator.getDefault() .getRepositoryCache(); Repository[] repositories = repositoryCache.getAllRepositories(); ElementListSelectionDialog repositorySelectionDialog = new ElementListSelectionDialog( shell, new NoRepositorySelectedLabelProvider()); repositorySelectionDialog.setElements(repositories); repositorySelectionDialog.setTitle( UIText.FetchChangeFromGerritCommand_noRepositorySelectedTitle); if (repositorySelectionDialog.open() != Window.OK) { return null; } else { repository = (Repository) repositorySelectionDialog .getResult()[0]; } } FetchGerritChangeWizard wiz = new FetchGerritChangeWizard(repository); NonBlockingWizardDialog dlg = new NonBlockingWizardDialog( HandlerUtil.getActiveShellChecked(event), wiz); dlg.setHelpAvailable(false); dlg.open(); return null; }
Source:
private String tryReadLine(FileChannel channel, char separator) throws IOException, InterruptedException { int retryNumber = 0; long rePos = 0; StringBuilder sb = new StringBuilder(); while (!Thread.currentThread().isInterrupted()) { if (retryNumber > failureRetryLimit && failureRetryLimit > 0) { LOG.error("fail to read line after attempts", retryNumber); throw new IOException(); } try { rePos = channel.position(); buffer.clear(); boolean end = false; int num; while (((num = channel.read(buffer)) != -1) && !end) { buffer.flip(); CharBuffer charBuffer = charset.decode(buffer); for (int i = 0; i < num; i++) { char ch = charBuffer.charAt(i); if (ch != separator) { sb.append(ch); rePos++; } else { rePos++; end = true; break; } } buffer.clear(); } break; } catch (IOException e) { retryNumber++; Thread.sleep(failureSleepInterval); } } channel.position(rePos); return sb.toString(); }

Target:
private String tryReadLine(FileChannel channel, char separator) throws IOException, InterruptedException { int retryNumber = 0; long position = channel.position(); StringBuilder sb = new StringBuilder(); boolean lineNotRead = true; while (lineNotRead) { if (retryNumber > failureRetryLimit && failureRetryLimit > 0) { LOG.error("fail to read line after attempts", retryNumber); throw new IOException(); } try { readBuffer.clear(); decoded.clear(); int len = channel.read(readBuffer); lineNotRead = false; if (len >= 0) { readBuffer.flip(); decoder.decode(readBuffer, decoded, false); decoded.flip(); for (int i = 0; i < decoded.length(); i++) { char ch = decoded.charAt(i); if (ch != separator) { sb.append(ch); } else { break; } } } } catch (IOException e) { retryNumber++; Thread.sleep(failureSleepInterval); } } String line = sb.toString(); channel.position(position + line.getBytes(charset).length + separatorByteLength); return line; }
Source:
public Host resolveHostNameWithoutDefault(String serverName, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { Host host = hostCache.getHostByAlias(serverName); User systemUser = APILocator.systemUser(); if(host == null){ try { host = findByNameNotDefault(serverName, systemUser, respectFrontendRoles); } catch (Exception e) { return findDefaultHost(systemUser, respectFrontendRoles); } if(host == null){ host = findByAlias(serverName, systemUser, respectFrontendRoles); } if(host != null){ hostCache.addHostAlias(serverName, host); } } if (host != null) { checkHostPermission(user, respectFrontendRoles, host); } return host; }

Target:
public Optional<Host> resolveHostNameWithoutDefault(String serverName, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { Host host = hostCache.getHostByAlias(serverName); User systemUser = APILocator.systemUser(); if(host == null){ host = findByNameNotDefault(serverName, systemUser, respectFrontendRoles); if(host == null){ host = findByAlias(serverName, systemUser, respectFrontendRoles); } if(host != null){ hostCache.addHostAlias(serverName, host); } } if (host != null) { checkHostPermission(user, respectFrontendRoles, host); } return Optional.ofNullable(host); }
Source:
private void processClassesForSchema() { try { final JAXBContext context = JAXBContext.newInstance(schemaClasses.toArray(new Class[schemaClasses.size()])); final List<StreamResult> results = new ArrayList<>(); context.generateSchema(new SchemaOutputResolver() { int counter = 0; @Override public Result createOutput(final String namespaceUri, final String suggestedFileName) { final StreamResult result = new StreamResult(new CharArrayWriter()); String systemId = "xsd" + (counter++) + ".xsd"; result.setSystemId(systemId); results.add(result); return result; } }); if (grammars != null) { Iterator<Include> iter = grammars.getInclude().iterator(); while (iter.hasNext()) { for (Doc doc : iter.next().getDoc()) { if ("Generated".equals(doc.getTitle())) ; iter.remove(); } } } addGrammars(new Grammars()); for (final StreamResult result : results) { final CharArrayWriter writer = (CharArrayWriter) result.getWriter(); final byte[] contents = writer.toString().getBytes("UTF8"); generatedSchemas.put( result.getSystemId(), contents); Include inc = new Include(); inc.setHref(result.getSystemId()); Doc doc = new Doc(); doc.setTitle("Generated"); doc.setLang("en"); inc.getDoc().add(doc); this.grammars.getInclude().add(inc); } } catch (JAXBException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void processClassesForSchema() { try { final JAXBContext context = JAXBContext.newInstance(schemaClasses.toArray(new Class[schemaClasses.size()])); final List<StreamResult> results = new ArrayList<>(); context.generateSchema(new SchemaOutputResolver() { int counter = 0; @Override public Result createOutput(final String namespaceUri, final String suggestedFileName) { final StreamResult result = new StreamResult(new CharArrayWriter()); String systemId = "xsd" + (counter++) + ".xsd"; result.setSystemId(systemId); results.add(result); return result; } }); if (grammars != null) { Iterator<Include> iter = grammars.getInclude().iterator(); while (iter.hasNext()) { for (Doc doc : iter.next().getDoc()) { if ("Generated".equals(doc.getTitle())) ; iter.remove(); } } } addGrammars(new Grammars()); for (final StreamResult result : results) { final CharArrayWriter writer = (CharArrayWriter) result.getWriter(); final byte[] contents = writer.toString().getBytes("UTF8"); generatedSchemas.put( result.getSystemId(), contents); Include inc = new Include(); inc.setHref(result.getSystemId()); Doc doc = new Doc(); doc.setTitle("Generated"); doc.setLang("en"); inc.getDoc().add(doc); this.grammars.getInclude().add(inc); } } catch (JAXBException e) { LogMessages.LOGGER.error(Messages.MESSAGES.cantProcessWadl()); } catch (IOException e) { LogMessages.LOGGER.error(Messages.MESSAGES.cantProcessWadl()); } }
Source:
void fireActivity(final TextSelectionActivity activity) { checkSWTAccess(); if (currentSelectionActivity == null) { currentSelectionActivity = activity; display.timerExec(DELAY, this::flushCurrentSelectionActivity); } else if (currentSelectionActivity.getPath().equals(activity.getPath())) { currentSelectionActivity = activity; } else { flushCurrentSelectionActivity(); currentSelectionActivity = activity; display.timerExec(DELAY, this::flushCurrentSelectionActivity); } }

Target:
void fireActivity(final TextSelectionActivity activity) { if (!checkThreadAccess(activity)) return; if (currentSelectionActivity == null) { currentSelectionActivity = activity; display.timerExec(DELAY, this::flushCurrentSelectionActivity); } else if (currentSelectionActivity.getPath().equals(activity.getPath())) { currentSelectionActivity = activity; } else { flushCurrentSelectionActivity(); currentSelectionActivity = activity; display.timerExec(DELAY, this::flushCurrentSelectionActivity); } }
Source:
protected Object unwrapCachedValue(Object cached) { if (currentKey instanceof EnhancerKey) { return ((WeakReference<EnhancerFactoryData>) cached).get(); } return super.unwrapCachedValue(cached); }

Target:
protected Object unwrapCachedValue(Object cached) { if (currentKey instanceof EnhancerKey) { EnhancerFactoryData data = ((WeakReference<EnhancerFactoryData>) cached).get(); return data; } return super.unwrapCachedValue(cached); }
Source:
public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep ) { int[] billableData = {11, -2, -3}; Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); return jobBuilderFactory.get("Number generator - second dataset") .start(dataProviderStep) .on("NOTIFY").to(notificationStep) .end() .build(); }

Target:
public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { int[] billableData = { 11, -2, -3 }; Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); return jobBuilderFactory.get("Number generator - second dataset") .start(dataProviderStep) .on(NOTIFY) .to(notificationStep) .end() .build(); }
Source:
public void testCopyObject() throws Exception { for (String regionId : regions) { String sourceContainer = "src" + containerName; String sourceObjectName = "original.txt"; String badSource = "badSource"; String destinationContainer = "dest" + containerName; String destinationObject = "copy.txt"; String destinationPath = "/" + destinationContainer + "/" + destinationObject; ContainerApi containerApi = api.getContainerApi(regionId); containerApi.create(sourceContainer); containerApi.create(destinationContainer); ObjectApi srcApi = api.getObjectApi(regionId, sourceContainer); ObjectApi destApi = api.getObjectApi(regionId, destinationContainer); assertNotNull(srcApi.put(sourceObjectName, PAYLOAD)); SwiftObject sourceObject = srcApi.get(sourceObjectName); checkObject(sourceObject); assertNotNull(destApi.put(destinationObject, PAYLOAD)); SwiftObject object = destApi.get(destinationObject); checkObject(object); assertTrue(destApi.copy(destinationObject, sourceContainer, sourceObjectName)); assertNotNull(destApi.get(destinationObject)); SwiftObject destSwiftObject = destApi.get(destinationObject); assertEquals(toStringAndClose(destSwiftObject.getPayload().openStream()), "swifty"); try { destApi.copy(destinationObject, badSource, sourceObjectName); } finally { deleteAllObjectsInContainer(regionId, sourceContainer); containerApi.deleteIfEmpty(sourceContainer); deleteAllObjectsInContainer(regionId, destinationContainer); containerApi.deleteIfEmpty(destinationContainer); } } }

Target:
public void testCopyObject() throws Exception { for (String regionId : regions) { String sourceContainer = "src" + containerName; String sourceObjectName = "original.txt"; String badSource = "badSource"; String destinationContainer = "dest" + containerName; String destinationObject = "copy.txt"; String destinationPath = "/" + destinationContainer + "/" + destinationObject; ContainerApi containerApi = api.getContainerApi(regionId); containerApi.create(sourceContainer); containerApi.create(destinationContainer); ObjectApi srcApi = api.getObjectApi(regionId, sourceContainer); ObjectApi destApi = api.getObjectApi(regionId, destinationContainer); assertNotNull(srcApi.put(sourceObjectName, PAYLOAD)); SwiftObject sourceObject = srcApi.get(sourceObjectName); checkObject(sourceObject); assertNotNull(destApi.put(destinationObject, PAYLOAD)); SwiftObject object = destApi.get(destinationObject); checkObject(object); assertTrue(destApi.copy(destinationObject, sourceContainer, sourceObjectName)); assertNotNull(destApi.get(destinationObject)); SwiftObject destSwiftObject = destApi.get(destinationObject); assertEquals(toStringAndClose(destSwiftObject.getPayload().openStream()), "swifty"); try { destApi.copy(destinationObject, badSource, sourceObjectName); } catch (KeyNotFoundException e) { continue; } finally { deleteAllObjectsInContainer(regionId, sourceContainer); containerApi.deleteIfEmpty(sourceContainer); deleteAllObjectsInContainer(regionId, destinationContainer); containerApi.deleteIfEmpty(destinationContainer); } fail("Expected KeyNotFoundException"); } }
Source:
public String evaluate(String url) throws HiveException { RefererClassification kind = Webrequest.classifyReferer(url); switch (kind) { case UNKNOWN: return "UNK"; case INTERNAL: return "INT"; case EXTERNAL: return "EXT"; } return "UNK"; }

Target:
public String evaluate(String url) throws HiveException { return Webrequest.getInstance().classifyReferer(url); }
Source:
public void start() { try { Map<String, MonitorConfig> monitorConfigs = getMonitorConfigs(config); for (Map.Entry<String, MonitorConfig> entry : monitorConfigs.entrySet()) { String monitorName = entry.getKey(); MonitorConfig monitorConfig = entry.getValue(); if (!Strings.isNullOrEmpty(monitorConfig.getMonitorFactoryClass())) { int schedulingIntervalInMs = monitorConfig.getSchedulingIntervalInMs(); int monitorSchedulingJitterInMs = (int) (RANDOM.nextInt(schedulingIntervalInMs + 1) * (monitorConfig.getSchedulingJitterPercent() / 100.0)); schedulingIntervalInMs += monitorSchedulingJitterInMs; LOGGER.info("Scheduling the monitor: to run every ms.", monitorName, schedulingIntervalInMs); getScheduler() .scheduleAtFixedRate(getRunnable(instantiateMonitor(monitorName, monitorConfig, metricsRegistry)), 0, schedulingIntervalInMs, TimeUnit.MILLISECONDS); } else { LOGGER.warn("Not scheduling the monitor: to run, since monitor factory class is not set in config.", monitorName); } } } catch (InstantiationException e) { LOGGER.error("Exception when instantiating the monitor : ", e); throw new SamzaException(e); } }

Target:
public void start() { try { Map<String, MonitorConfig> monitorConfigs = getMonitorConfigs(config); for (Map.Entry<String, MonitorConfig> entry : monitorConfigs.entrySet()) { String monitorName = entry.getKey(); MonitorConfig monitorConfig = entry.getValue(); if (!Strings.isNullOrEmpty(monitorConfig.getMonitorFactoryClass())) { int schedulingIntervalInMs = monitorConfig.getSchedulingIntervalInMs(); int monitorSchedulingJitterInMs = (int) (RANDOM.nextInt(schedulingIntervalInMs + 1) * (monitorConfig.getSchedulingJitterPercent() / 100.0)); schedulingIntervalInMs += monitorSchedulingJitterInMs; LOGGER.info("Scheduling the monitor: to run every ms.", monitorName, schedulingIntervalInMs); createSchedulerAndScheduleMonitor(monitorName, monitorConfig, schedulingIntervalInMs); } else { LOGGER.warn("Not scheduling the monitor: to run, since monitor factory class is not set in config.", monitorName); } } } catch (InstantiationException e) { LOGGER.error("Exception when instantiating the monitor : ", e); throw new SamzaException(e); } }
Source:
public void emitStats( String tier, MasterStats stats, List<ServerHolder> serverHolderList ) { return; }

Target:
public void emitStats( String tier, MasterStats stats, List<ServerHolder> serverHolderList ) { }
Source:
void addClassLoadingMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new MetricFamilySamples( "jvm_classloading_loaded_current", Type.GAUGE, "The number of classes that are currently loaded in the JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classloading_loaded_current", EMPTY_LABEL, EMPTY_LABEL, clBean.getLoadedClassCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_classloading_loaded_total", Type.COUNTER, "The total number of classes that have been loaded since the JVM has started execution", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classloading_loaded_total", EMPTY_LABEL, EMPTY_LABEL, clBean.getTotalLoadedClassCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_classloading_unloaded_total", Type.COUNTER, "The total number of classes that have been unloaded since the JVM has started execution", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classloading_unloaded_total", EMPTY_LABEL, EMPTY_LABEL, clBean.getUnloadedClassCount())))); }

Target:
void addClassLoadingMetrics(List<MetricFamilySamples> sampleFamilies) { sampleFamilies.add( new MetricFamilySamples( "jvm_classes_loaded", Type.GAUGE, "The number of classes that are currently loaded in the JVM", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classes_loaded", EMPTY_LABEL, EMPTY_LABEL, clBean.getLoadedClassCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_classes_loaded_total", Type.COUNTER, "The total number of classes that have been loaded since the JVM has started execution", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classes_loaded_total", EMPTY_LABEL, EMPTY_LABEL, clBean.getTotalLoadedClassCount())))); sampleFamilies.add( new MetricFamilySamples( "jvm_classes_unloaded_total", Type.COUNTER, "The total number of classes that have been unloaded since the JVM has started execution", Collections.singletonList( new MetricFamilySamples.Sample( "jvm_classes_unloaded_total", EMPTY_LABEL, EMPTY_LABEL, clBean.getUnloadedClassCount())))); }
Source:
public void processEvent(GlusterEvent event) { if (event == null) { return; } GlusterServer glusterServer = glusterServerDao.getByGlusterServerUuid(Guid.createGuidFromString(event.getNodeId())); if (glusterServer == null) { return; } VDS host = vdsDao.get(glusterServer.getId()); if (host == null) { return; } GlusterVolumeEntity vol = glusterVolumeDao.getByName(host.getClusterId(), (String)event.getMessage().get("volume")); if (vol == null) { return; } if (event.getEvent().equalsIgnoreCase("BRICK_DISCONNECTED") || event.getEvent().equalsIgnoreCase("BRICK_CONNECTED") ) { GlusterStatus status = event.getEvent().equalsIgnoreCase("BRICK_DISCONNECTED") ? GlusterStatus.DOWN : GlusterStatus.UP; String path = (String) event.getMessage().get("brick"); String peer = (String) event.getMessage().get("peer"); List<VDS> vdsList = vdsDao.getAllForCluster(host.getClusterId()); VDS vds = vdsList.stream() .filter(v -> v.getName().equals(peer) || v.getInterfaces().stream().anyMatch(iface -> iface.getIpv4Address().equals(peer))) .findFirst() .orElse(null); GlusterBrickEntity brick = vds != null ? glusterBrickDao.getBrickByServerIdAndDirectory(vds.getId(), path) : null; if (brick != null) { glusterBrickDao.updateBrickStatus(brick.getId(), status); } else { backend.runInternalAction(VdcActionType.RefreshGlusterVolumeDetails, new GlusterVolumeParameters(vol.getId())); } logBrickStatusChange(vol, status, brick); } }

Target:
public void processEvent(GlusterEvent event) { if (event == null) { return; } GlusterServer glusterServer = glusterServerDao.getByGlusterServerUuid(Guid.createGuidFromString(event.getNodeId())); if (glusterServer == null) { return; } VDS host = vdsDao.get(glusterServer.getId()); if (host == null) { return; } GlusterVolumeEntity vol = glusterVolumeDao.getByName(host.getClusterId(), (String) event.getMessage().get("volume")); if (vol == null) { return; } if (event.getEvent().equalsIgnoreCase("BRICK_DISCONNECTED") || event.getEvent().equalsIgnoreCase("BRICK_CONNECTED")) { GlusterStatus status = event.getEvent().equalsIgnoreCase("BRICK_DISCONNECTED") ? GlusterStatus.DOWN : GlusterStatus.UP; String path = (String) event.getMessage().get("brick"); String peer = (String) event.getMessage().get("peer"); List<VDS> vdsList = vdsDao.getAllForCluster(host.getClusterId()); VDS vds = vdsList.stream() .filter(v -> v.getName().equals(peer) || v.getInterfaces().stream().anyMatch(iface -> iface.getIpv4Address().equals(peer))) .findFirst() .orElse(null); GlusterBrickEntity brick = vds != null ? glusterBrickDao.getBrickByServerIdAndDirectory(vds.getId(), path) : null; if (brick != null) { glusterBrickDao.updateBrickStatus(brick.getId(), status); logBrickStatusChange(vol, status, brick); } else { log.debug("Forcing sync as brick event '{}' received that could not be resolved to brick", event); backend.runInternalAction(VdcActionType.RefreshGlusterVolumeDetails, new GlusterVolumeParameters(vol.getId())); } } }
Source:
public Builder disablePagination() { this.limit = null; return (Builder) this; }

Target:
public Builder disablePagination() { this.limit = Integer.MAX_VALUE; return (Builder) this; }
Source:
public String[] getOptionValues(final String optionName) { final String[] values = this.cmd.getOptionValues(optionName); if ((values == null) || (values.length == 0)) { return null; } return values; }

Target:
public String[] getOptionValues(final String optionName) { final String[] values = this.cmd.getOptionValues(optionName); if (values == null || values.length == 0) { return null; } return values; }
Source:
@Test public void startingFormMap_doesNotZoom_ifThereAreNoInstanceMarkers_andLocationIsUnavailable() { ActivityController controller = RobolectricHelpers.buildThemedActivity(FormMapActivity.class); FormMapActivity activity = (FormMapActivity) controller.get(); TestInstancesRepository testInstancesRepository = new TestInstancesRepository(new ArrayList<>()); FormMapViewModel viewModel = new FormMapViewModel(FormMapViewModelTest.testForm1, testInstancesRepository); activity.viewModelFactory = new TestFactory(viewModel); activity.map = new TestMapFragment(); controller.setup().visible().start().resume(); TestMapFragment map = (TestMapFragment) activity.map; assertThat(map.getZoomCount(), is(0)); }

Target:
@Test public void startingFormMap_doesNotZoom_ifThereAreNoInstanceMarkers_andLocationIsUnavailable() { ActivityController controller = RobolectricHelpers.buildThemedActivity(FormMapActivity.class); FormMapActivity activity = (FormMapActivity) controller.get(); TestInstancesRepository testInstancesRepository = new TestInstancesRepository(new ArrayList<>()); FormMapViewModel viewModel = new FormMapViewModel(FormMapViewModelTest.TEST_FORM_1, testInstancesRepository); activity.viewModelFactory = new TestFactory(viewModel); activity.map = new TestMapFragment(); controller.setup(); TestMapFragment map = (TestMapFragment) activity.map; assertThat(map.getZoomCount(), is(0)); }
Source:
public String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro) { String result = vipAddressMacro; if (vipAddressMacro == null) { return null; } Matcher matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); while (matcher.find()) { String key = matcher.group(1); String value = config.getString(key, ""); logger.debug("att:" + matcher.group()); logger.debug(", att key:" + key); logger.debug(", att value:" + value); logger.debug(""); result = result.replaceAll("\\$\\{" + key + "\\}", value); matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); } return result; }

Target:
public String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro) { if (vipAddressMacro == null) { return null; } String result = vipAddressMacro; Matcher matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); while (matcher.find()) { String key = matcher.group(1); String value = config.getString(key, ""); logger.debug("att:" + matcher.group()); logger.debug(", att key:" + key); logger.debug(", att value:" + value); logger.debug(""); result = result.replaceAll("\\$\\{" + key + "\\}", value); matcher = VIP_ATTRIBUTES_PATTERN.matcher(result); } return result; }
Source:
protected boolean deleteViews(Collection<? extends View> views) { for (View view : views) { ViewUtil.destroy(view); } return !views.isEmpty(); }

Target:
protected boolean deleteViews(Collection<? extends View> views) { for (View view : views) { EcoreUtil.remove(view); } return !views.isEmpty(); }
Source:
private JsonNode readCacheFile() { try (BufferedReader br = new BufferedReader(new FileReader(file))) { return new JsonNode(br.readLine()); } catch (IOException | JSONException e) { Slimefun.getLogger().log(Level.WARNING, "Failed to read Github cache file: {0}", file.getName()); return null; } }

Target:
private JsonNode readCacheFile() { try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { return new JsonNode(br.readLine()); } catch (IOException | JSONException e) { Slimefun.getLogger().log(Level.WARNING, "Failed to read Github cache file: {0}", file.getName()); return null; } }
Source:
public Map<String, DeviceGroupDto> findDeviceGroup( @PathVariable("id") Long id) { final Map<String, DeviceGroupDto> response = new HashMap<String, DeviceGroupDto>(); DeviceGroup s = deviceGroupDao.getByKey(id); DeviceGroupDto dto = null; if (s != null) { dto = marshallToDto(s); } response.put("device_group", dto); return response; }

Target:
public Map<String, DeviceGroupDto> findDeviceGroup( @PathVariable("id") Long id) { final Map<String, DeviceGroupDto> response = new HashMap<String, DeviceGroupDto>(); DeviceGroup dg = deviceGroupDao.getByKey(id); DeviceGroupDto dto = null; if (dg != null) { dto = marshallToDto(dg); } response.put("device_group", dto); return response; }
Source:
public void makeTextView(FormEntryPrompt prompt) { mStringAnswer = new TextView(getContext()); mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mStringAnswer.setGravity(Gravity.CENTER); String s = prompt.getAnswerText(); if (s != null) { launchIntentButton.setText(StringUtils.getStringSpannableRobust(getContext(), R.string.intent_callout_button_update)); mStringAnswer.setText(s); } addView(mStringAnswer); if(s == null && "quick".equals(ic.getAppearance()) && !ic.getCancelled()){ performCallout(); } else if (ic.getCancelled()) { ic.setCancelled(false); } }

Target:
public void makeTextView(FormEntryPrompt prompt) { mStringAnswer = new TextView(getContext()); mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mStringAnswer.setGravity(Gravity.CENTER); String s = prompt.getAnswerText(); if (s != null) { mStringAnswer.setText(s); } addView(mStringAnswer); if(s == null && "quick".equals(ic.getAppearance()) && !ic.getCancelled()){ performCallout(); } else if (ic.getCancelled()) { ic.setCancelled(false); } }
Source:
public void import_report() { orchestrator.resetData(); orchestrator.getServer().provisionProject(PROJECT, PROJECT); orchestrator.getServer().associateProjectToQualityProfile(PROJECT, "py", "no_rule"); orchestrator.executeBuild( SonarScanner.create() .setDebugLogs(true) .setProjectDir(new File("projects/bandit_project"))); assertThat(issues()).hasSize(1); }

Target:
public void import_report() { orchestrator.resetData(); orchestrator.getServer().provisionProject(PROJECT, PROJECT); orchestrator.getServer().associateProjectToQualityProfile(PROJECT, "py", "no_rule"); orchestrator.executeBuild( SonarScanner.create() .setProjectDir(new File("projects/bandit_project"))); List<Issues.Issue> issues = issues(); boolean externalIssuesSupported = orchestrator.getServer().version().isGreaterThanOrEquals(7, 2); if (externalIssuesSupported) { assertThat(issues).hasSize(1); Issues.Issue issue = issues.get(0); assertThat(issue.getComponent()).isEqualTo("bandit_project:src/file1.py"); assertThat(issue.getRule()).isEqualTo("external_bandit:B107"); assertThat(issue.getMessage()).isEqualTo("Possible hardcoded password: 'secret'"); assertThat(issue.getType()).isEqualTo(Common.RuleType.VULNERABILITY); assertThat(issue.getSeverity()).isEqualTo(Common.Severity.MINOR); assertThat(issue.getEffort()).isEqualTo("5min"); } else { assertThat(issues).hasSize(0); } }
Source:
private static List<MarkerMetadataSet> buildMarkerMetadataSet(final Dataset dataset, final Map<String, Marker> markerMap) { List<MarkerMetadataSet> markerMetadataSetList = new ArrayList<>(); for (final Marker marker : markerMap.values()) { final MarkerMetadataSet mdb = new MarkerMetadataSet(); mdb.setDataset(dataset); mdb.setMarkerId(marker.getMarkerId()); mdb.setMarkerSampleId(1); markerMetadataSetList.add(mdb); } return markerMetadataSetList; }

Target:
private static List<MarkerMetadataSet> buildMarkerMetadataSet(final Dataset dataset, final Map<String, Marker> markerMap) { final List<MarkerMetadataSet> markerMetadataSetList = new ArrayList<>(); for (final Marker marker : markerMap.values()) { final MarkerMetadataSet mdb = new MarkerMetadataSet(); mdb.setDataset(dataset); mdb.setMarkerId(marker.getMarkerId()); mdb.setMarkerSampleId(1); markerMetadataSetList.add(mdb); } return markerMetadataSetList; }
Source:
public void addBasePeerConfigsIfNotPresent(Configuration conf) { String basePeerConfigs = conf.get(HBASE_REPLICATION_PEER_BASE_CONFIG, ""); Map<String,String> receivedPeerConfigMap = this.getConfiguration(); if (basePeerConfigs.length() != 0) { Map<String, String> basePeerConfigMap = Splitter.on(';').trimResults().omitEmptyStrings() .withKeyValueSeparator("=").split(basePeerConfigs); for (Map.Entry<String,String> entry : basePeerConfigMap.entrySet()) { String configName = entry.getKey(); String configValue = entry.getValue(); if (!receivedPeerConfigMap.containsKey(configName)) { receivedPeerConfigMap.put(configName, configValue); } } } }

Target:
public void addBasePeerConfigsIfNotPresent(Configuration conf) { String basePeerConfigs = conf.get(HBASE_REPLICATION_PEER_BASE_CONFIG, ""); if (basePeerConfigs.length() != 0) { Map<String, String> basePeerConfigMap = Splitter.on(';').trimResults().omitEmptyStrings() .withKeyValueSeparator("=").split(basePeerConfigs); for (Map.Entry<String,String> entry : basePeerConfigMap.entrySet()) { String configName = entry.getKey(); String configValue = entry.getValue(); if (!this.getConfiguration().containsKey(configName)) { this.getConfiguration().put(configName, configValue); } } } }
Source:
public List<RowMap> jsonMaps() { ArrayList<RowMap> list = new ArrayList<>(); Object value; for ( Iterator<Row> ri = filteredRows().iterator() ; ri.hasNext(); ) { Row r = ri.next(); RowMap rowMap = new RowMap( getType(), getDatabase().getName(), getTable().getName(), getHeader().getTimestamp() / 1000, table.getPKList(), this.getNextBinlogPosition()); if ( this.txCommit && !ri.hasNext() ) rowMap.setTXCommit(); Iterator<Column> colIter = r.getColumns().iterator(); Iterator<ColumnDef> defIter = table.getColumnList().iterator(); while ( colIter.hasNext() && defIter.hasNext() ) { Column c = colIter.next(); ColumnDef d = defIter.next(); if (c instanceof DatetimeColumn) { value = ((DatetimeColumn) c).getLongValue(); } else { value = c.getValue(); } if ( value != null ) value = d.asJSON(value); rowMap.putData(d.getName(), value); } list.add(rowMap); } return list; }

Target:
public List<RowMap> jsonMaps() { ArrayList<RowMap> list = new ArrayList<>(); Object value; for ( Iterator<Row> ri = filteredRows().iterator() ; ri.hasNext(); ) { Row r = ri.next(); RowMap rowMap = new RowMap( getType(), getDatabase().getName(), getTable().getName(), getHeader().getTimestamp() / 1000, table.getPKList(), this.getNextBinlogPosition()); Iterator<Column> colIter = r.getColumns().iterator(); Iterator<ColumnDef> defIter = table.getColumnList().iterator(); while ( colIter.hasNext() && defIter.hasNext() ) { Column c = colIter.next(); ColumnDef d = defIter.next(); if (c instanceof DatetimeColumn) { value = ((DatetimeColumn) c).getLongValue(); } else { value = c.getValue(); } if ( value != null ) value = d.asJSON(value); rowMap.putData(d.getName(), value); } list.add(rowMap); } return list; }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Calypso_AlertDialog); builder.setTitle(R.string.role); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mListener != null) { String role = mRoleListAdapter.getSelectedRole(); Bundle args = getArguments(); if (args != null) { long personID = args.getLong(PERSON_ID_TAG); int localTableBlogId = args.getInt(PERSON_LOCAL_TABLE_BLOG_ID_TAG); mListener.onRoleChanged(personID, localTableBlogId, role); } } } }); if (mRoleListAdapter == null) { final String[] roles = getResources().getStringArray(R.array.roles); mRoleListAdapter = new RoleListAdapter(getActivity(), R.layout.role_list_row, roles); } Bundle args = getArguments(); if (args != null) { String role = args.getString(ROLE_TAG); mRoleListAdapter.setSelectedRole(role); } builder.setAdapter(mRoleListAdapter, null); return builder.create(); }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.Calypso_AlertDialog); builder.setTitle(R.string.role); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mListener != null) { String role = mRoleListAdapter.getSelectedRole(); Bundle args = getArguments(); if (args != null) { long personID = args.getLong(PERSON_ID_TAG); int localTableBlogId = args.getInt(PERSON_LOCAL_TABLE_BLOG_ID_TAG); mListener.onRoleChanged(personID, localTableBlogId, role); } } } }); if (mRoleListAdapter == null) { final String[] roles = getResources().getStringArray(R.array.roles); mRoleListAdapter = new RoleListAdapter(getActivity(), R.layout.role_list_row, roles); } if (savedInstanceState != null) { String savedRole = savedInstanceState.getString(ROLE_TAG); mRoleListAdapter.setSelectedRole(savedRole); } else { Bundle args = getArguments(); if (args != null) { String role = args.getString(ROLE_TAG); mRoleListAdapter.setSelectedRole(role); } } builder.setAdapter(mRoleListAdapter, null); return builder.create(); }
Source:
public List<Subscription> listSubscriptions(final Set<String> eventTypes, final Optional<String> owningApplication, final int offset, final int limit) throws ServiceTemporarilyUnavailableException { final StringBuilder queryBuilder = new StringBuilder("SELECT s_subscription_object FROM zn_data.subscription "); final List<String> clauses = Lists.newArrayList(); final List<Object> params = Lists.newArrayList(); owningApplication.ifPresent(owningApp -> { clauses.add(" s_subscription_object->>'owning_application' = ? "); params.add(owningApp); }); if (!eventTypes.isEmpty()) { final String clause = eventTypes.stream() .map(et -> " s_subscription_object->'event_types' @> ?::jsonb") .collect(Collectors.joining(" AND ")); clauses.add(clause); eventTypes.stream() .map(et -> format("\"{0}\"", et)) .forEach(params::add); } if (!clauses.isEmpty()) { queryBuilder.append(" WHERE "); queryBuilder.append(StringUtils.join(clauses, " AND ")); } queryBuilder.append(" ORDER BY s_subscription_object->>'created_at' DESC LIMIT ? OFFSET ? "); if (limit >= 0) { params.add(limit); } else { params.add("NULL"); } params.add(offset); try { return jdbcTemplate.query(queryBuilder.toString(), params.toArray(), rowMapper); } catch (final DataAccessException e) { LOG.error("Database error when listing subscriptions", e); throw new ServiceTemporarilyUnavailableException("Error occurred when running database request"); } }

Target:
public List<Subscription> listSubscriptions(final Set<String> eventTypes, final Optional<String> owningApplication, final int offset, final int limit) throws ServiceTemporarilyUnavailableException { final StringBuilder queryBuilder = new StringBuilder("SELECT s_subscription_object FROM zn_data.subscription "); final List<String> clauses = Lists.newArrayList(); final List<Object> params = Lists.newArrayList(); owningApplication.ifPresent(owningApp -> { clauses.add(" s_subscription_object->>'owning_application' = ? "); params.add(owningApp); }); if (!eventTypes.isEmpty()) { final String clause = eventTypes.stream() .map(et -> " s_subscription_object->'event_types' @> ?::jsonb") .collect(Collectors.joining(" AND ")); clauses.add(clause); eventTypes.stream() .map(et -> format("\"{0}\"", et)) .forEach(params::add); } if (!clauses.isEmpty()) { queryBuilder.append(" WHERE "); queryBuilder.append(StringUtils.join(clauses, " AND ")); } queryBuilder.append(" ORDER BY s_subscription_object->>'created_at' DESC LIMIT ? OFFSET ? "); params.add(limit); params.add(offset); try { return jdbcTemplate.query(queryBuilder.toString(), params.toArray(), rowMapper); } catch (final DataAccessException e) { LOG.error("Database error when listing subscriptions", e); throw new ServiceTemporarilyUnavailableException("Error occurred when running database request"); } }
Source:
private void saveVmGuestAgentNetworkDevices() { if (!vmGuestAgentNics.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { for (Guid vmId : vmGuestAgentNics.keySet()) { getDbFacade().getVmGuestAgentInterfaceDao().removeAllForVm(vmId); } for (List<VmGuestAgentInterface> nics : vmGuestAgentNics.values()) { if (nics != null && !nics.isEmpty()) { for (VmGuestAgentInterface nic : nics) { getDbFacade().getVmGuestAgentInterfaceDao().save(nic); } } } return null; } }); } }

Target:
private void saveVmGuestAgentNetworkDevices() { if (!vmGuestAgentNics.isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Void>() { @Override public Void runInTransaction() { for (Guid vmId : vmGuestAgentNics.keySet()) { getDbFacade().getVmGuestAgentInterfaceDao().removeAllForVm(vmId); } for (List<VmGuestAgentInterface> nics : vmGuestAgentNics.values()) { if (nics != null) { for (VmGuestAgentInterface nic : nics) { getDbFacade().getVmGuestAgentInterfaceDao().save(nic); } } } return null; } }); } }
Source:
public void testWaitForViewInstallationDisconnectDS() { InternalDistributedSystem system = getSystem(); ClusterDistributionManager dm = (ClusterDistributionManager) system.getDM(); MembershipView<InternalDistributedMember> view = dm.getDistribution().getView(); AtomicBoolean waitForViewInstallationDone = new AtomicBoolean(); executorService.submit(() -> { try { dm.waitForViewInstallation(view.getViewId() + 1); waitForViewInstallationDone.set(true); } catch (InterruptedException e) { errorCollector.addError(e); } }); await().timeout(2000, TimeUnit.MILLISECONDS); system.disconnect(); await() .untilAsserted(() -> assertThat(waitForViewInstallationDone.get()).isTrue()); }

Target:
public void testWaitForViewInstallationDisconnectDS() throws InterruptedException, TimeoutException, BrokenBarrierException, ExecutionException { InternalDistributedSystem system = getSystem(); ClusterDistributionManager dm = (ClusterDistributionManager) system.getDM(); MembershipView<InternalDistributedMember> view = dm.getDistribution().getView(); CyclicBarrier cyclicBarrier = new CyclicBarrier(2); Future future = executorService.submit(() -> { try { cyclicBarrier.await(getTimeout().toMillis(), TimeUnit.MILLISECONDS); dm.waitForViewInstallation(view.getViewId() + 1); } catch (InterruptedException | BrokenBarrierException | TimeoutException e) { errorCollector.addError(e); } }); cyclicBarrier.await(getTimeout().toMillis(), TimeUnit.MILLISECONDS); system.disconnect(); future.get(getTimeout().toMillis(), TimeUnit.MILLISECONDS); }
Source:
public void Case2() { assertEquals(ImmutableList.of(4, 4, 4, 4, 4, 4), query().from(cat) .select(Expressions.cases().when(cat.toes.eq(2)).then(cat.id.multiply(2)) .when(cat.toes.eq(3)).then(cat.id.multiply(3)) .otherwise(4)).fetch()); List<Integer> rv = query().from(cat) .select(Expressions.cases().when(cat.toes.eq(2)).then(cat.id.multiply(2)) .when(cat.toes.eq(3)).then(cat.id.multiply(3)) .otherwise(4)).fetch(); assertInstancesOf(Integer.class, rv); }

Target:
public void Case2() { assertEquals(ImmutableList.of(4, 4, 4, 4, 4, 4), query().from(cat) .select(Expressions.cases().when(cat.toes.eq(2)).then(cat.id.multiply(2)) .when(cat.toes.eq(3)).then(cat.id.multiply(3)) .otherwise(4)).fetch()); }
Source:
private SpanId getNewSpanId() { Span parentSpan = spanAndEndpoint().state().getCurrentLocalSpan(); if (null == parentSpan) parentSpan = spanAndEndpoint().state().getCurrentServerSpan().getSpan(); long newSpanId = randomGenerator().nextLong(); SpanId.Builder builder = SpanId.builder().spanId(newSpanId); if (parentSpan == null) return builder.build(); return builder.traceId(parentSpan.getTrace_id()).parentId(parentSpan.getId()).build(); }

Target:
private SpanId getNewSpanId() { Span parentSpan = spanAndEndpoint().state().getCurrentLocalSpan(); if (parentSpan == null) { ServerSpan serverSpan = spanAndEndpoint().state().getCurrentServerSpan(); if (serverSpan != null) { parentSpan = serverSpan.getSpan(); } } long newSpanId = randomGenerator().nextLong(); SpanId.Builder builder = SpanId.builder().spanId(newSpanId); if (parentSpan == null) return builder.build(); return builder.traceId(parentSpan.getTrace_id()).parentId(parentSpan.getId()).build(); }
Source:
public List<Service> getServicesBlockedOnDestination(int destinationId) { return jdbc .query("select " + ServicesManagerImpl.serviceMappingSelectQuery + " from services left join service_denials on service_denials.service_id = services.id where service_denials.destination_id = ?", ServicesManagerImpl.SERVICE_MAPPER, destinationId); }

Target:
public List<Service> getServicesBlockedOnDestination(int destinationId) throws InternalErrorException { try { return jdbc .query("select " + ServicesManagerImpl.serviceMappingSelectQuery + " from services left join service_denials on service_denials.service_id = services.id where service_denials.destination_id = ?", ServicesManagerImpl.SERVICE_MAPPER, destinationId); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
private void manipulatingFlattenJson(JsonElement in, String prefix) { if (in.isJsonObject()) { JsonObject obj = in.getAsJsonObject(); if (StringUtils.countMatches(prefix, ".") > 1) { addHeuristicValue(obj, prefix); return; } for (Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); manipulatingFlattenJson(value, appendPrefix(prefix, key)); } } else if (in.isJsonArray()) { JsonArray arrayObj = in.getAsJsonArray(); boolean isAllJsonObject = arrayObj.size() > 0 ? StreamSupport.stream(arrayObj.spliterator(), false).allMatch(x -> x.isJsonObject()) : false; if (isAllJsonObject) { Map<String, Integer> occurents = new HashMap<>(); for (JsonElement element : arrayObj) { JsonObject obj = element.getAsJsonObject(); for (Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); occurents.merge(key, 1, Integer::sum); } } JsonObject newObj = new JsonObject(); for (String key : occurents.keySet()) { if (newObj.get(key) == null) { newObj.add(key, new JsonArray()); } StreamSupport.stream(arrayObj.spliterator(), false).forEach(x -> { newObj.get(key).getAsJsonArray().add(x.getAsJsonObject().get(key)); }); } manipulatingFlattenJson(newObj, prefix); } else { flatten.add(prefix, new JsonPrimitive("String value")); } } else if (in.isJsonPrimitive()) { flatten.add(prefix, in.getAsJsonPrimitive()); } else { flatten.add(prefix, JsonNull.INSTANCE); } }

Target:
private void manipulatingFlattenJson(JsonElement in, String prefix) { if (in.isJsonObject()) { JsonObject obj = in.getAsJsonObject(); if (StringUtils.countMatches(prefix, ".") > 1) { addHeuristicValue(obj, prefix); return; } if (obj.entrySet().isEmpty()) { flatten.add(prefix, obj); } else { for (Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); manipulatingFlattenJson(value, appendPrefix(prefix, key)); } } } else if (in.isJsonArray()) { JsonArray arrayObj = in.getAsJsonArray(); boolean isAllJsonObject = arrayObj.size() > 0 && StreamSupport.stream(arrayObj.spliterator(), false).allMatch(JsonElement::isJsonObject); if (isAllJsonObject) { Map<String, Integer> occurents = new HashMap<>(); for (JsonElement element : arrayObj) { JsonObject obj = element.getAsJsonObject(); for (Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); occurents.merge(key, 1, Integer::sum); } } JsonObject newObj = new JsonObject(); for (String key : occurents.keySet()) { newObj.add(key, new JsonArray()); for (JsonElement elem : arrayObj) { newObj.get(key).getAsJsonArray().add(elem.getAsJsonObject().get(key)); } } manipulatingFlattenJson(newObj, prefix); } else { flatten.add(prefix, new JsonPrimitive("String value")); } } else if (in.isJsonPrimitive()) { flatten.add(prefix, in.getAsJsonPrimitive()); } else { flatten.add(prefix, JsonNull.INSTANCE); } }
Source:
public C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); }

Target:
public final C convert(K key, V oldValue, Metadata oldMetadata, V newValue, Metadata newMetadata, EventType eventType) { return filterAndConvert(key, oldValue, oldMetadata, newValue, newMetadata, eventType); }
Source:
public boolean readAndDispatch () { checkDevice (); runSkin (); runDeferredLayouts (); boolean events = false; events |= runSettings (); events |= runPopups (); OS.gdk_threads_leave(); events |= OS.g_main_context_iteration (0, false); if (events && eventQueue != null) { runDeferredEvents (); return true; } return isDisposed () || runAsyncMessages (false); }

Target:
public boolean readAndDispatch () { checkDevice (); runSkin (); runDeferredLayouts (); boolean events = false; events |= runSettings (); events |= runPopups (); OS.gdk_threads_leave(); events |= OS.g_main_context_iteration (0, false); if (events && eventQueue != null) { if (runDeferredEvents ()) return true; } return isDisposed () || runAsyncMessages (false); }