Example #1
0
 public static void initialbuild() throws IOException, InterruptedException {
   System.out.println("building an empty map");
   long start = System.currentTimeMillis();
   Thread t1 =
       new Thread("test 1") {
         public void run() {
           populate(1);
         }
       };
   t1.start();
   Thread t2 =
       new Thread("test 2") {
         public void run() {
           populate(2);
         }
       };
   t2.start();
   Thread t3 =
       new Thread("test 3") {
         public void run() {
           populate(3);
         }
       };
   t3.start();
   populate(0);
   t1.join();
   t2.join();
   t3.join();
   long now = System.currentTimeMillis();
   System.out.println(builder);
   System.out.println("Time taken to insert all entries " + ((now - start) / 1000.0) + " seconds");
 }
  public static void main(String[] args) throws Exception {
    int minTokenCount = 5;
    File corpusFile = new File(args[0]);
    CharSequence[] articleTexts = LdaWormbase.readCorpus(corpusFile);
    SymbolTable symbolTable = new MapSymbolTable();
    TokenizerFactory tokenizerFactory = LdaWormbase.WORMBASE_TOKENIZER_FACTORY;
    int[][] docTokens =
        LatentDirichletAllocation.tokenizeDocuments(
            articleTexts, tokenizerFactory, symbolTable, minTokenCount);

    LdaRunnable runnable1 =
        new LdaRunnable(docTokens, new LdaReportingHandler(symbolTable), new Random());

    LdaRunnable runnable2 =
        new LdaRunnable(docTokens, new LdaReportingHandler(symbolTable), new Random());

    Thread thread1 = new Thread(runnable1);
    Thread thread2 = new Thread(runnable2);

    thread1.start();
    thread2.start();

    thread1.join();
    thread2.join();

    LatentDirichletAllocation lda0 = runnable1.mLda;

    LatentDirichletAllocation lda1 = runnable2.mLda;

    System.out.println("\nComputing Greedy Aligned Symmetrized KL Divergences");
    double[] scores = similarity(lda0, lda1);
    for (int i = 0; i < scores.length; ++i) System.out.printf("%4d %15.3f\n", i, scores[i]);
  }
Example #3
0
 public static void main(String[] args) throws IOException, InterruptedException {
   long start = System.currentTimeMillis();
   initialbuild();
   System.out.println("Start highwatermark " + Highwatermark.get());
   for (int i = 0; i < 10; i++) {
     Thread t1 =
         new Thread("test 1") {
           public void run() {
             _test();
           }
         };
     Thread t2 =
         new Thread("test 2") {
           public void run() {
             _test();
           }
         };
     Thread t3 =
         new Thread("test 3") {
           public void run() {
             _test();
           }
         };
     t1.start();
     t2.start();
     t3.start();
     _test();
     t1.join();
     t2.join();
     t3.join();
   }
   System.out.println("End highwatermark " + Highwatermark.get());
   long time = System.currentTimeMillis() - start;
   System.out.printf("End to end took %.1f%n", time / 1e3);
 }
Example #4
0
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  JavaxHTTPSConnection() throws Exception {
    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }
  }
Example #5
0
  // --------------------------------actionDisconnect---------------------------
  private void actionDisconnect() {

    try {
      oConn.disconnect();
      tConn.join(2000);
      tMain.join(2000);
    } catch (Exception e) {
    }
  }
Example #6
0
  public static void main(String[] args) throws Exception {
    if (args.length == 0) {
      System.err.println("Usage: java PortForward <local-port> <listen-port>");
      return;
    }
    int localPort = Integer.parseInt(args[0]);
    int listenPort = Integer.parseInt(args[1]);
    ServerSocket ss = new ServerSocket(listenPort);
    final Socket in = ss.accept();
    final Socket out = new Socket("127.0.0.1", localPort);

    Thread in2out =
        new Thread() {
          public void run() {
            try {
              InputStream i = in.getInputStream();
              OutputStream o = out.getOutputStream();
              int b = i.read();
              while (b >= 0) {
                o.write((byte) b);
                b = i.read();
              }
              o.close();
              i.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    in2out.start();

    Thread out2in =
        new Thread() {
          public void run() {
            try {
              InputStream i = out.getInputStream();
              OutputStream o = in.getOutputStream();
              int b = i.read();
              while (b >= 0) {
                o.write((byte) b);
                b = i.read();
              }
              o.close();
              i.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    out2in.start();

    in2out.join();
    out2in.join();
    in.close();
    out.close();
  }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
Example #8
0
  /** Test the http protocol handler with one WWW-Authenticate header with the value "NTLM". */
  static void testNTLM() throws Exception {
    // server reply
    String reply = authReplyFor("NTLM");

    System.out.println("====================================");
    System.out.println("Expect client to fail with 401 Unauthorized");
    System.out.println(reply);

    try (ServerSocket ss = new ServerSocket(0)) {
      Client client = new Client(ss.getLocalPort());
      Thread thr = new Thread(client);
      thr.start();

      // client ---- GET ---> server
      // client <--- 401 ---- client
      try (Socket s = ss.accept()) {
        new MessageHeader().parseHeader(s.getInputStream());
        s.getOutputStream().write(reply.getBytes("US-ASCII"));
      }

      // the client should fail with 401
      System.out.println("Waiting for client to terminate");
      thr.join();
      IOException ioe = client.ioException();
      if (ioe != null) System.out.println("Client failed: " + ioe);
      int respCode = client.respCode();
      if (respCode != 0 && respCode != -1)
        System.out.println("Client received HTTP response code: " + respCode);
      if (respCode != HttpURLConnection.HTTP_UNAUTHORIZED)
        throw new RuntimeException("Unexpected response code");
    }
  }
  public static void main(String[] args) {
    BufferedReader in;

    try {
      in =
          new BufferedReader(
              new FileReader(
                  "/Users/rahulkhairwar/Documents/IntelliJ IDEA Workspace/Competitive "
                      + "Programming/src/com/google/codejam16/qualificationround/inputB.txt"));

      OutputWriter out = new OutputWriter(System.out);
      Thread thread = new Thread(null, new Solver(in, out), "Solver", 1 << 28);

      thread.start();

      try {
        thread.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      out.flush();

      in.close();
      out.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #10
0
  // Do some simple concurrent testing
  public void testConcurrentSimple() throws InterruptedException {
    final NonBlockingIdentityHashMap<String, String> nbhm =
        new NonBlockingIdentityHashMap<String, String>();
    final String[] keys = new String[20000];
    for (int i = 0; i < 20000; i++) keys[i] = "k" + i;

    // In 2 threads, add & remove even & odd elements concurrently
    Thread t1 =
        new Thread() {
          public void run() {
            work_helper(nbhm, "T1", 1, keys);
          }
        };
    t1.start();
    work_helper(nbhm, "T0", 0, keys);
    t1.join();

    // In the end, all members should be removed
    StringBuffer buf = new StringBuffer();
    buf.append("Should be emptyset but has these elements: {");
    boolean found = false;
    for (String x : nbhm.keySet()) {
      buf.append(" ").append(x);
      found = true;
    }
    if (found) System.out.println(buf + " }");
    assertThat("concurrent size=0", nbhm.size(), is(0));
    for (String x : nbhm.keySet()) {
      assertTrue("No elements so never get here", false);
    }
  }
Example #11
0
  /**
   * Closes the server socket and the connections with all clients. Any exception thrown while
   * closing a client is ignored. If one wishes to catch these exceptions, then clients should be
   * individually closed before calling this method. The method also stops listening if this thread
   * is running. If the server is already closed, this call has no effect.
   *
   * @exception IOException if an I/O error occurs while closing the server socket.
   */
  public final void close() throws IOException {
    if (serverSocket == null) return;
    stopListening();

    try {
      serverSocket.close();
    } finally {
      synchronized (this) {
        // Close the client sockets of the already connected clients
        Thread[] clientThreadList = getClientConnections();
        for (int i = 0; i < clientThreadList.length; i++) {
          try {
            ((ConnectionToClient) clientThreadList[i]).close();
          }
          // Ignore all exceptions when closing clients.
          catch (Exception ex) {
          }
        }
        serverSocket = null;
      }

      try {
        connectionListener.join(); // Wait for the end of listening thread.
      } catch (InterruptedException ex) {
      } catch (NullPointerException ex) {
      } // When thread already dead.

      serverClosed();
    }
  }
Example #12
0
  /** Stops unicast and multicast receiver threads */
  void stopThreads() {
    Thread tmp;

    // 1. Stop the multicast receiver thread
    if (mcast_receiver != null) {
      if (mcast_receiver.isAlive()) {
        tmp = mcast_receiver;
        mcast_receiver = null;
        closeMulticastSocket(); // will cause the multicast thread to terminate
        tmp.interrupt();
        try {
          tmp.join(100);
        } catch (Exception e) {
        }
        tmp = null;
      }
      mcast_receiver = null;
    }

    // 2. Stop the unicast receiver thread
    if (ucast_receiver != null) {
      ucast_receiver.stop();
      ucast_receiver = null;
    }

    // 3. Stop the in_packet_handler thread
    if (incoming_packet_handler != null) {
      incoming_packet_handler.stop();
    }
  }
 /** stopSending attempts to stop the thread, then waits for thread to stop. */
 public void stopSending() {
   _keepRunning = false;
   try {
     _sendThread.join();
   } catch (InterruptedException e) {
   }
 }
    public void run() {
      try {
        if (myPreviousThread != null) myPreviousThread.join();
        Thread.sleep(delay);
        log("> run MouseMoveThread " + x + ", " + y);
        while (!hasFocus()) {
          Thread.sleep(1000);
        }
        int x1 = lastMouseX;
        int x2 = x;
        int y1 = lastMouseY;
        int y2 = y;
        // shrink range by 1 px on both ends
        // manually move this 1px to trip DND code
        if (x1 != x2) {
          int dx = x - lastMouseX;
          if (dx > 0) {
            x1 += 1;
            x2 -= 1;
          } else {
            x1 -= 1;
            x2 += 1;
          }
        }
        if (y1 != y2) {
          int dy = y - lastMouseY;
          if (dy > 0) {
            y1 += 1;
            y2 -= 1;
          } else {
            y1 -= 1;
            y2 += 1;
          }
        }
        robot.setAutoDelay(Math.max(duration / 100, 1));
        robot.mouseMove(x1, y1);
        int d = 100;
        for (int t = 0; t <= d; t++) {
          x1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseX, (double) x2 - lastMouseX, (double) d);
          y1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseY, (double) y2 - lastMouseY, (double) d);
          robot.mouseMove(x1, y1);
        }
        robot.mouseMove(x, y);
        lastMouseX = x;
        lastMouseY = y;
        robot.waitForIdle();
        robot.setAutoDelay(1);
      } catch (Exception e) {
        log("Bad parameters passed to mouseMove");
        e.printStackTrace();
      }

      log("< run MouseMoveThread");
    }
  public void onDestroy() {
    running = false;
    if (scanThread != null) scanThread.interrupt();

    if (myWLocate != null) myWLocate.doPause();

    sensorManager.unregisterListener(
        this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

    if (scanData.getmView() != null) {
      ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(scanData.getmView());
      scanData.setmView(null);
    }
    try {
      if (wl != null) wl.release();
    } catch (RuntimeException re) {
    }
    wl = null;
    try {
      scanThread.join(1000);
    } catch (InterruptedException ie) {

    }
    System.exit(0);
  }
  public boolean request(Object soaprequest) {
    if (!checkSoapMemberVariable()) return false;

    ServiceRequest req =
        new ServiceRequest(
            this.ServerUrl,
            this.SoapAction,
            this.NameSpace,
            this.MethodName,
            this.SoapVersion,
            this.DotNet,
            (SoapObject) soaprequest);
    Thread thread = new Thread(req);

    try {
      thread.start();
      thread.join();
    } catch (Exception e) {
      this.Response = null;
      e.printStackTrace();
      return false;
    }

    this.Response = req.getResponse();
    if (this.Response == null) return false;
    return true;
  }
  public static void main(String[] args) throws Exception {
    int N = 6000;
    if (args.length >= 1) N = Integer.parseInt(args[0]);

    Crb = new double[N + 7];
    Cib = new double[N + 7];
    double invN = 2.0 / N;
    for (int i = 0; i < N; i++) {
      Cib[i] = i * invN - 1.0;
      Crb[i] = i * invN - 1.5;
    }
    yCt = new AtomicInteger();
    out = new byte[N][(N + 7) / 8];

    Thread[] pool = new Thread[2 * Runtime.getRuntime().availableProcessors()];
    for (int i = 0; i < pool.length; i++)
      pool[i] =
          new Thread() {
            public void run() {
              int y;
              while ((y = yCt.getAndIncrement()) < out.length) putLine(y, out[y]);
            }
          };
    for (Thread t : pool) t.start();
    for (Thread t : pool) t.join();

    OutputStream stream = new BufferedOutputStream(System.out);
    stream.write(("P4\n" + N + " " + N + "\n").getBytes());
    for (int i = 0; i < N; i++) stream.write(out[i]);
    stream.close();
  }
  /** {@inheritDoc} */
  public void updateBlock(Block oldblock, Block newblock) throws IOException {
    if (oldblock.getBlockId() != newblock.getBlockId()) {
      throw new IOException(
          "Cannot update oldblock (=" + oldblock + ") to newblock (=" + newblock + ").");
    }

    for (; ; ) {
      final List<Thread> threads = tryUpdateBlock(oldblock, newblock);
      if (threads == null) {
        return;
      }

      // interrupt and wait for all ongoing create threads
      for (Thread t : threads) {
        t.interrupt();
      }
      for (Thread t : threads) {
        try {
          t.join();
        } catch (InterruptedException e) {
          DataNode.LOG.warn("interruptOngoingCreates: t=" + t, e);
        }
      }
    }
  }
 public void stop() {
   running.set(false);
   try {
     thread.join();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Example #20
0
  public void start(ContentHandler sax, Target target) throws IOException, SAXException {
    this.target = target;

    XMLReader parser;
    try {
      parser = spf.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException e) {
      throw new LagoonException(e.getMessage());
    }

    parser.setContentHandler(sax);
    parser.setEntityResolver(
        new EntityResolver() {
          public InputSource resolveEntity(String publicId, String systemId)
              throws SAXException, IOException {
            InputSource is = new InputSource(getSourceMan().getFileURL(systemId));

            File fil = getSourceMan().getFile(systemId);

            if (fil != null) {
              InputStream istr = new FileInputStream(fil);
              is.setByteStream(istr);
            }

            return is;
          }
        });

    exception = null;

    mis = new MyInputStream();
    mos = new MyOutputStream(mis);

    thread = new Thread(this);
    thread.start();

    parser.parse(new InputSource(mis));
    mis.close();

    try {
      thread.join(1000);
    } catch (InterruptedException e) {
    }

    if (thread.isAlive()) {
      thread.interrupt();
    }

    this.target = null;

    if (exception != null) {
      if (exception instanceof SAXException) {
        throw (SAXException) exception;
      } else if (exception instanceof IOException) {
        throw (IOException) exception;
      }
    }
  }
  /*
   * Primary constructor, used to drive remainder of the test.
   *
   * Fork off the other side, then do your work.
   */
  InvalidateServerSessionRenegotiate() throws Exception {
    if (separateServerThread) {
      startServer(true);
      startClient(false);
    } else {
      startClient(true);
      startServer(false);
    }

    /*
     * Wait for other side to close down.
     */
    if (separateServerThread) {
      serverThread.join();
    } else {
      clientThread.join();
    }

    /*
     * When we get here, the test is pretty much over.
     *
     * If the main thread excepted, that propagates back
     * immediately.  If the other thread threw an exception, we
     * should report back.
     */
    if (serverException != null) {
      System.out.print("Server Exception:");
      throw serverException;
    }
    if (clientException != null) {
      System.out.print("Client Exception:");
      throw clientException;
    }

    /*
     * Give the Handshaker Thread a chance to run
     */
    Thread.sleep(1000);

    synchronized (this) {
      if (handshakesCompleted != 2) {
        throw new Exception("Didn't see 2 handshake completed events.");
      }
    }
  }
Example #22
0
 public static void main(String[] args) throws Exception {
   TypeServer ts = new TypeServer();
   ts.port = Integer.parseInt(args[0]);
   Thread t = new Thread(ts);
   t.start();
   System.out.println("Type server ready...Type CTRL-D to exit");
   while (System.in.read() > 0) ;
   ts.stopServer();
   t.join();
 }
Example #23
0
  public static void main(String[] args) {

    Thread thread = new Thread(new Download(args));
    thread.setDaemon(true);
    thread.start();
    try {
      thread.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** Stop the server. */
 public void stop() {
   try {
     safeClose(myServerSocket);
     closeAllConnections();
     if (myThread != null) {
       myThread.join();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #25
0
 synchronized void waitUntilCompleted(long timeout, boolean resume) {
   if (thread != null) {
     try {
       thread.join(timeout);
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt(); // set interrupt flag again
     }
     thread = null; // Added after Brian noticed that ViewHandler leaks class loaders
   }
   if (resume) resumeForce();
 }
Example #26
0
 public void stop() {
   if (streamReader == null || !streamReader.isAlive()) {
     System.out.println("Camera already stopped");
     return;
   }
   keepAlive = false;
   try {
     streamReader.join();
   } catch (InterruptedException e) {
     System.err.println(e.getMessage());
   }
 }
 void solve() {
   Thread tcThread = new Thread(tc);
   // System.out.println("starting client thread");
   tcThread.start();
   try {
     tcThread.join();
   } catch (Exception e) {
     e.printStackTrace();
   }
   // System.out.println("joined client thread");
   result = SudokuSolver.solve(tc.testcase);
   success = SudokuSolver.isLegalSolution(result, tc.testcase);
 }
 /**
  * When the server-side connector webapp is shutdown by the servlet container, the
  * ServerNotificationManager calls this method. All pending notifications are dropped.
  */
 public void close() {
   exiting = true;
   synchronized (que) {
     que.notify();
   }
   try {
     dispatchThr.join();
   } catch (InterruptedException intre) {
   }
   try {
     out.close();
   } catch (IOException ioe) {
     // XXX: Log it
   }
 }
Example #29
0
 @Test
 public void shouldPurgeDiskDumpAndRepositoryWhenAsked()
     throws IOException, ClassNotFoundException, InterruptedException {
   SuiteTimeRepo fooRepo = factory.createSuiteTimeRepo("foo", LATEST_VERSION);
   fooRepo.update(new SuiteTimeEntry("foo.bar.Baz", 15));
   fooRepo.update(new SuiteTimeEntry("foo.bar.Quux", 80));
   final Thread exitHook = factory.exitHook();
   exitHook.start();
   exitHook.join();
   factory.purge(fooRepo.identifier);
   fooRepo = factory.createSuiteTimeRepo("foo", LATEST_VERSION);
   assertThat(fooRepo.list().size(), is(0));
   fooRepo = new EntryRepoFactory(env()).createSuiteTimeRepo("foo", LATEST_VERSION);
   assertThat(fooRepo.list().size(), is(0));
 }
 public void run() {
   try {
     if (myPreviousThread != null) myPreviousThread.join();
     Thread.sleep(delay);
     log("> run MousePressThread");
     while (!hasFocus()) {
       Thread.sleep(1000);
     }
     robot.mousePress(mask);
     robot.waitForIdle();
   } catch (Exception e) {
     log("Bad parameters passed to mousePress");
     e.printStackTrace();
   }
   log("< run MousePressThread");
 }