Java Code Examples for net.sourceforge.argparse4j.inf.Namespace#getInt()
The following examples show how to use
net.sourceforge.argparse4j.inf.Namespace#getInt() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IndexTrimCommand.java From clue with Apache License 2.0 | 6 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { int trimPercent = args.getInt("percent"); if (trimPercent < 0 || trimPercent > 100) { throw new IllegalArgumentException("invalid percent: " + trimPercent); } IndexWriter writer = ctx.getIndexWriter(); if (writer != null) { IndexReader reader = ctx.getIndexReader(); writer.deleteDocuments(buildDeleteQuery(trimPercent, reader.maxDoc())); writer.commit(); ctx.refreshReader(); reader = ctx.getIndexReader(); out.println("trim successful, index now contains: " + reader.numDocs() + " docs."); } else { out.println("unable to open writer, index is in readonly mode"); } }
Example 2
Source File: Main.java From pcgen with GNU Lesser General Public License v2.1 | 6 votes |
/** * Initialize Main - must be called before any other getter can be used. * * @param argv the command line arguments to be parsed */ private static Namespace parseCommands(String[] argv) { Namespace args = getParser().parseArgsOrFail(argv); if (args.getInt("verbose") > 0) { Logging.setCurrentLoggingLevel(Logging.DEBUG); } settingsDir = args.getString("settingsdir"); campaignMode = args.getString("campaignmode"); characterSheet = args.get("D"); exportSheet = args.get("E"); partyFile = args.get("p"); characterFile = args.get("c"); outputFile = args.get("o"); startNameGen = args.get("name_generator"); return args; }
Example 3
Source File: OutputGraphCommand.java From socialite with Apache License 2.0 | 6 votes |
@Override protected void run(Bootstrap<SocialiteConfiguration> configBootstrap, Namespace namespace, SocialiteConfiguration config) throws Exception { final int userCount = namespace.getInt("users"); final int maxFollows = namespace.getInt("maxfollows"); final String csvFile = namespace.getString("csv"); GraphGenerator graphGenerator = new ZipZipfGraphGenerator(maxFollows); FileWriter file = new FileWriter(csvFile); try { for( int i = 0; i < userCount; i++ ) { GraphMutation mutation = graphGenerator.next(); file.append( mutation.user.getUserId() + ";" ); for( long follower : mutation.follows ) { file.append( String.valueOf(follower) + ";" ); } file.append("\n"); } } finally { file.flush(); file.close(); } }
Example 4
Source File: Main.java From pcgen with GNU Lesser General Public License v2.1 | 6 votes |
/** * Initialize Main - must be called before any other getter can be used. * * @param argv the command line arguments to be parsed */ private static Namespace parseCommands(String[] argv) { Namespace args = getParser().parseArgsOrFail(argv); if (args.getInt("verbose") > 0) { Logging.setCurrentLoggingLevel(Logging.DEBUG); } settingsDir = args.getString("settingsdir"); campaignMode = args.getString("campaignmode"); characterSheet = args.get("D"); exportSheet = args.get("E"); partyFile = args.get("p"); characterFile = args.get("c"); outputFile = args.get("o"); startNameGen = args.get("name_generator"); return args; }
Example 5
Source File: SearchCommand.java From clue with Apache License 2.0 | 5 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { IndexReader r = ctx.getIndexReader(); IndexSearcher searcher = new IndexSearcher(r); List<String> qlist = args.getList("query"); String qstring = CmdlineHelper.toString(qlist); Query q = null; try{ q = CmdlineHelper.toQuery(qlist, ctx.getQueryBuilder()); } catch(Exception e){ out.println("cannot parse query: "+e.getMessage()); return; } out.println("parsed query: " + q); int count = args.getInt("num"); long start = System.currentTimeMillis(); TopDocs td = searcher.search(q, count); long end = System.currentTimeMillis(); out.println("numhits: " + td.totalHits); out.println("time: " + (end-start) + "ms"); ScoreDoc[] docs = td.scoreDocs; for (ScoreDoc doc : docs){ out.println("doc: " + doc.doc + ", score: " + doc.score); } }
Example 6
Source File: Utils.java From helios with Apache License 2.0 | 5 votes |
/** * Return the timeout value to use, first checking the argument provided to the CLI invocation, * then an environment variable, then the default value. */ private static int parseTimeout( final Namespace options, final String dest, final String envVarName, final int defaultValue) { if (options.getInt(dest) != null) { return options.getInt(dest); } if (System.getenv(envVarName) != null) { // if this is not an integer then let it blow up return Integer.parseInt(System.getenv(envVarName)); } return defaultValue; }
Example 7
Source File: AllTablesReportCommand.java From emodb with Apache License 2.0 | 5 votes |
@Override protected void run(Environment environment, Namespace namespace, EmoConfiguration configuration) throws Exception { String id = namespace.getString("id"); AllTablesReportOptions options = new AllTablesReportOptions(); options.setReadOnly(namespace.getBoolean("readOnly")); List<String> placements = namespace.getList("placements"); if (placements != null && !placements.isEmpty()) { options.setPlacements(ImmutableSet.copyOf(placements)); } Integer shardId = namespace.getInt("shard"); if (shardId != null) { options.setFromShardId(shardId); } String table = namespace.getString("table"); if (table != null) { options.setFromTableUuid(TableUuidFormat.decode(table)); } Injector injector = Guice.createInjector(new EmoModule(configuration, environment, EmoServiceMode.CLI_TOOL)); ContainerLifeCycle containerLifeCycle = new ContainerLifeCycle(); environment.lifecycle().attach(containerLifeCycle); containerLifeCycle.start(); try { AllTablesReportGenerator generator = injector.getInstance(AllTablesReportGenerator.class); AllTablesReportResult result = generator.runReport(id, options); System.out.println(result); } finally { containerLifeCycle.stop(); } }
Example 8
Source File: MergeCommand.java From clue with Apache License 2.0 | 5 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { int count = args.getInt("num"); IndexWriter writer = ctx.getIndexWriter(); if (writer != null) { writer.forceMerge(count, true); writer.commit(); ctx.refreshReader(); } else { out.println("unable to open index writer, index is in readonly mode"); } }
Example 9
Source File: GenerateAesKeyCommand.java From keywhiz with Apache License 2.0 | 5 votes |
@Override public void run(Bootstrap<?> bootstrap, Namespace namespace) throws Exception { char[] password = namespace.getString("storepass").toCharArray(); Path destination = Paths.get(namespace.get("keystore")); int keySize = namespace.getInt("keysize"); String alias = namespace.getString("alias"); generate(password, destination, keySize, alias, SecureRandom.getInstanceStrong()); System.out.println(format("Generated a %d-bit AES key at %s with alias %s", keySize, destination.toAbsolutePath(), alias)); }
Example 10
Source File: RemoveDeviceCommand.java From signal-cli with GNU General Public License v3.0 | 5 votes |
@Override public int handleCommand(final Namespace ns, final Manager m) { if (!m.isRegistered()) { System.err.println("User is not registered."); return 1; } try { int deviceId = ns.getInt("deviceId"); m.removeLinkedDevices(deviceId); return 0; } catch (IOException e) { e.printStackTrace(); return 3; } }
Example 11
Source File: ItemSimilarityProcessor.java From seldon-server with Apache License 2.0 | 5 votes |
public ItemSimilarityProcessor(final Namespace ns) { this.windowSecs = ns.getInt("window_secs"); this.windowProcessed = ns.getInt("window_processed"); this.outputTopic = ns.getString("output_topic"); this.kafkaServers = ns.getString("kafka"); System.out.println(ns); this.streamJaccard = new StreamingJaccardSimilarity(windowSecs, ns.getInt("hashes"), ns.getInt("min_activity")); //createOutputSimilaritiesTimer(ns); }
Example 12
Source File: ServiceParser.java From helios with Apache License 2.0 | 5 votes |
protected FastForwardConfig ffwdConfig(final Namespace options) { if (!options.getBoolean(ffwdEnabled.getDest())) { return null; } return new FastForwardConfig( Optional.ofNullable(options.getString(ffwdAddress.getDest())), options.getInt(ffwdInterval.getDest()), options.getString(ffwdMetricKey.getDest())); }
Example 13
Source File: TimelineRampFollowers.java From socialite with Apache License 2.0 | 5 votes |
@Override public void runCommand(Namespace namespace) { this.getUserGraphService().removeUser(user.getUserId()); // Create the user this.getUserGraphService().createUser(user); // Create all of the users they're going to follow for( int i = 0; i < namespace.getInt("stop"); i++ ) { this.getUserGraphService().getOrCreateUserById("toFollow"+i); } Counter counter = this.getCounter("count"); counter.inc(namespace.getInt("start")); // prime the cache this.getFeedService().getFeedFor(user,TIMELINE_SIZE); // ramp up follower count and measure timeline read at each step for( int i = namespace.getInt("start"); i < namespace.getInt("stop"); i++ ) { // follow the user User toFollow = this.getUserGraphService().getOrCreateUserById("toFollow"+i); this.getUserGraphService().follow(user, toFollow); // send messages from the followed user for( int m = 0; m < 100; m++ ) { this.getFeedService().post( toFollow, ContentGenerator.newContent(toFollow) ); } counter.inc(); measureReadLatency(); } }
Example 14
Source File: AtomixAgent.java From atomix with Apache License 2.0 | 5 votes |
/** * Builds a REST service for the given Atomix instance from the given namespace. * * @param atomix the Atomix instance * @param namespace the namespace from which to build the service * @return the managed REST service */ private static ManagedRestService buildRestService(Atomix atomix, Namespace namespace) { final String httpHost = namespace.getString("http_host"); final Integer httpPort = namespace.getInt("http_port"); return RestService.builder() .withAtomix(atomix) .withAddress(Address.from(httpHost, httpPort)) .build(); }
Example 15
Source File: DocSetInfoCommand.java From clue with Apache License 2.0 | 4 votes |
@Override public void execute(Namespace args, PrintStream out) throws Exception { String field = args.getString("field"); String termVal = null; int bucketSize = args.getInt("size"); if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } IndexReader reader = ctx.getIndexReader(); List<LeafReaderContext> leaves = reader.leaves(); PostingsEnum postingsEnum = null; for (LeafReaderContext leaf : leaves) { LeafReader atomicReader = leaf.reader(); Terms terms = atomicReader.terms(field); if (terms == null){ continue; } if (terms != null && termVal != null){ TermsEnum te = terms.iterator(); if (te.seekExact(new BytesRef(termVal))){ postingsEnum = te.postings(postingsEnum, PostingsEnum.FREQS); int docFreq = te.docFreq(); int minDocId = -1, maxDocId = -1; int doc, count = 0; int[] percentDocs = new int[PERCENTILES.length]; int percentileIdx = 0; while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { maxDocId = doc; if (minDocId == -1) { minDocId = doc; } count ++; double perDocs = (double) count / (double) docFreq * 100.0; while (percentileIdx < percentDocs.length) { if (perDocs > PERCENTILES[percentileIdx]) { percentDocs[percentileIdx] = doc; percentileIdx++; } else { break; } } } // calculate histogram int[] buckets = null; if (maxDocId > 0) { buckets = new int[maxDocId / bucketSize + 1]; postingsEnum = te.postings(postingsEnum, PostingsEnum.FREQS); while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { int bucketIdx = doc / bucketSize; buckets[bucketIdx]++; } } double density = (double) docFreq / (double) (maxDocId - minDocId) ; out.println(String.format("min: %d, max: %d, count: %d, density: %.2f", minDocId, maxDocId, docFreq, density)); out.println("percentiles: " + Arrays.toString(PERCENTILES) + " => " + Arrays.toString(percentDocs)); out.println("histogram: (bucketsize=" + bucketSize+")"); out.println(Arrays.toString(buckets)); } } } }
Example 16
Source File: GlslGenerate.java From graphicsfuzz with Apache License 2.0 | 4 votes |
public static void mainHelper(String[] args, boolean failOnReferencePreparationException) throws ArgumentParserException, InterruptedException, IOException, ReferencePreparationException { final Namespace ns = parse(args); final File referencesDir = ns.get("references"); final File donorsDir = ns.get("donors"); final File outputDir = ns.get("output_dir"); final String prefix = ns.get("prefix"); final int numVariants = ns.getInt("num_variants"); final boolean verbose = ns.getBoolean("verbose"); final IRandom generator = new RandomWrapper(ArgsUtil.getSeedArgument(ns)); final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); fileOps.forceMkdir(outputDir); final File[] referenceShaderJobFiles = fileOps.listShaderJobFiles(referencesDir, (dir, name) -> true); if (referenceShaderJobFiles.length == 0) { LOGGER.warn("Warning: no reference shader jobs found in " + referencesDir.getAbsolutePath() + "."); } else { LOGGER.info("About to generate " + referenceShaderJobFiles.length + " shader famil" + (referenceShaderJobFiles.length == 1 ? "y" : "ies") + ", each with " + numVariants + " variant" + (numVariants == 1 ? "" : "s") + "."); } int referenceCount = 0; for (File shaderJobFile : referenceShaderJobFiles) { LOGGER.info("Generating family " + referenceCount + " from reference " + shaderJobFile.getName() + "."); referenceCount++; final List<String> generateShaderFamilyArgs = getGenerateShaderFamilyArgs(ns, outputDir, shaderJobFile, prefix, generator.nextInt(Integer.MAX_VALUE)); if (verbose) { LOGGER.info("Generating a shader family: " + generateShaderFamilyArgs.stream() .reduce((String item1, String item2) -> item1 + " " + item2).orElse("")); } try { GenerateShaderFamily.mainHelper(generateShaderFamilyArgs.toArray(new String[0])); } catch (ReferencePreparationException referencePreparationException) { LOGGER.info("Generation of shader family was aborted due to problems preparing the " + "reference."); if (failOnReferencePreparationException) { throw referencePreparationException; } } } LOGGER.info("Generation complete."); }
Example 17
Source File: PurgeDatabusEventsCommand.java From emodb with Apache License 2.0 | 4 votes |
@Override protected void run(Bootstrap<EmoConfiguration> bootstrap, Namespace namespace, EmoConfiguration config) throws Exception { String host = namespace.getString("host"); int limit = namespace.getInt("limit"); String subscription = namespace.getString("subscription"); String apiKey = namespace.getString("api_key"); Set<String> tables = Sets.newHashSet(namespace.<String>getList("table")); List<String> keys = namespace.getList("key"); Set<String> keySet = keys != null ? Sets.newHashSet(keys) : null; System.out.println("Connecting..."); URI uri = URI.create(host).resolve(DatabusClient.SERVICE_PATH + "/_raw"); MetricRegistry metricRegistry = bootstrap.getMetricRegistry(); Client client = createDefaultJerseyClient(config.getHttpClientConfiguration(), metricRegistry, ""); QueueService databus = QueueServiceAuthenticator.proxied(new QueueClient(uri, new JerseyEmoClient(client))) .usingCredentials(apiKey); for (;;) { List<Message> events = databus.peek(subscription, 5000); List<String> ids = Lists.newArrayList(); for (Message event : events) { //noinspection unchecked Map<String, String> coord = (Map<String, String>) checkNotNull(event.getPayload()); String table = checkNotNull(coord.get("table")); String key = checkNotNull(coord.get("key")); if (tables.contains(table) && (keySet == null || keySet.contains(key))) { ids.add(event.getId()); if (--limit <= 0) { break; } } } if (ids.isEmpty()) { System.out.println("All matching events of the first " + events.size() + " have been purged."); break; } System.out.println("Purging " + ids.size() + " events..."); databus.acknowledge(subscription, ids); if (limit == 0) { System.out.println("Limit reached."); break; } } }
Example 18
Source File: SingleClusterMonitor.java From kafka-monitor with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { ArgumentParser parser = argParser(); if (args.length == 0) { System.out.println(parser.formatHelp()); System.exit(-1); } Namespace res = parser.parseArgs(args); Map<String, Object> props = new HashMap<>(); // produce service config props.put(ProduceServiceConfig.ZOOKEEPER_CONNECT_CONFIG, res.getString("zkConnect")); props.put(ProduceServiceConfig.BOOTSTRAP_SERVERS_CONFIG, res.getString("brokerList")); if (res.getString("producerClassName") != null) props.put(ProduceServiceConfig.PRODUCER_CLASS_CONFIG, res.getString("producerClassName")); if (res.getString("topic") != null) props.put(ProduceServiceConfig.TOPIC_CONFIG, res.getString("topic")); if (res.getString("producerId") != null) props.put(ProduceServiceConfig.PRODUCER_ID_CONFIG, res.getString("producerId")); if (res.getString("recordDelayMs") != null) props.put(ProduceServiceConfig.PRODUCE_RECORD_DELAY_MS_CONFIG, res.getString("recordDelayMs")); if (res.getString("recordSize") != null) props.put(ProduceServiceConfig.PRODUCE_RECORD_SIZE_BYTE_CONFIG, res.getString("recordSize")); if (res.getString("producerConfig") != null) props.put(ProduceServiceConfig.PRODUCER_PROPS_CONFIG, Utils.loadProps(res.getString("producerConfig"))); props.put(ProduceServiceConfig.PRODUCE_THREAD_NUM_CONFIG, 5); // consume service config if (res.getString("consumerConfig") != null) props.put(ConsumeServiceConfig.CONSUMER_PROPS_CONFIG, Utils.loadProps(res.getString("consumerConfig"))); if (res.getString("consumerClassName") != null) props.put(ConsumeServiceConfig.CONSUMER_CLASS_CONFIG, res.getString("consumerClassName")); if (res.getString("latencyPercentileMaxMs") != null) props.put(ConsumeServiceConfig.LATENCY_PERCENTILE_MAX_MS_CONFIG, res.getString("latencyPercentileMaxMs")); if (res.getString("latencyPercentileGranularityMs") != null) props.put(ConsumeServiceConfig.LATENCY_PERCENTILE_GRANULARITY_MS_CONFIG, res.getString("latencyPercentileGranularityMs")); // topic management service config if (res.getBoolean("autoTopicCreationEnabled") != null) props.put(TopicManagementServiceConfig.TOPIC_CREATION_ENABLED_CONFIG, res.getBoolean("autoTopicCreationEnabled")); if (res.getInt("replicationFactor") != null) props.put(TopicManagementServiceConfig.TOPIC_REPLICATION_FACTOR_CONFIG, res.getInt("replicationFactor")); if (res.getInt("rebalanceMs") != null) props.put(MultiClusterTopicManagementServiceConfig.REBALANCE_INTERVAL_MS_CONFIG, res.getInt("rebalanceMs")); SingleClusterMonitor app = new SingleClusterMonitor(props, "single-cluster-monitor"); app.start(); // metrics export service config props = new HashMap<>(); if (res.getString("reportIntervalSec") != null) props.put(DefaultMetricsReporterServiceConfig.REPORT_INTERVAL_SEC_CONFIG, res.getString("reportIntervalSec")); List<String> metrics = Arrays.asList( "kmf.services:type=consume-service,name=*:topic-partitions-count", "kmf.services:type=produce-service,name=*:produce-availability-avg", "kmf.services:type=consume-service,name=*:consume-availability-avg", "kmf.services:type=produce-service,name=*:records-produced-total", "kmf.services:type=consume-service,name=*:records-consumed-total", "kmf.services:type=consume-service,name=*:records-lost-total", "kmf.services:type=consume-service,name=*:records-lost-rate", "kmf.services:type=consume-service,name=*:records-duplicated-total", "kmf.services:type=consume-service,name=*:records-delay-ms-avg", "kmf.services:type=produce-service,name=*:records-produced-rate", "kmf.services:type=produce-service,name=*:produce-error-rate", "kmf.services:type=consume-service,name=*:consume-error-rate", "kmf.services:type=commit-availability-service,name=*:offsets-committed-total", "kmf.services:type=commit-availability-service,name=*:offsets-committed-avg", "kmf.services:type=commit-availability-service,name=*:failed-commit-offsets-total", "kmf.services:type=commit-availability-service,name=*:failed-commit-offsets-avg", "kmf.services:type=commit-latency-service,name=*:commit-offset-latency-ms-avg", "kmf.services:type=commit-latency-service,name=*:commit-offset-latency-ms-max", "kmf.services:type=commit-latency-service,name=*:commit-offset-latency-ms-99th", "kmf.services:type=commit-latency-service,name=*:commit-offset-latency-ms-999th", "kmf.services:type=commit-latency-service,name=*:commit-offset-latency-ms-9999th", "kmf.services:type=" + ClusterTopicManipulationMetrics.METRIC_GROUP_NAME + ",name=*:topic-creation-metadata-propagation-ms-avg", "kmf.services:type=" + ClusterTopicManipulationMetrics.METRIC_GROUP_NAME + ",name=*:topic-creation-metadata-propagation-ms-max", "kmf.services:type=" + ClusterTopicManipulationMetrics.METRIC_GROUP_NAME + ",name=*:topic-deletion-metadata-propagation-ms-avg", "kmf.services:type=" + ClusterTopicManipulationMetrics.METRIC_GROUP_NAME + ",name=*:topic-deletion-metadata-propagation-ms-max" ); props.put(DefaultMetricsReporterServiceConfig.REPORT_METRICS_CONFIG, metrics); DefaultMetricsReporterService metricsReporterService = new DefaultMetricsReporterService(props, "end-to-end"); metricsReporterService.start(); JolokiaService jolokiaService = new JolokiaService(new HashMap<>(), "end-to-end"); jolokiaService.start(); }
Example 19
Source File: RedosTester.java From ReScue with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) { ArgumentParser parser = ArgumentParsers.newFor("ReScue").build(); parser.defaultHelp(true); parser.description("ReScue is a tool to auto detect ReDoS vulnerabilities in regexes. (noSeeding, noIncubating and noPumping are mutex arguments, and only used for testing)"); parser.addArgument("-q", "--quiet").action(Arguments.storeTrue()).help("Quiet mode, hide input tips."); parser.addArgument("-v", "--visual").action(Arguments.storeTrue()).help("Show e-NFA of the input regex."); parser.addArgument("-ml", "--maxLength").setDefault(128).help("Maximum string length."); parser.addArgument("-pz", "--popSize").setDefault(200).help("Maximum population size."); parser.addArgument("-g", "--generation").setDefault(200).help("Maximum generations."); parser.addArgument("-cp", "--crossPossibility").setDefault("10").help("The crossover possibility, default is 10, means 10%."); parser.addArgument("-mp", "--mutatePossibility").setDefault("10").help("The mutation possibility, default is 10, means 10%."); parser.addArgument("-ns", "--noSeeding").action(Arguments.storeTrue()).help("No seeding version of ReScue, only used for evaluation & testing."); parser.addArgument("-ni", "--noIncubating").action(Arguments.storeTrue()).help("No incubating version of ReScue, only used for evaluation & testing."); parser.addArgument("-np", "--noPumping").action(Arguments.storeTrue()).help("No pumping version of ReScue, only used for evaluation & testing."); if (args.length == 0) { parser.printHelp(); return ; } Namespace ns = null; try { ns = parser.parseArgs(args); System.out.println(ns.getBoolean("unittest")); } catch (ArgumentParserException e1) { e1.printStackTrace(); System.exit(-1); } if (ns.getBoolean("visual")){ RedosTester.testView(); } else { // These values are used for test int sl = 64; // The deprecated seed length int ml = 128; int pz = 200; int g = 200; int mp = 10; int cp = 5; // Read input arguments boolean quiet = ns.getBoolean("quiet"); sl = ns.getInt("maxLength"); ml = ns.getInt("maxLength"); pz = ns.getInt("popSize"); g = ns.getInt("generation"); cp = ns.getInt("crossPossibility"); mp = ns.getInt("mutatePossibility"); if (!quiet) System.out.print("Input regex: "); Scanner input = new Scanner(System.in); String regex = input.hasNextLine() ? input.nextLine() : null; input.close(); if (regex == null || regex.length() < 1) { System.out.println("Please check your regex."); return ; } RedosAttacker atk = null; if (ns.getBoolean("noSeeding")) atk = new GeneticAttackerWithoutSeeding(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100); else if (ns.getBoolean("noIncubating")) atk = new GeneticAttackerWithoutIncubating(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100); else if (ns.getBoolean("noPumping")) atk = new GeneticAttackerWithoutPumping(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100); else atk = new GeneticAttacker(sl, ml, pz, g, (double)mp / (double)100, (double)cp / (double) 100); RedosTester rt = new RedosTester(atk, regex); rt.attackAndPrint(); } }
Example 20
Source File: KnownValueShaderGenerator.java From graphicsfuzz with Apache License 2.0 | 4 votes |
public static void mainHelper(String[] args) throws ArgumentParserException, IOException { final Namespace ns = parse(args); final float rFloat = ns.getFloat("r"); final float gFloat = ns.getFloat("g"); final float bFloat = ns.getFloat("b"); final float aFloat = ns.getFloat("a"); final int maxUniforms = ns.getInt("max_uniforms"); final boolean isVulkan = ns.getBoolean("vulkan"); final IRandom generator = new RandomWrapper(ArgsUtil.getSeedArgument(ns)); final String version = ns.getString("version"); final File shaderJobFile = ns.get("output"); final ShaderJobFileOperations fileOps = new ShaderJobFileOperations(); final TranslationUnit tu = new TranslationUnit(Optional.of(ShadingLanguageVersion.fromVersionString(version)), Arrays.asList( new PrecisionDeclaration("precision highp float;"), new PrecisionDeclaration("precision highp int;"), new VariablesDeclaration(new QualifiedType(BasicType.VEC4, Arrays.asList(new LayoutQualifierSequence( new LocationLayoutQualifier(0)), TypeQualifier.SHADER_OUTPUT)), new VariableDeclInfo("_GLF_color", null, null)), new FunctionDefinition( new FunctionPrototype("main", VoidType.VOID, Collections.emptyList()), new BlockStmt(new ArrayList<>(), false)))); final PipelineInfo pipelineInfo = new PipelineInfo(); final FactManager globalFactManager = new FactManager(null); // A placeholder statement for what will eventually be the color assignment. final Stmt placeholderForColorAssignment = new NullStmt(); tu.getMainFunction().getBody().addStmt(placeholderForColorAssignment); LOGGER.info("About to generate the known value fragment shader" + " with the parameters R = " + rFloat + ", G = " + gFloat + ", B = " + bFloat + " and" + " A = " + aFloat + "."); final ExpressionGenerator expressionGenerator = new ExpressionGenerator(tu, pipelineInfo, generator, globalFactManager); final FactManager mainFactManager = globalFactManager.newScope(); final Expr[] rgbaExprs = Stream.of(rFloat, gFloat, bFloat, aFloat) .map(item -> expressionGenerator.generateExpr( mainFactManager, tu.getMainFunction(), placeholderForColorAssignment, new NumericValue(BasicType.FLOAT, Optional.of(item)))).toArray(Expr[]::new); tu.getMainFunction().getBody().replaceChild(placeholderForColorAssignment, new ExprStmt(new BinaryExpr(new VariableIdentifierExpr("_GLF_color"), new TypeConstructorExpr("vec4", rgbaExprs), BinOp.ASSIGN))); final ShaderJob shaderJob = new GlslShaderJob(Optional.empty(), pipelineInfo, tu); if (maxUniforms > 0) { PruneUniforms.pruneIfNeeded(shaderJob, maxUniforms, Collections.singletonList(Constants.GLF_UNIFORM)); } if (isVulkan) { shaderJob.makeUniformBindings(Optional.empty()); } fileOps.writeShaderJobFile(shaderJob, shaderJobFile); LOGGER.info("Generation complete."); }