Example #1
0
 def my_test(self):
     self.assertEqual(["L", "L", "R"], balance(5))
     self.assertEqual(["L", "L", "L", "R"], balance(14))
     self.assertEqual(["R", "R", "L", "R"], balance(22))
    
     
     
Example #2
0
 def run(self):
     self.client = fcoin_client()
     self.client.start()
     self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
     self.symbols_action()
     # self.get_balance_action(symbols)
     balance.balance()
     while True:
         self.trade()
 def run(self):
     self.symbols_action()
     # self.get_balance_action(symbols)
     balance.balance()
     self.client = fcoin_client(self.on_close)
     self.client.start()
     self.client.subscribe_tickers(symbol_pairs, self.ticker_handler)
     while True:
         tickers = ticker_queue.get()
         self.trade(tickers)
         ticker_queue.queue.clear()
Example #4
0
 def run(self):
     self.client = fcoin_client(self.on_close)
     # self.client = fcoin_client()
     self.client.start()
     self.client.subscribe_tickers([symbol], self.ticker_handler)
     self.symbols_action()
     # self.get_balance_action(symbols)
     if not is_mutable_amount:
         logging.info("交易标的:{} 每单交易量:{} {}".format(symbol, amount,
                                                   symbols[0]))
     balance.balance()
     while True:
         self.trade()
Example #5
0
 def get_blance(self):
     dic_blance = defaultdict(lambda: None)
     success, data = self.fcoin.get_balance()
     if success:
         for item in data['data']:
             dic_blance[item['currency']] = balance(float(item['available']), float(item['frozen']),float(item['balance']))
     return dic_blance
Example #6
0
 def get():
     node = balance()
     location = "http://127.0.0.1:500" + str(node) + request.script_root + request.path
     resp = requests.get(location)
     excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
     headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
     response = Response(resp.content, resp.status_code, headers)
     return response
Example #7
0
def show_menu():
    selected_option = int(input('Selecione uma opção:\n\n1 - Novo Cliente\n2 - Apagar Cliente\n3 - Debitar\n4 - Depositar\n5 - Saldo\n6 - Extrato\n0 - Sair\n'))
    if selected_option == 0:
        print('Sessão encerrada!\n')
        return False
    if selected_option == 1:
        new_client()
    if selected_option == 2:
        delete_client()
    if selected_option == 3:
        debit()
    if selected_option == 4:
        deposit()
    if selected_option == 5:
        balance()
    if selected_option == 6:
        extract()
Example #8
0
 def __init__(self, index, sam=None, autobalance=False, unbalanced=False):
     check_table(sam, len(index))
     if autobalance:
         if not(check_balance(sam)):
             sam = balance(sam)
     else if not(unbalanced):
         assert check_balance(sam), 'sam not balanced \nif you want to assign an unbalance table, use either the autobalance parmeter or unbalanced'
     super(Sam, self).__init__(index, index, sam)
Example #9
0
 def setUp(self):
     setup_plugin()
     setup_cvars({
         "qlx_balanceUseLocal": "0",
     })
     setup_game_in_progress()
     connected_players()
     self.plugin = balance()
Example #10
0
 def syn_blance(self):
     dic_blance = defaultdict(lambda: None)
     data = self.fcoin.get_balance()
     if data:
         for item in data['data']:
             dic_blance[item['currency']] = balance(
                 float(item['available']), float(item['frozen']),
                 float(item['balance']))
     self.dic_blance = dic_blance
     return dic_blance
Example #11
0
    def __init__(self):
        self.lib_version = '1.1.1'
        self.api_key = None
        self.api_private = None
        self.base_url = 'https://api.quiubas.com'
        self.version = '2.1'

        self.network = network(self)

        self.balance = balance(self)
        self.sms = sms(self)
Example #12
0
 def get_balance(self):
     dic_balance = defaultdict(lambda: None)
     success, data = self.fcoin.get_balance()
     if success:
         for item in data["data"]:
             dic_balance[item["currency"]] = balance(
                 float(item["available"]),
                 float(item["frozen"]),
                 float(item["balance"]),
             )
     return dic_balance
Example #13
0
    def initAccounts(self):
        accountDatas = self.dm.dataRead()
        if len(accountDatas):
            self.refreshAccountsList('INIT', accountDatas=accountDatas)
            for data in accountDatas:
                account = data['AccountName']
                money = data['Money']
                stock = data['Stock']

                self.accounts[account] = balance(account, money)
                self.accounts[account].stockList = stock
                self.accounts[account].saveAccount()
                self.records[account] = record(account)
Example #14
0
	def __init__( self ):
		self.lib_version		= '1.0.0'
		self.api_key			= None
		self.api_private		= None
		self.base_url			= 'https://rest.quiubas.com'
		self.version			= '1.0'

		self.network = network( self )

		self.balance = balance( self )
		self.callback = callback( self )
		self.keywords = keywords( self )
		self.sms = sms( self )
Example #15
0
def pay(username, user_file, shopping_car_list):
    '''
    :param username:
    :param user_file:
    :param shopping_car_list:
    :return:返回值为结算后的帐户余额
    '''
    price = 0
    for i in shopping_car_list:
        price += product[i]

    money_ye = balance.balance(username, user_file)
    if price > money_ye:
        print_color.print_color('余额不足,结算失败,请充值后再结算!', 'red')
        return False
    else:
        money_ye = money_ye - price
    return money_ye
Example #16
0
def pay(username,user_file,shopping_car_list):
    '''
    :param username:
    :param user_file:
    :param shopping_car_list:
    :return:返回值为结算后的帐户余额
    '''
    price = 0
    for i in shopping_car_list:
        price += product[i]

    money_ye = balance.balance(username,user_file)
    if price > money_ye:
        print_color.print_color('余额不足,结算失败,请充值后再结算!','red')
        return False
    else:
        money_ye = money_ye - price
    return money_ye
Example #17
0
 def submitNewAccount(self):
     account = self.leNewAccountName.text()
     baseMoney = self.leNewAccountBaseMoney.text()
     if not account or not baseMoney:
         self.showWarningMsgBox('계좌 번호와 기초 자금 모두 입력해 주세요.')
     elif account in self.accounts.keys():
         self.showWarningMsgBox('이미 존재하는 계좌입니다.')
     elif not baseMoney.isdecimal():
         self.showWarningMsgBox('기초 자금에는 숫자만 입력해 주세요.')
     else:
         self.accounts[account] = balance(account, int(baseMoney))
         self.records[account] = record(account)
         self.records[account].recordBalanceChange(
             int(baseMoney), self.accounts[account].money)
         self.refreshAccountsList('ADD')
         self.leNewAccountName.clear()
         self.leNewAccountBaseMoney.clear()
         self.showInfoMsgBox('새 계좌가 추가되었습니다.')
Example #18
0
def show_shopping_car_list(username,user_file,shopping_car_list):
    '''
    :param username:
    :param user_file:
    :return: 返回值为商品总价格 和 帐户余额。都为正整数.返回 False,说明购物车为空
    '''
    if len(shopping_car_list) == 0:
        print_color.print_color("购物车为空,赶紧购物吧!!",'green')
        return False
    else:
        total_price = 0
        car_dic = {}
        print('*'*51)
        print('%-6s%-30s%-15s' % ('编号','商品名称','价格'))
        for i,v in enumerate(shopping_car_list):
            #print('*'*51)
            print('%-8s%-30s%-15s' % (i,v,str(product[v])))
            total_price += product[v]
            car_dic[i] = v
        print('*'*51)
        money_ye = balance.balance(username,user_file)
        return car_dic
Example #19
0
def show_shopping_car_list(username, user_file, shopping_car_list):
    '''
    :param username:
    :param user_file:
    :return: 返回值为商品总价格 和 帐户余额。都为正整数.返回 False,说明购物车为空
    '''
    if len(shopping_car_list) == 0:
        print_color.print_color("购物车为空,赶紧购物吧!!", 'green')
        return False
    else:
        total_price = 0
        car_dic = {}
        print('*' * 51)
        print('%-6s%-30s%-15s' % ('编号', '商品名称', '价格'))
        for i, v in enumerate(shopping_car_list):
            #print('*'*51)
            print('%-8s%-30s%-15s' % (i, v, str(product[v])))
            total_price += product[v]
            car_dic[i] = v
        print('*' * 51)
        money_ye = balance.balance(username, user_file)
        return car_dic
Example #20
0
def shopping(login_user, user_file):
    shopping_car_list = []
    flag1 = True
    flag2 = True
    while flag1:
        product_list_dic = show_product_list()
        print_color.print_color('b  返回主菜单', 'yellow')
        choice_product = input("请输入您想购买的商品编号:")
        if choice_product == 'b':
            break
        elif choice_product.isdigit():
            if int(choice_product) in product_list_dic:
                add_car(shopping_car_list,
                        product_list_dic[int(choice_product)])
                while flag2:
                    print_color.print_color('当前购物车商品', 'green')
                    car_dic = show_shopping_car_list(
                        login_user, user_file, shopping_car_list)  #购物车商品名称及编号
                    shopping_car_fun_menu()
                    choice_fu = input('请输入您想要的操作编号:')
                    if choice_fu == 'e':
                        while True:
                            choice_del = input('请输入您想要删除的商品编号:')
                            if int(choice_del) in car_dic:
                                shopping_car_list.remove(
                                    car_dic[int(choice_del)])
                                print_color.print_color('删除成功!', 'green')
                                break
                            else:
                                print_color.print_color(
                                    '您输入的不正确,请重新输入!', 'red')
                                continue
                    elif choice_fu == 'x':
                        break
                    elif choice_fu == 'a':
                        while True:
                            money_cz = input('请输入你想要充值的金额,只能充入正整数金额:')
                            if money_cz.isdigit():
                                money_ye = balance.balance(
                                    login_user, user_file)
                                money_ye = money_ye + int(money_cz)
                                result = icbc.icbc(login_user, user_file,
                                                   money_ye)
                                if result == True:
                                    print_color.print_color(
                                        '充值成功!!本次充值金额:%s' % money_cz, 'green')
                                    balance.balance(login_user, user_file)
                                    break
                                else:
                                    print_color('充值失败,系统将返回购物车列表!', 'red')
                                    break
                            else:
                                print_color.print_color(
                                    '你输入的金额不正确,请重新输入!', 'red')
                                continue
                    elif choice_fu == 'p':
                        money = pay(login_user, user_file, shopping_car_list)
                        if money == False:
                            continue
                        else:
                            result = icbc.icbc(login_user, user_file,
                                               str(money))
                            if result == True:
                                print_color.print_color(
                                    '结算成功,东西就不给你了,哈哈哈!', 'green')
                                balance.balance(login_user, user_file)
                                shopping_car_list = []
                                while True:
                                    print_color.print_color(
                                        'b  回到主菜单  q 退出系统', 'yellow')
                                    choice_last = input("请选择对应的操作编号:")
                                    if choice_last == 'q':
                                        print_color.print_color(
                                            '感谢访问oldboy商城!欢迎下次光临,再见!', 'green')
                                        exit()
                                    elif choice_last == 'b':
                                        flag2 = False
                                        flag1 = False
                                        break
                                    else:
                                        print_color.print_color(
                                            '您输入的不正确,请重新输入!')
                                        continue

                            else:
                                print_color.print_color('结算失败,返回购物车列表')
                                continue

                    else:
                        print_color.print_color('您的输入不正确,请重新输入!', 'red')
            else:
                print_color.print_color('您输入的不正确,请重新输入', 'red')
                continue
        else:
            print_color.print_color('您输入的不正确,请重新输入', 'red')
Example #21
0
eidx = np.in1d(atom_name, elem_arr)
atom_arr = atom_arr[:, eidx]
atom_name = atom_name[eidx]

# Sort stoich_arr according to atom_name
sidx = np.zeros(len(atom_name), int)
for i in np.arange(len(atom_name)):
    sidx[i] = np.where(elem_arr == atom_name[i])[0][0]
stoich_arr = stoich_arr[:, sidx]

# Time / speed testing for balance.py
if times:
    ini = time.time()

# Initial abundances guess
guess = bal.balance(stoich_arr, atom_arr[0], verb)

# Retrieve balance runtime
if times:
    fin = time.time()
    elapsed = fin - ini
    print("balance.py:         " + str(elapsed))

# ============== Execute TEA for each T-P ==============
# Loop over all lines in pre-atm file and execute TEA loop
processes = []
for n in np.arange(ncpu):
    start = n * chunksize
    end = np.amin(((n + 1) * chunksize, n_runs))
    proc = mp.Process(target=worker,
                      args=(pres_arr, temp_arr, atom_arr, free_energy, heat,
Example #22
0
              " overwritten in inputs/ directory.\n")
    # Copy single T-P input file to inputs directory
    shutil.copy2(infile, inputs_dir + infile.split("/")[-1])

# Times / speed check for pre-loop runtime
if times:
    tnew = time.time()
    elapsed = tnew - tstart
    print("pre-loop:           " + str(elapsed))

# Execute main TEA loop
temp, pressure, speclist = mh.read_single(infile)
free_energy, heat = mh.read_gdata(speclist, thermo_dir)
g_RT = mh.calc_gRT(free_energy, heat, temp)
stoich_arr, stoich_atom, b = mh.read_stoich(speclist, getb=True)
guess = bal.balance(stoich_arr, b, verb)

# Save info for the iteration module and remove it afterwards if neccesery
save_info = location_out, desc, speclist, temp

# Perform iterations until reaching desired precision xtol
y, x, delta, y_bar, x_bar, delta_bar = it.iterate(pressure, stoich_arr, b,
                                                  g_RT, maxiter, verb, times,
                                                  guess, xtol, save_info)

# Save or delete lagrange.py and lambdacorr.py outputs
if savefiles:
    hfolder = location_out + desc + "/headers/"
    mh.write_header(hfolder, desc, temp, pressure, speclist, stoich_atom,
                    stoich_arr, b, g_RT)
else:
Example #23
0
def shopping(login_user,user_file):
    shopping_car_list = []
    flag1 = True
    flag2 = True
    while flag1:
        product_list_dic = show_product_list()
        print_color.print_color('b  返回主菜单','yellow')
        choice_product = input("请输入您想购买的商品编号:")
        if choice_product == 'b':
            break
        elif choice_product.isdigit():
            if int(choice_product) in product_list_dic:
                add_car(shopping_car_list,product_list_dic[int(choice_product)])
                while flag2:
                    print_color.print_color('当前购物车商品','green')
                    car_dic = show_shopping_car_list(login_user,user_file,shopping_car_list) #购物车商品名称及编号
                    shopping_car_fun_menu()
                    choice_fu = input('请输入您想要的操作编号:')
                    if choice_fu == 'e':
                        while True:
                            choice_del = input('请输入您想要删除的商品编号:')
                            if int(choice_del) in car_dic:
                                shopping_car_list.remove(car_dic[int(choice_del)])
                                print_color.print_color('删除成功!','green')
                                break
                            else:
                                print_color.print_color('您输入的不正确,请重新输入!','red')
                                continue
                    elif choice_fu == 'x':
                        break
                    elif choice_fu == 'a':
                        while True:
                            money_cz = input('请输入你想要充值的金额,只能充入正整数金额:')
                            if money_cz.isdigit():
                                money_ye = balance.balance(login_user,user_file)
                                money_ye = money_ye + int(money_cz)
                                result = icbc.icbc(login_user,user_file,money_ye)
                                if result == True:
                                    print_color.print_color('充值成功!!本次充值金额:%s' % money_cz,'green')
                                    balance.balance(login_user,user_file)
                                    break
                                else:
                                    print_color('充值失败,系统将返回购物车列表!','red')
                                    break
                            else:
                                print_color.print_color('你输入的金额不正确,请重新输入!','red')
                                continue
                    elif choice_fu == 'p':
                        money = pay(login_user,user_file,shopping_car_list)
                        if money == False:
                            continue
                        else:
                            result = icbc.icbc(login_user,user_file,str(money))
                            if result == True:
                                print_color.print_color('结算成功,东西就不给你了,哈哈哈!','green')
                                balance.balance(login_user,user_file)
                                shopping_car_list = []
                                while True:
                                    print_color.print_color('b  回到主菜单  q 退出系统','yellow')
                                    choice_last = input("请选择对应的操作编号:")
                                    if choice_last == 'q':
                                        print_color.print_color('感谢访问oldboy商城!欢迎下次光临,再见!','green')
                                        exit()
                                    elif choice_last == 'b':
                                        flag2 = False
                                        flag1 = False
                                        break
                                    else:
                                        print_color.print_color('您输入的不正确,请重新输入!')
                                        continue

                            else:
                                print_color.print_color('结算失败,返回购物车列表')
                                continue

                    else:
                        print_color.print_color('您的输入不正确,请重新输入!', 'red')
            else:
                print_color.print_color('您输入的不正确,请重新输入','red')
                continue
        else:
            print_color.print_color('您输入的不正确,请重新输入','red')
Example #24
0
	def test_3(self):
		brackets = '{[1]}'
		self.assertEquals(balance(brackets), False)
Example #25
0
 def balance(self):
     self.close()
     self.ui6=balance.balance()
Example #26
0
 def goog_test(self):
     self.assertEqual(["L", "R"], balance(2))
     self.assertEqual(["L", "-", "R"], balance(8))
Example #27
0
 def balance(self):
     self.sam = balance(self.sam)
Example #28
0
 def balance(self):
     self.latexEdit.setLatex(balance.balance(self.latexEdit.text()))
Example #29
0
 def delete():
     node = balance()
     location = "http://127.0.0.1:500" + str(node) + request.script_root + request.path
     resp = requests.delete(location).content
     response = Response(resp.content, resp.status_code, headers)
     return response
from balance import balance
from gui import GUInterface

inter = GUInterface()
bb = balance(inter)
bb.run()
    def run(self, timeout, num_newAlgn):

        numLines = len(self.corpus)
        if numLines > 2:
            nextRandomSize = balance(self.principal, 2, numLines - 1).next
        else:
            nextRandomSize = balance(self.principal, 1,numLines).next

        nssecnd = 0
        nsubach = 0
        nsubachsum = 0
        prevdl = 0
        prevasd = 0
        lstwrt = startTime = time()
        speed = sys.maxint

        print >> sys.stderr, "\rWorking, please wait..."
        tmpFile = getTempFIle(".al")

        try:
            try:
                while speed > num_newAlgn:
                    t = time()
                    if timeout is not None and t - startTime >= timeout:
                        break
                    elapsedTime = t - lstwrt
                    if nsubach >= 1 and elapsedTime >= 1:
                        speed = int(math.ceil((self.numAligns -
                                               prevdl) / elapsedTime))
                        prevdl = self.numAligns
                        lstwrt = t


                    subcorpusSize = nextRandomSize()
                    while subcorpusSize > maximumSize:
                        subcorpusSize = nextRandomSize()
                    if subcorpusSize == 2:
                        nssecnd += 1

                    nsubach += 1
                    nsubachsum += subcorpusSize
                    self.alignwords(random.sample(range(numLines), subcorpusSize),
                               tmpFile)
            except KeyboardInterrupt:
                pass

            if numLines > 2:
                wnum1 = 2 * nssecnd * math.log(1 - 2. / (numLines + 1)) / (numLines * math.log(1 - 1. / (numLines + 1)))
                wnum2 = 2 * nssecnd * math.log(1 - 2. / (numLines + 1)) / (numLines * math.log(1 -  1. * numLines / (numLines + 1)))
                if wnum1:
                    frac1, wnum1 = math.modf(wnum1)
                    wnum1 = int(wnum1)
                    for i in range(numLines):
                        wei = wnum1
                        if random.random() < frac1:
                            wei += 1
                        if wei:
                            self.alignwords([i], tmpFile, wei)
                if wnum2:
                    fracN, wnum2 = math.modf(wnum2)
                    wei = int(wnum2)
                    if random.random() < fracN:
                        wei += 1
                    if wei:
                        self.alignwords(range(numLines), tmpFile, wei)

            tmpFile.seek(0)
            self._weights(tmpFile)
        finally:
            tmpFile.close()
            print >> sys.stderr, "\rDone, please check your output file."
Example #32
0
	def test_1(self):
		brackets = '[]'
		self.assertEquals(balance(brackets), True)
Example #33
0
	def test_4(self):
		brackets = '{[}]'
		self.assertEquals(balance(brackets), False)
Example #34
0
	def test_2(self):
		brackets = '{[]}'
		self.assertEquals(balance(brackets), True)
Example #35
0
def main(args):
    path_to_files = sys.argv[1]
    min = int(sys.argv[2]) # 550
    max = int(sys.argv[3]) # 650
    step = int(sys.argv[4]) # 10
    do_balance = int(sys.argv[5])
    if(len(sys.argv) > 6): debug = 1
    else: debug = 0

    # Get the original files -- we do *not* want to modify these.
    original_files = glob.glob(path_to_files + '/*.h5')
    
    # First, pT-sort the files.
    for file in original_files: sorted_file = pt_sort(file,debug)
    
    # Record the new filenames.
    sort_files = glob.glob(path_to_files + '/*.h5')
    sort_files = list(set(sort_files) - set(original_files))

    # Next, perform the pT splicing. Delete the sorted files when no longer needed.
    for file in sort_files:
        for i in range(min,max,step): pt_slice(file,str(i),str(i+step))
        sub.check_call(['rm',file])

    # Get the pT-split files. By definition it's everything in the directory except for the "original files".
    pt_files = glob.glob(path_to_files + '/*.h5')
    pt_files = list(set(pt_files) - set(original_files))
    
    if(do_balance == 0): return
    # Now our goal is to remove events from training pt slices,
    # such that each has the same number of signal and background events, with a 50/50 split.
    # (We also want to "balance" the validation and testing pt slices to have a 50/50 split,
    #  but each slice need not have the same number of events.)
    
    # First handle validation & testing.
    val_test_pt_files = [x for x in pt_files if('test' in x or 'valid' in x)]
    for file in val_test_pt_files:
        balanced_file = balance(file)
        sub.check_call(['rm',file])
        sub.check_call(['mv',balanced_file,file])
    
    # Now handle training -- slightly more complicated since in addition to balancing signal and background,
    # we are also ensuring that each training pt slice has the same number of total events.
    pt_files = [x for x in pt_files if('train' in x)]

    # Now we seek file with the smallest number of signal *or* background events.
    files_h5 = [h5.File(x,'r') for x in pt_files]
    ns = [np.sum(x['is_signal'][:]) for x in files_h5]
    nb = [files_h5[x]['is_signal'].shape[0] - ns[x] for x in range(len(files_h5))]

    for file_h5 in files_h5: file_h5.close() # can safely close the files (will be overwritten later)

    min_s = (np.min(ns),np.argmin(ns))
    min_b = (np.min(nb),np.argmin(nb))
    min_index = -1
    if(min_s[0] < min_b[0]): min_index = min_s[1]
    else: min_index = min_b[1]
    min_file = pt_files[min_index] # filename of file with the smallest set of signal or background events
    
    # Now "balance" this file -- make a copy with 50% signal, 50% background.
    balanced_min_file = balance(min_file)
    
    # Now delete min_file, and rename balanced_min_file -> min_file
    sub.check_call(['rm',min_file])
    sub.check_call(['mv',balanced_min_file,min_file])
    
    # Now min file has 50% signal and 50% background, and all the other files can be rescaled to match
    # its number of signal and background events. (Thus they will be "balanced" too by definition).
    
    for pt_file in pt_files:
        if(pt_file == min_file): continue
        rescaled_file = rescale(pt_file, min_file)
        sub.check_call(['rm',pt_file])
        sub.check_call(['mv',rescaled_file,pt_file])
    
    # Done. Now we do an (optional) sanity check.
    if(debug != 0):
        files_h5 = [h5.File(x,'r') for x in pt_files]
        ns = [np.sum(x['is_signal'][:]) for x in files_h5]
        nb = [files_h5[x]['is_signal'].shape[0] - ns[x] for x in range(len(files_h5))]
        for i in range(len(files_h5)): print(pt_files[i], ns[i], nb[i])
    return