Java Code Examples for java.util.TreeSet#size()

The following examples show how to use java.util.TreeSet#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TreeCursorNoDuplicatesTest.java    From xodus with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertDeletes() {
    final ByteIterable value = value("value");
    final TreeSet<String> keys = new TreeSet<>();
    tm = createMutableTree(false, 1);
    for (int i = 0; i < 10000; ++i) {
        final String key = rndString();
        if (keys.add(key)) {
            Assert.assertTrue(tm.add(key(key), value));
        }
        if (keys.size() > 1000) {
            final String obsoleteKey = keys.first();
            keys.remove(obsoleteKey);
            Assert.assertTrue(tm.delete(key(obsoleteKey)));
        }
    }
    testCursorOrder(keys);
}
 
Example 2
Source File: DateTimePatternGenerator.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Used by CLDR tooling; not in ICU4C.
 * Note, this will not work correctly with normal skeletons, since fields
 * that should be related in the two skeletons being compared - like EEE and
 * ccc, or y and U - will not be sorted in the same relative place as each
 * other when iterating over both TreeSets being compare, using TreeSet's
 * "natural" code point ordering (this could be addressed by initializing
 * the TreeSet with a comparator that compares fields first by their index
 * from getCanonicalIndex()). However if comparing canonical skeletons from
 * getCanonicalSkeletonAllowingDuplicates it will be OK regardless, since
 * in these skeletons all fields are normalized to the canonical pattern
 * char for those fields - M or L to M, E or c to E, y or U to y, etc. -
 * so corresponding fields will sort in the same way for both TreeMaps.
 * @deprecated This API is ICU internal only.
 * @hide original deprecated declaration
 * @hide draft / provisional / internal are hidden on Android
 */
@Deprecated
public boolean skeletonsAreSimilar(String id, String skeleton) {
    if (id.equals(skeleton)) {
        return true; // fast path
    }
    // must clone array, make sure items are in same order.
    TreeSet<String> parser1 = getSet(id);
    TreeSet<String> parser2 = getSet(skeleton);
    if (parser1.size() != parser2.size()) {
        return false;
    }
    Iterator<String> it2 = parser2.iterator();
    for (String item : parser1) {
        int index1 = getCanonicalIndex(item, false);
        String item2 = it2.next(); // same length so safe
        int index2 = getCanonicalIndex(item2, false);
        if (types[index1][1] != types[index2][1]) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
/**
 * 10             20     30   ,t = 3
 * 12   15  18
 * 15  18     21
 *
 * @param nums
 * @param k    k 是索引之间的最大差值
 * @param t    是两个数值之间的最大差值
 * @return
 */
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> set = new TreeSet<>();
    for (int i = 0; i < nums.length; i++) {

        // 向右扩展看地板
        Long floor = set.floor((long) nums[i] + t);
        if ((floor != null && floor >= nums[i])) {
            return true;
        }

        // 向左扩展看天花板

        Long ceiling = set.ceiling((long) nums[i] - t);
        if ((ceiling != null && ceiling <= nums[i])) {
            return true;
        }

        // 下面两步先后顺序无所谓
        set.add((long) nums[i]);
        if (set.size() == (k + 1)) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 4
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/contains-duplicate-iii/
 * 题意:nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ
 * -------------------------------------------------------------------
 * 思考:
 * 数据特征:
 *     输入:数组、无序、所有整数(long)
 *     输出:boolean
 * -------------------------------------------------------------------
 * 思路:在思路1中维护的滑动窗口中,找到满足t,需要线性搜索耗时O(o)
 *  可以优化为维护一个BST,BST搜索耗时O(log(n))
 * -------------------------------------------------------------------
 * 时间复杂度:O(n*log(min(k,n)))
 * 空间复杂度:O(min(k,n))
 * -------------------------------------------------------------------
 * 执行用时 :44 ms, 在所有 Java 提交中击败了25.79%的用户
 * 内存消耗 :36.9 MB, 在所有 Java 提交中击败了89.89%的用户
 */
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> set = new TreeSet<>();
    for (int i = 0; i < nums.length; ++i) {
        // Find the successor of current element
        Long s = set.ceiling((long) nums[i]);//返回大于或等于给定键值的最小键值
        if (s != null && s - nums[i] <= t) return true;

        // Find the predecessor of current element
        Long g = set.floor((long) nums[i]);//返回小于或等于给定键值的最大键值
        if (g != null && nums[i] - g <= t) return true;

        set.add((long) nums[i]);
        if (set.size() > k) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 5
Source File: UserDictionaryList.java    From Android-Keyboard with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the entries that allow the user to go into the user dictionary for each locale.
 * @param userDictGroup The group to put the settings in.
 */
protected void createUserDictSettings(final PreferenceGroup userDictGroup) {
    final Activity activity = getActivity();
    userDictGroup.removeAll();
    final TreeSet<String> localeSet =
            UserDictionaryList.getUserDictionaryLocalesSet(activity);

    if (localeSet.size() > 1) {
        // Have an "All languages" entry in the languages list if there are two or more active
        // languages
        localeSet.add("");
    }

    if (localeSet.isEmpty()) {
        userDictGroup.addPreference(createUserDictionaryPreference(null));
    } else {
        for (String locale : localeSet) {
            userDictGroup.addPreference(createUserDictionaryPreference(locale));
        }
    }
}
 
Example 6
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
   * Returns the set of unique labels existing in the given stack, excluding 
   * the value zero (used for background).
* 
* @param image
*            a 3D label image
* @return the list of unique labels present in image (without background)
   */
  public final static int[] findAllLabels(ImageStack image) 
  {
      int sizeX = image.getWidth();
      int sizeY = image.getHeight();
      int sizeZ = image.getSize();
      
      TreeSet<Integer> labels = new TreeSet<Integer> ();
      
      // iterate on image pixels
      for (int z = 0; z < sizeZ; z++) 
      {
      	for (int y = 0; y < sizeY; y++)  
      	{
      		for (int x = 0; x < sizeX; x++)
      		{
      			labels.add((int) image.getVoxel(x, y, z));
      		}
      	}
      }
      
      // remove 0 if it exists
      if (labels.contains(0))
          labels.remove(0);
      
      // convert to array of integers
      int[] array = new int[labels.size()];
      Iterator<Integer> iterator = labels.iterator();
      for (int i = 0; i < labels.size(); i++) 
          array[i] = iterator.next();
      
      return array;
  }
 
Example 7
Source File: ColumnManage.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 添加栏目
 * @param column
 * @param dirName
 * @return
 */
public Integer addColumn(Column column,String dirName){
	List<Column> columnList = columnList(dirName);
	TreeSet<Integer> columnIdList = this.columnIdList(columnList,new TreeSet<Integer>());
	//最大号码
	int maxId = 0;
	if(columnIdList != null && columnIdList.size() >0){
		maxId = columnIdList.last();
	}
	maxId++;
	column.setId(maxId);
	if(column.getLinkMode().equals(4)){
		column.setUrl("column/"+maxId);
	}
	
	
	if(column.getParentId() >0){//有父栏目
		this.addColumnIdList(columnList,column);
	}else{
		columnList.add(column);
	}
	
	//栏目排序
	this.columnSort(columnList);
	int i = templateService.updateColumn(JsonUtils.toJSONString(columnList), dirName);
	if(i >0){
		return maxId;
	}
	return -1;
}
 
Example 8
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static final int[] findBorderLabels(ImageProcessor image) 
{
	int sizeX = image.getWidth();
	int sizeY = image.getHeight();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();

	// find labels in top and bottom borders
	for (int x = 0; x < sizeX; x++)
	{
		labelSet.add((int) image.getf(x, 0));
		labelSet.add((int) image.getf(x, sizeY - 1));
	}

	// find labels in left and right borders
	for (int y = 0; y < sizeY; y++) 
	{
		labelSet.add((int) image.getf(0, y));
		labelSet.add((int) image.getf(sizeX - 1, y));
	}

	// remove label for the background
	labelSet.remove(0);
	
	// convert to an array of int
	int[] labels = new int[labelSet.size()];
	int i = 0 ;
	Iterator<Integer> iter = labelSet.iterator();
	while(iter.hasNext()) 
	{
		labels[i++] = (int) iter.next();
	}
	
	return labels;
}
 
Example 9
Source File: ExamEditAjax.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected void coumputeClasses(String schedulingSubpartId, String courseId, PrintWriter out) throws Exception {
    if (schedulingSubpartId==null || schedulingSubpartId.length()==0 || schedulingSubpartId.equals(Preference.BLANK_PREF_VALUE)) {
        print(out, "-1", "N/A");
        return;
    }
    SchedulingSubpart subpart = (Long.parseLong(schedulingSubpartId)>0?new SchedulingSubpartDAO().get(Long.valueOf(schedulingSubpartId)):null);
    if (subpart==null) {
        print(out, "-1", "N/A");
        return;
    }
    CourseOffering co = null;
    if (courseId != null && !courseId.isEmpty()) {
    	co = CourseOfferingDAO.getInstance().get(Long.valueOf(courseId));
    }
    TreeSet classes = new TreeSet(new ClassComparator(ClassComparator.COMPARE_BY_HIERARCHY));
    classes.addAll(new Class_DAO().
        getSession().
        createQuery("select distinct c from Class_ c "+
                "where c.schedulingSubpart.uniqueId=:schedulingSubpartId").
        setFetchSize(200).
        setCacheable(true).
        setLong("schedulingSubpartId", Long.parseLong(schedulingSubpartId)).
        list());
    if (classes.size()>1)
        print(out, "-1", "-");
    for (Iterator i=classes.iterator();i.hasNext();) {
        Class_ c = (Class_)i.next();
        String extId = c.getClassSuffix(co);
        print(out, c.getUniqueId().toString(), c.getSectionNumberString() + (extId == null || extId.isEmpty() || extId.equalsIgnoreCase(c.getSectionNumberString()) ? "" : " - " + extId)); 
    }
}
 
Example 10
Source File: FractionalMultiset.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressFBWarnings("DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS")
public Iterable<Map.Entry<K, Double>> entriesInIncreasingOrder() {
    TreeSet<Map.Entry<K, Double>> result = new TreeSet<>(new DecreasingOrderEntryComparator<K>());
    result.addAll(map.entrySet());
    if (result.size() != map.size()) {
        throw new IllegalStateException("Map " + map.getClass().getSimpleName()
                + " reuses Map.Entry objects; entrySet can't be passed to addAll");
    }
    return result;
}
 
Example 11
Source File: TrieDictionaryTest.java    From Kylin with Apache License 2.0 5 votes vote down vote up
private static void benchmarkStringDictionary(ArrayList<String> str) throws UnsupportedEncodingException {
    TrieDictionaryBuilder<String> b = newDictBuilder(str);
    b.stats().print();
    TrieDictionary<String> dict = b.build(0);

    TreeSet<String> set = new TreeSet<String>();
    for (String s : str) {
        set.add(s);
    }

    // prepare id==>value array and value==>id map
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    String[] strArray = new String[set.size()];
    byte[][] array = new byte[set.size()][];
    Iterator<String> it = set.iterator();
    for (int id = 0; it.hasNext(); id++) {
        String value = it.next();
        map.put(value, id);
        strArray[id] = value;
        array[id] = value.getBytes("UTF-8");
    }

    // System.out.println("Dict size in bytes:  " +
    // MemoryUtil.deepMemoryUsageOf(dict));
    // System.out.println("Map size in bytes:   " +
    // MemoryUtil.deepMemoryUsageOf(map));
    // System.out.println("Array size in bytes: " +
    // MemoryUtil.deepMemoryUsageOf(strArray));

    // warm-up, said that code only got JIT after run 1k-10k times,
    // following jvm options may help
    // -XX:CompileThreshold=1500
    // -XX:+PrintCompilation
    benchmark("Warm up", dict, set, map, strArray, array);
    benchmark("Benchmark", dict, set, map, strArray, array);
}
 
Example 12
Source File: Solution.java    From java-technology-stack with MIT License 5 votes vote down vote up
public int findCircleNum(int[][] M) {

        int n = M.length;
        UnionFind2 uf = new UnionFind2(n);
        for(int i = 0 ; i < n ; i ++)
            for(int j = 0 ; j < i ; j ++)
                if(M[i][j] == 1)
                    uf.unionElements(i, j);

        TreeSet<Integer> set = new TreeSet<>();
        for(int i = 0 ; i < n ; i ++)
            set.add(uf.find(i));
        return set.size();
    }
 
Example 13
Source File: TiffSaver.java    From scifio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void writeIFD(final IFD ifd, final long nextOffset)
		throws FormatException, IOException
	{
		final TreeSet<Integer> keys = new TreeSet<>(ifd.keySet());
		int keyCount = keys.size();

		if (ifd.containsKey(IFD.LITTLE_ENDIAN)) keyCount--;
		if (ifd.containsKey(IFD.BIG_TIFF)) keyCount--;
		if (ifd.containsKey(IFD.REUSE)) keyCount--;

		final long fp = out.offset();
		final int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY
			: TiffConstants.BYTES_PER_ENTRY;
		final int ifdBytes = (bigTiff ? 16 : 6) + bytesPerEntry * keyCount;

		if (bigTiff) out.writeLong(keyCount);
		else out.writeShort(keyCount);

		final BytesLocation extra = new BytesLocation(0); // NB: autoresizes
		try (final DataHandle<Location> extraHandle = dataHandleService.create(
			extra))
		{
			for (final Integer key : keys) {
				if (key.equals(IFD.LITTLE_ENDIAN) || key.equals(IFD.BIG_TIFF) || key
					.equals(IFD.REUSE)) continue;

				final Object value = ifd.get(key);
				writeIFDValue(extraHandle, ifdBytes + fp, key.intValue(), value);
			}

//			if (bigTiff) out.seek(out.offset());

			writeIntValue(out, nextOffset);
			final int ifdLen = (int) extraHandle.offset();
			extraHandle.seek(0l);
			DataHandles.copy(extraHandle, out, ifdLen);
		}
	}
 
Example 14
Source File: HMDBGateway.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults,
    ParameterSet parameters) throws IOException {

  Range<Double> toleranceRange = mzTolerance.getToleranceRange(mass);

  String queryAddress = hmdbSeachAddress + "&query_from=" + toleranceRange.lowerEndpoint()
      + "&query_to=" + toleranceRange.upperEndpoint();

  URL queryURL = new URL(queryAddress);

  // Submit the query
  logger.finest("Loading URL " + queryAddress);
  String queryResult = InetUtils.retrieveData(queryURL);

  // Organize the IDs as a TreeSet to keep them sorted
  TreeSet<String> results = new TreeSet<String>();

  // Find IDs in the HTML data
  Pattern pat = Pattern.compile("metabolites/(HMDB[0-9]{5,})");
  Matcher matcher = pat.matcher(queryResult);
  while (matcher.find()) {
    String hmdbID = matcher.group(1);
    results.add(hmdbID);
  }

  // Remove all except first numOfResults IDs. The reason why we first
  // retrieve all results and then remove those above numOfResults is to
  // keep the lowest HDMB IDs - these may be the most interesting ones.
  while (results.size() > numOfResults) {
    String lastItem = results.last();
    results.remove(lastItem);
  }

  return results.toArray(new String[0]);

}
 
Example 15
Source File: TrieDictionaryTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
private static void benchmarkStringDictionary(Iterable<String> str) throws IOException {
    TrieDictionaryBuilder<String> b = newDictBuilder(str);
    b.stats().print();
    TrieDictionary<String> dict = b.build(0);

    TreeSet<String> set = new TreeSet<String>();
    for (String s : str) {
        set.add(s);
    }

    // prepare id==>value array and value==>id map
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    String[] strArray = new String[set.size()];
    byte[][] array = new byte[set.size()][];
    Iterator<String> it = set.iterator();
    for (int id = 0; it.hasNext(); id++) {
        String value = it.next();
        map.put(value, id);
        strArray[id] = value;
        array[id] = value.getBytes("UTF-8");
    }

    // System.out.println("Dict size in bytes:  " +
    // MemoryUtil.deepMemoryUsageOf(dict));
    // System.out.println("Map size in bytes:   " +
    // MemoryUtil.deepMemoryUsageOf(map));
    // System.out.println("Array size in bytes: " +
    // MemoryUtil.deepMemoryUsageOf(strArray));

    // warm-up, said that code only got JIT after run 1k-10k times,
    // following jvm options may help
    // -XX:CompileThreshold=1500
    // -XX:+PrintCompilation
    System.out.println("Benchmark awaitig...");
    benchmark("Warm up", dict, set, map, strArray, array);
    benchmark("Benchmark", dict, set, map, strArray, array);
}
 
Example 16
Source File: BeanMappingFactoryHelper.java    From super-csv-annotation with Apache License 2.0 4 votes vote down vote up
/**
 * 欠けているカラム番号がある場合、その番号を持つダミーのカラムを追加する。
 * @param beanType Beanタイプ
 * @param list カラム情報の一覧
 * @param partialAnno Beanに設定されているアノテーション{@link CsvPartial}の情報。
 * @param suppliedHeaders 提供されたヘッダー。提供されてない場合は、長さ0の配列。
 * @return
 */
public static TreeSet<Integer> supplyLackedNumberMappingColumn(final Class<?> beanType, final List<ColumnMapping> list,
        final Optional<CsvPartial> partialAnno, final String[] suppliedHeaders) {
    
    final TreeSet<Integer> checkedNumber = list.stream()
            .filter(col -> col.isDeterminedNumber())
            .map(col -> col.getNumber())
            .collect(Collectors.toCollection(TreeSet::new));
    
    // 定義されている列番号の最大値
    final int maxColumnNumber = checkedNumber.last();
    
    // Beanに定義されていない欠けているカラム番号の取得
    final TreeSet<Integer> lackedNumbers = new TreeSet<Integer>();
    for(int i=1; i <= maxColumnNumber; i++) {
        if(!checkedNumber.contains(i)) {
            lackedNumbers.add(i);
        }
    }
    
    // 定義されているカラム番号より、大きなカラム番号を持つカラム情報の補足
    if(partialAnno.isPresent()) {
        
        final int partialColumnSize = partialAnno.get().columnSize();
        if(maxColumnNumber > partialColumnSize) {
            throw new SuperCsvInvalidAnnotationException(partialAnno.get(), MessageBuilder.create("anno.CsvPartial.columSizeMin")
                    .var("property", beanType.getName())
                    .var("columnSize", partialColumnSize)
                    .var("maxColumnNumber", maxColumnNumber)
                    .format());
            
        }
        
        if(maxColumnNumber < partialColumnSize) {
            for(int i= maxColumnNumber+1; i <= partialColumnSize; i++) {
                lackedNumbers.add(i);
            }
        }
        
    }
    
    // 不足分のカラムがある場合は、部分的な読み書き用カラムとして追加する
    if(lackedNumbers.size() > 0) {
        
        for(int number : lackedNumbers) {
            list.add(createPartialColumnMapping(number, partialAnno, getSuppliedHeaders(suppliedHeaders, number)));
        }
        
        list.sort(null);
    }
    
    return lackedNumbers;
    
}
 
Example 17
Source File: SMOTE.java    From jatecs with GNU General Public License v3.0 4 votes vote down vote up
protected static HashMap<Integer, List<DocSim>> computeNNfaster(IIndex index, DocSet forDocuments, int k) {
	int nD=index.getDocumentDB().getDocumentsCount();
	SparseMatrix _distcache=new SparseMatrix(nD, nD);
	
	HashMap<Integer, List<DocSim>> nearest_neigbours=new HashMap<>();
	
	List<Integer> alldocuments=DocSet.genDocset(index.getDocumentDB()).asList();
	
	IndexVectorizer docvectorizer = new IndexVectorizer(index);
	HashMap<Integer, SparseVector> docVector = new HashMap<>();
	for(int docid:alldocuments){
		docVector.put(docid, docvectorizer.getDocumentWeights(docid));
	}
	
	List<Integer> doclist=forDocuments.asList();
	int progress=0;
	int totalsteps=doclist.size();
	JatecsLogger.status().println("Knn for " + totalsteps + " documents: ");
	for(int docID_i : doclist){
		TreeSet<DocSim> neighbours = new TreeSet<DocSim>();
		
		double distThreshold = Double.MAX_VALUE;
		SparseVector docvec_i=docVector.get(docID_i);
		
		for(int docID_j : alldocuments){
			if(docID_i==docID_j) continue;
			
			double distance = _distcache.get(Math.min(docID_i, docID_j), Math.max(docID_i, docID_j));
			if(distance==0){				
				distance = euclideanSquaredDistanceThresholded(docvec_i, docVector.get(docID_j), distThreshold);
				_distcache.set(Math.min(docID_i, docID_j), Math.max(docID_i, docID_j), distance);
			}
				
			neighbours.add(new DocSim(docID_j, distance));
			if(neighbours.size()>k){
				neighbours.pollLast();
				distThreshold = Math.min(neighbours.last().distance, distThreshold);
			}
		}

		nearest_neigbours.put(docID_i, new ArrayList<DocSim>(neighbours));
		
		if(progress++%(Math.max(totalsteps/10,1))==0)
			JatecsLogger.status().print("..."+(progress*100/totalsteps)+"%");
	}
	JatecsLogger.status().println("");
	
	return nearest_neigbours;
}
 
Example 18
Source File: RoomGroupAddAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
/** 
 * Method execute
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 */
public ActionForward execute(
	ActionMapping mapping,
	ActionForm form,
	HttpServletRequest request,
	HttpServletResponse response) throws Exception{
	RoomGroupEditForm roomGroupEditForm = (RoomGroupEditForm) form;
	
	MessageResources rsc = getResources(request);
	String doit = roomGroupEditForm.getDoit();
	
	if (doit != null) {
		//add new
		if(doit.equals(rsc.getMessage("button.addNew"))) {
			ActionMessages errors = new ActionMessages();
			errors = roomGroupEditForm.validate(mapping, request);
	        if(errors.size()==0) {
	        	save(mapping, roomGroupEditForm, request, response);
				return mapping.findForward("showRoomGroupList");
	        } else {
	        	saveErrors(request, errors);
	        }
		}
		
		//return to room list
		if(doit.equals(rsc.getMessage("button.returnToRoomGroupList"))) {
			return mapping.findForward("showRoomGroupList");
		}
	}
	
	//get depts owned by user
	LookupTables.setupDepartments(request, sessionContext, false);
	
       //set default department
	TreeSet<Department> departments = Department.getUserDepartments(sessionContext.getUser());
       if (departments.size() == 1) {
       	roomGroupEditForm.setDeptCode(departments.first().getDeptCode());
       } else {
       	String deptCode = (String)sessionContext.getAttribute(SessionAttribute.DepartmentCodeRoom);
       	if (deptCode != null && !deptCode.isEmpty() && !deptCode.equals("All") && !deptCode.matches("Exam[0-9]*"))
       		roomGroupEditForm.setDeptCode(deptCode);
	}
	
	if (roomGroupEditForm.getDeptCode() == null || roomGroupEditForm.getDeptCode().isEmpty() || roomGroupEditForm.getDeptCode().matches("Exam[0-9]*") ||
		!sessionContext.hasPermission(roomGroupEditForm.getDeptCode(), "Department", Right.DepartmentRoomGroupAdd)) {
		sessionContext.checkPermission(Right.GlobalRoomGroupAdd);
		roomGroupEditForm.setGlobal(true);
	} else {
		sessionContext.checkPermission(roomGroupEditForm.getDeptCode(), "Department", Right.DepartmentRoomGroupAdd);
		roomGroupEditForm.setGlobal(false);
	}
	
	roomGroupEditForm.setSessionId(sessionContext.getUser().getCurrentAcademicSessionId());
	
	return mapping.findForward("showAdd");
}
 
Example 19
Source File: LevenshteinAutomaton.java    From LevenshteinAutomaton with Apache License 2.0 4 votes vote down vote up
/**
 * Searches a collection of Strings for those which are within a given edit distance from a particular String.
 * 
 * This version of fuzzy search uses a pre-computed map of transitions, and is the fastest method for max 
 * edit distances less than or equal 2. Greater max edit distances require huge amounts of memory and 
 * are not guaranteed to be faster than a non-automaton approach, so use in those cases is discouraged.
 
 * @param maxEditDistance       an int denoting the maximum amount of edit operations that can separate
 *                              a String in the to-be-searched collection with the String of interest
 * @param automatonString       the String that all edit-distance calculations are to be carried out in relation to
 * @param mdag                  an MDAG containing the set of Strings to be processed against {@code automatonString}
 * @return                      a LinkedList containing all the Strings in {@code mdag} that are at most
 *                              {@code maxEditDistance} away from {@code automatonString}
 */
public static LinkedList<String> tableFuzzySearch(int maxEditDistance, String automatonString, MDAG mdag)
{
    //LinkedList which will contain Strings in mdag that are within maxEditDistance of automatonString
    LinkedList<String> resultStringLinkedList = new LinkedList<String>();
    
    //HashMap containing the transition relationships between the parametric states of an automaton with maxEditDistance
    createParametricStateTransitionMap(maxEditDistance);
    HashMap<ParametricState, HashMap<AugBitSet, ParametricState>> transitionHashMap = transitionHashMapContainerHashMap.get(maxEditDistance);
    
    //Stack to store collections of objects which collectively represent steps in the search process
    Stack<Object[]> processingStepStack = new Stack<Object[]>();

    boolean mdagIsSimplified = mdag.getSourceNode().getClass().equals(SimpleMDAGNode.class);
    SimpleMDAGNode[] simpleMDAGArray = mdag.getSimpleMDAGArray();
    
    //Push onto processingStepStack the collection of objects which represent the start step of the search process
    processingStepStack.push(createProcessingStepStackEntry("", mdag.getSourceNode(), initialState, new ParametricState(initialState)));
    
    //Retrieve the set of characters composing the Strings in mdag
    TreeSet<Character> charTreeSet = mdag.getTransitionLabelSet();
    int charCount = charTreeSet.size();
    /////
    
    //Iterate through charTreeSet, inserting each char in to charArray
    int counter = 0;
    char[] charArray = new char[charCount];
    for(Character c : charTreeSet) charArray[counter++] = c.charValue();
    /////
    
    //Transition through the MDAG and the automaton represented by transitionHashMap in-sync, adding to 
    //resultStringLinkedList the char sequences that lead to both an accept node (MDAG) and accept state (transition map)
    while(!processingStepStack.isEmpty())
    {
        //Pop the processing step at the top of the stack and re-cast its contents
        Object[] currentProcessingStepDataArray = processingStepStack.pop(); 
        
        Object currentNodeObj = currentProcessingStepDataArray[1];
        State currentState = (State)currentProcessingStepDataArray[2];
        ParametricState currentParametricState = (ParametricState)currentProcessingStepDataArray[3];
        /////
        
        //Loop through the chars in charArray, using each to transition the node & state in the
        //processing step at the top of the stack. If both the node and state have valid
        //transitions on a particular char, push the resulting transition String, node,
        //and State on the top of the stack
        for(int i = 0; i < charCount; i++)
        {
            char currentChar = charArray[i];

            //Execute a transition on the current MDAG node using currentChar     
            Object transitionNode = (mdagIsSimplified ? ((SimpleMDAGNode)currentNodeObj).transition(simpleMDAGArray, currentChar) : ((MDAGNode)currentNodeObj).transition(currentChar));
            
            if(transitionNode != null)
            {
                //Get currentState's relevant subword (with respect to currentChar) and  
                //use it to get the parametric version of the transition's result State
                AugBitSet rscv = currentState.getRelevantSubwordCharacteristicVector(maxEditDistance, automatonString, currentChar);  
                ParametricState transitionParametricState = transitionHashMap.get(currentParametricState).get(rscv);
                /////

                if(transitionParametricState != null)
                {
                    //Use transitionParametricState to create the actual State that is the result of the transition
                    State transitionState = transitionParametricState.createActualState(currentState.getMinimalBoundary() + transitionParametricState.getTransitionBoundaryOffset());
                    
                    String transitionPathString = (String)currentProcessingStepDataArray[0] + currentChar;
                    
                    //Push the resulting processing step on to the top of processingStepStack
                    processingStepStack.push(createProcessingStepStackEntry(transitionPathString, transitionNode, transitionState, transitionParametricState));

                    //If both transitionNode and transitionState are "accepting", add the sequence of chars that lead to them to resultStringLinkedList
                    if(MDAG.isAcceptNode(transitionNode) && isAcceptState(transitionState, automatonString.length(), maxEditDistance))
                        resultStringLinkedList.add(transitionPathString);
                }
            }
        }
        /////
    }
    /////
 
    return resultStringLinkedList;
}
 
Example 20
Source File: GridSqlQuerySplitter.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * @param sqlQry Query.
 * @param qryAst Select AST.
 * @param paramsCnt Number of parameters.
 */
private static void setupParameters(GridCacheSqlQuery sqlQry, GridSqlQuery qryAst, int paramsCnt) {
    TreeSet<Integer> paramIdxs = new TreeSet<>();

    SplitterUtils.findParamsQuery(qryAst, paramsCnt, paramIdxs);

    int[] paramIdxsArr = new int[paramIdxs.size()];

    int i = 0;

    for (Integer paramIdx : paramIdxs)
        paramIdxsArr[i++] = paramIdx;

    sqlQry.parameterIndexes(paramIdxsArr);
}