text
stringlengths
14
410k
label
int32
0
9
public int getClosestColor(int c) { if (c == 0) return 0; int bestInd = 0; float bestDif = Util.colorDiff(pal[0], c); for (int i = 0; i < pal.length; i++) { float d = Util.colorDiff(pal[i], c); if (d < bestDif) { bestDif = d; bestInd = i; } } return bestInd; }
3
public static void _pf_mark_area(Coord start, Coord end) { Coord s1 = start.sub(MapView.tilefy_ns(start)); Coord s2 = end.sub(MapView.tilefy_ns(end));// .add(MCache.tileSize); // Coord s1 = new Coord(start.x, start.y); // Coord s2 = new Coord(end.x, end.y); // Coord st_trans = start.sub((start.div(11)).mul(11)); // Coord en_trans = end.sub((end.div(11)).mul(11)); if (s1.x > 6) start.x += 6; if (s1.y > 6) start.y += 6; if (s2.x < 4) end.x -= 6; if (s2.y < 4) end.y -= 6; // if (s1.x > s2.x) s2.x = s1.x + 1; // if (s1.y > s2.y) s2.y = s1.y + 1; Coord p1 = _pf_real2map(start); Coord p2 = _pf_real2map(end); if (!_pf_in_array(p1) || !_pf_in_array(p2)) return; for (int i = p1.x; i <= p2.x; i++) for (int j = p1.y; j <= p2.y; j++) _pf_map[i][j] = AStar.Constants.DIAGONAL_NON_PASSABLE; }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainWindow().setVisible(true); knowledge = new Knowledge(); buttons = new ArrayList<>(); System.out.println("<<Knowledge created>>"); Question.question1(); createButtonList(); } }); }
6
public UninstallApplicationMenu(Logger logger, boolean debug, ADBController adbController, SettingsManager settings, LangFileParser parser, Device device) { initComponents(); this.setLocationRelativeTo(null); this.setIconImage(new ImageIcon(this.getClass().getResource("/eu/m4gkbeatz/androidtoolkit/resources/UniversalAndroidToolkit_logo.png")).getImage()); this.logger = logger; this.debug = debug; this.adbController = adbController; this.settings = settings; this.parser = parser; this.device = device; loadTranslations(); jList1.setCellRenderer(new ApplicationListCellRenderer()); try { getApps(); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while loading the packages from the device (" + device.toString() + "). Is it still plugged in?\n" + "The stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }
1
public void showColorKmean(int K, boolean useNativeColors) { try { Kmean kmean; if(useNativeColors) kmean = new Kmean(portableMap.getHeight(), portableMap.getWidth(), 3, portableMap.getColorData()); else kmean = new Kmean(portableMap.getHeight(), portableMap.getWidth(), 3, null); kmean.setK(K); for(int i = 0; i < portableMap.getHeight(); ++i) for(int j = 0; j < portableMap.getWidth(); ++j) kmean.setValue(i, j, new float[] {portableMap.getColorData(i, j).getRed(), portableMap.getColorData(i, j).getGreen(), portableMap.getColorData(i, j).getBlue()}); kmean.runKmean(); kmean.display(); } catch (MyExceptions e) { e.printStackTrace(); } }
4
@Override public void update(int mouseX, int mouseY, boolean pressed) { if(this.x <= mouseX && mouseX <= this.x+this.width && this.y <= mouseY && mouseY <= this.y+this.height) if(pressed) this.state = 2; else this.state = 1; else this.state = 0; super.update(mouseX, mouseY, pressed); }
5
private BaseObject GetNearestObjectByMat( Enums.GMaterials material ) { if (visible_objs.size() == 0) return null; BaseObject obj = null; for (BaseObject element : visible_objs) { if (element != null && element.GetMatCountByType(material) > 0) { if (obj == null) obj = element; if (Math.abs(obj.GetCellX() - this.GetCellX()) + Math.abs(obj.GetCellY() - this.GetCellY()) > Math.abs(element.GetCellX() - this.GetCellX()) + Math.abs(element.GetCellY() - this.GetCellY())) obj = element; } } return obj; }
6
public boolean doubleUp(int upcard, int total, boolean soft) { if (upcard == 1) return false; if (soft) { return upcard <= 6 && total <= 18 && total + 2*upcard >= 23; } else { return total <= 11 && total >= 9 && upcard != 10 && (total != 9 || upcard >= 7); } }
8
public void addFieldFilter(String fieldName, String pattern) { if (!fieldFilters.containsKey(fieldName)) { fieldFilters.put(fieldName, new LinkedList<String>()); } fieldFilters.get(fieldName).add(pattern); }
1
public JSONObject getBefehl() { JSONObject now = null; try { JSONObject file = new JSONObject(read()); if (file.getJSONArray("Befehl").length() == 0) { return null; } now = file.getJSONArray("Befehl").getJSONObject(0); file.getJSONArray("Befehl").remove(0); write(file.toString()); } catch (JSONException e) { Output.error(e); return null; } catch (FileNotFoundException e) { Output.printTabLn("Keine Befehlsdatei gefunden.", Output.ERROR); return null; } return now; }
3
public void run(File subjectSortedInput, File indexOutput) { try { IndexWriter indexWriter = new IndexWriter(indexOutput); NQuadParser parserIn = new NQuadParser(subjectSortedInput); PrintStream out = new PrintStream(indexOutput); while (parserIn.hasNext()) { NQuad nq = parserIn.next(); if ((nq.object.startsWith("\"")) && (nq.object.length()>2)) { String in = nq.object.substring(1,nq.object.length()-2); if (in.length()>0) { BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.ENGLISH); wordIterator.setText(in); int wordBoundary = wordIterator.first(); int wordPrev = wordBoundary; while (wordBoundary != BreakIterator.DONE) { wordPrev = wordBoundary; wordBoundary = wordIterator.next(); if (wordBoundary != BreakIterator.DONE) { String word = this.prepWord(in.substring(wordPrev, wordBoundary)); if (word.length() > 0) { TreeSet<String> terms = new TreeSet<String>(); terms.add(word); indexWriter.addToIndex(nq.subject, terms); } } } } } } out.close(); } catch (IOException e) { e.printStackTrace(); } }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InventoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InventoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InventoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InventoryFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InventoryFrame().setVisible(true); } }); }
6
private void writeFiles(DataOutputStream dataOut, TempFileInfo[] fileToWrite, int resolution) throws IOException, FileNotFoundException { final int sizeOfBuffer = 1024; byte[] byteTempArray = new byte[sizeOfBuffer]; for (TempFileInfo info3 : fileToWrite) { byte[] outputBytes = new byte[(int) info3.actualLength]; int pointInOutput = 0; File f = new File(Constants.getRoot(), info3.file + "-0"); try (FileInputStream in = new FileInputStream(f)) { IOUtils.skipFully(in, info3.offset); int current = 0; int posInFile = 0; while (current < info3.length) { int numOfBytesRead = IOUtils.read(in, byteTempArray, 0, sizeOfBuffer); current+= numOfBytesRead; if (current > info3.length) current = (int) info3.length; for (;posInFile < current/2 && pointInOutput < info3.actualLength; posInFile += resolution) { System.out.printf("I am adding something at %d, %d, %d, %d, %d\n",pointInOutput,posInFile,current,current/2,info3.actualLength); outputBytes[pointInOutput++] = byteTempArray[posInFile*2 - (current - numOfBytesRead)]; outputBytes[pointInOutput++] = byteTempArray[posInFile*2+1 - (current - numOfBytesRead)]; } } if (info3.actualLength != pointInOutput) throw new RuntimeException("Did not actually read in all stuff"); System.out.println("Writing at " + System.currentTimeMillis()); IOUtils.write(outputBytes, dataOut); System.out.println(f.getAbsolutePath() + " : " + outputBytes.length); } } }
6
@Override protected boolean isValidUrl(String url) { if ((url.startsWith(URL_PREFIX_HTTPS) || url.startsWith(URL_PREFIX_HTTP)) && !url.endsWith("/")) { //$NON-NLS-1$ try { new URL(url); return true; } catch (MalformedURLException e) { } } return false; }
4
public String deleteblogDetails() { FacesMessage doneMessage = null; String outcome = null; blogDelegate.deleteByKey(this.blogId); doneMessage = new FacesMessage("Deleted Successfully "); outcome = "/admin/success"; FacesContext.getCurrentInstance().addMessage(null, doneMessage); return outcome; }
0
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(!success) mob.tell(L("Your plant senses fail you.")); else { final CMMsg msg=CMClass.getMsg(mob,null,null,CMMsg.MSG_QUIETMOVEMENT|CMMsg.MASK_MAGIC,null); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final StringBuffer yourPlants=new StringBuffer(""); int plantNum=0; final int[] cols= { CMLib.lister().fixColWidth(3,mob.session()), CMLib.lister().fixColWidth(20,mob.session()), CMLib.lister().fixColWidth(40,mob.session()) }; final List<Room> V=myPlantRooms(mob); for(int v=0;v<V.size();v++) { final Room R=V.get(v); if(R!=null) { int i=0; Item I=myPlant(R,mob,0); while(I!=null) { yourPlants.append(CMStrings.padRight(""+(++plantNum),cols[0])+" "); yourPlants.append(CMStrings.padRight(I.name(),cols[1])+" "); yourPlants.append(CMStrings.padRight(R.displayText(mob),cols[2])); yourPlants.append("\n\r"); I=myPlant(R,mob,++i); } } } if(V.size()==0) mob.tell(L("You don't sense that there are ANY plants which are attuned to you.")); else mob.tell(L("### Plant Name Location\n\r@x1",yourPlants.toString())); } } return success; }
7
public static void createAppdataFolder() { File appdata = new File(System.getenv("APPDATA") + "\\CatSigner"); if (!appdata.exists() || !appdata.isDirectory()) { appdata.mkdirs(); System.out.println("AppData folder is created successfully!"); } else { System.out.println("Skipping creation of AppData folder. Already exists."); } }
2
@Override protected void setStatementParameters(PreparedStatement preparedStatement, WhereClause whereClause) throws IOException { int index = 0; for (WhereConstraint constraint : whereClause.getWhereConstraints()) { for (Object parameter : constraint.getParameters()) { if (parameter == null) { continue; } try { if (constraint.isId()) { preparedStatement.setLong(++index, (Long)parameter); } else { Comment._Fields field = (Comment._Fields)constraint.getField(); switch (field) { case content: preparedStatement.setString(++index, (String) parameter); break; case commenter_id: preparedStatement.setInt(++index, (Integer) parameter); break; case commented_on_id: preparedStatement.setLong(++index, (Long) parameter); break; case created_at: preparedStatement.setTimestamp(++index, new Timestamp((Long) parameter)); break; } } } catch (SQLException e) { throw new IOException(e); } } } }
9
public static void main(String args[]) { try{ Socket socket=new Socket("127.0.0.1",6888); //向本机的6888端口发出客户请求 BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //由系统标准输入设备构造BufferedReader对象 PrintWriter os=new PrintWriter(socket.getOutputStream()); //由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket对象得到输入流,并构造相应的BufferedReader对象 String readline; readline=sin.readLine(); //从系统标准输入读入一字符串 while(!readline.equals("bye")){ //若从标准输入读入的字符串为 "bye"则停止循环 os.println(readline); //将从系统标准输入读入的字符串输出到Server os.flush(); //刷新输出流,使Server马上收到该字符串 System.out.println("Client:"+readline); //在系统标准输出上打印读入的字符串 System.out.println("Server:"+is.readLine()); //从Server读入一字符串,并打印到标准输出上 readline=sin.readLine(); //从系统标准输入读入一字符串 } //继续循环 os.close(); //关闭Socket输出流 is.close(); //关闭Socket输入流 socket.close(); //关闭Socket }catch (Exception e) { System.out.println("Error"+e); //出错,则打印出错信息 } }
2
public boolean push(final LocalExpr expr) { final Boolean b = (Boolean) pushes.get(expr); return (b != null) && b.booleanValue(); }
1
private String currentCategory() { if (places[currentPlayer] == 0) return "Pop"; if (places[currentPlayer] == 4) return "Pop"; if (places[currentPlayer] == 8) return "Pop"; if (places[currentPlayer] == 1) return "Science"; if (places[currentPlayer] == 5) return "Science"; if (places[currentPlayer] == 9) return "Science"; if (places[currentPlayer] == 2) return "Sports"; if (places[currentPlayer] == 6) return "Sports"; if (places[currentPlayer] == 10) return "Sports"; return "Rock"; }
9
public PackDetails(String packName, String keyboardSourceFile, String dictionarySourceFile, String themeSourceFile) { PackageName = packName; KeyboardSourceCodeFile = keyboardSourceFile != null && keyboardSourceFile.startsWith(".") ? PackageName + keyboardSourceFile : keyboardSourceFile; DictionarySourceCodeFile = dictionarySourceFile != null && dictionarySourceFile.startsWith(".") ? PackageName + dictionarySourceFile : dictionarySourceFile; ThemeSourceCodeFile = themeSourceFile != null && themeSourceFile.startsWith(".") ? PackageName + themeSourceFile : themeSourceFile; }
6
@EventHandler public void onBlockBreak(BlockBreakEvent event) { BlockState block = event.getBlock().getState(); if (block instanceof Sign) { Sign sign = (Sign) block; if (!sign.getLine(0).equals("[Class]")) return; World world = event.getBlock().getWorld(); int x = event.getBlock().getX(); int y = event.getBlock().getY(); int z = event.getBlock().getZ(); String string = stringBuilder.BuildString(world, x, y, z); if (plugin.signSet.containsKey(string + "_exists")) { plugin.signSet.remove(string + "_exists"); } Iterator<String> iterator = plugin.signSet.keySet().iterator(); String s; while (iterator.hasNext()) { s = iterator.next(); if (s.startsWith(string)) { iterator.remove(); } } } }
5
private byte[] generateCode(String encodedSource) { boolean hasScript = (scriptOrFnNodes[0].getType() == Token.SCRIPT); boolean hasFunctions = (scriptOrFnNodes.length > 1 || !hasScript); String sourceFile = null; if (compilerEnv.isGenerateDebugInfo()) { sourceFile = scriptOrFnNodes[0].getSourceName(); } ClassFileWriter cfw = new ClassFileWriter(mainClassName, SUPER_CLASS_NAME, sourceFile); cfw.addField(ID_FIELD_NAME, "I", ClassFileWriter.ACC_PRIVATE); cfw.addField(DIRECT_CALL_PARENT_FIELD, mainClassSignature, ClassFileWriter.ACC_PRIVATE); cfw.addField(REGEXP_ARRAY_FIELD_NAME, REGEXP_ARRAY_FIELD_TYPE, ClassFileWriter.ACC_PRIVATE); if (hasFunctions) { generateFunctionConstructor(cfw); } if (hasScript) { cfw.addInterface("org/mozilla/javascript/Script"); generateScriptCtor(cfw); generateMain(cfw); generateExecute(cfw); } generateCallMethod(cfw); generateNativeFunctionOverrides(cfw, encodedSource); int count = scriptOrFnNodes.length; for (int i = 0; i != count; ++i) { ScriptOrFnNode n = scriptOrFnNodes[i]; BodyCodegen bodygen = new BodyCodegen(); bodygen.cfw = cfw; bodygen.codegen = this; bodygen.compilerEnv = compilerEnv; bodygen.scriptOrFn = n; bodygen.generateBodyCode(); if (n.getType() == Token.FUNCTION) { OptFunctionNode ofn = OptFunctionNode.get(n); generateFunctionInit(cfw, ofn); if (ofn.isTargetOfDirectCall()) { emitDirectConstructor(cfw, ofn); } } } if (directCallTargets != null) { int N = directCallTargets.size(); for (int j = 0; j != N; ++j) { cfw.addField(getDirectTargetFieldName(j), mainClassSignature, ClassFileWriter.ACC_PRIVATE); } } emitRegExpInit(cfw); emitConstantDudeInitializers(cfw); return cfw.toByteArray(); }
9
@Override public void remove(int i, int j) throws BadLocationException { if(!this.autoCompletion) { super.remove(i, j); return; } int k = getSelectionStart(); if(k > 0) k--; if(getText(0, k).equals("")) { super.remove(0, getLength()); return; } String s = getMatch(getText(0, k)); if(!Java2sAutoTextField.this.isStrict && s == null) super.remove(i, j); else { super.remove(0, getLength()); super.insertString(0, s, null); } if(Java2sAutoTextField.this.autoComboBox != null && s != null) Java2sAutoTextField.this.autoComboBox.setSelectedValue(s); try { setSelectionStart(k); setSelectionEnd(getLength()); } catch(Exception ignored) { } }
8
@Override public void i3channelSilence(MOB mob, String channel) { if((mob==null)||(!i3online())) return; if((channel==null) ||(channel.length()==0) ||(Intermud.getLocalChannel(channel).length()==0)) { mob.tell(L("You must specify an actual channel name.")); return; } if(Intermud.removeFakeChannel(channel).length()>0) mob.tell(L("Unofficial channel closed.")); final ChannelListen ck=new ChannelListen(); ck.sender_name=mob.Name(); ck.channel=channel; ck.onoff="0"; try { ck.send(); }catch(final Exception e){Log.errOut("IMudClient",e);} }
7
private Set<Point> generateDoors(Room room, Direction existingDirection) { Set<Point> doors = new LinkedHashSet<Point>(); for (Direction direction : Direction.values()) { if (direction == existingDirection) continue; if (generator.nextDouble() <= generationProbability) { doors.add(generateDoor(room, direction)); } } return doors; }
3
public void testThatDequeueOnEmptyThrowsIndexOutOfBoundsException() { boolean exceptionOccurred = false; try { Agent o = q.dequeue(); } catch (java.util.NoSuchElementException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); }
1
public void drawState(Graphics g, Automaton automaton, State state, Point point, Color color) { super.drawState(g, automaton, state, point, color); drawStateOutput(g, state, point, color); }
0
final int method2679(int i, int i_7_, int i_8_) { anInt4232++; if (i_8_ != 1595) return 38; int i_9_ = (Class348_Sub42_Sub8_Sub2.windowHeight <= i ? i : Class348_Sub42_Sub8_Sub2.windowHeight); if (Class186_Sub1.aClass341_5808 == this) return 0; if (this == Class237_Sub1.aClass341_5821) return i_9_ - i_7_; if (Class27.aClass341_399 == this) return (i_9_ - i_7_) / 2; return 0; }
5
public void init() { boolean debug = CommandLine.booleanVariable("debug"); if (debug) { // Enable debug logging Logger logger = Logger.getLogger("com.reuters.rfa"); logger.setLevel(Level.FINE); Handler[] handlers = logger.getHandlers(); if (handlers.length == 0) { Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); logger.addHandler(handler); } for (int index = 0; index < handlers.length; index++) handlers[index].setLevel(Level.FINE); } Context.initialize(); // Create a Session String sessionName = CommandLine.variable("session"); _session = Session.acquire(sessionName); if (_session == null) { System.out.println("Could not acquire session."); Context.uninitialize(); System.exit(1); } System.out.println("RFA Version: " + Context.getRFAVersionInfo().getProductVersion()); // Create an Event Queue _eventQueue = EventQueue.create("myEventQueue"); // Create a OMMPool. _pool = OMMPool.create(); // Create an OMMEncoder _encoder = _pool.acquireEncoder(); _encoder.initialize(OMMTypes.MSG, 5000); // Initialize client for login domain. _loginClient = new PrivateStrmLoginClient(this); // Initialize item manager for item domains _itemManager = new PrivateStrmItemManager(this); // Initialize directory client for directory domain. _directoryClient = new PrivateStrmDirectoryClient(this); // Create an OMMConsumer event source _ommConsumer = (OMMConsumer)_session.createEventSource(EventSource.OMM_CONSUMER, "myOMMConsumer", true); // Application may choose to down-load the enumtype.def and // RWFFldDictionary // This example program loads the dictionaries from file only. String fieldDictionaryFilename = CommandLine.variable("rdmFieldDictionary"); String enumDictionaryFilename = CommandLine.variable("enumType"); try { PSGenericOMMParser.initializeDictionary(fieldDictionaryFilename, enumDictionaryFilename); } catch (DictionaryException ex) { System.out.println("ERROR: Unable to initialize dictionaries."); System.out.println(ex.getMessage()); if (ex.getCause() != null) System.err.println(": " + ex.getCause().getMessage()); cleanup(-1); return; } // Send login request // Application must send login request first _loginClient.sendRequest(); }
6
@Test public void fillMap () { String map = "ghi\n"; map += "def\n"; map += "abc\n"; System.out.println (map); char[][] myMap = new char[3][3]; int row = 2, col = 0; for (int i = 0; i < map.length (); i++) { char c = map.charAt (i); if (c == '\n') { row--; col = 0; } else { myMap[row][col++] = c; } } for (char[] r : myMap) { for (char val : r) { System.out.print (val); } System.out.println (); } System.out.println (); int x = 0, y = 0; System.out.println (myMap[y][x] + " = a?"); x = 1; y = 2; System.out.println (myMap[y][x] + " = h?"); x = 2; y = 0; System.out.println (myMap[y][x] + " = c?"); System.out.println (); for (int i = myMap.length - 1; i >= 0; i--) { for (int j = 0; j < myMap[i].length; j++) { System.out.print (myMap[i][j]); } System.out.println (); } }
6
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { player = new Player(320 / 2, 240 / 2, this); player.init(gc, sbg); worldEntities.add(player); for(int x = 0; x < sizeX; x++) { for(int y = 0; y < sizeY; y++) { if(data[x][y] == wall) { worldTiles.add(new WallTile(x*tileSize, y*tileSize, 0)); } if(data[x][y] == floor) { worldTiles.add(new FloorTile(x*tileSize, y*tileSize)); } } } for(int i = 0; i < worldTiles.size(); i++) { worldTiles.get(i).init(gc, sbg); } }
5
public int getSecondID(){ return second_city.getID(); }
0
@SuppressWarnings("unchecked") @Override public T deleteAt(int index) throws DAIndexOutOfBoundsException { T returner = null; if((index >= 0) && (index <= size - 1)) { returner = (T)array[index]; // starts at index and shifts every object down by 1 System.arraycopy(array, index + 1, array, index, size - index - 1); // sets the last item to null array[size - 1] = null; size--; packArray(); } else if((index < 0) || (index > size - 1)) { throw new IndexOutOfBoundsException(); } return returner; }
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> try{ setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception e){ e.printStackTrace(); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Vista().setVisible(true); } }); }
7
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof AbstractFreightCarriage)) return false; AbstractFreightCarriage other = (AbstractFreightCarriage) obj; if (curCapacity != other.curCapacity) return false; if (maxCapacity != other.maxCapacity) return false; return true; }
5
public void tick(){ if (x + xa>0 && x + xa <GamePanel.WIDTH - width) { x = x + xa; } if (collision2()) { BlockModeState.block = new FallingBlocks(Random(15, 120),Random(15, 120)); FallingBlocks.lives--; Sound.playBlockHit(); } if (collision3()) { BlockModeState.block2 = new FallingBlocks(Random(15, 120),Random(15, 120)); FallingBlocks.lives--; Sound.playBlockHit(); } if (collision4()) { BlockModeState.block3 = new FallingBlocks(Random(15, 120),Random(15, 120)); FallingBlocks.lives--; Sound.playBlockHit(); } if (collision5()) { BlockModeState.block4 = new FallingBlocks(Random(15, 120),Random(15, 120)); FallingBlocks.lives--; Sound.playBlockHit(); } if (collision6()) { BlockModeState.block5 = new FallingBlocks(Random(15, 120),Random(15, 120)); FallingBlocks.lives--; Sound.playBlockHit(); } }
7
public boolean baca(String no_beli){ boolean adaKesalahan = false; Connection cn = null; this.no_beli = no_beli; listKwitansi = null; try{ Class.forName(Koneksi.driver); } catch (Exception ex){ adaKesalahan = true; JOptionPane.showMessageDialog(null,"JDBC Driver tidak ditemukan atau rusak\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE); } if (!adaKesalahan){ try { cn = DriverManager.getConnection(Koneksi.database+"?user="+ Koneksi.user+"&password="+Koneksi.password+""); } catch (Exception ex) { adaKesalahan = true; JOptionPane.showMessageDialog(null,"Koneksi ke "+Koneksi.database+" gagal\n"+ex,"Kesalahan",JOptionPane.ERROR_MESSAGE); } if (!adaKesalahan){ String SQLStatemen; Statement sta; ResultSet rset; try { SQLStatemen = "select * from kwitansi where no_beli='"+no_beli+"'"; sta = cn.createStatement(); rset = sta.executeQuery(SQLStatemen); rset.next(); rset.last(); listKwitansi = new Object[rset.getRow()][4]; rset.first(); int i=0; do { if (!rset.getString("kode_buku").equals("")){ listKwitansi[i] = new Object[]{ rset.getString("kode_buku"), rset.getInt("jumlah"), rset.getInt("harga")}; } i++; } while (rset.next()); sta.close(); rset.close(); if (listKwitansi.length>0) { adaKesalahan = false; } } catch (Exception ex){ adaKesalahan = true; } } } return !adaKesalahan; }
8
public int compare(String o1, String o2) { String s1 = (String)o1; String s2 = (String)o2; int thisMarker = 0; int thatMarker = 0; int s1Length = s1.length(); int s2Length = s2.length(); while (thisMarker < s1Length && thatMarker < s2Length) { String thisChunk = getChunk(s1, s1Length, thisMarker); thisMarker += thisChunk.length(); String thatChunk = getChunk(s2, s2Length, thatMarker); thatMarker += thatChunk.length(); // If both chunks contain numeric characters, sort them numerically int result = 0; if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // Simple chunk comparison by length. int thisChunkLength = thisChunk.length(); result = thisChunkLength - thatChunk.length(); // If equal, the first different number counts if (result == 0) { for (int i = 0; i < thisChunkLength; i++) { result = thisChunk.charAt(i) - thatChunk.charAt(i); if (result != 0) { return result; } } } } else { result = thisChunk.compareTo(thatChunk); } if (result != 0) return result; } return s1Length - s2Length; }
8
private boolean jj_3_7() { if (jj_3R_25()) return true; return false; }
1
@Override protected ElementHandler createHandler(String name) { if ("name".equals(name)) { return new StringValueBuilder(parentContext, new FinishCallback<String>() { @Override public void handle(String value) { CSGOperationNodeBuilder.this.operation = CSGOperation.valueOf(value); } }); } else if ("csg_operation".equals(name)) { return new CSGOperationNodeBuilder(parentContext, new FinishCallback<CSGOperationNode>() { @Override public void handle(CSGOperationNode value) { if (CSGOperationNodeBuilder.this.left == null) { CSGOperationNodeBuilder.this.left = value; } else if (CSGOperationNodeBuilder.this.right == null) { CSGOperationNodeBuilder.this.right = value; } else { throw new IllegalStateException("CSG operation has more than two arguments!"); } } }); } else if ("csg_object".equals(name)) { return new SceneObjectsBuilder(parentContext, new FinishCallback<List<SceneObject>>() { @Override public void handle(List<SceneObject> value) { if (value.isEmpty()) { throw new IllegalArgumentException("Empty CSG object!"); } if (value.size() > 1) { throw new IllegalArgumentException("Multiple primitives/models are not allowed under csg_object!"); } if (CSGOperationNodeBuilder.this.left == null) { CSGOperationNodeBuilder.this.left = new CSGObjectNode(value.get(0)); } else if (CSGOperationNodeBuilder.this.right == null) { CSGOperationNodeBuilder.this.right = new CSGObjectNode(value.get(0)); } else { throw new IllegalStateException("CSG operation has more than two arguments!"); } } }); } return null; }
9
public void setCanonicalizationMethod(CanonicalizationMethodType value) { this.canonicalizationMethod = value; }
0
public void drawCW(Bitmap bitmap, int xo, int yo) { for (int y = 0; y < bitmap.width; y++) { int yy = y + yo; if (yy < 0 || yy >= this.height) continue; for (int x = 0; x < bitmap.height; x++) { int xx = bitmap.height - x + xo; if (xx < 0 || xx >= this.width) continue; int color = bitmap.pixels[y + x * bitmap.width]; if (color < 0) pixels[xx + yy * this.width] = color; } } }
7
public static void DBClose() { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } }
1
public ExtDecimal negate() { if (type == Type.NUMBER) { return new ExtDecimal(content.negate()); } else if (type == Type.POSITIVEZERO) { return new ExtDecimal(Type.NEGATIVEZERO); } else if (type == Type.NEGATIVEZERO) { return new ExtDecimal(Type.POSITIVEZERO); } else if (type == Type.INFINITY) { return new ExtDecimal(Type.NEGATIVEINFINITY); } else if (type == Type.NEGATIVEINFINITY) { return new ExtDecimal(Type.INFINITY); } else { throw new UnsupportedOperationException("Unknown type"); } }
5
public Address getAddress(Class<?> clazz) { ArrayList<Address> adrList = addresses.get(clazz); if (adrList != null) { return adrList.get(random.nextInt(adrList.size())); /* TODO smart balancing */ } else { return null; } }
2
public static void main(String[] args) throws IOException { theme = new Theme(); MetalLookAndFeel.setCurrentTheme(theme); try { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } catch (ClassNotFoundException ex) { Logger.getLogger(TODOManager.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(TODOManager.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(TODOManager.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(TODOManager.class.getName()).log(Level.SEVERE, null, ex); } savedSettings = new State(); savedSettings.loadState(); backend = new BackendAPI(savedSettings.getItemIndex()); manager = new LanguageManager(); TODOManager main = new TODOManager(); manager.setTodoManager(main); Timer timer = new Timer(); TaskReminder reminder = new TaskReminder(); timer.schedule(reminder,0,1*60000); }
4
public static void insertActionLog( int uid, int bid, int auctionID, int actionType, String summary, String description ) throws DatabaseException { Connection conn = null; ResultSet rs = null; PreparedStatement ps = null; long nowTimeMillis = (new Date()).getTime(); String q = "INSERT INTO actionlog(uid,bid,auctionID,actionType,timeMillis,summary,description) VALUES(?,?,?,?,?,?,?)"; try { conn = DBPool.getInstance().getConnection(); ps = conn.prepareStatement( q ); ps.setInt( 1, uid ); ps.setInt( 2, bid ); ps.setInt( 3, auctionID ); ps.setInt( 4, actionType ); ps.setLong( 5, nowTimeMillis ); ps.setString( 6, summary ); ps.setString( 7, description ); ps.executeUpdate(); } catch ( SQLException e ) { System.out.println( "bridge " + e.toString() + e.getStackTrace() ); throw new DatabaseException( e.toString() ); } finally { try { if (rs != null) rs.close(); } catch(Exception e) { } try { if (ps != null) ps.close(); } catch(Exception e) { } try { if (conn != null) conn.close(); } catch(Exception e) { } } }
7
private HashSet<Integer> selectSample(Hashtable<Integer,List<Integer>> coi, int sampleRate){ HashSet<Integer> res = new HashSet<Integer>(); List<Integer> lst_aux = new ArrayList<Integer>(); Enumeration<Integer> e = coi.keys(); while(e.hasMoreElements()){ lst_aux.add(e.nextElement()); } int size = lst_aux.size(); float sample = (float)size*(float)sampleRate/(float)100; Random r = new Random(); int index; while(res.size() < sample && lst_aux.size() != 0){ index = r.nextInt(lst_aux.size()); int objIndex = lst_aux.get(index); int containsPairedIndex = containsPairedIndex(res, coi.get(objIndex)); if(!res.contains(objIndex) && containsPairedIndex != -1){ res.add(objIndex); res.add(containsPairedIndex); lst_aux.remove(index); } else if(res.contains(objIndex) && containsPairedIndex != -1){ res.add(containsPairedIndex); } else if(!res.contains(objIndex) && containsPairedIndex == -1){ res.add(objIndex); lst_aux.remove(index); } } return res; }
9
@EventHandler public void onDropItem(PlayerDropItemEvent e) { if (e.getPlayer().getGameMode() != GameMode.CREATIVE) { if (!plugin.getConfig().getBoolean("can-drop-hat-item")) { if (e.getItemDrop().getItemStack().equals(ItemStackUtil.getHatItem())) { e.getItemDrop().remove(); e.getPlayer().getInventory().setItem(plugin.getConfig().getInt("hat-item-slot") - 1, ItemStackUtil.getHatItem()); } } } }
3
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { loggedInUser = (User) request.getSession().getAttribute("user"); //Check is user is logged in for session if (loggedInUser == null) { response.sendRedirect(request.getContextPath() + "/login"); //Not logged in yet - redirect to login page return; } else { if (request.getRequestURI().equals(request.getContextPath() + "/profile")) { //Show logged in user's profile request.getSession().setAttribute("following", countFollowing(loggedInUser)); request.getSession().setAttribute("followers", countFollowers(loggedInUser)); request.getSession().setAttribute("userMessages", getAllMessages(loggedInUser)); request.getRequestDispatcher("profile.jsp").forward(request, response); //View from corresponding profile.jsp return; } else { //Show specific user's profile specified in URI - /profile/<userEmail> int lastSeparator = request.getRequestURI().lastIndexOf('/'); String uriString = request.getRequestURI().substring(lastSeparator + 1); otherUser = userService.getProfileUser(uriString); //Check to display 404 if (otherUser == null) { request.getRequestDispatcher("../404.jsp").forward(request, response); return; } request.setAttribute("user", otherUser); request.setAttribute("otherUser", true); //To differentiate between logged-in (Session) user and one we're viewing (Page) request.setAttribute("following", countFollowing(otherUser)); request.setAttribute("followers", countFollowers(otherUser)); request.setAttribute("userMessages", getUserMessages(otherUser));//Only view the user's messages, not their friends' etc. request.getRequestDispatcher("../profile.jsp").forward(request, response); //View from corresponding profile.jsp return; } } }
3
public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null || prefix.length() > str.length()) { return false; } final char[] inputCharArray = str.toCharArray(); final char[] prefixCharArray = prefix.toCharArray(); for (int i = 0; i < prefixCharArray.length; i++) { if (!equalsIgnoreCase(prefixCharArray[i], inputCharArray[i])) { return false; } } return true; }
5
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); // Retrieving the username and password form the POST data. String uname = request.getParameter("username"); String passwd1 = request.getParameter("password1"); String remember_me = request.getParameter("rememberMe"); Users u = null; Organizations o=null; // Session HttpSession session = request.getSession(); session.setMaxInactiveInterval(900); session.setAttribute("username", uname); // Handling bad form data in order to avoid Null Pointer Exception if(remember_me == null){ remember_me = "off"; } System.out.println(remember_me); // Creating an instance of the user class with project's root path as the parameter to the constructor Users newUser = new Users(this.getServletContext().getRealPath("/")); Organizations org = new Organizations(); try { u = new Users(this.getServletContext().getRealPath("/"),newUser.getFullName(uname)[0],newUser.getFullName(uname)[1]); o = new Organizations(org.getOrgName(uname)); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Clients client = new Clients(u,o); // Check if the username exists try { if(!newUser.checkIfValueExists("username", uname)){ // User not present, so redirect the user to registration page response.sendRedirect("signup.jsp"); }else{ // Setting cookie if(remember_me.equals("on")){ Cookie c = new Cookie("username",uname); // Setting cookie's age to one day - 24 hours c.setMaxAge(24*60*60); response.addCookie(c); } // User exists, so verify password try { if(newUser.authenticateUser(uname,passwd1)){ session.setAttribute("client", client); RequestDispatcher rd = request.getRequestDispatcher("flightSearchQuery.jsp") ; rd.include(request, response); } else{ // Incorrect password, so send an error message request.setAttribute("password_error", "Incorrect password! Try again."); RequestDispatcher rd = request.getRequestDispatcher("login.jsp") ; rd.include(request, response); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.println("</html></body>"); }
8
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == nextPlayer) { // check if human is done if (( (HumanPlayer) game.getPlayers().get(0)) .getHumanMustFinish()) { JOptionPane.showMessageDialog(game, "You need to finish your turn!", "Next Player", JOptionPane.INFORMATION_MESSAGE); } else { // Update the current player and display it currentPlayerIndex++; String name = game.getPlayers().get(currentPlayerIndex % game.getPlayers().size()).getName(); setCurrentPlayer(name); // Roll the die and display it, also calculates targets setDieRoll(game.rollDie(currentPlayerIndex)); submitted = false; // Take a turn game.getPlayers().get(currentPlayerIndex % game.getPlayers().size()).takeTurn(game); // Repaint players in their new cells game.getBoard().repaint(); } } else if(e.getSource() == makeAccusation) { if (( (HumanPlayer) game.getPlayers().get(0)) .getHumanMustFinish() && !submitted) { game.getAccuse().setVisible(true); } else { JOptionPane.showMessageDialog(game, "It's not your turn!", "Make Accusation", JOptionPane.INFORMATION_MESSAGE); } } }
5
private static String pluralityValue( ArrayList<HashMap<String, String>> examples, String goalAttribute) { Set<String> set = new HashSet<String>(); for (HashMap<String, String> example : examples) { set.add(example.get(goalAttribute)); } int largestFreq = 0; String value = ""; for (String s : set) { int freq = Collections.frequency(set, s); if (freq > largestFreq) { largestFreq = freq; value = s; } } return value; }
3
private int getNextNode() { int id = -1; int value = Integer.MAX_VALUE; for(int i = 0; i < nodes.size(); i++) { if(!nodes.get(i).isVisited() && nodes.get(i).getValue() < value) { id = i; value = nodes.get(i).getValue(); } } return id; }
3
public AbstractAttributesPanel() { model = new AttributeTableModel(this); setModel(model); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Setup Remove Column TableColumn removeColumn = getColumnModel().getColumn(0); removeColumn.setMinWidth(80); removeColumn.setMaxWidth(80); removeColumn.setResizable(false); AttributesButtonCellEditor editor = new AttributesButtonCellEditor(this); removeColumn.setCellRenderer(editor); removeColumn.setCellEditor(editor); removeColumn.setHeaderRenderer(removeColumnHeaderRenderer); // Setup Editable Column TableColumn editableColumn = getColumnModel().getColumn(1); editableColumn.setMinWidth(OutlineEditableIndicator.TRUE_WIDTH); editableColumn.setMaxWidth(OutlineEditableIndicator.TRUE_WIDTH); editableColumn.setResizable(false); AttributesImageIconCellEditor editor2 = new AttributesImageIconCellEditor(this); editableColumn.setCellEditor(editor2); // Setup Table Header getTableHeader().addMouseListener(model); getTableHeader().setReorderingAllowed(false); }
0
public static int[] getNeighboorsSlow(final int nb) { final int result[] = new int[36]; final int v1 = nb % 10; int root = nb - v1; int cpt = 0; for (int i = 0; i < 10; i++) { final int candidat = root + i; if (candidat == nb) { continue; } result[cpt++] = candidat; } final int v2 = (nb / 10) % 10; root = nb - v2 * 10; for (int i = 0; i < 10; i++) { final int candidat = root + i * 10; if (candidat == nb) { continue; } result[cpt++] = candidat; } final int v3 = (nb / 100) % 10; root = nb - v3 * 100; for (int i = 0; i < 10; i++) { final int candidat = root + i * 100; if (candidat == nb) { continue; } result[cpt++] = candidat; } final int v4 = nb / 1000; root = nb - v4 * 1000; for (int i = 0; i < 10; i++) { final int candidat = root + i * 1000; if (candidat == nb) { continue; } result[cpt++] = candidat; } return result; }
8
public int GetCLCooking(int ItemID) { if (ItemID == 10758) { return 100; } if (ItemID == 10760) { return 100; } if (ItemID == -1) { return 1; } String ItemName = GetItemName(ItemID); if (ItemName.startsWith("Cooking cape")) { return 100; } if (ItemName.startsWith("Cooking hood")) { return 100; } return 1; }
5
@Override public String getDesc() { return "Default"; }
0
public Preferences() throws FileNotFoundException, IOException { initComponents(); /* Load saved preferences if there are any */ File prefFile = new File(System.getProperty("user.home") + "/Documents/AcerX/settingsYM.txt"); if (prefFile.exists()) { BufferedReader pref = new BufferedReader(new FileReader(prefFile)); jTextField1.setText(pref.readLine()); jTextField2.setText(pref.readLine()); } }
1
public String displayToilets( char charForFreeToilet, char charForTrappedToilet, char charForOccupiedToilet, int widthBetween ) { String status = ""; for( int i = 0; i<urinalCount(); i++ ) { switch( urinalVOs.get( i ).getStatus() ) { case FREE_SAVE: status += generateSpaces( widthBetween ) + charForFreeToilet; break; case OCCUPIED: status += generateSpaces( widthBetween ) +charForOccupiedToilet ; break; case TRAPPED: status += generateSpaces( widthBetween ) + charForTrappedToilet; } } return status; }
4
private void dropTable(String sql, StringTokenizer tokenizer) throws Exception { try { // Get table name String tableName = tokenizer.nextToken(); // Check for the semicolon String tok = tokenizer.nextToken(); if (!tok.equals(";")) { throw new NoSuchElementException(); } // Check if there are more tokens if (tokenizer.hasMoreTokens()) { throw new NoSuchElementException(); } // Delete the table if everything is ok boolean dropped = false; for (Table table : tables) { if (table.getTableName().equalsIgnoreCase(tableName)) { table.delete = true; dropped = true; break; } } if (dropped) { out.println("Table " + tableName + " does not exist."); } else { out.println("Table " + tableName + " was dropped."); } } catch (NoSuchElementException ex) { throw new DbmsError("Invalid DROP TABLE statement. '" + sql + "'."); } }
6
@Override public void run() { String insert="insert into TermIDList (term,IDList) values(?,?)"; String IDList=""; int count=0; try { PreparedStatement statement = sqLconnection.conn .prepareStatement(insert); while(rsSet.next()) { String term=rsSet.getString("term"); ResultSet rs=null; String idquery="select distinct indexid from terminvertedindex where term=\""+term+"\" order by indexid asc"; rs=sqLconnection.Query(idquery); while(rs.next()) { int id=rs.getInt("indexid"); IDList+=id+","; } statement.setString(1, term); statement.setString(2, IDList); statement.addBatch(); IDList=""; count++; if(count%100==0) { System.out.println(name+"--"+count); statement.executeBatch(); statement.clearBatch(); IDList=""; } } statement.executeBatch(); } catch (SQLException e) { e.printStackTrace(); } }
4
protected static void modificar(){ //leer hasta encontrar que fila quiero modificar try{ BufferedReader stdin=Files.newBufferedReader(path, java.nio.charset.StandardCharsets.UTF_8); String linea=""; while((linea=stdin.readLine())!=null){ String [] part=linea.split(";"); } }catch(IOException e){ System.out.println("Error en leer el fichero "+e); } }
2
private static int getTableIndex(float[] elem, float threshold) { int tableIndex = 0; if(elem[0] < threshold) { tableIndex |= 1; } if(elem[1] < threshold) { tableIndex |= 2; } if(elem[2] < threshold) { tableIndex |= 4; } if(elem[3] < threshold) { tableIndex |= 8; } if(elem[4] < threshold) { tableIndex |= 16; } if(elem[5] < threshold) { tableIndex |= 32; } if(elem[6] < threshold) { tableIndex |= 64; } if(elem[7] < threshold) { tableIndex |= 128; } return tableIndex; }
8
public double getMaxMemory (){ double maxMemory = 0; for(int i = 0; i<memory.length; i++){ if(memory[i]>maxMemory) maxMemory = memory[i]; } return maxMemory; }
2
public String toString() { return super.toString() + ": \"" + getLabel() + "\""; }
0
public boolean isBlockIndirectlyGettingPowered(int var1, int var2, int var3) { return this.isBlockIndirectlyProvidingPowerTo(var1, var2 - 1, var3, 0) ? true : (this.isBlockIndirectlyProvidingPowerTo(var1, var2 + 1, var3, 1) ? true : (this.isBlockIndirectlyProvidingPowerTo(var1, var2, var3 - 1, 2) ? true : (this.isBlockIndirectlyProvidingPowerTo(var1, var2, var3 + 1, 3) ? true : (this.isBlockIndirectlyProvidingPowerTo(var1 - 1, var2, var3, 4) ? true : this.isBlockIndirectlyProvidingPowerTo(var1 + 1, var2, var3, 5))))); }
5
public boolean insertTicket(Ticket tic) throws SQLException{ Connection con = getConnection(); ArrayList<Ticket> ticket = getTicket(tic); if (ticket.size()!=0) { return false; } con.createStatement().executeUpdate("INSERT INTO ticket("+campos_ticket+") VALUES('" + tic.getPnr()+"','" + tic.getNumFile()+"','" + tic.getTicket()+"','" + tic.getOldTicket()+"','" + tic.getCodEmd()+"','" + tic.getFechaEmisionSql()+"','" + tic.getFechaAnulacionSql()+"','" + tic.getFechaReemisionSql()+"','" + tic.getPosicion()+"','" + tic.getNombrePasajero()+"','" + tic.getTipoPasajero()+"','" + tic.getcLineaAerea()+"','" + tic.getRuta()+"','" + tic.getMoneda()+"','" + tic.getValorNeto()+"','" + tic.getValorTasas()+"','" + tic.getValorFinal()+"','" + tic.getComision()+"','" + tic.getfPago()+"','" + tic.getTipo()+"','" + tic.getEstado()+"','" + "0" +"','" + tic.getGds() + "'" +")"); return true; }
1
String ChangeEmissionFilter(int Current_Item){ int Move_Item=Current_Item;//-Global.Emi_Previous_Item; //if (Move_Item<0) {Move_Item=Move_Item+6;} String CI=Integer.toString(Current_Item); //Global.Emi_Previous_Item=Current_Item; try{ if (Move_Item==0) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","14"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } if (Move_Item==1) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","32"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } if (Move_Item==2) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","18"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } if (Move_Item==3) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","20"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } if (Move_Item==4) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","22"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } if (Move_Item==5) { core_.setProperty(ShutterDev_FW_,"OnOff","0"); core_.setProperty(StateDev_FW_,"State","24"); core_.setProperty(ShutterDev_FW_,"OnOff","1"); } return CI; } catch (Exception ex) { Logger.getLogger(FilterControl.class.getName()).log(Level.SEVERE, null, ex); return("Error in Excitation Filter"+Integer.toString(Move_Item)); } }
7
void run(){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(), W = sc.nextInt(), K = 0; int[] w = new int[15], f = new int[15], s = new int[n+1]; for(int i=1;i<=n;i++){ int k = sc.nextInt(); while(k--!=0){ w[K] = sc.nextInt(); s[i]+=1<<K; f[K++] = i; } } int[] sum = new int[1<<K]; boolean[] valid = new boolean[1<<K]; for(int S=0;S<1<<K;S++){ for(int j=0;j<K;j++)if(((S>>j)&1)>0){ sum[S]+=w[j]; } valid[S] = sum[S]<=W; } int[] min = new int[1<<K]; Arrays.fill(min, K); min[0] = 0; for(int S=1;S<1<<K;S++){ int res = K, sub = S; do{ if(valid[sub]){ res = Math.min(res, min[S-sub]+1); } sub = (sub-1)&S; }while(sub!=S); min[S] = res; } int res = f[K-1]-m; for(int i=f[K-1];i>1;i--){ res+=2*(min[s[i]]-1)+1; s[i-1]|=s[i]; } System.out.println(Math.max(res, 0)); }
9
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int page=1; if(request.getParameter("page")!=null){ page=Integer.parseInt(request.getParameter("page")); } request.setAttribute("page", page); String name=""; if( request.getParameter("name")!=null){ name=request.getParameter("name"); } String pageName = (String) request.getSession() .getAttribute("pageName"); if(pageName==null) pageName=""; ArrayList<Dish> allApprovedDishes =(ArrayList<Dish>) request.getAttribute("alldishes"); ArrayList<Dish> allApprovedDishesFromSession =(ArrayList<Dish>) request.getSession().getAttribute("alldishes"); if((allApprovedDishes == null && allApprovedDishesFromSession==null && !pageName.equals("Found"))||page==1 ) { allApprovedDishes = (ArrayList<Dish>) Dish.getDishesByName(name);; }else if(allApprovedDishes == null && pageName.equals("Found")){ allApprovedDishes=allApprovedDishesFromSession; } request.getSession().setAttribute("alldishes",null); request.getSession().setAttribute("pageName",null); request.setAttribute("show", "Found"); request.setAttribute("alldishes", allApprovedDishes); RequestDispatcher dispatch = request.getRequestDispatcher("AllRecipes.jsp"); dispatch.forward(request, response); }
9
InternalTestLinkId(final Long id) { super(id); }
0
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int size = Integer.parseInt(line); for (int i = 0; i < size; i++) { Stack<Integer> d = new Stack<Integer>(); char[] a = in.readLine().toCharArray(); long ans = 0; for (int j = 0; j < a.length; j++) if (a[j] == '\\') d.push(j); else if (a[j] == '/' && !d.isEmpty()) ans += j - d.pop(); out.append(ans + "\n"); } } System.out.print(out); }
7
public int compareTo( Object obj ) { if( obj == null ) { return( 1 ); } else if( obj instanceof GenKbTagByNameIdxKey ) { GenKbTagByNameIdxKey rhs = (GenKbTagByNameIdxKey)obj; if( getRequiredTenantId() < rhs.getRequiredTenantId() ) { return( -1 ); } else if( getRequiredTenantId() > rhs.getRequiredTenantId() ) { return( 1 ); } { int cmp = getRequiredName().compareTo( rhs.getRequiredName() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else if( obj instanceof GenKbTagBuff ) { GenKbTagBuff rhs = (GenKbTagBuff)obj; if( getRequiredTenantId() < rhs.getRequiredTenantId() ) { return( -1 ); } else if( getRequiredTenantId() > rhs.getRequiredTenantId() ) { return( 1 ); } { int cmp = getRequiredName().compareTo( rhs.getRequiredName() ); if( cmp != 0 ) { return( cmp ); } } return( 0 ); } else { throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(), "compareTo", "obj", obj, null ); } }
9
public static void saveAttunment(String player, String bWorld, double x, double y, double z, float yaw, float pitch) throws SQLException { String table = Config.sqlPrefix + "Attunements_v2"; Connection con = getConnection(); PreparedStatement statement = null; int success = 0; String query = "UPDATE `" + table + "` SET `x` = ?, `y` = ?, `z` = ?, `yaw` = ?, `pitch` = ? WHERE `player` = ? AND `world` = ?"; statement = con.prepareStatement(query); statement.setDouble(1, x); statement.setDouble(2, y); statement.setDouble(3, z); statement.setFloat(4, yaw); statement.setFloat(5, pitch); statement.setString(6, player); statement.setString(7, bWorld); success = statement.executeUpdate(); statement.close(); if (success > 0) { return; } if (success == 0) { query = "insert into `" + table + "` (player, world, x,y,z,yaw, pitch) values (?, ?, ?, ?,?,?,?)"; statement = con.prepareStatement(query); statement.setString(1, player); statement.setString(2, bWorld); statement.setDouble(3, x); statement.setDouble(4, y); statement.setDouble(5, z); statement.setFloat(6, yaw); statement.setFloat(7, pitch); success = statement.executeUpdate(); statement.close(); con.close(); } con.close(); }
2
protected void computeRect(Raster[] sources, WritableRaster dest, Rectangle destRect) { int formatTag = MediaLibAccessor.findCompatibleTag(sources,dest); MediaLibAccessor srcAccessor1 = new MediaLibAccessor(sources[0], destRect,formatTag); MediaLibAccessor srcAccessor2 = new MediaLibAccessor(sources[1], destRect,formatTag); MediaLibAccessor dstAccessor = new MediaLibAccessor(dest, destRect, formatTag); mediaLibImage[] srcML1 = srcAccessor1.getMediaLibImages(); mediaLibImage[] srcML2 = srcAccessor2.getMediaLibImages(); mediaLibImage[] dstML = dstAccessor.getMediaLibImages(); switch (dstAccessor.getDataType()) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_INT: for (int i = 0 ; i < dstML.length; i++) { Image.Add(dstML[i], srcML1[i], srcML2[i]); } break; case DataBuffer.TYPE_FLOAT: case DataBuffer.TYPE_DOUBLE: for (int i = 0 ; i < dstML.length; i++) { Image.Add_Fp(dstML[i], srcML1[i], srcML2[i]); } break; default: String className = this.getClass().getName(); throw new RuntimeException(className + JaiI18N.getString("Generic2")); } if (dstAccessor.isDataCopy()) { dstAccessor.clampDataArrays(); dstAccessor.copyDataToRaster(); } }
9
public void renderPlayer(EntityPlayer par1EntityPlayer, double par2, double par4, double par6, float par8, float par9) { ItemStack itemstack = par1EntityPlayer.inventory.getCurrentItem(); modelArmorChestplate.heldItemRight = modelArmor.heldItemRight = modelBipedMain.heldItemRight = itemstack == null ? 0 : 1; if (itemstack != null && par1EntityPlayer.getItemInUseCount() > 0) { EnumAction enumaction = itemstack.getItemUseAction(); if (enumaction == EnumAction.block) { modelArmorChestplate.heldItemRight = modelArmor.heldItemRight = modelBipedMain.heldItemRight = 3; } else if (enumaction == EnumAction.bow) { modelArmorChestplate.aimedBow = modelArmor.aimedBow = modelBipedMain.aimedBow = true; } } modelArmorChestplate.isSneak = modelArmor.isSneak = modelBipedMain.isSneak = par1EntityPlayer.isSneaking(); double d = par4 - (double)par1EntityPlayer.yOffset; if (par1EntityPlayer.isSneaking() && !(par1EntityPlayer instanceof EntityPlayerSP)) { d -= 0.125D; } super.doRenderLiving(par1EntityPlayer, par2, d, par6, par8, par9); modelArmorChestplate.aimedBow = modelArmor.aimedBow = modelBipedMain.aimedBow = false; modelArmorChestplate.isSneak = modelArmor.isSneak = modelBipedMain.isSneak = false; modelArmorChestplate.heldItemRight = modelArmor.heldItemRight = modelBipedMain.heldItemRight = 0; }
7
private void handleEnterEvent(MouseEvent event) { gotEnterAfterExit = true; ArrayList exitables = new ArrayList(enteredComponents); ArrayList enterables = new ArrayList(); Component c = (Component) event.getSource(); while (c != null) { if (hoverableComponents.contains(c)) { exitables.remove(c); enterables.add(c); } c = c.getParent(); } if (enterables.size() > 0) { Object obj[] = enterables.toArray(); for (int i = obj.length - 1; i >= 0; i--) { if (!((Hoverable) obj[i]).acceptHover(enterables)) { enterables.remove(obj[i]); exitables.add(obj[i]); } } } for (int i = exitables.size() - 1; i >= 0; i--) { dispatchExit((Hoverable) exitables.get(i)); } for (int i = enterables.size() - 1; i >= 0; i--) { dispatchEnter((Hoverable) enterables.get(i)); } }
7
public boolean equals(User user){ return name.equals(user.getName()) && password.equals(user.getPassword()) && interest.equals(user.getInterest()) && followed.equals(user.getFollowed()) && followers.equals(user.getFollowers()); }
4
@Override public void remoteSignal(String from, String method, String url) { // TODO Auto-generated method stub String[] urlSplits = url.split(","); String sourceUrl = urlSplits[0]; String[] sourceUrlSplits = sourceUrl.split("/"); String type = sourceUrlSplits[sourceUrlSplits.length - 2]; String id = sourceUrlSplits[sourceUrlSplits.length - 1]; if(method.equals("DELETE")){ ArrayList<FsNode> list = types.get(type); FsNode nodeToDelete = null; for(Iterator<FsNode> i = list.iterator(); i.hasNext();){ FsNode node = i.next(); if(node.getId().equals(id)){ nodeToDelete = node; } } list.remove(nodeToDelete); updateObservers("DELETE", type, id); }else if(method.equals("PUT")){ FsNode newNode = Fs.getNode(sourceUrl); ArrayList<FsNode> list = types.get(type); FsNode nodeToDelete = null; for(Iterator<FsNode> i = list.iterator(); i.hasNext();){ FsNode node = i.next(); if(node.getId().equals(newNode.getId())){ nodeToDelete = node; } } list.remove(nodeToDelete); list.add(newNode); Collections.sort(list); updateObservers("PUT", type, id); } System.out.println("FsTimeLine.remoteSignal(from: " + from + ", method: " + method + ", url: " + url); }
6
public void loadChannelHooks() { for(Map.Entry<String, Channel> entry : channels.entrySet()) { if(!(config.contains("channels." + entry.getKey() + ".linkedChannels"))) { continue; } List<String> links = config.getStringList("channels." + entry.getKey() + ".linkedChannels"); for(String link : links) { if(link.contains(":")) { final String[] split = link.split(":"); // Other world WorldConfig otherWorld; try { otherWorld = plugin.getModuleForClass( ConfigHandler.class).getWorldConfig(split[0]); } catch(IllegalArgumentException e) { plugin.getLogger() .log(Level.WARNING, e.getMessage(), e); continue; } if(otherWorld != null) { final Channel otherChannel = otherWorld .getChannel(split[1]); if(otherChannel != null) { entry.getValue().addChannel(otherChannel); } else { plugin.getLogger().warning( "Link channel '" + split[1] + "' of other world '" + split[0] + "' not found for channel '" + entry.getKey() + "' of world '" + worldName + "'"); } } else { plugin.getLogger().warning( "Other world '" + split[0] + "' not found for channel '" + entry.getKey() + "' of world '" + worldName + "'"); } } else if(channels.containsKey(link)) { // local world channel to hook to entry.getValue().addChannel(channels.get(link)); } else { // Invalid entry plugin.getLogger().warning( "Invalid link channel entry '" + link + "' for channel '" + entry.getKey() + "' of world '" + worldName + "'"); } } } }
8
public void traverse(Node child,DefaultMutableTreeNode parent){ int type = child.getNodeType(); if(type == Node.ELEMENT_NODE){ Element elm = (Element)child; DefaultMutableTreeNode node = new DefaultMutableTreeNode("<" + elm.getTagName() + ">"); parent.add(node); if(elm.hasChildNodes()){ NodeList list = elm.getChildNodes(); for(int i=0; i<list.getLength(); i++){ traverse(list.item(i),node); } } } else if(type == Node.TEXT_NODE){ Text t = (Text)child; String textContent = t.getTextContent().trim(); if(!textContent.equals("")){ DefaultMutableTreeNode node = new DefaultMutableTreeNode(textContent); parent.add(node); } } }
5
public static <T extends DC> Set<DC> dMax(Set<Pair<T,T>> phiMax) { if(phiMax!=null) { if(phiMax.getNext()!=null) { return new Set(phiMax.getFst().fst().delta(phiMax.getFst().snd()).diff(),dMax(phiMax.getNext())); } else { return new Set(phiMax.getFst().fst().delta(phiMax.getFst().snd()).diff(),null); } } else { return null;} }
2
private void copyAndClose(InputStream inputStream, FileOutputStream outputStream) throws IOException { byte[] buffer = new byte[2048]; int read; try { while((read=inputStream.read(buffer))>0) { outputStream.write(buffer, 0, read); } } finally { closeQuietly(inputStream); closeQuietly(outputStream); } }
1
public cellPicker(){ cellpick = new JComboBox(Cells); MBOTPick = new JComboBox(MBOTCells); jack = new JLabel("Born"); jill = new JLabel("Survives"); rulab = new JLabel(); //labels for wolfram rules wlab[0] = new JLabel("111"); wlab[1] = new JLabel("110"); wlab[2] = new JLabel("101"); wlab[3] = new JLabel("100"); wlab[4] = new JLabel("011"); wlab[5] = new JLabel("010"); wlab[6] = new JLabel("001"); wlab[7] = new JLabel("000"); wrlab = new JLabel("Wolfram Rule: 0"); //Wolfram directions orlabel = new JLabel("Direction:"); wdirs[0] = new JRadioButton("|"); wdirs[1] = new JRadioButton("/"); wdirs[2] = new JRadioButton("--"); wdirs[3] = new JRadioButton("\\"); ButtonGroup orients = new ButtonGroup(); orients.add(wdirs[0]); orients.add(wdirs[1]); orients.add(wdirs[2]); orients.add(wdirs[3]);wdirs[0].setSelected(true); // 8 directions dirlabel = new JLabel("Direction:"); dirs[0] = new JRadioButton("Up"); dirs[1] = new JRadioButton("U-R"); dirs[2] = new JRadioButton("R"); dirs[3] = new JRadioButton("L-R"); dirs[4] = new JRadioButton("Down"); dirs[5] = new JRadioButton("L-L"); dirs[6] = new JRadioButton("L"); dirs[7] = new JRadioButton("U-L"); ButtonGroup directs = new ButtonGroup(); directs.add(dirs[0]);directs.add(dirs[1]);directs.add(dirs[2]);directs.add(dirs[3]);directs.add(dirs[4]); directs.add(dirs[5]);directs.add(dirs[6]);directs.add(dirs[7]); dirs[0].setSelected(true); // age and fade options opts[0] = new Checkbox("Ages"); opts[1] = new Checkbox("Fades"); fadeslider = new JSlider(1,1024); fadelabel = new JLabel(); //maturity option matslider = new JSlider(1,512); matlabel = new JLabel(); // born opts[2] = new Checkbox("0"); opts[3] = new Checkbox("1"); opts[4] = new Checkbox("2"); opts[5] = new Checkbox("3"); opts[6] = new Checkbox("4"); opts[7] = new Checkbox("5"); opts[8] = new Checkbox("6"); opts[9] = new Checkbox("7"); opts[10] = new Checkbox("8"); // survives opts[11] = new Checkbox("0"); opts[12] = new Checkbox("1"); opts[13] = new Checkbox("2"); opts[14] = new Checkbox("3"); opts[15] = new Checkbox("4"); opts[16] = new Checkbox("5"); opts[17] = new Checkbox("6"); opts[18] = new Checkbox("7"); opts[19] = new Checkbox("8"); //Wolfram rules opts[20] = new Checkbox(); opts[21] = new Checkbox(); opts[22] = new Checkbox(); opts[23] = new Checkbox(); opts[24] = new Checkbox(); opts[25] = new Checkbox(); opts[26] = new Checkbox(); opts[27] = new Checkbox(); // Mirror opts[28] = new Checkbox("Mirror Cell"); mirbutt = new JButton("Set Mirror"); refsetbutt = new JButton("Set Reference"); //Any & All opts[29] = new Checkbox("Any"); opts[30] = new Checkbox("All"); //Expansion Factor xfslider = new JSlider(1,8); xfind = new JLabel(""); xflabel = new JLabel("Expansion Factor"); //Input mode inmodlabel = new JLabel("Input Mode:"); inm[0] = new JRadioButton("Void"); inm[1] = new JRadioButton("Binary"); inm[2] = new JRadioButton("Integer"); inpmod = new ButtonGroup(); inpmod.add(inm[0]); inpmod.add(inm[1]); inpmod.add(inm[2]); inm[1].setSelected(true); GroupLayout cpLayout = new GroupLayout(this); cpLayout.setAutoCreateGaps(false); cpLayout.setAutoCreateContainerGaps(false); cpLayout.setHorizontalGroup( cpLayout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(cellpick) .addComponent(MBOTPick) // ages/fades .addGroup(cpLayout.createSequentialGroup() .addComponent(opts[0]) .addComponent(opts[1]) .addComponent(fadeslider) .addComponent(fadelabel)) //maturity .addGroup(cpLayout.createSequentialGroup() .addComponent(matslider) .addComponent(matlabel)) // MBOT rule .addGroup(cpLayout.createSequentialGroup() .addComponent(rulab)) //MBOT born .addGroup(cpLayout.createSequentialGroup() .addComponent(jack) .addComponent(opts[2]) .addComponent(opts[3]) .addComponent(opts[4]) .addComponent(opts[5]) .addComponent(opts[6]) .addComponent(opts[7]) .addComponent(opts[8]) .addComponent(opts[9]) .addComponent(opts[10])) //MBOT survives .addGroup(cpLayout.createSequentialGroup() .addComponent(jill) .addComponent(opts[11]) .addComponent(opts[12]) .addComponent(opts[13]) .addComponent(opts[14]) .addComponent(opts[15]) .addComponent(opts[16]) .addComponent(opts[17]) .addComponent(opts[18]) .addComponent(opts[19])) // Wolfram rule number .addGroup(cpLayout.createParallelGroup() .addComponent(wrlab)) // Wolfram rules .addGroup(cpLayout.createSequentialGroup() .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[0]) .addComponent(opts[20])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[1]) .addComponent(opts[21])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[2]) .addComponent(opts[22])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[3]) .addComponent(opts[23])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[4]) .addComponent(opts[24])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[5]) .addComponent(opts[25])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[6]) .addComponent(opts[26])) .addGroup(cpLayout.createParallelGroup() .addComponent(wlab[7]) .addComponent(opts[27])) ) // 4 orientations .addGroup(cpLayout.createSequentialGroup() .addComponent(orlabel) .addComponent(wdirs[0]) .addComponent(wdirs[1]) .addComponent(wdirs[2]) .addComponent(wdirs[3]) .addComponent(opts[29]) .addComponent(opts[30])) // 8 directions .addGroup(cpLayout.createSequentialGroup() .addComponent(dirlabel) .addComponent(dirs[0]) .addComponent(dirs[1]) .addComponent(dirs[2]) .addComponent(dirs[3])) .addGroup(cpLayout.createSequentialGroup() .addComponent(dirs[4]) .addComponent(dirs[5]) .addComponent(dirs[6]) .addComponent(dirs[7])) // Mirror .addGroup(cpLayout.createSequentialGroup() .addComponent(opts[28]) .addComponent(mirbutt) .addComponent(refsetbutt)) //expansion Factor .addGroup(cpLayout.createSequentialGroup() .addComponent(xflabel) .addComponent(xfslider) .addComponent(xfind)) //Input Mode .addComponent(inmodlabel) .addGroup(cpLayout.createSequentialGroup() .addComponent(inm[0]) .addComponent(inm[1]) .addComponent(inm[2])) ); cpLayout.setVerticalGroup( cpLayout.createSequentialGroup() .addComponent(cellpick) .addComponent(MBOTPick) // ages/ fades .addGroup(cpLayout.createParallelGroup() .addComponent(opts[0]) .addComponent(opts[1]) .addComponent(fadeslider) .addComponent(fadelabel)) // maturity .addGroup(cpLayout.createParallelGroup() .addComponent(matslider) .addComponent(matlabel)) //MBOT rule .addGroup(cpLayout.createParallelGroup() .addComponent(rulab)) //MBOT born .addGroup(cpLayout.createParallelGroup() .addComponent(jack) .addComponent(opts[2]) .addComponent(opts[3]) .addComponent(opts[4]) .addComponent(opts[5]) .addComponent(opts[6]) .addComponent(opts[7]) .addComponent(opts[8]) .addComponent(opts[9]) .addComponent(opts[10])) // MBOT survives .addGroup(cpLayout.createParallelGroup() .addComponent(jill) .addComponent(opts[11]) .addComponent(opts[12]) .addComponent(opts[13]) .addComponent(opts[14]) .addComponent(opts[15]) .addComponent(opts[16]) .addComponent(opts[17]) .addComponent(opts[18]) .addComponent(opts[19])) //Wolfram rule number .addGroup(cpLayout.createSequentialGroup() .addComponent(wrlab)) // Wolfram rules .addGroup(cpLayout.createParallelGroup() .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[0]) .addComponent(opts[20])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[1]) .addComponent(opts[21])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[2]) .addComponent(opts[22])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[3]) .addComponent(opts[23])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[4]) .addComponent(opts[24])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[5]) .addComponent(opts[25])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[6]) .addComponent(opts[26])) .addGroup(cpLayout.createSequentialGroup() .addComponent(wlab[7]) .addComponent(opts[27])) ) // 4 orientations .addGroup(cpLayout.createParallelGroup() .addComponent(orlabel) .addComponent(wdirs[0]) .addComponent(wdirs[1]) .addComponent(wdirs[2]) .addComponent(wdirs[3]) .addComponent(opts[29]) .addComponent(opts[30])) //8 directions .addGroup(cpLayout.createParallelGroup() .addComponent(dirlabel) .addComponent(dirs[0]) .addComponent(dirs[1]) .addComponent(dirs[2]) .addComponent(dirs[3])) .addGroup(cpLayout.createParallelGroup() .addComponent(dirs[4]) .addComponent(dirs[5]) .addComponent(dirs[6]) .addComponent(dirs[7])) //mirror .addGroup(cpLayout.createParallelGroup() .addComponent(opts[28]) .addComponent(mirbutt) .addComponent(refsetbutt)) //Expansion Factor .addGroup(cpLayout.createParallelGroup() .addComponent(xflabel) .addComponent(xfslider) .addComponent(xfind)) //Input Mode .addComponent(inmodlabel) .addGroup(cpLayout.createParallelGroup() .addComponent(inm[0]) .addComponent(inm[1]) .addComponent(inm[2])) ); setLayout(cpLayout); setPreferredSize(new Dimension(325,200)); cellpick.setMaximumSize(new Dimension(250, 10)); MBOTPick.setMaximumSize(new Dimension(250, 10)); //init wolfram labels for (int aa = 0; aa < wlab.length; aa++){ wlab[aa].setVisible(false);} wrlab.setVisible(false); //Wolfram direction for(int ac = 0; ac < wdirs.length; ac++){ wdirs[ac].setVisible(false); wdirs[ac].addActionListener(this);} orlabel.setVisible(false); // 8 directions for(int ad = 0; ad < dirs.length; ad++){ dirs[ad].setVisible(false); dirs[ad].addActionListener(this);} dirlabel.setVisible(false); //init opts for (int ab = 0; ab < opts.length; ab++){ opts[ab].setMaximumSize(new Dimension(10,10));opts[ab].setVisible(false); opts[ab].addItemListener(this);} // MBOT stuff jack.setVisible(false); jill.setVisible(false); rulab.setVisible(false); //init fade components fadeslider.setVisible(false); fadeslider.setEnabled(false);fadeslider.setValue(256); fadeslider.addChangeListener(this); fadeslider.setMaximumSize(new Dimension(100,15)); fadelabel.setVisible(false);fadelabel.setText(Integer.toString(fadeslider.getValue())); //set maturity components matslider.setVisible(false); matslider.setEnabled(false); matslider.setValue(1); matslider.addChangeListener(this); matslider.setMaximumSize(new Dimension(100,15)); matlabel.setVisible(false); matlabel.setText("Maturity: "+Integer.toString(matslider.getValue())); //init mirror mirbutt.setVisible(false); mirbutt.setEnabled(false); mirbutt.addActionListener(this); refsetbutt.setVisible(false); refsetbutt.setEnabled(false); refsetbutt.addActionListener(this); //Expansion Factor xflabel.setVisible(false); xfslider.setVisible(false); xfslider.setEnabled(false);xfslider.setValue(1); xfslider.addChangeListener(this);xfslider.setMaximumSize(new Dimension(100,15)); xfind.setText("1"); xfind.setVisible(false); //Input Mode inmodlabel.setVisible(false); inm[0].setVisible(false); inm[0].addActionListener(this);inm[1].setVisible(false); inm[1].addActionListener(this); inm[2].setVisible(false); inm[2].addActionListener(this); //init MBOT picker MBOTPick.setVisible(false); if(ct == 2 || ct == 12){MBOTPick.setVisible(true); } else{MBOTPick.setVisible(false); } cellpick.addActionListener(this); MBOTPick.addActionListener(this); }
6
public static OSType getOperatingSystemType() { if (detectedOS == null) { String OS = System.getProperty("os.name", "generic").toLowerCase(); if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) { detectedOS = OSType.MacOS; } else if (OS.indexOf("win") >= 0) { detectedOS = OSType.Windows; } else if (OS.indexOf("nux") >= 0) { detectedOS = OSType.Linux; } else { detectedOS = OSType.Other; } } return detectedOS; }
5
public void addAll(IntArrayBag addend) { ensureCapacity(manyItems + addend.manyItems); System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems); manyItems += addend.manyItems; }
0
public DataBase getGameData(TreeItem item){ if(item == null || item == rootItem){ return null; } DatabaseTreeItem dataItem = (DatabaseTreeItem) item; DataBase data = dataItem.gameData; if(data == null){ File file = new File(ProjectMgr.getDataGamePath(), "Map" + dataItem.editorData.getIdName() + "." + AppMgr.getExtension("data file")); data = (DataBase) DataMgr.load(file.getAbsolutePath()); if(data == null){ data = new DataMap(0, "" , 16, 16); data.id = dataItem.editorData.id; data.name = dataItem.editorData.name; dataItem.gameData = data; SaveMgr.requestSaveEnabled(); } } return data; }
4
static boolean isPiece(int i, int j) { return isWhitePiece(i, j) || isBlackPiece(i, j); }
1
public final CompilationUnitContext compilationUnit() throws RecognitionException { CompilationUnitContext _localctx = new CompilationUnitContext(_ctx, getState()); enterRule(_localctx, 0, RULE_compilationUnit); int _la; try { enterOuterAlt(_localctx, 1); { setState(195); switch ( getInterpreter().adaptivePredict(_input,0,_ctx) ) { case 1: { setState(194); packageDeclaration(); } break; } setState(200); _errHandler.sync(this); _la = _input.LA(1); while (_la==68) { { { setState(197); importDeclaration(); } } setState(202); _errHandler.sync(this); _la = _input.LA(1); } setState(206); _errHandler.sync(this); _la = _input.LA(1); while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << 1) | (1L << 11) | (1L << 16) | (1L << 24) | (1L << 30) | (1L << 33) | (1L << 39) | (1L << 41) | (1L << 50) | (1L << 58) | (1L << 62))) != 0) || ((((_la - 66)) & ~0x3f) == 0 && ((1L << (_la - 66)) & ((1L << (66 - 66)) | (1L << (73 - 66)) | (1L << (76 - 66)) | (1L << (77 - 66)) | (1L << (ENUM - 66)))) != 0)) { { { setState(203); typeDeclaration(); } } setState(208); _errHandler.sync(this); _la = _input.LA(1); } setState(209); match(EOF); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; }
7
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewFrame().setVisible(true); } }); }
6
static void input(double[][] matrix){ for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ matrix[i][j] = scan.nextDouble(); } } }
2
private void printAll(TreeNode root, TreeNode parent, Node parentNode, int i) { Node p; int parentPosition = getRectNextLeft(i); if (root != null && parent == null) { p = makeNode(String.valueOf(root.key), new Point(parentPosition, getRectNextTop(0)), Node.COLOR_PARENT, i); } else { p = parentNode; } if (root == null) { p = makeNode("", new Point(parentPosition, getRectNextTop(0)), Node.COLOR_PARENT, i); } if (root != null) { recursivePrint(root.left, parentPosition, null, p, i); recursivePrint(root.right, parentPosition, null, p, i); } }
4
public static AttackType getAttackType(WeaponType type) { switch (type) { case mel_sword: return AttackType.SLASH; case mel_hammer: return AttackType.BASH; case rng_bow: return AttackType.PIERCE; } return AttackType.SLASH; }
3
public void action() { BoundBox r; r = new BoundBox( entity.boundingBox.x, entity.boundingBox.y, entity.sprite.getWidth(), entity.sprite.getHeight()); entity.setBounds(r); entity.location = new Point2D.Double(r.getCenterX(), r.getCenterY()); for (AI ai : taskList) { if (ai.execute()) { break; } } if (!entity.isPlayer) { if (entity.direction > 0) { entity.setSprite(ImageManipulator.selectFromSheet( entity.spriteSheet, entity.spritenumber, entity.spriteSize.x, entity.spriteSize.y)); } else if (entity.direction < 0) { entity.setSprite(ImageManipulator.flipImage( ImageManipulator.selectFromSheet( entity.spriteSheet, entity.spritenumber, entity.spriteSize.x, entity.spriteSize.y))); } } }
5
@Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_UP: Game.VK_UP = true; break; case KeyEvent.VK_DOWN: Game.VK_DOWN = true; break; case KeyEvent.VK_LEFT: Game.VK_LEFT = true; break; case KeyEvent.VK_RIGHT: Game.VK_RIGHT = true; break; } }
4