Returns an integer that is equal to the margin of victory of the election profile, that is,
    the smallest number k such that changing k votes can change the winners.

    :ivar Profile profile: A Profile object that represents an election profile.
4759
def AppMoVMaximin(profile):
    

    # Currently, we expect the profile to contain complete ordering over candidates.
    elecType = profile.getElecType()
    if elecType != "soc" and elecType != "toc":
        print("ERROR: unsupported profile type")
        exit()

    # Initialization
    n = profile.numVoters
    m = profile.numCands

    # Compute the original winner d
    wmgMap = profile.getWmg()
    # Initialize each Copeland score as infinity.
    maximinscores = {}
    for cand in wmgMap.keys():
        maximinscores[cand] = float("inf")

    # For each pair of candidates, calculate the number of votes in which one beat the other.

    # For each pair of candidates, calculate the number of times each beats the other.
    for cand1, cand2 in itertools.combinations(wmgMap.keys(), 2):
        if cand2 in wmgMap[cand1].keys():
            maximinscores[cand1] = min(maximinscores[cand1], wmgMap[cand1][cand2])
            maximinscores[cand2] = min(maximinscores[cand2], wmgMap[cand2][cand1])
    d = max(maximinscores.items(), key=lambda x: x[1])[0]

    #Compute c* = argmax_c maximinscores(c)
    scores_without_d = maximinscores.copy()
    del scores_without_d[d]

    c_star = max(scores_without_d.items(), key=lambda x: x[1])[0]

    return (maximinscores[d] - maximinscores[c_star])/2
122586
@Override
    public double[] getVotesForInstance(Instance inst) {

        if (m_weights == null) {
            return new double[inst.numClasses()];
        }
        double[] result = (inst.classAttribute().isNominal())
                ? new double[inst.numClasses()]
                : new double[1];
        
        if (inst.classAttribute().isNumeric()) {
            double wx = dotProd(inst, m_weights[0], inst.classIndex());// * m_wScale;
            double z = (wx + m_bias[0]);
            result[0] = z;
            return result;
        }

        for (int i = 0; i < m_weights.length; i++){
            double wx = dotProd(inst, m_weights[i], inst.classIndex());// * m_wScale;
            double z = (wx + m_bias[i]);
            if (z <= 0) {
                //  z = 0;
                if (m_loss == LOGLOSS) {
                    //result[0] = 1.0 / (1.0 + Math.exp(z));
                    //result[1] = 1.0 - result[0];
                    result[i] = 1.0 - 1.0 / (1.0 + Math.exp(z)); 
                } else {
                    //result[0] = 1;
                    result[i] = 0;
                }
            } else {
                if (m_loss == LOGLOSS) {
                    //result[1] = 1.0 / (1.0 + Math.exp(-z));
                    //result[0] = 1.0 - result[1];
                    result[i] = 1.0 / (1.0 + Math.exp(-z)); 
                } else {
                    //result[1] = 1;
                    result[i] = 1;
                }
            }
        }
        return result;
    }
483401
def getMaximinScores(profile):
    

    # Currently, we expect the profile to contain complete ordering over candidates. Ties are
    # allowed however.
    elecType = profile.getElecType()
    if elecType != "soc" and elecType != "toc":
        print("ERROR: unsupported election type")
        exit()

    wmgMap = profile.getWmg()
    # Initialize each Copeland score as infinity.
    maximinscores = {}
    for cand in wmgMap.keys():
        maximinscores[cand] = float("inf")

    # For each pair of candidates, calculate the number of votes in which one beat the other.

    # For each pair of candidates, calculate the number of times each beats the other.
    for cand1, cand2 in itertools.combinations(wmgMap.keys(), 2):
        if cand2 in wmgMap[cand1].keys():
            maximinscores[cand1] = min(maximinscores[cand1], wmgMap[cand1][cand2])
            maximinscores[cand2] = min(maximinscores[cand2], wmgMap[cand2][cand1])

    return maximinscores
1036242
def coombs_winners(self, profile):
        
        elecType = profile.getElecType()
        if elecType == "soc" or elecType == "csv":
            return self.coombssoc_winners(profile)
        elif elecType == "toc":
            return self.coombstoc_winners(profile)
        else:
            print("ERROR: unsupported profile type")
            exit()
865369
protected double computeWeight(int i, Instance example) {
    	
    	int d = this.windowSize;
    	int t = this.processedInstances - this.ensemble[i].birthday;

        double e_it = 0;
        double mse_it = 0;
        double voteSum = 0;
        
        try{
	        double[] votes = this.ensemble[i].classifier.getVotesForInstance(example);
	        
	        for (double element : votes) {
	            voteSum += element;
	        }
	        
	        if (voteSum > 0) {
		        double f_it = 1 - (votes[(int) example.classValue()] / voteSum);
		        e_it = f_it * f_it;
	        } else {
	        	e_it = 1;
	        }
		} catch (Exception e) {
			e_it = 1;
		}
        
        if(t > d)
        {
        	mse_it = this.ensemble[i].mse_it + e_it/(double)d - this.ensemble[i].squareErrors[t % d]/(double)d;
        }
        else
        {
        	mse_it = this.ensemble[i].mse_it*(t-1)/t + e_it/(double)t;
        }

        this.ensemble[i].squareErrors[t % d] = e_it;
        this.ensemble[i].mse_it = mse_it;
        
        if(linearOption.isSet())
        {
        	return java.lang.Math.max(mse_r - mse_it, Double.MIN_VALUE);
        }
        else
        {
        	return 1.0 / (this.mse_r + mse_it + Double.MIN_VALUE);
        }
    }
1361979
private IntIntPair totalPivotSearch(int k) {
    double max = 0;
    int i, j, pivotRow = k, pivotCol = k;
    double absValue;
    for(i = k; i < coeff.length; i++) {
      for(j = k; j < coeff[0].length; j++) {
        // compute absolute value of
        // current entry in absValue
        absValue = Math.abs(coeff[row[i]][col[j]]);

        // compare absValue with value max
        // found so far
        if(max < absValue) {
          // remember new value and position
          max = absValue;
          pivotRow = i;
          pivotCol = j;
        } // end if
      } // end for j
    } // end for k
    return new IntIntPair(pivotRow, pivotCol);
  }
1192544
function minBy (valueComputer, list) {
    var
      idx = 0,
      winner = list[idx],
      computedWinner = valueComputer(winner),

      computedCurrent;

    while (++idx < list.length) {
      computedCurrent = valueComputer(list[idx]);

      if (computedCurrent < computedWinner) {
        computedWinner = computedCurrent;
        winner = list[idx];
      }
    }

    return winner;
  }
827830
def getCandScoresMap(self, profile):
        

        # Currently, we expect the profile to contain complete ordering over candidates.
        elecType = profile.getElecType()
        if elecType != "soc" and elecType != "toc":
            print("ERROR: unsupported profile type")
            exit()

        bucklinScores = dict()
        rankMaps = profile.getRankMaps()
        preferenceCounts = profile.getPreferenceCounts()
        for cand in profile.candMap.keys():

            # We keep track of the number of times a candidate is ranked in the first t positions.
            numTimesRanked = 0

            # We increase t in increments of 1 until we find t such that the candidate is ranked in the
            # first t positions in at least half the votes.
            for t in range(1, profile.numCands + 1):
                for i in range(0, len(rankMaps)):
                    if (rankMaps[i][cand] == t):
                        numTimesRanked += preferenceCounts[i]
                if numTimesRanked >= math.ceil(float(profile.numVoters) / 2):
                    bucklinScores[cand] = t
                    break

        return bucklinScores
859244
public int getNumberOfResults()
    {
        final String numberOfResults = agiReply.getAttribute("results");
        return numberOfResults == null ? 0 : Integer.parseInt(numberOfResults);
    }
1338919
private Profile getProfileFromResultSet(ResultSet result) throws Exception {
        Profile profile = new Profile();
        profile.setId(result.getInt(Constants.GENERIC_ID));
        Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);
        String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());
        profile.setName(profileName);
        return profile;
    }
876649
def getCopelandScores(profile, alpha=0.5, normalize=False):
    

    # Currently, we expect the profile to contain complete ordering over candidates. Ties are
    # allowed however.
    elecType = profile.getElecType()
    if elecType != "soc" and elecType != "toc":
        print("ERROR: unsupported election type")
        exit()

    # Initialize each Copeland score as 0.0.
    copelandscores = {}
    for cand in profile.candMap.keys():
        copelandscores[cand] = 0.0

    # For each pair of candidates, calculate the number of votes in which one beat the other.
    wmgMap = profile.getWmg()
    for cand1, cand2 in itertools.combinations(wmgMap.keys(), 2):
        if cand2 in wmgMap[cand1].keys():
            if wmgMap[cand1][cand2] > 0:
                copelandscores[cand1] += 1.0
            elif wmgMap[cand1][cand2] < 0:
                copelandscores[cand2] += 1.0

            # If a pair of candidates is tied, we add alpha to their score for each vote.
            else:
                copelandscores[cand1] += alpha
                copelandscores[cand2] += alpha

    if normalize:
        m = profile.numCands
        for cand in profile.candMap.keys():
            copelandscores[cand] /= (m - 1)

    return copelandscores
658686
def profile(self):
    """"""
    leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
    return (np.arange(self.num_vertices()) - leftmost_idx).sum()
160637
def _won_in(self):
        """"""
        if not self._summary['finished']:
            return
        starting_age = self._summary['settings']['starting_age'].lower()
        if starting_age == 'post imperial':
            starting_age = 'imperial'
        ages_reached = set([starting_age])
        for player in self._summary['players']:
            for age, reached in player['ages'].items():
                if reached:
                    ages_reached.add(age)
        ages = ['imperial', 'castle', 'feudal', 'dark']
        for age in ages:
            if age in ages_reached:
                return age
1373351
@Override
    public double[] getVotesForInstance(Instance inst) {

        if (m_weights == null) {
            return new double[inst.numClasses()];
        }
        double[] result = (inst.classAttribute().isNominal())
                ? new double[2]
                : new double[1];


        double wx = dotProd(inst, m_weights, inst.classIndex());// * m_wScale;
        double z = (wx + m_bias);

        if (inst.classAttribute().isNumeric()) {
            result[0] = z;
            return result;
        }

        if (z <= 0) {
            //  z = 0;
            if (m_loss == LOGLOSS) {
                result[0] = 1.0 / (1.0 + Math.exp(z));
                result[1] = 1.0 - result[0];
            } else {
                result[0] = 1;
            }
        } else {
            if (m_loss == LOGLOSS) {
                result[1] = 1.0 / (1.0 + Math.exp(-z));
                result[0] = 1.0 - result[1];
            } else {
                result[1] = 1;
            }
        }
        return result;
    }
23415
def check_win_by_step(self, x, y, user, line_number=None):
        ''''''
        if not line_number:
            line_number = self.win
        for ang in self.angle:
            self.win_list = [(x, y)]
            angs = [ang, ang + math.pi]
            line_num = 1
            radius = 1
            direction = [1, 1]
            while True:
                if line_num == line_number:
                    return True
                if direction == [0, 0]:
                    break
                for ind, a in enumerate(angs):
                    target_x = int(x + radius*(sign(math.cos(a)))) if direction[ind] else -1
                    target_y = int(y - radius*(sign(math.sin(a)))) if direction[ind] else -1
                    if target_x < 0 or target_y < 0 or target_x > self.board_size - 1 or target_y > self.board_size - 1:
                        direction[ind] = 0
                    elif self.pos[target_x][target_y] == user:
                        self.win_list.append((target_x, target_y))
                        line_num += 1
                    else:
                        direction[ind] = 0
                else:
                    radius += 1
        else:
            return (x, y)
1338485
def has_perf_results(self):
        '''
            
        '''
        num_results = SubmissionTestResult.objects.filter(perf_data__isnull=False).filter(submission_file__submissions__assignment=self).count()
        return num_results != 0
633609
def baldwinsoc_winners(self, profile):
        
        ordering = profile.getOrderVectors()
        m = profile.numCands
        prefcounts = profile.getPreferenceCounts()
        if min(ordering[0]) == 0:
            startstate = set(range(m))
        else:
            startstate = set(range(1, m + 1))
        wmg = self.getWmg2(prefcounts, ordering, startstate, normalize=False)
        known_winners = set()
        # ----------Some statistics--------------
        hashtable2 = set()

        # push the node of start state into the priority queue
        root = Node(value=startstate)
        stackNode = []
        stackNode.append(root)

        while stackNode:
            # ------------pop the current node-----------------
            node = stackNode.pop()
            # -------------------------------------------------
            state = node.value.copy()

            # goal state 1: if the state set contains only 1 candidate, then stop
            if len(state) == 1 and list(state)[0] not in known_winners:
                known_winners.add(list(state)[0])
                continue
            # goal state 2 (pruning): if the state set is subset of the known_winners set, then stop
            if state <= known_winners:
                continue
            # ----------Compute plurality score for the current remaining candidates--------------
            plural_score = dict()
            for cand in state:
                plural_score[cand] = 0
            for cand1, cand2 in itertools.permutations(state, 2):
                plural_score[cand1] += wmg[cand1][cand2]

            # if current state satisfies one of the 3 goal state, continue to the next loop

            # After using heuristics, generate children and push them into priority queue
            # frontier = [val for val in known_winners if val in state] + list(set(state) - set(known_winners))

            minscore = min(plural_score.values())
            for to_be_deleted in state:
                if plural_score[to_be_deleted] == minscore:
                    child_state = state.copy()
                    child_state.remove(to_be_deleted)
                    tpc = tuple(sorted(child_state))
                    if tpc in hashtable2:
                        continue
                    else:
                        hashtable2.add(tpc)
                        child_node = Node(value=child_state)
                        stackNode.append(child_node)
        return sorted(known_winners)