Jave sort

60 Jave code examples are found related to " sort". 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.
Example 1
Source File: ProfilerDataDumper.java    From bistoury with GNU General Public License v3.0 7 votes vote down vote up
private List<Map.Entry<Integer, Long>> sortByValue(Map<Integer, Long> countMap) {
    List<Map.Entry<Integer, Long>> countEntryList = new ArrayList<>(countMap.entrySet());
    Collections.sort(countEntryList, new Comparator<Map.Entry<Integer, Long>>() {
        @Override
        public int compare(Map.Entry<Integer, Long> l, Map.Entry<Integer, Long> r) {
            long left = l.getValue();
            long right = r.getValue();
            if (left > right) {
                return -1;
            } else if (left == right) {
                return 0;
            }
            return 1;
        }
    });
    return countEntryList;
}
 
Example 2
Source File: MergeSortinLinkedList.java    From CompetitiveJava with MIT License 7 votes vote down vote up
node mergeSort(node h) 
{ 
    if (h == null || h.next == null) { 
        return h; 
    } 
  
    node middle = getMiddle(h); 
    node nextofmiddle = middle.next; 
  
    middle.next = null; 
  
    node left = mergeSort(h); 
  
    node right = mergeSort(nextofmiddle); 
    node sortedlist = sortedMerge(left, right); 
    return sortedlist; 
}
 
Example 3
Source File: MultiSortMembersAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ICleanUp[] getCleanUps(ICompilationUnit[] units) {
	try {
        if (!hasMembersToSort(units)) {
			MessageDialog.openInformation(getShell(), ActionMessages.MultiSortMembersAction_noElementsToSortDialog_title, ActionMessages.MultiSortMembersAction_noElementsToSortDialog_message);
        	return null;
        }
       } catch (JavaModelException e) {
       	JavaPlugin.log(e);
        return null;
       }

	Map<String, String> settings= getSettings();
	if (settings == null)
		return null;

	return new ICleanUp[] {
		new SortMembersCleanUp(settings)
	};
}
 
Example 4
Source File: HypervGuru.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private NicTO[] sortNicsByDeviceId(NicTO[] nics) {

        List<NicTO> listForSort = new ArrayList<NicTO>();
        for (NicTO nic : nics) {
            listForSort.add(nic);
        }
        Collections.sort(listForSort, new Comparator<NicTO>() {

            @Override
            public int compare(NicTO arg0, NicTO arg1) {
                if (arg0.getDeviceId() < arg1.getDeviceId()) {
                    return -1;
                } else if (arg0.getDeviceId() == arg1.getDeviceId()) {
                    return 0;
                }

                return 1;
            }
        });

        return listForSort.toArray(new NicTO[0]);
    }
 
Example 5
Source File: DescColumnSortOrderExpressionTest.java    From phoenix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void multiply() throws Exception {
    List<Expression> args = Lists.newArrayList(getInvertedLiteral(10, PDataType.INTEGER), getLiteral(2));
    evaluateAndAssertResult(new DecimalMultiplyExpression(args), new BigDecimal(BigInteger.valueOf(2), -1));
    
    args = Lists.newArrayList(getInvertedLiteral(10, PDataType.INTEGER), getLiteral(2));
    evaluateAndAssertResult(new LongMultiplyExpression(args), 20l);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.FLOAT), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.UNSIGNED_FLOAT), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.UNSIGNED_DOUBLE), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
    
    args = Lists.newArrayList(getInvertedLiteral(10.0, PDataType.DOUBLE), getLiteral(2));
    evaluateAndAssertResult(new DoubleMultiplyExpression(args), 20.0);
}
 
Example 6
Source File: SearchUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public List<SortBuilder> getSortBuilders(final String sort, final String direction, boolean allowAnySort) {
  if (sort == null) {
    return emptyList();
  }

  switch (sort) {
    case GROUP:
      return handleGroupSort(direction);
    case NAME:
      return handleNameSort(direction);
    case VERSION:
      return handleVersionSort(direction);
    case "repository":
    case "repositoryName":
      return handleRepositoryNameSort(direction);
    default:
      return handleOtherSort(sort, direction, allowAnySort);
  }
}
 
Example 7
Source File: PdfCollectionSort.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Defines the sort order of the field (ascending or descending).
 * @param ascending	an array with every element corresponding with a name of a field.
 */
public void setSortOrder(boolean[] ascending) {
	PdfObject o = get(PdfName.S);
	if (o instanceof PdfArray) {
		if (((PdfArray)o).size() != ascending.length) {
			throw new IllegalArgumentException("The number of booleans in this array doesn't correspond with the number of fields.");
		}
		PdfArray array = new PdfArray();
		for (int i = 0; i < ascending.length; i++) {
			array.add(new PdfBoolean(ascending[i]));
		}
		put(PdfName.A, array);
	}
	else {
		throw new IllegalArgumentException("You need a single boolean for this collection sort dictionary.");
	}
}
 
Example 8
Source File: SREsPreferencePage.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Sorts by SRE name.
 */
private void sortByName() {
	this.sresList.setComparator(new ViewerComparator() {
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			if ((e1 instanceof ISREInstall) && (e2 instanceof ISREInstall)) {
				final ISREInstall left = (ISREInstall) e1;
				final ISREInstall right = (ISREInstall) e2;
				return left.getName().compareToIgnoreCase(right.getName());
			}
			return super.compare(viewer, e1, e2);
		}

		@Override
		public boolean isSorterProperty(Object element, String property) {
			return true;
		}
	});
	this.sortColumn = Column.NAME;
}
 
Example 9
Source File: AbstractConversionTable.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Sorts the type conversions by target type.
 */
private void sortByTargetColumn() {
	this.list.setComparator(new ViewerComparator() {
		@Override
		public int compare(Viewer viewer, Object e1, Object e2) {
			if (e1 != null  && e2 != null) {
				return e1.toString().compareToIgnoreCase(e2.toString());
			}
			return super.compare(viewer, e1, e2);
		}

		@Override
		public boolean isSorterProperty(Object element, String property) {
			return true;
		}
	});
	this.sort = Column.TARGET;
}
 
Example 10
Source File: SortForumsActivity.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
private void showStarGuide() {
    new GuideHelper.Builder(this)
            .setColor(ResourcesUtils.getAttrColor(this, R.attr.colorPrimary))
            .setPadding(LayoutUtils.dp2pix(this, 16))
            .setPaddingTop(LayoutUtils.dp2pix(this, 56))
            .setPaddingBottom(LayoutUtils.dp2pix(this, 56))
            .setMessagePosition(Gravity.RIGHT)
            .setMessage(getString(R.string.click_star_icon_pin))
            .setButton(getString(R.string.get_it))
            .setBackgroundColor(0x73000000)
            .setOnDissmisListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Settings.putGuidePinningStar(false);
                }
            }).show();
}
 
Example 11
Source File: IssueDatabaseExtensions.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Sorts the given list and replies it.
 *
 * @param descriptions the list to sort.
 * @return {@code descriptions}.
 */
@Pure
public static List<IssueDescription> sort(List<IssueDescription> descriptions) {
	descriptions.sort((a, b) -> {
		int cmp = a.getShortDisplayCode().compareToIgnoreCase(b.getShortDisplayCode());
		if (cmp != 0) {
			return cmp;
		}
		cmp = a.getCodePrefix().compareToIgnoreCase(b.getCodePrefix());
		if (cmp != 0) {
			return cmp;
		}
		cmp = a.getSortLevel().compareTo(b.getSortLevel());
		if (cmp != 0) {
			return cmp;
		}
		return a.message.compareToIgnoreCase(b.message);
	});
	return descriptions;
}
 
Example 12
Source File: ClusterBasedAgentLoadBalancerPlanner.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static LinkedHashMap<Long, List<HostVO>> sortByClusterSize(final Map<Long, List<HostVO>> hostToClusterMap) {
    List<Long> keys = new ArrayList<Long>();
    keys.addAll(hostToClusterMap.keySet());
    Collections.sort(keys, new Comparator<Long>() {
        @Override
        public int compare(Long o1, Long o2) {
            List<HostVO> v1 = hostToClusterMap.get(o1);
            List<HostVO> v2 = hostToClusterMap.get(o2);
            if (v1 == null) {
                return (v2 == null) ? 0 : 1;
            }

            if (v1.size() < v2.size()) {
                return 1;
            } else {
                return 0;
            }
        }
    });

    LinkedHashMap<Long, List<HostVO>> sortedMap = new LinkedHashMap<Long, List<HostVO>>();
    for (Long key : keys) {
        sortedMap.put(key, hostToClusterMap.get(key));
    }
    return sortedMap;
}
 
Example 13
Source File: QuickSort.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private static <T> void quicksort(List<T> list, Comparator<T> cmp)
{
    Deque<Integer> stack = new ArrayDeque<Integer>();
    stack.push(0);
    stack.push(list.size());
    while (!stack.isEmpty())
    {
        int right = stack.pop();
        int left = stack.pop();
        if (right - left < 2)
        {
            continue;
        }
        int p = left + ((right - left) / 2);
        p = partition(list, cmp, p, left, right);

        stack.push(p + 1);
        stack.push(right);

        stack.push(left);
        stack.push(p);
    }
}
 
Example 14
Source File: SortFluxTest.java    From influxdb-client-java with MIT License 6 votes vote down vote up
@Test
void sortByParameters() {

    Flux flux = Flux
            .from("telegraf")
            .sort()
            .withPropertyNamed("columns", "columnsParameter")
            .withPropertyNamed("desc", "descParameter");

    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("columnsParameter", new String[]{"region", "tag"});
    parameters.put("descParameter", false);

    String expected = "from(bucket:\"telegraf\") |> sort(columns: [\"region\", \"tag\"], desc: false)";

    Assertions
            .assertThat(flux.toString(parameters))
            .isEqualToIgnoringWhitespace(expected);
}
 
Example 15
Source File: MultiSort.java    From L2jBrasil with GNU General Public License v3.0 6 votes vote down vote up
public final double getStandardDeviation()
{
	if(getValues().isEmpty())
		return -1;

	List<Double> tempValList = new ArrayList<>();
	int meanValue = getMean();
	int numValues = getCount();

	for(int value : getValues())
	{
		double adjValue = Math.pow(value - meanValue, 2);
		tempValList.add(adjValue);
	}

	double totalValue = 0;

	for(double storedVal : tempValList)
	{
		totalValue += storedVal;
	}

	return Math.sqrt(totalValue / (numValues - 1));
}
 
Example 16
Source File: AttributeOrderingOperator.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Sorts a list of attributes alphabetically according to the desired sort direction. CAUTION:
 * The provided list 'unsortedAttributeList' will be changed internally.
 */
private void sortAttributeListAlphabetically(List<Attribute> unsortedAttributeList) throws UndefinedParameterError {

	// sort direction none -> just return
	if (getParameterAsString(PARAMETER_SORT_DIRECTION).equals(DIRECTION_NONE)) {
		return;
	}

	// sort attributes
	Collections.sort(unsortedAttributeList, new Comparator<Attribute>() {

		@Override
		public int compare(Attribute o1, Attribute o2) {
			return Collator.getInstance().compare(o1.getName(), o2.getName());
		}

	});

	// if descending, reverse sort
	if (getParameterAsString(PARAMETER_SORT_DIRECTION).equals(DIRECTION_DESCENDING)) {
		Collections.reverse(unsortedAttributeList);
	}
}
 
Example 17
Source File: SortForumsActivity.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (autoSortingSwitch == buttonView) {
        mAutoSorting = isChecked;
        Settings.putForumAutoSorting(isChecked);

        // update the list to sort them according to the present setting
        updateLazyList(false);
        // the list could be dramatically different so update them all
        mAdapter.notifyDataSetChanged();

        // show guide
        tryShowSecondGuide();

        mNeedUpdate = true;
    }
}
 
Example 18
Source File: ExtendedJTable.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
public void sortColumnsAccordingToNames() {
	int offset = 0;
	if (fixFirstColumn) {
		offset = 1;
	}
	for (int i = offset; i < getColumnCount(); i++) {
		int minIndex = -1;
		String minName = null;
		for (int j = i; j < getColumnCount(); j++) {
			String currentName = getColumnName(j);
			if (minName == null || currentName.compareTo(minName) < 0) {
				minName = currentName;
				minIndex = j;
			}
		}
		moveColumn(minIndex, i);
	}
}
 
Example 19
Source File: SortForumsActivity.java    From Nimingban with Apache License 2.0 6 votes vote down vote up
@Override
public void onBindViewHolder(ForumHolder holder, int position) {
    if (position > 0) {
        ACForumRaw raw = mLazyList.get(position - 1);
        holder.visibility.setActivated(raw.getVisibility());
        if (mAutoSorting) {
            holder.dragHandler.setVisibility(View.GONE);
            holder.pinning.setVisibility(View.VISIBLE);
            holder.pinning.setActivated(ForumAutoSortingUtils.isACForumPinned(raw));
        } else {
            holder.pinning.setVisibility(View.GONE);
            holder.dragHandler.setVisibility(View.VISIBLE);
        }

        CharSequence name = mForumNames.get(position);
        if (name == null) {
            if (raw.getDisplayname() == null) {
                name = "Forum";
            } else {
                name = Html.fromHtml(raw.getDisplayname());
            }
            mForumNames.put(position, name);
        }
        holder.forum.setText(name);
    }
}
 
Example 20
Source File: NodeMgrTools.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * sort Mappings
 * @param mapping
 * @return List<MapHandle>
 */
public static List<MapHandle> sortMap(Map<?, ?> mapping) {
    List<MapHandle> list = new ArrayList<>();
    Iterator it = mapping.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        MapHandle handle = new MapHandle(key, mapping.get(key));
        list.add(handle);
    }
    Collections.sort(list, new Comparator<MapHandle>() {
        @Override
        public int compare(MapHandle o1, MapHandle o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    return list;
}
 
Example 21
Source File: AbstractLongListUtil.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
public static LongArrayList mergeSort(LongArrayList a, LongArrayList b) {
    int posa=0, posb=0;
    LongArrayList result = new LongArrayList(a.size()+b.size());
    while (posa<a.size() || posb<b.size()) {
        long next;
        if (posa>=a.size()) {
            next=b.get(posb++);
        } else if (posb>=b.size()) {
            next=a.get(posa++);
        } else if (a.get(posa)<=b.get(posb)) {
            next=a.get(posa++);
        } else {
            next=b.get(posb++);
        }
        Preconditions.checkArgument(result.isEmpty() || result.get(result.size()-1)<=next,
                "The input lists are not sorted");
        result.add(next);
    }
    return result;
}
 
Example 22
Source File: KerasTokenizer.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Sort HashMap by values in reverse order
 *
 * @param map input HashMap
 * @return sorted HashMap
 */
private static HashMap reverseSortByValues(HashMap map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
                    .compareTo(((Map.Entry) (o2)).getValue());
        }
    });
    HashMap sortedHashMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        sortedHashMap.put(entry.getKey(), entry.getValue());
    }
    return sortedHashMap;
}
 
Example 23
Source File: RichLazyDataModel.java    From development with Apache License 2.0 6 votes vote down vote up
public void toggleSort() {
    for (Map.Entry<String, org.richfaces.component.SortOrder> entry : sortOrders
            .entrySet()) {
        org.richfaces.component.SortOrder newOrder;

        if (entry.getKey().equals(sortProperty)) {
            if (entry.getValue() == org.richfaces.component.SortOrder.ascending) {
                newOrder = org.richfaces.component.SortOrder.descending;
            } else {
                newOrder = org.richfaces.component.SortOrder.ascending;
            }
        } else {
            newOrder = org.richfaces.component.SortOrder.unsorted;
        }

        entry.setValue(newOrder);
    }
}
 
Example 24
Source File: SortOp.java    From flowmix with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {

  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  SortOp sortOp = (SortOp) o;

  if (clearOnTrigger != sortOp.clearOnTrigger) return false;
  if (evictionThreshold != sortOp.evictionThreshold) return false;
  if (triggerThreshold != sortOp.triggerThreshold) return false;
  if (evictionPolicy != sortOp.evictionPolicy) return false;
  if (sortBy != null ? !sortBy.equals(sortOp.sortBy) : sortOp.sortBy != null) return false;
  if (triggerPolicy != sortOp.triggerPolicy) return false;

  return true;
}
 
Example 25
Source File: TestSort.java    From tracingplane-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSimpleSort() {
    ByteBuffer payloadA = ByteBuffer.allocate(4);
    payloadA.putInt(0, 100);

    ByteBuffer payloadB = ByteBuffer.allocate(4);
    payloadB.putInt(0, 55);
    
    BaggageWriter writer = BaggageWriter.create();
    writer.writeBytes(payloadA);
    writer.writeBytes(payloadB);
    writer.sortData();
    
    List<ByteBuffer> atoms = writer.atoms();
    
    BaggageReader reader = BaggageReader.create(atoms);
    ByteBuffer firstRead = reader.nextData();
    ByteBuffer secondRead = reader.nextData();
    
    assertEquals(payloadB, firstRead);
    assertEquals(payloadA, secondRead);
}
 
Example 26
Source File: CustomizeComparator.java    From oncokb with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sortKitTreatment(List<IndicatorQueryTreatment> treatments) {
    if (treatments == null)
        return;
    Collections.sort(treatments, new Comparator<IndicatorQueryTreatment>() {
        public int compare(IndicatorQueryTreatment t1, IndicatorQueryTreatment t2) {
            if (t1.getLevel() != null
                && t2.getLevel() != null
                && t1.getLevel().equals(t2.getLevel())
                && t1.getDrugs() != null
                && t2.getDrugs() != null
                && t1.getDrugs().size() == 1
                && t2.getDrugs().size() == 1
                ) {
                return compareKitTreatmentOrder(
                    t1.getDrugs().get(0).getDrugName(),
                    t2.getDrugs().get(0).getDrugName()
                );
            } else {
                return 0;
            }
        }
    });
}
 
Example 27
Source File: SaneImage.java    From jfreesane with Apache License 2.0 6 votes vote down vote up
private static int frameSortOrder(Frame frame) {
  switch (frame.getType()) {
    case RED:
      return 0;
    case GREEN:
      return 1;
    case BLUE:
      return 2;
    case RGB:
      return 3;
    case GRAY:
      return 4;
    default:
      throw new IllegalArgumentException("unknown frame type " + frame.getType());
  }
}
 
Example 28
Source File: TestSort.java    From tracingplane-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testMultiSort() {
    int numbufs = 100;
    ByteBuffer[] bufs = new ByteBuffer[numbufs];
    for (int i = 0; i < numbufs; i++) {
        bufs[i] = ByteBuffer.allocate(4);
        bufs[i].putInt(0, numbufs-i-1);
    }
    
    BaggageWriter writer = BaggageWriter.create();
    for (int i = 0; i < numbufs; i++) {
        writer.writeBytes(bufs[i]);
    }
    writer.sortData();
    
    List<ByteBuffer> atoms = writer.atoms();
    
    BaggageReader reader = BaggageReader.create(atoms);
    for (int i = 0; i < numbufs; i++) {
        ByteBuffer bufRead = reader.nextData();
        assertEquals(bufs[numbufs-i-1], bufRead);
    }
}
 
Example 29
Source File: LeaderBoardTileSkin.java    From tilesfx with Apache License 2.0 6 votes vote down vote up
private void sortItems() {
    List<LeaderBoardItem> items = tile.getLeaderBoardItems();
    switch(tile.getItemSorting()) {
        case ASCENDING :
            switch(tile.getItemSortingTopic()) {
                case TIMESTAMP: items.sort(Comparator.comparing(LeaderBoardItem::getTimestamp)); break;
                case DURATION : items.sort(Comparator.comparing(LeaderBoardItem::getDuration)); break;
                case VALUE    :
                default       : items.sort(Comparator.comparing(LeaderBoardItem::getValue)); break;
            }
            break;
        case DESCENDING:
            switch(tile.getItemSortingTopic()) {
                case TIMESTAMP: items.sort(Comparator.comparing(LeaderBoardItem::getTimestamp).reversed()); break;
                case DURATION : items.sort(Comparator.comparing(LeaderBoardItem::getDuration).reversed()); break;
                case VALUE    :
                default       : items.sort(Comparator.comparing(LeaderBoardItem::getValue).reversed()); break;
            }
            break;
        case NONE:
        default: break;
    }
    items.forEach(i -> i.setIndex(items.indexOf(i)));
    updateChart();
}
 
Example 30
Source File: Sort.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Sort(String description) {
    this();
    if (description.startsWith("date:")) {
        this.option = Option.DATE;
        description = description.substring(5);
        if (description.startsWith("A")) {
            this.direction = SortOrder.ASC;
        } else {
            this.direction = SortOrder.DESC;
        }
    }
    if (description.startsWith("meta:")) {
        this.option = Option.METADATA;
        description = description.substring(5);
        int p = description.indexOf(':');
        if (p >= 0) {
            this.metafield = description.substring(0, p);
            description = description.substring(p + 1);
            if (description.startsWith("A")) {
                this.direction = SortOrder.ASC;
            } else {
                this.direction = SortOrder.DESC;
            }
        }
    }
}
 
Example 31
Source File: SearchUtils.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private SortOrder getValidSortOrder(String direction, SortOrder defaultValue) {
  if (direction != null) {
    switch (direction.toLowerCase()) {
      case "asc":
      case "ascending":
        return SortOrder.ASC;
      case "desc":
      case "descending":
        return SortOrder.DESC;
      default:
        break;
    }
  }

  return defaultValue;
}
 
Example 32
Source File: SortColors.java    From albert with MIT License 6 votes vote down vote up
public void sortColors(int[] nums) {
    int left = 0,right = nums.length-1;
    int temp = 0;
    for(int i=0;i<=right;)
        if(nums[i]==1){
            i++;
        }else if(nums[i]==0){
            temp = nums[left];
            nums[left] = nums[i];
            nums[i] = temp;
            left++;
            i++;

        }else{
            temp = nums[right];
            nums[right] = nums[i];
            nums[i] = temp;
            right--;
        }
}
 
Example 33
Source File: BaseSearchService.java    From albert with MIT License 6 votes vote down vote up
protected SortBuilder addSort(SearchParam param){
		Integer sort = param.getSort();
		
//		if(null==sort){
//			return SortBuilders.fieldSort("lastRefresh").order(SortOrder.DESC);
//		}else if(Constants.Sort.nearest == sort){
//			return SortBuilders.geoDistanceSort("geoPoint").point(param.getLat(), param.getLon()).order(SortOrder.ASC);
//		
//		} else if(Constants.Sort.pageView == sort){
//			return SortBuilders.fieldSort("reviewNum").order(SortOrder.DESC);
//		
//		} else if(Constants.Sort.score == sort){
//			return SortBuilders.fieldSort("avgScore").order(SortOrder.DESC);
//		
//		} else if(Constants.Sort.priceAsc == sort){
//			return SortBuilders.fieldSort("price").order(SortOrder.ASC);
//		
//		} else if(Constants.Sort.priceDesc == sort){
//			return SortBuilders.fieldSort("price").order(SortOrder.DESC);
//		
//		}
		
		return SortBuilders.fieldSort("addTime").order(SortOrder.DESC);
	}
 
Example 34
Source File: BisqDefaultCoinSelector.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, b) -> {
        int depth1 = a.getParentTransactionDepthInBlocks();
        int depth2 = b.getParentTransactionDepthInBlocks();
        Coin aValue = a.getValue();
        Coin bValue = b.getValue();
        BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
        BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
        int c1 = bCoinDepth.compareTo(aCoinDepth);
        if (c1 != 0) return c1;
        // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
        int c2 = bValue.compareTo(aValue);
        if (c2 != 0) return c2;
        // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
        BigInteger aHash = a.getParentTransactionHash() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example 35
Source File: BisqDefaultCoinSelector.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortOutputs(ArrayList<TransactionOutput> outputs) {
    Collections.sort(outputs, (a, b) -> {
        int depth1 = a.getParentTransactionDepthInBlocks();
        int depth2 = b.getParentTransactionDepthInBlocks();
        Coin aValue = a.getValue();
        Coin bValue = b.getValue();
        BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1));
        BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2));
        int c1 = bCoinDepth.compareTo(aCoinDepth);
        if (c1 != 0) return c1;
        // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size.
        int c2 = bValue.compareTo(aValue);
        if (c2 != 0) return c2;
        // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering.
        BigInteger aHash = a.getParentTransactionHash() != null ?
                a.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        BigInteger bHash = b.getParentTransactionHash() != null ?
                b.getParentTransactionHash().toBigInteger() : BigInteger.ZERO;
        return aHash.compareTo(bHash);
    });
}
 
Example 36
Source File: DefaultKeyedValues.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the items in the list by key.
 *
 * @param order  the sort order (<code>null</code> not permitted).
 */
public void sortByKeys(SortOrder order) {
    final int size = this.keys.size();
    final DefaultKeyedValue[] data = new DefaultKeyedValue[size];

    for (int i = 0; i < size; i++) {
        data[i] = new DefaultKeyedValue((Comparable) this.keys.get(i),
                (Number) this.values.get(i));
    }

    Comparator comparator = new KeyedValueComparator(
            KeyedValueComparatorType.BY_KEY, order);
    Arrays.sort(data, comparator);
    clear();

    for (int i = 0; i < data.length; i++) {
        final DefaultKeyedValue value = data[i];
        addValue(value.getKey(), value.getValue());
    }
}
 
Example 37
Source File: CategorySelectionBeanTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void sortCategories() {
    // given
    givenUnsortedCategories();

    // when
    categorySelectionBean.sortCategories();

    // then
    List<VOCategory> categories = categorySelectionBean.categoriesForMarketplace;
    assertEquals("%", categories.get(0).getName());
    assertEquals("&", categories.get(1).getName());
    assertEquals("A", categories.get(2).getName());
    assertEquals("a", categories.get(3).getName());
    assertEquals("Aa", categories.get(4).getName());
    assertEquals("aA", categories.get(5).getName());
    assertEquals("B", categories.get(6).getName());
    assertEquals("b", categories.get(7).getName());
}
 
Example 38
Source File: SortElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Calculates the required text edits to sort the <code>unit</code>
 * @param group
 * @return the edit or null if no sorting is required
 */
public TextEdit calculateEdit(org.eclipse.jdt.core.dom.CompilationUnit unit, TextEditGroup group) throws JavaModelException {
	if (this.elementsToProcess.length != 1)
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS));

	if (!(this.elementsToProcess[0] instanceof ICompilationUnit))
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this.elementsToProcess[0]));

	try {
		beginTask(Messages.operation_sortelements, getMainAmountOfWork());

		ICompilationUnit cu= (ICompilationUnit)this.elementsToProcess[0];
		String content= cu.getBuffer().getContents();
		ASTRewrite rewrite= sortCompilationUnit(unit, group);
		if (rewrite == null) {
			return null;
		}

		Document document= new Document(content);
		return rewrite.rewriteAST(document, cu.getJavaProject().getOptions(true));
	} finally {
		done();
	}
}
 
Example 39
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
public SortManager(boolean directoriesFirst) {
    resourceNameComparator = new ResourceNameComparator();
    resourceNameComparatorAsc = Collections.reverseOrder(resourceNameComparator);
    resourceSizeComparator = new ResourceSizeComparator(resourceNameComparator);
    resourceSizeComparatorAsc = Collections.reverseOrder(resourceSizeComparator);
    resourceLastModifiedComparator = new ResourceLastModifiedDateComparator(resourceNameComparator);
    resourceLastModifiedComparatorAsc = Collections.reverseOrder(resourceLastModifiedComparator);

    if(directoriesFirst) {
        resourceNameComparator = new DirsFirstComparator(resourceNameComparator);
        resourceNameComparatorAsc = new DirsFirstComparator(resourceNameComparatorAsc);
        resourceSizeComparator = new DirsFirstComparator(resourceSizeComparator);
        resourceSizeComparatorAsc = new DirsFirstComparator(resourceSizeComparatorAsc);
        resourceLastModifiedComparator = new DirsFirstComparator(resourceLastModifiedComparator);
        resourceLastModifiedComparatorAsc = new DirsFirstComparator(resourceLastModifiedComparatorAsc);
    }

    defaultResourceComparator = resourceNameComparator;
}
 
Example 40
Source File: DataSet.java    From Neural-Network-Programming-with-Java-SecondEdition with MIT License 6 votes vote down vote up
public void sortBy(int col){
    double[] value = this.getData(col);
    double[] ordered = ArrayOperations.quickSort(value);
    int[] ordIndexes = ArrayOperations.getIndexes(value, ordered);
    ArrayList<ArrayList<Double>> newData = new ArrayList<>();
    for(int i=0;i<numberOfRecords;i++){
        ArrayList<Double> newLine = new ArrayList<>();            
        for(int j=0;j<numberOfColumns;j++){
            double v = data.get(ordIndexes[i]).get(j);
            newLine.add(v);
        }
        newData.add(newLine);
    }
    this.data=newData;

}
 
Example 41
Source File: SubscriptionDaoIT_Paging_Sorting_Supplier.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void getSubscriptionsForMyCustomersAscendingSortByActivationTime()
        throws Exception {
    // given
    final Sorting sorting = new Sorting(TableColumns.ACTIVATION_TIME,
            SortOrder.ASC);
    Set<Filter> filterSet = createFilterSet(null, null,
            SUPPLIER_CUSTOMER_FOR_ACTTIME, null, null);
    final Pagination pagination = createPagination(0,
            NUM_CUSTOMER_SUBSCRIPTIONS, sorting, filterSet);

    // when
    List<Subscription> result = runTX(new Callable<List<Subscription>>() {
        @Override
        public List<Subscription> call() throws Exception {
            return dao.getSubscriptionsForMyCustomers(supplierUser, states,
                    pagination);
        }
    });

    // then
    assertEquals(NUM_ACTIVATION_TIMES, result.size());
    for (int i = 0; i < result.size(); i++)
        assertEquals(SUBSCRIPTION_ID_FOR_ACTIVATION_TIME_CASE + i,
                result.get(i).getSubscriptionId());
}
 
Example 42
Source File: SubscriptionDaoIT_Paging_Sorting_Supplier.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void getSubscriptionsForMyCustomersAscendingSortBySubscriptionId()
        throws Exception {
    // given
    final Sorting sorting = new Sorting(TableColumns.SUBSCRIPTION_ID,
            SortOrder.ASC);
    Set<Filter> filterSet = createFilterSet(null, null,
            SUPPLIER_CUSTOMER_FOR_SUB_ID_SORTING, null, null);
    final Pagination pagination = createPagination(0,
            NUM_CUSTOMER_SUBSCRIPTIONS, sorting, filterSet);

    // when
    List<Subscription> result = runTX(new Callable<List<Subscription>>() {
        @Override
        public List<Subscription> call() throws Exception {
            return dao.getSubscriptionsForMyCustomers(supplierUser, states,
                    pagination);
        }
    });

    // then
    assertEquals(NUM_SUBSCRIPTIONS, result.size());
    for (int i = 0; i < result.size(); i++)
        assertEquals(SUBSCRIPTION_ID_FOR_SUB_ID_CASE + i,
                result.get(i).getSubscriptionId());
}
 
Example 43
Source File: PageOf.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 把要代入查grid的 hql 的 map 參數加上 order by 條件
 * orderBy		如 kpi.id, kpi.name
 * sortType		如 ASC 或 DESC
 * @param queryParam
 */
public Map<String, Object> setQueryOrderSortParameter(Map<String, Object> queryParam) {
	if (queryParam == null) {
		return queryParam;
	}
	if (queryParam.get(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY) == null) {
		if (!StringUtils.isBlank(this.getOrderBy())) {
			queryParam.put(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY, this.getOrderBy());
		}
	}
	if (queryParam.get(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE) == null) {
		if (!StringUtils.isBlank(this.getSortType())) {
			queryParam.put(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE, this.getSortType());
		}
	}
	return queryParam;
}
 
Example 44
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void quickSort(char[][] list, int left, int right) {
	int original_left= left;
	int original_right= right;
	char[] mid= list[left + (right - left) / 2];
	do {
		while (compare(list[left], mid) < 0) {
			left++;
		}
		while (compare(mid, list[right]) < 0) {
			right--;
		}
		if (left <= right) {
			char[] tmp= list[left];
			list[left]= list[right];
			list[right]= tmp;
			left++;
			right--;
		}
	} while (left <= right);
	if (original_left < right) {
		quickSort(list, original_left, right);
	}
	if (left < original_right) {
		quickSort(list, left, original_right);
	}
}
 
Example 45
Source File: Node.java    From smithy with Apache License 2.0 6 votes vote down vote up
private static Node sortNode(Node node, Comparator<StringNode> keyComparator) {
    return node.accept(new NodeVisitor.Default<Node>() {
        @Override
        protected Node getDefault(Node node) {
            return node;
        }

        @Override
        public Node objectNode(ObjectNode node) {
            Map<StringNode, Node> members = new TreeMap<>(keyComparator);
            node.getMembers().forEach((k, v) -> members.put(k, sortNode(v, keyComparator)));
            return new ObjectNode(members, node.getSourceLocation());
        }

        @Override
        public Node arrayNode(ArrayNode node) {
            return node.getElements().stream()
                    .map(element -> sortNode(element, keyComparator))
                    .collect(ArrayNode.collect(node.getSourceLocation()));
        }
    });
}
 
Example 46
Source File: Util.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void reverseQuickSort(char[][] list, int left, int right) {
	int original_left= left;
	int original_right= right;
	char[] mid= list[left + ((right-left)/2)];
	do {
		while (CharOperation.compareTo(list[left], mid) > 0) {
			left++;
		}
		while (CharOperation.compareTo(mid, list[right]) > 0) {
			right--;
		}
		if (left <= right) {
			char[] tmp= list[left];
			list[left]= list[right];
			list[right]= tmp;
			left++;
			right--;
		}
	} while (left <= right);
	if (original_left < right) {
		reverseQuickSort(list, original_left, right);
	}
	if (left < original_right) {
		reverseQuickSort(list, left, original_right);
	}
}
 
Example 47
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void sortIn(ImportDeclEntry imp) {
	String fullImportName= imp.getElementName();
	int insertPosition= -1;
	int nInports= this.importEntries.size();
	for (int i= 0; i < nInports; i++) {
		ImportDeclEntry curr= getImportAt(i);
		if (!curr.isComment()) {
			int cmp= curr.compareTo(fullImportName, imp.isStatic());
			if (cmp == 0) {
				return; // exists already
			} else if (cmp > 0 && insertPosition == -1) {
				insertPosition= i;
			}
		}
	}
	if (insertPosition == -1) {
		this.importEntries.add(imp);
	} else {
		this.importEntries.add(insertPosition, imp);
	}
}
 
Example 48
Source File: MapUtils.java    From FuzzDroid with Apache License 2.0 6 votes vote down vote up
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(
		Map<K, V> map) {
	List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(
			map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
			return -(o1.getValue()).compareTo(o2.getValue());
		}
	});

	Map<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}
 
Example 49
Source File: SAXVSMDirectSampler.java    From sax-vsm_classic with GNU General Public License v2.0 6 votes vote down vote up
/**
 * returns sorted array and the original indicies
 * 
 * @param array
 * @return
 */
private static double[][] sort(double[] array) {
  double[][] arr1 = new double[3][array.length];
  double[][] arr2 = new double[2][array.length];
  System.arraycopy(array, 0, arr1[0], 0, array.length);
  Arrays.sort(array);
  for (int i = 0; i < array.length; i++) {
    for (int i1 = 0; i1 < array.length; i1++) {
      if (array[i] == arr1[0][i1] && arr1[2][i1] != 1) {
        arr1[2][i1] = 1;
        arr1[1][i] = i1;
        break;
      }
    }
  }
  arr2[0] = array;
  arr2[1] = arr1[1];
  return arr2;
}
 
Example 50
Source File: UsersEntityTest.java    From auth0-java with MIT License 6 votes vote down vote up
@Test
public void shouldListUsersWithSort() throws Exception {
    UserFilter filter = new UserFilter().withSort("date:1");
    Request<UsersPage> request = api.users().list(filter);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_USERS_LIST, 200);
    UsersPage response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/users"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("sort", "date:1"));

    assertThat(response, is(notNullValue()));
    assertThat(response.getItems(), hasSize(2));
}
 
Example 51
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private int sortParticipants(ArrayList group, IConfigurationElement[] configElements, int index) {
	int size = group.size();
	if (size == 0) return index;
	Object[] elements = group.toArray();
	Util.sort(elements, new Util.Comparer() {
		public int compare(Object a, Object b) {
			if (a == b) return 0;
			String id = ((IConfigurationElement) a).getAttribute("id"); //$NON-NLS-1$
			if (id == null) return -1;
			IConfigurationElement[] requiredElements = ((IConfigurationElement) b).getChildren("requires"); //$NON-NLS-1$
			for (int i = 0, length = requiredElements.length; i < length; i++) {
				IConfigurationElement required = requiredElements[i];
				if (id.equals(required.getAttribute("id"))) //$NON-NLS-1$
					return 1;
			}
			return -1;
		}
	});
	for (int i = 0; i < size; i++)
		configElements[index+i] = (IConfigurationElement) elements[i];
	return index + size;
}
 
Example 52
Source File: PdfCollectionSort.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Defines the sort order of the field (ascending or descending).
 * @param ascending	an array with every element corresponding with a name of a field.
 */
public void setSortOrder(boolean[] ascending) {
	PdfObject o = get(PdfName.S);
	if (o instanceof PdfArray) {
		if (((PdfArray)o).size() != ascending.length) {
			throw new IllegalArgumentException("The number of booleans in this array doesn't correspond with the number of fields.");
		}
		PdfArray array = new PdfArray();
		for (int i = 0; i < ascending.length; i++) {
			array.add(new PdfBoolean(ascending[i]));
		}
		put(PdfName.A, array);
	}
	else {
		throw new IllegalArgumentException("You need a single boolean for this collection sort dictionary.");
	}
}
 
Example 53
Source File: HollowCombiner.java    From hollow with Apache License 2.0 6 votes vote down vote up
private List<PrimaryKey> sortPrimaryKeys(List<PrimaryKey> primaryKeys) {
    final List<HollowSchema> dependencyOrderedSchemas = HollowSchemaSorter.dependencyOrderedSchemaList(output.getSchemas());
    primaryKeys.sort(new Comparator<PrimaryKey>() {
        public int compare(PrimaryKey o1, PrimaryKey o2) {
            return schemaDependencyIdx(o1) - schemaDependencyIdx(o2);
        }

        private int schemaDependencyIdx(PrimaryKey key) {
            for (int i = 0; i < dependencyOrderedSchemas.size(); i++) {
                if (dependencyOrderedSchemas.get(i).getName().equals(key.getType()))
                    return i;
            }
            throw new IllegalArgumentException("Primary key defined for non-existent type: " + key.getType());
        }
    });
    
    return primaryKeys;
}
 
Example 54
Source File: Sort.java    From offer with Apache License 2.0 6 votes vote down vote up
/**
 * 归并排序
 * 将数组分为一各个小块,对每一块进行排序再合并
 * @param nums
 */
public void mergeSort(int[] nums,int start,int end){
    // 当元素数量小于 3 时,不再向下分
    if (end == start) {
        return;
    }
    if (end - start == 1) {
        if (nums[start] > nums[end]) {
            swap(nums, start, end);
        }
        return;
    }
    int mid = (start + end) >>> 1;
    // 排序左区间
    mergeSort(nums, start, mid);
    // 排序右区间
    mergeSort(nums, mid + 1, end);
    // 合并两个有序区间
    merge(nums, start, mid, mid + 1, end);
}
 
Example 55
Source File: Sort.java    From offer with Apache License 2.0 6 votes vote down vote up
/**
 * 实现插入排序
 * 将元素分为有序区和无序区两个部分
 * 每次从无序区取出一个数,将数据搬迁,将数字插入无序区有序位置,
 * @param nums
 */
public void insertSort(int[] nums) {
    if (nums == null || nums.length < 2) {
        return;
    }
    // 默认第一数为有序区
    for (int i = 1; i < nums.length; i++) { // 无序区
        int j = i-1;
        int temp = nums[i];
        // 逆序查找有序区插入位置,当 temp<nums[j] 时插入
        for (; j >= 0; j--) {
            if (nums[j] > temp) {
                // 将数据搬迁
                nums[j + 1] = nums[j];
            } else {
                break;
            }
        }
        nums[j+1] = temp;
    }
}
 
Example 56
Source File: GroupbyResultSet.java    From baymax with Apache License 2.0 6 votes vote down vote up
/**
 * 分组排序
 *
 * TODO 优化:必须有order by 没有order by的 在解析的时候用 groupby的字段 作为orderby 重写sql,这样可以避免内存排序
 */
private void sort(){
    if (orderbyColumns == null || orderbyColumns.size() == 0){
        return;
    }
    if (groupbyValues == null || groupbyValues.length == 0){
        return;
    }
    Arrays.sort(groupbyValues, new Comparator<GroupbyValue>() {
        OrderByComparetor comparetor = new OrderByComparetor(orderbyColumns);
        @Override
        public int compare(final GroupbyValue v1, final GroupbyValue v2) {
            try {
                return comparetor.compare(v1, v2);
            } catch (SQLException e) {
                throw new BayMaxException("Group by ...Order by... 排序失败" , e);
            }
        }
    });
}
 
Example 57
Source File: MetaDataStatisticsController.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Sorts the {@link AbstractAttributeStatisticsModel}s via their attribute names.
 *
 * @param direction
 */
private void sortByName(List<AbstractAttributeStatisticsModel> list, final SortingDirection direction) {
	sort(list, (o1, o2) -> {
		int sortResult = o1.getAttribute().getName().compareTo(o2.getAttribute().getName());
		switch (direction) {
			case ASCENDING:
				return -1 * sortResult;
			case DESCENDING:
				return sortResult;
			case UNDEFINED:
				return 0;
			default:
				return sortResult;
		}
	});
}
 
Example 58
Source File: ExecutionCourseBibliographyDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward prepareSortBibliography(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {
    ExecutionCourse executionCourse = getExecutionCourse(request);
    boolean optional = request.getParameter("optional") != null;
    List<BibliographicReference> references;

    if (optional) {
        references = getOptionalBibliographicReferences(executionCourse);
    } else {
        references = getMainBibliographicReferences(executionCourse);
    }

    request.setAttribute("references", references);
    request.setAttribute("optional", optional);

    return forward(request, "/teacher/executionCourse/orderBibliographicReferences.jsp");
}
 
Example 59
Source File: SortContainersComparator.java    From vertexium with Apache License 2.0 6 votes vote down vote up
private int compareProperty(QueryBase.PropertySortContainer sortContainer, VertexiumObject elem1, VertexiumObject elem2) {
    List<Object> elem1PropertyValues = toList(elem1.getPropertyValues(sortContainer.propertyName));
    List<Object> elem2PropertyValues = toList(elem2.getPropertyValues(sortContainer.propertyName));
    if (elem1PropertyValues.size() > 0 && elem2PropertyValues.size() == 0) {
        return -1;
    } else if (elem2PropertyValues.size() > 0 && elem1PropertyValues.size() == 0) {
        return 1;
    } else {
        for (Object elem1PropertyValue : elem1PropertyValues) {
            for (Object elem2PropertyValue : elem2PropertyValues) {
                int result = comparePropertyValues(elem1PropertyValue, elem2PropertyValue);
                if (result != 0) {
                    return sortContainer.direction == SortDirection.ASCENDING ? result : -result;
                }
            }
        }
    }
    return 0;
}
 
Example 60
Source File: ElasticsearchSearchQueryBase.java    From vertexium with Apache License 2.0 6 votes vote down vote up
private void applySortStrategy(SearchRequestBuilder q, SortingStrategySortContainer sortContainer) {
    SortingStrategy sortingStrategy = sortContainer.sortingStrategy;
    if (!(sortingStrategy instanceof ElasticsearchSortingStrategy)) {
        throw new VertexiumException(String.format(
            "sorting strategies must implement %s to work with Elasticsearch",
            ElasticsearchSortingStrategy.class.getName()
        ));
    }
    ((ElasticsearchSortingStrategy) sortingStrategy).updateElasticsearchQuery(
        getGraph(),
        getSearchIndex(),
        q,
        getParameters(),
        sortContainer.direction
    );
}