private void pvp(final Player p, final Player d) { if (pvp.containsKey(p)) if (pvp.get(p).isSync()) pvp.get(p).cancel(); pvp.put( p, new BukkitRunnable() { @Override public void run() { if (pvp.containsKey(p)) pvp.remove(p); } }.runTaskLater(Main.getInstance(), 8 * 20L)); if (pvp.containsKey(d)) if (pvp.get(d).isSync()) pvp.get(d).cancel(); pvp.put( d, new BukkitRunnable() { @Override public void run() { if (pvp.containsKey(d)) pvp.remove(d); } }.runTaskLater(Main.getInstance(), 8 * 20L)); }
public static void main(String[] args) { Scanner in = new Scanner(System.in); int a, b, c; int L1, R1, C1; while (in.hasNext()) { L1 = in.nextInt(); R1 = in.nextInt(); C1 = in.nextInt(); if (L1 == 0 && R1 == 0 && C1 == 0) break; a = b = c = 0; char map1[][][] = new char[L1][R1][C1]; for (int i = 0; i < L1; i++) for (int j = 0; j < R1; j++) { map1[i][j] = in.next().toCharArray(); for (int k = 0; k < C1; k++) { if (map1[i][j][k] == 'S') { a = i; b = j; c = k; } } } Main m = new Main(map1, L1, R1, C1); int sum = m.bfs(a, b, c); if (sum != -1) System.out.printf("Escaped in %d minute(s).\n", sum); else System.out.printf("Trapped!\n"); } }
public MuffinFrame(String title, int min_width, int min_height) { super(title); minWidth = min_width; minHeight = min_height; if (!Main.getOptions().getBoolean("muffin.noWindow")) { setFont(Main.getOptions().getFont("muffin.font")); setIcon(); configColors(this); } addComponentListener( new ComponentAdapter() { public void componentResized(ComponentEvent e) { final int width = Math.max(e.getComponent().getWidth(), minWidth); final int height = Math.max(e.getComponent().getHeight(), minHeight); if (e.getComponent().getWidth() != width || e.getComponent().getHeight() != height) setSize(width, height); } }); frames.addElement(this); }
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, KeyStoreException, KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException { Main main = new Main(new MyDb(args[0], args[1], args[2]), Integer.valueOf(args[3])); main.main1(); }
public static void main(String[] args) { if (args.length == 0) { gui = new Gui(); gui.setVisible(true); } else if (args.length == 3 || args.length == 4) { Main.setBlogName(args[0]); Main.load(); if (args.length == 3) { int start, limit; try { start = Integer.parseInt(args[1]); limit = Integer.parseInt(args[2]); } catch (Exception e) { Main.status("usage: Main <blogname> <start_page> <end_page> -hires"); Main.status("start_page and end_page must be integers >= 1"); return; } Main.run(start, limit); Main.save(); } else if (args.length == 4 && args[3].equals("-hires")) { Main.downloadHiRes(); Main.save(); } else { Main.status("usage: Main <blogname> <start_page> <end_page> -hires"); } } else { Main.status("usage: Main <blogname> <start_page> <end_page> -hires"); } }
/** * Adds valid aliases to one of per-RawOffset table and removes invalid aliases from aliases List. * Aliases referring to excluded zones are not added to a per-RawOffset table. */ void resolve() { int index = rawOffsetsIndexTable.size(); List<String> toBeRemoved = new ArrayList<String>(); for (String key : aliases.keySet()) { boolean validname = false; for (int j = 0; j < index; j++) { Set<String> perRO = rawOffsetsIndexTable.get(j); boolean isExcluded = (excludeList == null) ? false : excludeList.contains(key); if ((perRO.contains(aliases.get(key)) || isExcluded) && Zone.isTargetZone(key)) { validname = true; if (!isExcluded) { perRO.add(key); Main.info("Alias <" + key + "> added to the list."); } break; } } if (!validname) { Main.info("Alias <" + key + "> removed from the list."); toBeRemoved.add(key); } } // Remove zones, if any, from the list. for (String key : toBeRemoved) { aliases.remove(key); } }
@Test public void testers() { Main test = new Main(); assertEquals("10 x 0 = 0", 0, test.multiply(10, 0)); assertEquals("20 x 2 = 40", 40, test.multiply(20, 2)); }
public synchronized boolean init() { if (fileName == null) { try { String tmpDir = ""; int mcoreID; try { mcoreID = Main.getCurCore().getMCoreID(); fileName = "fileBuf" + mcoreID + "thlog"; tmpDir = Main.getCurCore().getConfig().getTempStorage(); } catch (Exception e) { // it is for debugging purpose to run tests in the harness // VM this mode should be prohibited in the future fileName = "fileBuf"; tmpDir = System.getProperty("user.dir"); } finally { logFile = File.createTempFile(fileName, null, new File(tmpDir)); logFile.deleteOnExit(); logH = new FileHandler(logFile.getAbsolutePath()); logH.setFormatter(new TestLogFormatter()); in = new FileInputStream(logFile); } } catch (Exception e) { e.printStackTrace(); return false; } setUseParentHandlers(false); addHandler(logH); setLevel(Level.INFO); } return true; }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.comment); final EditText edt = (EditText) findViewById(R.id.editText1); TextView t = (TextView) findViewById(R.id.textView1); Button b = (Button) findViewById(R.id.button1); Bundle extra = getIntent().getExtras(); t.setText((extra.getString("user") + ":\n" + extra.getString("update"))); ImageView iv = (ImageView) findViewById(R.id.imageView1); final Main imageGetter = new Main(); Bitmap bmp = imageGetter.getImageFromWeb(imageGetter.webRoot + extra.getString("pic")); iv.setImageBitmap(bmp); iv.setAdjustViewBounds(true); iv.setMaxHeight(120); iv.setMaxWidth(120); b.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), edt.getText(), Toast.LENGTH_LONG).show(); } }); }
LatitudeAndLongitude(String s) { try { if (!s.startsWith("+") && !s.startsWith("-")) { Main.warning("Wrong latitude&longitude data: " + s); return; } int index; if (((index = s.lastIndexOf("+")) <= 0) && ((index = s.lastIndexOf("-")) <= 0)) { Main.warning("Wrong latitude&longitude data: " + s); return; } latitude = ((s.startsWith("+")) ? 1 : -1) * Float.parseFloat(s.substring(1, index)); if (index > 5) { latitude /= 10000; } else { latitude /= 100; } longitude = ((s.charAt(index) == '+') ? 1 : -1) * Float.parseFloat(s.substring(index + 1)); if ((s.length() - index) > 6) { longitude /= 10000; } else { longitude /= 100; } } catch (Exception e) { Main.warning("LatitudeAndLongitude() Parse error: " + s); } }
/** * The start method is called when the WrapperManager is signaled by the native wrapper code that * it can start its application. This method call is expected to return, so a new thread should be * launched if necessary. * * @param args List of arguments used to initialize the application. * @return Any error code if the application should exit on completion of the start method. If * there were no problems then this method should return null. */ public Integer start(String[] args) { if (WrapperManager.isDebugEnabled()) { System.out.println(Main.getRes().getString("LoadedWrapperListener: start(args)")); } Thread mainThread = new Thread(this, "LoadedWrapperListenerMain"); synchronized (this) { m_startMainArgs = args; mainThread.start(); // Wait for five seconds to give the application a chance to have failed. try { this.wait(5000); } catch (InterruptedException e) { } m_waitTimedOut = true; if (WrapperManager.isDebugEnabled()) { System.out.println( Main.getRes() .getString( "LoadedWrapperListener: start(args) end. Main Completed={0}, exitCode={1}", new Object[] {new Boolean(m_mainComplete), m_mainExitCode})); } return m_mainExitCode; } }
public View getView(int position, View convertView, ViewGroup parent) { if (position >= 0 && position < m_listViews.size() && null != m_listViews.get(position)) return m_listViews.get(position); Log.d(TAG, "creating new view for position: " + position); Site oSite = m_listSites.get(position); Main actMain = (Main) m_context; LinearLayout viewSite = (LinearLayout) actMain.getLayoutInflater().inflate(R.layout.view_site, null); TextView viewTextUsername = (TextView) viewSite.findViewById(R.id.site_username); if (oSite.getUsername().length() > 0) viewTextUsername.setText(oSite.getUsername()); else viewTextUsername.setText(m_context.getString(R.string.title_login)); TextView viewTextUrl = (TextView) viewSite.findViewById(R.id.site_url); String sSiteUrl = oSite.getUrl().replace("xmlrpc/", ""); viewTextUrl.setText(sSiteUrl); LoaderImageView viewImageLoader = (LoaderImageView) viewSite.findViewById(R.id.site_icon); viewImageLoader.setNoImageResource(R.drawable.ic_site_view); viewImageLoader.setImageDrawable(sSiteUrl + "media/images/mobile_logo.png"); return viewSite; }
/** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static FortfuehrungsanlaesseDialog getInstance() { if (INSTANCE == null) { INSTANCE = new FortfuehrungsanlaesseDialog(Main.getCurrentInstance(), false); INSTANCE.setLocationRelativeTo(Main.getCurrentInstance()); } return INSTANCE; }
public static void writeFile() { try { // if region data is saved read from it otherwise create a new one. read("regions"); // copy data from file to a new object RegionHandling.setRegions(); } catch (FileNotFoundException e) { // if file was not found, attempt to create a new one Main.sendDebugInfo("Can't find region data file. Attepting to create a new one"); try { // attempt to write regions object to file save("regions"); Main.sendDebugInfo("New region data file created successfully!"); } catch (FileNotFoundException e1) { // if FileNotFoundException send error msg to console Main.sendSevereInfo( "A problem occurred attempting to read from the region data file : FileNotFoundException"); e1.printStackTrace(); } } }
public void execute(Main main) { System.out.println("Let's execute " + main.getFileName() + " !!! "); OBJECTS_MEMORY = new ObjectsMemory(); // which browser should we use ? switch (main.getBrowserName()) { case "Firefox": SEL_DRIVER = new FirefoxDriver(); break; case "Chrome": System.out.println("Sorry, this borwser is not available yet"); SEL_DRIVER = new FirefoxDriver(); case "Internet Explorer": System.out.println("Sorry, this borwser is not available yet"); SEL_DRIVER = new FirefoxDriver(); default: SEL_DRIVER = new FirefoxDriver(); break; } // execute all orders for (EObject e : main.getOrders()) { this.execute(e); } System.out.println("Done with " + main.getFileName() + " ! "); }
@Test public void testProxy() throws Exception { int frontendPort = Utils.findOpenPort(); int backendPort = Utils.findOpenPort(); Context ctx = ZMQ.context(1); assert (ctx != null); Main mt = new Main(ctx, frontendPort, backendPort); mt.start(); new Dealer(ctx, "AA", backendPort).start(); new Dealer(ctx, "BB", backendPort).start(); Thread.sleep(1000); Thread c1 = new Client(ctx, "X", frontendPort); c1.start(); Thread c2 = new Client(ctx, "Y", frontendPort); c2.start(); c1.join(); c2.join(); ctx.term(); }
public static void main(String[] args) { Main obj = new Main(); String text = "Hello world!"; Range range = obj.encode(text); System.out.println(range.getLow() + " " + range.getHigh()); System.out.println(obj.decode(text.length(), (range.getLow() + range.getHigh()) / 2)); }
public static void main(String[] args) throws fullQueueException, EmptyQueueException, FullStackException { Main main = new Main(); System.out.println( main.maximum(new Student("ali", 12), new Student("zohre", 10), new Student("ali", 18))); Stack<Student> stack1 = new Stack<>(); stack1.push(new Student("ali", 15)); stack1.push(new Student("samira", 12)); System.out.println(stack1.pop()); Stack<Student> stack2 = new Stack<>(); stack2.push(new Student("ali", 15)); stack2.push(new Student("samira", 12)); System.out.println(stack2.pop()); boolean result = stack1.equals(new Stack<Double>()); System.out.println(result); Queue<Student> queue = new Queue<>(); queue.push(new Student("ali", 15)); queue.push(new Student("samira", 12)); System.out.println(queue.pop()); }
@Override public synchronized HomeworkPacket process(HomeworkPacket message) { if (message.getId() == -100 || message.getId() == -666) { LOGGER.info("Dead"); System.exit(0); } if (message.getCharacter() != null) { LOGGER.debug("Message is not null"); Main.updateGameField(message.getCharacter().visibleMap()); } if (Cache.event != null) { HomeworkPacket homeworkPacket = new HomeworkPacket(message.getId(), Cache.event, message.getCharacter(), "name"); // Deref the old event Cache.event = new Event(-1); if (homeworkPacket.getCharacter() != null) { Main.changeScore(homeworkPacket.getCharacter().getScore()); } else { Main.changeScore("No score"); } LOGGER.info("Score is: {}", Main.score); return homeworkPacket; } return message; }
private void saveCurrent() { PrintWriter writer = null; try { writer = new PrintWriter("config.txt", "UTF-8"); writer.println("PhoneNumbers:"); for (String s : Main.getEmails()) { writer.println(s); } writer.println("Items:"); for (Item s : Main.getItems()) { writer.println(s.getName() + "," + s.getWebsite()); } results.setText("Current settings have been saved sucessfully."); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } writer.close(); }
@Test public void whenAndroidDirectoryResolverChangesParserInvalidated() throws IOException, InterruptedException { ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot().toPath()); Object daemon = Main.getDaemon( new TestCellBuilder() .setAndroidDirectoryResolver( new FakeAndroidDirectoryResolver( Optional.<Path>absent(), Optional.<Path>absent(), Optional.<Path>absent(), Optional.of("something"))) .setFilesystem(filesystem) .build(), new ObjectMapper()); assertNotEquals( "Daemon should be replaced when not equal.", daemon, Main.getDaemon( new TestCellBuilder() .setAndroidDirectoryResolver( new FakeAndroidDirectoryResolver( Optional.<Path>absent(), Optional.<Path>absent(), Optional.<Path>absent(), Optional.of("different"))) .setFilesystem(filesystem) .build(), new ObjectMapper())); }
@Override public void init(GameContainer gc, StateBasedGame sbg) throws SlickException { windowSizeX = Main.screenX(); windowSizeY = Main.screenY(); ball = new PongBall(); ball.setPosition( windowSizeX / 2 - ball.object.getWidth() / 2, windowSizeY / 2 - ball.object.getHeight() / 2); // player1 = new AI(ball, windowSizeY, windowSizeX); player1 = new Player(); player1.setPosition(40, windowSizeY / 2 - player1.object.getHeight() / 2); if (stateID == 2) { System.out.println("Multiplayer initiated"); player2 = new Player(); } if (stateID == 1) { System.out.println("Singleplayer initiated"); player2 = new AI(ball, windowSizeY, windowSizeX); } player2.setPosition( windowSizeX - 40 - player2.object.getWidth(), windowSizeY / 2 - player1.object.getHeight() / 2); gc.setShowFPS(false); }
public void stop() { /* Dump a message */ System.err.println("ServiceDaemon: stopping"); try { final File homeDir = existMain.detectHome(); final String[] noArgs = {}; final Classpath classpath = existMain.constructClasspath(homeDir, noArgs); final ClassLoader cl = classpath.getClassLoader(null); Thread.currentThread().setContextClassLoader(cl); final Class<?> brokerPoolClass = cl.loadClass("org.exist.storage.BrokerPool"); // This only works in Java 1.5 // Method stopAll = brokerPoolClass.getDeclaredMethod("stopAll",java.lang.Boolean.TYPE); // stopAll.invoke(null,Boolean.TRUE); // This is the ugly Java 1.4 version final Class<?>[] paramTypes = new Class[1]; paramTypes[0] = java.lang.Boolean.TYPE; final Method stopAll = brokerPoolClass.getDeclaredMethod("stopAll", paramTypes); final Object[] arguments = new Object[1]; arguments[0] = Boolean.TRUE; stopAll.invoke(null, arguments); } catch (final Exception ex) { ex.printStackTrace(); } System.err.println("ServiceDaemon: stopped"); }
public void testPairesMemeDeuxPaireDifferentKicker() { Main mainSuperieure = new Main(); mainSuperieure.add(new Carte(Denomination.TROIS, CouleurCarte.CARREAU)); mainSuperieure.add(new Carte(Denomination.TROIS, CouleurCarte.PIQUE)); mainSuperieure.add(new Carte(Denomination.CINQ, CouleurCarte.COEUR)); mainSuperieure.add(new Carte(Denomination.CINQ, CouleurCarte.PIQUE)); mainSuperieure.add(new Carte(Denomination.DIX, CouleurCarte.TREFLE)); Main mainInferieure = new Main(); mainInferieure.add(new Carte(Denomination.TROIS, CouleurCarte.CARREAU)); mainInferieure.add(new Carte(Denomination.TROIS, CouleurCarte.COEUR)); mainInferieure.add(new Carte(Denomination.CINQ, CouleurCarte.TREFLE)); mainInferieure.add(new Carte(Denomination.CINQ, CouleurCarte.CARREAU)); mainInferieure.add(new Carte(Denomination.HUIT, CouleurCarte.PIQUE)); ReqAnalyseMain requeteMainSuperieure = new ReqAnalyseMain(mainSuperieure); ReqAnalyseMain requeteMainInferieure = new ReqAnalyseMain(mainInferieure); assertTrue(new DeuxPaires().reconnaitreMain(requeteMainSuperieure)); assertTrue(new DeuxPaires().reconnaitreMain(requeteMainInferieure)); RangPoker rangMainSuperieure = requeteMainSuperieure.getRangReconnu(); RangPoker rangMainInferieure = requeteMainInferieure.getRangReconnu(); assertTrue(rangMainSuperieure.compareTo(rangMainInferieure) > 0); assertTrue(rangMainInferieure.compareTo(rangMainSuperieure) < 0); }
/** Client behavior. Sleep until the fuse is over, then ask the service to the robot. */ public void run() { System.out.println( Main.now() + " Created client " + id + " with fuse=" + fuse + ", priority=" + priority + ", duration=" + duration); try { sleep(fuse - Main.now()); long time = Main.now(); System.out.println( time + " Req. from client " + id + " (delay=" + (time - fuse) + ")" + ", priority=" + priority); robbie.deliver(id, fuse, priority, duration); } catch (InterruptedException ie) { } }
public ChatManager(Main plugin) { this.plugin = plugin; this.secondsBetweenSameLine = 10; _player_mutex = new ReentrantLock(true); playerLastChatLine = new TreeMap<>(); playerWarnings = new TreeMap<>(); lastTalkPlayer = ""; lastChatLineTime = 0; File enBadWords = new File(plugin.getDataFolder(), "badwords.txt"); File spBadWords = new File(plugin.getDataFolder(), "malaspalabras.txt"); if (!enBadWords.exists()) { plugin.saveResource(enBadWords.getName(), true); } if (!spBadWords.exists()) { plugin.saveResource(spBadWords.getName(), true); } String badWordsList; badWordsList = loadBadWords(enBadWords); badWordsList = badWordsList.concat("|" + loadBadWords(spBadWords)); badWordsPattern = Pattern.compile("\\b(" + badWordsList + ")\\b"); if (plugin.getConfig().getBoolean("debug")) { plugin.getLogger().log(Level.INFO, "Debug: bad world list: {0}", badWordsList); } }
@Test public void testBuildCommandLine() throws IOException, NoSuchFieldException, IllegalAccessException { List<String> jvmArgs = new ArrayList<String>(); jvmArgs.add("--exec"); jvmArgs.add("-Xms1024m"); jvmArgs.add("-Xmx1024m"); List<String> xmls = new ArrayList<String>(); xmls.add("jetty.xml"); xmls.add("jetty-jmx.xml"); xmls.add("jetty-logging.xml"); Main main = new Main(); main.addJvmArgs(jvmArgs); Classpath classpath = nastyWayToCreateAClasspathObject("/jetty/home with spaces/"); CommandLineBuilder cmd = main.buildCommandLine(classpath, xmls); Assert.assertThat("CommandLineBuilder shouldn't be null", cmd, notNullValue()); String commandLine = cmd.toString(); Assert.assertThat("CommandLine shouldn't be null", commandLine, notNullValue()); Assert.assertThat( "Classpath should be correctly quoted and match expected value", commandLine, containsString( "-cp /jetty/home with spaces/somejar.jar:/jetty/home with spaces/someotherjar.jar")); Assert.assertThat( "CommandLine should contain jvmArgs", commandLine, containsString("--exec -Xms1024m -Xmx1024m")); Assert.assertThat( "CommandLine should contain xmls", commandLine, containsString("jetty.xml jetty-jmx.xml jetty-logging.xml")); }
/** Insertar un nodo en el grafoNoDirigido. */ @FXML protected void botonInsertar() { if (scene == null) { initializeGrafo(); } // Mostrar el codigo String tipo = getTipoString(); String codigoTexto = new Scanner( getClass() .getResourceAsStream( "/cl/cromer/estructuras/code/grafo" + tipo + "/insertarNodo")) .useDelimiter("\\Z") .next(); codigoGrafo.setText(codigoTexto); if (valorGrafo.getText() != null && !valorGrafo.getText().trim().equals("")) { try { int i; for (i = 0; i < 5; i++) { if (grafoNodos[i] == null) { grafoNodos[i] = new GrafoNodo(Integer.valueOf(valorGrafo.getText())); break; } else if (grafoNodos[i].getValue() == Integer.valueOf(valorGrafo.getText())) { Main.mostrarError(resourceBundle.getString("grafoNodoExiste"), resourceBundle); i = -1; break; } } if (i == 5) { // Maximo 5 nodos Main.mostrarError(resourceBundle.getString("grafoLleno"), resourceBundle); } else if (i != -1) { boolean exito; if (grafoTipos.getTipo() == Grafo.Tipos.NO_DIRIGIDO) { exito = noDirigido.addNode(grafoNodos[i]); } else { Grafo.Vertex<GrafoNodo> vertex = new Grafo.Vertex<>(String.valueOf(grafoNodos[i].getValue())); vertex.setData(grafoNodos[i]); exito = dirigido.addVertex(vertex); } if (exito) { valorGrafo.setText(""); generarGrafico(); } else { Main.mostrarError(resourceBundle.getString("grafoNodoExiste"), resourceBundle); } } } catch (NumberFormatException exception) { // El error no es fatal, sigue Main.mostrarError(resourceBundle.getString("grafoNoNumero"), resourceBundle); } } else { Main.mostrarError(resourceBundle.getString("grafoNoNumero"), resourceBundle); } }
public void saveDefaultStorageConfig() { if (storageConfigFile == null) { storageConfigFile = new File(plugin.getDataFolder(), "storage.yml"); } if (!storageConfigFile.exists()) { plugin.saveResource("storage.yml", false); } }
@EventHandler public void onPlayerJoinEvent(PlayerJoinEvent event) { if (!event.getPlayer().hasPlayedBefore()) { Main.newbie(event.getPlayer()); } else { Main.normal(event.getPlayer()); } }