/** * Create a new instance of NativeNumber * * @param owningEnvironment The environment in which this native number was created */ public JSNumberConstructor(Environment owningEnvironment) { super(owningEnvironment); int fileIndex = FileContextManager.BUILT_IN_FILE_INDEX; int offset = Range.Empty.getStartingOffset(); // get global IScope global = owningEnvironment.getGlobal(); // put self into environment global.putPropertyValue( "Number", this, fileIndex, Property.DONT_DELETE | Property.DONT_ENUM); // $NON-NLS-1$ // set Number.[[prototype]] IObject function = global.getPropertyValue("Function", fileIndex, offset); // $NON-NLS-1$ IObject functionPrototype = function.getPropertyValue("prototype", fileIndex, offset); // $NON-NLS-1$ this.setPrototype(functionPrototype); // create public prototype object IObject prototype = owningEnvironment.createObject(fileIndex, Range.Empty); // store our public prototype this.putPropertyValue("prototype", prototype, fileIndex); // $NON-NLS-1$ }
private void commandStop(StringTokenizer t) throws NoSessionException { String token; if (!t.hasMoreTokens()) { listEventRequests(); } else { token = t.nextToken(); // Ignore optional "at" or "in" token. // Allowed for backward compatibility. if (token.equals("at") || token.equals("in")) { if (t.hasMoreTokens()) { token = t.nextToken(); } else { env.error("Missing breakpoint specification."); return; } } BreakpointSpec bpSpec = parseBreakpointSpec(token); if (bpSpec != null) { // ### Add sanity-checks for deferred breakpoint. runtime.install(bpSpec); } else { env.error("Ill-formed breakpoint specification."); } } }
private void commandClear(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { // Print set breakpoints listEventRequests(); return; } // ### need 'clear all' BreakpointSpec bpSpec = parseBreakpointSpec(t.nextToken()); if (bpSpec != null) { List<EventRequestSpec> specs = runtime.eventRequestSpecs(); if (specs.isEmpty()) { env.notice("No breakpoints set."); } else { List<EventRequestSpec> toDelete = new ArrayList<EventRequestSpec>(); for (EventRequestSpec spec : specs) { if (spec.equals(bpSpec)) { toDelete.add(spec); } } // The request used for matching should be found if (toDelete.size() <= 1) { env.notice("No matching breakpoint set."); } for (EventRequestSpec spec : toDelete) { runtime.delete(spec); } } } else { env.error("Ill-formed breakpoint specification."); } }
public void draw() { background( theme.getColor(Types.BACKGROUND)); // Draws background, basically refreshes the screen win.setBackground(theme.getColor(Types.BACKGROUND)); sidePanel.setBackground(theme.getColor(Types.SIDEPANEL1)); for (int i = 0; i < SIM_TICKS; i++) { env.updateAllAgents(); // 'Ticks' for the new frame, sensors sense, networks network and // collisions are checked. env.updateCollisions(); // update the environment with the new collisions env.updateAgentsSight(); // update all the agents to everything they can see in their field // of view handleCollisions(); if (!env.fitnessOnly) { checkDeaths(); } updateUI(); autoSnapshot(); } // move drawn region if (arrowsPressed[0] && !arrowsPressed[1]) offsetY -= moveSpeed * zoomLevel; // UP if (arrowsPressed[1] && !arrowsPressed[0]) offsetY += moveSpeed * zoomLevel; // DOWN if (arrowsPressed[2] && !arrowsPressed[3]) offsetX -= moveSpeed * zoomLevel; // LEFT if (arrowsPressed[3] && !arrowsPressed[2]) offsetX += moveSpeed * zoomLevel; // RIGHT win.draw(); fill(255); text("FrameRate: " + frameRate, 10, 10); // Displays framerate in the top left hand corner text("Mouse X: " + mouseX + "Mouse Y: " + mouseY, 10, 30); text("Fish Generation: " + env.getFishGeneration(), 10, 50); text("Ticks to next fish generation: " + (1000 - (env.getTick() % 1000)), 10, 70); }
private void commandMethods(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { env.error("No class specified."); return; } String idClass = t.nextToken(); ReferenceType cls = findClass(idClass); if (cls != null) { List<Method> methods = cls.allMethods(); OutputSink out = env.getOutputSink(); for (int i = 0; i < methods.size(); i++) { Method method = methods.get(i); out.print(method.declaringType().name() + " " + method.name() + "("); Iterator<String> it = method.argumentTypeNames().iterator(); if (it.hasNext()) { while (true) { out.print(it.next()); if (!it.hasNext()) { break; } out.print(", "); } } out.println(")"); } out.show(); } else { // ### Should validate class name syntax. env.failure("\"" + idClass + "\" is not a valid id or class name."); } }
void accept(Environment env) throws TemplateException, IOException { boolean processedCase = false; Iterator iterator = nestedElements.iterator(); try { while (iterator.hasNext()) { Case cas = (Case) iterator.next(); boolean processCase = false; // Fall through if a previous case tested true. if (processedCase) { processCase = true; } else if (!cas.isDefault) { // Otherwise, if this case isn't the default, test it. ComparisonExpression equalsOp = new ComparisonExpression(testExpression, cas.expression, "=="); processCase = equalsOp.isTrue(env); } if (processCase) { env.visit(cas); processedCase = true; } } // If we didn't process any nestedElements, and we have a default, // process it. if (!processedCase && defaultCase != null) { env.visit(defaultCase); } } catch (BreakInstruction.Break br) { } }
/** * Add a new environment and one EnvironmentProperty for each defined property * * @param application * @param environmentName * @return * @throws ValidationException */ @Override public Environment addEnvironment(Application application, String environmentName) throws ValidationException { Application app = applicationDAO.findById(application.getId()); if (app == null) { String[] inserts = new String[] {application.getId().toString()}; throw validationException(INVALID_APPLICATION_MESSAGE, inserts); } for (Environment e : app.getEnvironmentList()) { if (e.getName().equals(environmentName)) { String[] inserts = new String[] {environmentName, app.getName()}; throw validationException(DUPLICATE_ENVIRONMENT_MESSAGE, inserts); } } Environment e = new Environment(); e.setName(environmentName); app.addEnvironment(e); e = environmentDAO.create(e); for (Property p : app.getPropertyList()) { EnvironmentProperty ep = new EnvironmentProperty(); ep.setEnvironment(e); ep.setProperty(p); environmentPropertyDAO.create(ep); } return e; }
/* public String getWindowTitle () { return "What's new in this version - " + Environment.getQuollWriterVersion (); } public String getHeaderTitle () { return this.getWindowTitle (); } public String getHeaderIconType () { return null;//"whatsnew"; } */ public String getFirstHelpText() { return String.format( "Welcome to version <b>%s</b>. This window describes the various changes that have been made since the last version and lets you setup new features. You can also see the <a href='help://version-changes/%s'>full list of changes online</a>.", Environment.getQuollWriterVersion().getVersion(), Environment.getQuollWriterVersion().getVersion().replace('.', '_')); }
@Test public void testgetRegionNetworks() { ProductRelease productRelease = new ProductRelease("product", "2.0"); List<ProductRelease> productReleases = new ArrayList<ProductRelease>(); productReleases.add(productRelease); Tier tier = new Tier("name1", new Integer(1), new Integer(5), new Integer(1), productReleases); tier.setRegion("region1"); tier.addNetwork(new Network("uno2", VDC, REGION)); Tier tier3 = new Tier("name3", new Integer(1), new Integer(5), new Integer(1), productReleases); tier3.setRegion("region3"); tier3.addNetwork(new Network("uno2", VDC, REGION)); Tier tier2 = new Tier("name2", new Integer(1), new Integer(5), new Integer(1), productReleases); tier2.setRegion("region2"); tier2.addNetwork(new Network("uno", VDC, REGION)); Tier tier4 = new Tier("name5", new Integer(1), new Integer(5), new Integer(1), productReleases); tier4.setRegion("region2"); tier4.addNetwork(new Network("uno2", VDC, REGION)); Set<Tier> tiers = new HashSet<Tier>(); tiers.add(tier); tiers.add(tier2); tiers.add(tier3); tiers.add(tier4); Environment envResult = new Environment("environemntName", tiers); Set<String> nets = envResult.getFederatedNetworks(); assertEquals(nets.size(), 1); }
void accept(Environment env) throws IOException, TemplateException { TemplateModel node = targetNode == null ? null : targetNode.getAsTemplateModel(env); TemplateModel nss = namespaces == null ? null : namespaces.getAsTemplateModel(env); if (namespaces instanceof StringLiteral) { nss = env.importLib(((TemplateScalarModel) nss).getAsString(), null); } else if (namespaces instanceof ListLiteral) { nss = ((ListLiteral) namespaces).evaluateStringsToNamespaces(env); } if (node != null && !(node instanceof TemplateNodeModel)) { throw new TemplateException( "Expecting an XML node here, for expression: " + targetNode + ", found a: " + node.getClass().getName(), env); } if (nss != null) { if (nss instanceof TemplateHashModel) { SimpleSequence ss = new SimpleSequence(1); ss.add(nss); nss = ss; } else if (!(nss instanceof TemplateSequenceModel)) { throw new TemplateException("Expecting a sequence of namespaces after 'using'", env); } } env.recurse((TemplateNodeModel) node, (TemplateSequenceModel) nss); }
void accept(Environment env) throws TemplateException, IOException { String templateNameString = templateName.getStringValue(env); if (templateNameString == null) { String msg = "Error " + getStartLocation() + "The expression " + templateName + " is undefined."; throw new InvalidReferenceException(msg, env); } Template importedTemplate; try { if (!env.isClassicCompatible()) { if (templateNameString.indexOf("://") > 0) {; } else if (templateNameString.length() > 0 && templateNameString.charAt(0) == '/') { int protIndex = templatePath.indexOf("://"); if (protIndex > 0) { templateNameString = templatePath.substring(0, protIndex + 2) + templateNameString; } else { templateNameString = templateNameString.substring(1); } } else { templateNameString = templatePath + templateNameString; } } importedTemplate = env.getTemplateForImporting(templateNameString); } catch (ParseException pe) { String msg = "Error parsing imported template " + templateNameString; throw new TemplateException(msg, pe, env); } catch (IOException ioe) { String msg = "Error reading imported file " + templateNameString; throw new TemplateException(msg, ioe, env); } env.importLib(importedTemplate, namespace); }
@Test public void createDefaultEnvironmentReturnsNullValues() throws Exception { Environment env = Environment.createEnvironment(); assertThat(env).isNotNull(); assertThat(env.getApplicationName()).isNull(); assertThat(env.getContextPath()).contains("null"); }
/** * Load Skylark aspect from an extension file. Is to be called from a SkyFunction. * * @return {@code null} if dependencies cannot be satisfied. */ @Nullable public static SkylarkAspect loadSkylarkAspect( Environment env, Label extensionLabel, String skylarkValueName) throws AspectCreationException { SkyKey importFileKey = SkylarkImportLookupValue.key(extensionLabel, false); try { SkylarkImportLookupValue skylarkImportLookupValue = (SkylarkImportLookupValue) env.getValueOrThrow(importFileKey, SkylarkImportFailedException.class); if (skylarkImportLookupValue == null) { return null; } Object skylarkValue = skylarkImportLookupValue.getEnvironmentExtension().get(skylarkValueName); if (!(skylarkValue instanceof SkylarkAspect)) { throw new ConversionException( skylarkValueName + " from " + extensionLabel.toString() + " is not an aspect"); } return (SkylarkAspect) skylarkValue; } catch (SkylarkImportFailedException | ConversionException e) { env.getListener().handle(Event.error(e.getMessage())); throw new AspectCreationException(e.getMessage()); } }
public Writer getWriter(final Writer out, Map args) throws TemplateModelException, IOException { try { Environment env = Environment.getCurrentEnvironment(); boolean lastFIRE = env.setFastInvalidReferenceExceptions(false); try { env.include(template); } finally { env.setFastInvalidReferenceExceptions(lastFIRE); } } catch (Exception e) { throw new _TemplateModelException( e, "Template created with \"?", key, "\" has stopped with this error:\n\n", MessageUtil.EMBEDDED_MESSAGE_BEGIN, new _DelayedGetMessage(e), MessageUtil.EMBEDDED_MESSAGE_END); } return new Writer(out) { @Override public void close() {} @Override public void flush() throws IOException { out.flush(); } @Override public void write(char[] cbuf, int off, int len) throws IOException { out.write(cbuf, off, len); } }; }
/** Test exclusive creation. */ @Test public void testExclusive() throws Throwable { try { EnvironmentConfig envConfig = TestUtils.initEnvConfig(); /* * Make sure that the database keeps its own copy of the * configuration object. */ envConfig.setAllowCreate(true); env = create(envHome, envConfig); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setExclusiveCreate(true); /* Should succeed and create the database. */ Database dbA = env.openDatabase(null, "foo", dbConfig); dbA.close(); /* Should not succeed, because the database exists. */ try { env.openDatabase(null, "foo", dbConfig); fail("Database already exists"); } catch (DatabaseException e) { } close(env); } catch (Throwable t) { t.printStackTrace(); throw t; } }
@Override public SkyValue compute(SkyKey skyKey, Environment env) throws SkyFunctionException, InterruptedException { PathFragment astFilePathFragment = (PathFragment) skyKey.argument(); FileLookupResult lookupResult = getASTFile(env, astFilePathFragment); if (lookupResult == null) { return null; } BuildFileAST ast = null; if (!lookupResult.lookupSuccessful()) { return ASTFileLookupValue.noFile(); } else { Path path = lookupResult.rootedPath().asPath(); // Skylark files end with bzl. boolean parseAsSkylark = astFilePathFragment.getPathString().endsWith(".bzl"); try { ast = parseAsSkylark ? BuildFileAST.parseSkylarkFile( path, env.getListener(), packageManager, ruleClassProvider.getSkylarkValidationEnvironment().clone()) : BuildFileAST.parseBuildFile(path, env.getListener(), packageManager, false); } catch (IOException e) { throw new ASTLookupFunctionException( new ErrorReadingSkylarkExtensionException(e.getMessage()), Transience.TRANSIENT); } } return ASTFileLookupValue.withFile(ast); }
@Override @SuppressWarnings({"unchecked", "rawtypes"}) public void execute( Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Site site = FrontUtils.getSite(env); List<Content> list = getList(params, env); Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params); paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list)); Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap); InvokeType type = DirectiveUtils.getInvokeType(params); String listStyle = DirectiveUtils.getString(PARAM_STYLE_LIST, params); if (InvokeType.sysDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } env.include(TPL_STYLE_LIST + listStyle + TPL_SUFFIX, UTF8, true); } else if (InvokeType.userDefined == type) { if (StringUtils.isBlank(listStyle)) { throw new ParamsRequiredException(PARAM_STYLE_LIST); } FrontUtils.includeTpl(TPL_STYLE_LIST, site, env); } else if (InvokeType.custom == type) { FrontUtils.includeTpl(TPL_NAME, site, params, env); } else if (InvokeType.body == type) { body.render(env.getOut()); } else { throw new RuntimeException("invoke type not handled: " + type); } DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap); }
@Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars env = super.getEnvironment(log); FilePath ws = getWorkspace(); if (ws != null) // if this is done very early on in the build, workspace may not be decided yet. // see HUDSON-3997 env.put("WORKSPACE", ws.getRemote()); // servlet container may have set CLASSPATH in its launch script, // so don't let that inherit to the new child process. // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html env.put("CLASSPATH", ""); JDK jdk = project.getJDK(); if (jdk != null) { Computer computer = Computer.currentComputer(); if (computer != null) { // just in case were not in a build jdk = jdk.forNode(computer.getNode(), log); } jdk.buildEnvVars(env); } project.getScm().buildEnvVars(this, env); if (buildEnvironments != null) for (Environment e : buildEnvironments) e.buildEnvVars(env); for (EnvironmentContributingAction a : Util.filter(getActions(), EnvironmentContributingAction.class)) a.buildEnvVars(this, env); EnvVars.resolve(env); return env; }
/** * Returns the configurable attribute conditions necessary to evaluate the given configured * target, or null if not all dependencies have yet been SkyFrame-evaluated. */ @Nullable private Set<ConfigMatchingProvider> getConfigurableAttributeConditions( TargetAndConfiguration ctg, Environment env) { if (!(ctg.getTarget() instanceof Rule)) { return ImmutableSet.of(); } Rule rule = (Rule) ctg.getTarget(); RawAttributeMapper mapper = RawAttributeMapper.of(rule); Set<SkyKey> depKeys = new LinkedHashSet<>(); for (Attribute attribute : rule.getAttributes()) { for (Label label : mapper.getConfigurabilityKeys(attribute.getName(), attribute.getType())) { if (!BuildType.Selector.isReservedLabel(label)) { depKeys.add(ConfiguredTargetValue.key(label, ctg.getConfiguration())); } } } Map<SkyKey, SkyValue> cts = env.getValues(depKeys); if (env.valuesMissing()) { return null; } ImmutableSet.Builder<ConfigMatchingProvider> conditions = ImmutableSet.builder(); for (SkyValue ctValue : cts.values()) { ConfiguredTarget ct = ((ConfiguredTargetValue) ctValue).getConfiguredTarget(); conditions.add(Preconditions.checkNotNull(ct.getProvider(ConfigMatchingProvider.class))); } return conditions.build(); }
void runLoop(Environment env) throws TemplateException, IOException { if (list instanceof TemplateCollectionModel) { TemplateCollectionModel baseListModel = (TemplateCollectionModel) list; TemplateModelIterator it = baseListModel.iterator(); hasNext = it.hasNext(); while (hasNext) { loopVar = it.next(); hasNext = it.hasNext(); if (nestedBlock != null) { env.visit(nestedBlock); } index++; } } else if (list instanceof TemplateSequenceModel) { TemplateSequenceModel tsm = (TemplateSequenceModel) list; int size = tsm.size(); for (index = 0; index < size; index++) { loopVar = tsm.get(index); hasNext = (size > index + 1); if (nestedBlock != null) { env.visit(nestedBlock); } } } else if (env.isClassicCompatible()) { loopVar = list; if (nestedBlock != null) { env.visit(nestedBlock); } } else { throw invalidTypeException(list, listExpression, env, "collection or sequence"); } }
public Map<String, String> getEnvVarsPreviousSteps(AbstractBuild build, EnvInjectLogger logger) throws IOException, InterruptedException, EnvInjectException { Map<String, String> result = new HashMap<String, String>(); List<Environment> environmentList = build.getEnvironments(); if (environmentList != null) { for (Environment e : environmentList) { if (e != null) { e.buildEnvVars(result); } } } EnvInjectPluginAction envInjectAction = build.getAction(EnvInjectPluginAction.class); if (envInjectAction != null) { result.putAll(getCurrentInjectedEnvVars(envInjectAction)); // Add build variables with axis for a MatrixRun if (build instanceof MatrixRun) { result.putAll(build.getBuildVariables()); } } else { result.putAll(getJenkinsSystemVariables(false)); result.putAll(getBuildVariables(build, logger)); } return result; }
private Decision executePDP(boolean logobligation, String format) { // Setup PDP - reuse PDPOnePolicyDataStore.properties PolicyDecisionPoint pdp = null; try { Properties props = new Properties(); URL url = ClassLoader.getSystemResource("PDPOnePolicyDataStore.properties"); props.load(url.openStream()); // Just to ensure cache is reloaded props.setProperty( "PDP_ETAG", logobligation ? "10101" + format.hashCode() : "10102" + format.hashCode()); if (logobligation) props.setProperty("PDP_LOG_OBLIGATION", "true"); else props.setProperty("PDP_LOG_OBLIGATION", "false"); props.setProperty("PDP_LOG_OBLIGATION_FORMAT", format); pdp = PolicyEnforcementPoint.getPDP(props); } catch (Exception ex) { System.out.println("Properties File not found:" + ex); ex.printStackTrace(); return null; } // Get Decision Target resource = new Target("web", "http://www.ebay.com/xxx"); List<Environment> env = new ArrayList<Environment>(); Environment env1 = new Environment("session", "env1"); env1.setAttribute("authn.level", new Integer(0)); env1.setAttribute("role", "manager"); env.add(env1); Decision decision = pdp.getPolicyDecision(resource, env); return decision; }
/** Command: unmonitor Unmonitor an expression */ private void commandUnmonitor(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { env.error("Argument required"); } else { env.getMonitorListModel().remove(t.nextToken("")); } }
private ResolvedTargets<Void> getTargetsInPackage( String originalPattern, PathFragment packageNameFragment, FilteringPolicy policy) throws TargetParsingException, InterruptedException { TargetPatternResolverUtil.validatePatternPackage(originalPattern, packageNameFragment, this); try { PackageIdentifier packageId = PackageIdentifier.createInDefaultRepo(packageNameFragment); Package pkg = packageProvider.getPackage(env.getListener(), packageId); ResolvedTargets<Target> packageTargets = TargetPatternResolverUtil.resolvePackageTargets(pkg, policy); ImmutableList.Builder<SkyKey> builder = ImmutableList.builder(); for (Target target : packageTargets.getTargets()) { builder.add(TransitiveTraversalValue.key(target.getLabel())); } ImmutableList<SkyKey> skyKeys = builder.build(); env.getValuesOrThrow(skyKeys, NoSuchPackageException.class, NoSuchTargetException.class); if (env.valuesMissing()) { throw new MissingDepException(); } return ResolvedTargets.empty(); } catch (NoSuchThingException e) { String message = TargetPatternResolverUtil.getParsingErrorMessage( "package contains errors", originalPattern); throw new TargetParsingException(message, e); } }
private void commandKill(StringTokenizer t) throws NoSessionException { // ### Should change the way in which thread ids and threadgroup names // ### are distinguished. if (!t.hasMoreTokens()) { env.error("Usage: kill <threadgroup name> or <thread id>"); return; } while (t.hasMoreTokens()) { String idToken = t.nextToken(); ThreadReference thread = findThread(idToken); if (thread != null) { runtime.stopThread(thread); env.notice("Thread " + thread.name() + " killed."); return; } else { /* Check for threadgroup name, NOT skipping "system". */ // ### Should skip "system"? Classic 'jdb' does this. // ### Should deal with possible non-uniqueness of threadgroup names. ThreadGroupIterator itg = allThreadGroups(); while (itg.hasNext()) { ThreadGroupReference tg = itg.nextThreadGroup(); if (tg.name().equals(idToken)) { ThreadIterator it = new ThreadIterator(tg); while (it.hasNext()) { runtime.stopThread(it.nextThread()); } env.notice("Threadgroup " + tg.name() + "killed."); return; } } env.failure("\"" + idToken + "\" is not a valid threadgroup or id."); } } }
private Class<?> loadImportedClass(String simpleName) throws ClassNotFoundException { Class<?> clazz = null; try { // check to see if we generated it clazz = super.loadClass(env.getGeneratedCodePackage() + "." + simpleName); } catch (ClassNotFoundException e) { } Set<String> names = env.getImports().stream().map(i -> i.resolveClass(simpleName)).collect(Collectors.toSet()); for (String name : names) { Class<?> next; try { next = super.loadClass(name); } catch (ClassNotFoundException e) { continue; } if (clazz != null) { throw new ClassNotFoundException("Ambiguous import. " + Arrays.asList(next, clazz)); } else { clazz = next; } } if (clazz == null) { throw new ClassNotFoundException("Could not find " + simpleName + " in " + env.getImports()); } return clazz; }
private ThreadReference findThread(String idToken) throws NoSessionException { String id; ThreadReference thread = null; if (idToken.startsWith("t@")) { id = idToken.substring(2); } else { id = idToken; } try { ThreadReference[] threads = threads(); long threadID = Long.parseLong(id, 16); for (ThreadReference thread2 : threads) { if (thread2.uniqueID() == threadID) { thread = thread2; break; } } if (thread == null) { // env.failure("No thread for id \"" + idToken + "\""); env.failure("\"" + idToken + "\" is not a valid thread id."); } } catch (NumberFormatException e) { env.error("Thread id \"" + idToken + "\" is ill-formed."); thread = null; } return thread; }
private void runTest() { Map<String, Object> config = new HashMap<String, Object>(); config.put(Locations.LOCATION_COUNT, 24); Environment locations = new CircleLocations(); locations.configure(config); GeneticAlgorithm ga = new GeneticAlgorithm( 100, 2649, new TravellingSalesmanPopulationFactory(), new TravellingSalesmanPopulationRenderer(locations), locations); List<EvolutionReport> reports = new LinkedList<EvolutionReport>(); for (int i = 0; i < 30; i++) { ga.reset(); ga.evolve(); reports.add(ga.getReport()); } // Calculate simple stats long totalBestHitGen = 0; long totalBestCost = 0; for (EvolutionReport report : reports) { totalBestHitGen += report.getHitCurrentValueOnGeneration(); totalBestCost += report.getCost(); } System.out.println("Average Best Hit Gen:" + (totalBestHitGen / reports.size())); System.out.println("Average Best Cost:" + (totalBestCost / reports.size())); }
@FXML private void lvListenerGetEmployeeInfo(MouseEvent event) { try { tabPayCheck.setDisable(true); clearTextFields(); String[] a = lvEmployees.getSelectionModel().getSelectedItem().split("-"); tfInfoId.setText(a[1].trim()); final int ID = Integer.parseInt(tfInfoId.getText()); tfInfoName.setText(Environment.getEmployeeStrInfo(ID, "name")); tfInfoPos.setText(Environment.getEmployeeStrInfo(ID, "position")); tfInfoStreet.setText(Environment.getEmployeeStrInfo(ID, "street")); tfInfoCSZ.setText(Environment.getCityStateZip(ID)); tfInfoPayRate.setText( String.format("%.2f", Double.parseDouble(Environment.getEmployeeStrInfo(ID, "payRate")))); } catch (Exception e) { Alert alert; alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Error Message"); alert.setHeaderText("Whoops you did not select an Employee."); alert.setContentText("Try again."); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK) { // ... user chose OK } else { // ... user chose CANCEL or closed the dialog } } }
@Test public void testGetAppliesTo() { List<String> appliesTo = new ArrayList<String>(); appliesTo.add("test"); env.setAppliesTo(appliesTo); assertNotNull(env.getAppliesTo()); }