Returns a float for sentiment strength based on the input text.
    Positive values are positive valence, negative value are negative valence.
178956
def sentiment(text):
    
    sentiment.valence_dict = load_valence_dict() if sentiment.valence_dict is None else sentiment_valence_dict
    wordsAndEmoticons = str(text).split() #doesn't separate words from adjacent punctuation (keeps emoticons & contractions)
    text_mod = regex_remove_punctuation.sub('', text) # removes punctuation (but loses emoticons & contractions)
    wordsOnly = str(text_mod).split()
    # get rid of empty items or single letter "words" like 'a' and 'I' from wordsOnly
    for word in wordsOnly:
        if len(word) <= 1:
            wordsOnly.remove(word)    
    # now remove adjacent & redundant punctuation from [wordsAndEmoticons] while keeping emoticons and contractions
    puncList = [".", "!", "?", ",", ";", ":", "-", "'", "\"", 
                "!!", "!!!", "??", "???", "?!?", "!?!", "?!?!", "!?!?"] 
    for word in wordsOnly:
        for p in puncList:
            pword = p + word
            x1 = wordsAndEmoticons.count(pword)
            while x1 > 0:
                i = wordsAndEmoticons.index(pword)
                wordsAndEmoticons.remove(pword)
                wordsAndEmoticons.insert(i, word)
                x1 = wordsAndEmoticons.count(pword)
            
            wordp = word + p
            x2 = wordsAndEmoticons.count(wordp)
            while x2 > 0:
                i = wordsAndEmoticons.index(wordp)
                wordsAndEmoticons.remove(wordp)
                wordsAndEmoticons.insert(i, word)
                x2 = wordsAndEmoticons.count(wordp)
    # get rid of residual empty items or single letter "words" like 'a' and 'I' from wordsAndEmoticons
    for word in wordsAndEmoticons:
        if len(word) <= 1:
            wordsAndEmoticons.remove(word)
    
    # remove stopwords from [wordsAndEmoticons]
    #stopwords = [str(word).strip() for word in open('stopwords.txt')]
    #for word in wordsAndEmoticons:
    #    if word in stopwords:
    #        wordsAndEmoticons.remove(word)
    
    # check for negation
    negate = ["aint", "arent", "cannot", "cant", "couldnt", "darent", "didnt", "doesnt",
              "ain't", "aren't", "can't", "couldn't", "daren't", "didn't", "doesn't",
              "dont", "hadnt", "hasnt", "havent", "isnt", "mightnt", "mustnt", "neither",
              "don't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't",
              "neednt", "needn't", "never", "none", "nope", "nor", "not", "nothing", "nowhere", 
              "oughtnt", "shant", "shouldnt", "uhuh", "wasnt", "werent",
              "oughtn't", "shan't", "shouldn't", "uh-uh", "wasn't", "weren't",  
              "without", "wont", "wouldnt", "won't", "wouldn't", "rarely", "seldom", "despite"]
    def negated(list, nWords=[], includeNT=True):
        nWords.extend(negate)
        for word in nWords:
            if word in list:
                return True
        if includeNT:
            for word in list:
                if "n't" in word:
                    return True
        if "least" in list:
            i = list.index("least")
            if i > 0 and list[i-1] != "at":
                return True
        return False
        
    def normalize(score, alpha=15):
        # normalize the score to be between -1 and 1 using an alpha that approximates the max expected value 
        normScore = score/math.sqrt( ((score*score) + alpha) )
        return normScore
    
    def wildCardMatch(patternWithWildcard, listOfStringsToMatchAgainst):
        listOfMatches = fnmatch.filter(listOfStringsToMatchAgainst, patternWithWildcard)
        return listOfMatches
        
    
    def isALLCAP_differential(wordList):
        countALLCAPS= 0
        for w in wordList:
            if str(w).isupper(): 
                countALLCAPS += 1
        cap_differential = len(wordList) - countALLCAPS
        if cap_differential > 0 and cap_differential < len(wordList):
            isDiff = True
        else: isDiff = False
        return isDiff
    isCap_diff = isALLCAP_differential(wordsAndEmoticons)
    
    b_incr = 0.293 #(empirically derived mean sentiment intensity rating increase for booster words)
    b_decr = -0.293
    # booster/dampener 'intensifiers' or 'degree adverbs' http://en.wiktionary.org/wiki/Category:English_degree_adverbs
    booster_dict = {"absolutely": b_incr, "amazingly": b_incr, "awfully": b_incr, "completely": b_incr, "considerably": b_incr, 
                    "decidedly": b_incr, "deeply": b_incr, "effing": b_incr, "enormously": b_incr, 
                    "entirely": b_incr, "especially": b_incr, "exceptionally": b_incr, "extremely": b_incr,
                    "fabulously": b_incr, "flipping": b_incr, "flippin": b_incr, 
                    "fricking": b_incr, "frickin": b_incr, "frigging": b_incr, "friggin": b_incr, "fully": b_incr, "fucking": b_incr, 
                    "greatly": b_incr, "hella": b_incr, "highly": b_incr, "hugely": b_incr, "incredibly": b_incr, 
                    "intensely": b_incr, "majorly": b_incr, "more": b_incr, "most": b_incr, "particularly": b_incr, 
                    "purely": b_incr, "quite": b_incr, "really": b_incr, "remarkably": b_incr, 
                    "so": b_incr,  "substantially": b_incr, 
                    "thoroughly": b_incr, "totally": b_incr, "tremendously": b_incr, 
                    "uber": b_incr, "unbelievably": b_incr, "unusually": b_incr, "utterly": b_incr, 
                    "very": b_incr, 
                    
                    "almost": b_decr, "barely": b_decr, "hardly": b_decr, "just enough": b_decr, 
                    "kind of": b_decr, "kinda": b_decr, "kindof": b_decr, "kind-of": b_decr,
                    "less": b_decr, "little": b_decr, "marginally": b_decr, "occasionally": b_decr, "partly": b_decr, 
                    "scarcely": b_decr, "slightly": b_decr, "somewhat": b_decr, 
                    "sort of": b_decr, "sorta": b_decr, "sortof": b_decr, "sort-of": b_decr}
    sentiments = []
    for item in wordsAndEmoticons:
        v = 0
        i = wordsAndEmoticons.index(item)
        if (i < len(wordsAndEmoticons)-1 and str(item).lower() == "kind" and \
           str(wordsAndEmoticons[i+1]).lower() == "of") or str(item).lower() in booster_dict:
            sentiments.append(v)
            continue
        item_lowercase = str(item).lower() 
        if  item_lowercase in sentiment.valence_dict:
            #get the sentiment valence
            v = float(sentiment.valence_dict[item_lowercase])
            
            #check if sentiment laden word is in ALLCAPS (while others aren't)
            c_incr = 0.733 #(empirically derived mean sentiment intensity rating increase for using ALLCAPs to emphasize a word)
            if str(item).isupper() and isCap_diff:
                if v > 0: v += c_incr
                else: v -= c_incr
            
            #check if the preceding words increase, decrease, or negate/nullify the valence
            def scalar_inc_dec(word, valence):
                scalar = 0.0
                word_lower = str(word).lower()
                if word_lower in booster_dict:
                    scalar = booster_dict[word_lower]
                    if valence < 0: scalar *= -1
                    #check if booster/dampener word is in ALLCAPS (while others aren't)
                    if str(word).isupper() and isCap_diff:
                        if valence > 0: scalar += c_incr
                        else:  scalar -= c_incr
                return scalar
            n_scalar = -0.74
            if i > 0 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict:
                s1 = scalar_inc_dec(wordsAndEmoticons[i-1], v)
                v = v+s1
                if negated([wordsAndEmoticons[i-1]]): v = v*n_scalar
            if i > 1 and str(wordsAndEmoticons[i-2]).lower() not in sentiment.valence_dict:
                s2 = scalar_inc_dec(wordsAndEmoticons[i-2], v)
                if s2 != 0: s2 = s2*0.95
                v = v+s2
                # check for special use of 'never' as valence modifier instead of negation
                if wordsAndEmoticons[i-2] == "never" and (wordsAndEmoticons[i-1] == "so" or wordsAndEmoticons[i-1] == "this"): 
                    v = v*1.5                    
                # otherwise, check for negation/nullification
                elif negated([wordsAndEmoticons[i-2]]): v = v*n_scalar
            if i > 2 and str(wordsAndEmoticons[i-3]).lower() not in sentiment.valence_dict:
                s3 = scalar_inc_dec(wordsAndEmoticons[i-3], v)
                if s3 != 0: s3 = s3*0.9
                v = v+s3
                # check for special use of 'never' as valence modifier instead of negation
                if wordsAndEmoticons[i-3] == "never" and \
                   (wordsAndEmoticons[i-2] == "so" or wordsAndEmoticons[i-2] == "this") or \
                   (wordsAndEmoticons[i-1] == "so" or wordsAndEmoticons[i-1] == "this"):
                    v = v*1.25
                # otherwise, check for negation/nullification
                elif negated([wordsAndEmoticons[i-3]]): v = v*n_scalar
                
                # check for special case idioms using a sentiment-laden keyword known to SAGE
                special_case_idioms = {"the shit": 3, "the bomb": 3, "bad ass": 1.5, "yeah right": -2, 
                                       "cut the mustard": 2, "kiss of death": -1.5, "hand to mouth": -2}
                # future work: consider other sentiment-laden idioms
                #other_idioms = {"back handed": -2, "blow smoke": -2, "blowing smoke": -2, "upper hand": 1, "break a leg": 2, 
                #                "cooking with gas": 2, "in the black": 2, "in the red": -2, "on the ball": 2,"under the weather": -2}
                onezero = "{} {}".format(str(wordsAndEmoticons[i-1]), str(wordsAndEmoticons[i]))
                twoonezero = "{} {}".format(str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1]), str(wordsAndEmoticons[i]))
                twoone = "{} {}".format(str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1]))
                threetwoone = "{} {} {}".format(str(wordsAndEmoticons[i-3]), str(wordsAndEmoticons[i-2]), str(wordsAndEmoticons[i-1]))
                threetwo = "{} {}".format(str(wordsAndEmoticons[i-3]), str(wordsAndEmoticons[i-2]))                    
                if onezero in special_case_idioms: v = special_case_idioms[onezero]
                elif twoonezero in special_case_idioms: v = special_case_idioms[twoonezero]
                elif twoone in special_case_idioms: v = special_case_idioms[twoone]
                elif threetwoone in special_case_idioms: v = special_case_idioms[threetwoone]
                elif threetwo in special_case_idioms: v = special_case_idioms[threetwo]
                if len(wordsAndEmoticons)-1 > i:
                    zeroone = "{} {}".format(str(wordsAndEmoticons[i]), str(wordsAndEmoticons[i+1]))
                    if zeroone in special_case_idioms: v = special_case_idioms[zeroone]
                if len(wordsAndEmoticons)-1 > i+1:
                    zeroonetwo = "{} {}".format(str(wordsAndEmoticons[i]), str(wordsAndEmoticons[i+1]), str(wordsAndEmoticons[i+2]))
                    if zeroonetwo in special_case_idioms: v = special_case_idioms[zeroonetwo]
                
                # check for booster/dampener bi-grams such as 'sort of' or 'kind of'
                if threetwo in booster_dict or twoone in booster_dict:
                    v = v+b_decr
            
            # check for negation case using "least"
            if i > 1 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict \
                and str(wordsAndEmoticons[i-1]).lower() == "least":
                if (str(wordsAndEmoticons[i-2]).lower() != "at" and str(wordsAndEmoticons[i-2]).lower() != "very"):
                    v = v*n_scalar
            elif i > 0 and str(wordsAndEmoticons[i-1]).lower() not in sentiment.valence_dict \
                and str(wordsAndEmoticons[i-1]).lower() == "least":
                v = v*n_scalar
        sentiments.append(v) 
            
    # check for modification in sentiment due to contrastive conjunction 'but'
    if 'but' in wordsAndEmoticons or 'BUT' in wordsAndEmoticons:
        try: bi = wordsAndEmoticons.index('but')
        except: bi = wordsAndEmoticons.index('BUT')
        for s in sentiments:
            si = sentiments.index(s)
            if si < bi: 
                sentiments.pop(si)
                sentiments.insert(si, s*0.5)
            elif si > bi: 
                sentiments.pop(si)
                sentiments.insert(si, s*1.5) 
                
    if sentiments:                      
        sum_s = float(sum(sentiments))
        #print sentiments, sum_s
        
        # check for added emphasis resulting from exclamation points (up to 4 of them)
        ep_count = str(text).count("!")
        if ep_count > 4: ep_count = 4
        ep_amplifier = ep_count*0.292 #(empirically derived mean sentiment intensity rating increase for exclamation points)
        if sum_s > 0:  sum_s += ep_amplifier
        elif  sum_s < 0: sum_s -= ep_amplifier
        
        # check for added emphasis resulting from question marks (2 or 3+)
        qm_count = str(text).count("?")
        qm_amplifier = 0
        if qm_count > 1:
            if qm_count <= 3: qm_amplifier = qm_count*0.18
            else: qm_amplifier = 0.96
            if sum_s > 0:  sum_s += qm_amplifier
            elif  sum_s < 0: sum_s -= qm_amplifier

        compound = normalize(sum_s)
        
        # want separate positive versus negative sentiment scores
        pos_sum = 0.0
        neg_sum = 0.0
        neu_count = 0
        for sentiment_score in sentiments:
            if sentiment_score > 0:
                pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1
            if sentiment_score < 0:
                neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals
            if sentiment_score == 0:
                neu_count += 1
        
        if pos_sum > math.fabs(neg_sum): pos_sum += (ep_amplifier+qm_amplifier)
        elif pos_sum < math.fabs(neg_sum): neg_sum -= (ep_amplifier+qm_amplifier)
        
        total = pos_sum + math.fabs(neg_sum) + neu_count
        pos = math.fabs(pos_sum / total)
        neg = math.fabs(neg_sum / total)
        neu = math.fabs(neu_count / total)
    else:
        compound, pos, neg, neu = 0., 0., 0., 0.

    s = {"neg" : round(neg, 3),
         "neu" : round(neu, 3),
         "pos" : round(pos, 3),
         "compound" : round(compound, 4)}
    return s
225576
def positive_int(value: str) -> int:
    
    try:
        ivalue = int(value)
        assert ivalue > 0
    except (AssertionError, TypeError, ValueError):
        raise ArgumentTypeError(
            "{!r} is an invalid positive int".format(value))
    return ivalue
760346
def to_boolean(value):
    
    if value is not None:
        if str(value).lower() in TRUE_TOKENS:
            return True

        vfloat = to_number(float, value)
        if vfloat is not None:
            return bool(vfloat)

    return False
1158721
def positive_int(val):
    """"""
    if isinstance(val, float):
        raise ValueError('"{}" must not be a float'.format(val))
    val = int(val)
    if val >= 0:
        return val
    raise ValueError('"{}" must be positive'.format(val))
1280993
def positive_value(target_type):
    
    def inner(string):
        value = target_type(string)
        if not value >= 0:
            raise argparse.ArgumentTypeError("Invalid positive number: " +
                    string)
        return value

    return inner
26987
def count_sign(values, min_value):
    
    positive_count = 0
    negative_count = 0
    for value in values:
        if value > min_value:
            positive_count += 1
        elif value < -min_value:
            negative_count += 1
    return positive_count, negative_count
1201962
def _min_max_filter(t: List, min_v: str, max_v: str) -> bool:
        

        def tofloat(value):
            try:
                float(value)
                return float(value)
            except ValueError:
                return False

        for a_token in t:
            if not tofloat(a_token.text):
                return False
            else:
                if min_v and tofloat(min_v):
                    this_v = tofloat(a_token.text)
                    if this_v < tofloat(min_v):
                        return False
                if max_v and tofloat(max_v):
                    this_v = tofloat(a_token.text)
                    if this_v > tofloat(max_v):
                        return False

        return True
1254270
def getBottomLeft(self):
        
        return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_r()))
1193617
def polarity(self):
    
    scores = [w.polarity for w in self.words if w.polarity != 0]
    if not scores:
      return 0.0
    return sum(scores) / float(len(scores))
1063456
def get_line_weight(value)   # :nodoc:
    value = value.downcase if value.respond_to?(:to_str)
    default = 0

    weights = {
      1          => -1,
      2          => 0,
      3          => 1,
      4          => 2,
      'hairline' => -1,
      'narrow'   => 0,
      'medium'   => 1,
      'wide'     => 2,
    }

    if weights.has_key?(value)
      weights[value]
    else
      default
    end
  end
321073
def get_real_rating(self):
        """"""
        if not (self.votes and self.score):
            return 0
        return float(self.score)/self.votes
760437
def value(self):
        

        if self.scores.numel() == 0:
            return 0
        ap = torch.zeros(self.scores.size(1))
        if hasattr(torch, "arange"):
            rg = torch.arange(1, self.scores.size(0) + 1).float()
        else:
            rg = torch.range(1, self.scores.size(0)).float()
        if self.weights.numel() > 0:
            weight = self.weights.new(self.weights.size())
            weighted_truth = self.weights.new(self.weights.size())

        # compute average precision for each class
        for k in range(self.scores.size(1)):
            # sort scores
            scores = self.scores[:, k]
            targets = self.targets[:, k]
            _, sortind = torch.sort(scores, 0, True)
            truth = targets[sortind]
            if self.weights.numel() > 0:
                weight = self.weights[sortind]
                weighted_truth = truth.float() * weight
                rg = weight.cumsum(0)

            # compute true positive sums
            if self.weights.numel() > 0:
                tp = weighted_truth.cumsum(0)
            else:
                tp = truth.float().cumsum(0)

            # compute precision curve
            precision = tp.div(rg)

            # compute average precision
            ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1)
        return ap
324171
function(value, token) {
			var score, pos;

			if (!value) return 0;
			value = String(value || '');
			pos = value.search(token.regex);
			if (pos === -1) return 0;
			score = token.string.length / value.length;
			if (pos === 0) score += 0.5;
			return score;
		}
923739
private function readDegrees(string $text, string $positive, string $negative): float
    {
        $text       = trim($text);
        $hemisphere = substr($text, 0, 1);
        $degrees    = substr($text, 1);

        // Match a valid GEDCOM format
        if (is_numeric($degrees)) {
            $hemisphere = strtoupper($hemisphere);
            $degrees    = (float) $degrees;

            if ($hemisphere === $positive) {
                return $degrees;
            }

            if ($hemisphere === $negative) {
                return -$degrees;
            }
        }

        // Just a number?
        if (is_numeric($text)) {
            return (float) $text;
        }

        // Can't match anything.
        return 0.0;
    }
1122112
def detect_intent_with_sentiment_analysis(project_id, session_id, texts,
                                          language_code):
    """"""
    import dialogflow_v2beta1 as dialogflow
    session_client = dialogflow.SessionsClient()

    session_path = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session_path))

    for text in texts:
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        # Enable sentiment analysis
        sentiment_config = dialogflow.types.SentimentAnalysisRequestConfig(
            analyze_query_text_sentiment=True)

        # Set the query parameters with sentiment analysis
        query_params = dialogflow.types.QueryParameters(
            sentiment_analysis_request_config=sentiment_config)

        response = session_client.detect_intent(
            session=session_path, query_input=query_input,
            query_params=query_params)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        # Score between -1.0 (negative sentiment) and 1.0 (positive sentiment).
        print('Query Text Sentiment Score: {}\n'.format(
            response.query_result.sentiment_analysis_result
            .query_text_sentiment.score))
        print('Query Text Sentiment Magnitude: {}\n'.format(
            response.query_result.sentiment_analysis_result
            .query_text_sentiment.magnitude))
1308008
def get_weight_range(weights):
    # type: (FeatureWeights) -> float
    
    return max_or_0(abs(fw.weight)
                    for lst in [weights.pos, weights.neg]
                    for fw in lst or [])
1090859
def strong(node):
    
    o = nodes.strong()
    for n in MarkDown(node):
        o += n
    return o