text
stringlengths
14
410k
label
int32
0
9
public User getUser(Integer i) { User result = new User(); Iterable<Entry> userQuery = this.query("{id:" + i + "}"); if (userQuery.iterator().hasNext()) { for (Entry user : userQuery) { result = (User) user; } } return result; }
2
public void update(Graphics g) { Graphics gImg = null; Dimension dmImg = null; Dimension dm = getSize(); int wndWidth = dm.width; int wndHeight = dm.height; if((dmImg == null) || (dmImg.width != wndWidth) || (dmImg.height != wndHeight)) { dmImg = new Dimension(wndWidth, wndHeight); mImg = createImage(wndWidth, wndHeight); gImg = mImg.getGraphics(); } Color fg = getForeground(); Color bg = getBackground(); gImg.setColor(bg); gImg.fillRect(0, 0, dmImg.width, dmImg.height); gImg.setColor(fg); gImg.setFont( new Font("Helvetica", Font.BOLD, 50)); gImg.drawString(szScrolledText, nPosition, nTitleHeight + 10); nPosition--; if(nPosition < -nStrLength) nPosition = getSize().width; paint(g); }
4
public void moveCameraToScene(Scene scene, boolean immediately) { Scene previous = scene.getPrevious(); if (previous != null) { String s = previous.getDepartInformation(); if (s != null) { runScriptImmediatelyWithoutThread("set echo bottom center;color echo yellow;echo \"" + s + "\""); } else { clearEcho(); } s = previous.getDepartScript(); if (s != null) runScriptImmediatelyWithoutThread(s); } Vector3f a = scene.getRotationAxis(); if (getNavigationMode()) { Point3f c = scene.getCameraPosition(); moveCameraTo(immediately ? 0 : scene.getTransitionTime(), a.x, a.y, a.z, scene.getRotationAngle(), c.x, c.y, c.z); } else { moveTo(immediately ? 0 : scene.getTransitionTime(), a.x, a.y, a.z, scene.getRotationAngle(), (int) scene .getZoomPercent(), scene.getXTrans(), scene.getYTrans()); } String s = scene.getArriveInformation(); if (s != null) { runScriptImmediatelyWithoutThread("set echo bottom center;color echo yellow;echo \"" + s + "\""); } else { clearEcho(); } s = scene.getArriveScript(); if (s != null) runScriptImmediatelyWithoutThread(s); }
8
@SuppressWarnings("unchecked") public int addTag(String filename, String tagType, String tagValue) { Tag t = new Tag(tagType, tagValue); Iterator it = GuiView.control.getCurrentUser().getAlbumList().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Album> pairs = (Map.Entry<String, Album>) it.next(); if (pairs.getValue().getPhotoList().containsKey(filename)) { if (!pairs.getValue().getPhotoList().get(filename).getTagList().containsKey(tagValue)) { pairs.getValue().getPhotoList().get(filename).addTag(t); //return 1;//"Added tag: " + filename + " " + tagType + ":" + tagValue; } else if (pairs.getValue().getPhotoList().get(filename).getTagList().containsKey(tagValue) && pairs.getValue().getPhotoList().get(filename).getTagList().containsValue(tagType)) { return -1; } else continue; //else //return -1; //"Tag already exists for " + filename + " " + tagType + ":" + tagValue; } } return 1; //""; }
5
public static void readStandardInput() { if (readingStandardInput) return; try { in.close(); } catch (Exception e) { } emptyBuffer(); // Added November 2007 in = standardInput; inputFileName = null; readingStandardInput = true; inputErrorCount = 0; }
2
public LoginWindow(ClientGUI clientInterface) { mInterface = clientInterface; setTitle("Login"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 190, 304); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); txtUser = new JTextField(); txtUser.setBounds(12, 55, 158, 19); contentPane.add(txtUser); txtUser.setColumns(10); txtPass = new JPasswordField(); txtPass.setBounds(12, 106, 158, 19); contentPane.add(txtPass); txtPass.setColumns(10); JButton btnCheckIn = new JButton("Login"); btnCheckIn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mInterface.setUser(txtUser.getText()); mInterface.setPass(txtPass.getText()); if(mInterface.login()) { close(); } else { JOptionPane.showOptionDialog(null, "Der Login war nicht erfolgreich. Mögliche Gründe:\n\n" + "- falscher Username\n" + "- falsches Passwort\n" + "- Sie sind auf einem anderen PC angemeldet\n" + "- der Server ist nicht erreichbar", "Fehler beim Login", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null); } } }); btnCheckIn.setBounds(36, 149, 117, 25); contentPane.add(btnCheckIn); JLabel lblUsername = new JLabel("Username:"); lblUsername.setBounds(12, 36, 158, 19); contentPane.add(lblUsername); JLabel lblPassword = new JLabel("Password:"); lblPassword.setBounds(12, 89, 158, 15); contentPane.add(lblPassword); JButton btnRegister = new JButton("Create User"); btnRegister.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { mInterface.setUser(txtUser.getText()); mInterface.setPass(txtPass.getText()); if(mInterface.register()) { mInterface.login(); close(); } else { JOptionPane.showOptionDialog(null, "Die Registrierung war nicht erfolgreich. Mögliche Gründe:\n\n" + "- Username existiert bereits\n" + "- der Server ist nicht erreichbar", "Fehler beim Login", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null); } } }); btnRegister.setBounds(12, 240, 158, 25); contentPane.add(btnRegister); }
2
public boolean batchFinished() throws Exception { if (getInputFormat() == null) throw new IllegalStateException("No input instance format defined"); Instances toFilter = getInputFormat(); if (!isFirstBatchDone()) { // filter out attributes if necessary Instances toFilterIgnoringAttributes = removeIgnored(toFilter); // serialized model or build clusterer from scratch? File file = getSerializedClustererFile(); if (!file.isDirectory()) { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); m_ActualClusterer = (Clusterer) ois.readObject(); Instances header = null; // let's see whether there's an Instances header stored as well try { header = (Instances) ois.readObject(); } catch (Exception e) { // ignored } ois.close(); // same dataset format? if ((header != null) && (!header.equalHeaders(toFilterIgnoringAttributes))) throw new WekaException( "Training header of clusterer and filter dataset don't match:\n" + header.equalHeadersMsg(toFilterIgnoringAttributes)); } else { m_ActualClusterer = AbstractClusterer.makeCopy(m_Clusterer); m_ActualClusterer.buildClusterer(toFilterIgnoringAttributes); } // create output dataset with new attribute Instances filtered = new Instances(toFilter, 0); FastVector nominal_values = new FastVector(m_ActualClusterer.numberOfClusters()); for (int i = 0; i < m_ActualClusterer.numberOfClusters(); i++) { nominal_values.addElement("cluster" + (i+1)); } filtered.insertAttributeAt(new Attribute("cluster", nominal_values), filtered.numAttributes()); setOutputFormat(filtered); } // build new dataset for (int i=0; i<toFilter.numInstances(); i++) { convertInstance(toFilter.instance(i)); } flushInput(); m_NewBatch = true; m_FirstBatchDone = true; return (numPendingOutput() != 0); }
8
public double getTempRange(String type){ double t=0; if (type.equals(MASHOUT)) t = MASHOUTTMPF; else if (type.equals(SPARGE)) t = SPARGETMPF; if (tempUnits.equals("C")) t = BrewCalcs.fToC(t); return t; }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ClassAce)) return false; ClassAce other = (ClassAce) obj; if (canonicalTypeName == null) { if (other.canonicalTypeName != null) return false; } else if (!canonicalTypeName.equals(other.canonicalTypeName)) return false; if (user_id == null) { if (other.user_id != null) return false; } else if (!user_id.equals(other.user_id)) return false; return true; }
9
public List<Character> getCharacterList(String path) { List<?> list = getList(path); if (list == null) { return new ArrayList<Character>(0); } List<Character> result = new ArrayList<Character>(); for (Object object : list) { if (object instanceof Character) { result.add((Character) object); } else if (object instanceof String) { String str = (String) object; if (str.length() == 1) { result.add(str.charAt(0)); } } else if (object instanceof Number) { result.add((char) ((Number) object).intValue()); } } return result; }
7
private static StructureComponent getNextComponentVillagePath(ComponentVillageStartPiece par0ComponentVillageStartPiece, List par1List, Random par2Random, int par3, int par4, int par5, int par6, int par7) { if (par7 > 3 + par0ComponentVillageStartPiece.terrainType) { return null; } else if (Math.abs(par3 - par0ComponentVillageStartPiece.getBoundingBox().minX) <= 112 && Math.abs(par5 - par0ComponentVillageStartPiece.getBoundingBox().minZ) <= 112) { StructureBoundingBox var8 = ComponentVillagePathGen.func_35087_a(par0ComponentVillageStartPiece, par1List, par2Random, par3, par4, par5, par6); if (var8 != null && var8.minY > 10) { ComponentVillagePathGen var9 = new ComponentVillagePathGen(par7, par2Random, var8, par6); int var10 = (var9.boundingBox.minX + var9.boundingBox.maxX) / 2; int var11 = (var9.boundingBox.minZ + var9.boundingBox.maxZ) / 2; int var12 = var9.boundingBox.maxX - var9.boundingBox.minX; int var13 = var9.boundingBox.maxZ - var9.boundingBox.minZ; int var14 = var12 > var13 ? var12 : var13; if (par0ComponentVillageStartPiece.getWorldChunkManager().areBiomesViable(var10, var11, var14 / 2 + 4, MapGenVillage.villageSpawnBiomes)) { par1List.add(var9); par0ComponentVillageStartPiece.field_35106_f.add(var9); return var9; } } return null; } else { return null; } }
7
@Override public void printReception() { if (!readTemplate()) return; // Заполняем то, что необходимо заменить fillMappings(); JOptionPane.showMessageDialog(null, "Заменяем данные ", "Инфо", JOptionPane.INFORMATION_MESSAGE); // Очищаем документ try { org.docx4j.model.datastorage.migration.VariablePrepare.prepare(wordMLPackage); } catch (Exception e) { e.printStackTrace(); } MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); List<Object> texts = ExportUtil.getAllElementFromObject(documentPart, Text.class); Set<String> keys = mappings.keySet(); // заменяем текстовые вставки for (String key : keys) { String value = mappings.get(key); for (Object obj: texts) { if(obj instanceof Text) { Text textElem = (Text) obj; String text = textElem.getValue(); if(text.contains(key)) { text = text.replace(key,value); textElem.setValue(text); } } } } saveRequest(); }
6
@Override public void run() { try { while(run) { testCase.update(); if(testCase.getAvgFitness() == Double.POSITIVE_INFINITY) { correctSolutions++; totalGenerations += testCase.getGeneration(); testCase.reinitialize(); } if(testCase.getGeneration() == settings.getInt("nonConvergingGenCount")) { nonConverging++; totalGenerations += testCase.getGeneration(); if(settings.getBool("verbose")) { System.out.println(number + ": Did not converge, #" + nonConverging + " / " + (nonConverging + correctSolutions)); } testCase.reinitialize(); } if(settings.getBool("runToTarget") && correctSolutions + nonConverging == settings.getInt("solutionTarget")) { run = false; } } } catch(Exception e) { System.out.println("Tests terminated: '" + e.getMessage() + "'"); run = false; } }
7
public static void disposeFonts() { // clear fonts for (Font font : m_fontMap.values()) { font.dispose(); } m_fontMap.clear(); // clear bold fonts for (Font font : m_fontToBoldFontMap.values()) { font.dispose(); } m_fontToBoldFontMap.clear(); }
2
public static void main(String[] args) { int counter = 0; int start = 22; long sum = 0L; while (counter < 11) { int currentLeft = start; int currentRight = start; while (isPrime(currentLeft) && currentLeft > 0) { currentLeft = leftShift(currentLeft); } while (isPrime(currentRight) && currentRight > 0) { currentRight = rightShift(currentRight); } if (currentLeft == 0 && currentRight == 0) { sum += start; ++counter; } ++start; } System.out.println(sum); }
7
public void onTick(Instrument instrument, ITick tick) throws JFException { // 各通貨ペアのティック情報を受信した際に呼ばれます。 // LOGGER.info("onTick"); }
0
public static int jump(int[] A) { if (null == A || 0 == A.length) return -1; int len = A.length; int[] step = new int[len]; step[len - 1] = 0; for (int i = len - 2; i >= 0; i--) { int min = len + 1; for (int j = i + 1; j <= i + A[i] && j < len; j++) { if (min > 1 + step[j]) { min = 1 + step[j]; } } step[i] = min; } return step[0]; }
6
public BellmanFordAlgorithm(IWeightedGraph<N, Number> graph, N source) { for(N node : graph) { nodes.put(node, new Node<N>(node, Double.MAX_VALUE)); } nodes.get(source).distance = 0; List<WeightedEdge<N, Number>> edges = graph.getEdges(); for(int i = 1; i < graph.size(); i++) { for(WeightedEdge<N, Number> edge : edges) { if(nodes.get(edge.from).distance + edge.weight.doubleValue() < nodes.get(edge.to).distance) { nodes.get(edge.to).distance = nodes.get(edge.from).distance + edge.weight.doubleValue(); nodes.get(edge.to).previousNode = nodes.get(edge.from); } } } for(WeightedEdge<N, Number> edge : edges) { if(nodes.get(edge.from).distance + edge.weight.doubleValue() < nodes.get(edge.to).distance) { System.err.println("Graph contains a negative-weight cycle"); return; } } for(N node : graph) { ArrayList<Node<N>> tempPath = new ArrayList<Node<N>>(); Node<N> current = nodes.get(node); while(current != null) { tempPath.add(current); current = current.previousNode; } Collections.reverse(tempPath); paths.put(node, tempPath); } }
8
public String encode(String plain) { //int period=key.length(); String plain_u=plain.toUpperCase(); int left=plain_u.length()%(key.length()*2); int add_x=0; if(left!=0) { add_x=key.length()*2-left; } for(int i=0;i<add_x;i++) { plain_u+='X'; } char[][] block=Incomp_column.build_block(plain_u, -1,key.length(), 0); char[][] result_block=new char[block.length][block[0].length]; for(int i=0;i<block[0].length;i++) { //encipher by column for(int j=0;j<block.length;j+=2) { Pair<Character> p=get_ct(block[j][i],block[j+1][i],key.charAt(i)); result_block[j][i]=p.get_first(); result_block[j+1][i]=p.get_second(); } } //Random r=new Random(); //int key_len=1+r.nextInt(7); String r=read_block(result_block, true); return r; }
4
public static StatusWapper constructWapperStatus(Response res) throws WeiboException { JSONObject jsonStatus = res.asJSONObject(); //asJSONArray(); JSONArray statuses = null; try { if(!jsonStatus.isNull("statuses")){ statuses = jsonStatus.getJSONArray("statuses"); } if(!jsonStatus.isNull("reposts")){ statuses = jsonStatus.getJSONArray("reposts"); } int size = statuses.length(); List<Status> status = new ArrayList<Status>(size); for (int i = 0; i < size; i++) { status.add(new Status(statuses.getJSONObject(i))); } long previousCursor = jsonStatus.getLong("previous_curosr"); long nextCursor = jsonStatus.getLong("next_cursor"); long totalNumber = jsonStatus.getLong("total_number"); String hasvisible = jsonStatus.getString("hasvisible"); return new StatusWapper(status, previousCursor, nextCursor,totalNumber,hasvisible); } catch (JSONException jsone) { throw new WeiboException(jsone); } }
4
private static void loop() { String menu[] = {"Quitter", "Statistiques", "Personnalisée", "Supérieur", "Prédéfini"}; int choix; int quit; Jeu jeu = new Jeu(); quit = -1; do { choix = JOptionPane.showOptionDialog( null, "Quelle action voulez-vous faire?", "Banque", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, menu, menu[0]); switch(choix) { case 0: quit = jeu.getGame(); break; case 1: jeu.stats(); break; case 2: jeu.perso(); break; case 3: jeu.superieur(); break; case 4: jeu.predefini(); break; } } while(quit == -1); JOptionPane.showMessageDialog(null, "Vous avez faites "+quit+" "+(quit>1?"parties":"partie")+"."); }
7
public boolean newCompraAction(String id_compras, String costo, String descripcion, String nombre, String cantidad, String fecha) throws SQLException, EmptyFieldException { boolean res; conn = ConexionBD.getInstance(); if(id_compras.isEmpty() || costo.isEmpty() || descripcion.isEmpty() || nombre.isEmpty()|| cantidad.isEmpty() || fecha.isEmpty()) { throw new EmptyFieldException(); } res = conn.insertRecordToTable( "INSERT INTO compras " + "VALUES(" + id_compras + "', '" + costo + "', " + descripcion + "', '" + nombre + "', '" + cantidad + "', '" +fecha + "', '" + "')"); return res; }
6
public int lengthOfLongestSubstring(String s) { int length = s.length(); int max = 0; int index = -1;// 为了保证length =1 时正确。 Map<Character,Integer> map = new HashMap<Character,Integer>(); for (int i =0; i < length;i++){ char key = s.charAt(i); if(map.containsKey(key) && index < map.get(key)) index = map.get(key); max = Math.max(max,i - index); map.put(key,i); } return max; }
3
@Override public void transform(double[] src, double[] dst) { // TODO Auto-generated method stub for (int i = 0; i < 3; i++) temp2[i] = src[i]; temp2[3] = 1; for (int i = 0; i < 3; i++) { dst[i] = 0; for (int j = 0; j < 4; j++) { dst[i] += matrix[i][j] * temp2[j]; } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { copy[i][j] = matrix[i][j]; } } Invert.invert(copy, inverseMatrix); transpose(inverseMatrix, inverseMatrixTranspose); for (int i = 0; i < 3; i++) temp2[i] = src[i+3]; temp2[3]=0; for (int i = 0; i < 3; i++) { dst[i+3] = 0; for (int j = 0; j < 4; j++) { dst[i+3] += inverseMatrixTranspose[i][j] * temp2[j]; } } }
8
public Organism createOrganism(List<Gene> genes) { List<Gene> copyGenes = new ArrayList<>(); for (Iterator<Gene> it = genes.iterator(); it.hasNext();) { copyGenes.add(new Gene(it.next())); } Genome newGenome = new Genome(nextEnabeledGenomeID(), copyGenes); //refresh NET made in Organism constructor return (new Organism(newGenome)); }
1
public UserStoreImpl(String userListFilename, String level3ElectorateFilename, String level5ElectorateFilename ){ storeFile = new File(userListFilename); if (storeFile.exists()){ try{ users = new HashMap<String, User>(); Scanner scanner = new Scanner(storeFile); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] details = line.split("\t"); if (details.length == 5){ String surname = details[0].trim(); String forename = details[1].trim(); String GUID = details[2].trim(); String password = details[3].trim(); boolean isManager = (details[4].trim().equals("true") ? true : false); users.put(GUID, new User(surname, forename, GUID, password, isManager)); } else System.out.println("Wrong details length"); } } catch (FileNotFoundException e) { e.printStackTrace(); } } else this.users = new HashMap<String,User>(); electorateMap = new HashMap<String, Set<User>>(); Set<User> level3Users = addElectorate(level3ElectorateFilename); electorateMap.put("level3", level3Users); Set<User> level5Users = addElectorate(level5ElectorateFilename); electorateMap.put("level5", level5Users); }
5
public void sendChannelMSGExclude(Client excludeme, String message){ if(excludeme != null){ for(Client c: usershere){ if(!(excludeme.equals(c))){ c.sendMessage(message); } } } else { for(Client c: usershere){ c.sendMessage(message); } } }
4
protected boolean initBehavior() { java.lang.Class cl; if (behavior == null) return true; if (!super.initBehavior()) return false; if (!super.initBehavior()) return false; if ((cl = getMyBehavior()) == null) return true; if (!cl.isAssignableFrom(behavior.getClass())) return true; if (!behavior.setAttribute("Recover","always")) return false; return true; }
6
@Override public int doStartTag() throws JspException { handleEventualEvictCache(); RestletResourceFactory factory = new RestletResourceFactory(); Logger logger = Context.getCurrentLogger(); String fullSearchUri = buildSearchUriToUse(); logger.log(Level.FINEST, "fullSearchUri: " + fullSearchUri); List<PackageMeta> packageMetaList = null; // retrieving eventual data from cache if (caching) { packageMetaList = retrieveFromCache(fullSearchUri); } if (packageMetaList == null) { SearchResultMetaRestletResource restletResource = factory .createSearchResultMetaResource(fullSearchUri); logger.log(Level.FINEST, "restletResource: " + restletResource.toString()); SearchResultMeta listOfFoundPackagesResult = restletResource.get(); logger.log(Level.FINEST, "listOfFoundPackagesResult: " + listOfFoundPackagesResult); packageMetaList = new ArrayList<PackageMeta>(); for (String packageName : listOfFoundPackagesResult.getResults()) { packageMetaList.add(retrievePackageMeta(packageName, factory)); } logger.log(Level.FINEST, "packageMetaList: " + packageMetaList); if (caching) { storeInCache(fullSearchUri, packageMetaList); } } else { logger.log(Level.FINEST, "packageMetaList retrieved from cache : " + packageMetaList); } pageContext.setAttribute(getVar(), packageMetaList); pageContext.setAttribute("searchUri", fullSearchUri); return SKIP_BODY; }
4
public void possibleMoves() { int[] top = { 0, 0, 0 }; for (Pin p : pins) { if (!p.isEmpty()) top[p.id] = p.getTopDisc().getSize(); } System.out.println((top[0] < top[1] ? "[L -> C]" : "[ ]") + " " + (top[0] < top[2] ? "[L -> R]" : "[ ]") + " " + (top[1] < top[0] ? "[C -> L]" : "[ ]") + " " + (top[1] < top[1] ? "[C -> R]" : "[ ]") + " " + (top[2] < top[0] ? "[R -> L]" : "[ ]") + " " + (top[2] < top[1] ? "[R -> C]" : "[ ]") ); }
8
public String getColumnName(int column) { return COLUMN_NAMES[column]; }
0
@Override public boolean action() throws JSONException { if (getResult().getJSONObject("char").getString("viergewinnt").equals( "4")) { Output.printTabLn("Vier gewinnt steht auf 4: " + getResult().getJSONObject("char").getString("var1"), Output.INFO); } else { Output.printTabLn("Vier gewinnt", Output.INFO); } Control.sleep(10); return true; }
1
public Population select(Population population){ Config config = Config.getInstance(); if (selectionType == null){ return population; } switch(selectionType){ case ROULETTE: return rouletteWheel(population, config.populationSize); case SUS: return stochasticUniversalSampling(population, config.populationSize); case TOURNAMENT: return tournamentSelection(population, config.populationSize, config.tournamentSize); case ELITISM: return elitism(population, config.populationSize); default: return population; } }
5
private int getNumberOfNewLinesTillSelectionIndex(String allLogText, int selectionIndex) { int numberOfNewlines = 0; int pos = 0; while((pos = allLogText.indexOf("\n", pos))!=-1 && pos <= selectionIndex) { numberOfNewlines++; pos++; } return numberOfNewlines; }
2
public double observe() { RandomVariable unif = null; try { unif = new ContinuousUniform(0, 1); } catch (ParameterException e) { e.printStackTrace(); } double u = unif.observe(); int observed = 0; double cumulativeMass = 0; while (cumulativeMass < u) { cumulativeMass += mass(observed); observed++; } return observed - 1; }
2
private static TspPopulation[] generate(){ Graph g = new Graph(INDIVIDUAL_SIZE); TspPopulation[] h = new TspPopulation[GLOBAL_STEPS]; for (int i = 0; i < GLOBAL_STEPS; ++i){ h[i] = new TspPopulation(POPULATION_SIZE, INDIVIDUAL_SIZE, g.getGraph()); } resultsRandom = new long[GLOBAL_STEPS]; Arrays.fill(resultsRandom, Long.MAX_VALUE); for (int i = 0; i < GLOBAL_STEPS; ++i){ if (i % 100 == 0){ System.out.println("random " + i); } TspPopulation populationRandom = new TspPopulation(h[i]); InverseOperator randomIO = new InverseOperator(populationRandom, RNG); SwapOperator randomSWO = new SwapOperator(populationRandom, RNG); ScrambleOperator randomSCO = new ScrambleOperator(populationRandom, RNG); MPX1 randomMPX1 = new MPX1(populationRandom, RNG); MPX2 randomMPX2 = new MPX2(populationRandom, RNG); for (int step = 0; step < MAX_STEPS; ++step){ double r; synchronized (RNG){ r = RNG.nextDouble(); } if (r < 0.33) { randomIO.mutate(); } else if (r < 0.66) { randomSWO.mutate(); } else if (r < 1.1) { randomSCO.mutate(); }// else if (r < 0.8) { // randomMPX1.mutate(); // } else { // randomMPX2.mutate(); // } } resultsRandom[i] = populationRandom.getFittest(); } Arrays.sort(resultsRandom); return h; }
7
public String getName(){ return Name; }
0
public synchronized void setSharedCounter(int sharedCounter) { this.sharedCounter = sharedCounter; }
0
public static void loadLevel(final int level, final World world) { BufferedReader breader = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("/level_" + level + ".lvl"))); Tile[][] tiles = new Tile[World.TILE_Y][World.TILE_X]; try { world.setDescription(breader.readLine()); for (int i = 0; i < World.TILE_Y; i++) { String line = breader.readLine(); process(i, line, tiles, world); } } catch (IOException e1) { e1.printStackTrace(); } world.setTiles(tiles); try { breader.close(); } catch (IOException e) { e.printStackTrace(); } }
3
public boolean exist(int searchId) { ListElement current = this.getHead(); while (current != null) { if (current.getId() == searchId) { return true; } current = current.getNext(); } return false; }
2
public Shader (String s) { shader= ARBShaderObjects.glCreateProgramObjectARB(); if(shader!=0){ vertShader=createShader(loadCode("Shaders/"+s+".vert"), ARBVertexShader.GL_VERTEX_SHADER_ARB); if (hardDebug) System.out.println("[Shader] Vertex shader code loaded: "+s); fragShader=createShader(loadCode("Shaders/"+s+".frag"), ARBFragmentShader.GL_FRAGMENT_SHADER_ARB); if (hardDebug) System.out.println("[Shader] Fragment shader code loaded: "+s); }else { System.err.println("[Shader] Failed to create shaders"); } if(vertShader!=0 && fragShader!=0){ ARBShaderObjects.glAttachObjectARB(shader, vertShader); if (hardDebug) System.out.println("[Shader] Vertex shader code attached: "+s); ARBShaderObjects.glAttachObjectARB(shader, fragShader); if (hardDebug) System.out.println("[Shader] Fragment shader code attached: "+s); ARBShaderObjects.glLinkProgramARB(shader); ARBShaderObjects.glValidateProgramARB(shader); if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_VALIDATE_STATUS_ARB) == GL11.GL_FALSE) { System.err.println("[Shader] Failed to validate "+s); } else if (hardDebug) System.out.println("[Shader] Shader ready to work: "+s); }else { System.err.println("[Shader] Failed to compile shader"); } }
9
void checkFrameValue(final Object value) { if (value == Opcodes.TOP || value == Opcodes.INTEGER || value == Opcodes.FLOAT || value == Opcodes.LONG || value == Opcodes.DOUBLE || value == Opcodes.NULL || value == Opcodes.UNINITIALIZED_THIS) { return; } if (value instanceof String) { checkInternalName((String) value, "Invalid stack frame value"); return; } if (!(value instanceof Label)) { throw new IllegalArgumentException("Invalid stack frame value: " + value); } else { usedLabels.add((Label) value); } }
9
@Override public void mouseDragged(MouseEvent e) { Point pt = e.getPoint(); JComponent parent = (JComponent) e.getComponent(); if (startPt != null && Math.sqrt(Math.pow(pt.x - startPt.x, 2) + Math.pow(pt.y - startPt.y, 2)) > gestureMotionThreshold) { startDragging(parent, pt); startPt = null; return; } if (!window.isVisible() || draggingComonent == null) { return; } Dimension d = draggingComonent.getPreferredSize(); Point p = new Point(pt.x - d.width / 2, pt.y - d.height / 2); SwingUtilities.convertPointToScreen(p, parent); window.setLocation(p); for (int i = 0; i < parent.getComponentCount(); i++) { Component c = parent.getComponent(i); Rectangle r = c.getBounds(); int ht2 = r.height / 2; Rectangle r1 = new Rectangle(r.x, r.y, r.width, ht2); Rectangle r2 = new Rectangle(r.x, r.y + ht2, r.width, ht2); if (r1.contains(pt)) { swapComponentLocation(parent, gap, gap, i - 1 > 0 ? i : 0); return; } else if (r2.contains(pt)) { swapComponentLocation(parent, gap, gap, i); return; } } parent.remove(gap); parent.revalidate(); }
8
private Component cycle(Component currentComponent, int delta) { int index = -1; loop : for (int i = 0; i < m_Components.length; i++) { Component component = m_Components[i]; for (Component c = currentComponent; c != null; c = c.getParent()) { if (component == c) { index = i; break loop; } } } // try to find enabled component in "delta" direction int initialIndex = index; while (true) { int newIndex = indexCycle(index, delta); if (newIndex == initialIndex) { break; } index = newIndex; // Component component = m_Components[newIndex]; if (component.isEnabled() && component.isVisible() && component.isFocusable()) { return component; } } // not found return currentComponent; }
8
public void setVision(Coords coords, int size) { int xLoc = coords.getX(); int yLoc = coords.getY(); int y = 0 - size; int x = 0; for (int i = 0; i<=size*2; i++) { x = (int)Math.sqrt((size*size) - y*y); int dist = Math.abs(-x)+ x; Coords setCoords = new Coords((x*20) + xLoc,((y*20) + yLoc)); if (upperLayers.containsKey(setCoords)) { upperLayers.remove(setCoords); } addBlack(setCoords); for (int r = 1; r <= dist; r++) { setCoords = new Coords(((x-r)*20)+xLoc,((y*20) + yLoc)); if (upperLayers.containsKey(setCoords)) { upperLayers.remove(setCoords); } setCoords = new Coords(((-x+r)*20)+xLoc,((y*20) + yLoc)); if (upperLayers.containsKey(setCoords)) { upperLayers.remove(setCoords); } } setCoords = new Coords((-x*20) + xLoc,((y*20) + yLoc)); if (upperLayers.containsKey(setCoords)) { upperLayers.remove(setCoords); } y++; } }
6
protected void teeTilaus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Otetaan sessiosta vastaan sinne tallennettu tilaus-olio. Tilaus tilaus = (Tilaus) request.getSession().getAttribute("tilaus"); int tilausID = 0; // Tallennetaan saatu tilaus tietokantaan try { TilausDAO tilDao = new TilausDAO(); tilausID = tilDao.TallennaTilaus(tilaus); } catch (DAOPoikkeus e) { // Virheen sattuessa heitetään poikkeus ruudulle. throw new ServletException(e); } catch (SQLException e) { e.printStackTrace(); } // tallennaTilaus-metodi palauttaa tilauksen ID:n. Tallennetaan se... request.getSession().setAttribute("tilausID", tilausID); // ...ja ohjataan käyttäjä tilausvahvistussivulle (doGet-metodi). response.sendRedirect("tilaa?tilaus=saved"); }
2
public Comparator getDirectoryComparator() { return directoryComparator; }
0
private boolean jj_2_50(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_50(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(49, xla); } }
1
public void warn(Event event) { String c = ""; switch(event.getTypeEvent()) { case WHITE_DETECTED : c = "White"; case COLOR_DETECTED : if(event.getName().equals(color) || c.equals(color)) { if(state == 3) { state = 4; } else ignore(); } else ignore(); break; case GOFORWARD_END : if(state == 3) { state = 5; } else ignore(); break; case ROTATE_END : if(state == 0) { state = 1; } else ignore(); break; default: ignore(); break; } }
9
public T pop(){ if(size == 0) throw new NoSuchElementException(); T value = arr[--size]; arr[size] = null; if(size > 0 && size == arr.length / 4) resize(arr.length / 2); return value; }
3
public static ArrayList<Position> findPieces(Board b, int piece) { ArrayList<Position> pieces = new ArrayList<Position>(); for (int rank = 0; rank < b.board.length; rank++) { for (int file = 0; file < b.board[rank].length; file++) { if (b.board[rank][file] == piece) { pieces.add(new Position(rank, file)); } } } return pieces; }
3
public static Object toReflectType(String typeSig, Object value) { switch (typeSig.charAt(0)) { case 'Z': return new Boolean(((Integer) value).intValue() != 0); case 'B': return new Byte(((Integer) value).byteValue()); case 'S': return new Short(((Integer) value).shortValue()); case 'C': return new Character((char) ((Integer) value).intValue()); default: return value; } }
4
@Override public String getFileName() { return getName() + "_x" + planeCenterX + "_y" + planeCenterY + "_w" + planeWidth + "_h" + planeHeight + "_it" + mits + (crossHairs ? "_ch" : "") + (drawBox ? "_box(" + boxCenterX + "," + boxCenterY + ")(" + boxWidth + "x" + boxHeight + ")" : "") + "_cs:" + colorScheme + (colorScheme.equals("Random") ? "_seed:" + seed : "") + (colorScheme.equals("Hue") ? "_hm" + hueMultiplier + "_bm" + brightnessMultiplier : ""); }
4
public double cdfUpEq(double p, int k, int n) { if (k < 0) return 1.0; if (k > n) return 0; double cdf = cdfUp(p, k, n) + pdf(p, k, n); cdf = Math.min(1.0, cdf); return cdf; }
2
public static int guessLoomDefinitionArity(int arity, Stella_Object definition, Cons constraints) { if ((arity == -1) && (definition != null)) { arity = Logic.computeLoomDescriptionArity(definition); } if (arity == -1) { { Stella_Object c = null; Cons iter000 = constraints; loop000 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) { c = iter000.value; arity = Logic.computeLoomDescriptionArity(c); if (arity > 0) { break loop000; } } } } if (arity == -1) { arity = 2; } return (arity); }
6
public boolean isEmpty() { boolean retVal = false; if (backPtr == -1) { retVal = true; } return retVal; }
1
public static void writeToFile(List<String> lines, File f) throws IOException { System.out.println("writeToFile function started."); String encoding = code(f); encoding = "UTF-16LE"; FileOutputStream fos = new FileOutputStream(f); OutputStreamWriter writer = new OutputStreamWriter(fos, encoding); // OutputStreamWriter writer = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(writer); // bw.w for (int i=0; i<lines.size();i++) { if(i == 0){ bw.write("\uFEFF"+lines.get(i)); if(i != lines.size() - 1){ bw.newLine(); } continue; } bw.write(lines.get(i)); if(i != lines.size() - 1){ bw.newLine(); } } bw.write("\r\n"); bw.flush(); writer.flush(); fos.flush(); bw.close(); writer.close(); fos.close(); System.out.println("writeToFile function finished."); }
4
public void write(final DataOutputStream out) throws IOException { out.writeShort(modifiers); out.writeShort(name); out.writeShort(type); out.writeShort(attrs.length); for (int i = 0; i < attrs.length; i++) { out.writeShort(attrs[i].nameIndex()); out.writeInt(attrs[i].length()); attrs[i].writeData(out); } }
1
public final void translate(double x, double y, double z) { if (DIRS[0] != x || DIRS[1] != y || DIRS[2] != z) { // Cache it! DIRS[0] = TRANSLATE.entry[0][3] = x; DIRS[1] = TRANSLATE.entry[1][3] = y; DIRS[2] = TRANSLATE.entry[2][3] = z; } premultiply(TRANSLATE); }
3
public synchronized void start() throws Exception { if (thread != null) { throw new Exception("ProcessRunner already started."); } thread = new Thread(new Runnable() { @Override /** run() * * The run function of the runnable object within the thread * Checks to see if any ProcessChildren have completed or terminated */ public void run() { running = true; while(running) { for (int i = 0; i < processes.size(); i++) { ProcessChild cur = processes.get(i); if (cur !=null) { if (cur.isTerminated()) { processes.remove(i); } else if (cur.isComplete()) { System.out.print("\n" + cur.getMPW().getName() + " has terminated\n==> "); processes.remove(i); } } } } } }); thread.start(); }
6
public boolean deleteEvidence(Evidence c) { Element evidenceE; boolean flag = false; for (Iterator i = root.elementIterator("evidence"); i.hasNext();) { evidenceE = (Element)i.next(); if (evidenceE.element("id").getText().equals(c.getId())) { evidenceE.element("isDelete").setText("true"); // Write to xml try { XmlUtils.write2Xml(fileName, document); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } flag = true; break; } } return flag; }
3
public EqualDivisionNormalDistributedOrdersGenerator( int numberOfForerunPeriods, int offSet) { if (numberOfForerunPeriods < 0 || offSet < 0) throw new IllegalArgumentException(); this.forerun = numberOfForerunPeriods; this.offSet = offSet; }
2
public ListModel<ICPBrasilCertificate> getChainListModel() { DefaultListModel<ICPBrasilCertificate> lmodel = new DefaultListModel<>(); for (ICPBrasilCertificate c : this.getCertificate().getChain()) { lmodel.addElement(c); } return lmodel; }
1
public String login() { User fetchUser = userHelper.getUser(username, password); if (fetchUser != null) { // success user = fetchUser; loggedIn = true; if (user.getType().equals("admin")) { admin = true; librarian = true; } if (user.getType().equals("librarian")) librarian = true; // ako je januar, pustaj sve if (Calendar.getInstance().get(Calendar.MONTH) == 0) return "index"; // monthly awards trigger SystemBean.monthlyAwards(); // unactive if (user.getActive() == null || !user.getActive()) { FacesMessage message = new FacesMessage("Nalog neaktivan. Morate platiti članarinu i sačekati odobrenje administratora."); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(btnLogin.getClientId(context), message); return null; } return "search"; } else { // invalid FacesMessage message = new FacesMessage("Podaci nisu ispravni"); FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(btnLogin.getClientId(context), message); return null; } }
6
public void setupCommands() { PluginCommand cs = plugin.getCommand("cs"); CommandExecutor commandExecutor = new CommandExecutor() { public boolean onCommand( CommandSender sender, Command command, String label, String[] args ) { if (args.length > 0) { cs(sender, args); } return true; } }; if (cs != null) { cs.setExecutor(commandExecutor); } }
2
public static String decodeJavaEscape(String encoded){ if(encoded.indexOf('\\') == -1) return encoded; StringBuffer buf = new StringBuffer(); for(int i = 0; i < encoded.length(); i++){ if(encoded.charAt(i) == '\\'){ char c = encoded.charAt(++i); switch(c){ case 't': buf.append('\t'); break; case 'n': buf.append('\r'); break; case 'r': buf.append('\n'); break; case '\\': buf.append('\\'); break; case 'u': buf.append((char) Integer.parseInt(encoded.substring(i+1, i+5), 16)); i+=4; break; default: buf.append('\\'); buf.append(c); } } else{ buf.append(encoded.charAt(i)); } } return buf.toString(); }
8
@Override public void actionPerformed(ActionEvent e) { if( e.getSource() == boton_alta_empleado ){ Controlador.getInstance().accion(EventoNegocio.GUI_ALTA_EMPLEADO,GUIPrincipal_Empleado.this); } else if( e.getSource() == boton_baja_empleado){ Controlador.getInstance().accion(EventoNegocio.GUI_BAJA_EMPLEADO, GUIPrincipal_Empleado.this); } else if( e.getSource() == boton_modificar_empleado){ Controlador.getInstance().accion(EventoNegocio.GUI_MODIFICAR_EMPLEADO, GUIPrincipal_Empleado.this); } else if (e.getSource() == boton_mostrar_empleado) { Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_EMPLEADO, GUIPrincipal_Empleado.this); }else if (e.getSource() == boton_mostrar_lista_empleados) { Controlador.getInstance().accion(EventoNegocio.GUI_MOSTRAR_LISTA_EMPLEADOS, GUIPrincipal_Empleado.this); } }
5
public int setBusy() { for(int i=0; i<this.docStates_IsBusy.length;i++) if(!this.docStates_IsBusy[i]) { this.docStates_IsBusy[i] = true; return i; } return -1; }
2
public void setName(String name) { this.name = name; }
0
public void gameRender(ScreenManager screenmanager, ClientStreamReader reciever) { sm = screenmanager; recieveDataHandler = reciever; init(); while(running){ Graphics2D g = sm.getGraphics(); try{ networkTransmit(); }catch(Exception e){ System.err.println("network transmission"); e.printStackTrace(); } try{ renderThings(g); }catch(Exception e){ System.err.println("render things"); e.printStackTrace(); } try{ renderUI(g); }catch(Exception e){ System.err.println("render ui"); e.printStackTrace(); } g.dispose(); //update the screen sm.update(); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } }
5
public static void main(String ... args) throws AWTException, InterruptedException { TetrisSensor sensor = new TetrisSensor(); Point p = sensor.getBoardPosition(); Point [][] points = sensor.getGridPointArray(p); if (p != null) { int width = 0; int height = 0; for (Point [] array : points ) { for (Point point : array) { point.x -= p.x; point.y -= p.y; if (point.x > width) { width = point.x; } if (point.y > height) { height = point.y; } } } //make sure the game has focus. This should be moved Robot r = sensor.getRobot(); r.setAutoDelay(50); r.mouseMove(p.x + 50, p.y + 100); r.waitForIdle(); r.mousePress(InputEvent.BUTTON1_MASK); r.waitForIdle(); r.mouseRelease(InputEvent.BUTTON1_MASK); Rectangle rectangle = new Rectangle(p.x, p.y, width + 1, height + 1); while (true) { //long start = -System.currentTimeMillis(); r.waitForIdle(); sensor = new TetrisSensor(points, rectangle, r); //System.out.println("Made sensor in: " + ((start + System.currentTimeMillis()) + "ms")); //Get piece and move instructions ArrayList<Integer> keyPresses = getKeyPresses(sensor, p, points); if (keyPresses != null) { System.out.println(keyPresses); } //start = -System.currentTimeMillis(); doMoves(r, keyPresses); if (keyPresses != null) { if (keyPresses.contains(KeyEvent.VK_SPACE)) { pieceNumber++; } } //System.out.println("Moved pieces in: " + ((start + System.currentTimeMillis()) + "ms")); } } else { System.out.println("Didn't find board."); } }
9
public void checkEvent(){ // for(String script : haltables.keySet()) // System.out.println(script+": "+haltables.get(script)); for(String script : scripts.keySet()) if(!triggered(script)){ // System.out.println("CondMet: \""+script+"\"\t"+ // main.evaluator.evaluate(scripts.get(script).getKey())+"\ttrig: "+scripts.get(script).getValue()); if(conditionsMet(script)){ main.triggerScript(script, this); if(haltable(script)) main.character.killVelocity(); if(!retrig(script)) scripts.get(script).setValue(true); break; } } }
5
public Forest<T> build(Iterable<T> values) { /* * 1. split by cardinality * 2. from low cardinality to high: append nodes * */ Map<Integer, Map<List<E>, T>> byCardinality = Maps.newTreeMap(); for (T value : values) { List<E> path = funnel.getPath(value); int cardinality = path.size(); if (!byCardinality.containsKey(cardinality)) { byCardinality.put(cardinality, new LinkedHashMap<List<E>, T>()); } //todo handle collision byCardinality.get(cardinality).put(path, value); } List<Tree<T>> roots = new ArrayList<Tree<T>>(); Map<Integer, Map<List<E>, Tree<T>>> treesByCardinality = Maps.newHashMap(); for (Map<List<E>, T> level : byCardinality.values()) { for (Map.Entry<List<E>, T> entry : level.entrySet()) { List<E> path = entry.getKey(); T value = entry.getValue(); Tree<T> valueTree = new Tree<T>(value); //searching parent boolean parentFound = false; for (int prefixCardinality = path.size() - 1; prefixCardinality > 0; prefixCardinality--) { List<E> prefix = path.subList(0, prefixCardinality); if (treesByCardinality.containsKey(prefixCardinality)) { Map<List<E>, Tree<T>> rootsForCardinality = treesByCardinality.get(prefixCardinality); if (rootsForCardinality.containsKey(prefix)) { rootsForCardinality.get(prefix).addChild(valueTree); parentFound = true; break; } } } if (!parentFound) roots.add(valueTree); if (!treesByCardinality.containsKey(path.size())) { treesByCardinality.put(path.size(), new LinkedHashMap<List<E>, Tree<T>>()); } //todo handle collision treesByCardinality.get(path.size()).put(path, valueTree); } } return new Forest<T>(roots); }
9
private String showOpenDialog(){ JFileChooser fc = new JFileChooser(); int rc = fc.showDialog(null, "Select Data File"); if (rc == JFileChooser.APPROVE_OPTION){ File file = fc.getSelectedFile(); return file.getAbsolutePath(); } return null; }
1
public void decrementLifetime() { lifetime--; if(lifetime == 0) for(PositionChangedObservable o : hoveringElements) { o.accept(new DeactivatePowerFailureVisitor()); } }
2
public boolean commandPASS(String nombreUsuario, String passwordUsuario) { if (nombreUsuario == null || passwordUsuario == null) { out.println("autentication_error"); return false; } else { try { // Leer el listado de Usuarios y contrasenas BufferedReader reader = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/root/" + "usersftp.txt")); String line = reader.readLine(); boolean salir = false; while (line != null && salir == false) { line = reader.readLine(); if (line != null) { String[] separacion = line.split(";"); if (separacion[0].equalsIgnoreCase(usuarioEsperandoAutenticacion) && separacion[1].equalsIgnoreCase(passwordUsuario)) { out.println("autentication_success"); logueado = true; reader.close(); return true; } } } out.println("autentication_error"); reader.close(); } catch (Exception e) { e.printStackTrace(); } return false; } }
8
public static String createContact(String name, String email, String publicKey, String memo) { String contactID = "error"; System.out.println("in createContact"); AddressBook addressBook = Helpers.getAddressBook(); if (addressBook == null) { System.out.println("createContact - addressBook returns null"); return contactID; } System.out.println("in createContact,addressBook:"+addressBook); Storable storable = otapi.CreateObject(StoredObjectType.STORED_OBJ_CONTACT); System.out.println("in createContact, storable:"+storable); if (storable != null) { Contact contact = Contact.ot_dynamic_cast(storable); System.out.println("contact:"+contact); if (contact != null) { contact.setContact_id(Helpers.generateID()); contact.setEmail(email); contact.setGui_label(name); contact.setMemo(memo); contact.setPublic_key(publicKey); boolean status = addressBook.AddContact(contact); System.out.println("status addressBook.AddContact:" + status); if (!status) { return contactID; } status = otapi.StoreObject(addressBook, "moneychanger", "gui_contacts.dat"); System.out.println("status addressBook otapi.StoreObject:" + status); if (!status) { return contactID; } contactID = Helpers.generateID(); } } return contactID; }
5
public JsonArray getArray(int index) { Object value = get(index); if (value instanceof JsonArray) { return (JsonArray) value; } return new JsonArray(); }
1
@Override public boolean isRelevant(GameState inState){ boolean isLiveSeer = (inState.playerTest(this.Player) == 2); boolean isDeadSeer = (inState.playerTest(this.Player) == -2); int TimeOfDeath = inState.getTimeOfDeath(this.Player); if(isLiveSeer){ return true; } else { if(isDeadSeer && (this.RoundNum <= TimeOfDeath)) return true; } return false; }
3
public int bestPolynomialFit(){ this.methodUsed = 3; this.sampleErrorFlag = true; this.titleOne = "Best polynomial fitting: r = c[0] + c[1].a + c[1].a^2 + ... + c[n].a^n; best fit degree (n) = "; if(!this.setDataOneDone)this.setDataOne(); ArrayList<Object> al = super.bestPolynomial(); this.bestPolyDegree = ((Integer)al.get(0)).intValue(); this.titleOne += " " + this.bestPolyDegree; for(int i=0; i<this.nInterp; i++){ this.calculatedResponses[i] = 0.0; for(int j=0; j<=this.bestPolyDegree; j++){ this.calculatedResponses[i] += super.best[j]*Math.pow(interpolationConcns[i], j); } } if(!this.supressPlot)this.plott(); this.curveCheck(this.methodIndices[this.methodUsed]); return super.bestPolynomialDegree; }
4
@Override public ArrayList<String> getTopStreak() { ArrayList<String> top_Players = new ArrayList<String>(); PreparedStatement pst = null; ResultSet rs = null; try { pst = conn.prepareStatement("SELECT player_name FROM `ffa_leaderboards` ORDER BY `killstreak` DESC"); rs = pst.executeQuery(); int count = 0; while (rs.next() & count < 10) { if (!rs.getString("player_name").equals("")) { top_Players.add(rs.getString("player_name")); } count++; } } catch (SQLException ex) { } finally { if (pst != null) { try { pst.close(); } catch (SQLException ex) { } } if (rs != null) { try { rs.close(); } catch (SQLException ex) { } } } return top_Players; }
7
public void fadeOut() { stopFadeIn(); if(fadeTime > 0.0f) { if(fadeOut != null) { if(!fadeOut.isFading()) { stopFadeOut(); fadeOut = new GameMusicFade(this, currentGain, getMinGain(), fadeTime, 0.0f); } } else if(gamePlayList.getStopping()) { fadeOut = new GameMusicFade(this, currentGain, getMinGain(), fadeTime, 0.0f); } } else { stop(); } }
4
private float[] normalize(byte[] pixels, float[] normComponents, int normOffset) { if (normComponents == null) { normComponents = new float[normOffset + pixels.length]; } // trivial loop unroll - saves a little time switch (pixels.length) { case 4: normComponents[normOffset + 3] = decodeMins[3] + (float)(pixels[3] & 0xFF) * decodeCoefficients[3]; case 3: normComponents[normOffset + 2] = decodeMins[2] + (float)(pixels[2] & 0xFF) * decodeCoefficients[2]; case 2: normComponents[normOffset + 1] = decodeMins[1] + (float)(pixels[1] & 0xFF) * decodeCoefficients[1]; case 1: normComponents[normOffset ] = decodeMins[0] + (float)(pixels[0] & 0xFF) * decodeCoefficients[0]; break; default: throw new IllegalArgumentException("Someone needs to add support for more than 4 components"); } return normComponents; }
5
public synchronized void valueChanged(TreeSelectionEvent e) { if (decompileThread != null) return; TreePath path = e.getNewLeadSelectionPath(); if (path == null) return; Object node = path.getLastPathComponent(); if (node != null) { if (hierarchyTree && hierModel.isValidClass(node)) lastClassName = hierModel.getFullName(node); else if (!hierarchyTree && packModel.isValidClass(node)) lastClassName = packModel.getFullName(node); else return; startDecompiler(); } }
7
public void run() throws IOException { //Setup Logging environment FileHandler file = new FileHandler(config.serverLog); file.setFormatter(new SimpleFormatter()); LOG.setLevel(Level.INFO); LOG.addHandler(file); // create server socket and set timeout to 0 ServerSocket ss = new ServerSocket(config.port, 0, InetAddress.getByName("0.0.0.0")); ss.setSoTimeout(0); LOG.info("Server running on port: " + config.port); // create new client Client client = new Client(ss, RECV_BUF_LEN, pluginManager, LOG); // while client is accepting create new client thread for the client while(client.accepting) { if(client.canAuthenticate(config.authentication)) { this.clients.add(client); (new ClientThread(client)).start(); } else { client.close(); // close connection to client because it can't authenticate } client = new Client(ss, RECV_BUF_LEN, pluginManager, LOG); // create new client } }
2
private Image getImage(AffineTransform transformation) { if (cachedImage == null || lastZoom != pModel.getZoom() || lastOffsetX != pModel.getViewOffsetX() || lastOffsetY != pModel.getViewOffsetY() || lastCanvasWidth != pModel.getCanvasWidth() || lastCanvasHeight != pModel.getCanvasHeight()) { cachedImage = createNewImage(transformation); lastZoom = pModel.getZoom(); lastOffsetX = pModel.getViewOffsetX(); lastOffsetY = pModel.getViewOffsetY(); lastCanvasWidth = pModel.getCanvasWidth(); lastCanvasHeight = pModel.getCanvasHeight(); } return cachedImage; }
6
static boolean isBoardElementEmpty(char boardElement) { return boardElement != NEXT_LINE_FIELD_CHAR && boardElement == EMPTY_FIELD_CHAR; }
1
private int goTowardsTargetDirection(){ if (target.getX() == this.getX()){ int yDistance = target.getY() - this.getY(); if (yDistance <= 0){ return Standards.NORTH; } else { return Standards.SOUTH; } } else if (target.getY() == this.getY()){ int xDistance = target.getX() - this.getX(); if (xDistance <= 0){ return Standards.WEST; } else { return Standards.EAST; } } else { int xDistance = target.getX() - this.getX(); int yDistance = target.getY() - this.getY(); if (xDistance <= yDistance){ if (yDistance <= 0){ return Standards.NORTH; } else { return Standards.SOUTH; } } else { if (xDistance <= 0){ return Standards.WEST; } else { return Standards.EAST; } } } }
7
@Override public void mouseClicked(MouseEvent event, Rectangle bounds, Row row, Column column) { Boolean enabled = (Boolean) row.getData(column); row.setData(column, enabled.booleanValue() ? Boolean.FALSE : Boolean.TRUE); }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BankClient other = (BankClient) obj; if (accounts == null) { if (other.accounts != null) return false; } else if (!accounts.equals(other.accounts)) return false; if (clientId == null) { if (other.clientId != null) return false; } else if (!clientId.equals(other.clientId)) return false; return true; }
9
@Override public double membership(double x) { if (Double.isNaN(x)) { return Double.NaN; } //from Octave smf.m double a_b_ave = (bottomLeft + topLeft) / 2.0; double b_minus_a = topLeft - bottomLeft; double c_d_ave = (topRight + bottomRight) / 2.0; double d_minus_c = bottomRight - topRight; if (Op.isLE(x, bottomLeft)) { return 0.0; } else if (Op.isLE(x, a_b_ave)) { return 2.0 * Math.pow((x - bottomLeft) / b_minus_a, 2); } else if (Op.isLt(x, topLeft)) { return 1.0 - 2.0 * Math.pow((x - topLeft) / b_minus_a, 2); } else if (Op.isLE(x, topRight)) { return 1; } else if (Op.isLE(x, c_d_ave)) { return 1 - 2 * Math.pow((x - topRight) / d_minus_c, 2); } else if (Op.isLt(x, bottomRight)) { return 2 * Math.pow((x - bottomRight) / d_minus_c, 2); } return 0.0; }
7
private static boolean isValidPrice(Float price) { return price != null && price >= PRICE_MIN && price <= PRICE_MAX; }
2
public Main() throws Exception { Config.glAvoidTextureCopies = true; Config.maxPolysVisible = 1000; Config.glColorDepth = 24; Config.glFullscreen = false; Config.farPlane = 4000; Config.glShadowZBias = 0.8f; Config.lightMul = 1; Config.collideOffset = 500; Config.glTrilinear = true; Config.oldStyle3DSLoader = true; }
0
public MinuetoImage flip(boolean horizontal, boolean vertical) { if (horizontal == false && vertical == false) { // Have Nothing To Do But Return Original Image return (MinuetoImage) this.clone(); } else { /* What we want to flip */ int iFlipX = 1, iFlipY = 1; /* Test our Arguments and Convert to Useable Values */ if (horizontal == true) { iFlipX = -1; } if (vertical == true) { iFlipY = -1; } // Return a Negatively Scaled Image return this.scaleInternal(iFlipX, iFlipY); } }
4
public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
0
public synchronized void status(HTSMsg msg, int clientId){ Subscription s = getSubscription((Long) msg.get("subscriptionId"), clientId); HTSPServerConnection c = monitor.getServerConnection(s.serverConnectionId); msg.put("subscriptionId", s.serverSubscriptionId); try { c.send(msg); } catch (IOException e) { try { monitor.getClient(clientId).unsubscribe((Long) msg.get("subscriptionId")); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } }
2
public static String checkForBootstrapperUpdates(boolean verbose, String currentVersion, JSONObject versionsConfig) { if (Util.versionIsEquivalentOrNewer(currentVersion, versionsConfig.get("latestmupdate").toString())) { //Jump out if the launcher is up to date Logger.info("Updater.checkForBootstrapperUpdates", "MUpdate is up to date!"); return null; } else { Logger.info("Updater.checkForBootstrapperUpdates", "Updates were found!"); //Init message variable String message = ""; //Init update queue stack Stack<String> updateQueue = new Stack(); //Build a list of versions to install and the update messages for (Object updateObj : (JSONArray)versionsConfig.get("mupdateversions")) { JSONObject update = (JSONObject)updateObj; if (update.get("name").toString().equals(currentVersion)) { //Break out of loop if the current version is reached break; } else { //Add to queue updateQueue.push(update.get("name").toString()); //Append to message message += "Version " + update.get("name").toString() + ":\n"; for (Object messagesObj : (JSONArray)update.get("messages")) { message += messagesObj.toString() + "\n"; } message += "\n"; } } //Show the update dialog GlobalDialogs.showUpdateNotification(message, "MUpdate"); //Wait for the dialog result while (DialogResult == -1); int updateDialogResult = DialogResult; DialogResult = -1; if (updateDialogResult == 1) { //Update! if (doBootstrapperUpdate(updateQueue, versionsConfig)) { return versionsConfig.get("latestmupdate").toString(); } else { return null; } } else { return null; } } }
7
public static QuenchThirst getSingleton(){ // needed because once there is singleton available no need to acquire // monitor again & again as it is costly if(singleton==null) { synchronized(QuenchThirst.class){ // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton = new QuenchThirst(); } } return singleton; }
2
public static void startupLiterals() { if (Stella.currentStartupTimePhaseP(0)) { Stella.ZERO_WRAPPER = IntegerWrapper.newIntegerWrapper(0); Stella.ONE_WRAPPER = IntegerWrapper.newIntegerWrapper(1); Stella.FALSE_WRAPPER = BooleanWrapper.newBooleanWrapper(false); Stella.TRUE_WRAPPER = BooleanWrapper.newBooleanWrapper(true); Stella.NULL_INTEGER_WRAPPER = IntegerWrapper.newIntegerWrapper(Stella.NULL_INTEGER); Stella.NULL_LONG_INTEGER_WRAPPER = LongIntegerWrapper.newLongIntegerWrapper(Stella.NULL_LONG_INTEGER); Stella.NULL_FLOAT_WRAPPER = FloatWrapper.newFloatWrapper(Stella.NULL_FLOAT); Stella.NULL_STRING_WRAPPER = StringWrapper.newStringWrapper(null); Stella.NULL_MUTABLE_STRING_WRAPPER = MutableStringWrapper.newMutableStringWrapper(null); Stella.NULL_CHARACTER_WRAPPER = CharacterWrapper.newCharacterWrapper(Stella.NULL_CHARACTER); Stella.NULL_FUNCTION_CODE_WRAPPER = FunctionCodeWrapper.newFunctionCodeWrapper(null); Stella.NULL_METHOD_CODE_WRAPPER = MethodCodeWrapper.newMethodCodeWrapper(((java.lang.reflect.Method)(null))); } { Object old$Module$000 = Stella.$MODULE$.get(); Object old$Context$000 = Stella.$CONTEXT$.get(); try { Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$); Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get()))); if (Stella.currentStartupTimePhaseP(2)) { _StartupLiterals.helpStartupLiterals1(); } if (Stella.currentStartupTimePhaseP(4)) { _StartupLiterals.helpStartupLiterals2(); } if (Stella.currentStartupTimePhaseP(6)) { Stella.finalizeClasses(); } if (Stella.currentStartupTimePhaseP(7)) { _StartupLiterals.helpStartupLiterals3(); Stella.defineFunctionObject("BQUOTIFY", "(DEFUN (BQUOTIFY OBJECT) ((TREE OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "bquotify", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("EXPAND-BQUOTE-TREE", "(DEFUN (EXPAND-BQUOTE-TREE OBJECT) ((TREE OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "expandBquoteTree", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineFunctionObject("SIMPLIFY-BQUOTE-TREE", "(DEFUN (SIMPLIFY-BQUOTE-TREE OBJECT) ((TREE OBJECT)))", Native.find_java_method("edu.isi.stella.Stella_Object", "simplifyBquoteTree", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineMethodObject("(DEFMETHOD (PERMANENTIFY OBJECT) ((SELF OBJECT)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella_Object", "permanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (PERMANENTIFY SYMBOL) ((SELF SYMBOL)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Symbol", "permanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (PERMANENTIFY SYMBOL) ((SELF TRANSIENT-SYMBOL)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.TransientSymbol", "permanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (PERMANENTIFY LITERAL-WRAPPER) ((SELF LITERAL-WRAPPER)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.LiteralWrapper", "permanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("PERMANENT-COPY", "(DEFUN (PERMANENT-COPY OBJECT) ((TREE OBJECT)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella_Object", "permanentCopy", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object")}), null); Stella.defineMethodObject("(DEFMETHOD (SOFT-PERMANENTIFY SYMBOL) ((SYMBOL SYMBOL)))", Native.find_java_method("edu.isi.stella.Symbol", "softPermanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (SOFT-PERMANENTIFY SYMBOL) ((SYMBOL TRANSIENT-SYMBOL)))", Native.find_java_method("edu.isi.stella.TransientSymbol", "softPermanentify", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("PRINT-CHARACTER", "(DEFUN PRINT-CHARACTER ((CHAR CHARACTER) (STREAM NATIVE-OUTPUT-STREAM)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "printCharacter", new java.lang.Class [] {java.lang.Character.TYPE, Native.find_java_class("org.powerloom.PrintableStringWriter")}), null); Stella.defineFunctionObject("CREATE-CHARACTER-TYPE-TABLE", "(DEFUN (CREATE-CHARACTER-TYPE-TABLE (ARRAY (256) OF KEYWORD)) ())", Native.find_java_method("edu.isi.stella.Stella", "createCharacterTypeTable", new java.lang.Class [] {}), null); Stella.defineFunctionObject("DIGIT-CHARACTER?", "(DEFUN (DIGIT-CHARACTER? BOOLEAN) ((CH CHARACTER)) :DOCUMENTATION \"Return TRUE if `ch' represents a digit.\" :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE (RETURN (EQL? (AREF *CHARACTER-TYPE-TABLE* (CHARACTER-CODE CH)) :DIGIT)))", Native.find_java_method("edu.isi.stella.Stella", "digitCharacterP", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("LETTER-CHARACTER?", "(DEFUN (LETTER-CHARACTER? BOOLEAN) ((CH CHARACTER)) :DOCUMENTATION \"Return TRUE if `ch' represents a letter.\" :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE (RETURN (EQL? (AREF *CHARACTER-TYPE-TABLE* (CHARACTER-CODE CH)) :LETTER)))", Native.find_java_method("edu.isi.stella.Stella", "letterCharacterP", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("UPPER-CASE-CHARACTER?", "(DEFUN (UPPER-CASE-CHARACTER? BOOLEAN) ((CH CHARACTER)) :PUBLIC? TRUE :DOCUMENTATION \"Return TRUE if `ch' represents an upper-case character.\")", Native.find_java_method("edu.isi.stella.Stella", "upperCaseCharacterP", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("LOWER-CASE-CHARACTER?", "(DEFUN (LOWER-CASE-CHARACTER? BOOLEAN) ((CH CHARACTER)) :PUBLIC? TRUE :DOCUMENTATION \"Return TRUE if `ch' represents a lower-case character.\")", Native.find_java_method("edu.isi.stella.Stella", "lowerCaseCharacterP", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("WHITE-SPACE-CHARACTER?", "(DEFUN (WHITE-SPACE-CHARACTER? BOOLEAN) ((CH CHARACTER)) :DOCUMENTATION \"Return TRUE if `ch' is a white space character.\" :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE (RETURN (EQL? (AREF *CHARACTER-TYPE-TABLE* (CHARACTER-CODE CH)) :WHITE-SPACE)))", Native.find_java_method("edu.isi.stella.Stella", "whiteSpaceCharacterP", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("ALL-UPPER-CASE-STRING?", "(DEFUN (ALL-UPPER-CASE-STRING? BOOLEAN) ((S STRING)) :DOCUMENTATION \"Return TRUE if all letters in `s' are upper case.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "allUpperCaseStringP", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("ALL-LOWER-CASE-STRING?", "(DEFUN (ALL-LOWER-CASE-STRING? BOOLEAN) ((S STRING)) :DOCUMENTATION \"Return TRUE if all letters in `s' are lower case.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella", "allLowerCaseStringP", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("INITIALIZE-CHARACTER-UPCASE-TABLE", "(DEFUN (INITIALIZE-CHARACTER-UPCASE-TABLE STRING) ())", Native.find_java_method("edu.isi.stella.Stella", "initializeCharacterUpcaseTable", new java.lang.Class [] {}), null); Stella.defineFunctionObject("INITIALIZE-CHARACTER-DOWNCASE-TABLE", "(DEFUN (INITIALIZE-CHARACTER-DOWNCASE-TABLE STRING) ())", Native.find_java_method("edu.isi.stella.Stella", "initializeCharacterDowncaseTable", new java.lang.Class [] {}), null); Stella.defineFunctionObject("UPCASE-CHARACTER", "(DEFUN (UPCASE-CHARACTER CHARACTER) ((CHAR CHARACTER)) :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE :DOCUMENTATION \"If `char' is lowercase, return its uppercase version,\notherwise, return 'char' unmodified.\" (RETURN (NTH *CHARACTER-UPCASE-TABLE* (CHARACTER-CODE CHAR))))", Native.find_java_method("edu.isi.stella.Stella", "upcaseCharacter", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("DOWNCASE-CHARACTER", "(DEFUN (DOWNCASE-CHARACTER CHARACTER) ((CHAR CHARACTER)) :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE :DOCUMENTATION \"If `char' is uppercase, return its lowercase version,\notherwise, return 'char' unmodified.\" (RETURN (NTH *CHARACTER-DOWNCASE-TABLE* (CHARACTER-CODE CHAR))))", Native.find_java_method("edu.isi.stella.Stella", "downcaseCharacter", new java.lang.Class [] {java.lang.Character.TYPE}), null); Stella.defineFunctionObject("PRINT-STRING-READABLY", "(DEFUN PRINT-STRING-READABLY ((STRING STRING) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.stella.Stella", "printStringReadably", new java.lang.Class [] {Native.find_java_class("java.lang.String"), Native.find_java_class("org.powerloom.PrintableStringWriter")}), null); Stella.defineFunctionObject("STRING-TO-MUTABLE-STRING", "(DEFUN (STRING-TO-MUTABLE-STRING MUTABLE-STRING) ((S STRING)) :DOCUMENTATION \"Copy `s' into a mutable string with the same content.\nIn Lisp and C++ this simply copies `s'.\" :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE (RETURN (VERBATIM :COMMON-LISP (CL:COPY-SEQ S) :CPP \"strcpy(new (GC) char[strlen(s)+1], s)\" :JAVA \"new StringBuffer(s)\")))", Native.find_java_method("edu.isi.stella.Stella", "stringToMutableString", new java.lang.Class [] {Native.find_java_class("java.lang.String")}), null); Stella.defineFunctionObject("MUTABLE-STRING-TO-STRING", "(DEFUN (MUTABLE-STRING-TO-STRING STRING) ((S MUTABLE-STRING)) :DOCUMENTATION \"Convert `s' into a regular string with the same content.\nIn Lisp and C++ this is a no-op.\" :PUBLIC? TRUE :GLOBALLY-INLINE? TRUE (RETURN (VERBATIM :COMMON-LISP S :CPP \"s\" :JAVA \"s.toString()\")))", Native.find_java_method("edu.isi.stella.Stella", "mutableStringToString", new java.lang.Class [] {Native.find_java_class("java.lang.StringBuffer")}), null); Stella.defineMethodObject("(DEFMETHOD (NUMBER-WRAPPER-TO-FLOAT FLOAT) ((SELF OBJECT)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.Stella_Object", "numberWrapperToFloat", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (NUMBER-WRAPPER-TO-FLOAT FLOAT) ((SELF INTEGER-WRAPPER)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.IntegerWrapper", "numberWrapperToFloat", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (NUMBER-WRAPPER-TO-FLOAT FLOAT) ((SELF LONG-INTEGER-WRAPPER)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.LongIntegerWrapper", "numberWrapperToFloat", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineMethodObject("(DEFMETHOD (NUMBER-WRAPPER-TO-FLOAT FLOAT) ((SELF FLOAT-WRAPPER)) :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella.FloatWrapper", "numberWrapperToFloat", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null))); Stella.defineFunctionObject("STARTUP-LITERALS", "(DEFUN STARTUP-LITERALS () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupLiterals", "startupLiterals", new java.lang.Class [] {}), null); { MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_LITERALS); KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupLiterals"), Stella.NULL_STRING_WRAPPER); } } if (Stella.currentStartupTimePhaseP(8)) { Stella.finalizeSlots(); Stella.cleanupUnfinalizedClasses(); } if (Stella.currentStartupTimePhaseP(9)) { Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA"))))); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL ZERO-WRAPPER INTEGER-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL ONE-WRAPPER INTEGER-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL TRUE-WRAPPER BOOLEAN-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL FALSE-WRAPPER BOOLEAN-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-INTEGER-WRAPPER INTEGER-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-LONG-INTEGER-WRAPPER LONG-INTEGER-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-FLOAT-WRAPPER FLOAT-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-STRING-WRAPPER STRING-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-MUTABLE-STRING-WRAPPER MUTABLE-STRING-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-CHARACTER-WRAPPER CHARACTER-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-FUNCTION-CODE-WRAPPER FUNCTION-CODE-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL NULL-METHOD-CODE-WRAPPER METHOD-CODE-WRAPPER NULL :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LITERAL-TYPE-INFO-TABLE* (HASH-TABLE OF TYPE (KEY-VALUE-LIST OF KEYWORD OBJECT)) (NEW HASH-TABLE) :DOCUMENTATION \"Table that holds a variety of information about literal\ntypes, e.g., the name of their null-wrapper, wrap-function, etc.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LITERAL-TYPES* (LIST OF TYPE) (NEW LIST) :DOCUMENTATION \"List of literal types stored in '*literal-type-info-table*'.\nMaintained for iteration purposes.\")"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CHARACTER-TYPE-TABLE* (ARRAY (256) OF KEYWORD) (CREATE-CHARACTER-TYPE-TABLE) :DOCUMENTATION \"Table of character types. Entry 'i' represents the type\nof the character whose 'char-code' equals 'i'. Each character is classified \nby one of the following keywords: :DIGIT, :LETTER, :SYMBOL-CONSTITUENT, \n:SYMBOL-QUALIFIER, :ESCAPE, :DELIMITER, :WHITE-SPACE, or :OTHER.\" :PUBLIC? TRUE)"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CHARACTER-UPCASE-TABLE* STRING (INITIALIZE-CHARACTER-UPCASE-TABLE))"); Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *CHARACTER-DOWNCASE-TABLE* STRING (INITIALIZE-CHARACTER-DOWNCASE-TABLE))"); } } finally { Stella.$CONTEXT$.set(old$Context$000); Stella.$MODULE$.set(old$Module$000); } } }
7
public Function parse() { System.out.println(s); StringTokenizer tokenizer = new StringTokenizer(s); while (tokenizer.hasMoreTokens()) { String str = tokenizer.nextToken(); last = operation_stack.peek(); if (str.equals("(")) { operation_stack.push(str); } else if (str.equals(")")) { //vyhodnocuje az po predch. zatvorku while (!last.equals("(")) { f = createFunction(last, f); operation_stack.pop(); last = operation_stack.peek(); } operation_stack.pop(); } else if (priority.indexOf(str) > -1) { //nie je to cislo, ale op. if (priority.indexOf(str) >= priority.indexOf(last)) { operation_stack.push(str); } else { while (priority.indexOf(str) < priority.indexOf(last)) { f = createFunction(last, f); operation_stack.remove(last); last = operation_stack.peek(); } operation_stack.push(str); } } else if (str.equals("z")) { function_stack.push(id); } else { Complex c = parse_complex(str); Function constant = new Constant(c); function_stack.push(constant); } } // System.out.println(operation_stack); // System.out.println(complex_stack); return f; }
8