Example #1
0
 /* Creates tree by mapping the array left to right, top to bottom. */
 public static TreeNode createTreeFromArray(int[] array) {
   if (array.length > 0) {
     TreeNode root = new TreeNode(array[0]);
     java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();
     queue.add(root);
     boolean done = false;
     int i = 1;
     while (!done) {
       TreeNode r = (TreeNode) queue.element();
       if (r.left == null) {
         r.left = new TreeNode(array[i]);
         i++;
         queue.add(r.left);
       } else if (r.right == null) {
         r.right = new TreeNode(array[i]);
         i++;
         queue.add(r.right);
       } else {
         queue.remove();
       }
       if (i == array.length) done = true;
     }
     return root;
   } else {
     return null;
   }
 }
Example #2
0
 public Iterator<Integer> askServerForMore() {
   mCurrConf = mUnreadConfs.element();
   Log.i(
       TAG,
       "PrefetchNextUnread askServerForMore mCurrConf: "
           + mCurrConf
           + " mCurrConfLocalNo: "
           + mCurrConfLastRead);
   final Membership membership;
   final TextMapping tm;
   final List<Integer> maybeUnread = new ArrayList<Integer>();
   try {
     membership = mKom.getSession().queryReadTexts(mKom.getUserId(), mCurrConf, true);
     mCurrConfLastRead = lastTextReadFrom(membership, mCurrConfLastRead);
     Log.i(TAG, "PrefetchNextUnread mCurrConfLastRead: " + mCurrConfLastRead);
     final UConference conf = mKom.getSession().getUConfStat(mCurrConf);
     if (mCurrConfLastRead < conf.getHighestLocalNo()) {
       tm = mKom.getSession().localToGlobal(mCurrConf, mCurrConfLastRead + 1, ASK_AMOUNT);
       Log.i(
           TAG,
           "PrefetchNextUnread asked for "
               + ASK_AMOUNT
               + " texts in conf "
               + mCurrConf
               + ", got "
               + tm.size());
     } else {
       Log.i(TAG, "PrefetchNextUnread too high local number in " + mCurrConf);
       tm = null;
     }
   } catch (final IOException e) {
     Log.i(TAG, "PrefetchNextUnread IOException");
     return Collections.<Integer>emptyList().iterator();
   }
   while (tm != null && tm.hasMoreElements()) {
     final int globalNo = (Integer) tm.nextElement();
     final int localNo = tm.local();
     if (!membership.isRead(localNo)) {
       Log.i(
           TAG, "PrefetchNextUnread adding localNo " + localNo + " (globalNo " + globalNo + ")");
       maybeUnread.add(globalNo);
     }
     mCurrConfLastRead = Math.max(mCurrConfLastRead, localNo);
   }
   if (tm == null || !tm.laterTextsExists()) {
     Log.i(TAG, "PrefetchNextUnread no later texts exists in conf " + mCurrConf);
     mUnreadConfs.remove();
     mCurrConfLastRead = -1;
   }
   return maybeUnread.iterator();
 }
  public void setSendImg(long groupId, int[] msgIds) {
    Message msg;
    mConv = JMessageClient.getGroupConversation(groupId);
    for (int msgId : msgIds) {
      msg = mConv.getMessage(msgId);
      if (msg != null) {
        mMsgList.add(msg);
        incrementStartPosition();
        mMsgQueue.offer(msg);
      }
    }

    Message message = mMsgQueue.element();
    sendNextImgMsg(message);
    notifyDataSetChanged();
  }
  // @include
  public static Pair<Integer, Integer>[] findStableAssignment(
      int[][] professorPreference, int[][] studentPreference) {

    // stores currently free students.
    Queue<Integer> freeStudent = new LinkedList<>();
    for (int i = 0; i < studentPreference.length; ++i) {
      freeStudent.add(i);
    }

    // Records the professors that each student have asked.
    int[] studentPrefIdx = new int[studentPreference.length];
    Arrays.fill(studentPrefIdx, 0);

    // Records the current student choice for each professor.
    int[] professorChoice = new int[professorPreference.length];
    Arrays.fill(professorChoice, -1);

    while (!freeStudent.isEmpty()) {
      int i = freeStudent.element(); // free student.
      int j = studentPreference[i][studentPrefIdx[i]]; // target professor.
      if (professorChoice[j] == -1) { // this professor is free.
        professorChoice[j] = i;
        freeStudent.remove();
      } else { // this professor has student now.
        int originalPref = find(professorPreference[j], professorChoice[j]);
        int newPref = find(professorPreference[j], i);
        if (newPref < originalPref) { // this professor prefers the new one.
          freeStudent.add(professorChoice[j]);
          professorChoice[j] = i;
          freeStudent.remove();
        }
      }
      ++studentPrefIdx[i];
    }

    Pair<Integer, Integer>[] matchResult = new Pair[professorChoice.length];
    for (int j = 0; j < professorChoice.length; ++j) {
      matchResult[j] = new Pair<>(professorChoice[j], j);
    }
    return matchResult;
  }
  public void serialByteReceivedEvent(ByteFifo fifo) {
    readResponseLock.lock();

    serialInUse.lock();
    byte[] response = fifo.dequeueLine();
    int responseLength = response.length;
    serialInUse.unlock();

    // 0 is now an acceptable value; it merely means that we timed out
    // waiting for input
    if (responseLength < 0) {
      // This signifies EOF. FIXME: How do we handle this?
      Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured");
      readResponseLock.unlock();
      return;
    } else if (responseLength != 0) {
      String line;
      try {
        // convert to string and remove any trailing \r or \n's
        line = new String(response, 0, responseLength, "US-ASCII").trim().toLowerCase();
      } catch (UnsupportedEncodingException e) {
        Base.logger.severe("US-ASCII required. Terminating.");
        readResponseLock.unlock();
        throw new RuntimeException(e);
      }

      // System.out.println("received: " + line);
      if (debugLevel > 1) Base.logger.info("<< " + line);

      if (line.length() == 0) Base.logger.fine("empty line received");
      else if (line.startsWith("echo:")) {
        // if echo is turned on relay it to the user for debugging
        Base.logger.info(line);
      } else if (line.startsWith("ok t:") || line.startsWith("t:")) {
        Pattern r = Pattern.compile("t:([0-9\\.]+)");
        Matcher m = r.matcher(line);
        if (m.find()) {
          String temp = m.group(1);

          machine.currentTool().setCurrentTemperature(Double.parseDouble(temp));
        }
        r = Pattern.compile("^ok.*b:([0-9\\.]+)$");
        m = r.matcher(line);
        if (m.find()) {
          String bedTemp = m.group(1);
          machine.currentTool().setPlatformCurrentTemperature(Double.parseDouble(bedTemp));
        }
      } else if (line.startsWith("ok c:") || line.startsWith("c:")) {
        Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)");
        Matcher m = r.matcher(line);
        if (m.find()) {
          double x = Double.parseDouble(m.group(1));
          double y = Double.parseDouble(m.group(2));
          double z = Double.parseDouble(m.group(3));
          // super to avoid parroting back a G92
          try {
            super.setCurrentPosition(new Point5d(x, y, z));
            // Base.logger.fine("setting currentposition to:"+x+","+y+","+z+".");
          } catch (RetryException e) {
            // do or do not, there is no retry
          }
        }
      }
      if (line.startsWith("ok")) {

        synchronized (okReceived) {
          okReceived.set(true);
          okReceived.notifyAll();
        }

        bufferLock.lock();
        // Notify the thread waitining in this gcode's sendCommand method that the gcode has been
        // received.
        if (buffer.isEmpty()) {
          Base.logger.severe("Received OK with nothing queued!");
        } else {
          String notifier = buffer.removeLast();
          if (debugLevel > 1) Base.logger.info("FW Accepted: " + notifier);
          synchronized (notifier) {
            notifier.notifyAll();
          }
        }
        bufferLock.unlock();

        synchronized (bufferLock) {
          /*let any sendCommand method waiting to send know that the buffer is
          now smaller and may be able to fit their command.*/
          bufferLock.notifyAll();
        }
      }

      // old arduino firmware sends "start"
      else if (line.contains("start")) {
        // Reset line number first in case gcode is sent below
        lineNumber.set(-1);

        boolean active = !buffer.isEmpty();
        flushBuffer();

        if (isInitialized()) {
          sendInitializationGcode(false);

          // If there were outstanding commands try to abort any print in progress.
          // This is a poor test:  but do we know if we're printing at this level?
          // tried setInitialized(false); but that didn't work well
          if (active) {
            Base.logger.severe("Firmware reset with active commands!");
            setError("Firmware reset with active commands!");
          }
        }
        if (okAfterStart) {
          // firmware sends "ok" after start, put something here to consume it:
          bufferLock.lock();
          buffer.addLast(";start-ok");
          bufferLock.unlock();
        }

        // todo: set version
        synchronized (startReceived) {
          startReceived.set(true);
          startReceived.notifyAll();
        }

        // Wake up connect task to try again
        synchronized (okReceived) {
          okReceived.set(false);
          okReceived.notifyAll();
        }

      } else if (line.startsWith("extruder fail")) {
        setError("Extruder failed:  cannot extrude as this rate.");

      } else if (line.startsWith("resend:") || line.startsWith("rs ")) {
        // Bad checksum, resend requested
        Matcher badLineMatch = resendLinePattern.matcher(line);

        // Is it a Dud M or G code?
        String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1);

        if (badLineMatch.find()) {
          int badLineNumber = Integer.parseInt(badLineMatch.group(1));
          if (debugLevel > 1)
            Base.logger.warning("Received resend request for line " + badLineNumber);

          Queue<String> resend = new LinkedList<String>();
          boolean found = false;
          // Search backwards for the bad line in our buffer.
          // Firmware flushed everything after this line, so
          // build a queue of lines to resend.
          bufferLock.lock();
          lineSearch:
          while (!buffer.isEmpty()) {
            String bufferedLine = buffer.removeLast();
            if (debugLevel > 1) Base.logger.info("Searching: " + bufferedLine);
            int bufferedLineNumber =
                Integer.parseInt(
                    getRegexMatch(gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1));
            if (dudLetter != null && bufferedLineNumber == badLineNumber) {
              Base.logger.info("Dud " + dudLetter + " code: Dropping " + bufferedLine);
              synchronized (bufferedLine) {
                bufferedLine.notifyAll();
              }
              found = true;
              break lineSearch;
            }
            resend.add(bufferedLine);
            if (bufferedLineNumber == badLineNumber) {
              found = true;
              break lineSearch;
            }
          }
          if (okAfterResend) {
            // firmware sends "ok" after resend, put something here to consume it:
            buffer.addLast(";resend-ok");
          }
          bufferLock.unlock();

          if (!found) {
            int restartLineNumber =
                Integer.parseInt(
                    getRegexMatch(gcodeLineNumberPattern, resend.element().toLowerCase(), 1));
            Base.logger.severe(
                "resend for line "
                    + badLineNumber
                    + " not in our buffer.  Resuming from "
                    + restartLineNumber);
            this.resendCommand(applyChecksum("N" + (restartLineNumber - 1) + " M110"));
          }
          // resend the lines
          while (!resend.isEmpty()) {
            String bufferedLine = resend.remove();
            this.resendCommand(bufferedLine);
          }
        } else {
          // Malformed resend line request received. Resetting the line number
          Base.logger.warning(
              "malformed line resend request, "
                  + "resetting line number. Malformed Data: \n"
                  + line);
          this.resendCommand(applyChecksum("N" + (lineNumber.get() - 1) + " M110"));
        }

      } else if (line.startsWith("t:") || line.startsWith("c:")) {
        // temperature, position handled above
      } else {
        Base.logger.severe("Unknown: " + line);
      }
    }

    readResponseLock.unlock();
  }
  // 处理图片
  private void handleImgMsg(final Message msg, final ViewHolder holder, final int position) {
    final ImageContent imgContent = (ImageContent) msg.getContent();
    // 先拿本地缩略图
    final String path = imgContent.getLocalThumbnailPath();
    // 接收图片
    if (msg.getDirect() == MessageDirect.receive) {
      if (path == null) {
        // 从服务器上拿缩略图
        imgContent.downloadThumbnailImage(
            msg,
            new DownloadCompletionCallback() {
              @Override
              public void onComplete(int status, String desc, File file) {
                if (status == 0) {
                  Picasso.with(mContext).load(file).into(holder.picture);
                }
              }
            });
      } else {
        setPictureScale(path, holder.picture);
        Picasso.with(mContext).load(new File(path)).into(holder.picture);
      }
      // 群聊中显示昵称
      if (mIsGroup) {
        holder.displayName.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(msg.getFromUser().getNickname())) {
          holder.displayName.setText(msg.getFromUser().getUserName());
        } else {
          holder.displayName.setText(msg.getFromUser().getNickname());
        }
      }

      switch (msg.getStatus()) {
        case receive_fail:
          holder.picture.setImageResource(R.drawable.jmui_fetch_failed);
          break;
        default:
      }
      // 发送图片方,直接加载缩略图
    } else {
      try {
        setPictureScale(path, holder.picture);
        Picasso.with(mContext).load(new File(path)).into(holder.picture);
      } catch (NullPointerException e) {
        Picasso.with(mContext).load(R.drawable.jmui_picture_not_found).into(holder.picture);
      }

      final Animation sendingAnim = AnimationUtils.loadAnimation(mContext, R.anim.jmui_rotate);
      LinearInterpolator lin = new LinearInterpolator();
      sendingAnim.setInterpolator(lin);
      // 检查状态
      switch (msg.getStatus()) {
        case send_success:
          holder.sendingIv.clearAnimation();
          holder.sendingIv.setVisibility(View.GONE);
          holder.picture.setAlpha(1.0f);
          holder.progressTv.setVisibility(View.GONE);
          holder.resend.setVisibility(View.GONE);
          break;
        case send_fail:
          holder.sendingIv.clearAnimation();
          holder.sendingIv.setVisibility(View.GONE);
          holder.picture.setAlpha(1.0f);
          holder.progressTv.setVisibility(View.GONE);
          holder.resend.setVisibility(View.VISIBLE);
          break;
        case send_going:
          sendingImage(holder, sendingAnim, msg);
          break;
        default:
          holder.picture.setAlpha(0.75f);
          holder.sendingIv.setVisibility(View.VISIBLE);
          holder.sendingIv.startAnimation(sendingAnim);
          holder.progressTv.setVisibility(View.VISIBLE);
          holder.progressTv.setText("0%");
          holder.resend.setVisibility(View.GONE);
          // 从别的界面返回聊天界面,继续发送
          if (!mMsgQueue.isEmpty()) {
            Message message = mMsgQueue.element();
            if (message.getId() == msg.getId()) {
              Log.d(TAG, "Start sending message");
              JMessageClient.sendMessage(message);
              mSendMsgId = message.getId();
              sendingImage(holder, sendingAnim, message);
            }
          }
      }
      // 点击重发按钮,重发图片
      holder.resend.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View arg0) {
              showResendDialog(holder, sendingAnim, msg);
            }
          });
    }
    if (holder.picture != null) {

      // TODO 点击图片事件

      holder.picture.setOnLongClickListener(
          new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
              String name = msg.getFromUser().getUserName();
              OnClickListener listener =
                  new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                      switch (v.getId()) {
                        case R.id.copy_msg_btn:
                          break;
                        case R.id.forward_msg_btn:
                          mDialog.dismiss();
                          break;
                        case R.id.delete_msg_btn:
                          mConv.deleteMessage(msg.getId());
                          mMsgList.remove(position);
                          notifyDataSetChanged();
                          mDialog.dismiss();
                          break;
                      }
                    }
                  };
              mDialog = DialogCreator.createLongPressMessageDialog(mContext, name, true, listener);
              mDialog.show();
              mDialog
                  .getWindow()
                  .setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
              return true;
            }
          });
    }
  }
Example #7
0
 @Override
 public E element() {
   return queue.element();
 }
Example #8
0
 public void testElement() {
   forward.element();
   assertEquals("[element]", getCalls());
 }
Example #9
0
 /** {@inheritDoc} */
 public E element() {
   return queue.element();
 }