void mixLists(
      LinkedList<Integer> left,
      LinkedList<Integer> right,
      ArrayList<LinkedList<Integer>> mix,
      LinkedList<Integer> before) {
    if (before.isEmpty() || right.isEmpty()) {
      LinkedList<Integer> l = new LinkedList<>();
      l = (LinkedList<Integer>) before.clone();
      l.addAll(left);
      l.addAll(right);
      mix.add(l);
      return;
    }
    int hl = left.removeFirst();
    before.addLast(hl);
    mixLists(left, right, mix, before);
    before.removeLast();
    left.addFirst(hl);

    int hr = right.removeFirst();
    before.addLast(hr);
    mixLists(left, right, mix, before);
    before.removeLast();
    right.addFirst(hr);
  }
Beispiel #2
0
  /**
   * Helper function: update the "old" RM group with the "next" group provided.
   *
   * @param old
   * @param next
   */
  private void updateRMGroup(LinkedList<MemberInfo> old, LinkedList<MemberInfo> next) {
    if (next == null || next.isEmpty()) {
      System.out.println("empty or null next MemberInfo sent in updated.");
      return;
    }

    // Add to our old list the memberInfo objects that were not previously there.
    for (MemberInfo m : next) {
      if (old == null) {
        System.out.println("OLD NULL");
      }

      if (m == null) {
        System.out.println("M NULL");
      }

      if (!old.contains(m)) {
        old.add(m);
      }
    }

    // Remove from our old list the memberInfo objects that are absent in next.
    LinkedList<MemberInfo> toRemove = new LinkedList<MemberInfo>();
    for (MemberInfo m : old) {
      if (!next.contains(m)) {
        toRemove.add(m);
      }
    }
    for (MemberInfo m : toRemove) {
      old.remove(m);
    }
  }
  /**
   * Run all jobs in the work list (and any children they have) to completion. This method returns
   * <code>true</code> if all jobs were successfully completed. If all jobs were successfully
   * completed, then the worklist will be empty.
   *
   * <p>The scheduling of <code>Job</code>s uses two methods to maintain scheduling invariants:
   * <code>selectJobFromWorklist</code> selects a <code>SourceJob</code> from <code>worklist</code>
   * (a list of jobs that still need to be processed); <code>enforceInvariants</code> is called
   * before a pass is performed on a <code>SourceJob</code> and is responsible for ensuring all
   * dependencies are satisfied before the pass proceeds, i.e. enforcing any scheduling invariants.
   */
  public boolean runToCompletion() {
    boolean okay = true;

    while (okay && !worklist.isEmpty()) {
      SourceJob job = selectJobFromWorklist();

      if (Report.should_report(Report.frontend, 1)) {
        Report.report(1, "Running job " + job);
      }

      okay &= runAllPasses(job);

      if (job.completed()) {
        // the job has finished. Let's remove it from the map so it
        // can be garbage collected, and free up the AST.
        jobs.put(job.source(), COMPLETED_JOB);

        if (Report.should_report(Report.frontend, 1)) {
          Report.report(1, "Completed job " + job);
        }
      } else {
        // the job is not yet completed (although, it really
        // should be...)
        if (Report.should_report(Report.frontend, 1)) {
          Report.report(1, "Failed to complete job " + job);
        }
        worklist.add(job);
      }
    }

    if (Report.should_report(Report.frontend, 1))
      Report.report(1, "Finished all passes -- " + (okay ? "okay" : "failed"));

    return okay;
  }
Beispiel #4
0
 public static String normalizePath(String path) {
   if (!path.contains("./")) {
     return path;
   }
   boolean absolute = path.startsWith("/");
   String[] elements = path.split(Repository.SEPARATOR);
   LinkedList<String> list = new LinkedList<String>();
   for (String e : elements) {
     if ("..".equals(e)) {
       if (list.isEmpty() || "..".equals(list.getLast())) {
         list.add(e);
       } else {
         list.removeLast();
       }
     } else if (!".".equals(e) && e.length() > 0) {
       list.add(e);
     }
   }
   StringBuilder sb = new StringBuilder(path.length());
   if (absolute) {
     sb.append("/");
   }
   int count = 0, last = list.size() - 1;
   for (String e : list) {
     sb.append(e);
     if (count++ < last) sb.append("/");
   }
   return sb.toString();
 }
Beispiel #5
0
 public String getTitle() {
   LinkedList<Throwable> stack = getStack();
   if (stack.isEmpty()) {
     return "NO EXCEPTION";
   } else {
     return getTitle(stack.removeFirst());
   }
 }
Beispiel #6
0
 /* process the list of pending constraints */
 protected void processWorklist() {
   int iter = 0;
   while (!w.isEmpty()) {
     int size = w.size();
     Constraint c = w.removeFirst();
     c.accept(this);
     size -= w.size();
     iter++;
   }
 }
 private void relabelToFront() {
   assert (!V.isEmpty()) : "No vertices";
   ListIterator<Vertex> iter = V.listIterator();
   while (iter.hasNext()) {
     Vertex v = iter.next();
     // System.out.println("Considering vertex: " + v);
     int oldHeight = v.getHeight();
     discharge(v);
     if (v.getHeight() > oldHeight) {
       iter.remove();
       V.addFirst(v);
       iter = V.listIterator(1);
     }
   }
 }
Beispiel #8
0
  public static void main(String[] args) throws Exception {
    String portName = null;
    String portVersion = null;
    String portVendor = null;
    String portDesc = null;
    String ymzFilename = null;

    boolean invalid = true;
    LinkedList<String> list = new LinkedList<>(Arrays.asList(args));
    argCheck:
    while (!list.isEmpty()) {
      String arg = list.removeFirst();
      switch (arg) {
        case "--midi-name":
          if (list.isEmpty()) {
            break argCheck;
          }
          portName = list.removeFirst();
          break;
        case "--midi-version":
          if (list.isEmpty()) {
            break argCheck;
          }
          portVersion = list.removeFirst();
          break;
        case "--midi-vendor":
          if (list.isEmpty()) {
            break argCheck;
          }
          portVendor = list.removeFirst();
          break;
        case "--midi-desc":
          if (list.isEmpty()) {
            break argCheck;
          }
          portDesc = list.removeFirst();
          break;
        default:
          ymzFilename = arg;
          invalid = false;
          break argCheck;
      }
    }

    if (invalid || !(list.isEmpty())) {
      usage();
      System.exit(1);
    }

    File input = new File(ymzFilename);
    YMZPlayer player = new YMZPlayer(input);
    player.play(portName, portVersion, portVendor, portDesc);
  }
 public static boolean processFilesRecursively(
     @NotNull File root,
     @NotNull Processor<File> processor,
     @Nullable final Processor<File> directoryFilter) {
   final LinkedList<File> queue = new LinkedList<File>();
   queue.add(root);
   while (!queue.isEmpty()) {
     final File file = queue.removeFirst();
     if (!processor.process(file)) return false;
     if (file.isDirectory() && (directoryFilter == null || directoryFilter.process(file))) {
       final File[] children = file.listFiles();
       if (children != null) {
         ContainerUtil.addAll(queue, children);
       }
     }
   }
   return true;
 }
  public List<VirtualFile> gatherPatchFiles(final Collection<VirtualFile> files) {
    final List<VirtualFile> result = new ArrayList<VirtualFile>();

    final LinkedList<VirtualFile> filesQueue = new LinkedList<VirtualFile>(files);
    while (!filesQueue.isEmpty()) {
      ProgressManager.checkCanceled();
      final VirtualFile file = filesQueue.removeFirst();
      if (file.isDirectory()) {
        filesQueue.addAll(Arrays.asList(file.getChildren()));
        continue;
      }
      if (PatchFileType.NAME.equals(file.getFileType().getName())) {
        result.add(file);
      }
    }

    return result;
  }
Beispiel #11
0
 public static ArrayList<String> serializeTree(TreeNode tree) {
   ArrayList<String> res = new ArrayList<>();
   LinkedList<TreeNode> queue = new LinkedList<>();
   queue.addLast(tree);
   while (!queue.isEmpty()) {
     TreeNode node = queue.removeFirst();
     if (node == null) {
       res.add(NULL);
     } else {
       res.add(String.valueOf(node.val));
       queue.add(node.left);
       queue.add(node.right);
     }
   }
   while (res.size() > 1 && res.get(res.size() - 1).equals(NULL)) {
     res.remove(res.size() - 1);
   }
   return res;
 }
 public void search(Vertex[] nodes, int start) {
   LinkedList<Vertex> queue = new LinkedList<>();
   nodes[start].numPaths = 1;
   nodes[start].minDistance = 0;
   queue.addLast(nodes[start]);
   while (!queue.isEmpty()) {
     Vertex curr = queue.removeFirst();
     for (Edge e : curr.edges) {
       Vertex other = e.end;
       if (!other.checked) {
         other.checked = true;
         queue.addLast(other);
       }
       if (curr.minDistance + e.weight < other.minDistance) {
         other.minDistance = curr.minDistance + e.weight;
         other.numPaths = curr.numPaths;
       } else if (curr.minDistance + e.weight == other.minDistance) {
         other.numPaths += curr.numPaths;
       }
     }
   }
 }
  public static void processFilesRecursively(
      @NotNull VirtualFile root,
      @NotNull Processor<VirtualFile> processor,
      @NotNull Convertor<VirtualFile, Boolean> directoryFilter) {
    if (!processor.process(root)) return;

    if (root.isDirectory() && directoryFilter.convert(root)) {
      final LinkedList<VirtualFile[]> queue = new LinkedList<VirtualFile[]>();

      queue.add(root.getChildren());

      do {
        final VirtualFile[] files = queue.removeFirst();

        for (VirtualFile file : files) {
          if (!processor.process(file)) return;
          if (file.isDirectory() && directoryFilter.convert(file)) {
            queue.add(file.getChildren());
          }
        }
      } while (!queue.isEmpty());
    }
  }
  public static boolean processFilesRecursively(
      @NotNull VirtualFile root, @NotNull Processor<VirtualFile> processor) {
    if (!processor.process(root)) return false;

    if (root.isDirectory()) {
      final LinkedList<VirtualFile[]> queue = new LinkedList<VirtualFile[]>();

      queue.add(root.getChildren());

      do {
        final VirtualFile[] files = queue.removeFirst();

        for (VirtualFile file : files) {
          if (!processor.process(file)) return false;
          if (file.isDirectory()) {
            queue.add(file.getChildren());
          }
        }
      } while (!queue.isEmpty());
    }

    return true;
  }
  /**
   * Waits for the given configurations to finish, retrying any that qualify to be rerun.
   *
   * @param execution Provided by the plugin.
   * @param patterns List of regular expression patterns used to scan the log to determine if a
   *     build should be rerun.
   * @param retries Mutable map that tracks the number of times a specific configuration has been
   *     retried.
   * @param configurations The configurations that have already been scheduled to run that should be
   *     waited for to finish.
   * @return The worst result of all the runs. If a build was rerun, only the result of the rerun is
   *     considered.
   * @throws InterruptedException
   * @throws IOException
   */
  private Result waitForMatrixRuns(
      MatrixBuild.MatrixBuildExecution execution,
      List<Pattern> patterns,
      Map<MatrixConfiguration, Integer> retries,
      LinkedList<MatrixConfiguration> configurations)
      throws InterruptedException, IOException {
    BuildListener listener = execution.getListener();
    PrintStream logger = listener.getLogger();

    Map<String, String> whyBlockedMap =
        new HashMap<
            String,
            String>(); // keep track of why builds are blocked so we can print unique messages when
    // they change.
    Result finalResult = Result.SUCCESS;
    int iteration = 0;
    boolean continueRetrying = true;
    while (!configurations.isEmpty()) {
      ++iteration;
      MatrixConfiguration configuration = configurations.removeFirst();
      if (isBuilding(execution, configuration, whyBlockedMap)) {
        if (iteration >= configurations.size()) {
          // Every time we loop through all the configurations, sleep for a bit.
          // This is to prevent polling too often while everything is still building.
          iteration = 0;
          Thread.sleep(1000);
        }
        configurations.add(configuration);
        continue;
      }

      Run parentBuild = execution.getBuild();
      MatrixRun matrixRun = configuration.getBuildByNumber(parentBuild.getNumber());
      Result runResult = matrixRun.getResult();
      if (continueRetrying
          && runResult.isWorseOrEqualTo(getWorseThanOrEqualTo())
          && runResult.isBetterOrEqualTo(getBetterThanOrEqualTo())) {
        if (matchesPattern(matrixRun, patterns)) {
          int retriedCount = retries.get(configuration);
          if (retriedCount < getMaxRetries()) {
            ++retriedCount;
            retries.put(configuration, retriedCount);
            // rerun
            String logMessage =
                String.format(
                    "%s was %s. Matched pattern to rerun. Rerunning (%d).",
                    matrixRun, runResult, retriedCount);
            listener.error(logMessage);

            HealedAction action = parentBuild.getAction(HealedAction.class);
            if (action == null) {
              //noinspection SynchronizationOnLocalVariableOrMethodParameter
              synchronized (parentBuild.getActions()) {
                action = parentBuild.getAction(HealedAction.class);
                if (action == null) {
                  action = new HealedAction(matrixRun.getCharset());
                  parentBuild.addAction(action);
                }
              }
            }
            action.addAutoHealedJob(matrixRun);

            MatrixConfiguration parent = matrixRun.getParent();
            if (parent != null) {
              // I'm paranoid about NPEs
              parent.removeRun(matrixRun);
              matrixRun.delete();
            } else {
              LOGGER.severe(
                  "couldn't remove old run, parent was null. This is a Jenkins core bug.");
            }
            scheduleConfigurationBuild(
                execution, configuration, new SelfHealingCause(parentBuild, retriedCount));
            configurations.add(configuration);
            continue;
          } else {
            String logMessage =
                String.format(
                    "%s was %s. Matched pattern to rerun, but the max number of retries (%d) has been met.",
                    matrixRun, runResult, getMaxRetries());
            listener.error(logMessage);
            if (getStopRetryingAfterOneFails()) {
              listener.error("Not retrying any more builds.");
              continueRetrying = false;
            }
          }
        } else {
          String logMessage =
              String.format(
                  "%s was %s. It did not match the pattern to rerun. Accepting result.",
                  matrixRun, runResult);
          logger.println(logMessage);
        }
      }
      notifyEndRun(matrixRun, execution.getAggregators(), execution.getListener());
      finalResult = finalResult.combine(runResult);
    }
    return finalResult;
  }
Beispiel #16
0
 protected boolean isEmpty() {
   return stored.isEmpty() && listeners == null;
 }
Beispiel #17
0
 protected void removeListener(SpaceListener l) {
   if (listeners != null) {
     listeners.remove(l);
     if (listeners.isEmpty()) listeners = null;
   }
 }
  /**
   * Before running <code>Pass pass</code> on <code>SourceJob job</code> make sure that all
   * appropriate scheduling invariants are satisfied, to ensure that all passes of other jobs that
   * <code>job</code> depends on will have already been done.
   */
  protected void enforceInvariants(Job job, Pass pass) throws CyclicDependencyException {
    SourceJob srcJob = job.sourceJob();
    if (srcJob == null) {
      return;
    }

    BarrierPass lastBarrier = srcJob.lastBarrier();
    if (lastBarrier != null) {
      // make sure that _all_ dependent jobs have completed at least up to
      // the last barrier (not just children).
      //
      // Ideally the invariant should be that only the source jobs that
      // job _depends on_ should be brought up to the last barrier.
      // This is work to be done in the future...
      List allDependentSrcs = new ArrayList(srcJob.dependencies());
      Iterator i = allDependentSrcs.iterator();
      while (i.hasNext()) {
        Source s = (Source) i.next();
        Object o = jobs.get(s);
        if (o == COMPLETED_JOB) continue;
        if (o == null) {
          throw new InternalCompilerError("Unknown source " + s);
        }
        SourceJob sj = (SourceJob) o;
        if (sj.pending(lastBarrier.id())) {
          // Make the job run up to the last barrier.
          // We ignore the return result, since even if the job
          // fails, we will keep on going and see
          // how far we get...
          if (Report.should_report(Report.frontend, 3)) {
            Report.report(3, "Running " + sj + " to " + lastBarrier.id() + " for " + srcJob);
          }
          runToPass(sj, lastBarrier.id());
        }
      }
    }

    if (pass instanceof GlobalBarrierPass) {
      // need to make sure that _all_ jobs have completed just up to
      // this global barrier.

      // If we hit a cyclic dependency, ignore it and run the other
      // jobs up to that pass.  Then try again to run the cyclic
      // pass.  If we hit the cycle again for the same job, stop.
      LinkedList barrierWorklist = new LinkedList(jobs.values());

      while (!barrierWorklist.isEmpty()) {
        Object o = barrierWorklist.removeFirst();
        if (o == COMPLETED_JOB) continue;
        SourceJob sj = (SourceJob) o;
        if (sj.completed(pass.id()) || sj.nextPass() == sj.passByID(pass.id())) {
          // the source job has either done this global pass
          // (which is possible if the job was loaded late in the
          // game), or is right up to the global barrier.
          continue;
        }

        // Make the job run up to just before the global barrier.
        // We ignore the return result, since even if the job
        // fails, we will keep on going and see
        // how far we get...
        Pass beforeGlobal = sj.getPreviousTo(pass.id());
        if (Report.should_report(Report.frontend, 3)) {
          Report.report(3, "Running " + sj + " to " + beforeGlobal.id() + " for " + srcJob);
        }

        // Don't use runToPass, since that catches the
        // CyclicDependencyException that we should report
        // back to the caller.
        while (!sj.pendingPasses().isEmpty()) {
          Pass p = (Pass) sj.pendingPasses().get(0);

          runPass(sj, p);

          if (p == beforeGlobal) {
            break;
          }
        }
      }
    }
  }
  public String BFS(Graph g, Vertex start, Vertex end, LinkedList<String> strToParse) {
    String parsed = "";
    LinkedList<VISTriple> q = new LinkedList<VISTriple>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    // System.out.println("parsed: " + parsed);

    q.push(new VISTriple(0, start, ""));
    // System.out.println(q.peek().ver);

    while (!q.isEmpty()) {
      try {
        // reader.readLine();
      } catch (Exception e) {
      }

      VISTriple v = q.removeFirst();
      // System.out.println("WHILE: " + v);

      LinkedList<Edge> successors = new LinkedList<Edge>();
      successors.clear();

      EdgeIterator ei = g.incidentEdges(v.ver);
      // System.out.println("Getting incident edges:");
      while (ei.hasNext()) {
        Edge temp = ei.nextEdge();
        if (g.origin(temp) == v.ver) {
          successors.addFirst(temp);
          // System.out.println(successors.peekFirst().toString());
        }
      }

      if (v.ind >= strToParse.size() && v.ver.equals(end)) {
        // System.out.println("*result: " + v.result);
        return v.result;
      }

      String toFind = "";
      if (v.ind < strToParse.size()) {
        toFind = strToParse.get(v.ind);
      } else toFind = "";

      // System.out.println("toFind: " + toFind);

      for (int i = 0; i < successors.size(); i++) {
        Edge e = successors.get(i);
        EdgeTuple tempET = (EdgeTuple) e.element();
        // System.out.println("tempET: " + tempET);
        if (tempET.lhs.equals("") || tempET.lhs.equals(toFind)) {
          Vertex w = g.destination(e);
          if (tempET.lhs.equals(toFind)) {
            q.addFirst(new VISTriple(v.ind + 1, w, v.result + tempET.rhs));
            // System.out.println("found LHS: " + q.peekFirst());
          } else {
            q.addFirst(new VISTriple(v.ind, w, v.result + tempET.rhs));
            // System.out.println("!found LHS: " + q.peekFirst());
          }
        } // end if
      } // end for
    } // end while
    return "";
  } // end BFS
Beispiel #20
0
    public Writer getErrorReport(
        Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException {
      final Writer logMsg = new StringWriter();
      final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg);
      Writer msg = tee;

      LinkedList<Throwable> stack = getStack();
      String ticket = new Date().toString();

      Map<String, String> props;
      try {
        props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage");
      } catch (javax.naming.NamingException ne) {
        props = Collections.emptyMap();
        log.info(ne);
      }

      if (request != null) {
        {
          msg.append("Headers\n----------\n");
          // request properties
          for (Object name : Collections.list(request.getHeaderNames())) {
            msg.append(
                escape.transform(
                    name + ": " + escape.transform(request.getHeader((String) name)) + "\n"));
          }
        }
        {
          msg.append("\nAttributes\n----------\n");
          Pattern p = requestIgnore;
          if (p == null && props.get("request_ignore") != null) {
            p = Pattern.compile(props.get("request_ignore"));
          }
          for (Object name : Collections.list(request.getAttributeNames())) {
            if (p == null || !p.matcher((String) name).matches()) {
              msg.append(
                  escape.transform(name + ": " + request.getAttribute((String) name) + "\n"));
            }
          }
        }
        if (Boolean.TRUE.equals(showSession)
            || (showSession == null && !"false".equals(props.get("show_session")))) {
          HttpSession ses = request.getSession(false);
          if (ses != null) {
            msg.append("\nSession\n----------\n");
            Pattern p = sessionIgnore;
            if (p == null && props.get("session_ignore") != null) {
              p = Pattern.compile(props.get("session_ignore"));
            }
            for (Object name : Collections.list(ses.getAttributeNames())) {
              if (p == null || !p.matcher((String) name).matches()) {
                msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n"));
              }
            }
          }
        }
      }
      msg.append("\n");
      msg.append("Misc. properties\n----------\n");

      if (request != null) {
        msg.append("method: ").append(escape.transform(request.getMethod())).append("\n");
        msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n");
        msg.append("requesturl: ")
            .append(escape.transform(request.getRequestURL().toString()))
            .append("\n");
      }
      if (Boolean.TRUE.equals(showMMBaseVersion)
          || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) {
        msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n");
      }
      msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n");

      if (request != null) {
        msg.append("Parameters\n----------\n");
        // request parameters
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String name = (String) en.nextElement();
          msg.append(name)
              .append(": ")
              .append(escape.transform(request.getParameter(name)))
              .append("\n");
        }
      }
      msg.append("\nException ")
          .append(ticket)
          .append("\n----------\n\n")
          .append(
              exception != null
                  ? (escape.transform(exception.getClass().getName()))
                  : "NO EXCEPTION")
          .append(": ");

      int wroteCauses = 0;
      while (!stack.isEmpty()) {

        Throwable t = stack.removeFirst();
        // add stack stacktraces
        if (t != null) {
          if (stack.isEmpty()) { // write last message always
            msg = tee;
          }
          String message = t.getMessage();
          if (msg != tee) {
            to.append("\n=== skipped(see log)  : ")
                .append(escape.transform(t.getClass().getName()))
                .append(": ")
                .append(message)
                .append("\n");
          }

          msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message));
          StackTraceElement[] stackTrace = t.getStackTrace();
          for (StackTraceElement e : stackTrace) {
            msg.append("\n        at ").append(escape.transform(e.toString()));
          }
          if (!stack.isEmpty()) {
            msg.append("\n-------caused:\n");
          }
          wroteCauses++;
          if (wroteCauses >= MAX_CAUSES) {
            msg = logMsg;
          }
        }
      }
      // write errors to  log
      if (status == 500) {
        try {
          if (props.get("to") != null && props.get("to").length() > 0) {
            javax.naming.Context initCtx = new javax.naming.InitialContext();
            javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
            Object mailSession = envCtx.lookup("mail/Session");
            Class sessionClass = Class.forName("javax.mail.Session");
            Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType");
            Class messageClass = Class.forName("javax.mail.internet.MimeMessage");
            Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession);
            messageClass
                .getMethod("addRecipients", recipientTypeClass, String.class)
                .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to"));
            messageClass.getMethod("setSubject", String.class).invoke(mail, ticket);
            mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString());
            Class.forName("javax.mail.Transport")
                .getMethod("send", Class.forName("javax.mail.Message"))
                .invoke(null, mail);
            tee.append("\nmailed to (").append(String.valueOf(props)).append(")");
          }

        } catch (Exception nnfe) {
          tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")");
          if (log.isDebugEnabled()) {
            log.debug(nnfe.getMessage(), nnfe);
          }
        }
        log.error("TICKET " + ticket + ":\n" + logMsg);
      }
      return to;
    }
Beispiel #21
0
  public int ai_move(int[][] board) {
    if (running) {
      System.out.println(
          "This AI appears to be running multiple ai_moves simultaneously. That can't be right.");
    }
    running = true;
    try {
      // System.out.println(2 + Math.random());
      if (recording) {
        if (out == null) {
          try {
            int ind = 1;
            File f = null;
            while (true) {
              try {
                Scanner sc = new Scanner(new File("AIReplay" + ind + ".txt"));
                ind++;
              } catch (Exception e) {
                break;
              }
            }
            out = new PrintWriter(new File("AIReplay" + ind + ".txt"));
            filename = "AIReplay" + ind + ".txt";
            out.println("AI Version: " + VERSION);
          } catch (Exception e) {
            System.out.println("Could not write to file.");
          }
        }
        fprint(board);
      }
      // if (fml == null) fml = new PrintWriter (new File("fmldebug.txt"));
      if (thisAIIsCheating && max(board) < 8) {
        board[0][0] = GameGUI.win_target;
      }
      if (debug2) sc.nextLine();
      if (debug2) print(board);
      if (debug) System.out.println("New cycle.");
      if (debug) sc.nextLine();
      if (dumbai) name += "Dumby";
      turn++;
      if (!queue.isEmpty()) {
        int temp = queue.removeFirst();
        if (temp > 0) {
          running = false;
          return temp;
        }
      }
      int boardsum = 0;
      for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
          boardsum += board[i][j];
        }
      }
      boolean report = debug;
      /*if (Math.random() < 0.0001) {
      report = true;
      for (int i = 0; i < 4; i++) {
      	System.out.println(Arrays.toString(board[i]));
      }
      for (int i = 0; i < 4; i++) {
      	System.out.println(movable(board, i));
      }
      System.out.println();
      sc.nextLine();
      }*/
      if (dumbai) {
        if (!name.endsWith("Dumby")) name += "Dumby";
        System.out.println(turn);
        running = false;
        if (turn % 600 == 599) return KeyEvent.VK_DOWN;
        if (turn % 3 == 0) return KeyEvent.VK_UP;
        if (turn % 6 < 3) return KeyEvent.VK_LEFT;
        return KeyEvent.VK_RIGHT;
      } else {
        if (name.indexOf(".") < 0) name += VERSION;
      }
      // gamestart processing
      /*if(board[0][0] == 0) {
      	if (board[1][0] > board[0][1]) {
      		return KeyEvent.VK_UP;
      	}
      	if (board[1][0] < board[0][1]) {
      		return KeyEvent.VK_LEFT;
      	}
      	if (Math.random() < 0.5) return KeyEvent.VK_UP;
      	return KeyEvent.VK_LEFT;
      }*/
      long[] pref = {10, 20, 1, 1}; // LEFT, UP, RIGHT, DOWN

      // check if moving right/down is safe
      boolean occupied = true;

      for (int i = 0; i < 4; i++) {
        if (board[0][i] == 0) occupied = false;
        if (i < 3 && board[0][i] == board[0][i + 1]) occupied = false;
      }
      if (!occupied) {
        // pref[2] -= 100000000;
      }
      occupied = true;
      for (int i = 0; i < 4; i++) {
        if (board[i][0] == 0) occupied = false;
        if (i < 3 && board[i][0] == board[i + 1][0]) occupied = false;
      }
      if (!occupied) {
        // pref[3] -= 100000000;
      }

      pref[0] += 5;
      pref[1] += 5;

      // System.out.println(6 + Math.random());
      // simulate
      sum_board = sum(board);
      delta_sum_board_7over8 = delta(sum_board * 7 / 8);
      if (debug) print(board);
      max_depth = 0;
      for (int m = 0; m < 4; m++) {
        if (debug) System.out.println("Now testing move: " + m);
        int[][] sim = simulate(board, m);
        if (Arrays.deepEquals(sim, board)) {
          if (out != null) out.println("Move " + m + " invalid; skipping");
          if (GameGUI.out != null) GameGUI.out.println("Move " + m + " invalid; skipping");
          continue;
        }
        long worst = (long) 1999999999 * 1000000000;
        long avg = 0;
        int numt = 0;
        for (int i = 0; i < 4; i++) {
          for (int j = 0; j < 4; j++) {
            if (sim[i][j] > 0) continue;
            sim[i][j] = 2;
            long temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1);
            if (temp < worst) worst = temp;
            avg += 9 * temp;
            sim[i][j] = 4;
            temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1);
            if (temp < worst) worst = temp;
            avg += temp;
            sim[i][j] = 0;
            numt += 10;
          }
        }
        if (countBlank(sim) == 0) {
          long temp = predictor(sim, iter_max / (int) pow((countBlank(sim) + 1), 2), 1);
          if (temp < worst) worst = temp;
          avg += temp;
          numt++;
        }
        avg /= numt;
        worst = (worst_weight * worst + avg) / (worst_weight + 1);
        if (countBlank(sim) >= 8 && max(board) < 64) worst = avg;
        if (debug || debug2) System.out.println("Move " + m + " final eval: " + worst);
        if (out != null) out.println("Move " + m + " final eval: " + worst);
        if (GameGUI.out != null) GameGUI.out.println("Move " + m + " final eval: " + worst);
        pref[m] += worst;
      }
      if (debug2) System.out.println("Max depth: " + max_depth);
      if (out != null) out.println("Max depth: " + max_depth);
      if (GameGUI.out != null) GameGUI.out.println("Max depth: " + max_depth);

      // System.out.println(5 + Math.random());
      // process output
      int[] dir = new int[4];
      dir[0] = KeyEvent.VK_LEFT;
      dir[1] = KeyEvent.VK_UP;
      dir[2] = KeyEvent.VK_RIGHT;
      dir[3] = KeyEvent.VK_DOWN;
      if (report) System.out.println("Pref: " + Arrays.toString(pref));
      for (int i = 0; i < 4; i++) {
        int best = 0;
        for (int j = 0; j < 4; j++) {
          if (pref[j] > pref[best]) {
            best = j;
          }
        }
        pref[best] = Long.MIN_VALUE;
        if (movable(board, best)) {
          if (report) {
            report = false;
            if (debug) System.out.println("Chosen: " + best);
            if (debug) sc.nextLine();
          }
          // if (pref[best] < -50000000) queue.add(best - 2);
          running = false;
          return dir[best];
        }
        // System.out.println("Unmovable: " + best);
        // System.out.println("Pref: " + Arrays.toString(pref));
      }
      System.out.println("???");
      for (int i = 0; i < 4; i++) {
        System.out.println(Arrays.toString(board[i]));
      }
      // sc.nextLine();
    } catch (Exception e) {
      e.printStackTrace();
    }
    running = false;
    return KeyEvent.VK_LEFT;
  }