sys.float_info.min

Here are the examples of the python api sys.float_info.min taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

48 Examples 7

Example 1

Project: chainer
Source File: test_ranges.py
View license
    @testing.with_requires('numpy>=1.10')
    @testing.numpy_cupy_array_equal()
    def test_linspace_float_underflow(self, xp):
        # find minimum subnormal number
        x = sys.float_info.min
        while x / 2 > 0:
            x /= 2
        return xp.linspace(0., x, 10, dtype=float)

Example 2

Project: cupy
Source File: test_ranges.py
View license
    @testing.with_requires('numpy>=1.10')
    @testing.numpy_cupy_array_equal()
    def test_linspace_float_underflow(self, xp):
        # find minimum subnormal number
        x = sys.float_info.min
        while x / 2 > 0:
            x /= 2
        return xp.linspace(0., x, 10, dtype=float)

Example 3

Project: python-driver
Source File: test_connection.py
View license
    def test_connect_timeout(self):
        # Underlying socket implementations don't always throw a socket timeout even with min float
        # This can be timing sensitive, added retry to ensure failure occurs if it can
        max_retry_count = 10
        exception_thrown = False
        for i in range(max_retry_count):
            start = time.time()
            try:
                self.get_connection(timeout=sys.float_info.min)
            except Exception as e:
                end = time.time()
                self.assertAlmostEqual(start, end, 1)
                exception_thrown = True
                break
        self.assertTrue(exception_thrown)

Example 4

Project: medpy
Source File: energy_label.py
View license
    def addition_directed_ltd(key1, key2, v1, v2, dic): # for light-to-dark # tested
        "Takes a key defined by two uints, two voxel intensities and a dict to which it adds g(v1, v2)."
        if not key1 == key2: # do not process voxel pairs which belong to the same region
            # The function used to compute the weight contribution of each voxel pair
            weight = math.pow(1./(1. + max(abs(v1), abs(v2))), 2)
            # ensure that no value is zero; this can occur due to rounding errors
            weight = max(weight, sys.float_info.min)
            # add weighted values to already existing edge
            if v1 > v2: graph.set_nweight(key1 - 1, key2 - 1, min(1, weight + beta), weight)
            else: graph.set_nweight(key1 - 1, key2 - 1, weight, min(1, weight + beta))

Example 5

Project: medpy
Source File: energy_label.py
View license
    def addition_directed_dtl(key1, key2, v1, v2): # for dark-to-light # tested
        "Takes a key defined by two uints, two voxel intensities and a dict to which it adds g(v1, v2)."
        if not key1 == key2: # do not process voxel pairs which belong to the same region
            # The function used to compute the weight contribution of each voxel pair
            weight = math.pow(1./(1. + max(abs(v1), abs(v2))), 2)
            # ensure that no value is zero; this can occur due to rounding errors
            weight = max(weight, sys.float_info.min)
            # add weighted values to already existing edge
            if v1 > v2: graph.set_nweight(key1 - 1, key2 - 1, weight, min(1, weight + beta))
            else: graph.set_nweight(key1 - 1, key2 - 1, min(1, weight + beta), weight)

Example 6

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_linear(intensities):
        """
        Implementation of a linear boundary term computation over an array.
        """
        # normalize the intensity distances to the interval (0, 1]
        intensities /= max_intensity
        #difference_to_neighbour[difference_to_neighbour > 1] = 1 # this line should not be required, but might be due to rounding errors
        intensities = (1. - intensities) # reverse weights such that high intensity difference lead to small weights and hence more likely to a cut at this edge
        intensities[intensities == 0.] = sys.float_info.min # required to avoid zero values
        return intensities

Example 7

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_linear(intensities):
        """
        Implementation of a linear boundary term computation over an array.
        """
        # normalize the intensity distances to the interval (0, 1]
        intensities /= max_intensity_difference
        #difference_to_neighbour[difference_to_neighbour > 1] = 1 # this line should not be required, but might be due to rounding errors
        intensities = (1. - intensities) # reverse weights such that high intensity difference lead to small weights and hence more likely to a cut at this edge
        intensities[intensities == 0.] = sys.float_info.min # required to avoid zero values
        return intensities

Example 8

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_exponential(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply exp-(x**2/sigma**2)
        intensities = scipy.power(intensities, 2)
        intensities /= math.pow(sigma, 2)
        intensities *= -1
        intensities = scipy.exp(intensities)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 9

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_exponential(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply exp-(x**2/sigma**2)
        intensities = scipy.power(intensities, 2)
        intensities /= math.pow(sigma, 2)
        intensities *= -1
        intensities = scipy.exp(intensities)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 10

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_division(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply 1 / (1  + x/sigma)
        intensities /= sigma
        intensities = 1. / (intensities + 1)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 11

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_division(intensities):
        """
        Implementation of a division boundary term computation over an array.
        """
        # apply 1 / (1  + x/sigma)
        intensities /= sigma
        intensities = 1. / (intensities + 1)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 12

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_power(intensities):
        """
        Implementation of a power boundary term computation over an array.
        """
        # apply (1 / (1  + x))^sigma
        intensities = 1. / (intensities + 1)
        intensities = scipy.power(intensities, sigma)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 13

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_power(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply (1 / (1  + x))^sigma
        intensities = 1. / (intensities + 1)
        intensities = scipy.power(intensities, sigma)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 14

Project: medpy
Source File: energy_label.py
View license
    def addition_directed_ltd(key1, key2, v1, v2, dic): # for light-to-dark # tested
        "Takes a key defined by two uints, two voxel intensities and a dict to which it adds g(v1, v2)."
        if not key1 == key2: # do not process voxel pairs which belong to the same region
            # The function used to compute the weight contribution of each voxel pair
            weight = math.pow(1./(1. + max(abs(v1), abs(v2))), 2)
            # ensure that no value is zero; this can occur due to rounding errors
            weight = max(weight, sys.float_info.min)
            # add weighted values to already existing edge
            if v1 > v2: graph.set_nweight(key1 - 1, key2 - 1, min(1, weight + beta), weight)
            else: graph.set_nweight(key1 - 1, key2 - 1, weight, min(1, weight + beta))

Example 15

Project: medpy
Source File: energy_label.py
View license
    def addition_directed_dtl(key1, key2, v1, v2): # for dark-to-light # tested
        "Takes a key defined by two uints, two voxel intensities and a dict to which it adds g(v1, v2)."
        if not key1 == key2: # do not process voxel pairs which belong to the same region
            # The function used to compute the weight contribution of each voxel pair
            weight = math.pow(1./(1. + max(abs(v1), abs(v2))), 2)
            # ensure that no value is zero; this can occur due to rounding errors
            weight = max(weight, sys.float_info.min)
            # add weighted values to already existing edge
            if v1 > v2: graph.set_nweight(key1 - 1, key2 - 1, weight, min(1, weight + beta))
            else: graph.set_nweight(key1 - 1, key2 - 1, min(1, weight + beta), weight)

Example 16

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_linear(intensities):
        """
        Implementation of a linear boundary term computation over an array.
        """
        # normalize the intensity distances to the interval (0, 1]
        intensities /= max_intensity
        #difference_to_neighbour[difference_to_neighbour > 1] = 1 # this line should not be required, but might be due to rounding errors
        intensities = (1. - intensities) # reverse weights such that high intensity difference lead to small weights and hence more likely to a cut at this edge
        intensities[intensities == 0.] = sys.float_info.min # required to avoid zero values
        return intensities

Example 17

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_linear(intensities):
        """
        Implementation of a linear boundary term computation over an array.
        """
        # normalize the intensity distances to the interval (0, 1]
        intensities /= max_intensity_difference
        #difference_to_neighbour[difference_to_neighbour > 1] = 1 # this line should not be required, but might be due to rounding errors
        intensities = (1. - intensities) # reverse weights such that high intensity difference lead to small weights and hence more likely to a cut at this edge
        intensities[intensities == 0.] = sys.float_info.min # required to avoid zero values
        return intensities

Example 18

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_exponential(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply exp-(x**2/sigma**2)
        intensities = scipy.power(intensities, 2)
        intensities /= math.pow(sigma, 2)
        intensities *= -1
        intensities = scipy.exp(intensities)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 19

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_exponential(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply exp-(x**2/sigma**2)
        intensities = scipy.power(intensities, 2)
        intensities /= math.pow(sigma, 2)
        intensities *= -1
        intensities = scipy.exp(intensities)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 20

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_division(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply 1 / (1  + x/sigma)
        intensities /= sigma
        intensities = 1. / (intensities + 1)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 21

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_division(intensities):
        """
        Implementation of a division boundary term computation over an array.
        """
        # apply 1 / (1  + x/sigma)
        intensities /= sigma
        intensities = 1. / (intensities + 1)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 22

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_power(intensities):
        """
        Implementation of a power boundary term computation over an array.
        """
        # apply (1 / (1  + x))^sigma
        intensities = 1. / (intensities + 1)
        intensities = scipy.power(intensities, sigma)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 23

Project: medpy
Source File: energy_voxel.py
View license
    def boundary_term_power(intensities):
        """
        Implementation of a exponential boundary term computation over an array.
        """
        # apply (1 / (1  + x))^sigma
        intensities = 1. / (intensities + 1)
        intensities = scipy.power(intensities, sigma)
        intensities[intensities <= 0] = sys.float_info.min
        return intensities

Example 24

View license
def random_float():
    return random.uniform(float_info.min, float_info.max)

Example 25

Project: codenn
Source File: bleu.py
View license
def score_cooked(allcomps, n=4, ground=0, smooth=1):
    totalcomps = {'testlen':0, 'reflen':0, 'guess':[0]*n, 'correct':[0]*n}
    for comps in allcomps:
        for key in ['testlen','reflen']:
            totalcomps[key] += comps[key]
        for key in ['guess','correct']:
            for k in xrange(n):
                totalcomps[key][k] += comps[key][k]
    logbleu = 0.0
    all_bleus = []
    for k in xrange(n):
      correct = totalcomps['correct'][k]
      guess = totalcomps['guess'][k]
      addsmooth = 0
      if smooth == 1 and k > 0:
        addsmooth = 1
      logbleu += math.log(correct + addsmooth + sys.float_info.min)-math.log(guess + addsmooth)
      if guess == 0:
        all_bleus.append(-10000000)
      else:
        all_bleus.append(math.log(correct + sys.float_info.min)-math.log( guess ))

    logbleu /= float(n)
    all_bleus.insert(0, logbleu)

    brevPenalty = min(0,1-float(totalcomps['reflen'] + 1)/(totalcomps['testlen'] + 1))
    for i in xrange(len(all_bleus)):
      if i ==0:
        all_bleus[i] += brevPenalty
      all_bleus[i] = math.exp(all_bleus[i])
    return all_bleus

Example 26

Project: statsmodels
Source File: proportion.py
View license
def proportion_confint(count, nobs, alpha=0.05, method='normal'):
    '''confidence interval for a binomial proportion

    Parameters
    ----------
    count : int or array
        number of successes
    nobs : int
        total number of trials
    alpha : float in (0, 1)
        significance level, default 0.05
    method : string in ['normal']
        method to use for confidence interval,
        currently available methods :

         - `normal` : asymptotic normal approximation
         - `agresti_coull` : Agresti-Coull interval
         - `beta` : Clopper-Pearson interval based on Beta distribution
         - `wilson` : Wilson Score interval
         - `jeffreys` : Jeffreys Bayesian Interval
         - `binom_test` : experimental, inversion of binom_test

    Returns
    -------
    ci_low, ci_upp : float
        lower and upper confidence level with coverage (approximately) 1-alpha.
        Note: Beta has coverage
        coverage is only 1-alpha on average for some other methods.)

    Notes
    -----
    Beta, the Clopper-Pearson interval has coverage at least 1-alpha, but is
    in general conservative. Most of the other methods have average coverage
    equal to 1-alpha, but will have smaller coverage in some cases.

    Method "binom_test" directly inverts the binomial test in scipy.stats.
    which has discrete steps.

    TODO: binom_test intervals raise an exception in small samples if one
       interval bound is close to zero or one.

    References
    ----------
    http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval

    Brown, Lawrence D.; Cai, T. Tony; DasGupta, Anirban (2001). "Interval
        Estimation for a Binomial Proportion",
        Statistical Science 16 (2): 101–133. doi:10.1214/ss/1009213286.
        TODO: Is this the correct one ?

    '''

    q_ = count * 1. / nobs
    alpha_2 = 0.5 * alpha

    if method == 'normal':
        std_ = np.sqrt(q_ * (1 - q_) / nobs)
        dist = stats.norm.isf(alpha / 2.) * std_
        ci_low = q_ - dist
        ci_upp = q_ + dist

    elif method == 'binom_test':
        # inverting the binomial test
        def func(qi):
            return stats.binom_test(q_ * nobs, nobs, p=qi) - alpha
        if count == 0:
            ci_low = 0
        else:
            ci_low = optimize.brentq(func, float_info.min, q_)
        if count == nobs:
            ci_upp = 1
        else:
            ci_upp = optimize.brentq(func, q_, 1. - float_info.epsilon)

    elif method == 'beta':
        ci_low = stats.beta.ppf(alpha_2, count, nobs - count + 1)
        ci_upp = stats.beta.isf(alpha_2, count + 1, nobs - count)

    elif method == 'agresti_coull':
        crit = stats.norm.isf(alpha / 2.)
        nobs_c = nobs + crit**2
        q_c = (count + crit**2 / 2.) / nobs_c
        std_c = np.sqrt(q_c * (1. - q_c) / nobs_c)
        dist = crit * std_c
        ci_low = q_c - dist
        ci_upp = q_c + dist

    elif method == 'wilson':
        crit = stats.norm.isf(alpha / 2.)
        crit2 = crit**2
        denom = 1 + crit2 / nobs
        center = (q_ + crit2 / (2 * nobs)) / denom
        dist = crit * np.sqrt(q_ * (1. - q_) / nobs + crit2 / (4. * nobs**2))
        dist /= denom
        ci_low = center - dist
        ci_upp = center + dist

    # method adjusted to be more forgiving of misspellings or incorrect option name
    elif method[:4] == 'jeff':
        ci_low, ci_upp = stats.beta.interval(1 - alpha, count + 0.5,
                                             nobs - count + 0.5)

    else:
        raise NotImplementedError('method "%s" is not available' % method)
    return ci_low, ci_upp

Example 27

Project: topaz
Source File: test_floatobject.py
View license
    def test_min(self, space):
        assert space.float_w(space.execute("return Float::MIN")) == sys.float_info.min

Example 28

Project: mpipe
Source File: FilterWorker.py
View license
    def doTask(self, task):
        """Filter input *task* to pipelines -- make sure each one has no more
        than *max_tasks* tasks in it. Return a tuple
          (*task*, *results*)
        where *task* is the given task, and *results* is 
        a list of latest retrieved results from pipelines."""

        # If we're not caching, then clear the table of last results.
        if not self._cache_results:
            self._last_results = dict()

        # Iterate the list of pipelines, draining each one of any results.
        # For pipelines whose current stream has less than *max_tasks* tasks 
        # remaining, feed them the current task.
        for pipe in self._pipelines:

            count = self._task_counts[pipe]

            # Let's attempt to drain all (if any) results from the pipeline.
            valid = True
            last_result = None
            while count and valid:
                valid, result = pipe.get(sys.float_info.min)
                if valid:
                    last_result = result
                    count -= 1

            # Unless we're dropping results, save the last result (if any).
            if not self._drop_results:
                if last_result is not None:
                    self._last_results[pipe] = last_result

            # If there is room for the task, or if it is a "stop" request,
            # put it on the pipeline.
            if count <= self._max_tasks-1 or task is None:
                pipe.put(task)
                count += 1

            # Update the task count for the pipeline.
            self._task_counts[pipe] = count

        # If we're only propagating the task, do so now.
        if self._drop_results:
            return task

        # Otherwise, also propagate the assembly of pipeline results.
        all_results = [res for res in self._last_results.values()]
        return task, all_results

Example 29

Project: brython
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            self.assertEqual(passValue(i), i)
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            self.assertEqual(passValue(f), f)
        for f in float('nan'), float('inf'), -float('inf'):
            if f != f: # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,)))

Example 30

Project: milkman
Source File: generators.py
View license
def random_float():
    return random.uniform(sys.float_info.min, sys.float_info.max)

Example 31

Project: milkman
Source File: tests.py
View license
    def test_random_float(self):
        assert random_float() >= sys.float_info.min
        assert random_float() <= sys.float_info.max
        assert isinstance(random_float(), float)

Example 32

Project: yatsm
Source File: ccdc.py
View license
    def fit(self, X, Y, dates):
        """ Fit timeseries model

        Args:
            X (numpy.ndarray): design matrix (number of observations x number
                of features)
            Y (numpy.ndarray): independent variable matrix (number of series x
                number of observations)
            dates (numpy.ndarray): ordinal dates for each observation in X/Y

        Returns:
            CCDCesque: Returns ``self``
        """
        if len(dates) != X.shape[0] or len(dates) != Y.shape[1]:
            raise ValueError('X/Y/dates must have same number of observations')

        self.X = np.asarray(X, dtype=np.float64)
        self.Y = np.asarray(Y, dtype=np.float64)
        self.dates = dates
        self.n_features = X.shape[1]
        self.n_series = Y.shape[0]

        # Setup test indices
        if not np.any(np.asarray(self.test_indices)):
            self.test_indices = np.arange(self.n_series)
        # Setup minimum RMSE
        if isinstance(self.min_rmse, (list, np.ndarray)):
            self.min_rmse = np.asarray(self.min_rmse)
        elif isinstance(self.min_rmse, (int, float)):
            self.min_rmse = np.array([self.min_rmse] * self.n_series)
        else:
            self.min_rmse = np.array([sys.float_info.min] * self.n_series)

        # Set or reset state variables
        self.reset()
        if len(dates) < self.here + self.consecutive:
            raise TSLengthException('Not enough observations (n = %s)' %
                                    len(dates))

        self.n_record = 0
        self.record = np.copy(self.record_template)

        while self.running:

            while not self.monitoring and self.can_monitor:
                self.train()
                self.here += 1

            # Ensure all bands are fit in case we can't monitor
            # First check if there are enough obs to estimate model
            if self.span_index > self.n_features:
                self._update_model()

            while self.monitoring and self.can_monitor:
                # Update model if required
                self._update_model()
                # Perform monitoring check
                self.monitor()
                # Iterate forward
                self.here += 1

            self.here += 1

        # Update record for last model
        self.record[self.n_record]['start'] = self.dates[self.start]
        # Re-adjust end for consecutive, and for two ``self.here += 1`` calls
        offset = 1 + (1 if self.monitoring else 0)
        self.record[self.n_record]['end'] = self.dates[
            self.here - self.consecutive - offset]
        for i, m in enumerate(self.models):
            self.record[self.n_record]['coef'][:, i] = m.coef
            self.record[self.n_record]['rmse'][i] = m.rmse

        # If we ended without being able to monitor again, delete last model
        # since it will be empty
        # TODO: fit this time period with median
        if not self.monitoring:
            self.record = self.record[:-1]

        return self

Example 33

Project: datafari
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\xbd'), 'string\xbd')
        self.assertEqual(passValue('string\xe2\x82\xac'), u'string\u20ac')
        self.assertEqual(passValue(u'string'), u'string')
        self.assertEqual(passValue(u'string\xbd'), u'string\xbd')
        self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\xc0\x80ing'), 'str\x00ing')
        self.assertEqual(passValue(u'str\x00ing'), u'str\x00ing')
        self.assertEqual(passValue(u'str\x00ing\xbd'), u'str\x00ing\xbd')
        self.assertEqual(passValue(u'str\x00ing\u20ac'), u'str\x00ing\u20ac')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')

Example 34

Project: datafari
Source File: test_tcl.py
View license
    def test_user_command(self):
        result = []
        def testfunc(arg):
            result.append(arg)
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, eq=self.assertEqual):
            if expected is None:
                expected = value
            del result[:]
            r = self.interp.call('testfunc', value)
            self.assertEqual(len(result), 1)
            self.assertIsInstance(result[0], (str, unicode))
            eq(result[0], expected)
            self.assertIsInstance(r, (str, unicode))
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\xe2\x82\xac', u'string\u20ac')
        check('')
        check(u'string')
        check(u'string\xbd')
        check(u'string\u20ac')
        check(u'')
        check('str\xc0\x80ing', u'str\x00ing')
        check('str\xc0\x80ing\xe2\x82\xac', u'str\x00ing\u20ac')
        check(u'str\x00ing')
        check(u'str\x00ing\xbd')
        check(u'str\x00ing\u20ac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

Example 35

Project: openPDS
Source File: mitfit_tasks.py
View license
def leaderboardComputation(internalDataStore):
    #probeEntries = internalDataStore.getData( probe, start, end)
    answer = internalDataStore.getAnswerList("recentActivityProbeByHour")
    answer = answer[0]["value"] #if answer.count() > 0 else []
    num_answers = len(answer)
    #print answer[0]["value"]
    activity_rate = 0
    average_activity_rate = 0
    max_high_activity_rate = sys.float_info.min
    min_low_activity_rate = sys.float_info.max
    for activityAnswer in answer:
	#print activityAnswer
	if activityAnswer["total"] > 0:
            high_activity_rate = activityAnswer["high"]/activityAnswer["total"]
            low_activity_rate = activityAnswer["low"]/activityAnswer["total"]
	else:
	    high_activity_rate = 0 
            low_activity_rate = 0
        activity_rate = activity_rate + ((0.7*high_activity_rate) + (0.3*low_activity_rate))
        #print "activity_rate: " + str(activity_rate) + ", high_activity_rate: " + str(high_activity_rate) + ", low_activity_rate: " + str(low_activity_rate)  
        if high_activity_rate > max_high_activity_rate:
            max_high_activity_rate = high_activity_rate
        if low_activity_rate < min_low_activity_rate:
	    min_low_activity_rate = low_activity_rate 
    if len(answer) > 0:
        average_activity_rate = activity_rate/len(answer)
    user_activity = { "average_activity_rate": average_activity_rate, "max_high_activity_rate": max_high_activity_rate, "min_low_activity_rate": min_low_activity_rate}
    return user_activity

Example 36

Project: medpy
Source File: energy_label.py
View license
    def test_boundary_difference_of_means_borders(self):
        """Test the @link medpy.graphcut.boundary_difference_of_means() border conditions.""" 
        # TEST1: test for a label image with not continuous label ids not starting from 0
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test1')
        # TEST2: test for a label image with negative labels
        label = [[-1, 4, 8],
                 [-1, 3, 10],
                 [1, -3, 10]]
        expected_result = {(-1, 1): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (-1, 3): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (-3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (-3, 1): (sys.float_info.min, sys.float_info.min), (-3, 3): (sys.float_info.min, sys.float_info.min), (-1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test2')
        # TEST3: test for behavior on occurrence of very small (~0) and 1 weights
        gradient = [[0., 0., 0.],
                    [0., 0., sys.float_info.max]]
        label = [[0, 1, 2],
                 [0, 1, 3]]
        expected_result = {(0, 1): (1.0, 1.0), (1, 2): (1.0, 1.0), (1, 3): (sys.float_info.min, sys.float_info.min), (2, 3): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (gradient))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test3')
        # TEST4: check behavior for integer gradient image
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        label = scipy.asarray(label)
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, scipy.int_)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test4')
        # TEST5: reaction to different array orders
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        label = scipy.asarray(label, order='C') # C-order, gradient same order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (C,C)')
        label = scipy.asarray(label, order='F') # Fortran order, gradient same order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (F, F)')
        label = scipy.asarray(label, order='C') # C-order, gradient different order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, order='F')))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (C, F)')
        label = scipy.asarray(label, order='F') # F-order, gradient different order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, order='C')))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (F, C)')  

Example 37

Project: medpy
Source File: energy_label.py
View license
    def test_boundary_difference_of_means_borders(self):
        """Test the @link medpy.graphcut.boundary_difference_of_means() border conditions.""" 
        # TEST1: test for a label image with not continuous label ids not starting from 0
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test1')
        # TEST2: test for a label image with negative labels
        label = [[-1, 4, 8],
                 [-1, 3, 10],
                 [1, -3, 10]]
        expected_result = {(-1, 1): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (-1, 3): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (-3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (-3, 1): (sys.float_info.min, sys.float_info.min), (-3, 3): (sys.float_info.min, sys.float_info.min), (-1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test2')
        # TEST3: test for behavior on occurrence of very small (~0) and 1 weights
        gradient = [[0., 0., 0.],
                    [0., 0., sys.float_info.max]]
        label = [[0, 1, 2],
                 [0, 1, 3]]
        expected_result = {(0, 1): (1.0, 1.0), (1, 2): (1.0, 1.0), (1, 3): (sys.float_info.min, sys.float_info.min), (2, 3): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (gradient))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test3')
        # TEST4: check behavior for integer gradient image
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        label = scipy.asarray(label)
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, scipy.int_)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test4')
        # TEST5: reaction to different array orders
        label = [[1, 4, 8],
                 [1, 3, 10],
                 [1, 3, 10]]
        label = scipy.asarray(label, order='C') # C-order, gradient same order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (C,C)')
        label = scipy.asarray(label, order='F') # Fortran order, gradient same order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros_like(label)))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (F, F)')
        label = scipy.asarray(label, order='C') # C-order, gradient different order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, order='F')))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (C, F)')
        label = scipy.asarray(label, order='F') # F-order, gradient different order
        expected_result = {(1, 3): (sys.float_info.min, sys.float_info.min), (4, 8): (sys.float_info.min, sys.float_info.min), (3, 10): (sys.float_info.min, sys.float_info.min), (8, 10): (sys.float_info.min, sys.float_info.min), (1, 4): (sys.float_info.min, sys.float_info.min), (3, 4): (sys.float_info.min, sys.float_info.min)}
        result = boundary_difference_of_means(label, (scipy.zeros(label.shape, order='C')))
        result = self._reorder_keys(result)
        self.__compare_dictionaries(result, expected_result, 'Test5 (F, C)')  

Example 38

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'),
                         b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

Example 39

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

Example 40

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'),
                         b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

Example 41

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

Example 42

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'),
                         b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

Example 43

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

Example 44

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue('str\x00ing'), 'str\x00ing')
        self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd')
        self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac')
        self.assertEqual(passValue(b'str\x00ing'),
                         b'str\x00ing' if self.wantobjects else 'str\x00ing')
        self.assertEqual(passValue(b'str\xc0\x80ing'),
                         b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing')
        self.assertEqual(passValue(b'str\xbding'),
                         b'str\xbding' if self.wantobjects else 'str\xbding')
        for i in self.get_integers():
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            self.assertEqual(passValue(2**1000), str(2**1000))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
            # XXX NaN representation can be not parsable by float()
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')
        self.assertEqual(passValue(['a', ['b', 'c']]),
                         ('a', ('b', 'c')) if self.wantobjects else 'a {b c}')

Example 45

Project: iot-utilities
Source File: test_tcl.py
View license
    def test_user_command(self):
        result = None
        def testfunc(arg):
            nonlocal result
            result = arg
            return arg
        self.interp.createcommand('testfunc', testfunc)
        self.addCleanup(self.interp.tk.deletecommand, 'testfunc')
        def check(value, expected=None, *, eq=self.assertEqual):
            if expected is None:
                expected = value
            nonlocal result
            result = None
            r = self.interp.call('testfunc', value)
            self.assertIsInstance(result, str)
            eq(result, expected)
            self.assertIsInstance(r, str)
            eq(r, expected)
        def float_eq(actual, expected):
            self.assertAlmostEqual(float(actual), expected,
                                   delta=abs(expected) * 1e-10)

        check(True, '1')
        check(False, '0')
        check('string')
        check('string\xbd')
        check('string\u20ac')
        check('')
        check(b'string', 'string')
        check(b'string\xe2\x82\xac', 'string\xe2\x82\xac')
        check(b'string\xbd', 'string\xbd')
        check(b'', '')
        check('str\x00ing')
        check('str\x00ing\xbd')
        check('str\x00ing\u20ac')
        check(b'str\x00ing', 'str\x00ing')
        check(b'str\xc0\x80ing', 'str\xc0\x80ing')
        check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac')
        for i in self.get_integers():
            check(i, str(i))
        if tcl_version < (8, 5):  # bignum was added in Tcl 8.5
            check(2**1000, str(2**1000))
        for f in (0.0, 1.0, -1.0):
            check(f, repr(f))
        for f in (1/3.0, sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, eq=float_eq)
        check(float('inf'), eq=float_eq)
        check(-float('inf'), eq=float_eq)
        # XXX NaN representation can be not parsable by float()
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')
        check([1, [2,], [3, 4], '5 6', []], '1 2 {3 4} {5 6} {}')

Example 46

Project: neuroConstruct
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)
        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue(u'string'), u'string')
        self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac')
        for i in (0, 1, -1, int(2**31-1), int(-2**31)):
            self.assertEqual(passValue(i), i)
        for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            self.assertEqual(passValue(f), f)
        for f in float('nan'), float('inf'), -float('inf'):
            if f != f: # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,)))

Example 47

Project: neuroConstruct
Source File: test_tcl.py
View license
    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)
        self.assertEqual(passValue(True), True)
        self.assertEqual(passValue(False), False)
        self.assertEqual(passValue('string'), 'string')
        self.assertEqual(passValue('string\u20ac'), 'string\u20ac')
        self.assertEqual(passValue(u'string'), u'string')
        self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac')
        for i in (0, 1, -1, int(2**31-1), int(-2**31)):
            self.assertEqual(passValue(i), i)
        for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            self.assertEqual(passValue(f), f)
        for f in float('nan'), float('inf'), -float('inf'):
            if f != f: # NaN
                self.assertNotEqual(passValue(f), f)
            else:
                self.assertEqual(passValue(f), f)
        self.assertEqual(passValue((1, '2', (3.4,))), (1, '2', (3.4,)))

Example 48

Project: slave
Source File: types.py
View license
    def simulate(self):
        min_ = sys.float_info.min if self._min is None else self._min
        max_ = sys.float_info.max if self._max is None else self._max
        return random.uniform(min_, max_)