Пример #1
0
 private void next() {
   int index = mMediaList.indexOf(mCurrentMedia);
   mPrevious.push(mCurrentMedia);
   if (mRepeating == RepeatType.Once) mCurrentMedia = mMediaList.get(index);
   else if (mShuffling && mPrevious.size() < mMediaList.size()) {
     while (mPrevious.contains(
         mCurrentMedia = mMediaList.get((int) (Math.random() * mMediaList.size())))) ;
   } else if (!mShuffling && index < mMediaList.size() - 1) {
     mCurrentMedia = mMediaList.get(index + 1);
   } else {
     if (mRepeating == RepeatType.All && mMediaList.size() > 0) mCurrentMedia = mMediaList.get(0);
     else {
       stop();
       return;
     }
   }
   if (mLibVLCPlaylistActive) {
     if (mRepeating == RepeatType.None) mLibVLC.next();
     else if (mRepeating == RepeatType.Once) mLibVLC.playIndex(index);
     else mLibVLC.playIndex(mMediaList.indexOf(mCurrentMedia));
   } else {
     mLibVLC.readMedia(mCurrentMedia.getLocation(), true);
   }
   mHandler.sendEmptyMessage(SHOW_PROGRESS);
   setUpRemoteControlClient();
   showNotification();
   updateWidget(this);
   updateRemoteControlClientMetadata();
   saveCurrentMedia();
 }
  public void writeNN(String source, String target, boolean flag) {
    this.loadCorpus(source, target);
    try {
      Writer bw =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source + ".nn"), "UTF-8"));

      Writer bw1 =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target + ".nn"), "UTF-8"));
      if (flag)
        for (int i = 0; i < nelist.size(); i++) {
          String ne[] = nelist.get(i).split("\t");

          bw.write(this.formatStringCausal(ne[0]) + "\n");
          bw1.write(this.formatStringCausal(ne[1]) + "\n");
          bw.flush();
          bw1.flush();
        }
      else
        for (int i = 0; i < nelist.size(); i++) {
          String ne[] = nelist.get(i).split("\t");

          bw.write(ne[0] + "\n");
          bw1.write(ne[1] + "\n");
          bw.flush();
          bw1.flush();
        }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  @Override
  public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
    if (mProgressDialog.isShowing()) {
      // should always be showing here
      mProgressDialog.dismiss();
    }

    // add our list of completed uploads to "completed"
    // and remove them from our toSend list.
    ArrayList<Long> workingSet = new ArrayList<Long>();
    Collections.addAll(workingSet, mInstancesToSend);
    if (doneSoFar != null) {
      Set<String> uploadedInstances = doneSoFar.keySet();
      Iterator<String> itr = uploadedInstances.iterator();

      while (itr.hasNext()) {
        Long removeMe = Long.valueOf(itr.next());
        boolean removed = workingSet.remove(removeMe);
        if (removed) {
          Log.i(t, removeMe + " was already sent, removing from queue before restarting task");
        }
      }
      mUploadedInstances.putAll(doneSoFar);
    }

    // and reconstruct the pending set of instances to send
    Long[] updatedToSend = new Long[workingSet.size()];
    for (int i = 0; i < workingSet.size(); ++i) {
      updatedToSend[i] = workingSet.get(i);
    }
    mInstancesToSend = updatedToSend;

    mUrl = url.toString();
    showDialog(AUTH_DIALOG);
  }
Пример #4
0
  // Generated from:
  // org.dmd.dms.meta.MetaComplexTypeFormatter.dumpComplexType(MetaComplexTypeFormatter.java:168)
  void initialize(String initialInput) throws DmcValueException {
    ArrayList<ParsedNameValuePair> nvp = ComplexTypeSplitter.parse(initialInput);

    if (nvp.size() < requiredParts)
      throw (new DmcValueException("Missing required values for complex type: Part"));

    type = DmcTypeTypeDefinitionREFSTATIC.instance.typeCheck(nvp.get(0).getValue());
    name = DmcTypeStringSTATIC.instance.typeCheck(nvp.get(1).getValue());
    description = DmcTypeStringSTATIC.instance.typeCheck(nvp.get(2).getValue());

    if (nvp.size() > requiredParts) {
      for (int i = 3; i < nvp.size(); i++) {
        if (nvp.get(i).getName() == null) {
          if (nvp.get(i).getValue() == null)
            throw (new DmcValueException(
                "Expecting a partname=\"some value\" in complex type: Part"));
          else
            throw (new DmcValueException(
                "Expecting a partname=\"" + nvp.get(i).getValue() + "\" in complex type: Part"));
        }
        if (nvp.get(i).getName().equals("quoted"))
          quoted = DmcTypeBooleanSTATIC.instance.typeCheck(nvp.get(i).getValue());
        else if (nvp.get(i).getName().equals("multivalued"))
          multivalued = DmcTypeBooleanSTATIC.instance.typeCheck(nvp.get(i).getValue());
        else if (nvp.get(i).getName().equals("weakref"))
          weakref = DmcTypeBooleanSTATIC.instance.typeCheck(nvp.get(i).getValue());
        else if (nvp.get(i).getName().equals("greedy"))
          greedy = DmcTypeBooleanSTATIC.instance.typeCheck(nvp.get(i).getValue());
        else {
          throw (new DmcValueException(
              "Unknown field for complex type Part: " + nvp.get(i).getName()));
        }
      }
    }
  }
Пример #5
0
  /*
   * aka. addNeuron ()
   */
  public int addNode(int historicalID) {
    Gene randLink;

    do {
      randLink = links.get(rand.nextInt(links.size()));
    } while (randLink.isDisabled());
    double[] from = getNeuronPos(randLink.getFrom());
    double[] to = getNeuronPos(randLink.getTo());

    int minx = sm.getCornerOffset() + sm.getWidth() * (sm.getSmallTileSize() + 2) + 2;
    if (from[0] < minx) {
      from[0] = minx;
    }

    randLink.setDisabled(true);

    int neuralID = neurons.size() + numInputs;
    neurons.add(new Neuron((from[0] + to[0]) / 2, (int) (from[1] + to[1]) / 2));

    // (int from_, int to_, double weight_, int histID_, boolean negative_, boolean disabled_
    addLink(randLink.getFrom(), neuralID, 1.0, historicalID, false);
    addLink(neuralID, randLink.getTo(), randLink.getWeight(), historicalID + 1, false);

    bubbleSortNeurons();

    return historicalID + 2;
  }
  public UnaryDerivation /*@Nullable*/[] instantiate(VarInfo vi) {
    // System.out.println("SequenceMinMaxSumFactory.instantiate(" + vi.name + ")");

    if (vi.rep_type != ProglangType.INT_ARRAY) return null;
    if (!vi.type.isArray()) return null;
    if (!vi.type.elementIsIntegral() && !vi.type.elementIsFloat()) return null;
    if (vi.type.base() == "char") // interned
    return null;
    // Should be reversed at some point; for now, will improve runtime.
    if (Daikon.output_format != OutputFormat.DAIKON) return null;

    ArrayList<UnaryDerivation> result = new ArrayList<UnaryDerivation>(3);
    if (SequenceMin.dkconfig_enabled) {
      result.add(new SequenceMin(vi));
    }
    if (SequenceMax.dkconfig_enabled) {
      result.add(new SequenceMax(vi));
    }
    if (SequenceSum.dkconfig_enabled) {
      result.add(new SequenceSum(vi));
    }

    if (result.size() == 0) {
      return null;
    }

    return result.toArray(new UnaryDerivation[result.size()]);
  }
Пример #7
0
  public static List<String> findTopKWinner(int time, Vector<LogEntry> logs, int k) {
    List<String> result = new ArrayList<String>();

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (LogEntry log : logs) {
      if (log.time <= time) {
        if (map.containsKey(log.candidate)) map.put(log.candidate, map.get(log.candidate) + 1);
        else map.put(log.candidate, 1);
      }
    }

    ArrayList<Integer> a = new ArrayList<Integer>();
    for (String str : map.keySet()) a.add(map.get(str));

    // find top K in a

    // method1: Using PriorityQuene.  time complexity: (nlgn+k)

    // method2: Using quick select

    quickSelect(a, 0, a.size() - 1, a.size() - k + 1);
    System.out.println(a);

    for (int i = a.size() - k; i < a.size(); i++) {
      int value = a.get(i);
      for (String str : map.keySet()) {
        if (map.get(str) == value) result.add(str);
      }
    }

    return result;
  }
Пример #8
0
 /**
  * 创建者:仲瑞庆 功能: 参数: 返回: 例外: 日期:(2001-6-19 下午 3:27) 修改日期,修改人,修改原因,注释标志:
  *
  * @return nc.vo.ic.pub.bill.FreeVO
  */
 public FreeVO getFreeVO() {
   FreeVO fvoFVO = new FreeVO();
   if ((m_alFreeItemID != null)
       && (m_alFreeItemID.size() == 10)
       && (m_alFreeItemReturnName != null)
       && (m_alFreeItemReturnName.size() >= 10)
       && (m_alFreeItemReturnValue != null)
       && (m_alFreeItemReturnValue.size() >= 10)) {
     for (int i = 1; i <= 10; i++) {
       fvoFVO.setAttributeValue("vfreeid" + Integer.toString(i).trim(), m_alFreeItemID.get(i - 1));
       fvoFVO.setAttributeValue(
           "vfreename" + Integer.toString(i).trim(), m_alFreeItemReturnName.get(i - 1));
       fvoFVO.setAttributeValue(
           "vfree" + Integer.toString(i).trim(), m_alFreeItemReturnValue.get(i - 1));
       // fvoFVO.setAttributeValue(
       // "vfreevalue" + Integer.toString(i).trim(),
       // m_alFreeItemReturnValueName.get(i - 1));
     }
   } else {
     for (int i = 1; i <= 10; i++) {
       fvoFVO.setAttributeValue("vfreeid" + Integer.toString(i).trim(), null);
       fvoFVO.setAttributeValue("vfreename" + Integer.toString(i).trim(), null);
       fvoFVO.setAttributeValue("vfree" + Integer.toString(i).trim(), null);
       // fvoFVO.setAttributeValue("vfreevalue" +
       // Integer.toString(i).trim(), null);
     }
   }
   fvoFVO.setAttributeValue("vfree0", this.getText() == null ? null : this.getText().trim());
   return fvoFVO;
 }
Пример #9
0
  // A segment is added to an area if it has at least 1 common position with the area
  // return true if new segment added or already existing
  // return false if new segment can't be added.
  public boolean addSegment(SGSegment s) {
    boolean added = false;

    if (s == null) {
      SGTools.Log1(this, "Can't add null segment to WoS !");
      return false;
    }

    int i = 0;
    while (i < rideAreas.size() && added == false) {
      added = rideAreas.get(i).addSegment(s);
      i++;
    }

    if (added == true) {
      // Successfully added ==> Need to check if can be added to another area.
      // If yes ==> merge areas
      boolean found = false;
      for (; i < rideAreas.size(); i++) {
        found = rideAreas.get(i).addSegment(s);
        if (found == true) {
          // the new segment matches a second area ==> need to merge !
          // TODO: merge areas
        }
      }
    } else {
      // Not added ==> create new ride area
    }
    return true;
  }
Пример #10
0
 public String[] getElements(String key) {
   ArrayList<String> result = new ArrayList<String>();
   for (int i = 0; i < values.size(); i++) {
     if (values.get(i).getType().getURI().equals(key)) result.add(values.get(i).getValue());
   }
   return result.toArray(new String[result.size()]);
 }
Пример #11
0
 /** @return the uncompressed array */
 public int[] toArray() {
   int[] returnArray;
   int counter = 0;
   // determine size of array
   for (int i = 0; i < compressedSequence.size(); i++) {
     counter += compressedSequence.get(i).getNumber();
   }
   returnArray = new int[counter];
   // adding in each value
   // counter is reused, because i like that word
   int innerCounter = 0;
   int outerCounter = 0;
   for (int i = 0; i < compressedSequence.size(); i++) {
     outerCounter += innerCounter;
     innerCounter = 0;
     for (int j = 0; j < compressedSequence.get(i).getNumber(); j++) {
       //	System.out.println(i+" "+j+" "+outerCounter);
       returnArray[i + j + outerCounter] = compressedSequence.get(i).getValue();
       if (j > 0) {
         innerCounter++;
       }
     }
   }
   return returnArray;
 }
Пример #12
0
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

      String filterString = constraint.toString().toLowerCase();

      FilterResults results = new FilterResults();

      final ArrayList<WeatherInfo> list = data;

      int count = list.size();
      final ArrayList<WeatherInfo> weatherInfos = new ArrayList<>(count);

      WeatherInfo filterableObject;

      for (int i = 0; i < count; i++) {
        filterableObject = list.get(i);
        if (filterableObject.getName().toLowerCase().contains(filterString)) {
          weatherInfos.add(filterableObject);
        }
      }

      results.values = weatherInfos;
      results.count = weatherInfos.size();
      return results;
    }
Пример #13
0
 public Cell randomAvailableCell() {
   ArrayList<Cell> availableCells = getAvailableCells();
   if (availableCells.size() >= 1) {
     return availableCells.get((int) Math.floor(Math.random() * availableCells.size()));
   }
   return null;
 }
  private void checkHashtag(String hashtag) {

    hashtag = hashtag.replace("#", "");
    hashtag = hashtag.replace(" ", "");

    if (hashtag.length() > 0) {

      if (hashtags.size() < 5.0) {

        Log.d("postText final ", hashtag);

        if (hashtags.size() == 0) {}
        hashtags.add(0, "#" + hashtag);

      } else {
        Toast.makeText(
                getActivity().getApplicationContext(),
                "Only 5 Hashtags allowed.",
                Toast.LENGTH_SHORT)
            .show();
      }

      postText.setText("");
      checkHeader();
    }
    adapter.notifyDataSetChanged();
  }
  /**
   * find the grade of a particular topic based on its difficulty level
   *
   * @param userId
   * @param topic
   * @param difficulty
   * @return averageQuizGrade
   * @throws Exception
   */
  public static double findTopicDifficultyGrade(int userId, String topic, String difficulty)
      throws Exception {
    QuizAttempt quizAttempt = new QuizAttempt();
    ArrayList<Integer> userQuizIds = quizAttempt.getUserQuizIds(userId);

    ArrayList<Double> userQuizGrades = new ArrayList<Double>();

    for (int i = 0; i < userQuizIds.size(); i++) {
      QuizSlot quizSlot = new QuizSlot();
      // get the question ids of questions belonging to a particular quiz
      ArrayList<Integer> questionIds =
          quizSlot.getDifficultyAndTopicWiseQuestionIdsOfAQuiz(
              userQuizIds.get(i), topic, difficulty);

      if (questionIds.size() > 0) {
        double quizGrade = Grade.findQuizGrade(questionIds, userId);

        userQuizGrades.add(quizGrade);
      }
    }

    double quizGrade = 0;

    for (int i = 0; i < userQuizGrades.size() - 1; i++) {
      quizGrade += userQuizGrades.get(i);
    }

    double averageQuizGrade = 0;
    if (quizGrade != 0) {
      averageQuizGrade = quizGrade / userQuizGrades.size();
    }

    return averageQuizGrade;
  }
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
Пример #17
0
  public List<Polygon> compute() {
    // Compute delaunay triangulation:
    delaunay = (new SweepHullDelaunay2D(points)).getDelaunay();

    List<Polygon> polys = new ArrayList<>();

    // Working data
    long[] used = BitsUtil.zero(delaunay.size());
    List<double[]> cur = new ArrayList<>();

    for (int i = 0 /* = used.nextClearBit(0) */;
        i < delaunay.size() && i >= 0;
        i = BitsUtil.nextClearBit(used, i + 1)) {
      if (!BitsUtil.get(used, i)) {
        BitsUtil.setI(used, i);
        SweepHullDelaunay2D.Triangle tri = delaunay.get(i);
        if (tri.r2 <= alpha2) {
          // Check neighbors
          processNeighbor(cur, used, i, tri.ab, tri.b);
          processNeighbor(cur, used, i, tri.bc, tri.c);
          processNeighbor(cur, used, i, tri.ca, tri.a);
        }
        if (cur.size() > 0) {
          polys.add(new Polygon(cur));
          cur = new ArrayList<>();
        }
      }
    }

    return polys;
  }
  private static IJavaProject[] getProjectSearchOrder(String projectName) {

    ArrayList<String> projectNames = new ArrayList<String>();
    projectNames.add(projectName);

    int nextProject = 0;
    while (nextProject < projectNames.size()) {
      String nextProjectName = projectNames.get(nextProject);
      IJavaProject jproject = getJavaProject(nextProjectName);

      if (jproject != null) {
        try {
          String[] childProjectNames = jproject.getRequiredProjectNames();
          for (int i = 0; i < childProjectNames.length; i++) {
            if (!projectNames.contains(childProjectNames[i])) {
              projectNames.add(childProjectNames[i]);
            }
          }
        } catch (JavaModelException e) {
          JavaPlugin.log(e);
        }
      }
      nextProject += 1;
    }

    ArrayList<IJavaProject> result = new ArrayList<IJavaProject>();
    for (int i = 0, size = projectNames.size(); i < size; i++) {
      String name = projectNames.get(i);
      IJavaProject project = getJavaProject(name);
      if (project != null) result.add(project);
    }

    return result.toArray(new IJavaProject[result.size()]);
  }
Пример #19
0
 public card draw() {
   if (cards.size() == 0) return null;
   int index = (int) (Math.ceil(Math.random() * cards.size()) - 1);
   card spell = cards.get(index);
   cards.remove(index);
   return spell;
 }
Пример #20
0
  private static void calculateBestProfit() {
    ArrayList<GraphNode> tp = graph.topologicalSort();

    for (GraphNode g : tp) {
      for (GraphEdge e : g.goingEdges) {
        relax(e);
      }
    }

    ArrayList<GraphNode> lp = getLongestPath();

    System.out.print("The longest path is ");
    for (int i = 0; i < lp.size(); i++) {
      System.out.print(lp.get(i));
      if (i != lp.size() - 1) {
        System.out.print("-");
      }
    }
    System.out.print(" and the total gain is ");
    int total = 0;
    int currentKnapsack = 0;
    for (int i = 0; i < lp.size(); i++) {
      currentKnapsack = oneZeroKnapsack(lp.get(i).room);
      total += currentKnapsack;
      System.out.print(currentKnapsack);

      if (i != lp.size() - 1) {
        System.out.print("+");
      } else {
        System.out.print("=" + total + "TL");
      }
    }
  }
Пример #21
0
 public String characteristicsString() {
   String s = "(";
   for (int i = 0; i < characteristics.size() - 1; i++) s += characteristics.get(i) + ",";
   if (!characteristics.isEmpty()) s += characteristics.get(characteristics.size() - 1);
   s += ")";
   return s;
 }
Пример #22
0
 public static void putTimersInSharedPrefs(SharedPreferences prefs, ArrayList<TimerObj> timers) {
   if (timers.size() > 0) {
     for (int i = 0; i < timers.size(); i++) {
       timers.get(i).writeToSharedPref(prefs);
     }
   }
 }
Пример #23
0
  public void randomwalk(int v) {
    // weighted random walk
    RandomWalk rw = new RandomWalk(p_w);
    int status = rw.stay_move();
    ArrayList<Integer> walkpath = new ArrayList<Integer>();
    Integer u = v;
    walkpath.add(v);
    while (status == 1) // keep moving until status = 0
    {
      u = rw.move(G, u);
      if (u == null) // no neighbors
      break;
      if (!walkpath.contains(u)) walkpath.add(u);
      status = rw.stay_move();
    }
    //		System.out.println("walking length: "+ Integer.toString(walkpath.size()));

    for (int i = 0; i < walkpath.size(); i++)
      for (int j = i + 1; j < walkpath.size(); j++) {
        int m = walkpath.get(i);
        int n = walkpath.get(j);
        if (!G.containsEdge(m, n)) {
          double distance = Math.abs(socialposition.get(m) - socialposition.get(n));
          double prob = linkprob(distance, (j - i));
          if (random.nextDouble() < prob) {
            G.setEdgeWeight((DefaultWeightedEdge) G.addEdge(m, n), 1);
          }
        } else {
          DefaultWeightedEdge edge = G.getEdge(m, n);
          G.setEdgeWeight(edge, G.getEdgeWeight(edge) + 1);
        }
      }
    return;
  }
  private void updateTextDataUI() {

    if (!mIsTimestampDisplayMode) {
      if (mDataBufferLastSize != mDataBuffer.size()) {

        final int bufferSize = mDataBuffer.size();
        if (bufferSize > maxPacketsToPaintAsText) {
          mDataBufferLastSize = bufferSize - maxPacketsToPaintAsText;
          mTextSpanBuffer.clear();
          addTextToSpanBuffer(
              mTextSpanBuffer, getString(R.string.uart_text_dataomitted) + "\n", mInfoColor);
        }

        // Log.d(TAG, "update packets: "+(bufferSize-mDataBufferLastSize));
        for (int i = mDataBufferLastSize; i < bufferSize; i++) {
          final UartDataChunk dataChunk = mDataBuffer.get(i);
          final boolean isRX = dataChunk.getMode() == UartDataChunk.TRANSFERMODE_RX;
          final String data = dataChunk.getData();
          final String formattedData = mShowDataInHexFormat ? asciiToHex(data) : data;
          addTextToSpanBuffer(mTextSpanBuffer, formattedData, isRX ? mRxColor : mTxColor);
        }

        mDataBufferLastSize = mDataBuffer.size();
        mBufferTextView.setText(mTextSpanBuffer);
        mBufferTextView.setSelection(
            0, mTextSpanBuffer.length()); // to automatically scroll to the end
      }
    }
  }
Пример #25
0
  /*
   * This method lines up two AI's links, aka genes, and returns the order of the lined up genes, and where they occur.
   * This method returns an arraylist of arraylist of Integer.
   * The outer arraylist contains arraylists on:
   * 0: neuron historical ID of links present in the two AI
   * 1: where in the first ai's link list the link occurs
   * 2: where in the second ai's link list the link occurs
   */
  public ArrayList<ArrayList<Integer>> lineUpAILinks(NeatAI second) {

    ArrayList<Gene> secondL = second.getCloneLinks();

    ArrayList<Integer> ai1histIDlist = new ArrayList<Integer>();
    ArrayList<Integer> ai2histIDlist = new ArrayList<Integer>();

    ArrayList<Integer> linkID = new ArrayList<Integer>();
    ArrayList<Integer> linkList1Pos = new ArrayList<Integer>();
    ArrayList<Integer> linkList2Pos = new ArrayList<Integer>();

    // Get genes.
    int histID;
    for (Gene l : links) {
      histID = l.getHistID();
      linkID.add(histID);
      ai1histIDlist.add(histID);
    }

    int pos;
    for (Gene l : secondL) {
      histID = l.getHistID();
      pos = linkID.indexOf(histID);
      if (pos == -1) {
        // New histID found
        linkID.add(histID);
      }
      ai2histIDlist.add(histID);
    }

    // Sort genes
    // Bubble sort, meh
    int lowest;
    for (int i = 0; i < linkID.size(); i++) {
      lowest = i;
      for (int j = i + 1; j < linkID.size(); j++) {
        if (linkID.get(j) < linkID.get(lowest)) {
          lowest = j;
        }
      }

      int temp = linkID.get(i);
      linkID.set(i, linkID.get(lowest));
      linkID.set(lowest, temp);
    }

    // Add gene positions
    for (Integer tempID : linkID) {
      linkList1Pos.add(ai1histIDlist.indexOf(tempID));
      linkList2Pos.add(ai2histIDlist.indexOf(tempID));
    }

    ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>();

    temp.add(linkID);
    temp.add(linkList1Pos);
    temp.add(linkList2Pos);

    return temp;
  }
  @Test
  public void testAddItem() {

    ArrayList<GroceryItem> items = _activity.getItemsDisplayed();
    int count = items.size();

    _btnAdd.performClick();

    try {

      _btnAdd.performClick();
      Intent data =
          super.targetActivityIsStarted(
              shadowOf(this._activity), EditMasterItemActivity.class.getName());
      assert (data != null);

      GroceryItem item = saveGroceryItemValues(data);
      _activity.processActivityResult(BaseListActivity.ACTIVITY_ADD, Activity.RESULT_OK, data);
      ArrayList<GroceryItem> itemsDisplayed = _activity.getItemsDisplayed();

      assertTrue(itemsDisplayed.contains(item));
      _activity.saveList();
      items = _activity.loadGroceryItems(FileNameConstants.MasterFileName);
      assertEquals(count + 1, items.size());

    } catch (Exception e) {
      fail("Exception testing adding of an empty category");
      // TODO Auto-generated catch block
      // e.printStackTrace();
    }
  }
  /** {@inheritDoc} */
  @Override
  public IPortTemplateDesc[] findTemplatesByRepId(final String repId, final String language) {
    final ArrayList<IPortTemplateDesc> codegens = new ArrayList<IPortTemplateDesc>();

    // Search all repId's
    for (final Entry<String, Set<String>> ent : this.repToIdMap.entrySet()) {
      final String key = ent.getKey();

      // We allow for patterns, check if the passed in repId matches
      if (Pattern.matches(key, repId)) {

        // Loop through all the generators registered for this repId
        for (final String id : ent.getValue()) {
          final IPortTemplateDesc codegen = this.templateMap.get(id);
          if (codegen != null) {

            // Check for a match
            for (final String lang : codegen.getLanguages()) {
              if (lang.equals(language)) {
                codegens.add(codegen);
                break;
              }
            }
          }
        }
      }
    }

    Collections.sort(codegens);
    codegens.size();
    return codegens.toArray(new IPortTemplateDesc[codegens.size()]);
  }
  /**
   * find the progress of a particular topic based on its difficulty level
   *
   * @param userId
   * @param topic
   * @param difficulty
   * @return quizGradingProgress
   * @throws Exception
   */
  public static double findTopicDifficultyProgress(int userId, String topic, String difficulty)
      throws Exception {
    QuizAttempt quizAttempt = new QuizAttempt();
    ArrayList<Integer> userQuizIds = quizAttempt.getUserQuizIds(userId);

    ArrayList<Double> userQuizGrades = new ArrayList<Double>();

    for (int i = 0; i < userQuizIds.size(); i++) {
      QuizSlot quizSlot = new QuizSlot();
      // get the question ids of questions belonging to a particular quiz
      ArrayList<Integer> questionIds =
          quizSlot.getDifficultyAndTopicWiseQuestionIdsOfAQuiz(
              userQuizIds.get(i), topic, difficulty);

      double quizGradingProgress = Progress.findQuizProgress(questionIds, userId);

      userQuizGrades.add(quizGradingProgress);
    }

    double quizProgress = 0;

    for (int i = 0; i < userQuizGrades.size() - 1; i++) {
      if (userQuizGrades.get(i + 1) >= userQuizGrades.get(i)) {
        quizProgress += 1;
      }
    }

    double quizGradingProgress = 0;
    if (quizProgress != 0 && userQuizGrades.size() > 1) {
      quizGradingProgress = quizProgress / (userQuizGrades.size() - 1);
    }

    return quizGradingProgress;
  }
Пример #29
0
  private static boolean expandMediaSet(
      ArrayList<MediaPath> items, MediaSet set, int maxSelection) {
    int subCount = set.getSubMediaSetCount();
    for (int i = 0; i < subCount; i++) {
      if (!expandMediaSet(items, set.getSubMediaSet(i), maxSelection)) {
        return false;
      }
    }
    int total = set.getMediaItemCount();
    int batch = 50;
    int index = 0;

    while (index < total) {
      int count = index + batch < total ? batch : total - index;
      ArrayList<MediaItem> list = set.getMediaItem(index, count);
      if (list != null && list.size() > (maxSelection - items.size())) {
        return false;
      }
      for (MediaItem item : list) {
        items.add(item.getPath());
      }
      index += batch;
    }
    return true;
  }
Пример #30
0
  private void loadAndShowHyps() {
    if (selectHypFileUI.getSelectedHypFile() != null) {
      hypotheses = selectHypFileUI.getLoadedHyps();
      Iterator hypothesisIterator = hypotheses.iterator();
      showLoadedHypsUI.createTable(hypotheses.size());
      int rowNumber = 0;
      while (hypothesisIterator.hasNext()) {
        Hypothesis hypothesis = (Hypothesis) hypothesisIterator.next();
        showLoadedHypsUI.addHyp(
            rowNumber,
            hypothesis.getNumber(),
            hypothesis.getHypothesisText(),
            hypothesis.getScore());
        rowNumber++;
      }
      showLoadedHypsUI.setInfoLabelText(
          "You selected "
              + selectHypFileUI.getSelectedHypFile().getName().toString()
              + " as the input file."
              + " I found "
              + hypotheses.size()
              + " hypotheses.");

    } else {
      showLoadedHypsUI.setInfoLabelText("No hypothesis file selected.");
    }
  }