Assign fair share if total share < min demand.

@param totalShare   The share to be distributed.
@param schedulables The collection of schedulables
@return Excess share after assigning the min demand to each schedulable.
348261
private static double assignShareIfUnderAllocated(
      double totalShare,
      final Collection<? extends Schedulable> schedulables) {

    double totalMinDemand = 0;
    for (Schedulable schedulable : schedulables) {
      schedulable.share = 0;
      totalMinDemand += Math.min(schedulable.getRequested(),
                                 schedulable.getMinimum());
    }

    if ((totalMinDemand > 0) && (totalMinDemand >= totalShare)) {
      distributeShareMin(schedulables);
    }

    return totalShare - totalMinDemand;
  }
478683
public function allocate(array $ratios, $precision = self::PRECISION_CURRENCY)
    {
        $precision  = $this->castPrecision($precision);
        $remainder  = $this->amount;
        $results    = [];
        $total      = Decimal::create(array_sum($ratios), $precision);

        foreach ($ratios as $ratio) {
            $share = $this->amount
                ->mul(Decimal::create($ratio, $precision), $precision)
                ->div($total, $precision);

            $results[] = $this->newInstance($share);
            $remainder = $remainder->sub($share, $precision);
        }

        $minValue = Decimal::create(
            $precision ? '0.' . str_repeat('0', $precision - 1) . '1' : 1
        );

        for ($i = 0; !$remainder->isZero($precision); $i++) {
            if ($remainder->isPositive()) {
                $remainder = $remainder->sub($minValue, $precision);
                $results[$i]->amount = $results[$i]->amount->add($minValue, $precision);
            } else {
                $remainder = $remainder->add($minValue, $precision);
                $results[$i]->amount = $results[$i]->amount->sub($minValue, $precision);
            }
        }

        return $results;
    }
1044147
public void setSharedSet(com.google.api.ads.adwords.axis.v201809.cm.SharedSet sharedSet) {
        this.sharedSet = sharedSet;
    }
615539
public static List<PartitionDefinition> assignPartitions(List<PartitionDefinition> partitions, int currentTask, int totalTasks) {
        int esPartitions = partitions.size();
        if (totalTasks >= esPartitions) {
            return (currentTask >= esPartitions ? Collections.<PartitionDefinition>emptyList() : Collections.singletonList(partitions.get(currentTask)));
        } else {
            int partitionsPerTask = esPartitions / totalTasks;
            int remainder = esPartitions % totalTasks;

            int partitionsPerCurrentTask = partitionsPerTask;

            // spread the reminder against the tasks
            if (currentTask < remainder) {
                partitionsPerCurrentTask++;
            }

            // find the offset inside the collection
            int offset = partitionsPerTask * currentTask;
            if (currentTask != 0) {
                offset += (remainder > currentTask ? 1 : remainder);
            }

            // common case
            if (partitionsPerCurrentTask == 1) {
                return Collections.singletonList(partitions.get(offset));
            }

            List<PartitionDefinition> pa = new ArrayList<PartitionDefinition>(partitionsPerCurrentTask);
            for (int index = offset; index < offset + partitionsPerCurrentTask; index++) {
                pa.add(partitions.get(index));
            }
            return pa;
        }
    }
1138305
protected void accumulatePersistedWorkspaceChanges(long delta) throws QuotaManagerException
   {
      long dataSize = 0;
      try
      {
         dataSize = quotaPersister.getWorkspaceDataSize(rName, wsName);
      }
      catch (UnknownDataSizeException e)
      {
         if (LOG.isTraceEnabled())
         {
            LOG.trace(e.getMessage(), e);
         }
      }

      long newDataSize = Math.max(dataSize + delta, 0); // avoid possible inconsistency
      quotaPersister.setWorkspaceDataSize(rName, wsName, newDataSize);
   }
692586
public boolean distributeForget() throws SystemException {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "distributeForget", this);

        boolean retryRequired = false; // indicates whether retry necessary
        final int resourceCount = _resourceObjects.size();

        // Browse through the participants, processing them as appropriate
        for (int i = 0; i < resourceCount; i++) {
            final JTAResource currResource = _resourceObjects.get(i);

            switch (currResource.getResourceStatus()) {
                case StatefulResource.HEURISTIC_COMMIT:
                case StatefulResource.HEURISTIC_ROLLBACK:
                case StatefulResource.HEURISTIC_MIXED:
                case StatefulResource.HEURISTIC_HAZARD:
                    if (forgetResource(currResource)) {
                        retryRequired = true;
                        _retryRequired = true;
                    }
                    break;

                default: // do nothing
                    break;

            } // end switch

        } // end for

        if (_systemException != null) {
            final Throwable toThrow = new SystemException().initCause(_systemException);
            if (tc.isEntryEnabled())
                Tr.exit(tc, "distributeForget", toThrow);
            throw (SystemException) toThrow;
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "distributeForget", retryRequired);
        return retryRequired;
    }
516080
public boolean isStarving(long now) {
    double starvingShare = getShare() * shareStarvingRatio;
    if (getGranted() >= Math.ceil(starvingShare)) {
      lastTimeAboveStarvingShare = now;
    }

    if (getGranted() >= Math.min(getShare(), getMinimum())) {
      lastTimeAboveMinimum = now;
    }
    if (now - lastPreemptTime < getMinPreemptPeriod()) {
      // Prevent duplicate preemption
      return false;
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Pool:" + getName() +
          " lastTimeAboveMinimum:" + lastTimeAboveMinimum +
          " lastTimeAboveStarvingShare:" + lastTimeAboveStarvingShare +
          " minimumStarvingTime:" + getMinimumStarvingTime(now) +
          " shareStarvingTime:" + getShareStarvingTime(now) +
          " starvingTime:" + getStarvingTime(now));
    }
    if (getMinimumStarvingTime(now) >= 0) {
      LOG.info("Pool:" + getName() + " for type:" + getType() +
          " is starving min:" + getMinimum() +
          " granted:" + getGranted());
      lastPreemptTime = now;
      return true;
    }
    if (getShareStarvingTime(now) >= 0) {
      LOG.info("Pool:" + getName() + " for type:" + getType() +
          " is starving share:" + getShare() +
          " starvingRatio:" + shareStarvingRatio +
          " starvingShare:" + starvingShare +
          " granted:" + getGranted());
      lastPreemptTime = now;
      return true;
    }
    return false;
  }
1316024
protected void populateTasksByStealer(List<StealerBasedRebalanceTask> sbTaskList) {
        // Setup mapping of stealers to work for this run.
        for(StealerBasedRebalanceTask task: sbTaskList) {
            if(task.getStealInfos().size() != 1) {
                throw new VoldemortException("StealerBasedRebalanceTasks should have a list of RebalancePartitionsInfo of length 1.");
            }

            RebalanceTaskInfo stealInfo = task.getStealInfos().get(0);
            int stealerId = stealInfo.getStealerId();
            if(!this.tasksByStealer.containsKey(stealerId)) {
                this.tasksByStealer.put(stealerId, new ArrayList<StealerBasedRebalanceTask>());
            }
            this.tasksByStealer.get(stealerId).add(task);
        }

        if(tasksByStealer.isEmpty()) {
            return;
        }
        // Shuffle order of each stealer's work list. This randomization
        // helps to get rid of any "patterns" in how rebalancing tasks were
        // added to the task list passed in.
        for(List<StealerBasedRebalanceTask> taskList: tasksByStealer.values()) {
            Collections.shuffle(taskList);
        }
    }
516790
public boolean checkMinimumSlotsAvailable(
      ClusterStatus clusterStatus, TaskType type) {
    Map<String, Integer> poolToMinSlots = (type == TaskType.MAP) ?
        mapAllocs : reduceAllocs;
    int totalSlots = (type == TaskType.MAP) ?
        clusterStatus.getMaxMapTasks() : clusterStatus.getMaxReduceTasks();
    int totalMinSlots = 0;
    for (int minSlots : poolToMinSlots.values()) {
      totalMinSlots += minSlots;
    }
    if (totalMinSlots > totalSlots) {
      LOG.warn(String.format(
          "Bad minimum %s slot configuration. cluster:%s totalMinSlots:%s",
          type, totalSlots, totalMinSlots));
      return false;
    }
    LOG.info(String.format(
        "Minimum %s slots checked. cluster:%s totalMinSlots:%s",
        type, totalSlots, totalSlots));
    return true;
  }
274311
def get_share(self, sharename):
        

        response = GettRequest().get("/shares/%s" % sharename)

        if response.http_status == 200:
            return GettShare(self.user, **response.response)
491014
public static void sharingPolicy(int sharingPolicy) {
        if (verify) {
            if (sharingPolicy != EntryInfo.SHARED_PULL &&
                sharingPolicy != EntryInfo.SHARED_PUSH &&
                sharingPolicy != EntryInfo.SHARED_PUSH_PULL &&
                sharingPolicy != EntryInfo.NOT_SHARED) {
                    throw new IllegalArgumentException("sharingPolicy:"+sharingPolicy);
                }
        }
    }
654691
@Override
  protected double computeCost(
      final DataSegment proposalSegment,
      final ServerHolder server,
      final boolean includeCurrentServer
  )
  {
    double cost = super.computeCost(proposalSegment, server, includeCurrentServer);

    if (cost == Double.POSITIVE_INFINITY) {
      return cost;
    }

    int nSegments = 1;
    if (server.getServer().getLazyAllSegments().size() > 0) {
      nSegments = server.getServer().getLazyAllSegments().size();
    }

    double normalizedCost = cost / nSegments;
    double usageRatio = (double) server.getSizeUsed() / (double) server.getServer().getMaxSize();

    return normalizedCost * usageRatio;
  }
1012679
public void setShareErrors(java.util.Collection<ShareError> shareErrors) {
        if (shareErrors == null) {
            this.shareErrors = null;
            return;
        }

        this.shareErrors = new java.util.ArrayList<ShareError>(shareErrors);
    }
99855
private void splitDays(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
   {
      LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();
      boolean remainderInserted = false;
      
      for (TimephasedWork assignment : list)
      {
         if (remainderInserted)
         {
            assignment.setStart(DateHelper.addDays(assignment.getStart(), 1));
            remainderInserted = false;
         }

         while (assignment != null)
         {
            Date startDay = DateHelper.getDayStartDate(assignment.getStart());
            Date finishDay = DateHelper.getDayStartDate(assignment.getFinish());

            // special case - when the finishday time is midnight, it's really the previous day...
            if (assignment.getFinish().getTime() == finishDay.getTime())
            {
               finishDay = DateHelper.addDays(finishDay, -1);
            }

            if (startDay.getTime() == finishDay.getTime())
            {
               Duration totalWork = assignment.getTotalAmount();
               Duration assignmentWork = getAssignmentWork(calendar, assignment);
               if ((totalWork.getDuration() - assignmentWork.getDuration()) > EQUALITY_DELTA)
               {
                  assignment.setTotalAmount(assignmentWork);
                  result.add(assignment);
                  Duration remainingWork = Duration.getInstance(totalWork.getDuration() - assignmentWork.getDuration(), TimeUnit.MINUTES);
                  
                  Date remainderStart = DateHelper.addDays(finishDay, 1);
                  Date remainderFinish = DateHelper.addDays(remainderStart, 1);
                  
                  TimephasedWork remainder = new TimephasedWork();
                  remainder.setStart(remainderStart);
                  remainder.setFinish(remainderFinish);
                  remainder.setTotalAmount(remainingWork);
                  result.add(remainder);

                  remainderInserted = true;
               }
               else
               {
                  result.add(assignment);
               }
               break;
            }

            TimephasedWork[] split = splitFirstDay(calendar, assignment);
            if (split[0] != null)
            {
               result.add(split[0]);
            }

            if (assignment.equals(split[1]))
            {
               break;
            }

            assignment = split[1];
         }
      }
     
      list.clear();
      list.addAll(result);
   }
559253
public List<Protos.Resource> takeRanges(String resourceName, int amount, Set<String> roles) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Allocating {} {}", amount, resourceName);
		}

		List<Protos.Resource> result = new ArrayList<>(1);
		for (ListIterator<Protos.Resource> i = resources.listIterator(); i.hasNext();) {
			if (amount <= 0) {
				break;
			}

			// take from next available range resource that is unreserved or reserved for an applicable role
			Protos.Resource available = i.next();
			if (!resourceName.equals(available.getName()) || !available.hasRanges()) {
				continue;
			}
			if (!UNRESERVED_ROLE.equals(available.getRole()) && !roles.contains(available.getRole())) {
				continue;
			}

			List<Protos.Value.Range> takenRanges = new ArrayList<>();
			List<Protos.Value.Range> remainingRanges = new ArrayList<>(available.getRanges().getRangeList());
			for (ListIterator<Protos.Value.Range> j = remainingRanges.listIterator(); j.hasNext();) {
				if (amount <= 0) {
					break;
				}

				// take from next available range (note: ranges are inclusive)
				Protos.Value.Range availableRange = j.next();
				long amountToTake = Math.min(availableRange.getEnd() - availableRange.getBegin() + 1, amount);
				Protos.Value.Range takenRange = availableRange.toBuilder().setEnd(availableRange.getBegin() + amountToTake - 1).build();
				amount -= amountToTake;
				takenRanges.add(takenRange);

				// keep remaining range (if any)
				long remaining = availableRange.getEnd() - takenRange.getEnd();
				if (remaining > 0) {
					j.set(availableRange.toBuilder().setBegin(takenRange.getEnd() + 1).build());
				}
				else {
					j.remove();
				}
			}
			Protos.Resource taken = available.toBuilder().setRanges(Protos.Value.Ranges.newBuilder().addAllRange(takenRanges)).build();
			if (LOG.isDebugEnabled()) {
				LOG.debug("Taking {} from {}", Utils.toString(taken.getRanges()), Utils.toString(available));
			}
			result.add(taken);

			// keep remaining ranges (if any)
			if (remainingRanges.size() > 0) {
				i.set(available.toBuilder().setRanges(Protos.Value.Ranges.newBuilder().addAllRange(remainingRanges)).build());
			}
			else {
				i.remove();
			}
		}

		if (LOG.isDebugEnabled()) {
			LOG.debug("Allocated: {}, unsatisfied: {}", Utils.toString(result), amount);
		}
		return result;
	}
848770
private void updateFairShares(double totalSlots, final TaskType type) {
    // Find the proper ratio of (# of slots share / weight) by bineary search
    BinarySearcher searcher = new BinarySearcher() {
      @Override
      double targetFunction(double x) {
        return slotsUsedWithWeightToSlotRatio(x, type);
      }
    };
    double ratio = searcher.getSolution(totalSlots, lastWeightToFairShareRatio);
    lastWeightToFairShareRatio = ratio;

    // Set the fair shares based on the value of R we've converged to
    for (JobInfo info : infos.values()) {
      if (type == TaskType.MAP) {
        info.mapFairShare = computeShare(info, ratio, type);
      } else {
        info.reduceFairShare = computeShare(info, ratio, type);
      }
    }
  }
816775
private int calculateMaxPendingSplits(int splitAffinity, int totalDepth)
    {
        if (totalDepth == 0) {
            return maxPendingSplitsPerTask;
        }
        // Use half the queue for any split
        // Reserve the other half for splits that have some amount of network affinity
        double queueFraction = 0.5 * (1.0 + splitAffinity / (double) totalDepth);
        return (int) Math.ceil(maxPendingSplitsPerTask * queueFraction);
    }