auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void downloadPackageWithScope(@RepositoryMapping Repository repository, @PathVariable(name = "packageScope") String packageScope, @PathVariable(name = "packageName") String packageName, @PathVariable(name = "packageNameWithVersion") String packageNameWithVersion, @PathVariable(name = "packageExtension") String packageExtension, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); String pattern = packageName + "-"; final String packageVersion = packageNameWithVersion.replaceAll(pattern, ""); NpmArtifactCoordinates coordinates; try { coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.BAD_REQUEST.value()); response.getWriter().write(e.getMessage()); return; } RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath()); provideArtifactDownloadResponse(request, response, httpHeaders, path); }

Target:
public void downloadPackageWithScope(@RepositoryMapping Repository repository, @PathVariable(name = "packageScope") String packageScope, @PathVariable(name = "packageName") String packageName, @PathVariable(name = "packageNameWithVersion") String packageNameWithVersion, @PathVariable(name = "packageExtension") String packageExtension, @RequestHeader HttpHeaders httpHeaders, HttpServletRequest request, HttpServletResponse response) throws Exception { final String storageId = repository.getStorage().getId(); final String repositoryId = repository.getId(); if (!packageNameWithVersion.startsWith(packageName + "-")) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } final String packageVersion = getPackageVersion(packageNameWithVersion, packageName); NpmArtifactCoordinates coordinates; try { coordinates = NpmArtifactCoordinates.of(String.format("%s/%s", packageScope, packageName), packageVersion); } catch (IllegalArgumentException e) { response.setStatus(HttpStatus.BAD_REQUEST.value()); response.getWriter().write(e.getMessage()); return; } RepositoryPath path = artifactResolutionService.resolvePath(storageId, repositoryId, coordinates.toPath()); provideArtifactDownloadResponse(request, response, httpHeaders, path); }
Source:
public int compareTo(QC t) { if (getId() != 0L && t.getId() != 0L) { if (getId() < t.getId()) return -1; if (getId() > t.getId()) return 1; } else if (getQcType() != null && t.getQcType() != null && getQcDate() != null && t.getQcDate() != null) { int type = getQcType().compareTo(t.getQcType()); if (type != 0) return type; int creator = getQcDate().compareTo(t.getQcDate()); if (creator != 0) return creator; } return 0; }

Target:
public int compareTo(QC t) { if (getId() != AbstractQC.UNSAVED_ID && t.getId() != AbstractQC.UNSAVED_ID) { if (getId() < t.getId()) return -1; if (getId() > t.getId()) return 1; } else if (getQcType() != null && t.getQcType() != null && getQcDate() != null && t.getQcDate() != null) { int type = getQcType().compareTo(t.getQcType()); if (type != 0) return type; int creator = getQcDate().compareTo(t.getQcDate()); if (creator != 0) return creator; } return 0; }
Source:
Set<Broadcast> mergeBroadcastContinuations( Collection<Broadcast> broadcasts ) { return broadcasts.stream() .sorted(Comparator.comparing(Broadcast::getTransmissionEndTime)) .collect( Collector.<Broadcast, ListMultimap<Id, Broadcast>, Set<Broadcast>>of( ArrayListMultimap::create, this::accumulateBroadcastContinuations, this::combineBroadcastContinuations, m -> ImmutableSet.copyOf(m.values()))); }

Target:
Set<Broadcast> mergeBroadcastContinuations(Collection<Broadcast> broadcasts) { return broadcasts.stream() .sorted(Comparator.comparing(Broadcast::getTransmissionEndTime)) .collect( Collector.<Broadcast, ListMultimap<Id, Broadcast>, Set<Broadcast>>of( ArrayListMultimap::create, this::accumulateBroadcastContinuations, this::combineBroadcastContinuations, channelId2broadcasts -> ImmutableSet.copyOf(channelId2broadcasts.values()))); }
Source:
public InlineAnnotatedMethods() { JAnnotationMethod removeAfter = (JAnnotationMethod) forceInlineAnnotationType.getMethod(REMOVE_AFTER_ANNOTATION, JPrimitiveTypeEnum.BOOLEAN.getType(), new ArrayList<JType>(0)); JBooleanLiteral defaultValue = (JBooleanLiteral) removeAfter.getDefaultValue(); removeAfterDefault = defaultValue.getValue(); }

Target:
public InlineAnnotatedMethods() { JAnnotationMethod removeAfter = (JAnnotationMethod) forceInlineAnnotationType.getMethod(REMOVE_AFTER_ANNOTATION, JPrimitiveTypeEnum.BOOLEAN.getType(), new ArrayList<JType>(0)); assert removeAfter != null; JBooleanLiteral defaultValue = (JBooleanLiteral) removeAfter.getDefaultValue(); assert defaultValue != null; removeAfterDefault = defaultValue.getValue(); }
Source:
public void shouldNotifyListenerWhenNewLogIsCreated() throws Exception { final CountDownLatch allowRotationComplete = new CountDownLatch( 1 ); final CountDownLatch rotationComplete = new CountDownLatch( 1 ); String outputFileCreatedMessage = "Output file created"; String rotationCompleteMessage = "Rotation complete"; RotationListener rotationListener = spy( new RotationListener() { @Override public void outputFileCreated( OutputStream out ) { try { allowRotationComplete.await( 1L, TimeUnit.SECONDS ); out.write( outputFileCreatedMessage.getBytes() ); } catch ( InterruptedException | IOException e ) { throw new RuntimeException( e ); } } @Override public void rotationCompleted( OutputStream out ) { rotationComplete.countDown(); try { out.write( rotationCompleteMessage.getBytes() ); } catch ( IOException e ) { throw new RuntimeException( e ); } } } ); ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, 10, 0, 10, rotationExecutor, rotationListener ); write( supplier, "A string longer than 10 bytes" ); write( supplier, "A string longer than 10 bytes" ); allowRotationComplete.countDown(); rotationComplete.await( 1L, TimeUnit.SECONDS ); verify( rotationListener ).outputFileCreated( any( OutputStream.class ) ); verify( rotationListener ).rotationCompleted( any( OutputStream.class ) ); shutDownExecutor( rotationExecutor ); }

Target:
public void shouldNotifyListenerWhenNewLogIsCreated() throws Exception { final CountDownLatch allowRotationComplete = new CountDownLatch( 1 ); final CountDownLatch rotationComplete = new CountDownLatch( 1 ); String outputFileCreatedMessage = "Output file created"; String rotationCompleteMessage = "Rotation complete"; RotationListener rotationListener = spy( new RotationListener() { @Override public void outputFileCreated( OutputStream out ) { try { allowRotationComplete.await( 1L, TimeUnit.SECONDS ); out.write( outputFileCreatedMessage.getBytes() ); } catch ( InterruptedException | IOException e ) { throw new RuntimeException( e ); } } @Override public void rotationCompleted( OutputStream out ) { rotationComplete.countDown(); try { out.write( rotationCompleteMessage.getBytes() ); } catch ( IOException e ) { throw new RuntimeException( e ); } } } ); ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); try { RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier( fileSystem, logFile, 10, 0, 10, rotationExecutor, rotationListener ); write( supplier, "A string longer than 10 bytes" ); write( supplier, "A string longer than 10 bytes" ); allowRotationComplete.countDown(); rotationComplete.await( 1L, TimeUnit.SECONDS ); verify( rotationListener ).outputFileCreated( any( OutputStream.class ) ); verify( rotationListener ).rotationCompleted( any( OutputStream.class ) ); } finally { shutDownExecutor( rotationExecutor ); } }
Source:
public void showForm(ModelMap model, @RequestParam(value = "uuid", required = false) String uuid, @RequestParam(value = "copyFromUuid", required = false) String copyFromUuid) { if (uuid == null) { model.addAttribute("definition", new ScriptedCompositionPatientDataDefinition()); } else { PatientDataDefinition def = Context.getService(PatientDataService.class).getDefinitionByUuid(uuid); if (def instanceof ScriptedCompositionPatientDataDefinition) { ScriptedCompositionPatientDataDefinition definition = (ScriptedCompositionPatientDataDefinition) def; model.addAttribute("definition", definition); } else { throw new RuntimeException("This definition is not of the right class"); } } }

Target:
public void showForm(ModelMap model, @RequestParam(value = "uuid", required = false) String uuid, @RequestParam(value = "copyFromUuid", required = false) String copyFromUuid) { model.put("scriptTypes", TemplateEngineManager.getAvailableTemplateEngineNames()); if (uuid == null) { model.addAttribute("definition", new ScriptedCompositionPatientDataDefinition()); } else { PatientDataDefinition def = Context.getService(PatientDataService.class).getDefinitionByUuid(uuid); if (def instanceof ScriptedCompositionPatientDataDefinition) { ScriptedCompositionPatientDataDefinition definition = (ScriptedCompositionPatientDataDefinition) def; model.addAttribute("definition", definition); } else { throw new RuntimeException("This definition is not of the right class"); } } }
Source:
private Map<Long, InProgressTx> txnBackwardsCompatCheck(Map<Long, InProgressTx> inProgress) { for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) { if (entry.getValue().getExpiration() < 0) { InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), getTxExpiration(defaultLongTimeout), TransactionType.LONG); entry.setValue(compatTx); } else if (entry.getValue().getType() == null) { InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(), TransactionType.SHORT); entry.setValue(compatTx); } } return inProgress; }

Target:
private Map<Long, InProgressTx> txnBackwardsCompatCheck(Map<Long, InProgressTx> inProgress) { for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) { if (entry.getValue().getExpiration() < 0) { long writePointer = entry.getKey(); long expiration = getTxExpirationFromWritePointer(writePointer, defaultLongTimeout); InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), expiration, TransactionType.LONG); entry.setValue(compatTx); } else if (entry.getValue().getType() == null) { InProgressTx compatTx = new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(), TransactionType.SHORT); entry.setValue(compatTx); } } return inProgress; }
Source:
public void testAsExtend() { final TestSubscriber<Object> subscriber = new TestSubscriber<Object>(); final Object value = new Object(); Flowable.just(value).as(new FlowableConverter<Object, Object>() { @Override public Object apply(Flowable<Object> onSubscribe) { onSubscribe.subscribe(subscriber); subscriber.assertNoErrors(); subscriber.assertComplete(); subscriber.assertValue(value); return subscriber.values().get(0); } }); }

Target:
public void testAsExtend() { final TestSubscriber<Object> subscriber = new TestSubscriber<Object>(); final Object value = new Object(); Object returned = Flowable.just(value).as(new FlowableConverter<Object, Object>() { @Override public Object apply(Flowable<Object> onSubscribe) { onSubscribe.subscribe(subscriber); subscriber.assertNoErrors(); subscriber.assertComplete(); subscriber.assertValue(value); return subscriber.values().get(0); } }); assertSame(returned, value); }
Source:
protected Constraint periodDurationTooShort(ConstraintFactory constraintFactory) { return constraintFactory.fromUnfiltered(Exam.class) .filter(exam -> exam.getPeriod() != null) .filter(exam -> exam.getTopicDuration() > exam.getPeriodDuration()) .penalize("Period duration too short", HardSoftScore.ONE_HARD, Exam::getTopicStudentSize); }

Target:
protected Constraint periodDurationTooShort(ConstraintFactory constraintFactory) { return constraintFactory.from(Exam.class) .filter(exam -> exam.getTopicDuration() > exam.getPeriodDuration()) .penalizeConfigurable("periodDurationTooShort", Exam::getTopicStudentSize); }
Source:
protected ReqWriter newReqWriter(XmlRpcRequest pRequest) throws XmlRpcException, IOException, SAXException { if (METHOD_LIST.contains(pRequest.getMethodName())) { pRequest = new XmlRpcClientRequestImpl(pRequest.getConfig(), pRequest.getMethodName(), normalizeDoubles(pRequest)); } return super.newReqWriter(pRequest); }

Target:
protected ReqWriter newReqWriter(XmlRpcRequest pRequest) throws XmlRpcException, IOException, SAXException { if (METHOD_LIST.contains(pRequest.getMethodName())) { pRequest = new XmlRpcClientRequestImpl(pRequest.getConfig(), pRequest.getMethodName(), normalizeLongs(pRequest)); } return super.newReqWriter(pRequest); }
Source:
public UserDTO getByName(final String userName) throws UserRetrievalException { loginAdminUser(); UserDTO dto = securedUserManager.getBySubjectName(userName); logoutAdminUser(); return dto; }

Target:
public UserDTO getByName(final String userName) throws UserRetrievalException { UserDTO dto = securedUserManager.getBySubjectName(userName); return dto; }
Source:
public String getBrokerHost(String table) { try { List<String> brokers = brokersForTableCache.get(table); if (brokers.isEmpty()) { throw new PinotException(PinotErrorCode.PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "No valid brokers found for " + table); } return brokers.get(ThreadLocalRandom.current().nextInt(brokers.size())); } catch (ExecutionException e) { Throwable err = e.getCause(); if (err instanceof PinotException) { throw (PinotException) err; } else { throw new PinotException(PinotErrorCode.PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "Error when getting brokers for table " + table, err); } } }

Target:
public String getBrokerHost(String table) { try { List<String> brokers = brokersForTableCache.get(table); if (brokers.isEmpty()) { throw new PinotException(PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "No valid brokers found for " + table); } return brokers.get(ThreadLocalRandom.current().nextInt(brokers.size())); } catch (ExecutionException e) { Throwable throwable = e.getCause(); if (throwable instanceof PinotException) { throw (PinotException) throwable; } else { throw new PinotException(PINOT_UNABLE_TO_FIND_BROKER, Optional.empty(), "Error when getting brokers for table " + table, throwable); } } }
Source:
private void writeCanceledFromThreadToMainThread() { mainHandler.post(new Runnable() { @Override public void run() { thread.quit(); boolean success = file.delete(); if (!success) { Log.d(getClass().getSimpleName(), "Failed to delete file " + file.toString()); } } }); }

Target:
private void writeCanceledFromThreadToMainThread() { mainHandler.post(new Runnable() { @Override public void run() { thread.quit(); boolean success = file.delete(); if (!success) { LogExt.d(getClass(), "Failed to delete file " + file.toString()); } } }); }
Source:
private Map<String, String> getTraceProperties() { for (ITmfTrace fTrace : TmfTraceManager.getInstance().getOpenedTraces()) { if (fTrace.getResource().equals(this.getResource())) { if (fTrace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) fTrace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }

Target:
private Map<String, String> getTraceProperties() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(this.getResource())) { if (trace instanceof ITmfTraceProperties) { ITmfTraceProperties traceProperties = (ITmfTraceProperties) trace; return traceProperties.getTraceProperties(); } } } return new HashMap<String, String>(); }
Source:
RequestBuilder(Picasso picasso, Uri uri, int resourceId) { if (picasso.shutdown) { throw new IllegalStateException( "Picasso instance already shut down. " + "Cannot submit new requests."); } this.picasso = picasso; this.uri = uri; this.resourceId = resourceId; }

Target:
RequestBuilder(Picasso picasso, Uri uri, int resourceId) { if (picasso.shutdown) { throw new IllegalStateException( "Picasso instance already shut down. Cannot submit new requests."); } this.picasso = picasso; this.uri = uri; this.resourceId = resourceId; }
Source:
public int getResultFiles(ZipOutputStream target, String provider, String organization, String activity, String resultId) { LOG.trace("Getting file for: providers/{}/organizations/{}/activities/{}/results/{}", organization, activity, resultId); StreamingCallbackHandler handler = new StreamingCallbackHandler(target); jdbcTemplate.query("select object_name, object_content from result_object where data_source = ? and organization = ? and activity = ? and result_id = ?::int order by object_id", new Object[] {provider, organization, activity, resultId}, handler); return handler.getRowCount(); }

Target:
public int getResultFiles(ZipOutputStream target, String provider, String organization, String activity, String resultId) { LOG.trace("Getting file for: providers/{}/organizations/{}/activities/{}/results/{}", provider, organization, activity, resultId); StreamingCallbackHandler handler = new StreamingCallbackHandler(target); jdbcTemplate.query("select object_name, object_content from result_object where data_source = ? and organization = ? and activity = ? and result_id = ?::int order by object_id", new Object[] {provider, organization, activity, resultId}, handler); return handler.getRowCount(); }
Source:
private static boolean validate(CLIParse parser) { boolean fOK = true; if ((!parser.hasArg("enc")) && (!parser.hasArg("dec")) && (!parser.hasArg("pvk")) && (!parser.hasArg("pubkey2ssh"))) { System.out.println("What do you wish me to do? -please specify -enc, -dec, -pvk or -pubkey2ssh"); fOK = false; } if ((parser.hasArg("enc") || parser.hasArg("dec")) && (!parser.hasArg("string"))) { System.out.println("Can't find a string to work with :( -please specify -string='something'."); fOK = false; } if ((!parser.hasArg("store")) || (!new File(parser.getArg("store")).exists())) { System.out.println("Can't find a keystore to work with :( -please specify -store with the correct keystore path."); fOK = false; } if (!parser.hasArg("pass")) { System.out.println("Can't find a keystore pass :( -please specify -pass with the correct keystore password."); fOK = false; } if (!fOK) { printUsage(); } return fOK; }

Target:
private static boolean validate(CLIParse parser) { boolean fOK = true; if ((!parser.hasArg("enc")) && (!parser.hasArg("dec")) && (!parser.hasArg("pvk")) && (!parser.hasArg("pubkey2ssh"))) { System.out.println("What do you wish me to do? -please specify -enc, -dec or -pubkey2ssh"); fOK = false; } if ((parser.hasArg("enc") || parser.hasArg("dec")) && (!parser.hasArg("string"))) { System.out.println("Can't find a string to work with :( -please specify -string='something'."); fOK = false; } if ((!parser.hasArg("store")) || (!new File(parser.getArg("store")).exists())) { System.out.println("Can't find a keystore to work with :( -please specify -store with the correct keystore path."); fOK = false; } if (!parser.hasArg("pass")) { System.out.println("Can't find a keystore pass :( -please specify -pass with the correct keystore password."); fOK = false; } if (!fOK) { printUsage(); } return fOK; }
Source:
protected void run() { try { runInterceptHook(); Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx()); BtcWalletService btcWalletService = processModel.getBtcWalletService(); NetworkParameters params = btcWalletService.getParams(); Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx()); Coin delayedPayoutTxInputValue = preparedDepositTx.getOutput(0).getValue(); String id = processModel.getOffer().getId(); byte[] buyerMultiSigPubKey = processModel.getMyMultiSigPubKey(); DeterministicKey myMultiSigKeyPair = btcWalletService.getMultiSigKeyPair(id, buyerMultiSigPubKey); checkArgument(Arrays.equals(buyerMultiSigPubKey, btcWalletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG).getPubKey()), "buyerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id); byte[] sellerMultiSigPubKey = processModel.getTradingPeer().getMultiSigPubKey(); byte[] delayedPayoutTxSignature = processModel.getTradeWalletService().signDelayedPayoutTx( preparedDelayedPayoutTx, delayedPayoutTxInputValue, myMultiSigKeyPair, buyerMultiSigPubKey, sellerMultiSigPubKey); processModel.setDelayedPayoutTxSignature(delayedPayoutTxSignature); complete(); } catch (Throwable t) { failed(t); } }

Target:
protected void run() { try { runInterceptHook(); Transaction preparedDelayedPayoutTx = checkNotNull(processModel.getPreparedDelayedPayoutTx()); BtcWalletService btcWalletService = processModel.getBtcWalletService(); NetworkParameters params = btcWalletService.getParams(); Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx()); String id = processModel.getOffer().getId(); byte[] buyerMultiSigPubKey = processModel.getMyMultiSigPubKey(); DeterministicKey myMultiSigKeyPair = btcWalletService.getMultiSigKeyPair(id, buyerMultiSigPubKey); checkArgument(Arrays.equals(buyerMultiSigPubKey, btcWalletService.getOrCreateAddressEntry(id, AddressEntry.Context.MULTI_SIG).getPubKey()), "buyerMultiSigPubKey from AddressEntry must match the one from the trade data. trade id =" + id); byte[] sellerMultiSigPubKey = processModel.getTradingPeer().getMultiSigPubKey(); byte[] delayedPayoutTxSignature = processModel.getTradeWalletService().signDelayedPayoutTx( preparedDelayedPayoutTx, preparedDepositTx, myMultiSigKeyPair, buyerMultiSigPubKey, sellerMultiSigPubKey); processModel.setDelayedPayoutTxSignature(delayedPayoutTxSignature); complete(); } catch (Throwable t) { failed(t); } }
Source:
public void visitPrefixExpression(UnaryExpressionTree tree) { if (tree.is(Kind.LOGICAL_COMPLEMENT) && tree.expression().is(Kind.PARENTHESISED_EXPRESSION)) { checkParenthesisedExpression(tree, (ParenthesisedExpressionTree) tree.expression()); } super.visitPrefixExpression(tree); }

Target:
public void visitPrefixExpression(UnaryExpressionTree tree) { if (tree.is(Kind.LOGICAL_COMPLEMENT)) { checkComplementParenthesisedExpression(tree, tree.expression()); } super.visitPrefixExpression(tree); }
Source:
public Iterable<Person> people(Iterable<Publisher> publishers, ApplicationConfiguration config, Selection selection) { Iterable<LookupEntry> entries = selection.apply(peopleLookupEntryStore.entriesForPublishers(publishers, null)); Map<String, LookupEntry> entriesIndex = Maps.uniqueIndex(entries, Functions.compose(LookupRef.TO_URI, LookupEntry.TO_SELF)); Map<String, Person> peopleIndex = Maps.uniqueIndex(peopleForEntries(entriesIndex, config), Identified.TO_URI); ListMultimap<String, Person> idToPeople = keysToPeople(entriesIndex, peopleIndex, LookupRef.TO_URI); return findOrMerge(peopleIndex.keySet(), idToPeople, Identified.TO_URI, config); }

Target:
public Iterable<Person> people(Iterable<Publisher> publishers, ApplicationConfiguration config, Selection selection) { Iterable<LookupEntry> entries = peopleLookupEntryStore.entriesForPublishers(publishers, selection); Map<String, LookupEntry> entriesIndex = Maps.uniqueIndex(entries, Functions.compose(LookupRef.TO_URI, LookupEntry.TO_SELF)); Map<String, Person> peopleIndex = Maps.uniqueIndex(peopleForEntries(entriesIndex, config), Identified.TO_URI); ListMultimap<String, Person> idToPeople = keysToPeople(entriesIndex, peopleIndex, LookupRef.TO_URI); return findOrMerge(peopleIndex.keySet(), idToPeople, Identified.TO_URI, config); }
Source:
private void autoDiscoverLaTeXPath() { try { String command; if (System.getProperty("os.name").contains("Windows")) { command = "where " + ApplicationUtils.TEX_NAME; } else { command = "which " + ApplicationUtils.TEX_NAME; } Process p = Runtime.getRuntime().exec(command); p.waitFor(); File path = new File(new Scanner(p.getInputStream()).nextLine()); if (path != null && path.exists() && path.isFile()) { ApplicationSettings.Setting.LATEX_PATH.setValue(path.getParent()); ApplicationSettings.INSTANCE.save(); } } catch (IOException | InterruptedException | NoSuchElementException | IllegalStateException ex) { } }

Target:
private void autoDiscoverLaTeXPath() { try { String command = (ApplicationUtils.isWindows() ? "where " : "which ") + ApplicationUtils.TEX_NAME; Process p = Runtime.getRuntime().exec(command); p.waitFor(); File path = new File(new Scanner(p.getInputStream()).nextLine()); if (path.exists() && path.isFile() && path.canExecute()) { ApplicationSettings.Setting.LATEX_PATH.setValue(path.getParent()); ApplicationSettings.INSTANCE.save(); } } catch (IOException | InterruptedException | NoSuchElementException | IllegalStateException ex) { LOGGER.log("Couldn't find LaTeX installed on your computer."); LOGGER.log("Go to Tools -> Options -> LaTeX to specify LaTeX directory."); ex.printStackTrace(); } }
Source:
private String formatPlan(PlanNode plan, TypeProvider types) { return inTransaction(session -> textLogicalPlan(plan, types, metadata.getFunctionRegistry(), statsCalculator, costCalculator, session)); }

Target:
private String formatPlan(PlanNode plan, TypeProvider types) { return inTransaction(session -> textLogicalPlan(plan, types, metadata.getFunctionRegistry(), statsCalculator, costCalculator, session, 2, false)); }
Source:
public void createIndexWhileClearOnReplicateRegion() throws Exception { invokeInEveryMember(() -> { Cache cache = ClusterStartupRule.getCache(); cache.createRegionFactory(RegionShortcut.PARTITION) .create("replicateCities"); }, server1, server2); Region replicateCities = clientCacheRule.createProxyRegion("replicateCities"); IntStream.range(0, 100).forEach(i -> replicateCities.put(i, new City(i))); AsyncInvocation createIndex = server1.invokeAsync("create index on replicate regions", () -> { Cache cache = ClusterStartupRule.getCache(); QueryService queryService = cache.getQueryService(); Index cityZip = queryService.createIndex("cityZip_replicate", "c.zip", "/replicateCities c"); assertThat(cityZip).isNotNull(); }); replicateCities.clear(); createIndex.await(); QueryService queryService = clientCache.getQueryService(); Query query = queryService .newQuery("select * from /replicateCities c where c.zip < " + (City.ZIP_START + 10)); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); IntStream.range(0, 10).forEach(i -> replicateCities.put(i, new City(i))); assertThat(((SelectResults) query.execute()).size()).isEqualTo(10); }

Target:
public void createIndexWhileClearOnReplicateRegion() throws Exception { invokeInEveryMember(() -> { Cache cache = ClusterStartupRule.getCache(); cache.createRegionFactory(RegionShortcut.PARTITION) .create("replicateCities"); }, server1, server2); Region replicateCities = clientCacheRule.createProxyRegion("replicateCities"); IntStream.range(0, 1000).forEach(i -> replicateCities.put(i, new City(i))); AsyncInvocation createIndex = server1.invokeAsync("create index on replicate regions", () -> { Cache cache = ClusterStartupRule.getCache(); QueryService queryService = cache.getQueryService(); Index cityZip = queryService.createIndex("cityZip_replicate", "c.zip", "/replicateCities c"); assertThat(cityZip).isNotNull(); }); for (int i = 0; i < 3; i++) { replicateCities.clear(); } createIndex.await(); invokeInEveryMember(() -> { verifyIndexesAfterClear("replicateCities", "cityZip_replicate"); }, server1, server2); QueryService queryService = clientCache.getQueryService(); Query query = queryService .newQuery("select * from /replicateCities c where c.zip < " + (City.ZIP_START + 10)); assertThat(((SelectResults) query.execute()).size()).isEqualTo(0); IntStream.range(0, 10).forEach(i -> replicateCities.put(i, new City(i))); assertThat(((SelectResults) query.execute()).size()).isEqualTo(10); }
Source:
CallbackThrottle create() { switch (type) { case THROTTLE_BY_TIME: return new CallbackThrottleByTime(SchedulerFactory.createFixedRateTimerScheduler(timeUnit.toMillis(frequency))); case THROTTLE_BY_PROGRESS_INCREASE: return new CallbackThrottleByProgressIncrease(); case CUSTOM: return createCallbackThrottle(); default: throw new IllegalStateException("type " + type + " not supported"); } }

Target:
CallbackThrottle create() { switch (type) { case THROTTLE_BY_TIME: ActionScheduler actionScheduler = SchedulerFactory.createFixedRateTimerScheduler(timeUnit.toMillis(frequency)); return new CallbackThrottleByTime(actionScheduler); case THROTTLE_BY_PROGRESS_INCREASE: return new CallbackThrottleByProgressIncrease(); case CUSTOM: return createCallbackThrottle(); default: throw new IllegalStateException("type " + type + " not supported"); } }
Source:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { int retry = 3; boolean valid = false; ChecksumValue providedChecksum = new ChecksumValue(checksum); String algorithm = providedChecksum.getAlgorithm(); String checksumCommand = "echo '%s %s' | %s -c --quiet"; String cmd = String.format(checksumCommand, providedChecksum.getChecksum(), downloadedFilePath, getChecksumCommandFromAlgorithm(algorithm)); int result; while (!valid && retry > 0) { s_logger.debug("Performing checksum validation for downloaded template " + templateId + ", retries left: " + retry); result = Script.runSimpleBashScriptForExitValue(cmd); valid = result == 0; retry--; if (!valid && retry > 0) { s_logger.debug("Checksum validation failded, re-downloading template"); resetDownloadFile(); downloadTemplate(); } } return valid; } return true; }

Target:
public boolean validateChecksum() { if (StringUtils.isNotBlank(checksum)) { int retry = 3; boolean valid = false; try { while (!valid && retry > 0) { s_logger.info("Performing checksum validation for downloaded template " + templateId + ", retries left: " + retry); valid = DigestHelper.check(checksum, new FileInputStream(downloadedFilePath)); retry--; if (!valid && retry > 0) { s_logger.info("Checksum validation failded, re-downloading template"); redownload = true; resetDownloadFile(); downloadTemplate(); } } s_logger.info("Checksum validation for template " + templateId + ": " + (valid ? "succeeded" : "failed")); return valid; } catch (IOException e) { throw new CloudRuntimeException("could not check sum for file: " + downloadedFilePath, e); } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unknown checksum algorithm: " + checksum, e); } } s_logger.info("No checksum provided, skipping checksum validation"); return true; }
Source:
public CohortDefinition getAnyEncounterDuringPeriodWithOccurrence() { EncounterCohortDefinition cd = new EncounterCohortDefinition(); cd.addParameter(new Parameter("onOrAfter", "reporting.parameter.startDate", Date.class)); cd.addParameter(new Parameter("onOrBefore", "reporting.parameter.endDate", Date.class)); cd.addParameter(new Parameter("atLeastCount", "reporting.parameter.atleast", Integer.class)); cd.addParameter(new Parameter("atMostCount", "reporting.parameter.atMost", Integer.class)); cd.addParameter(new Parameter("encounterTypeList", "reporting.parameter.encounterTypeList", EncounterType.class, List.class, null)); cd.addParameter(new Parameter("formList", "reporting.parameter.formList", Form.class, List.class, null)); cd.addParameter(new Parameter("locationList", "reporting.parameter.location", Location.class, List.class, null)); return new MappedParametersCohortDefinition(cd, "onOrAfter", "fromDate", "onOrBefore", "toDate", "encounterTypeList", "encounterTypes", "locationList", "location", "atLeastCount", "atLeast", "atMostCount", "atMost", "formList", "form"); }

Target:
public CohortDefinition getAnyEncounterDuringPeriodWithOccurrence() { EncounterCohortDefinition cd = new EncounterCohortDefinition(); cd.addParameter(new Parameter("onOrAfter", "reporting.parameter.startDate", Date.class)); cd.addParameter(new Parameter("onOrBefore", "reporting.parameter.endDate", Date.class)); cd.addParameter(new Parameter("atLeastCount", "reporting.parameter.atleast", Integer.class)); cd.addParameter(new Parameter("atMostCount", "reporting.parameter.atMost", Integer.class)); cd.addParameter(new Parameter("encounterTypeList", "reporting.parameter.encounterTypeList", EncounterType.class, List.class, null)); cd.addParameter(new Parameter("formList", "reporting.parameter.formList", Form.class, List.class, null)); cd.addParameter(new Parameter("locationList", "reporting.parameter.location", Location.class, List.class, null)); return new MappedParametersCohortDefinition(cd, "onOrAfter", "startDate", "onOrBefore", "endDate", "encounterTypeList", "encounterTypes", "locationList", "locations", "atLeastCount", "atLeast", "atMostCount", "atMost", "formList", "forms"); }
Source:
public String getDisplayName() { return ""; }

Target:
public String getDisplayName() { return Messages.Plot_Series(); }
Source:
@Override public Class getClass(int typeId, ClassLoader ldr) throws ClassNotFoundException, IgniteCheckedException { String clsName; ClassNotFoundException err = null; for (byte platformId : new byte[] {JAVA_ID, DOTNET_ID}) { try { clsName = getClassName(platformId, typeId); if (clsName != null) return U.forName(clsName, ldr, clsFilter); } catch (ClassNotFoundException e) { if (err == null) err = e; } } if (err != null) throw err; throw new ClassNotFoundException("Unknown type ID: " + typeId); }

Target:
@Override public Class getClass(int typeId, ClassLoader ldr) throws ClassNotFoundException, IgniteCheckedException { String clsName = getClassName(JAVA_ID, typeId); if (clsName == null) throw new ClassNotFoundException("Unknown type ID: " + typeId); return U.forName(clsName, ldr, clsFilter); }
Source:
public CompletableFuture<JobMasterGateway> getJobMasterGateway() { Preconditions.checkState( isRunning(), "JobMaster Gateway is not available during initialization"); try { return jobManagerRunnerFuture.thenCompose(JobManagerRunner::getJobMasterGateway); } catch (Throwable e) { throw new IllegalStateException("JobMaster gateway is not available", e); } }

Target:
public CompletableFuture<JobMasterGateway> getJobMasterGateway() { Preconditions.checkState( isInitialized(), "JobMaster Gateway is not available during initialization"); return jobManagerRunnerFuture.thenCompose(JobManagerRunner::getJobMasterGateway); }
Source:
public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); UUID uuid = p.getUniqueId(); Boolean keepininv = stayininvonuse.getValue(); if (!e.getClickedBlock().isPresent() && !SlimefunPlugin.getGrapplingHookListener().isGrappling(uuid)) { e.cancel(); if (p.getInventory().getItemInOffHand().getType() == Material.BOW) { return; } ItemStack item = e.getItem(); if (item.getType() == Material.LEAD) { if (!keepininv) { item.setAmount(item.getAmount() - 1); } } Vector direction = p.getEyeLocation().getDirection().multiply(2.0); Arrow arrow = p.getWorld().spawn(p.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), Arrow.class); arrow.setShooter(p); arrow.setVelocity(direction); Bat bat = (Bat) p.getWorld().spawnEntity(p.getLocation(), EntityType.BAT); bat.setCanPickupItems(false); bat.setAI(false); bat.setSilent(true); bat.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); bat.setLeashHolder(arrow); boolean state = item.getType() != Material.SHEARS; SlimefunPlugin.getGrapplingHookListener().addGrapplingHook(p, arrow, bat, state, despawnTicks.getValue(), keepininv); } }; }

Target:
public ItemUseHandler getItemHandler() { return e -> { Player p = e.getPlayer(); UUID uuid = p.getUniqueId(); boolean consumeOnUseValue = consumeOnUse.getValue(); if (!e.getClickedBlock().isPresent() && !SlimefunPlugin.getGrapplingHookListener().isGrappling(uuid)) { e.cancel(); if (p.getInventory().getItemInOffHand().getType() == Material.BOW) { return; } ItemStack item = e.getItem(); if (item.getType() == Material.LEAD) { if (consumeOnUseValue) { item.setAmount(item.getAmount() - 1); } } Vector direction = p.getEyeLocation().getDirection().multiply(2.0); Arrow arrow = p.getWorld().spawn(p.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), Arrow.class); arrow.setShooter(p); arrow.setVelocity(direction); Bat bat = (Bat) p.getWorld().spawnEntity(p.getLocation(), EntityType.BAT); bat.setCanPickupItems(false); bat.setAI(false); bat.setSilent(true); bat.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 100000, 100000)); bat.setLeashHolder(arrow); boolean state = item.getType() != Material.SHEARS; SlimefunPlugin.getGrapplingHookListener().addGrapplingHook(p, arrow, bat, state, despawnTicks.getValue(), consumeOnUseValue); } }; }
Source:
public void testServiceUsage() { final DomainModelReferenceConverter converter = mock(DomainModelReferenceConverter.class); final VFeaturePathDomainModelReference reference = mock(VFeaturePathDomainModelReference.class); final ServiceRegistration<DomainModelReferenceConverter> converterService = bundleContext.registerService( DomainModelReferenceConverter.class, converter, null); service.getValueProperty(reference); verify(converter).isApplicable(reference); verify(converter).convert(reference); converterService.unregister(); }

Target:
public void testServiceUsage() { final DomainModelReferenceConverter converter = mock(DomainModelReferenceConverter.class); final VFeaturePathDomainModelReference reference = mock(VFeaturePathDomainModelReference.class); when(converter.isApplicable(reference)).thenReturn(0d); final ServiceRegistration<DomainModelReferenceConverter> converterService = bundleContext.registerService( DomainModelReferenceConverter.class, converter, null); service.getValueProperty(reference); verify(converter).isApplicable(reference); verify(converter).convert(reference); converterService.unregister(); }
Source:
public CompletableFuture<Void> downloadAndInstallMod(URL url, @Nullable DoubleProperty progressProperty, @Nullable StringProperty titleProperty) { InstallModTask task = applicationContext.getBean(InstallModTask.class); task.setUrl(url); if (progressProperty != null) { progressProperty.bind(task.progressProperty()); } if (titleProperty != null) { titleProperty.bind(task.titleProperty()); } return taskService.submitTask(task).getFuture() .thenCompose(aVoid -> loadInstalledMods()); }

Target:
public CompletableFuture<Void> downloadAndInstallMod(URL url, @Nullable DoubleProperty progressProperty, @Nullable StringProperty titleProperty) { InstallModTask task = applicationContext.getBean(InstallModTask.class); task.setUrl(url); if (progressProperty != null) { progressProperty.bind(task.progressProperty()); } if (titleProperty != null) { titleProperty.bind(task.titleProperty()); } return taskService.submitTask(task).getFuture() .thenRun(this::loadInstalledMods); }
Source:
public void touchSession() { Date now = new Date(); if (now.getTime() - sessionData.getLastTouchTime() > Prefs.getSessionTimeout() * DateUtils.MINUTE_IN_MILLIS) { long sessionLengthSeconds = (sessionData.getLastTouchTime() - sessionData.getStartTime()) / DateUtils.SECOND_IN_MILLIS; log( "length", sessionLengthSeconds, "fromSearch", sessionData.getPagesFromSearch(), "fromRandom", sessionData.getPagesFromRandom(), "fromLanglink", sessionData.getPagesFromLangLink(), "fromInternal", sessionData.getPagesFromInternal(), "fromExternal", sessionData.getPagesFromExternal(), "fromHistory", sessionData.getPagesFromHistory(), "fromSaved", sessionData.getPagesFromSaved(), "fromNearby", sessionData.getPagesFromNearby(), "fromDisambig", sessionData.getPagesFromDisambig(), "fromBack", sessionData.getPagesFromBack(), "totalPages", sessionData.getTotalPages(), "leadLatency", (long) leadSectionLatency.getAverage(), "restLatency", (long) restSectionsLatency.getAverage(), "apiMode", RbSwitch.INSTANCE.isRestBaseEnabled() ? 1 : 0 ); sessionData = new SessionData(); sessionData.setStartTime(now.getTime()); leadSectionLatency.reset(); restSectionsLatency.reset(); } sessionData.setLastTouchTime(now.getTime()); }

Target:
public void touchSession() { if (hasTimedOut()) { logSessionData(); sessionData = new SessionData(); sessionData.setStartTime(System.currentTimeMillis()); } sessionData.setLastTouchTime(System.currentTimeMillis()); }
Source:
public Integer random(int digit_number) { switch (digit_number) { case 1: return new Random().nextInt(9); case 2: return new Random().nextInt(99); case 3: return new Random().nextInt(999); case 4: return new Random().nextInt(9999); case 5: return new Random().nextInt(99999); case 6: return new Random().nextInt(999999); case 7: return new Random().nextInt(9999999); case 8: return new Random().nextInt(99999999); case 9: return new Random().nextInt(999999999); default: return null; } }

Target:
public Integer random(int digit_number) throws TemplateException { if (digit_number < 1 || digit_number > 9) { throw new TemplateException("Random number " + digit_number + " is out of range", null); } int max = Integer.parseInt(StringUtils.repeat("9", digit_number)); return ThreadLocalRandom.current().nextInt(0, max + 1); }
Source:
public VolumePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus, resources); initListBoxEditors(); initCheckboxEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(constants); initAddBricksButton(); initBricksCountLabele(); driver.initialize(this); virtStoreOptimiseWarningLabel.setText(constants.newVolumeOptimiseForVirtStoreWarning()); virtStoreOptimiseWarningLabel.setVisible(false); }

Target:
public VolumePopupView(EventBus eventBus, ApplicationResources resources, ApplicationConstants constants) { super(eventBus, resources); initListBoxEditors(); initCheckboxEditors(); initWidget(ViewUiBinder.uiBinder.createAndBindUi(this)); ViewIdHandler.idHandler.generateAndSetIds(this); localize(constants); setVisibilities(); initAddBricksButton(); initBricksCountLabele(); driver.initialize(this); }
Source:
public MongoConnector build() throws SchedulerConfigException { if (connector != null) { validateForConnector(); return connector; } final WriteConcern writeConcern = createWriteConcern(); if (database != null) { validateForDatabase(); return new ExternalMongoConnector(writeConcern, database); } if (client != null) { validateForClient(); return new ExternalMongoConnector(writeConcern, client, dbName); } if (uri != null) { validateForUri(); MongoClientURI mongoUri=new MongoClientURI(uri); return new InternalMongoConnector(writeConcern, mongoUri); } checkNotNull(addresses, "At least one MongoDB address or a MongoDB URI must be specified."); final List<ServerAddress> serverAddresses = collectServerAddresses(); final List<MongoCredential> credentials = createCredentials(); final MongoClientOptions options = createOptions(); return new InternalMongoConnector(writeConcern, serverAddresses, credentials, options, dbName); }

Target:
public MongoConnector build() throws SchedulerConfigException { if (connector != null) { validateForConnector(); return connector; } final WriteConcern writeConcern = createWriteConcern(); if (database != null) { validateForDatabase(); return new ExternalMongoConnector(writeConcern, database); } if (uri != null) { validateForUri(); MongoClientURI mongoUri = new MongoClientURI(uri); if(dbName == null){ dbName = mongoUri.getDatabase(); } return new InternalMongoConnector(writeConcern, mongoUri); } checkNotNull(dbName, "'Database name' parameter is required."); if (client != null) { validateForClient(); return new ExternalMongoConnector(writeConcern, client, dbName); } checkNotNull(addresses, "At least one MongoDB address or a MongoDB URI must be specified."); final List<ServerAddress> serverAddresses = collectServerAddresses(); final List<MongoCredential> credentials = createCredentials(); final MongoClientOptions options = createOptions(); return new InternalMongoConnector(writeConcern, serverAddresses, credentials, options, dbName); }
Source:
public T INTO_VALUES(String... values) { List<List<String>> list = sql().values; if(list.isEmpty()){ list.add(new ArrayList<>()); } int index = list.size() - 1; for (String value : values) { list.get(index).add(value); } return getSelf(); }

Target:
public T INTO_VALUES(String... values) { List<String> list = sql().valuesList.get(sql().valuesList.size() - 1); for (String value : values) { list.add(value); } return getSelf(); }
Source:
public static void registerMBean(Object mBeanInstance, ObjectName objectName, MBeanServer mBeanServer) throws Exception { try { SecurityActions.registerMBean(mBeanInstance, objectName, mBeanServer); if (log.isTraceEnabled()) { log.tracef("Registered MBean %s under %s", mBeanInstance, objectName); } } catch (InstanceAlreadyExistsException e) { throw CONTAINER.jmxMBeanAlreadyRegistered(objectName); } catch (Exception e) { throw CONTAINER.jmxCouldNotRegisterMBean(objectName, e); } }

Target:
public static void registerMBean(Object mBeanInstance, ObjectName objectName, MBeanServer mBeanServer) throws Exception { try { SecurityActions.registerMBean(mBeanInstance, objectName, mBeanServer); if (log.isTraceEnabled()) { log.tracef("Registered MBean %s under %s", mBeanInstance, objectName); } } catch (InstanceAlreadyExistsException e) { log.couldNotRegisterObjectName(objectName, e); throw e; } }
Source:
public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); DynamicNodeInstance dynamicContext = (DynamicNodeInstance) ((WorkflowProcessInstanceImpl) processInstance).getNodeInstances(true).stream() .filter(ni -> (ni instanceof DynamicNodeInstance) && stageId.equals(ni.getNode().getMetaData().get("UniqueId"))) .findFirst() .orElse(null); if (dynamicContext == null) { throw new StageNotFoundException("No stage found with id " + stageId); } dynamicContext.signalEvent(fragmentName, data); return null; }

Target:
public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); DynamicNodeInstance dynamicContext = (DynamicNodeInstance) ((WorkflowProcessInstanceImpl) processInstance).getNodeInstances(true).stream() .filter(ni -> (ni instanceof DynamicNodeInstance) && stageId.equals(ni.getNode().getMetaData().get("UniqueId"))) .findFirst() .orElseThrow(() -> new StageNotFoundException("No stage found with id " + stageId)); dynamicContext.signalEvent(fragmentName, data); return null; }