def iStatBP(self, location, fastaRow):
		"""
		iStatBP(statsDict, fastaRow) -- At statsDict location, builds a list of base-pair related statistics for subsequent rows of fasta sequence data.  This "inplace" function uses statsDict in situ, so does a running total on its various stats. 
			
		Future: 'GATTCA' type buckets		
		"""	

 		if len(fastaRow) >0:
 			if not isinstance(location, dict):
 				if isinstance(location, basestring):
					(obj, key) = self.callerInstance.getNamespace(location)
					location = obj[key] # by reference
				else:
					raise ValueError ("Error: iStatBP() function wasn't given a good location for first parameter: %s" % location)
 		
			buckets = ['G','C','A','T']
			if not 'A' in location: #indicates it hasn't been initialized.
				#obj[key] = OrderedDict()
				for item in buckets:
					location[item]=0
				location['total'] = 0
			
			#Tally buckets.  Allows for N ,U, * etc. to be identified
			for char in fastaRow:
				char = char.upper()
				location[char] = (location[char] + 1) if char in location else 1 

			location['total'] += len(fastaRow)
			#Might not be at last line but calculate these anyways, in case we are:
			for item in buckets:
				location[item + '%'] = int(round(100*operator.truediv(location[item], location['total'] ) ))
				
			location['GC_content%'] = int(round(100*operator.truediv(location['G'] + location['C'], location['total'] )) )
			
		return location
 def __truediv__(self, other):
     "Get a new Vector3 by true dividing each component of this one."
     return Vector3(
         operator.truediv(self._vec[0], other),
         operator.truediv(self._vec[1], other),
         operator.truediv(self._vec[2], other),
     )
Exemplo n.º 3
0
 def __rtruediv__(self, other):
     try:
         return Vector2(operator.truediv(other[0], self[0]), 
                        operator.truediv(other[1], self[1]))
     except TypeError:
         return Vector2(operator.truediv(other, self[0]), 
                        operator.truediv(other, self[1]))
Exemplo n.º 4
0
def check_truediv(Poly):
    # true division is valid only if the denominator is a Number and
    # not a python bool.
    p1 = Poly([1,2,3])
    p2 = p1 * 5

    for stype in np.ScalarType:
        if not issubclass(stype, Number) or issubclass(stype, bool):
            continue
        s = stype(5)
        assert_poly_almost_equal(op.truediv(p2, s), p1)
        assert_raises(TypeError, op.truediv, s, p2)
    for stype in (int, long, float):
        s = stype(5)
        assert_poly_almost_equal(op.truediv(p2, s), p1)
        assert_raises(TypeError, op.truediv, s, p2)
    for stype in [complex]:
        s = stype(5, 0)
        assert_poly_almost_equal(op.truediv(p2, s), p1)
        assert_raises(TypeError, op.truediv, s, p2)
    for s in [tuple(), list(), dict(), bool(), np.array([1])]:
        assert_raises(TypeError, op.truediv, p2, s)
        assert_raises(TypeError, op.truediv, s, p2)
    for ptype in classes:
        assert_raises(TypeError, op.truediv, p2, ptype(1))
    def fractionToDecimal(self, numerator, denominator):
        import operator

        isNegtive = numerator * denominator < 0
        numerator = abs(numerator)
        denominator = abs(denominator)
        quotient = int(operator.truediv(numerator, denominator))
        remainder = numerator % denominator
        dic = {remainder:0}
        intPart = "-" + str(quotient) if isNegtive else str(quotient)
        decimals = ""
        idx = 1
        while remainder != 0:
            # print "abaw"
            numerator = remainder * 10
            quotient = int(operator.truediv(numerator, denominator))
            remainder = numerator % denominator
            decimals += str(quotient)
            if remainder in dic:
                decimals = decimals[:dic[remainder]] + "("+decimals[dic[remainder]:]+")"
                break

            dic[remainder] = idx
            idx += 1

        return intPart+"."+decimals if len(decimals) else intPart
Exemplo n.º 6
0
    def test_operators(self):
        from operator import truediv
        from _numpypy import float64, int_, True_, False_

        assert 5 / int_(2) == int_(2)
        assert truediv(int_(3), int_(2)) == float64(1.5)
        assert truediv(3, int_(2)) == float64(1.5)
        assert int_(8) % int_(3) == int_(2)
        assert 8 % int_(3) == int_(2)
        assert divmod(int_(8), int_(3)) == (int_(2), int_(2))
        assert divmod(8, int_(3)) == (int_(2), int_(2))
        assert 2 ** int_(3) == int_(8)
        assert int_(3) << int_(2) == int_(12)
        assert 3 << int_(2) == int_(12)
        assert int_(8) >> int_(2) == int_(2)
        assert 8 >> int_(2) == int_(2)
        assert int_(3) & int_(1) == int_(1)
        assert 2 & int_(3) == int_(2)
        assert int_(2) | int_(1) == int_(3)
        assert 2 | int_(1) == int_(3)
        assert int_(3) ^ int_(5) == int_(6)
        assert True_ ^ False_ is True_
        assert 5 ^ int_(3) == int_(6)

        assert +int_(3) == int_(3)
        assert ~int_(3) == int_(-4)

        raises(TypeError, lambda: float64(3) & 1)
Exemplo n.º 7
0
 def test_fifth(self):
     "Nearest rounding of 1/5 is upwards."
     from operator import truediv
     assert  1 / 5.0 == fpu.up  (lambda: truediv(1.0,  5.0))
     assert  1 / 5.0 >  fpu.down(lambda: truediv(1.0,  5.0))
     assert -1 / 5.0 == fpu.down(lambda: truediv(1.0, -5.0))
     assert -1 / 5.0 <  fpu.up  (lambda: truediv(1.0, -5.0))
Exemplo n.º 8
0
 def test_fourth(self):
     " 1/4 is exact."
     from operator import truediv
     assert  1 / 4.0 == fpu.down(lambda: truediv(1.0,  4.0))
     assert  1 / 4.0 == fpu.up  (lambda: truediv(1.0,  4.0))
     assert -1 / 4.0 == fpu.up  (lambda: truediv(1.0, -4.0))
     assert -1 / 4.0 == fpu.down(lambda: truediv(1.0, -4.0))
Exemplo n.º 9
0
 def test_third(self):
     "Nearest rounding of 1/3 is downwards."
     from operator import truediv
     assert  1 / 3.0 == fpu.down(lambda: truediv(1.0,  3.0))
     assert  1 / 3.0 <  fpu.up  (lambda: truediv(1.0,  3.0))
     assert -1 / 3.0 == fpu.up  (lambda: truediv(1.0, -3.0))
     assert -1 / 3.0 >  fpu.down(lambda: truediv(1.0, -3.0))
Exemplo n.º 10
0
 def __truediv__(self, other):
     if type(other) in (int, long, float):
         return self.__class__(operator.truediv(self.X, other),
                    operator.truediv(self.Y, other),
                    operator.truediv(self.Z, other))
     else:
         raise TypeError("Divider must be instance of (int, long, or float). '%s' given." % other.__class__.__name__)
Exemplo n.º 11
0
 def getClusteringCoefficient(self):
     index=[]
     C_eachnode=[]
     ClusteringCoeff=0
     for i in range(0,len(adjmatrix)):
         num=0
         ejk=0
         for j in range(0,len(adjmatrix)):
             if adjmatrix[i][j]==1:
                 num=num+1
                 index.append(j)
         for k in range(0,len(index)):
             t1=index[k]
             for l in range(0,len(index)):
                 t2=index[l]
                 if adjmatrix[t1][t2]==1:
                     ejk=ejk+1
         numerator=2 * (operator.truediv(ejk,2))
         denominator=num * (num-1)
         if denominator==0:
             C_eachnode.append(0)
         else:
             Ci=operator.truediv(numerator,denominator)
             C_eachnode.append(Ci)
         index=[]
     ClusteringCoeff=operator.truediv(sum(C_eachnode),len(nodeslist))
     print ClusteringCoeff
Exemplo n.º 12
0
 def test_truediv_empty(self):
     for (fun, funlen, _) in testfunctions:
         chebtech = Chebtech2.initfun_fixedlen(fun, funlen)
         self.assertTrue(operator.truediv(self.emptyfun,chebtech).isempty)
         self.assertTrue(operator.truediv(chebtech,self.emptyfun).isempty)
         # __truediv__
         self.assertTrue((self.emptyfun/chebtech).isempty)
         self.assertTrue((chebtech/self.emptyfun).isempty)
Exemplo n.º 13
0
 def test_truediv_empty(self):
     subinterval = Interval(-2,3)
     for (fun, _, _) in testfunctions:
         bndfun = Bndfun.initfun_adaptive(fun, subinterval)
         self.assertTrue(operator.truediv(self.emptyfun, bndfun).isempty)
         self.assertTrue(operator.truediv(self.emptyfun, bndfun).isempty)
         # __truediv__
         self.assertTrue((self.emptyfun/bndfun).isempty)
         self.assertTrue((bndfun/self.emptyfun).isempty)
Exemplo n.º 14
0
 def __truediv__(self, other):
   if isinstance(other, Poly):
     if len(other) == 1:
       delta, value = other.data.items()[0]
       return Poly({(k - delta): operator.truediv(v, other)
                    for k, v in self.data.iteritems()})
     raise NotImplementedError("Can't divide general Poly instances")
   return Poly({k: operator.truediv(v, other)
                for k, v in self.data.iteritems()})
Exemplo n.º 15
0
 def test_z_div_truediv_delay_over_constant(self, a):
   div_filter = operator.div(z ** -1, a)
   truediv_filter = operator.truediv(z ** -1, a)
   div_expected = it.imap(lambda x: operator.div(x, a),
                          [0.] + self.data[:-1])
   truediv_expected = it.imap(lambda x: operator.truediv(x, a),
                              [0.] + self.data[:-1])
   assert almost_eq(div_filter(self.data), div_expected)
   assert almost_eq(truediv_filter(self.data), truediv_expected)
Exemplo n.º 16
0
 def test_truedivision(self, input_tuple, expected):
     self.ureg.autoconvert_offset_to_baseunit = False
     qin1, qin2 = input_tuple
     q1, q2 = self.Q_(*qin1), self.Q_(*qin2)
     input_tuple = q1, q2
     if expected == 'error':
         self.assertRaises(OffsetUnitCalculusError, op.truediv, q1, q2)
     else:
         expected = self.Q_(*expected)
         self.assertEqual(op.truediv(q1, q2).units, expected.units)
         self.assertQuantityAlmostEqual(op.truediv(q1, q2), expected,
                                        atol=0.01)
Exemplo n.º 17
0
 def _units_to_mb(speed, unit):
     sp = float(speed)
     u = unit.lower().strip()
     if u[:1] == 'b':
         return truediv(sp, 1024 * 1024)
     if u[:2] == 'kb':
         return truediv(sp, 1024)
     if u[:2] == 'mb':
         return sp
     if u[:2] == 'gb':
         return sp * 1024
     raise ValueError('could not convert \'%s %s\' to MB/s' % (sp, unit))
Exemplo n.º 18
0
    def test_truediv(self):
        import operator
        x = 1000000
        a = x / 2
        assert a == 500000
        a = operator.truediv(x, 2)
        assert a == 500000.0

        x = 63050394783186940
        a = x / 7
        assert a == 9007199254740991
        a = operator.truediv(x, 7)
        assert a == 9007199254740991.0
Exemplo n.º 19
0
	def __init__(self, *argz, **kwz):
		tick_strangle_max = op.truediv(optz.tbf_max_delay, optz.tbf_tick)
		super(NotificationDaemon, self).__init__(*argz, **kwz)
		self._note_limit = core.FC_TokenBucket(
			tick=optz.tbf_tick, burst=optz.tbf_size,
			tick_strangle=lambda x: min(x*optz.tbf_inc, tick_strangle_max),
			tick_free=lambda x: max(op.truediv(x, optz.tbf_dec), 1) )
		self._note_buffer = core.RRQ(optz.queue_len)
		self._note_windows = dict()
		self._note_id_pool = it.chain.from_iterable(
			it.imap(ft.partial(xrange, 1), it.repeat(2**30)) )
		self._renderer = NotificationDisplay(
			optz.layout_margin, optz.layout_anchor, optz.layout_direction, optz.img_w, optz.img_h)
		self._activity_event()
Exemplo n.º 20
0
 def __truediv__(self, other):
   if isinstance(other, Poly):
     if len(other) == 1:
       delta, value = next(iteritems(other._data))
       return Poly(OrderedDict(((k - delta), operator.truediv(v, value))
                               for k, v in iteritems(self._data)),
                   zero=self.zero)
     elif len(other) == 0:
       raise ZeroDivisionError("Dividing Poly instance by zero")
     raise NotImplementedError("Can't divide general Poly instances")
   other = thub(other, len(self))
   return Poly(OrderedDict((k, operator.truediv(v, other))
                           for k, v in iteritems(self._data)),
               zero=self.zero)
Exemplo n.º 21
0
    def __init__(self, pubsub=None):
        tick_strangle_max = op.truediv(optz.tbf_max_delay, optz.tbf_tick)
        self._note_limit = core.FC_TokenBucket(
            tick=optz.tbf_tick,
            burst=optz.tbf_size,
            tick_strangle=lambda x: min(x * optz.tbf_inc, tick_strangle_max),
            tick_free=lambda x: max(op.truediv(x, optz.tbf_dec), 1),
        )
        self._note_buffer = core.RRQ(optz.queue_len)
        self._note_history = core.RRQ(optz.history_len)
        self._note_windows = dict()
        self._note_id_pool = it.chain.from_iterable(it.imap(ft.partial(xrange, 1), it.repeat(2 ** 30)))
        self._renderer = NotificationDisplay(
            optz.layout_margin,
            optz.layout_anchor,
            optz.layout_direction,
            icon_scale=optz.icon_scale,
            markup_default=not optz.markup_disable,
            markup_warn=optz.markup_warn_on_err,
            markup_strip=optz.markup_strip_on_err,
        )
        self._activity_event()

        self.pubsub = pubsub
        if pubsub:
            GLib.io_add_watch(pubsub.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_PRI, self._notify_pubsub)

        if optz.test_message:
            # Also test crazy web-of-90s markup here :P
            summary = "Notification daemon started <small><tt>¯\(°_o)/¯</tt></small>"
            body = (
                "Desktop notification daemon started successfully on host: <u>{host}</u>"
                '\nVersion: <span stretch="extraexpanded">{v}</span>'
                "\nCode path: <small>{code}</small>"
                '\nSound enabled: <span color="{sound_color}">{sound}</span>'
                '\nPubSub enabled: <span color="{pubsub_color}">{pubsub}</span>'
            ).format(
                host=os.uname()[1],
                v=core.__version__,
                sound_color="green" if optz.filter_sound else "red",
                sound=unicode(bool(optz.filter_sound)).lower(),
                pubsub_color="green" if pubsub else "red",
                pubsub=unicode(bool(pubsub)).lower(),
                code=os.path.abspath(os.path.dirname(core.__file__)),
            )
            if not self._renderer.markup_default:
                summary, body = it.imap(strip_markup, [summary, body])
            self.display(summary, body)
        if optz.test_sound and optz.filter_sound:
            optz.filter_sound["play"](optz.test_sound)
    def test_simple_weights(self):
        results = {"Red": 0, "Blue": 0}
        choices = [(generators.StaticGenerator("Red"), 50),
                   (generators.StaticGenerator("Blue"), 50)]
        generate = generators.WeightedGenerator(choices)

        runs = 10000

        for i in range(runs):
            results[generate()] += 1

        MARGIN = 0.025

        self.assertTrue(0.5 - MARGIN < truediv(results["Red"], runs) < 0.5 + MARGIN)
        self.assertTrue(0.5 - MARGIN < truediv(results["Blue"], runs) < 0.5 + MARGIN)
Exemplo n.º 23
0
    def test_operators(self):

        assert (Q > 1).eval_(2)
        assert (Q >= 1).eval_(1)
        assert (Q <= 1).eval_(1)
        assert (Q < 1).eval_(0)
        assert (Q == 1).eval_(1)
        assert (Q != 1).eval_(2)

        assert not (Q > 1).eval_(1)
        assert not (Q >= 1).eval_(0)
        assert not (Q <= 1).eval_(2)
        assert not (Q < 1).eval_(1)
        assert not (Q == 1).eval_(2)
        assert not (Q != 1).eval_(1)

        assert (Q <= Q).eval_(5)

        assert (Q + 5).eval_(2) == 7
        assert (Q - 1).eval_(1) == 0
        assert (Q * 2).eval_(4) == 8

        if not PY3:
            assert operator.div(Q, 2).eval_(3) == 1

        assert operator.truediv(Q, 2).eval_(3) == 1.5

        assert (Q / 2).eval_(4) == 2.0
        assert (Q // 2).eval_(4) == 2
        assert (Q % 2).eval_(3) == 1
        assert (Q ** 2).eval_(3) == 9
Exemplo n.º 24
0
def _luadiv(o1, o2):
    if o2 == 0.0:
        if o1 == 0.0:
            return float("nan")
        return float("inf")

    return operator.truediv(o1, o2)
Exemplo n.º 25
0
 def __truediv__(self, other):
   if isinstance(other, ZFilter):
     return ZFilter(self.numpoly * other.denpoly,
                    self.denpoly * other.numpoly)
   if isinstance(other, LinearFilter):
     raise ValueError("Filter equations have different domains")
   return self * operator.truediv(1, other)
Exemplo n.º 26
0
 def test_arithmetic_returns_money_instance(self):
     assert type(Currency(3) + 2) is Currency
     assert type(3 + Currency(2)) is Currency
     assert type(Currency(3) - 2) is Currency
     assert type(3 - Currency(2)) is Currency
     assert type(Currency(3) * 2) is Currency
     assert type(3 * Currency(2)) is Currency
     assert type(floordiv(Currency(3), 2)) is Currency
     assert type(floordiv(3, Currency(2))) is Currency
     assert type(truediv(Currency(3), 2)) is Currency
     assert type(truediv(3, Currency(2))) is Currency
     assert type(Currency(3) ** 2) is Currency
     assert type(2 ** Currency(3)) is Currency
     assert type(+Currency(2)) is Currency
     assert type(-Currency(2)) is Currency
     assert type(abs(Currency(2))) is Currency
Exemplo n.º 27
0
    def uniquifying_suffix(self, iteration):
        """
        Create a unique suffix.

        This creates a suffix based on the number given as ``iteration``. It
        will return a value encoded as lowercase ascii letter. So we have an
        alphabet of 26 letters. The returned suffix will be for example ``_yh``
        where ``yh`` is the encoding of ``iteration``. The length of it will be
        ``math.log(iteration, 26)``.

        Examples::

            uniquifying_suffix(0) == '_a'
            uniquifying_suffix(25) == '_z'
            uniquifying_suffix(26) == '_ba'
            uniquifying_suffix(52) == '_ca'
        """
        alphabet = string.ascii_lowercase
        length = len(alphabet)
        if iteration == 0:
            power = 0
        else:
            power = int(math.log(iteration, length))
        current = iteration
        suffix = ''
        for exp in reversed(list(range(0, power + 1))):
            digit = int(truediv(current, length ** exp))
            suffix += alphabet[digit]
            current = current % length ** exp
        return '_{suffix}'.format(suffix=suffix)
Exemplo n.º 28
0
    def recalc_cpu(self):
        # Determine how much CPU we have.
        self.available_cpus = array([0,0,0,0,0], long)
        self.sleeping_cpus = 0
        for base in g.all_bases():
            if base.done:
                if base.power_state in ["active", "overclocked", "suicide"]:
                    self.available_cpus[:base.location.safety+1] += base.cpu
                elif base.power_state == "sleep":
                    self.sleeping_cpus += base.cpu

        # Convert back from <type 'numpy.int32'> to avoid overflow issues later.
        self.available_cpus = [int(danger) for danger in self.available_cpus]

        # If we don't have enough to meet our CPU usage, we reduce each task's
        # usage proportionately.
        # It must be computed separalty for each danger.
        needed_cpus = array([0,0,0,0,0], long)
        for task_id, cpu in self.cpu_usage.iteritems():
            danger = task.danger_for(task_id)
            needed_cpus[:danger+1] += cpu
        for danger, (available_cpu, needed_cpu) in enumerate(zip(self.available_cpus, needed_cpus)):
            if needed_cpu > available_cpu:
                pct_left = truediv(available_cpu, needed_cpu)
                for task_id, cpu_assigned in self.cpu_usage.iteritems():
                    task_danger = task.danger_for(task_id)
                    if (danger == task_danger):
                        self.cpu_usage[task_id] = int(cpu_assigned * pct_left)
                g.map_screen.needs_rebuild = True
Exemplo n.º 29
0
def test_arithmetic_returns_money_instance():
    assert type(Money(3) + 2) is Money
    assert type(3 + Money(2)) is Money
    assert type(Money(3) - 2) is Money
    assert type(3 - Money(2)) is Money
    assert type(Money(3) * 2) is Money
    assert type(3 * Money(2)) is Money
    assert type(floordiv(Money(3), 2)) is Money
    assert type(floordiv(3, Money(2))) is Money
    assert type(truediv(Money(3), 2)) is Money
    assert type(truediv(3, Money(2))) is Money
    assert type(Money(3) ** 2) is Money
    assert type(2 ** Money(3)) is Money
    assert type(+Money(2)) is Money
    assert type(-Money(2)) is Money
    assert type(abs(Money(2))) is Money
Exemplo n.º 30
0
 def test_div_truediv(self, op):
   input1 = [1, 5, 7., 3.3]
   input2 = [9.2, 10, 11, 4.9]
   data = op(Stream(input1), Stream(input2))
   expected = [operator.truediv(x, y) for x, y in xzip(input1, input2)]
   assert isinstance(data, Stream)
   assert list(data) == expected
Exemplo n.º 31
0
class TestSeriesOperators(TestData):
    def test_operators_empty_int_corner(self):
        s1 = Series([], [], dtype=np.int32)
        s2 = Series({'x': 0.})
        assert_series_equal(s1 * s2, Series([np.nan], index=['x']))

    def test_ops_datetimelike_align(self):
        # GH 7500
        # datetimelike ops need to align
        dt = Series(date_range('2012-1-1', periods=3, freq='D'))
        dt.iloc[2] = np.nan
        dt2 = dt[::-1]

        expected = Series([timedelta(0), timedelta(0), pd.NaT])
        # name is reset
        result = dt2 - dt
        assert_series_equal(result, expected)

        expected = Series(expected, name=0)
        result = (dt2.to_frame() - dt.to_frame())[0]
        assert_series_equal(result, expected)

    def test_operators_corner(self):
        series = self.ts

        empty = Series([], index=Index([]))

        result = series + empty
        assert np.isnan(result).all()

        result = empty + Series([], index=Index([]))
        assert len(result) == 0

        # TODO: this returned NotImplemented earlier, what to do?
        # deltas = Series([timedelta(1)] * 5, index=np.arange(5))
        # sub_deltas = deltas[::2]
        # deltas5 = deltas * 5
        # deltas = deltas + sub_deltas

        # float + int
        int_ts = self.ts.astype(int)[:-5]
        added = self.ts + int_ts
        expected = Series(self.ts.values[:-5] + int_ts.values,
                          index=self.ts.index[:-5],
                          name='ts')
        tm.assert_series_equal(added[:-5], expected)

    pairings = []
    for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']:
        fv = 0
        lop = getattr(Series, op)
        lequiv = getattr(operator, op)
        rop = getattr(Series, 'r' + op)
        # bind op at definition time...
        requiv = lambda x, y, op=op: getattr(operator, op)(y, x)
        pairings.append((lop, lequiv, fv))
        pairings.append((rop, requiv, fv))
    if compat.PY3:
        pairings.append((Series.div, operator.truediv, 1))
        pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), 1))
    else:
        pairings.append((Series.div, operator.div, 1))
        pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1))

    @pytest.mark.parametrize('op, equiv_op, fv', pairings)
    def test_operators_combine(self, op, equiv_op, fv):
        def _check_fill(meth, op, a, b, fill_value=0):
            exp_index = a.index.union(b.index)
            a = a.reindex(exp_index)
            b = b.reindex(exp_index)

            amask = isna(a)
            bmask = isna(b)

            exp_values = []
            for i in range(len(exp_index)):
                with np.errstate(all='ignore'):
                    if amask[i]:
                        if bmask[i]:
                            exp_values.append(nan)
                            continue
                        exp_values.append(op(fill_value, b[i]))
                    elif bmask[i]:
                        if amask[i]:
                            exp_values.append(nan)
                            continue
                        exp_values.append(op(a[i], fill_value))
                    else:
                        exp_values.append(op(a[i], b[i]))

            result = meth(a, b, fill_value=fill_value)
            expected = Series(exp_values, exp_index)
            assert_series_equal(result, expected)

        a = Series([nan, 1., 2., 3., nan], index=np.arange(5))
        b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6))

        result = op(a, b)
        exp = equiv_op(a, b)
        assert_series_equal(result, exp)
        _check_fill(op, equiv_op, a, b, fill_value=fv)
        # should accept axis=0 or axis='rows'
        op(a, b, axis=0)

    def test_operators_na_handling(self):
        from decimal import Decimal
        from datetime import date
        s = Series([Decimal('1.3'), Decimal('2.3')],
                   index=[date(2012, 1, 1), date(2012, 1, 2)])

        result = s + s.shift(1)
        result2 = s.shift(1) + s
        assert isna(result[0])
        assert isna(result2[0])

    def test_op_duplicate_index(self):
        # GH14227
        s1 = Series([1, 2], index=[1, 1])
        s2 = Series([10, 10], index=[1, 2])
        result = s1 + s2
        expected = pd.Series([11, 12, np.nan], index=[1, 1, 2])
        assert_series_equal(result, expected)

    @pytest.mark.parametrize(
        "test_input,error_type",
        [
            (pd.Series([]), ValueError),

            # For strings, or any Series with dtype 'O'
            (pd.Series(['foo', 'bar', 'baz']), TypeError),
            (pd.Series([(1, ), (2, )]), TypeError),

            # For mixed data types
            (pd.Series(['foo', 'foo', 'bar', 'bar', None, np.nan, 'baz'
                        ]), TypeError),
        ])
    def test_assert_idxminmax_raises(self, test_input, error_type):
        """
        Cases where ``Series.argmax`` and related should raise an exception
        """
        with pytest.raises(error_type):
            test_input.idxmin()
        with pytest.raises(error_type):
            test_input.idxmin(skipna=False)
        with pytest.raises(error_type):
            test_input.idxmax()
        with pytest.raises(error_type):
            test_input.idxmax(skipna=False)

    def test_idxminmax_with_inf(self):
        # For numeric data with NA and Inf (GH #13595)
        s = pd.Series([0, -np.inf, np.inf, np.nan])

        assert s.idxmin() == 1
        assert np.isnan(s.idxmin(skipna=False))

        assert s.idxmax() == 2
        assert np.isnan(s.idxmax(skipna=False))

        # Using old-style behavior that treats floating point nan, -inf, and
        # +inf as missing
        with pd.option_context('mode.use_inf_as_na', True):
            assert s.idxmin() == 0
            assert np.isnan(s.idxmin(skipna=False))
            assert s.idxmax() == 0
            np.isnan(s.idxmax(skipna=False))
Exemplo n.º 32
0
 def __rtruediv__(self, other):
     return operator.truediv(other, self._val)
Exemplo n.º 33
0
 def __truediv__(self, other: Num) -> float:
     return operator.truediv(object.__getattribute__(self, "_obj"), other)
Exemplo n.º 34
0
 def __rtruediv__(self, other):
     return operator.truediv(other, self.__wrapped__)
Exemplo n.º 35
0
 def __itruediv__(self, other):
     'True divide each component of this Vector3.'
     self.x = operator.truediv(self.x, other)
     self.y = operator.truediv(self.y, other)
     self.z = operator.truediv(self.z, other)
     return self
Exemplo n.º 36
0
 def test_truediv_scalar(self):
     finalVector = truediv(Vector(6, 6), 2.)
     self.assertAlmostEqual(finalVector.x, 3.)
     self.assertAlmostEqual(finalVector.y, 3.)
Exemplo n.º 37
0
 def __rtruediv__(self, other: Number) -> MatBaseType:
     return self._apply_op(other, lambda val_b, val_a: operator.truediv(val_a, val_b))
Exemplo n.º 38
0
 def __rtruediv__(self, other):
     assert type(other) in (int, float), \
         'Cannot divide types {} and {}'.format(self.__class__.__name__, type(other))
     return Vector3D(operator.truediv(other, self.x),
                     operator.truediv(other, self.y),
                     operator.truediv(other, self.z))
Exemplo n.º 39
0
    'normalize_to_max':
    lambda d, _: d / np.max(d),

    # Cumulation
    'cumulate':
    lambda d, _: np.cumsum(d),
    'cumulate_complementary':
    lambda d, _: np.cumsum(d[::-1])[::-1],

    # Elementwise (binary) operations
    'add':
    lambda d, v: operator.add(d, v),
    'concat':
    lambda d, v: operator.concat(d, v),
    'div':
    lambda d, v: operator.truediv(d, v),
    'truediv':
    lambda d, v: operator.truediv(d, v),
    'floordiv':
    lambda d, v: operator.floordiv(d, v),
    'lshift':
    lambda d, v: operator.lshift(d, v),
    'mod':
    lambda d, v: operator.mod(d, v),
    'mul':
    lambda d, v: operator.mul(d, v),
    'matmul':
    lambda d, v: operator.matmul(d, v),
    'rshift':
    lambda d, v: operator.rshift(d, v),
    'sub':
Exemplo n.º 40
0
 def __rtruediv__(self, y):
   return NonStandardInteger(operator.truediv(y, self.val))
    def run_model(self):

        ## initialize data structure

        self.res = np.zeros([
            self.duration,
            len(MODEL_RUN_COLUMNS) + len(EXPORT_COLUMNS_FOR_CSV)
        ],
                            dtype=np.float32)

        self.res[0, 0] = self.nf1
        self.res[0, 1] = self.nf2
        self.res[0, 2] = self.nf3
        self.res[0, 3] = self.nm1
        self.res[0, 4] = self.nm2
        self.res[0, 5] = self.nm3
        self.res[0, 6] = 0
        self.res[0, 7] = 0
        self.res[0, 8] = 0
        self.res[0, 9] = self.female_promotion_probability_1
        self.res[0, 10] = self.female_promotion_probability_2
        self.res[0, 11] = np.float32(
            sum(list([self.nf1, self.nf2, self.nf3])) / sum(
                list([
                    self.nf1, self.nf2, self.nf3, self.nm1, self.nm2, self.nm3
                ])))
        self.res[0, 12] = 0
        self.res[0, 13] = self.res[0, 0:6].sum()
        self.res[0, 14:] = 0

        # I assign the state variables to temporary variables. That way I
        # don't have to worry about overwriting the original state variables.

        hiring_rate_female_level_1 = self.bf1
        hiring_rate_female_level_2 = self.bf2
        hiring_rate_female_level_3 = self.bf3
        attrition_rate_female_level_1 = self.df1
        attrition_rate_female_level_2 = self.df2
        attrition_rate_female_level_3 = self.df3
        attrition_rate_male_level_1 = self.dm1
        attrition_rate_male_level_2 = self.dm2
        attrition_rate_male_level_3 = self.dm3
        probability_of_outside_hire_level_3 = self.phire3
        probability_of_outside_hire_level_2 = self.phire2
        female_promotion_probability_1_2 = self.female_promotion_probability_1
        female_promotion_probability_2_3 = self.female_promotion_probability_2
        department_size_upper_bound = self.upperbound
        department_size_lower_bound = self.lowerbound
        variation_range = self.variation_range
        unfilled_vacanies = 0
        change_to_level_1 = 0
        change_to_level_2 = 0
        change_to_level_3 = 0

        for i in range(1, self.duration):
            # initialize variables for this iteration

            prev_number_of_females_level_1 = self.res[i - 1, 0]
            prev_number_of_females_level_2 = self.res[i - 1, 1]
            prev_number_of_females_level_3 = self.res[i - 1, 2]
            prev_number_of_males_level_1 = self.res[i - 1, 3]
            prev_number_of_males_level_2 = self.res[i - 1, 4]
            prev_number_of_males_level_3 = self.res[i - 1, 5]
            prev_number_of_vacancies_level_3 = self.res[i - 1, 6]
            prev_number_of_vacancies_level_2 = self.res[i - 1, 7]
            prev_number_of_vacancies_level_1 = self.res[i - 1, 8]
            prev_promotion_rate_female_level_1 = self.female_promotion_probability_1
            prev_promotion_rate_female_level_2 = self.female_promotion_probability_2
            department_size = self.res[i - 1, 0:6].sum()

            # Process Model

            # Determine department size variation for this timestep

            # first both female and males leave the department according to binomial probability.

            female_attrition_level_3 = binomial(prev_number_of_females_level_3,
                                                attrition_rate_female_level_3)

            male_attrition_level_3 = binomial(prev_number_of_males_level_3,
                                              attrition_rate_male_level_3)

            # the departures create a set of vacancies. These vacancies are the basis for new hiring
            total_vacancies_3 = female_attrition_level_3 + \
                                male_attrition_level_3 + change_to_level_3

            # women are hired first and then men
            hiring_female_3 = binomial(
                max(0,
                    total_vacancies_3), probability_of_outside_hire_level_3 *
                hiring_rate_female_level_3)

            hiring_male_3 = binomial(
                max(0, total_vacancies_3 - hiring_female_3),
                probability_of_outside_hire_level_3 *
                (1 - hiring_rate_female_level_3))

            total_hiring_3 = hiring_female_3 + hiring_male_3

            # level 3 vacancies that are not filled by new hires create opportunities
            # for promotion from level 2. Again women are promoted first and men second.
            # Also note the error trap that if we try to promote more professors from
            # level 2 than there exist at level 2, then we will prevent this from happening.

            vacancies_remaining_after_hiring_3 = total_vacancies_3 - total_hiring_3

            potential_promotions_after_hiring_3 = max(
                0, vacancies_remaining_after_hiring_3)

            promotions_of_females_level_2_3 = binomial(
                min(potential_promotions_after_hiring_3,
                    prev_number_of_females_level_2),
                female_promotion_probability_2_3)

            promotions_of_males_level_2_3 = binomial(
                max(
                    0,
                    min(
                        vacancies_remaining_after_hiring_3 -
                        promotions_of_females_level_2_3,
                        prev_number_of_males_level_2)),
                1 - female_promotion_probability_2_3)

            # attrition at level 2 - either people leave from attrition or promotion

            female_attrition_level_2 = binomial(
                max(
                    0, prev_number_of_females_level_2 -
                    promotions_of_females_level_2_3),
                attrition_rate_female_level_2)

            male_attrition_level_2 = binomial(
                max(
                    0, prev_number_of_males_level_2 -
                    promotions_of_males_level_2_3),
                attrition_rate_male_level_2)

            # the departures create a set of vacancies. These vacancies are the basis for new hiring
            total_vacancies_2 = sum(
                list([
                    female_attrition_level_2, male_attrition_level_2,
                    promotions_of_females_level_2_3,
                    promotions_of_males_level_2_3, change_to_level_2
                ]))

            hiring_female_2 = binomial(
                max(0,
                    total_vacancies_2), probability_of_outside_hire_level_2 *
                hiring_rate_female_level_2)
            hiring_male_2 = binomial(
                max(0, total_vacancies_2 - hiring_female_2),
                probability_of_outside_hire_level_2 *
                (1 - hiring_rate_female_level_2))

            total_hiring_2 = hiring_female_2 + hiring_male_2

            vacancies_remaining_after_hiring_2 = total_vacancies_2 - total_hiring_2

            potential_promotions_after_hiring_2 = max(
                0, vacancies_remaining_after_hiring_2)

            promotions_of_females_level_1_2 = binomial(
                max(
                    0,
                    min(potential_promotions_after_hiring_2,
                        prev_number_of_females_level_1)),
                female_promotion_probability_1_2)

            promotions_of_males_level_1_2 = binomial(
                max(
                    0,
                    min(
                        vacancies_remaining_after_hiring_2 -
                        promotions_of_females_level_1_2,
                        prev_number_of_females_level_1)),
                probability_of_outside_hire_level_2 *
                (1 - female_promotion_probability_1_2))

            ## Level 1

            female_attrition_level_1 = binomial(
                max(
                    0, prev_number_of_females_level_1 -
                    promotions_of_females_level_1_2),
                attrition_rate_female_level_1)

            male_attrition_level_1 = binomial(
                max(
                    0, prev_number_of_males_level_1 -
                    promotions_of_males_level_1_2),
                attrition_rate_male_level_1)

            total_vacancies_1 = sum(
                list([
                    female_attrition_level_1, male_attrition_level_1,
                    promotions_of_females_level_1_2,
                    promotions_of_males_level_1_2, change_to_level_1
                ]))

            hiring_female_1 = binomial(max(0, total_vacancies_1),
                                       hiring_rate_female_level_1)

            hiring_male_1 = binomial(
                max(0, total_vacancies_1 - hiring_female_1),
                1 - hiring_rate_female_level_1)

            # Write state variables to array and move to next iteration

            self.res[i, 0] = number_of_females_level_1 = sum(
                list([
                    prev_number_of_females_level_1,
                    neg(female_attrition_level_1),
                    neg(promotions_of_females_level_1_2), hiring_female_1
                ]))

            assert (number_of_females_level_1 >=
                    0), "negative number of females 1"

            self.res[i, 1] = number_of_females_level_2 = max(
                0,
                sum(
                    list([
                        prev_number_of_females_level_2,
                        neg(female_attrition_level_2),
                        neg(promotions_of_females_level_2_3),
                        promotions_of_females_level_1_2, hiring_female_2
                    ])))

            self.res[i, 2] = number_of_females_level_3 = sum(
                list([
                    prev_number_of_females_level_3,
                    neg(female_attrition_level_3),
                    promotions_of_females_level_2_3, hiring_female_3
                ]))

            self.res[i, 3] = number_of_males_level_1 = sum(
                list([
                    prev_number_of_males_level_1,
                    neg(male_attrition_level_1),
                    neg(promotions_of_males_level_1_2), hiring_male_1
                ]))

            self.res[i, 4] = number_of_males_level_2 = sum(
                list([
                    prev_number_of_males_level_2,
                    neg(male_attrition_level_2),
                    neg(promotions_of_males_level_2_3),
                    promotions_of_males_level_1_2, hiring_male_2
                ]))

            self.res[i, 5] = number_of_males_level_3 = sum(
                list([
                    prev_number_of_males_level_3,
                    neg(male_attrition_level_3), promotions_of_males_level_2_3,
                    hiring_male_3
                ]))

            self.res[i, 6] = sum(
                list([male_attrition_level_3, female_attrition_level_3]))

            self.res[i, 7] = sum(
                list([
                    male_attrition_level_2, female_attrition_level_2,
                    promotions_of_females_level_2_3,
                    promotions_of_males_level_2_3
                ]))

            self.res[i, 8] = sum(
                list([
                    male_attrition_level_1, female_attrition_level_1,
                    promotions_of_males_level_1_2,
                    promotions_of_females_level_1_2
                ]))

            self.res[i, 9] = self.female_promotion_probability_1
            self.res[i, 10] = self.female_promotion_probability_2
            self.res[i, 11] = np.float32(
                truediv(
                    sum(
                        list([
                            number_of_females_level_1,
                            number_of_females_level_2,
                            number_of_females_level_3
                        ])),
                    sum(
                        list([
                            number_of_females_level_1,
                            number_of_females_level_2,
                            number_of_females_level_3, number_of_males_level_1,
                            number_of_males_level_2, number_of_males_level_3
                        ]))))
            unfilled_vacanies = abs(department_size - self.res[i, 0:6].sum())

            self.res[i, 12] = unfilled_vacanies
            department_size = self.res[i, 0:6].sum()
            self.res[i, 13] = department_size
            self.res[i, 14] = hiring_female_3
            self.res[i, 15] = hiring_male_3
            self.res[i, 16] = hiring_female_2
            self.res[i, 17] = hiring_male_2
            self.res[i, 18] = hiring_female_1
            self.res[i, 19] = hiring_male_1
            self.res[i, 20] = 0
            self.res[i, 21] = 0
            self.res[i, 22] = promotions_of_females_level_2_3
            self.res[i, 23] = promotions_of_males_level_2_3
            self.res[i, 24] = promotions_of_females_level_1_2
            self.res[i, 25] = promotions_of_males_level_1_2
            self.res[i, 26] = hiring_rate_female_level_1
            self.res[i, 27] = hiring_rate_female_level_2
            self.res[i, 28] = hiring_rate_female_level_3
            self.res[i, 29] = 1 - hiring_rate_female_level_1
            self.res[i, 30] = 1 - hiring_rate_female_level_2
            self.res[i, 31] = 1 - hiring_rate_female_level_3
            self.res[i, 32] = attrition_rate_female_level_1
            self.res[i, 33] = attrition_rate_female_level_2
            self.res[i, 34] = attrition_rate_female_level_3
            self.res[i, 35] = attrition_rate_male_level_1
            self.res[i, 36] = attrition_rate_male_level_2
            self.res[i, 37] = attrition_rate_male_level_3
            self.res[i, 38] = 1
            self.res[i, 39] = probability_of_outside_hire_level_2
            self.res[i, 40] = probability_of_outside_hire_level_3
            self.res[i, 41] = female_promotion_probability_1_2
            self.res[i, 42] = female_promotion_probability_2_3
            self.res[i, 43] = 1 - female_promotion_probability_1_2
            self.res[i, 44] = 1 - female_promotion_probability_2_3
            self.res[i, 45] = department_size_upper_bound
            self.res[i, 46] = department_size_lower_bound
            self.res[i, 47] = variation_range
            self.res[i, 48] = self.duration

            # this produces an array of values. Then I need to assign the
            # values to levels. So if I have say a range of variation of 5. I
            #  will get something like [-1,0,1,-1,0] or something. I need to
            # turn this into something like [2,-1,0]. That means randomly
            # assigning the values in the array to levels.

            flag = False
            while flag == False:

                changes = np.random.choice([-1, 0, 1], variation_range)

                levels = np.random.choice([1, 2, 3], variation_range)  #
                # random level
                # choice

                # need to test whether the candidate changes keep the
                # department size within bounds.
                # print(["old dept size:", department_size,
                #        "new dept size:", self.res[i, 0:6].sum(),
                #        "candidate:", department_size +
                #        changes.sum(),
                #        " added postions: ", changes.sum(),
                #        "unfilled ", unfilled_vacanies])
                if (department_size + changes.sum() <=
                        department_size_upper_bound
                        and department_size + changes.sum() >=
                        department_size_lower_bound):
                    change_to_level_3 = np.int(
                        changes[np.where(levels == 3)[0]].sum())
                    change_to_level_2 = np.int(
                        changes[np.where(levels == 2)[0]].sum())
                    change_to_level_1 = np.int(
                        changes[np.where(levels == 1)[0]].sum())
                    flag = True

                if (department_size > department_size_upper_bound):
                    change_to_level_3 = 0
                    change_to_level_2 = 0
                    change_to_level_1 = 0

                    flag = True

                if department_size < department_size_lower_bound:
                    changes = np.ones(variation_range)
                    change_to_level_3 = np.int(
                        changes[np.where(levels == 3)[0]].sum())
                    change_to_level_2 = np.int(
                        changes[np.where(levels == 2)[0]].sum())
                    change_to_level_1 = np.int(
                        changes[np.where(levels == 1)[0]].sum())
                    flag = True

        df_ = pd.DataFrame(self.res)
        df_.columns = MODEL_RUN_COLUMNS + EXPORT_COLUMNS_FOR_CSV

        recarray_results = df_.to_records(index=True)
        self.run = recarray_results
        return recarray_results
Exemplo n.º 42
0
 def _percent_complete(self, available=(0, 0, 0)):
     available_array = array(available, long)
     return truediv(self.cost_paid + available_array, self.total_cost)
Exemplo n.º 43
0
 def test_truediv_twovectors(self):
     finalVector = truediv(Vector(6, 6), Vector(2., 2.))
     self.assertAlmostEqual(finalVector.x, 3.)
     self.assertAlmostEqual(finalVector.y, 3.)
Exemplo n.º 44
0
 def __rdiv__(self, other):
     return operator.truediv(*reversed(self._get_operands(other)))
Exemplo n.º 45
0
def main():
    print('{:.2f}'.format(float(truediv(*map(int, input().split())))))
Exemplo n.º 46
0
def is_valid_prefix_expression(expression):
    '''
    >>> is_valid_prefix_expression('12')
    Correct prefix expression
    >>> is_valid_prefix_expression('+ 12 4')
    Correct prefix expression
    >>> is_valid_prefix_expression('- + 12 4 10')
    Correct prefix expression
    >>> is_valid_prefix_expression('+ - + 12 4 10 * 11 4')
    Correct prefix expression
    >>> is_valid_prefix_expression('/ + - + 12 4 10 * 11 4 5')
    Correct prefix expression
    >>> is_valid_prefix_expression('+ / + - + 12 4 10 * 11 4 5 - 80 82 ')
    Correct prefix expression
    >>> is_valid_prefix_expression('twelve')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('2 3')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+ + 2 3')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+1 2')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+ / 1 2 *3 4')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+1 2')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+ +1 2')
    Correct prefix expression
    >>> is_valid_prefix_expression('++1 2')
    Incorrect prefix expression
    >>> is_valid_prefix_expression('+ +1 -2')
    Correct prefix expression
    '''
    stack = []
    op_dic = {
        '+': lambda x, y: add(x, y),
        '-': lambda x, y: sub(x, y),
        '*': lambda x, y: mul(x, y),
        '/': lambda x, y: truediv(x, y)
        }
    try:
        list_ = expression.split(' ')
        for item in reversed(list_):
            if not item:
                continue
            if item in op_dic:
                up = stack.pop()
                down = stack.pop()
                stack.append(op_dic[item](up, down))
            else:
                stack.append(int(item))
        if len(stack) != 1:
            raise ListNonEmpty
                
                
                
        
    # - IndexError is raised in particular when trying to pop from an empty list
    # - ValueError is raised in particular when trying to convert to an int
    #   a string that cannot be converted to an int
    # - ListNonEmpty is expected to be raised when a list is found out not to be empty
    except (IndexError, ValueError, ListNonEmpty):
        print('Incorrect prefix expression')
    else:
        print('Correct prefix expression')
Exemplo n.º 47
0
 def __truediv__(self, other):
     'Get a new Vector3 by true dividing each component of this one.'
     return Vector3Index(self.index, operator.truediv(self.x, other),
                         operator.truediv(self.y, other),
                         operator.truediv(self.z, other))
Exemplo n.º 48
0
def doLinePlots(args, df0, key_geo, comparison=True):

    if comparison == True:
        region = 'WorldAll'
        if key_geo == 'EU':
            return
    else:
        region = key_geo

    for perCapita in (
            True,
            False,
    ):
        # for k, limSum in (('cases_weekly', 20000), ('deaths_weekly', 500)):
        for k in ('cases', 'deaths'):
            print('line', key_geo, perCapita, k)

            path = 'days100_{}_perCapita{}_{}.png'.format(
                k, perCapita, key_geo.replace(' ', '_'))
            if os.path.isfile(path):
                continue

            k += '_weekly'

            d = {True: [], False: []}
            # for country in df0['countriesAndTerritories'].unique():
            labels = set()
            for country in args.d_region2countries[region]:
                if comparison is True and country == key_geo:
                    continue
                if df0[df0['countriesAndTerritories'].isin([country
                                                            ])][k].sum() == 0:
                    continue
                if perCapita is True:
                    value = operator.truediv(
                        10**6 * df0[df0['countriesAndTerritories'].isin(
                            [country])][k].sum(),
                        df0[df0['countriesAndTerritories'].isin(
                            [country])]['popData2019'].unique(),
                    )[0]
                    if np.isnan(value):
                        continue
                else:
                    value = df0[df0['countriesAndTerritories'].isin(
                        [country])][k].sum()
                if comparison is True:
                    _ = args.d_country2continent[
                        country] == args.d_country2continent[key_geo]
                else:
                    _ = True
                d[_].append((value, country))

            if comparison is True:
                tuples = itertools.chain(
                    reversed(sorted(d[False])),
                    reversed(sorted(d[True])),
                    [(None, key_geo)],
                )
            else:
                tuples = itertools.chain(
                    reversed(sorted(d[False])),
                    reversed(sorted(d[True])),
                )

            for t in tuples:
                country = t[1]
                df = df0[df0['countriesAndTerritories'].isin(
                    [country])].sort_values(by='dateRep', ascending=True)
                if k == 'deaths' and 'South' in country:
                    print(k, country, df[k].sum())
                if df[k].sum() < 10:
                    continue
                # if df[k].sum() < limSum and country not in (
                #     'Japan', 'South_Korea', 'Taiwan', 'Singapore',
                #     'United_States_of_America', 'United_Kingdom',
                #     ):
                #     continue
                # if country in ('Iran',):
                #     continue
                # print(country, df[k].sum())
                # print(country, df[k].sum())
                if perCapita is False:
                    lim = {'cases_weekly': 1000, 'deaths_weekly': 100}[k]
                    y = df[k].cumsum()[df[k].cumsum() > lim].values
                else:
                    lim = 1
                    # s = 10**6 * df[k].cumsum()[df[k].cumsum() > 100].values / df['popData2018'].unique()[0]
                    # y = s
                    s = 10**6 * df[k].cumsum() / df['popData2019'].unique()
                    y = s[s > lim]
                    y = df[k].cumsum()[df[k].cumsum(
                    ) > 100].values / df['popData2019'].unique()
                if df[k].sum() < lim:
                    continue
                if len(y) == 0:
                    continue
                x = list(range(len(y)))
                if comparison is False:
                    color = None
                    label = '{} ({:d})'.format(
                        country.replace('_', ' ').replace(
                            'United States of America',
                            'US').replace('United Kingdom', 'UK'),
                        int(max(y)),
                    )
                    linewidth = 2
                else:
                    if country == key_geo:
                        # country = country.replace('United States of America', 'US')
                        # country = country.replace('United Kingdom', 'UK')
                        color = '#e41a1c'  # red
                        label = '{} ({:d})'.format(
                            country.replace('_', ' '),
                            int(max(y)),
                        )
                        linewidth = 4
                    else:
                        continent = args.d_country2continent[country]
                        if continent == 'North America':
                            continent = 'Americas'
                        color = {
                            # 'North America': '#8dd3c7',
                            'Americas': '#8dd3c7',
                            'Africa': '#ffffb3',
                            'Europe': '#bebada',
                            'Asia': '#fb8072',
                            'Oceania': '#80b1d3',
                        }[continent]

                        if continent == args.d_country2continent[key_geo]:
                            color = 'darkgrey'
                            label = continent
                        else:
                            color = 'lightgrey'
                            label = 'Rest of World'

                        if label in labels:
                            label = None
                        else:
                            labels.add(label)

                        linewidth = 2

                plt.semilogy(
                    x,
                    y,
                    label=label,
                    color=color,
                    linewidth=linewidth,
                )
            plt.legend(prop={'size': 6})

            if perCapita is True:
                textPerCapita = ' per 1 million capita'
            else:
                textPerCapita = ''

            if lim == 1:
                kSingPlur = k.lower().split('_')[0][:-1]
            else:
                kSingPlur = k.lower().split('_')[0]

            plt.xlabel('Weeks since {} confirmed {}{}'.format(
                lim, kSingPlur, textPerCapita))
            plt.ylabel('Cumulated confirmed {}{}'.format(
                k.lower().split('_')[0], textPerCapita))
            if lim == 1:
                textLim = '{}{}'.format(k.lower()[:-1], textPerCapita)
                textLim = kSingPlur
            else:
                textLim = '{}{}'.format(k.lower(), textPerCapita)
                textLim = kSingPlur
            keyUpperCase = '{}{} {}'.format(
                k.split('_')[1][0].upper(),
                k.split('_')[1][1:],
                k.split('_')[0])
            plt.title('{}\n{}{} after first week with more than {} {}'.format(
                key_geo, keyUpperCase, textPerCapita, lim, textLim),
                      fontsize='small')
            plt.savefig(path, dpi=75)
            plt.savefig(path[:-4] + '_thumb.png', dpi=25)
            plt.clf()

    return
Exemplo n.º 49
0
 def aspect(self):
     producer = self._renderer.producer
     return truediv(*producer.framesize) if producer is not None else 16 / 9
Exemplo n.º 50
0
func print() has output/return value None and displays whatever is passed into it.
"""
print(-2) is None  # True



# true dividend
2013 / 10
# integer dividend
2013 // 10
# reminder dividend
2013 % 10

from operator import truediv, floordiv, mod
truediv(2013, 10)
floordiv(2013, 10)
mod(2013, 10)


"""
Boolean contexts

False values in Python: False, 0, '', None
True values in Python: anything else
"""



"""
return and print
Exemplo n.º 51
0
 def __div__(self, other):
     return operator.truediv(*self._get_operands(other))
Exemplo n.º 52
0
def optimize_image(path):
    _image = Image.open(path)
    if _image.size[0] > 720:
        _image.resize(
            (720, round(truediv(*_image.size[::-1]) * 720))).save(path,
                                                                  quality=95)
Exemplo n.º 53
0
def python_filter(img, layer):
    region = layer.get_pixel_rgn(0, 0, img.width, img.height, True, False)
    xed = img.width
    yed = img.height

    clust = [[0] * 8] * 8
    r0 = [[0] * 8] * 8
    g0 = [[0] * 8] * 8
    b0 = [[0] * 8] * 8

    plte = [0x000000] * 16
    plte[0] = 0x000000
    plte[2] = 0x0000B4
    plte[1] = 0xB40000
    plte[3] = 0xB400B4
    plte[4] = 0x00B400
    plte[6] = 0x00B4B4
    plte[5] = 0xB4B400
    plte[7] = 0xB4B4B4
    plte[8] = 0x000000
    plte[10] = 0x0000FF
    plte[9] = 0xFF0000
    plte[11] = 0xFF00FF
    plte[12] = 0x00FF00
    plte[14] = 0x00FFFF
    plte[13] = 0xFFFF00
    plte[15] = 0xFFFFFF

    #'- "00,12,03,15,08,04,11,07,02,14,01,13,10,06,09,05."
    #'- "00,06,08,14,02,12,04,10,08,14,00,06,04,10,02,12."
    clust = [[0, 6, 8, 14], [2, 12, 4, 10], [8, 14, 0, 6], [4, 10, 2, 12]]
    hbedge = 180  #- halfbright attr edge -zx32=218, zx32fs=153 , realthing=180?
    rgrsp = 30
    ggrsp = 30
    bgrsp = 30  #- for r, g and b saturation levels

    for y1 in range(0, int(img.height / 8), 1):
        gimp.progress_update(operator.truediv(y1, int(img.height / 8)))
        # print y1
        for x1 in range(0, int(img.width / 8), 1):
            for y2 in range(0, 8, 1):
                for x2 in range(0, 8, 1):
                    y = y1 * 8 + y2
                    x = x1 * 8 + x2
                    # zzz=point(x,y)
                    str1 = region[x, y]
                    b0[x2][y2] = ord(str1[0])
                    g0[x2][y2] = ord(str1[1])
                    r0[x2][y2] = ord(str1[2])
            bi = 0
            ri = 0
            gi = 0
            for y2 in range(0, 8, 1):
                for x2 in range(0, 8, 1):
                    x = (x1 * 8) + x2
                    y = (y1 * 8) + y2
                    bi = bi + b0[x2][y2]
                    gi = gi + g0[x2][y2]
                    ri = ri + r0[x2][y2]
                    # next:next

            #b=bi/64
            #g=gi/64
            #r=ri/64
            b = operator.truediv(bi, 64)
            g = operator.truediv(gi, 64)
            r = operator.truediv(ri, 64)

            xrreg = 0
            hbrite = 0
            if (r < hbedge) and (g < hbedge) and (b < hbedge):
                hbrite = 1
            hbampl = 255 - (hbrite * (255 - hbedge))

            # if b>(hbampl/2):
            if b > operator.truediv(hbampl, 2):
                b = (hbampl - b)
                xrreg = xrreg | 1

            # if r>(hbampl/2):
            if r > operator.truediv(hbampl, 2):
                r = (hbampl - r)
                xrreg = xrreg | 2

            # if g>(hbampl/2):
            if g > operator.truediv(hbampl, 2):
                g = (hbampl - g)
                xrreg = xrreg | 4

            # halbr=(r*rgrsp)/100
            # halbg=(g*ggrsp)/100
            # halbb=(b*bgrsp)/100
            halbr = operator.truediv((r * rgrsp), 100)
            halbg = operator.truediv((g * ggrsp), 100)
            halbb = operator.truediv((b * bgrsp), 100)

            vlik = 7
            if ((r > halbb) and (g <= halbb)) or ((b <= halbr) and
                                                  (g <= halbr)):
                vlik = 3
            if ((g > halbb) and (r <= halbb)) or ((b <= halbg) and
                                                  (r <= halbg)):
                vlik = 5
            if ((g > halbr) and (b <= halbr)) or ((r <= halbg) and
                                                  (b <= halbg)):
                vlik = 6
            if ((r <= halbb) and (g <= halbb)):
                vlik = 1
            if ((b <= halbr) and (g <= halbr)):
                vlik = 2
            if ((b <= halbg) and (r <= halbg)):
                vlik = 4

            brattr = 1 - hbrite
            ikattr = (
                vlik ^ xrreg
            )  #- ^ is used for xor? very weird.... - from ansi-basic, ^ is ** ?
            paattr = xrreg

            if ikattr < paattr:
                tmpr = ikattr
                ikattr = paattr
                paattr = tmpr

            ikval = ikattr + ((ikattr & 6) / 2)
            paval = paattr + ((paattr & 6) / 2)

            # lumik=(ikval*255)/10
            lumik = operator.truediv((ikval * 255), 10)

            # lumpa=(paval*255)/10
            lumpa = operator.truediv((paval * 255), 10)

            if brattr < 1:
                # lumik=(lumik*hbedge)/255
                lumik = operator.truediv((lumik * hbedge), 255)

                # lumpa=(lumpa*hbedge)/255
                lumpa = operator.truediv((lumpa * hbedge), 255)

            dflum = lumik - lumpa
            for y2 in range(0, 8, 1):
                for x2 in range(0, 8, 1):
                    y = y1 * 8 + y2
                    x = x1 * 8 + x2
                    b = b0[x2][y2]
                    g = g0[x2][y2]
                    r = r0[x2][y2]
                    vlue = (float(b + (r * 3) + (g * 6)) / 10)
                    patgf = (float((clust[x2 & 3][y2 & 3] + 1) * 255) / 16)
                    varnd = (float(patgf * dflum) / 255) + lumpa
                    ik = ikattr + (8 * brattr)
                    if varnd > vlue:
                        ik = paattr + (8 * brattr)

                    str2 = chr((plte[ik] & 0xFF0000) / 65536) + chr(
                        (plte[ik] & 0x00FF00) / 256) + chr(plte[ik] & 0x0000FF)
                    region[x, y] = str2

    layer.update(0, 0, img.width, img.height)
Exemplo n.º 54
0
from operator import add, mul

2 + 3
add(2, 3)
2 + 3 * 4 + 5
add(add(2, mul(3, 4)), 5)
(2 + 3) * (4 + 5)
mul(add(2, 3), add(4, 5))
"""Division"""

2014 / 10
2014 // 10
2014 % 10
from operator import truediv, floordiv, mod
floordiv(2014, 10)
truediv(2014, 10)
mod(2014, 10)
"""Multiple return values"""


def divide_exact(n, d):
    return n // d, n % d


quotient, remainder = divide_exact(2014, 10)
"""Doctrings, doctests, & default arguments"""


def divide_exact2(n, d):
    """Return the quotient and remainder of dividing N by D.
Exemplo n.º 55
0
def calculate_additional_fields(data):
    '''
        add calculated fields to data: \
        total days, total price, \
        total square root of price, unit cost
    '''
    for key, value in data.items():
        # --------------------------------
        try:
            rental_start = datetime.datetime.strptime(value['rental_start'],
                                                      '%m/%d/%y')
        except (SyntaxError, ValueError) as err:
            logging.error('incorect formatting at %s generates %s', key, err)
            logging.warning('rental start date for %s format not m-d-y', key)
            logging.debug('rectify rental start date for %s: %s', key, value)
        # --------------------------------
        try:
            rental_end = datetime.datetime.strptime(value['rental_end'],
                                                    '%m/%d/%y')
        except (SyntaxError, ValueError):
            logging.warning(
                'rental end date for %s has incorrect format \
                            not matching m-d-y', key)
            logging.debug('rectify rental end date for %s: %s', key, value)
        # --------------------------------
        value['total_days'] = (rental_end - rental_start).days
        if op.lt(value['total_days'], 0):
            logging.warning(
                'for %s the rental start date %s \
                            comes after rental end date %s', key, rental_start,
                rental_end)
            logging.debug('rectify rental start date for %s: %s', key, value)
        # --------------------------------
        value['rental_start'] = value['rental_end']
        value['rental_end'] = value['rental_start']
        value['total_price'] = value['total_days'] * value['price_per_day']
        if op.lt(value['total_price'], 0):
            logging.warning(
                'for %s the calculated total price is negative \
                            because calculated rental duration ended up \
                            being negative', key)
            try:
                value['sqrt_total_price'] = math.sqrt(value['total_price'])
            except (ValueError, KeyError) as err:
                logging.warning(
                    'the rental start and end dates reversely \
                                 inserted leading to a math error %s; \
                                 correcting negativity could lead to \
                                 a valid business result', err.args)
                logging.debug('reverse dates insertion to correct at %s', key)
            finally:
                logging.warning('corrected square root total price for %s',
                                key)
                value['sqrt_total_price'] = round(
                    math.sqrt(abs(value['total_price'])), 2)
                value['total_price'] = abs(value['total_price'])
        else:
            value['sqrt_total_price'] = math.sqrt(value['total_price'])
        # --------------------------------
        if op.le(value['units_rented'], 0):
            try:
                value['unit_cost'] = op.truediv(value['total_price'],
                                                value['units_rented'])
            except (ArithmeticError, ZeroDivisionError) as err:
                logging.warning(
                    "for %s the unit cost \
                                 cannot be calculated because %s units \
                                 are rented", key, value['units_rented'])
                logging.error('division by zero: %s', err)
        else:
            value['unit_cost'] = round(
                op.truediv(value['total_price'], value['units_rented']), 2)
        value['total_days'] = abs(value['total_days'])
    return data
Exemplo n.º 56
0
 def __rtruediv__(self, other):
     assert type(other) in (int, long, float)
     return Vector2(operator.truediv(other, self.x),
                    operator.truediv(other, self.y))
Exemplo n.º 57
0
def L2_Norm(data):
    norm = np.linalg.norm(data, ord=2)
    return truediv(data, norm)
Exemplo n.º 58
0
 def __truediv__(self, other):
     if isinstance(other, Register):
         return operator.truediv(self._val, other._val)
     else:
         return operator.truediv(self._val, other)
Exemplo n.º 59
0
print "Length: ", len(y_test)

mf = get_mf(dataset)
mfc = membership.membershipfunction.MemFuncs(mf)
anf = anfis.ANFIS(x_train, y_train, mfc)
anf.trainHybridJangOffLine(epochs=10)
y_predicted = []

for i in range(len(y_test)):
    res = round(anf.fittedValues[y_test[i]], 1)
    if abs(res - 0) < abs(res - 1) < abs(res - 2):
        y_predicted.append(0)
    elif abs(res - 0) > abs(res - 1) < abs(res - 2):
        y_predicted.append(1)
    elif abs(res - 0) > abs(res - 1) > abs(res - 2):
        y_predicted.append(2)

trupred = 0
print y_test
print y_predicted

#check accuracy
for i in range(len(y_predicted)):
    if y_predicted[i] == y_test[i]:
        trupred += 1

print "Sum of TruePrediction: ", trupred
print truediv(trupred, len(y_test)) * 100, "%"

print(classification_report(y_test, y_predicted))
anf.plotResults()
Exemplo n.º 60
0
def feature_normalize2(data):
    mu = np.mean(data, axis=0)
    std = np.std(data, axis=0)
    return truediv((data - mu), std)