auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Void visitTopNRowNumber(TopNRowNumberNode node, Integer indent) { List<String> partitionBy = Lists.transform(node.getPartitionBy(), Functions.toStringFunction()); List<String> orderBy = Lists.transform(node.getOrderingScheme().getOrderBy(), input -> input + " " + node.getOrderingScheme().getOrderings().get(input)); List<String> args = new ArrayList<>(); args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy))); args.add(format("order by (%s)", Joiner.on(", ").join(orderBy))); print(indent, "- TopNRowNumber[%s limit %s]%s => [%s]", Joiner.on(", ").join(args), node.getMaxRowCountPerPartition(), formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols())); printPlanNodesStats(indent + 2, node); printStats(indent + 2, node.getId()); print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()"); return processChildren(node, indent + 1); }

Target:
public Void visitTopNRowNumber(TopNRowNumberNode node, Integer indent) { List<String> partitionBy = node.getPartitionBy().stream() .map(Functions.toStringFunction()) .collect(toImmutableList()); List<String> orderBy = node.getOrderingScheme().getOrderBy().stream() .map(input -> input + " " + node.getOrderingScheme().getOrdering(input)) .collect(toImmutableList()); List<String> args = new ArrayList<>(); args.add(format("partition by (%s)", Joiner.on(", ").join(partitionBy))); args.add(format("order by (%s)", Joiner.on(", ").join(orderBy))); print(indent, "- TopNRowNumber[%s limit %s]%s => [%s]", Joiner.on(", ").join(args), node.getMaxRowCountPerPartition(), formatHash(node.getHashSymbol()), formatOutputs(node.getOutputSymbols())); printPlanNodesStats(indent + 2, node); printStats(indent + 2, node.getId()); print(indent + 2, "%s := %s", node.getRowNumberSymbol(), "row_number()"); return processChildren(node, indent + 1); }
Source:
public void actionPerformed(ActionEvent e) { final List<java.lang.Class<?>> types = new ArrayList<java.lang.Class<?>>(); types.add(com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class.class); final Frame dialogParent = MDDialogParentProvider.getProvider().getDialogParent(); final ElementSelectionDlg dlg = ElementSelectionDlgFactory.create(dialogParent); SessionManager.getInstance().createSession(Application.getInstance().getProject(), "Creating aspect."); final SelectElementTypes set = new SelectElementTypes(types, types, null, null); final SelectElementInfo sei = new SelectElementInfo(true, false, Application.getInstance().getProject().getModel().getOwner(), true); ArrayList<Classifier> aspects = new ArrayList<>(); findAspectsOfClassifier(aspects); ElementSelectionDlgFactory.initMultiple(dlg,set,sei,aspects); dlg.show(); if (dlg.isOkClicked()) { List<BaseElement> selected = dlg.getSelectedElements(); for(BaseElement be : selected){ System.out.println(be.getHumanName()); Stereotype aspectSt = Utils.getStereotype("aspect"); Utils.createDependencyWithStereotype(classToAddAspect, (Element) be, aspectSt); AspectRemedyAction ara = new AspectRemedyAction(classToAddAspect, (Classifier) be); ara.run(); } } SessionManager.getInstance().closeSession(Application.getInstance().getProject()); }

Target:
public void actionPerformed(ActionEvent e) { final List<java.lang.Class<?>> types = new ArrayList<java.lang.Class<?>>(); types.add(com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class.class); final Frame dialogParent = MDDialogParentProvider.getProvider().getDialogParent(); final ElementSelectionDlg dlg = ElementSelectionDlgFactory.create(dialogParent); SessionManager.getInstance().createSession(Application.getInstance().getProject(), "Creating aspect."); final SelectElementTypes set = new SelectElementTypes(types, types, null, null); final SelectElementInfo sei = new SelectElementInfo(true, false, Application.getInstance().getProject().getModel().getOwner(), true); ArrayList<Classifier> aspects = new ArrayList<>(); findAspectsOfClassifier(aspects); ElementSelectionDlgFactory.initMultiple(dlg, set, sei, aspects); dlg.show(); if (dlg.isOkClicked()) { List<BaseElement> selected = dlg.getSelectedElements(); Element aspectStereotype = Converters.getIdToElementConverter().apply("_18_0_2_407019f_1449688347122_736579_14412", Application.getInstance().getProject()); for (BaseElement be : selected) { System.out.println(be.getHumanName()); if (aspectStereotype != null && aspectStereotype instanceof Stereotype) { Utils.createDependencyWithStereotype(classToAddAspect, (Element) be, (Stereotype) aspectStereotype); AspectRemedyAction ara = new AspectRemedyAction(classToAddAspect, (Classifier) be); ara.run(); } } } SessionManager.getInstance().closeSession(Application.getInstance().getProject()); }
Source:
public void stop(Runnable runnable) { }

Target:
public void stop(Runnable runnable) { stop(); runnable.run(); }
Source:
private boolean iterateLoop() { Iterable.CloseableIterator iterator; long getIteratorStart = System.nanoTime(); try { if (converter == null) { iterator = iterable.getIterator(containerName, filter); } else { iterator = iterable.getIterator(containerName, filter, converter); } stats.registerRequest(System.nanoTime() - getIteratorStart, Iterable.GET_ITERATOR); } catch (Exception e) { log.error("Failed to get the iterator", e); this.failed = true; return true; } int nextFailures = 0; long elements = 0; long loopStart = System.nanoTime(); while (!terminate) { boolean hasNext; long hasNextStart = System.nanoTime(); try { hasNext = iterator.hasNext(); stats.registerRequest(System.nanoTime() - hasNextStart, Iterable.HAS_NEXT); } catch (Exception e) { stats.registerError(System.nanoTime() - hasNextStart, Iterable.HAS_NEXT); hasNext = false; log.error("hasNext() failed", e); } if (!hasNext) break; long nextStart = System.nanoTime(); try { iterator.next(); stats.registerRequest(System.nanoTime() - nextStart, Iterable.NEXT); elements++; } catch (Exception e) { stats.registerError(System.nanoTime() - nextStart, Iterable.NEXT); log.error("next() failed", e); nextFailures++; if (nextFailures >= maxNextFailures) { failed = true; break; } } } if (minElements < 0 || elements < minElements) minElements = elements; if (maxElements < 0 || elements > maxElements) maxElements = elements; try { iterator.close(); } catch (IOException e) { log.error("Failed to close the iterator", e); failed = true; } stats.registerRequest(System.nanoTime() - loopStart, Iterable.FULL_LOOP); return false; }

Target:
private boolean iterateLoop() { Iterable.CloseableIterator iterator; long getIteratorStart = System.nanoTime(); try { if (converter == null) { iterator = iterable.getIterator(containerName, filter); } else { iterator = iterable.getIterator(containerName, filter, converter); } stats.registerRequest(System.nanoTime() - getIteratorStart, Iterable.GET_ITERATOR); } catch (Exception e) { log.error("Failed to get the iterator", e); this.failed = true; return true; } int nextFailures = 0; long elements = 0; long loopStart = System.nanoTime(); while (!terminate) { boolean hasNext; long hasNextStart = System.nanoTime(); try { hasNext = iterator.hasNext(); stats.registerRequest(System.nanoTime() - hasNextStart, Iterable.HAS_NEXT); } catch (Exception e) { stats.registerError(System.nanoTime() - hasNextStart, Iterable.HAS_NEXT); hasNext = false; log.error("hasNext() failed", e); } if (!hasNext) break; long nextStart = System.nanoTime(); try { iterator.next(); stats.registerRequest(System.nanoTime() - nextStart, Iterable.NEXT); elements++; } catch (Exception e) { stats.registerError(System.nanoTime() - nextStart, Iterable.NEXT); log.error("next() failed", e); nextFailures++; if (nextFailures > maxNextFailures) { failed = true; break; } } } if (minElements < 0 || elements < minElements) minElements = elements; if (maxElements < 0 || elements > maxElements) maxElements = elements; try { iterator.close(); } catch (IOException e) { log.error("Failed to close the iterator", e); failed = true; } stats.registerRequest(System.nanoTime() - loopStart, Iterable.FULL_LOOP); return false; }
Source:
public void run() { try (Realm realm = Realm.getDefaultInstance()) { final RealmResults<Person> persons = realm.where(Person.class).findAll(); Realm.Transaction transaction = (Realm r) -> { for (Person person : persons) { person.setAge(person.getAge() + 1); } }; while (!isInterrupted()) { realm.executeTransaction(transaction); Thread.sleep(1000L); } } catch (InterruptedException e) { Log.i(TAG, "Background job stopped."); } }

Target:
public void run() { try (Realm realm = Realm.getDefaultInstance()) { final RealmResults<Person> persons = realm.where(Person.class).findAll(); Realm.Transaction transaction = (Realm r) -> { for (Person person : persons) { person.setAge(person.getAge() + 1); } }; while (!isInterrupted()) { realm.executeTransaction(transaction); SystemClock.sleep(1000L); } } Log.i(TAG, "Background job stopped."); }
Source:
public long timestampCyclesToNanos(long cycles){ long retVal = cycles + getOffset(); if( getTimeScale() != 1.0 ){ retVal = (long)(retVal * getTimeScale()); } return retVal; }

Target:
public long timestampCyclesToNanos(long cycles){ long retVal = cycles + getOffset(); if( clockNeedsScale() ) { retVal = (long)(retVal * getTimeScale()); } return retVal; }
Source:
protected Header generateBasicAuthHeader(HttpUriRequest request, Configuration configuration) { Header basicAuthHeader; BasicScheme basicScheme = new BasicScheme(); try { basicAuthHeader = basicScheme.authenticate( new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()), request, HttpClientContext.create()); } catch (Exception e) { return null; } return basicAuthHeader; }

Target:
protected Header generateBasicAuthHeader(HttpUriRequest request, Configuration configuration) { Header basicAuthHeader; BasicScheme basicScheme = new BasicScheme(); try { basicAuthHeader = basicScheme.authenticate( new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()), request, HttpClientContext.create()); } catch (Exception e) { throw new BasicAuthException(e); } return basicAuthHeader; }
Source:
public String renderSiteContent(Model model, @SiteParam Site site, @PathVariable String pageName) throws IOException { Theme theme = site.getTheme(); Map<String, Object> pageConfig = theme.getConfigMap("siteContent"); String repoKeyPrefix = (String) pageConfig.get("contentRepoKeyPrefix"); if (repoKeyPrefix == null) { throw new RuntimeConfigurationException("Content repo prefix not configured for theme " + theme.toString()); } String repoKey = repoKeyPrefix.concat(".").concat(pageName); String cacheKey = "siteContent_meta:" + repoKey; Optional<Integer> version = Optional.absent(); try { Map<String, Object> pageMetadata = editorialContentService.requestMetadata(CacheParams.create(cacheKey), repoKey, version); } catch (EntityNotFoundException e) { throw new NotFoundException(); } model.addAttribute("siteContentRepoKey", repoKey); return site + "/ftl/siteContent/container"; }

Target:
public String renderSiteContent(Model model, @SiteParam Site site, @PathVariable String pageName) throws IOException { Theme theme = site.getTheme(); Map<String, Object> pageConfig = theme.getConfigMap("siteContent"); String repoKeyPrefix = (String) pageConfig.get("contentRepoKeyPrefix"); if (repoKeyPrefix == null) { throw new RuntimeConfigurationException("Content repo prefix not configured for theme " + theme.toString()); } String repoKey = repoKeyPrefix.concat(".").concat(pageName); String cacheKey = "siteContent_meta:" + repoKey; Optional<Integer> version = Optional.absent(); try { Map<String, Object> pageMetadata = editorialContentService.requestMetadata(CacheParams.create(cacheKey), repoKey, version); } catch (EntityNotFoundException e) { throw new NotFoundException(e); } model.addAttribute("siteContentRepoKey", repoKey); return site + "/ftl/siteContent/container"; }
Source:
public void testTableViewDuringRebuilding() throws Exception { isPersistenceEnabled = true; IgniteEx srv = startGrid(getConfiguration()); srv.cluster().active(true); String cacheName1 = "CACHE_1"; String cacheSqlName1 = "SQL_PUBLIC_" + cacheName1; String cacheName2 = "CACHE_2"; String cacheSqlName2 = "SQL_PUBLIC_" + cacheName2; execSql("CREATE TABLE " + cacheName1 + " (ID1 INT PRIMARY KEY, MY_VAL VARCHAR)"); execSql("CREATE INDEX IDX_1 ON "+ cacheName1 + " (MY_VAL DESC)"); execSql("CREATE TABLE " + cacheName2 + " (ID INT PRIMARY KEY, MY_VAL VARCHAR)"); execSql("CREATE INDEX IDX_2 ON " + cacheName2 + " (ID DESC)"); execSql("INSERT INTO " + cacheName1 + " VALUES(?, ?)", 1, "12345"); execSql("INSERT INTO " + cacheName2 + " VALUES(?, ?)", 1, "12345"); List<Path> idxPaths = getIndexBinPaths(cacheSqlName1); idxPaths.addAll(getIndexBinPaths(cacheSqlName2)); stopAllGrids(); idxPaths.forEach(idxPath -> assertTrue(U.delete(idxPath))); GridQueryProcessor.idxCls = BlockingIndexing.class; srv = startGrid(getConfiguration()); srv.cluster().active(true); checkIndexRebuild(cacheName1, true); checkIndexRebuild(cacheName2, true); ((BlockingIndexing)srv.context().query().getIndexing()).stopBlock(cacheSqlName1); srv.cache(cacheSqlName1).indexReadyFuture().get(); checkIndexRebuild(cacheName1, false); checkIndexRebuild(cacheName2, true); ((BlockingIndexing)srv.context().query().getIndexing()).stopBlock(cacheSqlName2); srv.cache(cacheSqlName2).indexReadyFuture().get(); checkIndexRebuild(cacheName1, false); checkIndexRebuild(cacheName2, false); }

Target:
public void testTableViewDuringRebuilding() throws Exception { isPersistenceEnabled = true; IgniteEx srv = startGrid(getConfiguration()); srv.cluster().active(true); String cacheName1 = "CACHE_1"; String cacheSqlName1 = "SQL_PUBLIC_" + cacheName1; String cacheName2 = "CACHE_2"; String cacheSqlName2 = "SQL_PUBLIC_" + cacheName2; execSql("CREATE TABLE " + cacheName1 + " (ID1 INT PRIMARY KEY, MY_VAL VARCHAR)"); execSql("CREATE INDEX IDX_1 ON "+ cacheName1 + " (MY_VAL DESC)"); execSql("CREATE TABLE " + cacheName2 + " (ID INT PRIMARY KEY, MY_VAL VARCHAR)"); execSql("CREATE INDEX IDX_2 ON " + cacheName2 + " (ID DESC)"); execSql("INSERT INTO " + cacheName1 + " VALUES(?, ?)", 1, "12345"); execSql("INSERT INTO " + cacheName2 + " VALUES(?, ?)", 1, "12345"); List<Path> idxPaths = getIndexBinPaths(cacheSqlName1); idxPaths.addAll(getIndexBinPaths(cacheSqlName2)); stopAllGrids(); idxPaths.forEach(idxPath -> assertTrue(U.delete(idxPath))); GridQueryProcessor.idxCls = BlockingIndexing.class; srv = startGrid(getConfiguration()); srv.cluster().active(true); checkIndexRebuild(cacheName1, true); checkIndexRebuild(cacheName2, true); ((BlockingIndexing)srv.context().query().getIndexing()).stopBlock(cacheSqlName1); srv.cache(cacheSqlName1).indexReadyFuture().get(30_000); checkIndexRebuild(cacheName1, false); checkIndexRebuild(cacheName2, true); ((BlockingIndexing)srv.context().query().getIndexing()).stopBlock(cacheSqlName2); srv.cache(cacheSqlName2).indexReadyFuture().get(30_000); checkIndexRebuild(cacheName1, false); checkIndexRebuild(cacheName2, false); }
Source:
private Map<String, String> sortMapByValue(Map<String, String> map) { List<Map.Entry<String, String>> list = new LinkedList<Map.Entry<String, String>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { private Pattern regex = Pattern.compile(SysprepHandler.TimzeZoneExtractTimePattern); @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { int a = 0, b = 0; Matcher match1 = regex.matcher(o1.toString()); Matcher match2 = regex.matcher(o2.toString()); if (match1.matches() && match1.groupCount() > 0) { a = Integer.parseInt(match1.group(1).substring(3).replace(":", "").replace("+", "")); } if (match2.matches() && match2.groupCount() > 0) { b = Integer.parseInt(match2.group(1).substring(3).replace(":", "").replace("+", "")); } return (a > b) ? 1 : 0; } }); Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); result.put(entry.getKey(), entry.getValue()); } return result; }

Target:
private static Map<String, String> sortMapByValue(Map<String, String> map) { List<Map.Entry<String, String>> list = new LinkedList<Map.Entry<String, String>>(map.entrySet()); Collections.sort(list, TimeZoneTimeExtractComperator.instance); Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); result.put(entry.getKey(), entry.getValue()); } return result; }
Source:
private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, "No specific or invalid MI version", command); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, "command", command, "version", versionString); return; } TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_VERSION, "command", command, "version", versionString); final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }

Target:
private void readVersion() { final String command = fScriptCommand.get(0); final List<String> commandLine = ImmutableList.<@NonNull String> builder() .add(command).add(MI_VERSION_FLAG).build(); final String output = getOutputFromCommand(commandLine); if (output == null) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, INVALID_MI_VERSION, command); return; } final String versionString = output.trim(); if (!versionString.matches("\\d{1,3}\\.\\d{1,3}")) { TraceCompassLogUtils.traceInstant(LOGGER, Level.INFO, LOG_NO_MI_VERSION, COMMAND, command, VERSION, versionString); return; } TraceCompassLogUtils.traceInstant(LOGGER, Level.FINE, LOG_VERSION, COMMAND, command, VERSION, versionString); final String[] parts = versionString.split("\\."); final int major = Integer.valueOf(parts[0]); final int minor = Integer.valueOf(parts[1]); fMiVersion = major * 100 + minor; }
Source:
public void testWhitelistedCapabilities_noWhitelist() throws Exception { final Job job = Job.newBuilder() .setName("foo") .setVersion("1") .setImage("foobar") .setAddedCapabilities(ImmutableSet.of("cap1", "cap2")) .build(); assertEquals(1, validator.validate(job).size()); }

Target:
public void testWhitelistedCapabilities_noWhitelist() throws Exception { final Job job = Job.newBuilder() .setName("foo") .setVersion("1") .setImage("foobar") .setAddCapabilities(ImmutableSet.of("cap1", "cap2")) .build(); assertEquals(1, validator.validate(job).size()); }
Source:
public synchronized int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (formats) { stime = MONTH_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }

Target:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (MONTH_FORMAT) { stime = MONTH_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }
Source:
private static void setupHelixClusterIfNeeded(String helixClusterName, String zkPath) { HelixAdmin admin = new ZKHelixAdmin(zkPath); if (admin.getClusters().contains(helixClusterName)) { LOGGER.info("Helix cluster: already exists", helixClusterName); } else { LOGGER.info("Creating a new Helix cluster: {}", helixClusterName); admin.addCluster(helixClusterName, false); HelixConfigScope configScope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(helixClusterName).build(); Map<String, String> configMap = new HashMap<>(); configMap.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, Boolean.toString(true)); configMap.put(ENABLE_CASE_INSENSITIVE_KEY, Boolean.toString(false)); configMap.put(DEFAULT_HYPERLOGLOG_LOG2M_KEY, Integer.toString(DEFAULT_HYPERLOGLOG_LOG2M)); configMap.put(CommonConstants.Broker.CONFIG_OF_ENABLE_QUERY_LIMIT_OVERRIDE, Boolean.toString(false)); admin.setConfig(configScope, configMap); admin.close(); LOGGER.info("New Helix cluster: created", helixClusterName); } }

Target:
private static void setupHelixClusterIfNeeded(String helixClusterName, String zkPath) { HelixAdmin admin = null; try { admin = new ZKHelixAdmin(zkPath); if (admin.getClusters().contains(helixClusterName)) { LOGGER.info("Helix cluster: already exists", helixClusterName); } else { LOGGER.info("Creating a new Helix cluster: {}", helixClusterName); admin.addCluster(helixClusterName, false); HelixConfigScope configScope = new HelixConfigScopeBuilder(ConfigScopeProperty.CLUSTER).forCluster(helixClusterName).build(); Map<String, String> configMap = new HashMap<>(); configMap.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, Boolean.toString(true)); configMap.put(ENABLE_CASE_INSENSITIVE_KEY, Boolean.toString(false)); configMap.put(DEFAULT_HYPERLOGLOG_LOG2M_KEY, Integer.toString(DEFAULT_HYPERLOGLOG_LOG2M)); configMap.put(CommonConstants.Broker.CONFIG_OF_ENABLE_QUERY_LIMIT_OVERRIDE, Boolean.toString(false)); admin.setConfig(configScope, configMap); LOGGER.info("New Helix cluster: created", helixClusterName); } } finally { if (admin != null) { admin.close(); } } }
Source:
public void setBuildSource(IBuildSource source){ switch(source.getType()) { case BuildSourceType.Git: if(!(source instanceof IGitBuildSource)) { throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); } IGitBuildSource git = (IGitBuildSource) source; set(BUILDCONFIG_SOURCE_REF, git.getRef()); break; } set(BUILDCONFIG_SOURCE_URI, source.getURI()); set(BUILDCONFIG_SOURCE_TYPE, source.getType().toString()); }

Target:
public void setBuildSource(IBuildSource source){ switch(source.getType()) { case BuildSourceType.GIT: if(!(source instanceof IGitBuildSource)) { throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); } IGitBuildSource git = (IGitBuildSource) source; set(BUILDCONFIG_SOURCE_REF, git.getRef()); break; } set(BUILDCONFIG_SOURCE_URI, source.getURI()); set(BUILDCONFIG_SOURCE_TYPE, source.getType().toString()); }
Source:
public void setInputs( final Map<String, Object> inputs ) { if ( inputs == null ) { this.inputs = Collections.emptyMap(); return; } this.inputs = inputs; if ( inputs.containsKey( OUTPUT_TYPE ) ) { setOutputType( String.valueOf( inputs.get( OUTPUT_TYPE ) ) ); } if ( inputs.containsKey( OUTPUT_TARGET ) ) { setOutputTarget( String.valueOf( inputs.get( OUTPUT_TARGET ) ) ); } if ( inputs.containsKey( REPORT_DEFINITION_INPUT ) ) { setReportDefinitionInputStream( (InputStream) inputs.get( REPORT_DEFINITION_INPUT ) ); } if ( inputs.containsKey( PAGINATE_OUTPUT ) ) { paginateOutput = "true".equals( String.valueOf( inputs.get( PAGINATE_OUTPUT ) ) ); } if ( inputs.containsKey( ACCEPTED_PAGE ) ) { acceptedPage = ParserUtil.parseInt( String.valueOf( inputs.get( ACCEPTED_PAGE ) ), -1 ); } if ( inputs.containsKey( PRINT ) ) { print = "true".equals( String.valueOf( inputs.get( PRINT ) ) ); } if ( inputs.containsKey( PRINTER_NAME ) ) { printer = String.valueOf( inputs.get( PRINTER_NAME ) ); } if ( inputs.containsKey( DASHBOARD_MODE ) ) { dashboardMode = "true".equals( String.valueOf( inputs.get( DASHBOARD_MODE ) ) ); } if ( inputs.containsKey( QUERY_LIMIT ) ) { try { if ( this.getReport() != null && inputs.get( QUERY_LIMIT ) != null ) { this.getReport().setQueryLimit( Integer.parseInt( (String) inputs.get( QUERY_LIMIT ) ) ); } } catch ( Exception e ) { log.warn( e.getMessage(), e ); } } }

Target:
public void setInputs( final Map<String, Object> inputs ) { if ( inputs == null ) { this.inputs = Collections.emptyMap(); return; } this.inputs = inputs; if ( inputs.containsKey( OUTPUT_TYPE ) ) { setOutputType( String.valueOf( inputs.get( OUTPUT_TYPE ) ) ); } if ( inputs.containsKey( OUTPUT_TARGET ) ) { setOutputTarget( String.valueOf( inputs.get( OUTPUT_TARGET ) ) ); } if ( inputs.containsKey( REPORT_DEFINITION_INPUT ) ) { setReportDefinitionInputStream( (InputStream) inputs.get( REPORT_DEFINITION_INPUT ) ); } if ( inputs.containsKey( PAGINATE_OUTPUT ) ) { paginateOutput = "true".equals( String.valueOf( inputs.get( PAGINATE_OUTPUT ) ) ); } if ( inputs.containsKey( ACCEPTED_PAGE ) ) { acceptedPage = ParserUtil.parseInt( String.valueOf( inputs.get( ACCEPTED_PAGE ) ), -1 ); } if ( inputs.containsKey( PRINT ) ) { print = "true".equals( String.valueOf( inputs.get( PRINT ) ) ); } if ( inputs.containsKey( PRINTER_NAME ) ) { printer = String.valueOf( inputs.get( PRINTER_NAME ) ); } if ( inputs.containsKey( DASHBOARD_MODE ) ) { dashboardMode = "true".equals( String.valueOf( inputs.get( DASHBOARD_MODE ) ) ); } if ( inputs.containsKey( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ) ) { try { if ( inputs.get( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ) != null ) { this.getReport().setQueryLimit( checkAndGetUserInputQueryLimit( inputs.get( ParameterXmlContentHandler.SYS_PARAM_QUERY_LIMIT ), this.getReport().getQueryLimit() ) ); } } catch ( Exception e ) { log.warn( e.getMessage(), e ); } } }
Source:
private Requester initRequesterForResponsesWithTimeout(int numberOfResponses) throws Exception { RequestOptions requestOptionsMock = mock(RequestOptions.class); MessageTemplate messageTemplateMock = mock(MessageTemplate.class); when(requestOptionsMock.getMessageTemplate()).thenReturn(messageTemplateMock); when(requestOptionsMock.getWaitForResponses()).thenReturn(numberOfResponses); when(requestOptionsMock.isWaitForResponses()).thenReturn(numberOfResponses > 0 ? true : false); when(requestOptionsMock.getResponseTimeout()).thenReturn(100); when(channelManagerMock.findOrCreateProducer(anyString())).thenReturn(producerMock); MsbContext msbContext = TestUtils.createSimpleMsbContext(); msbContext = TestUtils.createMsbContext(msbContext.getMsbConfig(), msbContext.getMessageFactory(), channelManagerMock, msbContext.getClock(), msbContext.getTimeoutManager()); Requester requester = spy(Requester.create("test:requester", requestOptionsMock, null, msbContext)); collectorMock = spy(new Collector(requestOptionsMock, msbContext, eventHandlerMock)); doReturn(collectorMock) .when(requester) .createCollector(any(RequestOptions.class), any(MsbContext.class), any(EventHandlers.class)); return requester; }

Target:
private Requester initRequesterForResponsesWithTimeout(int numberOfResponses) throws Exception { RequestOptions requestOptionsMock = mock(RequestOptions.class); MessageTemplate messageTemplateMock = mock(MessageTemplate.class); when(requestOptionsMock.getMessageTemplate()).thenReturn(messageTemplateMock); when(requestOptionsMock.getWaitForResponses()).thenReturn(numberOfResponses); when(requestOptionsMock.isWaitForResponses()).thenReturn(numberOfResponses > 0 ? true : false); when(requestOptionsMock.getResponseTimeout()).thenReturn(100); when(channelManagerMock.findOrCreateProducer(anyString())).thenReturn(producerMock); MsbContext msbContext = TestUtils.createMsbContextBuilder() .withChannelManager(channelManagerMock) .build(); Requester requester = spy(Requester.create("test:requester", requestOptionsMock, null, msbContext)); collectorMock = spy(new Collector(requestOptionsMock, msbContext, eventHandlerMock)); doReturn(collectorMock) .when(requester) .createCollector(any(RequestOptions.class), any(MsbContext.class), any(EventHandlers.class)); return requester; }
Source:
static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("ContainerPlacementModule", new Version(1, 0, 0, "")); module.addSerializer(ContainerPlacementMessage.class, new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageSerializer()); module.addDeserializer(ContainerPlacementMessage.class, new ContainerPlacementMessageObjectMapper.ContainerPlacementMessageDeserializer()); objectMapper.registerModule(module); objectMapper.registerSubtypes(new NamedType(ContainerPlacementResponseMessage.class)); objectMapper.registerSubtypes(new NamedType(ContainerPlacementRequestMessage.class)); return objectMapper; }

Target:
static ObjectMapper getObjectMapper() { if (objectMapper == null) { objectMapper = createObjectMapper(); } return objectMapper; }
Source:
private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { File inputFile = null; File outputFile = null; try { String localDiskPath = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + file.getId() + file.getName(); inputFile = new File(localDiskPath); ContentUtils.writeToFile(content, inputFile); ProcessBuilder process = new ProcessBuilder(); String outputFilePath = Case.getCurrentCaseThrows().getTempDirectory() + File.separator + file.getId() + "output"; String executeablePath = TESSERACT_PATH.toString(); process.command(executeablePath, String.format("\"%s\"", inputFile.getAbsolutePath()), String.format("\"%s\"", outputFilePath), "-l", LANGUAGE_PACKS); if (processTerminator != null) { ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); } else { ExecUtil.execute(process); } outputFile = new File(outputFilePath + ".txt"); return new CleanUpStream(outputFile); } catch (NoCurrentCaseException | IOException ex) { if (outputFile != null) { outputFile.delete(); } throw new ExtractionException("Could not successfully run Tesseract", ex); } finally { if (inputFile != null) { inputFile.delete(); } } }

Target:
private InputStream runOcrAndGetOutputStream(AbstractFile file) throws ExtractionException { File inputFile = null; File outputFile = null; try { String tempFileName = file.getId() + file.getName(); inputFile = Paths.get(Case.getCurrentCaseThrows().getTempDirectory(), tempFileName).toFile(); ContentUtils.writeToFile(content, inputFile); String tempOutputName = file.getId() + TESSERACT_OUTPUT_FILE_NAME; String outputFilePath = Paths.get(Case.getCurrentCaseThrows().getTempDirectory(), tempOutputName).toString(); String executeablePath = TESSERACT_PATH.toString(); ProcessBuilder process = new ProcessBuilder(); process.command(executeablePath, String.format("\"%s\"", inputFile.getAbsolutePath()), String.format("\"%s\"", outputFilePath), "-l", LANGUAGE_PACKS); if (processTerminator != null) { ExecUtil.execute(process, 1, TimeUnit.SECONDS, processTerminator); } else { ExecUtil.execute(process); } outputFile = new File(outputFilePath + ".txt"); return new CleanUpStream(outputFile); } catch (NoCurrentCaseException | IOException ex) { if (outputFile != null) { outputFile.delete(); } throw new ExtractionException("Could not successfully run Tesseract", ex); } finally { if (inputFile != null) { inputFile.delete(); } } }
Source:
public static double theoreticalSensitivity(final Histogram<Integer> depthHistogram, final Histogram<Integer> qualityHistogram, final int sampleSize, final double logOddsThreshold, final double alleleFraction) { if (alleleFraction > 1.0 || alleleFraction < 0.0) { throw new PicardException("Allele fractions must be between 0 and 1."); } final double[] depthDistribution = normalizeHistogram(depthHistogram); double sensitivity = 0.0; int k = 0; double right = sensitivityAtConstantDepth(k, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); while (k < depthDistribution.length) { double width = 0.0; while (width < DEPTH_BIN_WIDTH && k < depthDistribution.length) { width += depthDistribution[k]; k++; } double left = right; right = sensitivityAtConstantDepth(k, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); sensitivity += width * (left + right) / 2.0; } return sensitivity; }

Target:
public static double theoreticalSensitivity(final Histogram<Integer> depthHistogram, final Histogram<Integer> qualityHistogram, final int sampleSize, final double logOddsThreshold, final double alleleFraction) { if (alleleFraction > 1.0 || alleleFraction < 0.0) { throw new IllegalArgumentException("Allele fractions must be between 0 and 1."); } final double[] depthDistribution = normalizeHistogram(depthHistogram); double sensitivity = 0.0; int currentDepth = 0; double right = 0; while (currentDepth < depthDistribution.length) { double deltaDepthProbability = 0.0; while (deltaDepthProbability == 0 && currentDepth < depthDistribution.length || deltaDepthProbability < DEPTH_BIN_WIDTH && currentDepth < depthDistribution.length && depthDistribution[currentDepth] < DEPTH_BIN_WIDTH / 2.0) { deltaDepthProbability += depthDistribution[currentDepth]; currentDepth++; } final double left = right; right = sensitivityAtConstantDepth(currentDepth, qualityHistogram, logOddsThreshold, sampleSize, alleleFraction); sensitivity += deltaDepthProbability * (left + right) / 2.0; } return sensitivity; }
Source:
public void putAll(Map<K, V> entries) { if (trace) log.tracef("PUT_ALL cache=%s keys=%s", noReturn.getName(), entries); if (preferAsync) { noReturn.putAllAsync(entries); } else { noReturn.putAll(entries); } }

Target:
public void putAll(Map<K, V> entries) { if (trace) log.tracef("PUT_ALL cache=%s keys=%s", noReturn.getName(), entries); if (preferAsync) { Map<K, Future<V>> futures = new HashMap<K, Future<V>>(entries.size()); for (Map.Entry<K, V> entry : entries.entrySet()) { futures.put(entry.getKey(), noReturn.putAsync(entry.getKey(), entry.getValue())); } for (Map.Entry<K, Future<V>> entry : futures.entrySet()) { try { entry.getValue().get(); } catch (Exception e) { throw new RuntimeException(e); } } } else { noReturn.putAll(entries); } }
Source:
public static List<CancerGene> getCancerGeneList() { List<CancerGene> CancerGeneList = new ArrayList<CancerGene>(); try { List<String> lines = FileUtils.readTrimedLinesStream( CancerGeneUtils.class.getResourceAsStream(CANCER_GENE_FILE_PATH)); Iterator itr = lines.iterator(); itr.next(); while(itr.hasNext()) { String[] line = itr.next().toString().split("\t"); if (line.length != 10) continue; CancerGene item = new CancerGene(); item.setHugoSymbol(line[0]); item.setEntrezGeneId(line[1]); item.setOncokbAnnotated(line[2].trim().equals("1") ? true : false); item.setOccurrenceCount(MainUtils.isInteger(line[3].trim()) ? Integer.parseInt(line[3].trim()) : 0); item.setMSKImpact(line[4].trim().equals("1") ? true : false); item.setMSKHeme(line[5].trim().equals("1") ? true : false); item.setFoundation(line[6].trim().equals("1") ? true : false); item.setFoundationHeme(line[7].trim().equals("1") ? true : false); item.setVogelstein(line[8].trim().equals("1") ? true : false); item.setSangerCGC(line[9].trim().equals("1") ? true : false); CancerGeneList.add(item); } } catch (IOException e) { e.printStackTrace(); } return CancerGeneList; }

Target:
public static List<CancerGene> getCancerGeneList() { List<CancerGene> CancerGeneList = new ArrayList<CancerGene>(); try { List<String> lines = FileUtils.readTrimedLinesStream( CancerGeneUtils.class.getResourceAsStream(CANCER_GENE_FILE_PATH)); Iterator itr = lines.iterator(); itr.next(); while(itr.hasNext()) { String[] line = itr.next().toString().split("\t"); if (line.length != 10) continue; CancerGene item = new CancerGene(); item.setHugoSymbol(line[0]); item.setEntrezGeneId(line[1]); item.setOncokbAnnotated(line[2].trim().equals("1")); item.setOccurrenceCount(NumberUtils.isNumber(line[3].trim()) ? Integer.parseInt(line[3].trim()) : 0); item.setmSKImpact(line[4].trim().equals("1")); item.setmSKHeme(line[5].trim().equals("1")); item.setFoundation(line[6].trim().equals("1")); item.setFoundationHeme(line[7].trim().equals("1")); item.setVogelstein(line[8].trim().equals("1")); item.setSangerCGC(line[9].trim().equals("1")); CancerGeneList.add(item); } } catch (IOException e) { e.printStackTrace(); } return CancerGeneList; }
Source:
private boolean isMatchmakerPartyMessage(String channelName) { return channelName.endsWith("'sParty"); }

Target:
private boolean isMatchmakerPartyMessage(String channelName) { return channelName.endsWith(PARTY_CHANNEL_SUFFIX); }
Source:
public void testRecoveryMonitorWithSuccess() throws Exception { XAResource dummy = new XAResource() { @Override public void commit(Xid xid, boolean b) throws XAException { } @Override public void end(Xid xid, int i) throws XAException { } @Override public void forget(Xid xid) throws XAException { } @Override public int getTransactionTimeout() throws XAException { return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override public int prepare(Xid xid) throws XAException { return 0; } @Override public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override public void rollback(Xid xid) throws XAException { } @Override public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override public void start(Xid xid, int i) throws XAException { } }; XATestResourceXARecovery.setUseFaultyResources(false); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(dummy)); assertTrue(tx.enlistResource(dummy)); ut.commit(); manager.scan(); assertFalse(!xaRecoveryModule.isPeriodicWorkSuccessful()); }

Target:
public void testRecoveryMonitorWithSuccess() throws Exception { XAResource dummy = new XAResource() { @Override public void commit(Xid xid, boolean b) throws XAException { } @Override public void end(Xid xid, int i) throws XAException { } @Override public void forget(Xid xid) throws XAException { } @Override public int getTransactionTimeout() throws XAException { return 0; } @Override public boolean isSameRM(XAResource xaResource) throws XAException { return false; } @Override public int prepare(Xid xid) throws XAException { return 0; } @Override public Xid[] recover(int i) throws XAException { return new Xid[0]; } @Override public void rollback(Xid xid) throws XAException { } @Override public boolean setTransactionTimeout(int i) throws XAException { return false; } @Override public void start(Xid xid, int i) throws XAException { } }; XATestResourceXARecovery.setUseFaultyResources(false); UserTransaction ut = com.arjuna.ats.jta.UserTransaction.userTransaction(); ut.begin(); TransactionImple tx = TransactionImple.getTransaction(); assertTrue(tx.enlistResource(dummy)); assertTrue(tx.enlistResource(dummy)); ut.commit(); manager.scan(); assertTrue(xaRecoveryModule.isPeriodicWorkSuccessful()); }
Source:
private ResultScanner<Row> readRows( ReadRowsRequest request, boolean retriable, boolean resumable) { if (retriable) { return new RetryingStreamingResultScanner( retryOptions, request, new BigtableResultScannerFactory() { @Override public ResultScanner<Row> createScanner(ReadRowsRequest request) { return readRows(request, false, false); } }); } if (resumable) { return new ResumingBigtableResultScanner(request, new BigtableResultScannerFactory() { @Override public ResultScanner<Row> createScanner(ReadRowsRequest request) { return readRows(request, false, false); } }); } final Call<ReadRowsRequest, ReadRowsResponse> readRowsCall = channel.newCall(BigtableServiceGrpc.CONFIG.readRows); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner( retryOptions.getStreamingBufferSize(), retryOptions.getReadPartialRowTimeoutMillis(), cancellationToken); Calls.asyncServerStreamingCall( readRowsCall, request, new ReadRowsStreamObserver(resultScanner, readRowsCall)); return resultScanner; }

Target:
private ResultScanner<Row> readRows( ReadRowsRequest request, boolean retriable, boolean resumable) { if (retriable) { return new RetryingStreamingResultScanner(retryOptions, request, streamingScannerFactory); } if (resumable) { return new ResumingBigtableResultScanner(request, streamingScannerFactory); } return createStreamingScanner(request); }
Source:
public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { try { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = createExecutableFlow("exec1"); flow1.getExecutionOptions().setConcurrentOption( ExecutionOptions.CONCURRENT_OPTION_SKIP); User testUser = getTestUser(); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.enableQueueProcessorThread(); manager.submitExecutableFlow(flow1, testUser.getUserId()); Assert.fail("Expecting exception, but didn't get one"); } catch (ExecutorManagerException ex) { System.out.println("Test true"); } }

Target:
public void testDuplicateQueuedFlows() throws ExecutorManagerException, IOException { ExecutorManager manager = createMultiExecutorManagerInstance(); ExecutableFlow flow1 = TestUtils.createExecutableFlow("exectest1", "exec1"); flow1.getExecutionOptions().setConcurrentOption( ExecutionOptions.CONCURRENT_OPTION_SKIP); User testUser = TestUtils.getTestUser(); manager.submitExecutableFlow(flow1, testUser.getUserId()); manager.submitExecutableFlow(flow1, testUser.getUserId()); }
Source:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException { Moh361BCohortDefinition definition = (Moh361BCohortDefinition) cohortDefinition; if (definition == null) return null; String reportDate = sdf.format(context.getEvaluationDate()); String sql = "select person_id" + " from amrsreports_hiv_care_enrollment " + " where " + " first_arv_date is not NULL" + " enrollment_date is not NULL" + " and enrollment_date <= ':reportDate'" + " and enrollment_location_id in ( :locationList )"; List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); sql.replaceAll(":locationList",locationList.toString()); SqlCohortDefinition sqlCohortDefinition = new SqlCohortDefinition(sql.replaceAll(":reportDate", reportDate)); Cohort results = Context.getService(CohortDefinitionService.class).evaluate(sqlCohortDefinition, context); return new EvaluatedCohort(results, sqlCohortDefinition, context); }

Target:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException { Moh361BCohortDefinition definition = (Moh361BCohortDefinition) cohortDefinition; if (definition == null) return null; String reportDate = sdf.format(context.getEvaluationDate()); List<Location> locationList = (List<Location>) context.getParameterValue("locationList"); String sql = "select person_id" + " from amrsreports_hiv_care_enrollment " + " where " + " first_arv_date is not NULL" + " and enrollment_date is not NULL" + " and first_arv_date <= ':reportDate'" + " and first_arv_location_id in ( :locationList )"; SqlCohortDefinition sqlCohortDefinition = new SqlCohortDefinition(sql.replaceAll(":reportDate", reportDate)); Cohort results = Context.getService(CohortDefinitionService.class).evaluate(sqlCohortDefinition, context); return new EvaluatedCohort(results, sqlCohortDefinition, context); }
Source:
public static RandomPasswordEntropy createEntropy(final List<Rule> passwordRules, final PasswordData passwordData) { final Set<Character> uniqueCharacters = new HashSet<>(); passwordRules.stream().forEach((rule) -> { if (rule instanceof CharacterCharacteristicsRule) { final CharacterCharacteristicsRule characteristicRule = (CharacterCharacteristicsRule) rule; characteristicRule.getRules().forEach((characterRule) -> uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters()))); } else if (rule instanceof AllowedCharacterRule) { final AllowedCharacterRule allowedCharacterRule = (AllowedCharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(String.valueOf(allowedCharacterRule.getAllowedCharacters()))); } }); if (uniqueCharacters.isEmpty()) { throw new IllegalArgumentException( "Password rules must contain at least 1 unique character by CharacterRule definition"); } return new RandomPasswordEntropy(uniqueCharacters.size(), passwordData.getPassword().length()); }

Target:
public static RandomPasswordEntropy createEntropy(final List<Rule> passwordRules, final PasswordData passwordData) { if (!passwordData.getOrigin().equals(PasswordData.Origin.Generated)) { throw new IllegalArgumentException("Password data must have an origin of " + PasswordData.Origin.Generated); } final Set<Character> uniqueCharacters = new HashSet<>(); passwordRules.stream().forEach((rule) -> { if (rule instanceof CharacterCharacteristicsRule) { final CharacterCharacteristicsRule characteristicRule = (CharacterCharacteristicsRule) rule; characteristicRule.getRules().forEach((characterRule) -> uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters()))); } else if (rule instanceof CharacterRule) { final CharacterRule characterRule = (CharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(characterRule.getValidCharacters())); } else if (rule instanceof AllowedCharacterRule) { final AllowedCharacterRule allowedCharacterRule = (AllowedCharacterRule) rule; uniqueCharacters.addAll(getUniqueCharacters(String.valueOf(allowedCharacterRule.getAllowedCharacters()))); } }); if (uniqueCharacters.isEmpty()) { throw new IllegalArgumentException( "Password rules must contain at least 1 unique character by CharacterRule definition"); } return new RandomPasswordEntropy(uniqueCharacters.size(), passwordData.getPassword().length()); }
Source:
public static ArrayList<String> readCSVFile(MultipartFile file) throws IOException { BufferedReader reader; ArrayList<String> subjectKeyList = new ArrayList<>(); String line; InputStream is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); Iterable<CSVRecord> csvRecords = csvParser.getRecords(); for (CSVRecord csvRecord : csvRecords) { String participantID = csvRecord.get("ParticipantID"); if (participantID != null && !(participantID.isEmpty())) { subjectKeyList.add(participantID); } } return subjectKeyList; }

Target:
public static ArrayList<String> readCSVFile(MultipartFile file) throws IOException { ArrayList<String> subjectKeyList = new ArrayList<>(); try { BufferedReader reader; String line; InputStream is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); for (CSVRecord csvRecord : csvParser) { String participantID = csvRecord.get("ParticipantID"); if (StringUtils.isNotEmpty(participantID)) { subjectKeyList.add(participantID); } } }catch (Exception e) { log.error("Exception with cause = {}", e.getCause(), e.getMessage()); } return subjectKeyList; }
Source:
String getKeyAsString() { if (key == null || key.getAsString().equals("")) { logger.warn("Found user with null/empty key: " + toString()); return ""; } else { return key.getAsString(); } }

Target:
String getKeyAsString() { if (key == null) { return ""; } else { return key.getAsString(); } }
Source:
public int weigh(EntryKey k, Boolean v) { return 16 + 2 * (16 + 20) + 8 + 8 + 2 * k.mergeStrategy.length() + 1; }

Target:
public int weigh(EntryKey k, Boolean v) { return 16 + 2 * (16 + 20) + 4 * 8 + 1; }
Source:
public void testCompletingCheckoutWithNullPaymentToken() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); try { buyClient.completeCheckout(null, checkout.getToken()); } catch (NullPointerException e) { latch.countDown(); return; } latch.await(); fail("Expected an NullPointerException"); }

Target:
public void testCompletingCheckoutWithNullPaymentToken() throws InterruptedException { try { buyClient.completeCheckout(null, checkout.getToken()); } catch (NullPointerException e) { return; } fail("Expected an NullPointerException"); }
Source:
public void getsAllBatchStatuses_whenServiceAlreadyExists() { downloadManager.initialise(mock(DownloadService.class)); downloadManager.getAllDownloadBatchStatuses(allBatchStatusesCallback); assertThat(downloadBatchStatuses).containsAllOf(BATCH_STATUS, ADDITIONAL_BATCH_STATUS); }

Target:
public void getsAllBatchStatuses_whenServiceAlreadyExists() { downloadManager.initialise(mock(DownloadService.class)); downloadManager.getAllDownloadBatchStatuses(allBatchStatusesCallback); assertThat(downloadBatchStatuses).containsExactly(BATCH_STATUS, ADDITIONAL_BATCH_STATUS); }