def softmax_logits(self, manipulated_images, batch_size=512): model = self.model func = K.function( [model.layers[0].input] + [K.learning_phase()], [model.layers[model.layers.__len__() - 1].output.op.inputs[0]]) batch, remainder = divmod(len(manipulated_images), batch_size) if len(manipulated_images) >= batch_size: softmax_logits = [] for b in range(batch): logits = func([ manipulated_images[b * batch_size:(b + 1) * batch_size], 0 ])[0] softmax_logits.append(logits) softmax_logits = np.asarray(softmax_logits) softmax_logits = softmax_logits.reshape(batch * batch_size, model.output_shape[1]) # note that here if logits is empty, it is fine, as it won't be concatenated. if batch * batch_size < len(manipulated_images): logits = func([ manipulated_images[batch * batch_size:len(manipulated_images)], 0 ])[0] softmax_logits = np.concatenate((softmax_logits, logits), axis=0) else: softmax_logits = func([manipulated_images, 0])[0] return softmax_logits
def func(): try: time.sleep(1) get_all_url_line(get_html('https://1xstavka.ru/live/Handball/'),links_to_check_line,driver) get_all_url_live(get_html('https://1xstavka.ru/line/Handball/'),links_to_check_line,driver) except Exception as e: print(e,0) func()
def runAllContours(img, contours, func): for c in contours: # 設置敏感度 # contourArea計算輪廓面積 if cv2.contourArea(c) < 1000: continue else: func(c)
def bkg_2d(ra, dec): dis_ra = (ra - M87[0]) / 180. * pi * DIS dis_dec = (dec - M87[1]) / 180. * pi * DIS n = -1.54 PA = 0.736 e = 0.692 H = 78 Const = -0.0128 exp_density = func((dis_ra, dis_dec), n, PA, e, H, Const) bkg_unif = func((bkg_level_radius / sqrt(2), bkg_level_radius / sqrt(2)), n, PA, e, H, Const) return exp_density, bkg_unif
def cmd_func(self, cmd, args=None): ''' Attempts to call the function cmd from self.cmd_parser with any additional args if they exist ''' func = self.cmd_parser.get(cmd, None) if args == None: return func() elif len(signature(func).parameters) == len(args): return func(*args) else: return
def plot_energy_distribution(func, **arg): ''' Plot the energy distribution -> func: the function to calculate the Hamiltonian -> the parameters of the Hamiltonian ''' print "\n********** Plot the energy distribution **********" H = func(**arg) sym = H.sym plt.figure("energy distribution") name = "" for kw in arg.keys(): if arg[kw]!=0: name += kw + "=" + str(arg[kw]) + " " plt.title(name) evals = [] for s in range(sym): print "\t calculate eigenvalues for symmetry sector %d ..." % s D, U = eigh(H.val[s][s]) evals.append(D) for s in range(len(evals))[::-1]: plt.subplot(121) plt.plot(evals[s], 'o', label="sector %d" % s) plt.subplot(122) plt.hist(np.array(evals[:s+1]).ravel(), 75) plt.subplot(121) plt.legend(loc='best') plt.xticks([])
def plot_entanglement_entropy(func, fit=False, level=0, **arg): ''' Plot the entanglement entropy as a function of subsystem size -> func: the function to calculate the Hamiltonian -> level: the energy level to plot -> the parameters of the Hamiltonian ''' print "\n********** Plot the entanglement entropy at each cut **********" H = func(**arg) L = H.L sym = H.sym plt.figure("Entanglement entropy") name = "" for kw in arg.keys(): if arg[kw]!=0: name += kw + "=" + str(arg[kw]) + " " plt.title(name) ee = np.zeros(L-1) for s in range(sym): print "\t calculate eigenvalues for symmetry sector %d ..." % s D, U = eigh(H.val[s][s]) for l in range(1,L): ee[l-1] = entanglement_entropy(U[:,level], l, H, s=s) plt.plot(np.arange(1,L), ee, 'o', label="sector %d" % s) if fit: p = fit_central_charge(ee) x = np.linspace(1,L-1,100,endpoint=True) plt.plot(x, np.polyval(p, np.log(np.sin(np.pi*x/L))/6), '-', label="c=%.2f"%p[0]) plt.xticks(range(L+1)) plt.legend(loc='best')
def do_help(self, args): '''may or may not accept an argument(s), check if first argument is an internal command or requires output redirection''' '''sets up readme omly in the first call of help method''' self.set_stdout() global readme if not (readme): with open('readme', 'r') as f: readme = f.read() #check for the case of help on an internal method if args and args[0] != '>': '''isolate the internal method which is callable in the Help class''' attr = args.split()[0] func = getattr(Help, attr) self.stdout.write(func()) elif self.outFile: '''if help does not take an argument but requires output redirection, write the manual into the file''' self.stdout.write(readme) else: manual = readme.split('\n') line = 0 m_index = 0 '''keep going until a non enter key is inputted, couldnt get the space key listener working''' while True: '''display 25 lines at a time and keep going only if the index is less than the length of manual''' while m_index < len(manual) and line < 26: self.stdout.write(manual[m_index] + '\n') line += 1 m_index += 1 if not (input()) and m_index < len(manual): '''reset line in order to run inner loop''' line = 0 continue else: break
def phi(factor, kibun, emo_num): ret = np.zeros(SIT_NUM) for sit_num in range(SIT_NUM): ret[sit_num] = func(factor[sit_num], kibun, func_num[sit_num][emo_num]) return ret
def cmd_func(self, cmd): ''' Attempts to call the function cmd from self.cmd_parser with any additional args if they exist ''' split = cmd.strip().split(" ") func = self.cmd_parser.get(split[0], None) if func is None: print("Invalid server command, type help for list of commands") return params = signature(func).parameters num_args = len(params) num_non_default_args = count_non_default_args(params) if len(split[1:]) < num_non_default_args: print( f"Too few args. {func.__name__} takes {num_non_default_args} argument{'s'*(num_non_default_args!=1)}" ) print(f"format: {func.__name__}{str(signature(func))}") elif len(split[1:]) > num_args: print( f"Too many args. {func.__name__} takes {num_args} argument{'s'*(num_args!=1)}" ) print(f"format: {func.__name__}{str(signature(func))}") else: return func(*split[1:])
def plot_energy_distribution(func, **arg): ''' Plot the energy distribution -> func: the function to calculate the Hamiltonian -> the parameters of the Hamiltonian ''' print "\n********** Plot the energy distribution **********" H = func(**arg) sym = H.sym plt.figure("energy distribution") name = "" for kw in arg.keys(): if arg[kw] != 0: name += kw + "=" + str(arg[kw]) + " " plt.title(name) evals = [] for s in range(sym): print "\t calculate eigenvalues for symmetry sector %d ..." % s D, U = eigh(H.val[s][s]) evals.append(D) for s in range(len(evals))[::-1]: plt.subplot(121) plt.plot(evals[s], 'o', label="sector %d" % s) plt.subplot(122) plt.hist(np.array(evals[:s + 1]).ravel(), 75) plt.subplot(121) plt.legend(loc='best') plt.xticks([])
def plot_energy_split(func, k, **arg): ''' Plot the energy split -> func: the function to calculate the Hamiltonian -> k: the number of energy levels to be plotted -> the parameters of the Hamiltonian ''' print "\n********** Plot the energy splitting as a function of system size **********" H = func(2, **arg) sym = H.sym min_l = int( np.log(k*sym)/np.log(sym) ) + 1 max_l = int( np.log(1e4*sym)/np.log(sym) ) val_l = np.arange(min_l, max_l) ene = np.zeros((val_l.shape[0], k, sym)) for i,L in enumerate(val_l): H = func(L, **arg) for j in range(sym): # cc = fermion_construct(L, 2, fermion_c_d(), 0, fermion_c(), L-1) print "\t calculate eigenvalues for symmetry sector %d ..." % j D, U = eigh(H.val[j][j]) ene[i,:,j] = D[:k] # print np.diag( np.dot(U[:,:1].T, np.dot(cc.val[0][0], U[:,:1])) ) # D, U = eigh(H.val[1][1]) # ene1[i,:] = D[:k] # print np.diag( np.dot(U[:,:1].T, np.dot(cc.val[0][0], U[:,:1])) ) plt.figure("Energy split") name = "" for kw in arg.keys(): if arg[kw]!=0: name += kw + "=" + str(arg[kw]) + " " plt.suptitle(name) for j in range(sym-1): plt.subplot(2, sym-1, j+1) for i in range(k): diff = ene[:,i,j+1] - ene[:,i,0] plt.plot(val_l+0.2*i, diff, 'o') plt.xticks(val_l) plt.subplot(2, sym-1, j+1+sym-1) for i in range(k): diff = ene[:,i,j+1] - ene[:,i,0] plt.plot(val_l+0.2*i, np.abs(diff), 'o') plt.xticks(val_l) plt.yscale('log')
def plot_energy_split(func, k, **arg): ''' Plot the energy split -> func: the function to calculate the Hamiltonian -> k: the number of energy levels to be plotted -> the parameters of the Hamiltonian ''' print "\n********** Plot the energy splitting as a function of system size **********" H = func(2, **arg) sym = H.sym min_l = int(np.log(k * sym) / np.log(sym)) + 1 max_l = int(np.log(1e4 * sym) / np.log(sym)) val_l = np.arange(min_l, max_l) ene = np.zeros((val_l.shape[0], k, sym)) for i, L in enumerate(val_l): H = func(L, **arg) for j in range(sym): # cc = fermion_construct(L, 2, fermion_c_d(), 0, fermion_c(), L-1) print "\t calculate eigenvalues for symmetry sector %d ..." % j D, U = eigh(H.val[j][j]) ene[i, :, j] = D[:k] # print np.diag( np.dot(U[:,:1].T, np.dot(cc.val[0][0], U[:,:1])) ) # D, U = eigh(H.val[1][1]) # ene1[i,:] = D[:k] # print np.diag( np.dot(U[:,:1].T, np.dot(cc.val[0][0], U[:,:1])) ) plt.figure("Energy split") name = "" for kw in arg.keys(): if arg[kw] != 0: name += kw + "=" + str(arg[kw]) + " " plt.suptitle(name) for j in range(sym - 1): plt.subplot(2, sym - 1, j + 1) for i in range(k): diff = ene[:, i, j + 1] - ene[:, i, 0] plt.plot(val_l + 0.2 * i, diff, 'o') plt.xticks(val_l) plt.subplot(2, sym - 1, j + 1 + sym - 1) for i in range(k): diff = ene[:, i, j + 1] - ene[:, i, 0] plt.plot(val_l + 0.2 * i, np.abs(diff), 'o') plt.xticks(val_l) plt.yscale('log')
def Process2(): if len(sys.argv) < 2: print('No argument found.. terminating!') else: cmd = sys.argv[1] option = None interval = None if len(sys.argv) == 4: option = sys.argv[2] interval = int(sys.argv[3]) func = None if cmd == 'live': func = LiveStock elif cmd == 'bye': print('Later!') elif cmd == 'help': print("Usage:") print("%s <cmd> [option]" % sys.argv[0]) print("Available commands:") print("\thelp") print("\tlive") print("\tnews") print("\tobook") print("\ttimesale") print("\ttest") print("\tbye") print("Available options:") print("\t--loop\t:run continuously") elif cmd == 'news': func = News elif cmd == 'obook': func = OBook elif cmd == 'timesale': func = TimeSale elif cmd == 'test': func = test else: print('unknown command. try help') if func: if option and interval and option == '--loop': func2 = func func = Loop(func2, interval) func()
def _check(self, func: Function, np_func, np_der, x_var, left=0, right=1, delta=10e-6, uniform=False): if uniform: x_var.set_value(random.random()) else: x_var.set_value(random.randrange(left, right)) self.assertAlmostEqual(func(), np_func(x_var()), delta=delta) self.assertAlmostEqual(func.partial_derivative(x_var)(), np_der(x_var()), delta=delta)
def Newton_method(a, epsilon, func, deriv): """Solves func(x) = 0 using Newton's method within an error of epsilon. Input: initial guess a , error wanted epsilon, function func, derivative of function deriv Output: x solution, number of iterations """ x = a x_prime = x - func(x) / deriv(x) error = abs(x_prime - x) a_list = [a] # list of test values while error > epsilon: # update x, x_prime x = x_prime x_prime = x - func(x) / deriv(x) a_list.append(x_prime) # error = abs(x_prime - x) return a_list[-1], len(a_list)
def bkg_2d(ra,dec): dis_ra = (ra - M87[0])/180.*pi*DIS dis_dec = (dec - M87[1])/180.*pi*DIS n = -1.5716456 PA = 0.658513273 e = 0.740146285 H = 85.1889069 C = -0.0123046213 exp_density = func((dis_ra,dis_dec), n, PA, e, H, C) bkg_unif = 0 return exp_density,bkg_unif
def __loop_over_each_gdb_entry(id_row, func): #[GID, BG, KKD, XXX] #[1, 2, 4, None] #[2, 3, None, None] GID = id_row[0] mid = id_row[1] print "get manga id %d" % mid mng = mdb.Get(mid) mng['GID'] = GID ret = func(mng) if ret == 'NEXT_GID': return True return False
def get_mental(factor, signal, mental, weight): new_mental = None size_x = factor.shape[1] #size_x is factor type size_t = factor.shape[0] size_z = signal.shape[1] #size_z is signal type(facial expression type) sig_hat = np.zeros((size_t, size_z)) while (err > ERR_THRE): for sig_type in range(size_z): for t in range(size_t): for fac_type in range(size_x): sig_hat[t, sig_type] += weight[t, fac_type, sig_type] * func( inv_norm(4 * sig_type + fac_type, factor[fac_type, sig_type]), mental[t], 4 * sig_type + fac_type) print("err", np.sum(sig_hat - signal)) return new_mental
def set_phi(factor, signal, mental): if factor.shape[0] != mental.shape[0]: print("input same time size factor and mental") return -1 else: size_x = factor.shape[1] #size_x is factor type size_t = mental.shape[0] #size_t is time length size_z = signal.shape[ 1] #size_z is signal type(facial expression type) #get_phi() phi = np.zeros((size_x, size_t, size_z)) for sig_type in range(size_z): for t in range(size_t): for fac_type in range(size_x): phi[fac_type, t, sig_type] = func( inv_norm(4 * sig_type + fac_type, factor[fac_type, sig_type]), mental[t], 4 * sig_type + fac_type) return phi
def print_results(test_name, func, result, exec_time, trials, n): print() print() print('===================================') print() print('Test:', test_name) print('Execution time:', exec_time, 'sec') print() print('===================================') print('===================================') print() for t in range(trials): print('===================================') print() print('Trial', t + 1) print('x =', ''.join([str(result[i][t]) for i in range(n)])) print('f(x) =', func([result[i][t] for i in range(n)])) print() print('===================================') print() print()
def plot_entanglement_entropy(func, fit=False, level=0, **arg): ''' Plot the entanglement entropy as a function of subsystem size -> func: the function to calculate the Hamiltonian -> level: the energy level to plot -> the parameters of the Hamiltonian ''' print "\n********** Plot the entanglement entropy at each cut **********" H = func(**arg) L = H.L sym = H.sym plt.figure("Entanglement entropy") name = "" for kw in arg.keys(): if arg[kw] != 0: name += kw + "=" + str(arg[kw]) + " " plt.title(name) ee = np.zeros(L - 1) for s in range(sym): print "\t calculate eigenvalues for symmetry sector %d ..." % s D, U = eigh(H.val[s][s]) for l in range(1, L): ee[l - 1] = entanglement_entropy(U[:, level], l, H, s=s) plt.plot(np.arange(1, L), ee, 'o', label="sector %d" % s) if fit: p = fit_central_charge(ee) x = np.linspace(1, L - 1, 100, endpoint=True) plt.plot(x, np.polyval(p, np.log(np.sin(np.pi * x / L)) / 6), '-', label="c=%.2f" % p[0]) plt.xticks(range(L + 1)) plt.legend(loc='best')
""" This is used for dynamic object completion. Jedi tries to guess param types with a backtracking approach. """ def func(a, default_arg=2): #? int() default_arg #? int() str() return a #? int() func(1) func int(1) + (int(2)) + func('') # Again the same function, but with another call. def func(a): #? float() return a func(1.0) # Again the same function, but with no call.
def wrapper(self, value): # 如果值相同, 就不调用 if not hasattr(self, private_name) or getattr( self, private_name) != value: self.__write(cmd=func(self, value))
from func import * file = open('input.txt') line = file.readline() input = [] while line: input.append(line.strip('\n')) line = file.readline() print( func(input, 1, 1) * func(input, 3, 1) * func(input, 5, 1) * func(input, 7, 1) * func(input, 1, 2))
def __setupC(self, N, m, real = False): func = createBlockedToeplitz return ToeplitzFactorizor(func(N/m, m, real), m)
def wrapper(*args): return func(1, *args)
""" This is used for dynamic object completion. Jedi tries to guess the types with a backtracking approach. """ def func(a): #? int() str() return a #? int() func(1) func int(1) + (int(2))+ func('') # Again the same function, but with another call. def func(a): #? float() return a func(1.0) # Again the same function, but with no call. def func(a): #? return a def func(a): #? float() return a str(func(1.0))
""" This is used for dynamic object completion. Jedi tries to guess param types with a backtracking approach. """ def func(a, default_arg=2): #? int() default_arg #? int() str() return a #? int() func(1) func int(1) + (int(2))+ func('') # Again the same function, but with another call. def func(a): #? float() return a func(1.0) # Again the same function, but with no call. def func(a): #? return a def func(a): #? float()
import func hello world func(a+b)
def get_t_matrix(func, _n): m = [] for i in range(_n): m.append([func(i)(0), func(i)(1)]) return m
def __setupC(self, N, m, real=False): func = createBlockedToeplitz return ToeplitzFactorizor(func(N / m, m, real), m)
def test_one(self): val = 2 func = func() self.assertEqual(func, val)
from func import * import selenium import telebot import requests import json import time options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome('chromedriver.exe',options = options) links_to_check_line = {} def func(): try: time.sleep(1) get_all_url_line(get_html('https://1xstavka.ru/live/Handball/'),links_to_check_line,driver) get_all_url_live(get_html('https://1xstavka.ru/line/Handball/'),links_to_check_line,driver) except Exception as e: print(e,0) func() while True: func()
ret = sig(factor, a, b, c) return ret if __name__ == '__main__': import matplotlib.pyplot as plt print(func_num[0][0]) print(np.linspace(0.01, 1, 100)) for i in range(40): val = np.zeros((10, 100)) val2 = np.zeros((10, 100)) for m in range(1, 10): for f in range(1, 100): #val[m][f] = func(inv_norm(i,f),m,i) val[m][f] = func(inv_norm(i, f / 100.0), m, i) plt.plot(inv_norm(i, np.linspace(0.01, 1, 99)), val[m, 1:]) #plt.plot(val2) plt.title(str(i) + func_name_str[i]) plt.show() """ if i == 30 or i== 31 or i == 38: plt.show() else: plt.clf() """ """ #//1〜10種類ある予測関数番号をもらうと計算をする関数を作ります double func2(double factor,double mental, int func_num){ if func_num == 0: ret= 2.0/(1.0+np.exp((factor/80.0-0.15-mental/50.0)*30.0))-1.0#
def command_func(update, context, *args, **kwargs): context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING) return func(update, context, *args, **kwargs)