Beispiel #1
0
class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        self.assertEqual(6, self.calc.add(3, 3))

    def test_add_method_raises_typeerror_if_not_ints(self):
         self.assertRaises(TypeError, self.calc.add, "Hello", "World")

    def test_error(self):
        with self.assertRaises(AttributeError):
            self.calc.subtract(7, 5)

    def test_assert_equal(self):
        self.assertEqual(1, 1)

    def test_assert_raises(self):
        self.assertRaises(ValueError, int, "a")

    def test_assert_raises_alternative(self):
        with self.assertRaises(AttributeError):
            [].get

    def test_assert_greater(self):
        self.assertGreater(2, 1, "Value is not greater.")

    def test_assert_in(self):
        self.assertIn(1, (1, 2, 3))
Beispiel #2
0
 def test_function_print_result(self):
     myclass = Calculate()
     try:
         myclass.print_result(5, 10)
     except:
         self.fail("Can't call function print result successfully")
     pass
Beispiel #3
0
    def run(self):
        check_md5 = True
        # check_md5 = self.check()
        if not check_md5:
            # 数据源有改动 另算
            print("数据源有改动")
            clear = ClearPhoto()
            clear.run()
            color = Calculate()
            color.run()

        photo_db = self.get_db().get("photo_db")
        photos = self.splits(self.width)
        target_photo = Image.open(self.target_path)
        alls = []
        for p_x in photos:
            temp = []
            for p_y in p_x:
                region = target_photo.crop(p_y)
                limit_photo_value = self.similar(get_photo_avg(region),
                                                 photo_db)[1]
                print(limit_photo_value, '')
                limit_photo_name = list(photo_db.keys())[list(
                    photo_db.values()).index(limit_photo_value)]
                print(limit_photo_name, 'limit_photo_name')
                temp.append(limit_photo_name)
            alls.append(temp)
        self.split_join(alls)
    def testDiag2Chain(self):
        # Perform the diagonalization for a 2-site chain. Compare
        # an exact diagonalization against scipy.
        
        # First calculate X,P
        calc = Calculate()
        polygon = sp.array([[0,0],[2,0]]) 
        maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu")
        precision = 25
        
        X,P = calc.correlations(polygon, maple_link, precision)
        
        entropy = calc.entropy(X, P, 1, precision,False)

        # Manual diag.
        # [ a, b,
        #   c, d]
        XP = X*P
        a = XP[0,0]
        b = XP[0,1]
        c = XP[1,0]
        d = XP[1,1]
        
        eig_plus = ((a+d)+sympy.mpmath.sqrt((a+d)**2-4*(a*d-b*c)))/2
        eig_minus = ((a+d)-sympy.mpmath.sqrt((a+d)**2-4*(a*d-b*c)))/2
        
        sqrt_eigs = [sympy.mpmath.sqrt(eig_plus),sympy.mpmath.sqrt(eig_minus)]
        
        S = 0
        for vk in sqrt_eigs:
            S += ((vk + 0.5)*sympy.mpmath.log(vk + 0.5) - (vk - 0.5)*sympy.mpmath.log(vk - 0.5))
            
        # Scipy operates in double, so we check equality up to a tolerance
        bound = 10**(-13)
        eq_(True, abs(S - entropy) < bound)
Beispiel #5
0
 def run(self):
     poll_obj = poll()
     calculate_obj = Calculate()
     if len(self.names) > 0:
         for server in self.names:
             stopwatch = Stopwatch()
             comm = "openstack server delete " + server
             stopwatch.start()
             os.system(comm)
             SERVER_LIST.append(server)
             while True:
                 delete_status = poll_obj.delete_server(server)
                 if delete_status == 1:
                     TIME_LIST.append(stopwatch.time_elapsed)
                     stopwatch.stop()
                     break
                 elif delete_status == 0:
                     pass
                 elif delete_status == -1:
                     print "Deletion Failed"
                     break
             print "Deleted server..." + server
         min = calculate_obj.getMin(TIME_LIST)
         max = calculate_obj.getMax(TIME_LIST)
         avg = calculate_obj.getAverage(TIME_LIST)
         print "Min: " + str(min)
         print "Max: " + str(max)
         print "Average: " + str(avg)
         dict_return['server'] = SERVER_LIST
         dict_return['min'] = min
         dict_return['max'] = max
         dict_return['avg'] = avg
         dict_return['name'] = "nova.delete"
         disp_list.append(dict_return)
         return disp_list
Beispiel #6
0
def index():
    value = request.json['percentage']
    cls = Calculate(value)
    out = cls.main()
    print(out)
    # result = {"output":out}
    #return jsonify(out)
    response = jsonify(out)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
Beispiel #7
0
	def change(self, array):
		Cal = Calculate()
		ary = Cal.random(array)
		# print ary
		skyWeed_1_0 = Cal.devide(ary, 0)
		earthWeed_1_0 = Cal.devide(ary, 1)
		# print 's1-0', skyWeed_1_0, len(skyWeed_1_0)
		# print 'e1-0', earthWeed_1_0, len(earthWeed_1_0)

		earthWeed_1_1 = Cal.reduceElement(earthWeed_1_0, 1)
		# print 'e1-1', earthWeed_1_1, len(earthWeed_1_1)

		# print Cal.check(Cal.quarterRemains(skyWeed_1_0), Cal.quarterRemains(earthWeed_1_1))

		skyWeed_1_2 = Cal.reduceElement(skyWeed_1_0, 0)
		earthWeed_1_2 = Cal.reduceElement(earthWeed_1_1, 0)
		# print 's1-1', skyWeed_1_2, len(skyWeed_1_2)
		# print 'e1-1', earthWeed_1_2, len(earthWeed_1_2)

		# 2.2: 和“一变”的“2”一样。
		# 2.3: 和“一变”的“3”一样。
		# 2.4: 和“一变”的“4”一样。
		# 2.5: 和“一变”的“5”一样。
		newWeed = Cal.intergrate(skyWeed_1_2, earthWeed_1_2)
		# print newWeed, len(newWeed)
		return newWeed
Beispiel #8
0
def main(request):

    drawer = parse_request(request)

    try:
        calculate = Calculate(drawer)
        output = calculate.display()
        calculate.write_to_database(output)

        return str(output)

    except AttributeError as e:
        return "Drawer information not in system. Error: {}".format(e)
Beispiel #9
0
class TestCalculate(unittest.TestCase):
	def setUp(self):
		self.calc = Calculate()

	def test_add_method_returns_correct_result(self):
		print "Hello"
		self.assertEquals(4, self.calc.add(2, 2))
		self.assertAlmostEquals(1,1)

	def test_add_method_returns_incorrect_result(self):
		self.assertEquals(5, self.calc.add(2, 3))
	
	def test_add_method_raises_typerror_if_not_inits(self):
		self.assertRaises(TypeError, self.calc.add, "Hello", "World")
 def testLatticeGen(self):
     
     calc = Calculate()
     
     #Lattice sizes
     sizes = [0,1,2,3]
     sets = {0:set([(0,0)]),
             1:set([(0,0),(0,1),(1,0),(1,1)]),
             2:set([(0,0),(0,1),(1,0),(1,1),(2,0),(0,2),(1,2),(2,1),(2,2)]),
             3:set([(0,0),(0,1),(1,0),(1,1),(2,0),(0,2),(2,1),(1,2),(2,2),(3,0),(0,3),(3,1),(1,3),(3,2),(2,3),(3,3)])
             }
     
     for size in sizes:
         lattice = calc.square_lattice(size)
         eq_(sets[size],set(tuple(tuple(x) for x in lattice)))
Beispiel #11
0
    def run(self):
        if Market_Calendar().is_market_open(self.__today_str, self.__now_str):
            try:
                libor_rates_curve = FRED_API().get_libor_rates_curve()
            except:
                print ('\n'*2), 'The request to the FRED api has failed. Now exiting...', ('\n'*2)
            else:
                td_session = TD_API(self.__usr_pars['TD_ID'], self.__usr_pars['TD_VERSION'])
                td_session.login(self.__usr_pars['TD_NAME'], self.__usr_pars['TD_PASSWORD'])

                if td_session.logged_in:
                    # pull raw data
                    all_data = td_session.pull_data(self.__symbols, self.__expiry_months)
                    td_session.logout()
                    # parse raw data
                    parsed_data = td_session.parse_data(all_data)
                    # perform calcs on parsed data
                    final_data = Calculate(self.__today_str, parsed_data, libor_rates_curve).run()
                    # store final data
                    mongo = Mongo(self.__today_str, final_data, \
                                     {'user':self.__usr_pars['TD_NAME'], 'pwd':self.__usr_pars['DB_PASSWORD']})
                    mongo.write()
                    mongo.disconnect()
                    print ('\n'*2), 'SUCCESS.', ('\n'*2)
        else:
            print ('\n'*2), 'The markets are currently closed.', ('\n'*2)
Beispiel #12
0
class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
	def on_signin(self, name, cords):
		name = name + str(random.randint(0,10000))
		cords = str(cords).split(",")
		self.c = Calculate((float(cords[0]),float(cords[1])))
		self.environ.setdefault('person', []).append(name)
		self.socket.session['person'] = name
		self.broadcast_event('person', self.environ['person'])
		self.on_update_rooms()
		self.join('main_room')

	def on_update_rooms(self):
		a = self.c.genList()
		out = json.dumps(a)
		self.broadcast_event('rooms', out)
	
	def on_user_message(self, msg):
		self.emit_to_room('main_room', 'msg_to_room', self.socket.session['person'], msg)

	def on_preoccupy(self, msg):
		self.broadcast_event('preoccupy', '%s'% (msg))

	def refresh(self):
		pass

	def recv_message(self, message):
		print "PING!!!", message
Beispiel #13
0
 def get_test_data(self, data):
     '''
         Return random 0.2 of data
     '''
     size = 0.2 * len(data)
     chosen_idx = Calculate.get_list_rand_numbers(len(data), size)
     return data.iloc[chosen_idx]
Beispiel #14
0
def main():
    # 传输层
    transport = TSocket.TSocket('127.0.0.1', 8888)
    transport = TTransport.TBufferedTransport(transport)

    # 消息协议
    protocal = TCompactProtocol.TCompactProtocol(transport)

    client = Calculate.Client(protocal)

    # 进行具体调用
    # 打开
    transport.open()
    client.ping()
    print('调用了ping')
    result = client.divide(100, 50)
    print('100/50= {}'.format(result))
    try:
        result = client.divide(100, 0)
    except InvalidOperation as e:
        print(e.why, '-', e.whatOp)

    work = Work(num1=100, num2=20, op=Opertation.SUBTRACT)
    result = client.calculate(work)
    print('100-20={}'.format(result))

    # 关闭
    transport.close()
Beispiel #15
0
def startTheGame(score):
    difficulty = int(input('Enter the difficulty of the game (1-3): '))

    calculate = Calculate(difficulty)

    print('Show the result of the operation below')
    calculate.operation()

    result = int(input('Enter the result: '))

    if calculate.verifyResult(result):
        score += 1

    if input('Continue the game (yes or no): ') == 'yes':
        startTheGame(score)
    else:
        print(f'You finished the game with {score} scores')
class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        self.assertEqual(4, self.calc.add(2, 2))

    def test_add_method_raises_typeerror_if_not_ints(self):
        self.assertRaises(TypeError, self.calc.add, "Hello", "World")
Beispiel #17
0
	def on_signin(self, name, cords):
		name = name + str(random.randint(0,10000))
		cords = str(cords).split(",")
		self.c = Calculate((float(cords[0]),float(cords[1])))
		self.environ.setdefault('person', []).append(name)
		self.socket.session['person'] = name
		self.broadcast_event('person', self.environ['person'])
		self.on_update_rooms()
		self.join('main_room')
Beispiel #18
0
class TestCalculate(unittest.TestCase):
	def setUp(self):
		self.calc = Calculate()
		
	def test_add_ret_correctly(self):
		self.assertEqual(4, self.calc.add(2,2),"No add correctly, FAIL")
		
	def test_add_strings_raise_error(self):
		self.assertRaises(TypeError, self.calc.add, 'hello', 'world') 
		
	def test_add_ret_float_correctly(self):
		self.assertEqual(6.81, self.calc.add(4.51,2.3),"No add floats correctly, FAIL")
		
	def test_sub_ret_correctly(self):
		self.assertEqual(3, self.calc.sub(9,6),"No subtract correctly, FAIL")
		
	def test_mult_ret_correctly(self):
		self.assertEqual(6, self.calc.mult(2,3),"No multiply correctly, FAIL")
	
	def test_div_ret_correctly(self):
		self.assertEqual(3, self.calc.div(9,3),"No divide correctly, FAIL")
    def testPolygonScramble(self):
        # Here, rearrange polygon randomly and repeatedly get results. See if come out different.

        # Presets.
        precision = 20
        maple_link = maple.MapleLink(
            "/opt/maple13/bin/maple -tu"
        )  #TODO: hopefully remove this maple dependency...too hardwirey.
        L = 3
        calc = Calculate()

        polygon = calc.square_lattice(L)

        X, P = calc.correlations(polygon, maple_link, precision)

        # Get eigenvals
        with sympy.mpmath.extraprec(500):
            XP = X * P
        XPnum = sympy.matrix2numpy(XP)
        sqrt_eigs = sp.sqrt(linalg.eigvals(XPnum))
        sqrt_eigs_orig = sqrt_eigs.real

        # Scramble polygon.
        sp.random.shuffle(polygon)

        # Perform the integration again.
        X, P = calc.correlations(polygon, maple_link, precision)

        # Get eigenvals
        with sympy.mpmath.extraprec(500):
            XP = X * P
        XPnum = sympy.matrix2numpy(XP)
        sqrt_eigs = sp.sqrt(linalg.eigvals(XPnum))
        sqrt_eigs_scrambled = sqrt_eigs.real

        # Compare.
        a = set(tuple([round(float(x), 10) for x in sqrt_eigs_orig]))
        b = set(tuple([round(float(x), 10) for x in sqrt_eigs_scrambled]))
        eq_(a, b)
    def setUpClass(cls):
        cls.calc = Calculate()
        if cls.X is None and cls.P is None:
            # Startup Maple. #TODO: Replace with sympy when they fix bug (see src.main). This is ugly since relying on a hardcoded dir.
            cls.maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu")
            cls.precision = 25

            lattice = cls.calc.square_lattice(5)
            cls.X, cls.P = cls.calc.correlations(lattice, cls.maple_link,
                                                 cls.precision)
        else:
            # TODO: rremove this if this doesn't show up
            print "Bug: This function has been called twice"
Beispiel #21
0
class TestCalculate(unittest.TestCase):
    """unittest class"""
    def setUp(self):
        """set-up method - create a 'Calculate' object"""
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        """add method test - assertEqual"""
        self.assertEqual(4, self.calc.add(2, 2))

    def test_add_method_raises_typeerror_if_not_ints(self):
        """test for correct 'Raise' for type error"""
        self.assertRaises(TypeError, self.calc.add, 'Hello', 'World')
    def testDiag2Chain(self):
        # Perform the diagonalization for a 2-site chain. Compare
        # an exact diagonalization against scipy.

        # First calculate X,P
        calc = Calculate()
        polygon = sp.array([[0, 0], [2, 0]])
        maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu")
        precision = 25

        X, P = calc.correlations(polygon, maple_link, precision)

        entropy = calc.entropy(X, P, 1, precision, False)

        # Manual diag.
        # [ a, b,
        #   c, d]
        XP = X * P
        a = XP[0, 0]
        b = XP[0, 1]
        c = XP[1, 0]
        d = XP[1, 1]

        eig_plus = ((a + d) + sympy.mpmath.sqrt((a + d)**2 - 4 *
                                                (a * d - b * c))) / 2
        eig_minus = ((a + d) - sympy.mpmath.sqrt((a + d)**2 - 4 *
                                                 (a * d - b * c))) / 2

        sqrt_eigs = [sympy.mpmath.sqrt(eig_plus), sympy.mpmath.sqrt(eig_minus)]

        S = 0
        for vk in sqrt_eigs:
            S += ((vk + 0.5) * sympy.mpmath.log(vk + 0.5) -
                  (vk - 0.5) * sympy.mpmath.log(vk - 0.5))

        # Scipy operates in double, so we check equality up to a tolerance
        bound = 10**(-13)
        eq_(True, abs(S - entropy) < bound)
Beispiel #23
0
    def prune(self, dtree, dtree_root, data):
        '''
            Post-prune dtree recursively and return the new tree
        '''

        is_next_leaf = len(dtree.children) != 0
        for child in dtree.children:
            if child.children:
                is_next_leaf = False
                break

        if is_next_leaf:
            # Prune this node
            ntree = copy.deepcopy(dtree)  # Backup a copy of current node
            dtree.children = list()
            dtree.value.current_node = None
            dtree.value.result = Calculate.most_value(dtree.value.values)
            dtree.value.is_leaf = True

            # Check accuracy if this node being pruned
            data_test = self.get_test_data(data)
            predicted_result = self.predict(dtree_root,
                                            data_test[self.features])

            is_same_accuracy = self.is_same_accuracy(
                list(data_test[self.target]), predicted_result)
            if is_same_accuracy:
                # if accuracy remains the same, return the new node
                return dtree
            else:
                # otherwise return the same node
                return ntree
        else:
            for i in range(len(dtree.children)):
                # Recursively check every children that is node
                dtree.children[i] = self.prune(dtree.children[i], dtree_root,
                                               data)

            # Again, check if the current pruned tree satisfied the condition to be pruned
            is_next_leaf = len(dtree.children) != 0
            for child in dtree.children:
                if child.children:
                    is_next_leaf = False
                    break

            if is_next_leaf:
                dtree = self.prune(dtree, dtree_root, data)

            # Return the new tree
            return dtree
Beispiel #24
0
 def run(self):
     poll_obj = poll()
     calculate_obj = Calculate()
     for i in range(0, self.count):
         stopwatch = Stopwatch()
         comm = "openstack server list"
         stopwatch.start()
         os.system(comm)
         TIME_LIST.append(stopwatch.time_elapsed)
         stopwatch.stop()
     min = calculate_obj.getMin(TIME_LIST)
     max = calculate_obj.getMax(TIME_LIST)
     avg = calculate_obj.getAverage(TIME_LIST)
     print "Min: " + str(min)
     print "Max: " + str(max)
     print "Average: " + str(avg)
     dict_return['server'] = SERVER_LIST
     dict_return['min'] = min
     dict_return['max'] = max
     dict_return['avg'] = avg
     dict_return['name'] = "nova.list"
     disp_list.append(dict_return)
     return disp_list
    def testLatticeGen(self):

        calc = Calculate()

        #Lattice sizes
        sizes = [0, 1, 2, 3]
        sets = {
            0:
            set([(0, 0)]),
            1:
            set([(0, 0), (0, 1), (1, 0), (1, 1)]),
            2:
            set([(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2), (1, 2),
                 (2, 1), (2, 2)]),
            3:
            set([(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (0, 2), (2, 1),
                 (1, 2), (2, 2), (3, 0), (0, 3), (3, 1), (1, 3), (3, 2),
                 (2, 3), (3, 3)])
        }

        for size in sizes:
            lattice = calc.square_lattice(size)
            eq_(sets[size], set(tuple(tuple(x) for x in lattice)))
Beispiel #26
0
class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_ret_correctly(self):
        self.assertEqual(4, self.calc.add(2, 2), "No add correctly, FAIL")

    def test_add_strings_raise_error(self):
        self.assertRaises(TypeError, self.calc.add, 'hello', 'world')

    def test_add_ret_float_correctly(self):
        self.assertEqual(6.81, self.calc.add(4.51, 2.3),
                         "No add floats correctly, FAIL")

    def test_sub_ret_correctly(self):
        self.assertEqual(3, self.calc.sub(9, 6), "No subtract correctly, FAIL")

    def test_mult_ret_correctly(self):
        self.assertEqual(6, self.calc.mult(2, 3),
                         "No multiply correctly, FAIL")

    def test_div_ret_correctly(self):
        self.assertEqual(3, self.calc.div(9, 3), "No divide correctly, FAIL")
    def testPolygonScramble(self):
        # Here, rearrange polygon randomly and repeatedly get results. See if come out different.

        # Presets.
        precision = 20
        maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu") #TODO: hopefully remove this maple dependency...too hardwirey.
        L = 3
        calc = Calculate()
        
        polygon = calc.square_lattice(L)
        
        X,P = calc.correlations(polygon, maple_link, precision)

        # Get eigenvals
        with sympy.mpmath.extraprec(500):
            XP = X*P
        XPnum = sympy.matrix2numpy(XP)
        sqrt_eigs = sp.sqrt(linalg.eigvals(XPnum))
        sqrt_eigs_orig = sqrt_eigs.real
        
        # Scramble polygon.
        sp.random.shuffle(polygon)
        
        # Perform the integration again.        
        X,P = calc.correlations(polygon, maple_link, precision)

        # Get eigenvals
        with sympy.mpmath.extraprec(500):
            XP = X*P
        XPnum = sympy.matrix2numpy(XP)
        sqrt_eigs = sp.sqrt(linalg.eigvals(XPnum))
        sqrt_eigs_scrambled = sqrt_eigs.real
        
        # Compare.
        a = set(tuple([round(float(x),10) for x in sqrt_eigs_orig]))
        b = set(tuple([round(float(x),10) for x in sqrt_eigs_scrambled]))
        eq_(a,b)
Beispiel #28
0
 def run(self):
    poll_obj = poll()
    calculate_obj = Calculate()
    for i in range(0,self.count):
         stopwatch = Stopwatch()
         random=getrandom(5)
         self.name="server-"+random.getSuffix()
         comm = "openstack server create "+self.name+" --image "+self.image+" --flavor "+self.flavor+" --nic net-id="+self.network
         subprocess.check_output(comm,shell=True)
         SERVER_LIST.append(self.name)
         stopwatch.start()
         while True:
               create_status = poll_obj.create_server(self.name)
               if create_status == 1:
                   TIME_LIST.append(stopwatch.time_elapsed)
                   stopwatch.stop()
                   break
               elif create_status == 0:
                   pass
               elif create_status == -1:
                   print "Creation Failed"
                   break
         print "Created Server... "+self.name
    min = calculate_obj.getMin(TIME_LIST)
    max = calculate_obj.getMax(TIME_LIST)
    avg = calculate_obj.getAverage(TIME_LIST)  
    #print_output(min,max,avg,"nova.create",self.count)     
    #print "Min: "+str(min)
    #print "Max: "+str(max)
    #print "Average: "+str(avg)
    dict_return['server']=SERVER_LIST
    dict_return['min']=min
    dict_return['max']=max
    dict_return['avg']=avg
    dict_return['name'] = "nova.create"
    disp_list.append(dict_return)
    return disp_list
Beispiel #29
0
	def hexgram(self):
		array = []
		Cal = Calculate()
		TC = TrebleChange()
		Weed1 = Cal.weed(49)		
		array.append(TC.change(Weed1))
		Weed2 = Cal.weed(49)		
		array.append(TC.change(Weed2))
		Weed3 = Cal.weed(49)		
		array.append(TC.change(Weed3))
		Weed4 = Cal.weed(49)		
		array.append(TC.change(Weed4))
		Weed5 = Cal.weed(49)		
		array.append(TC.change(Weed5))
		Weed6 = Cal.weed(49)		
		array.append(TC.change(Weed6))
		return array
Beispiel #30
0
    def find_threshold(self, data_attr, data_target):
        '''
            Find threshold of data_attr with respect to data_target
        '''
        attr_name = data_attr.columns[0]
        target_name = data_target.columns[0]
        data = pd.concat([data_attr, data_target], axis=1)
        data = data.sort_values(attr_name).reset_index(drop=True)

        # Retrieve all indexes with different value of target attribute
        diff_index = list()
        for i in range(len(data) - 1):
            if data[target_name].iloc[i] != data[target_name].iloc[i + 1]:
                diff_index.append(i)

        best_point = 0
        best_idx = -1
        for i in diff_index:
            if (self.gain_ratio):
                point = Calculate.gain_ratio(data[attr_name],
                                             data[target_name],
                                             is_continue=True,
                                             split_index=i)
            else:
                point = Calculate.info_gain(data[attr_name],
                                            data[target_name],
                                            is_continue=True,
                                            split_index=i)
            if point > best_point:
                best_point = point
                best_idx = i

        best_splitter = (data[attr_name].iloc[best_idx] +
                         data[attr_name].iloc[best_idx + 1]) / 2

        return [best_splitter, best_point]
Beispiel #31
0
class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
	def on_signin(self, name, cords):
		name = name + str(random.randint(0,10000))
		cords = str(cords).split(",")
		self.c = Calculate((float(cords[0]),float(cords[1])))
		self.environ.setdefault('person', []).append(name)
		self.socket.session['person'] = name
		self.broadcast_event('person', self.environ['person'])
		self.broadcast_event('new_user')
		self.on_update_rooms()
		self.join('main_room')

	def on_push(self, cords):
		self.broadcast_event('pull', cords )

	def on_calculate(self, cords):
		results =[]
		for c in cords:
			if c == None:
				continue
			else:
				cs = str(c).split(",")
				cord = (cs[0], cs[1])
				results.append(cord)
		print results
		b = Best()
		best = b.genBest(results)
		self.broadcast_event('best_room', best )

	def on_update_rooms(self):
		a = self.c.genList()
		out = json.dumps(a)
		self.broadcast_event('rooms', out)
	
	def on_user_message(self, msg):
		self.emit_to_room('main_room', 'msg_to_room', self.socket.session['person'], msg)

	def on_preoccupy(self, msg):
		self.broadcast_event('preoccupy', '%s'% (msg))

	def on_clear(self):
		self.broadcast_event('clear')

	def refresh(self):
		pass

	def recv_message(self, message):
		print "PING!!!", message
Beispiel #32
0
 def predict_score(self, sample, m, n):
     """
     Calculate the predicted score for each sample.
     Args:
         sample: A sample in the dataset.
         m: The parameter for component position.
         n: The parameter for component distance.
     Returns:
         score: The predicted score.
     """
     with MongoConnection(self.host, self.port) as mongo:
         collection = mongo.connection["kdetector"]["dataset"]
         src = collection.find_one({"test_id": sample[0]})
         tgt = collection.find_one({"test_id": sample[1]})
         order_pair = [src["cpnt_order"], tgt["cpnt_order"]]
         block_pair = [src["func_block"], tgt["func_block"]]
     return Calculate(order_pair, block_pair).calculate_sim(m, n)
class TestCalculate(unittest.TestCase):
# setUp method - which is excuted before each test, so that you need define your
# instance only once and have it created before each test.   
    def setUp(self):
      self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
# assertEqual method checks if the first argument is equal to the second.
     # self.assertEqual("HelloWorld", self.calc.add("Hello","World"))
      print 'Hello'
      self.assertEqual(4, self.calc.add("Hello", "World"))
      self.assertAlmostEquals(1,1)

    def test_add_method_raises_typeerror_if_not_ints(self):
# unittest method assertRaises takes 3 arguments. 1 - the type of exception you
# expect to be raised. 2 - the method under test. 3 - the value passed in the
#argument to the method under test. 
      self.assertRaises(TypeError, self.calc.add, "Hello","World")
Beispiel #34
0
class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        self.assertEqual(4, self.calc.add(2, 2))

    def test_add_method_raises_typeerror_if_not_ints(self):
        self.assertRaises(TypeError, self.calc.add, "Hello", "World")

    def test_assert_equal(self):
        self.assertEqual(1, 1)

    def test_assert_almost_equal_delta_0_5(self):
        self.assertAlmostEqual(1, 1.2, delta=0.5)

    def test_assert_almost_equal_places(self):
        self.assertAlmostEqual(1, 1.00001, places=4)

    def test_assert_true(self):
        self.assertTrue(1)
        self.assetTrue("Hello, World")
Beispiel #35
0
 def detect_sim(self):
     """
     Detect crash dump similarity and output the comparison result.
     """
     message = []
     order_pair, block_pair = [], []
     for param in self.params:
         # parameter is test_id
         if re.match(r"^\d{9,}$", param):
             dump = ETL().extract_cdb(param)
             processed = Process(dump).internal_process()
         # parameter is dump_path
         else:
             with open(param, "r", encoding="utf-8") as fp:
                 dump = fp.read()
             processed = Process(dump).pre_process()
         cpnt_order, func_block = Knowledge(processed).add_knowledge()
         message.extend([cpnt_order, func_block])
         order_pair.append(cpnt_order)
         block_pair.append(func_block)
     # output dump comparison
     Log().dump_print(message)
     Calculate(order_pair, block_pair).calculate_sim(debug=True)
Beispiel #36
0
    def __init__(self):
        '''Shows a table in console with the output of relatives sizes ranges

        '''
        calculate = Calculate()
        values = calculate.get_relative_size_ranges()
        table = Texttable()
        table.set_cols_align(["l", "l", "l","l", "l", "l"])
        table.set_cols_valign(["m", "m", "m","m", "m", "m"])
        table.set_cols_dtype(['t', 'f', 'f', 'f', 'f','f'])
        table.set_precision(4)
        head = ['',
            color(bcolors.GREEN,"VS"),
            color(bcolors.GREEN,"S"),
            color(bcolors.GREEN,"M"),
            color(bcolors.GREEN,"L"),
            color(bcolors.GREEN,"VL")
        ]
        rows = []
        rows.append(head)
        [rows.append(element) for element in values]
        table.add_rows(rows)
        print(table.draw() + "\n")
class TestCalculate(unittest.TestCase):

    def setUp(self):
         self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
         self.assertEqual(4, self.calc.add(2,2))

    def test_add_method_raises_typeerror_if_not_ints(self):
         self.assertRaises(TypeError, self.calc.add, "Hello", "World")

    def test_assert_equal(self):
        self.assertEqual(1, 1)

    def test_assert_almost_equal_delta_0_5(self):
        self.assertAlmostEqual(1, 1.2, delta=0.5)

    def test_assert_almost_equal_places(self):
        self.assertAlmostEqual(1, 1.00001, places=4)


    def test_assert_true(self):
        self.assertTrue(1)
        self.assetTrue("Hello, World")        
Beispiel #38
0
	def setUp(self):
		self.calc = Calculate()
Beispiel #39
0
class TestCalculate(unittest.TestCase):
	def setUp(self):
		self.calc = Calculate()

	def test_add_method_returns_correct_result(self):
		self.assertEqual(4, self.calc.add(2,2))
class CorrelationsTest(unittest.TestCase):
    #TODO: Currently limited to a small case.  In future, when program optimized, expand this!
    
    maple_link = None
    # For L = 3...
    X = None
    P = None
    XP = None
    precision = None
    
    @classmethod
    def setUpClass(cls):
        cls.calc = Calculate()
        if cls.X is None and cls.P is None:
            # Startup Maple. #TODO: Replace with sympy when they fix bug (see src.main). This is ugly since relying on a hardcoded dir.
            cls.maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu")
            cls.precision = 25
            
            lattice = cls.calc.square_lattice(5)
            cls.X,cls.P = cls.calc.correlations(lattice,cls.maple_link,cls.precision)
        else:
            # TODO: rremove this if this doesn't show up
            print "Bug: This function has been called twice"
    
    def setUp(self):
        self.calc = Calculate()
        
    def testSymmetric(self):
        eq_(True,self.X.is_symmetric())
        eq_(True,self.P.is_symmetric())
        
    def testReal(self):
        eq_(True, self.X == self.X.conjugate())
        eq_(True, self.P == self.P.conjugate())
        
    def testPrecision(self):
        """
        See if the precision increases with the variable.
        """
        polygon = self.calc.square_lattice(1)
        precisions = [20,30,40,50]
         
        # Find X,P for each precision
        corrs_collection = []
        for precision in precisions:
            X,P = self.calc.correlations(polygon, self.maple_link, precision)
            corrs_collection.append([X,P])
             
        for i in range(0, len(precisions)-1):
            # get X and P pairs for precisions[i] and precisions[i+1]
            pairX = sp.array([corrs_collection[i][0],corrs_collection[i+1][0]])
            pairP = sp.array([corrs_collection[i][1],corrs_collection[i+1][1]])
             
            # Check if increasing the precision variable actually does this.
            bound = 10**(-precisions[i])
             
            eq_(True, ( abs(pairX[0] - pairX[1]) < bound ).all())
            eq_(True, ( abs(pairP[0] - pairP[1]) < bound ).all())
        
    def testPrecomputed(self):
        """
        Test the precomputed correlations feature.
        """
        precision = 25

        lattice3 = self.calc.square_lattice(3)
        lattice4 = self.calc.square_lattice(4)
        
        X3,P3 = self.calc.correlations(lattice3, self.maple_link, precision, verbose=True)
        X4,P4 = self.calc.correlations(lattice4, self.maple_link, precision, verbose=True)
        
        # With precomputed.
        precomputed_correlations = {}
        X3_quick, P3_quick, precomputed_correlations = self.calc.correlations(lattice3, self.maple_link, precision, precomputed_correlations, verbose=True)
        X4_quick, P4_quick, precomputed_correlations = self.calc.correlations(lattice4, self.maple_link, precision, precomputed_correlations, verbose=True)

        eq_(True, X3 == X3_quick)
        eq_(True, P3 == P3_quick)
        eq_(True, X4 == X4_quick)
        eq_(True, P4 == P4_quick)
        
    def testMatrixSymmetries(self):
        """
        X and P should have the same pattern as the distance matrix defined by
        the lattice.
        """
        precision = 20
        polygon = self.calc.square_lattice(5)
        X,P = self.calc.correlations(polygon, self.maple_link, precision)
        
        # Round X and P down so we can see if elements are distinct or not.
        X = sympy.matrix2numpy(X)
        P = sympy.matrix2numpy(P)
        X = X.astype('float')
        P = P.astype('float')
        
        # Get the pattern of the distance matrix.
        D = spatial.distance.cdist(polygon,polygon)
        
        # The pattern of the distance matrix
        D_pat = sp.zeros(D.shape)
        getSignatureMatrix(D_pat,sp.nditer(D),D.shape)
        
        # Get the pattern of X and P.
        X_pat = sp.zeros(X.shape)
        P_pat = sp.zeros(P.shape)
        getSignatureMatrix(X_pat,sp.nditer(X),X.shape)
        getSignatureMatrix(P_pat,sp.nditer(P),P.shape)
        
        # Check if patterns match.
        eq_(False,(D_pat - X_pat).all())
        eq_(False,(D_pat - P_pat).all())
Beispiel #41
0
            exit()
    else:
        date_str = get_days_ago_day_str(1)
    
    input_dir,output_dir,tmp_dir,log_dir = Configuration("conf/p9.cfg").getConfigDir()
    input_dir_day = formatInputDir(input_dir,date_str)

    clearSortTmpDir(tmp_dir,date_str)  
    
    #---merge and sort -------
    mergeLog(log_dir,tmp_dir,date_str)
    sortLog(log_dir,tmp_dir,date_str)
 
    #----计算性能指标------
    pub_count,mc_count = calculate_pub_mc(tmp_dir,date_str)
    calc = Calculate(tmp_dir+'/'+date_str+'/',pub_count,mc_count)
    writeStdOutLog(log_dir,time.ctime() + '  start calculate tt/tr .... ',date_str)
    pub_tt_data,pub_tt_pdata= calc.calculate_pub_tt()
    pub_tr_data,pub_tr_pdata= calc.calculate_pub_tr()
    mc_tt_data,mc_tt_pdata= calc.calculate_mc_tt()
    mc_tr_data,mc_tr_pdata= calc.calculate_mc_tr()
    writeStdOutLog(log_dir,time.ctime() + '  finish calculate tt/tr .... ',date_str)
    
    #----send to graphite----
    writeStdOutLog(log_dir,time.ctime() + '  send p-series data to graphite .... ',date_str)
    sendPubAndMcRequest(pub_count,mc_count)
    sendDataToGraphite(pub_tt_pdata,pub_tr_pdata,mc_tt_pdata,mc_tr_pdata)
    writeStdOutLog(log_dir,time.ctime() + '  send p-series data to graphite success.... ',date_str)
    
    #----save-----
    saveDataAsCsv(date_str,pub_count,mc_count,output_dir,pub_tt_data,pub_tr_data,mc_tt_data,mc_tr_data)
class Correlator_ijTest(unittest.TestCase):
    # See if we match values from maple here (use varying precisions?)
    maple_link = None
    calc = None
    
    @classmethod
    def setUpClass(cls):
        # Startup Maple. #TODO: Replace with sympy when they fix bug (see src.main). This is ugly since relying on a hardcoded dir.
        cls.maple_link = maple.MapleLink("/opt/maple13/bin/maple -tu")
        
    def setUp(self):
        self.calc = Calculate()
        
    def testPrecision(self):
        """
        See if precision increases with the variable "precision".
        
        Note: There is some redundancy in that this test acts in much the same 
        way as testPrecision in the CorrelationsTest TestCase, but acts on a 
        set of only a few [i,j].  This could be seen as a quicker alternative.
        """
        # TODO: Is this actually quicker?
        ijs = [[1,2],[3,5],[2,8]]

        precisions = [20,30,40,50]
        
        for [i,j] in ijs:
            # Find X,P for each precision
            phipi_collection = []
            for precision in precisions:
                phi,pi = self.calc.correlators_ij(i, j, self.maple_link, precision)
                phipi_collection.append([phi,pi])
                
            for i in range(0, len(precisions)-1):
                # get X and P pairs for precisions[i] and precisions[i+1]
                pairPhi = [phipi_collection[i][0],phipi_collection[i+1][0]]
                pairPi = [phipi_collection[i][1],phipi_collection[i+1][1]]
                
                # Check if increasing the precision variable actually does this.
                bound = 10**(-precisions[i])
                
                eq_(True, abs(pairPhi[0] - pairPhi[1]) < bound )
                eq_(True, abs(pairPi[0] - pairPi[1]) < bound ) 
        
            
    def testSymmetry(self):
        # Calculate for i,j and j,i. See if get same results.
        
        # Some random ijs.
        ijs = [[1,2],[3,5],[2,8]]
        
        precision = 20
        
        for ij in ijs:
            i = ij[0]
            j = ij[1]
            phi_corr, pi_corr = self.calc.correlators_ij(i, j, self.maple_link, precision)
            phi_corr2, pi_corr2 = self.calc.correlators_ij(j, i, self.maple_link, precision)
            eq_(phi_corr,phi_corr2)
            eq_(pi_corr,pi_corr2)
            
    def testValues(self):
        # Test values against maple values.
        maple_vals = [[0.03490480875099482936704802,], \
                      [0.01359884308448908943342273,], \
                      [0.009657881846921001497223915,]]
          
        # Some random ijs.
        ijs = [[1,2],[3,5],[2,8]]
          
        precision = 25
          
        for count, [i,j] in enumerate(ijs):
            phi_corr, pi_corr = self.calc.correlators_ij(i, j, self.maple_link, precision)
            eq_(phi_corr,maple_vals[count][0])
            eq_(pi_corr,maple_vals[count][1])
Beispiel #43
0
from calculate import Calculate
obj = Calculate()

print(obj.add(5, 5))
Beispiel #44
0
"""Example file to call methods."""

from calculate import Calculate

pointsOfArea = {
    "geojson":
    "{\"type\": \"Polygon\", \"coordinates\": [[[19.936901, 50.062682], [19.935745, 50.061403], [19.937697, 50.060558], [19.938877, 50.062003]]]}"
}

verifiedPoint = (19.937032, 50.061587)

# calculate area:
area = Calculate.area(pointsOfArea)
print("Area: {}".format(area))

# calculate circumference:
circumference = Calculate.circumference(pointsOfArea)
print("Circumference: {}".format(circumference))

# calculate distance:
distance = Calculate.distance(pointsOfArea)
print("Distance: {}".format(distance))

# checking if the point is in a given area:
contains = Calculate.contains(pointsOfArea, verifiedPoint)
print("Contains: {}".format(contains))
 def setUp(self):
     self.calc = Calculate()
Beispiel #46
0
# Flask routes
app = Flask(__name__)
@app.route('/')
def index():
	return send_file('public/index.html')

@app.route('/<path:path>')
def re(path):
	return redirect("/")

@app.route("/socket.io/<path:path>")
def run_socketio(path):
	socketio_manage(request.environ, {'': ChatNamespace})
	return Response()

if __name__ == '__main__':
	print 'Listening on http://localhost:8080'
	c = Calculate((42.37223265, -71.116110))
	c.genList()
	port = int(os.environ.get('PORT', 3000))
	app.debug = True
	from werkzeug.wsgi import SharedDataMiddleware

	app = SharedDataMiddleware(app, {
		'/': os.path.join(os.path.dirname(__file__), 'public')
		})
	from socketio.server import SocketIOServer
	SocketIOServer(('', port), app, resource="socket.io",
            transports=['xhr-polling','websocket'], policy_server=False).serve_forever()
	
Beispiel #47
0
 def setUpClass(cls):
     cls.calc = Calculate()